PetScan::unsupported: optionally print custom message
[pet.git] / scan.cc
blob2317a8b4697d65e8b8f9d5f05cd052665bcf33b8
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following
13 * disclaimer in the documentation and/or other materials provided
14 * with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
20 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 * The views and conclusions contained in the software and documentation
29 * are those of the authors and should not be interpreted as
30 * representing official policies, either expressed or implied, of
31 * Leiden University.
32 */
34 #include <set>
35 #include <map>
36 #include <iostream>
37 #include <clang/AST/ASTDiagnostic.h>
38 #include <clang/AST/Expr.h>
39 #include <clang/AST/RecursiveASTVisitor.h>
41 #include <isl/id.h>
42 #include <isl/space.h>
43 #include <isl/aff.h>
44 #include <isl/set.h>
46 #include "scan.h"
47 #include "scop.h"
48 #include "scop_plus.h"
50 #include "config.h"
52 using namespace std;
53 using namespace clang;
56 /* Check if the element type corresponding to the given array type
57 * has a const qualifier.
59 static bool const_base(QualType qt)
61 const Type *type = qt.getTypePtr();
63 if (type->isPointerType())
64 return const_base(type->getPointeeType());
65 if (type->isArrayType()) {
66 const ArrayType *atype;
67 type = type->getCanonicalTypeInternal().getTypePtr();
68 atype = cast<ArrayType>(type);
69 return const_base(atype->getElementType());
72 return qt.isConstQualified();
75 /* Mark "decl" as having an unknown value in "assigned_value".
77 * If no (known or unknown) value was assigned to "decl" before,
78 * then it may have been treated as a parameter before and may
79 * therefore appear in a value assigned to another variable.
80 * If so, this assignment needs to be turned into an unknown value too.
82 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
83 ValueDecl *decl)
85 map<ValueDecl *, isl_pw_aff *>::iterator it;
87 it = assigned_value.find(decl);
89 assigned_value[decl] = NULL;
91 if (it == assigned_value.end())
92 return;
94 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
95 isl_pw_aff *pa = it->second;
96 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
98 for (int i = 0; i < nparam; ++i) {
99 isl_id *id;
101 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
102 continue;
103 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
104 if (isl_id_get_user(id) == decl)
105 it->second = NULL;
106 isl_id_free(id);
111 /* Look for any assignments to scalar variables in part of the parse
112 * tree and set assigned_value to NULL for each of them.
113 * Also reset assigned_value if the address of a scalar variable
114 * is being taken. As an exception, if the address is passed to a function
115 * that is declared to receive a const pointer, then assigned_value is
116 * not reset.
118 * This ensures that we won't use any previously stored value
119 * in the current subtree and its parents.
121 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
122 map<ValueDecl *, isl_pw_aff *> &assigned_value;
123 set<UnaryOperator *> skip;
125 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
126 assigned_value(assigned_value) {}
128 /* Check for "address of" operators whose value is passed
129 * to a const pointer argument and add them to "skip", so that
130 * we can skip them in VisitUnaryOperator.
132 bool VisitCallExpr(CallExpr *expr) {
133 FunctionDecl *fd;
134 fd = expr->getDirectCallee();
135 if (!fd)
136 return true;
137 for (int i = 0; i < expr->getNumArgs(); ++i) {
138 Expr *arg = expr->getArg(i);
139 UnaryOperator *op;
140 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
141 ImplicitCastExpr *ice;
142 ice = cast<ImplicitCastExpr>(arg);
143 arg = ice->getSubExpr();
145 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
146 continue;
147 op = cast<UnaryOperator>(arg);
148 if (op->getOpcode() != UO_AddrOf)
149 continue;
150 if (const_base(fd->getParamDecl(i)->getType()))
151 skip.insert(op);
153 return true;
156 bool VisitUnaryOperator(UnaryOperator *expr) {
157 Expr *arg;
158 DeclRefExpr *ref;
159 ValueDecl *decl;
161 if (expr->getOpcode() != UO_AddrOf)
162 return true;
163 if (skip.find(expr) != skip.end())
164 return true;
166 arg = expr->getSubExpr();
167 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
168 return true;
169 ref = cast<DeclRefExpr>(arg);
170 decl = ref->getDecl();
171 clear_assignment(assigned_value, decl);
172 return true;
175 bool VisitBinaryOperator(BinaryOperator *expr) {
176 Expr *lhs;
177 DeclRefExpr *ref;
178 ValueDecl *decl;
180 if (!expr->isAssignmentOp())
181 return true;
182 lhs = expr->getLHS();
183 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
184 return true;
185 ref = cast<DeclRefExpr>(lhs);
186 decl = ref->getDecl();
187 clear_assignment(assigned_value, decl);
188 return true;
192 /* Keep a copy of the currently assigned values.
194 * Any variable that is assigned a value inside the current scope
195 * is removed again when we leave the scope (either because it wasn't
196 * stored in the cache or because it has a different value in the cache).
198 struct assigned_value_cache {
199 map<ValueDecl *, isl_pw_aff *> &assigned_value;
200 map<ValueDecl *, isl_pw_aff *> cache;
202 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
203 assigned_value(assigned_value), cache(assigned_value) {}
204 ~assigned_value_cache() {
205 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
206 for (it = assigned_value.begin(); it != assigned_value.end();
207 ++it) {
208 if (!it->second ||
209 (cache.find(it->first) != cache.end() &&
210 cache[it->first] != it->second))
211 cache[it->first] = NULL;
213 assigned_value = cache;
217 /* Insert an expression into the collection of expressions,
218 * provided it is not already in there.
219 * The isl_pw_affs are freed in the destructor.
221 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
223 std::set<isl_pw_aff *>::iterator it;
225 if (expressions.find(expr) == expressions.end())
226 expressions.insert(expr);
227 else
228 isl_pw_aff_free(expr);
231 PetScan::~PetScan()
233 std::set<isl_pw_aff *>::iterator it;
235 for (it = expressions.begin(); it != expressions.end(); ++it)
236 isl_pw_aff_free(*it);
239 /* Called if we found something we (currently) cannot handle.
240 * We'll provide more informative warnings later.
242 * We only actually complain if autodetect is false.
244 void PetScan::unsupported(Stmt *stmt, const char *msg)
246 if (autodetect)
247 return;
249 SourceLocation loc = stmt->getLocStart();
250 DiagnosticsEngine &diag = PP.getDiagnostics();
251 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
252 msg ? msg : "unsupported");
253 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
256 /* Extract an integer from "expr" and store it in "v".
258 int PetScan::extract_int(IntegerLiteral *expr, isl_int *v)
260 const Type *type = expr->getType().getTypePtr();
261 int is_signed = type->hasSignedIntegerRepresentation();
263 if (is_signed) {
264 int64_t i = expr->getValue().getSExtValue();
265 isl_int_set_si(*v, i);
266 } else {
267 uint64_t i = expr->getValue().getZExtValue();
268 isl_int_set_ui(*v, i);
271 return 0;
274 /* Extract an integer from "expr" and store it in "v".
275 * Return -1 if "expr" does not (obviously) represent an integer.
277 int PetScan::extract_int(clang::ParenExpr *expr, isl_int *v)
279 return extract_int(expr->getSubExpr(), v);
282 /* Extract an integer from "expr" and store it in "v".
283 * Return -1 if "expr" does not (obviously) represent an integer.
285 int PetScan::extract_int(clang::Expr *expr, isl_int *v)
287 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
288 return extract_int(cast<IntegerLiteral>(expr), v);
289 if (expr->getStmtClass() == Stmt::ParenExprClass)
290 return extract_int(cast<ParenExpr>(expr), v);
292 unsupported(expr);
293 return -1;
296 /* Extract an affine expression from the IntegerLiteral "expr".
298 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
300 isl_space *dim = isl_space_params_alloc(ctx, 0);
301 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
302 isl_aff *aff = isl_aff_zero_on_domain(ls);
303 isl_set *dom = isl_set_universe(dim);
304 isl_int v;
306 isl_int_init(v);
307 extract_int(expr, &v);
308 aff = isl_aff_add_constant(aff, v);
309 isl_int_clear(v);
311 return isl_pw_aff_alloc(dom, aff);
314 /* Extract an affine expression from the APInt "val".
316 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
318 isl_space *dim = isl_space_params_alloc(ctx, 0);
319 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
320 isl_aff *aff = isl_aff_zero_on_domain(ls);
321 isl_set *dom = isl_set_universe(dim);
322 isl_int v;
324 isl_int_init(v);
325 isl_int_set_ui(v, val.getZExtValue());
326 aff = isl_aff_add_constant(aff, v);
327 isl_int_clear(v);
329 return isl_pw_aff_alloc(dom, aff);
332 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
334 return extract_affine(expr->getSubExpr());
337 /* Extract an affine expression from the DeclRefExpr "expr".
339 * If the variable has been assigned a value, then we check whether
340 * we know what (affine) value was assigned.
341 * If so, we return this value. Otherwise we convert "expr"
342 * to an extra parameter (provided nesting_enabled is set).
344 * Otherwise, we simply return an expression that is equal
345 * to a parameter corresponding to the referenced variable.
347 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
349 ValueDecl *decl = expr->getDecl();
350 const Type *type = decl->getType().getTypePtr();
351 isl_id *id;
352 isl_space *dim;
353 isl_aff *aff;
354 isl_set *dom;
356 if (!type->isIntegerType()) {
357 unsupported(expr);
358 return NULL;
361 if (assigned_value.find(decl) != assigned_value.end()) {
362 if (assigned_value[decl])
363 return isl_pw_aff_copy(assigned_value[decl]);
364 else
365 return nested_access(expr);
368 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
369 dim = isl_space_params_alloc(ctx, 1);
371 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
373 dom = isl_set_universe(isl_space_copy(dim));
374 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
375 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
377 return isl_pw_aff_alloc(dom, aff);
380 /* Extract an affine expression from an integer division operation.
381 * In particular, if "expr" is lhs/rhs, then return
383 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
385 * The second argument (rhs) is required to be a (positive) integer constant.
387 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
389 Expr *rhs_expr;
390 isl_pw_aff *lhs, *lhs_f, *lhs_c;
391 isl_pw_aff *res;
392 isl_int v;
393 isl_set *cond;
395 rhs_expr = expr->getRHS();
396 isl_int_init(v);
397 if (extract_int(rhs_expr, &v) < 0) {
398 isl_int_clear(v);
399 return NULL;
402 lhs = extract_affine(expr->getLHS());
403 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
405 lhs = isl_pw_aff_scale_down(lhs, v);
406 isl_int_clear(v);
408 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(lhs));
409 lhs_c = isl_pw_aff_ceil(lhs);
410 res = isl_pw_aff_cond(cond, lhs_f, lhs_c);
412 return res;
415 /* Extract an affine expression from a modulo operation.
416 * In particular, if "expr" is lhs/rhs, then return
418 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
420 * The second argument (rhs) is required to be a (positive) integer constant.
422 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
424 Expr *rhs_expr;
425 isl_pw_aff *lhs, *lhs_f, *lhs_c;
426 isl_pw_aff *res;
427 isl_int v;
428 isl_set *cond;
430 rhs_expr = expr->getRHS();
431 if (rhs_expr->getStmtClass() != Stmt::IntegerLiteralClass) {
432 unsupported(expr);
433 return NULL;
436 lhs = extract_affine(expr->getLHS());
437 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
439 isl_int_init(v);
440 extract_int(cast<IntegerLiteral>(rhs_expr), &v);
441 res = isl_pw_aff_scale_down(isl_pw_aff_copy(lhs), v);
443 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(res));
444 lhs_c = isl_pw_aff_ceil(res);
445 res = isl_pw_aff_cond(cond, lhs_f, lhs_c);
447 res = isl_pw_aff_scale(res, v);
448 isl_int_clear(v);
450 res = isl_pw_aff_sub(lhs, res);
452 return res;
455 /* Extract an affine expression from a multiplication operation.
456 * This is only allowed if at least one of the two arguments
457 * is a (piecewise) constant.
459 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
461 isl_pw_aff *lhs;
462 isl_pw_aff *rhs;
464 lhs = extract_affine(expr->getLHS());
465 rhs = extract_affine(expr->getRHS());
467 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
468 isl_pw_aff_free(lhs);
469 isl_pw_aff_free(rhs);
470 unsupported(expr);
471 return NULL;
474 return isl_pw_aff_mul(lhs, rhs);
477 /* Extract an affine expression from an addition or subtraction operation.
479 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
481 isl_pw_aff *lhs;
482 isl_pw_aff *rhs;
484 lhs = extract_affine(expr->getLHS());
485 rhs = extract_affine(expr->getRHS());
487 switch (expr->getOpcode()) {
488 case BO_Add:
489 return isl_pw_aff_add(lhs, rhs);
490 case BO_Sub:
491 return isl_pw_aff_sub(lhs, rhs);
492 default:
493 isl_pw_aff_free(lhs);
494 isl_pw_aff_free(rhs);
495 return NULL;
500 /* Compute
502 * pwaff mod 2^width
504 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
505 unsigned width)
507 isl_int mod;
509 isl_int_init(mod);
510 isl_int_set_si(mod, 1);
511 isl_int_mul_2exp(mod, mod, width);
513 pwaff = isl_pw_aff_mod(pwaff, mod);
515 isl_int_clear(mod);
517 return pwaff;
520 /* Extract an affine expression from a boolean expression.
521 * In particular, return the expression "expr ? 1 : 0".
523 __isl_give isl_pw_aff *PetScan::extract_implicit_affine(Expr *expr)
525 isl_set *cond = extract_condition(expr);
526 isl_space *space = isl_set_get_space(cond);
527 isl_local_space *ls = isl_local_space_from_space(space);
528 isl_aff *zero = isl_aff_zero_on_domain(isl_local_space_copy(ls));
529 isl_aff *one = isl_aff_zero_on_domain(ls);
530 one = isl_aff_add_constant_si(one, 1);
531 return isl_pw_aff_cond(cond, isl_pw_aff_from_aff(one),
532 isl_pw_aff_from_aff(zero));
535 /* Extract an affine expression from some binary operations.
536 * If the result of the expression is unsigned, then we wrap it
537 * based on the size of the type.
539 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
541 isl_pw_aff *res;
543 switch (expr->getOpcode()) {
544 case BO_Add:
545 case BO_Sub:
546 res = extract_affine_add(expr);
547 break;
548 case BO_Div:
549 res = extract_affine_div(expr);
550 break;
551 case BO_Rem:
552 res = extract_affine_mod(expr);
553 break;
554 case BO_Mul:
555 res = extract_affine_mul(expr);
556 break;
557 case BO_LT:
558 case BO_LE:
559 case BO_GT:
560 case BO_GE:
561 case BO_EQ:
562 case BO_NE:
563 case BO_LAnd:
564 case BO_LOr:
565 res = extract_implicit_affine(expr);
566 break;
567 default:
568 unsupported(expr);
569 return NULL;
572 if (expr->getType()->isUnsignedIntegerType())
573 res = wrap(res, ast_context.getIntWidth(expr->getType()));
575 return res;
578 /* Extract an affine expression from a negation operation.
580 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
582 if (expr->getOpcode() == UO_Minus)
583 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
584 if (expr->getOpcode() == UO_LNot)
585 return extract_implicit_affine(expr);
587 unsupported(expr);
588 return NULL;
591 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
593 return extract_affine(expr->getSubExpr());
596 /* Extract an affine expression from some special function calls.
597 * In particular, we handle "min", "max", "ceild" and "floord".
598 * In case of the latter two, the second argument needs to be
599 * a (positive) integer constant.
601 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
603 FunctionDecl *fd;
604 string name;
605 isl_pw_aff *aff1, *aff2;
607 fd = expr->getDirectCallee();
608 if (!fd) {
609 unsupported(expr);
610 return NULL;
613 name = fd->getDeclName().getAsString();
614 if (!(expr->getNumArgs() == 2 && name == "min") &&
615 !(expr->getNumArgs() == 2 && name == "max") &&
616 !(expr->getNumArgs() == 2 && name == "floord") &&
617 !(expr->getNumArgs() == 2 && name == "ceild")) {
618 unsupported(expr);
619 return NULL;
622 if (name == "min" || name == "max") {
623 aff1 = extract_affine(expr->getArg(0));
624 aff2 = extract_affine(expr->getArg(1));
626 if (name == "min")
627 aff1 = isl_pw_aff_min(aff1, aff2);
628 else
629 aff1 = isl_pw_aff_max(aff1, aff2);
630 } else if (name == "floord" || name == "ceild") {
631 isl_int v;
632 Expr *arg2 = expr->getArg(1);
634 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
635 unsupported(expr);
636 return NULL;
638 aff1 = extract_affine(expr->getArg(0));
639 isl_int_init(v);
640 extract_int(cast<IntegerLiteral>(arg2), &v);
641 aff1 = isl_pw_aff_scale_down(aff1, v);
642 isl_int_clear(v);
643 if (name == "floord")
644 aff1 = isl_pw_aff_floor(aff1);
645 else
646 aff1 = isl_pw_aff_ceil(aff1);
647 } else {
648 unsupported(expr);
649 return NULL;
652 return aff1;
656 /* This method is called when we come across an access that is
657 * nested in what is supposed to be an affine expression.
658 * If nesting is allowed, we return a new parameter that corresponds
659 * to this nested access. Otherwise, we simply complain.
661 * The new parameter is resolved in resolve_nested.
663 isl_pw_aff *PetScan::nested_access(Expr *expr)
665 isl_id *id;
666 isl_space *dim;
667 isl_aff *aff;
668 isl_set *dom;
670 if (!nesting_enabled) {
671 unsupported(expr);
672 return NULL;
675 id = isl_id_alloc(ctx, NULL, expr);
676 dim = isl_space_params_alloc(ctx, 1);
678 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
680 dom = isl_set_universe(isl_space_copy(dim));
681 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
682 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
684 return isl_pw_aff_alloc(dom, aff);
687 /* Affine expressions are not supposed to contain array accesses,
688 * but if nesting is allowed, we return a parameter corresponding
689 * to the array access.
691 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
693 return nested_access(expr);
696 /* Extract an affine expression from a conditional operation.
698 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
700 isl_set *cond;
701 isl_pw_aff *lhs, *rhs;
703 cond = extract_condition(expr->getCond());
704 lhs = extract_affine(expr->getTrueExpr());
705 rhs = extract_affine(expr->getFalseExpr());
707 return isl_pw_aff_cond(cond, lhs, rhs);
710 /* Extract an affine expression, if possible, from "expr".
711 * Otherwise return NULL.
713 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
715 switch (expr->getStmtClass()) {
716 case Stmt::ImplicitCastExprClass:
717 return extract_affine(cast<ImplicitCastExpr>(expr));
718 case Stmt::IntegerLiteralClass:
719 return extract_affine(cast<IntegerLiteral>(expr));
720 case Stmt::DeclRefExprClass:
721 return extract_affine(cast<DeclRefExpr>(expr));
722 case Stmt::BinaryOperatorClass:
723 return extract_affine(cast<BinaryOperator>(expr));
724 case Stmt::UnaryOperatorClass:
725 return extract_affine(cast<UnaryOperator>(expr));
726 case Stmt::ParenExprClass:
727 return extract_affine(cast<ParenExpr>(expr));
728 case Stmt::CallExprClass:
729 return extract_affine(cast<CallExpr>(expr));
730 case Stmt::ArraySubscriptExprClass:
731 return extract_affine(cast<ArraySubscriptExpr>(expr));
732 case Stmt::ConditionalOperatorClass:
733 return extract_affine(cast<ConditionalOperator>(expr));
734 default:
735 unsupported(expr);
737 return NULL;
740 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
742 return extract_access(expr->getSubExpr());
745 /* Return the depth of an array of the given type.
747 static int array_depth(const Type *type)
749 if (type->isPointerType())
750 return 1 + array_depth(type->getPointeeType().getTypePtr());
751 if (type->isArrayType()) {
752 const ArrayType *atype;
753 type = type->getCanonicalTypeInternal().getTypePtr();
754 atype = cast<ArrayType>(type);
755 return 1 + array_depth(atype->getElementType().getTypePtr());
757 return 0;
760 /* Return the element type of the given array type.
762 static QualType base_type(QualType qt)
764 const Type *type = qt.getTypePtr();
766 if (type->isPointerType())
767 return base_type(type->getPointeeType());
768 if (type->isArrayType()) {
769 const ArrayType *atype;
770 type = type->getCanonicalTypeInternal().getTypePtr();
771 atype = cast<ArrayType>(type);
772 return base_type(atype->getElementType());
774 return qt;
777 /* Extract an access relation from a reference to a variable.
778 * If the variable has name "A" and its type corresponds to an
779 * array of depth d, then the returned access relation is of the
780 * form
782 * { [] -> A[i_1,...,i_d] }
784 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
786 ValueDecl *decl = expr->getDecl();
787 int depth = array_depth(decl->getType().getTypePtr());
788 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
789 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
790 isl_map *access_rel;
792 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
794 access_rel = isl_map_universe(dim);
796 return access_rel;
799 /* Extract an access relation from an integer contant.
800 * If the value of the constant is "v", then the returned access relation
801 * is
803 * { [] -> [v] }
805 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
807 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
810 /* Try and extract an access relation from the given Expr.
811 * Return NULL if it doesn't work out.
813 __isl_give isl_map *PetScan::extract_access(Expr *expr)
815 switch (expr->getStmtClass()) {
816 case Stmt::ImplicitCastExprClass:
817 return extract_access(cast<ImplicitCastExpr>(expr));
818 case Stmt::DeclRefExprClass:
819 return extract_access(cast<DeclRefExpr>(expr));
820 case Stmt::ArraySubscriptExprClass:
821 return extract_access(cast<ArraySubscriptExpr>(expr));
822 default:
823 unsupported(expr);
825 return NULL;
828 /* Assign the affine expression "index" to the output dimension "pos" of "map"
829 * and return the result.
831 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
832 __isl_take isl_pw_aff *index)
834 isl_map *index_map;
835 int len = isl_map_dim(map, isl_dim_out);
836 isl_id *id;
838 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
839 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
840 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
841 id = isl_map_get_tuple_id(map, isl_dim_out);
842 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
844 map = isl_map_intersect(map, index_map);
846 return map;
849 /* Extract an access relation from the given array subscript expression.
850 * If nesting is allowed in general, then we turn it on while
851 * examining the index expression.
853 * We first extract an access relation from the base.
854 * This will result in an access relation with a range that corresponds
855 * to the array being accessed and with earlier indices filled in already.
856 * We then extract the current index and fill that in as well.
857 * The position of the current index is based on the type of base.
858 * If base is the actual array variable, then the depth of this type
859 * will be the same as the depth of the array and we will fill in
860 * the first array index.
861 * Otherwise, the depth of the base type will be smaller and we will fill
862 * in a later index.
864 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
866 Expr *base = expr->getBase();
867 Expr *idx = expr->getIdx();
868 isl_pw_aff *index;
869 isl_map *base_access;
870 isl_map *access;
871 int depth = array_depth(base->getType().getTypePtr());
872 int pos;
873 bool save_nesting = nesting_enabled;
875 nesting_enabled = allow_nested;
877 base_access = extract_access(base);
878 index = extract_affine(idx);
880 nesting_enabled = save_nesting;
882 pos = isl_map_dim(base_access, isl_dim_out) - depth;
883 access = set_index(base_access, pos, index);
885 return access;
888 /* Check if "expr" calls function "minmax" with two arguments and if so
889 * make lhs and rhs refer to these two arguments.
891 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
893 CallExpr *call;
894 FunctionDecl *fd;
895 string name;
897 if (expr->getStmtClass() != Stmt::CallExprClass)
898 return false;
900 call = cast<CallExpr>(expr);
901 fd = call->getDirectCallee();
902 if (!fd)
903 return false;
905 if (call->getNumArgs() != 2)
906 return false;
908 name = fd->getDeclName().getAsString();
909 if (name != minmax)
910 return false;
912 lhs = call->getArg(0);
913 rhs = call->getArg(1);
915 return true;
918 /* Check if "expr" is of the form min(lhs, rhs) and if so make
919 * lhs and rhs refer to the two arguments.
921 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
923 return is_minmax(expr, "min", lhs, rhs);
926 /* Check if "expr" is of the form max(lhs, rhs) and if so make
927 * lhs and rhs refer to the two arguments.
929 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
931 return is_minmax(expr, "max", lhs, rhs);
934 /* Extract a set of values satisfying the comparison "LHS op RHS"
935 * "comp" is the original statement that "LHS op RHS" is derived from
936 * and is used for diagnostics.
938 * If the comparison is of the form
940 * a <= min(b,c)
942 * then the set is constructed as the intersection of the set corresponding
943 * to the comparisons
945 * a <= b and a <= c
947 * A similar optimization is performed for max(a,b) <= c.
948 * We do this because that will lead to simpler representations of the set.
949 * If isl is ever enhanced to explicitly deal with min and max expressions,
950 * this optimization can be removed.
952 __isl_give isl_set *PetScan::extract_comparison(BinaryOperatorKind op,
953 Expr *LHS, Expr *RHS, Stmt *comp)
955 isl_pw_aff *lhs;
956 isl_pw_aff *rhs;
957 isl_set *cond;
959 if (op == BO_GT)
960 return extract_comparison(BO_LT, RHS, LHS, comp);
961 if (op == BO_GE)
962 return extract_comparison(BO_LE, RHS, LHS, comp);
964 if (op == BO_LT || op == BO_LE) {
965 Expr *expr1, *expr2;
966 isl_set *set1, *set2;
967 if (is_min(RHS, expr1, expr2)) {
968 set1 = extract_comparison(op, LHS, expr1, comp);
969 set2 = extract_comparison(op, LHS, expr2, comp);
970 return isl_set_intersect(set1, set2);
972 if (is_max(LHS, expr1, expr2)) {
973 set1 = extract_comparison(op, expr1, RHS, comp);
974 set2 = extract_comparison(op, expr2, RHS, comp);
975 return isl_set_intersect(set1, set2);
979 lhs = extract_affine(LHS);
980 rhs = extract_affine(RHS);
982 switch (op) {
983 case BO_LT:
984 cond = isl_pw_aff_lt_set(lhs, rhs);
985 break;
986 case BO_LE:
987 cond = isl_pw_aff_le_set(lhs, rhs);
988 break;
989 case BO_EQ:
990 cond = isl_pw_aff_eq_set(lhs, rhs);
991 break;
992 case BO_NE:
993 cond = isl_pw_aff_ne_set(lhs, rhs);
994 break;
995 default:
996 isl_pw_aff_free(lhs);
997 isl_pw_aff_free(rhs);
998 unsupported(comp);
999 return NULL;
1002 cond = isl_set_coalesce(cond);
1004 return cond;
1007 __isl_give isl_set *PetScan::extract_comparison(BinaryOperator *comp)
1009 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1010 comp->getRHS(), comp);
1013 /* Extract a set of values satisfying the negation (logical not)
1014 * of a subexpression.
1016 __isl_give isl_set *PetScan::extract_boolean(UnaryOperator *op)
1018 isl_set *cond;
1020 cond = extract_condition(op->getSubExpr());
1022 return isl_set_complement(cond);
1025 /* Extract a set of values satisfying the union (logical or)
1026 * or intersection (logical and) of two subexpressions.
1028 __isl_give isl_set *PetScan::extract_boolean(BinaryOperator *comp)
1030 isl_set *lhs;
1031 isl_set *rhs;
1032 isl_set *cond;
1034 lhs = extract_condition(comp->getLHS());
1035 rhs = extract_condition(comp->getRHS());
1037 switch (comp->getOpcode()) {
1038 case BO_LAnd:
1039 cond = isl_set_intersect(lhs, rhs);
1040 break;
1041 case BO_LOr:
1042 cond = isl_set_union(lhs, rhs);
1043 break;
1044 default:
1045 isl_set_free(lhs);
1046 isl_set_free(rhs);
1047 unsupported(comp);
1048 return NULL;
1051 return cond;
1054 __isl_give isl_set *PetScan::extract_condition(UnaryOperator *expr)
1056 switch (expr->getOpcode()) {
1057 case UO_LNot:
1058 return extract_boolean(expr);
1059 default:
1060 unsupported(expr);
1061 return NULL;
1065 /* Extract a set of values satisfying the condition "expr != 0".
1067 __isl_give isl_set *PetScan::extract_implicit_condition(Expr *expr)
1069 return isl_pw_aff_non_zero_set(extract_affine(expr));
1072 /* Extract a set of values satisfying the condition expressed by "expr".
1074 * If the expression doesn't look like a condition, we assume it
1075 * is an affine expression and return the condition "expr != 0".
1077 __isl_give isl_set *PetScan::extract_condition(Expr *expr)
1079 BinaryOperator *comp;
1081 if (!expr)
1082 return isl_set_universe(isl_space_params_alloc(ctx, 0));
1084 if (expr->getStmtClass() == Stmt::ParenExprClass)
1085 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1087 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1088 return extract_condition(cast<UnaryOperator>(expr));
1090 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1091 return extract_implicit_condition(expr);
1093 comp = cast<BinaryOperator>(expr);
1094 switch (comp->getOpcode()) {
1095 case BO_LT:
1096 case BO_LE:
1097 case BO_GT:
1098 case BO_GE:
1099 case BO_EQ:
1100 case BO_NE:
1101 return extract_comparison(comp);
1102 case BO_LAnd:
1103 case BO_LOr:
1104 return extract_boolean(comp);
1105 default:
1106 return extract_implicit_condition(expr);
1110 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1112 switch (kind) {
1113 case UO_Minus:
1114 return pet_op_minus;
1115 default:
1116 return pet_op_last;
1120 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1122 switch (kind) {
1123 case BO_AddAssign:
1124 return pet_op_add_assign;
1125 case BO_SubAssign:
1126 return pet_op_sub_assign;
1127 case BO_MulAssign:
1128 return pet_op_mul_assign;
1129 case BO_DivAssign:
1130 return pet_op_div_assign;
1131 case BO_Assign:
1132 return pet_op_assign;
1133 case BO_Add:
1134 return pet_op_add;
1135 case BO_Sub:
1136 return pet_op_sub;
1137 case BO_Mul:
1138 return pet_op_mul;
1139 case BO_Div:
1140 return pet_op_div;
1141 case BO_EQ:
1142 return pet_op_eq;
1143 case BO_LE:
1144 return pet_op_le;
1145 case BO_LT:
1146 return pet_op_lt;
1147 case BO_GT:
1148 return pet_op_gt;
1149 default:
1150 return pet_op_last;
1154 /* Construct a pet_expr representing a unary operator expression.
1156 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1158 struct pet_expr *arg;
1159 enum pet_op_type op;
1161 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1162 if (op == pet_op_last) {
1163 unsupported(expr);
1164 return NULL;
1167 arg = extract_expr(expr->getSubExpr());
1169 return pet_expr_new_unary(ctx, op, arg);
1172 /* Mark the given access pet_expr as a write.
1173 * If a scalar is being accessed, then mark its value
1174 * as unknown in assigned_value.
1176 void PetScan::mark_write(struct pet_expr *access)
1178 isl_id *id;
1179 ValueDecl *decl;
1181 access->acc.write = 1;
1182 access->acc.read = 0;
1184 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1185 return;
1187 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1188 decl = (ValueDecl *) isl_id_get_user(id);
1189 clear_assignment(assigned_value, decl);
1190 isl_id_free(id);
1193 /* Construct a pet_expr representing a binary operator expression.
1195 * If the top level operator is an assignment and the LHS is an access,
1196 * then we mark that access as a write. If the operator is a compound
1197 * assignment, the access is marked as both a read and a write.
1199 * If "expr" assigns something to a scalar variable, then we mark
1200 * the variable as having been assigned. If, furthermore, the expression
1201 * is affine, then keep track of this value in assigned_value
1202 * so that we can plug it in when we later come across the same variable.
1204 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1206 struct pet_expr *lhs, *rhs;
1207 enum pet_op_type op;
1209 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1210 if (op == pet_op_last) {
1211 unsupported(expr);
1212 return NULL;
1215 lhs = extract_expr(expr->getLHS());
1216 rhs = extract_expr(expr->getRHS());
1218 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1219 mark_write(lhs);
1220 if (expr->isCompoundAssignmentOp())
1221 lhs->acc.read = 1;
1224 if (expr->getOpcode() == BO_Assign &&
1225 lhs && lhs->type == pet_expr_access &&
1226 isl_map_dim(lhs->acc.access, isl_dim_out) == 0) {
1227 isl_id *id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1228 ValueDecl *decl = (ValueDecl *) isl_id_get_user(id);
1229 Expr *rhs = expr->getRHS();
1230 isl_pw_aff *pa = try_extract_affine(rhs);
1231 clear_assignment(assigned_value, decl);
1232 if (pa) {
1233 assigned_value[decl] = pa;
1234 insert_expression(pa);
1236 isl_id_free(id);
1239 return pet_expr_new_binary(ctx, op, lhs, rhs);
1242 /* Construct a pet_expr representing a conditional operation.
1244 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1246 struct pet_expr *cond, *lhs, *rhs;
1248 cond = extract_expr(expr->getCond());
1249 lhs = extract_expr(expr->getTrueExpr());
1250 rhs = extract_expr(expr->getFalseExpr());
1252 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1255 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1257 return extract_expr(expr->getSubExpr());
1260 /* Construct a pet_expr representing a floating point value.
1262 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1264 return pet_expr_new_double(ctx, expr->getValueAsApproximateDouble());
1267 /* Extract an access relation from "expr" and then convert it into
1268 * a pet_expr.
1270 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1272 isl_map *access;
1273 struct pet_expr *pe;
1275 switch (expr->getStmtClass()) {
1276 case Stmt::ArraySubscriptExprClass:
1277 access = extract_access(cast<ArraySubscriptExpr>(expr));
1278 break;
1279 case Stmt::DeclRefExprClass:
1280 access = extract_access(cast<DeclRefExpr>(expr));
1281 break;
1282 case Stmt::IntegerLiteralClass:
1283 access = extract_access(cast<IntegerLiteral>(expr));
1284 break;
1285 default:
1286 unsupported(expr);
1287 return NULL;
1290 pe = pet_expr_from_access(access);
1292 return pe;
1295 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1297 return extract_expr(expr->getSubExpr());
1300 /* Construct a pet_expr representing a function call.
1302 * If we are passing along a pointer to an array element
1303 * or an entire row or even higher dimensional slice of an array,
1304 * then the function being called may write into the array.
1306 * We assume here that if the function is declared to take a pointer
1307 * to a const type, then the function will perform a read
1308 * and that otherwise, it will perform a write.
1310 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1312 struct pet_expr *res = NULL;
1313 FunctionDecl *fd;
1314 string name;
1316 fd = expr->getDirectCallee();
1317 if (!fd) {
1318 unsupported(expr);
1319 return NULL;
1322 name = fd->getDeclName().getAsString();
1323 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1324 if (!res)
1325 return NULL;
1327 for (int i = 0; i < expr->getNumArgs(); ++i) {
1328 Expr *arg = expr->getArg(i);
1329 int is_addr = 0;
1330 pet_expr *main_arg;
1332 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1333 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1334 arg = ice->getSubExpr();
1336 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1337 UnaryOperator *op = cast<UnaryOperator>(arg);
1338 if (op->getOpcode() == UO_AddrOf) {
1339 is_addr = 1;
1340 arg = op->getSubExpr();
1343 res->args[i] = PetScan::extract_expr(arg);
1344 main_arg = res->args[i];
1345 if (is_addr)
1346 res->args[i] = pet_expr_new_unary(ctx,
1347 pet_op_address_of, res->args[i]);
1348 if (!res->args[i])
1349 goto error;
1350 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1351 array_depth(arg->getType().getTypePtr()) > 0)
1352 is_addr = 1;
1353 if (is_addr && main_arg->type == pet_expr_access) {
1354 ParmVarDecl *parm = fd->getParamDecl(i);
1355 if (!const_base(parm->getType()))
1356 mark_write(main_arg);
1360 return res;
1361 error:
1362 pet_expr_free(res);
1363 return NULL;
1366 /* Try and onstruct a pet_expr representing "expr".
1368 struct pet_expr *PetScan::extract_expr(Expr *expr)
1370 switch (expr->getStmtClass()) {
1371 case Stmt::UnaryOperatorClass:
1372 return extract_expr(cast<UnaryOperator>(expr));
1373 case Stmt::CompoundAssignOperatorClass:
1374 case Stmt::BinaryOperatorClass:
1375 return extract_expr(cast<BinaryOperator>(expr));
1376 case Stmt::ImplicitCastExprClass:
1377 return extract_expr(cast<ImplicitCastExpr>(expr));
1378 case Stmt::ArraySubscriptExprClass:
1379 case Stmt::DeclRefExprClass:
1380 case Stmt::IntegerLiteralClass:
1381 return extract_access_expr(expr);
1382 case Stmt::FloatingLiteralClass:
1383 return extract_expr(cast<FloatingLiteral>(expr));
1384 case Stmt::ParenExprClass:
1385 return extract_expr(cast<ParenExpr>(expr));
1386 case Stmt::ConditionalOperatorClass:
1387 return extract_expr(cast<ConditionalOperator>(expr));
1388 case Stmt::CallExprClass:
1389 return extract_expr(cast<CallExpr>(expr));
1390 default:
1391 unsupported(expr);
1393 return NULL;
1396 /* Check if the given initialization statement is an assignment.
1397 * If so, return that assignment. Otherwise return NULL.
1399 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1401 BinaryOperator *ass;
1403 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1404 return NULL;
1406 ass = cast<BinaryOperator>(init);
1407 if (ass->getOpcode() != BO_Assign)
1408 return NULL;
1410 return ass;
1413 /* Check if the given initialization statement is a declaration
1414 * of a single variable.
1415 * If so, return that declaration. Otherwise return NULL.
1417 Decl *PetScan::initialization_declaration(Stmt *init)
1419 DeclStmt *decl;
1421 if (init->getStmtClass() != Stmt::DeclStmtClass)
1422 return NULL;
1424 decl = cast<DeclStmt>(init);
1426 if (!decl->isSingleDecl())
1427 return NULL;
1429 return decl->getSingleDecl();
1432 /* Given the assignment operator in the initialization of a for loop,
1433 * extract the induction variable, i.e., the (integer)variable being
1434 * assigned.
1436 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1438 Expr *lhs;
1439 DeclRefExpr *ref;
1440 ValueDecl *decl;
1441 const Type *type;
1443 lhs = init->getLHS();
1444 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1445 unsupported(init);
1446 return NULL;
1449 ref = cast<DeclRefExpr>(lhs);
1450 decl = ref->getDecl();
1451 type = decl->getType().getTypePtr();
1453 if (!type->isIntegerType()) {
1454 unsupported(lhs);
1455 return NULL;
1458 return decl;
1461 /* Given the initialization statement of a for loop and the single
1462 * declaration in this initialization statement,
1463 * extract the induction variable, i.e., the (integer) variable being
1464 * declared.
1466 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1468 VarDecl *vd;
1470 vd = cast<VarDecl>(decl);
1472 const QualType type = vd->getType();
1473 if (!type->isIntegerType()) {
1474 unsupported(init);
1475 return NULL;
1478 if (!vd->getInit()) {
1479 unsupported(init);
1480 return NULL;
1483 return vd;
1486 /* Check that op is of the form iv++ or iv--.
1487 * "inc" is accordingly set to 1 or -1.
1489 bool PetScan::check_unary_increment(UnaryOperator *op, clang::ValueDecl *iv,
1490 isl_int &inc)
1492 Expr *sub;
1493 DeclRefExpr *ref;
1495 if (!op->isIncrementDecrementOp()) {
1496 unsupported(op);
1497 return false;
1500 if (op->isIncrementOp())
1501 isl_int_set_si(inc, 1);
1502 else
1503 isl_int_set_si(inc, -1);
1505 sub = op->getSubExpr();
1506 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1507 unsupported(op);
1508 return false;
1511 ref = cast<DeclRefExpr>(sub);
1512 if (ref->getDecl() != iv) {
1513 unsupported(op);
1514 return false;
1517 return true;
1520 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1521 * has a single constant expression on a universe domain, then
1522 * put this constant in *user.
1524 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1525 void *user)
1527 isl_int *inc = (isl_int *)user;
1528 int res = 0;
1530 if (!isl_set_plain_is_universe(set) || !isl_aff_is_cst(aff))
1531 res = -1;
1532 else
1533 isl_aff_get_constant(aff, inc);
1535 isl_set_free(set);
1536 isl_aff_free(aff);
1538 return res;
1541 /* Check if op is of the form
1543 * iv = iv + inc
1545 * with inc a constant and set "inc" accordingly.
1547 * We extract an affine expression from the RHS and the subtract iv.
1548 * The result should be a constant.
1550 bool PetScan::check_binary_increment(BinaryOperator *op, clang::ValueDecl *iv,
1551 isl_int &inc)
1553 Expr *lhs;
1554 DeclRefExpr *ref;
1555 isl_id *id;
1556 isl_space *dim;
1557 isl_aff *aff;
1558 isl_pw_aff *val;
1560 if (op->getOpcode() != BO_Assign) {
1561 unsupported(op);
1562 return false;
1565 lhs = op->getLHS();
1566 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1567 unsupported(op);
1568 return false;
1571 ref = cast<DeclRefExpr>(lhs);
1572 if (ref->getDecl() != iv) {
1573 unsupported(op);
1574 return false;
1577 val = extract_affine(op->getRHS());
1579 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1581 dim = isl_space_params_alloc(ctx, 1);
1582 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1583 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1584 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1586 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1588 if (isl_pw_aff_foreach_piece(val, &extract_cst, &inc) < 0) {
1589 isl_pw_aff_free(val);
1590 unsupported(op);
1591 return false;
1594 isl_pw_aff_free(val);
1596 return true;
1599 /* Check that op is of the form iv += cst or iv -= cst.
1600 * "inc" is set to cst or -cst accordingly.
1602 bool PetScan::check_compound_increment(CompoundAssignOperator *op,
1603 clang::ValueDecl *iv, isl_int &inc)
1605 Expr *lhs, *rhs;
1606 DeclRefExpr *ref;
1607 bool neg = false;
1609 BinaryOperatorKind opcode;
1611 opcode = op->getOpcode();
1612 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1613 unsupported(op);
1614 return false;
1616 if (opcode == BO_SubAssign)
1617 neg = true;
1619 lhs = op->getLHS();
1620 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1621 unsupported(op);
1622 return false;
1625 ref = cast<DeclRefExpr>(lhs);
1626 if (ref->getDecl() != iv) {
1627 unsupported(op);
1628 return false;
1631 rhs = op->getRHS();
1633 if (rhs->getStmtClass() == Stmt::UnaryOperatorClass) {
1634 UnaryOperator *op = cast<UnaryOperator>(rhs);
1635 if (op->getOpcode() != UO_Minus) {
1636 unsupported(op);
1637 return false;
1640 neg = !neg;
1642 rhs = op->getSubExpr();
1645 if (rhs->getStmtClass() != Stmt::IntegerLiteralClass) {
1646 unsupported(op);
1647 return false;
1650 extract_int(cast<IntegerLiteral>(rhs), &inc);
1651 if (neg)
1652 isl_int_neg(inc, inc);
1654 return true;
1657 /* Check that the increment of the given for loop increments
1658 * (or decrements) the induction variable "iv".
1659 * "up" is set to true if the induction variable is incremented.
1661 bool PetScan::check_increment(ForStmt *stmt, ValueDecl *iv, isl_int &v)
1663 Stmt *inc = stmt->getInc();
1665 if (!inc) {
1666 unsupported(stmt);
1667 return false;
1670 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1671 return check_unary_increment(cast<UnaryOperator>(inc), iv, v);
1672 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1673 return check_compound_increment(
1674 cast<CompoundAssignOperator>(inc), iv, v);
1675 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1676 return check_binary_increment(cast<BinaryOperator>(inc), iv, v);
1678 unsupported(inc);
1679 return false;
1682 /* Embed the given iteration domain in an extra outer loop
1683 * with induction variable "var".
1684 * If this variable appeared as a parameter in the constraints,
1685 * it is replaced by the new outermost dimension.
1687 static __isl_give isl_set *embed(__isl_take isl_set *set,
1688 __isl_take isl_id *var)
1690 int pos;
1692 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1693 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1694 if (pos >= 0) {
1695 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1696 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1699 isl_id_free(var);
1700 return set;
1703 /* Construct a pet_scop for an infinite loop around the given body.
1705 * We extract a pet_scop for the body and then embed it in a loop with
1706 * iteration domain
1708 * { [t] : t >= 0 }
1710 * and schedule
1712 * { [t] -> [t] }
1714 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1716 isl_id *id;
1717 isl_space *dim;
1718 isl_set *domain;
1719 isl_map *sched;
1720 struct pet_scop *scop;
1722 scop = extract(body);
1723 if (!scop)
1724 return NULL;
1726 id = isl_id_alloc(ctx, "t", NULL);
1727 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1728 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
1729 dim = isl_space_from_domain(isl_set_get_space(domain));
1730 dim = isl_space_add_dims(dim, isl_dim_out, 1);
1731 sched = isl_map_universe(dim);
1732 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
1733 scop = pet_scop_embed(scop, domain, sched, id);
1735 return scop;
1738 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1740 * for (;;)
1741 * body
1744 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1746 return extract_infinite_loop(stmt->getBody());
1749 /* Check if the while loop is of the form
1751 * while (1)
1752 * body
1754 * If so, construct a scop for an infinite loop around body.
1755 * Otherwise, fail.
1757 struct pet_scop *PetScan::extract(WhileStmt *stmt)
1759 Expr *cond;
1760 isl_set *set;
1761 int is_universe;
1763 cond = stmt->getCond();
1764 if (!cond) {
1765 unsupported(stmt);
1766 return NULL;
1769 set = extract_condition(cond);
1770 is_universe = isl_set_plain_is_universe(set);
1771 isl_set_free(set);
1773 if (!is_universe) {
1774 unsupported(stmt);
1775 return NULL;
1778 return extract_infinite_loop(stmt->getBody());
1781 /* Check whether "cond" expresses a simple loop bound
1782 * on the only set dimension.
1783 * In particular, if "up" is set then "cond" should contain only
1784 * upper bounds on the set dimension.
1785 * Otherwise, it should contain only lower bounds.
1787 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
1789 if (isl_int_is_pos(inc))
1790 return !isl_set_dim_has_lower_bound(cond, isl_dim_set, 0);
1791 else
1792 return !isl_set_dim_has_upper_bound(cond, isl_dim_set, 0);
1795 /* Extend a condition on a given iteration of a loop to one that
1796 * imposes the same condition on all previous iterations.
1797 * "domain" expresses the lower [upper] bound on the iterations
1798 * when inc is positive [negative].
1800 * In particular, we construct the condition (when inc is positive)
1802 * forall i' : (domain(i') and i' <= i) => cond(i')
1804 * which is equivalent to
1806 * not exists i' : domain(i') and i' <= i and not cond(i')
1808 * We construct this set by negating cond, applying a map
1810 * { [i'] -> [i] : domain(i') and i' <= i }
1812 * and then negating the result again.
1814 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
1815 __isl_take isl_set *domain, isl_int inc)
1817 isl_map *previous_to_this;
1819 if (isl_int_is_pos(inc))
1820 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
1821 else
1822 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
1824 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
1826 cond = isl_set_complement(cond);
1827 cond = isl_set_apply(cond, previous_to_this);
1828 cond = isl_set_complement(cond);
1830 return cond;
1833 /* Construct a domain of the form
1835 * [id] -> { [] : exists a: id = init + a * inc and a >= 0 }
1837 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
1838 __isl_take isl_pw_aff *init, isl_int inc)
1840 isl_aff *aff;
1841 isl_space *dim;
1842 isl_set *set;
1844 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
1845 dim = isl_pw_aff_get_domain_space(init);
1846 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1847 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
1848 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
1850 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
1851 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1852 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1853 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1855 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
1857 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
1859 return isl_set_project_out(set, isl_dim_set, 0, 1);
1862 static unsigned get_type_size(ValueDecl *decl)
1864 return decl->getASTContext().getIntWidth(decl->getType());
1867 /* Assuming "cond" represents a simple bound on a loop where the loop
1868 * iterator "iv" is incremented (or decremented) by one, check if wrapping
1869 * is possible.
1871 * Under the given assumptions, wrapping is only possible if "cond" allows
1872 * for the last value before wrapping, i.e., 2^width - 1 in case of an
1873 * increasing iterator and 0 in case of a decreasing iterator.
1875 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
1877 bool cw;
1878 isl_int limit;
1879 isl_set *test;
1881 test = isl_set_copy(cond);
1883 isl_int_init(limit);
1884 if (isl_int_is_neg(inc))
1885 isl_int_set_si(limit, 0);
1886 else {
1887 isl_int_set_si(limit, 1);
1888 isl_int_mul_2exp(limit, limit, get_type_size(iv));
1889 isl_int_sub_ui(limit, limit, 1);
1892 test = isl_set_fix(cond, isl_dim_set, 0, limit);
1893 cw = !isl_set_is_empty(test);
1894 isl_set_free(test);
1896 isl_int_clear(limit);
1898 return cw;
1901 /* Given a one-dimensional space, construct the following mapping on this
1902 * space
1904 * { [v] -> [v mod 2^width] }
1906 * where width is the number of bits used to represent the values
1907 * of the unsigned variable "iv".
1909 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
1910 ValueDecl *iv)
1912 isl_int mod;
1913 isl_aff *aff;
1914 isl_map *map;
1916 isl_int_init(mod);
1917 isl_int_set_si(mod, 1);
1918 isl_int_mul_2exp(mod, mod, get_type_size(iv));
1920 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1921 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1922 aff = isl_aff_mod(aff, mod);
1924 isl_int_clear(mod);
1926 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
1927 map = isl_map_reverse(map);
1930 /* Construct a pet_scop for a for statement.
1931 * The for loop is required to be of the form
1933 * for (i = init; condition; ++i)
1935 * or
1937 * for (i = init; condition; --i)
1939 * The initialization of the for loop should either be an assignment
1940 * to an integer variable, or a declaration of such a variable with
1941 * initialization.
1943 * The condition is allowed to contain nested accesses, provided
1944 * they are not being written to inside the body of the loop.
1946 * We extract a pet_scop for the body and then embed it in a loop with
1947 * iteration domain and schedule
1949 * { [i] : i >= init and condition' }
1950 * { [i] -> [i] }
1952 * or
1954 * { [i] : i <= init and condition' }
1955 * { [i] -> [-i] }
1957 * Where condition' is equal to condition if the latter is
1958 * a simple upper [lower] bound and a condition that is extended
1959 * to apply to all previous iterations otherwise.
1961 * If the stride of the loop is not 1, then "i >= init" is replaced by
1963 * (exists a: i = init + stride * a and a >= 0)
1965 * If the loop iterator i is unsigned, then wrapping may occur.
1966 * During the computation, we work with a virtual iterator that
1967 * does not wrap. However, the condition in the code applies
1968 * to the wrapped value, so we need to change condition(i)
1969 * into condition([i % 2^width]).
1970 * After computing the virtual domain and schedule, we apply
1971 * the function { [v] -> [v % 2^width] } to the domain and the domain
1972 * of the schedule. In order not to lose any information, we also
1973 * need to intersect the domain of the schedule with the virtual domain
1974 * first, since some iterations in the wrapped domain may be scheduled
1975 * several times, typically an infinite number of times.
1976 * Note that there is no need to perform this final wrapping
1977 * if the loop condition (after wrapping) is simple.
1979 * Wrapping on unsigned iterators can be avoided entirely if
1980 * loop condition is simple, the loop iterator is incremented
1981 * [decremented] by one and the last value before wrapping cannot
1982 * possibly satisfy the loop condition.
1984 * Before extracting a pet_scop from the body we remove all
1985 * assignments in assigned_value to variables that are assigned
1986 * somewhere in the body of the loop.
1988 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
1990 BinaryOperator *ass;
1991 Decl *decl;
1992 Stmt *init;
1993 Expr *lhs, *rhs;
1994 ValueDecl *iv;
1995 isl_space *dim;
1996 isl_set *domain;
1997 isl_map *sched;
1998 isl_set *cond = NULL;
1999 isl_id *id;
2000 struct pet_scop *scop;
2001 assigned_value_cache cache(assigned_value);
2002 isl_int inc;
2003 bool is_one;
2004 bool is_unsigned;
2005 bool is_simple;
2006 isl_map *wrap = NULL;
2008 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2009 return extract_infinite_for(stmt);
2011 init = stmt->getInit();
2012 if (!init) {
2013 unsupported(stmt);
2014 return NULL;
2016 if ((ass = initialization_assignment(init)) != NULL) {
2017 iv = extract_induction_variable(ass);
2018 if (!iv)
2019 return NULL;
2020 lhs = ass->getLHS();
2021 rhs = ass->getRHS();
2022 } else if ((decl = initialization_declaration(init)) != NULL) {
2023 VarDecl *var = extract_induction_variable(init, decl);
2024 if (!var)
2025 return NULL;
2026 iv = var;
2027 rhs = var->getInit();
2028 lhs = DeclRefExpr::Create(iv->getASTContext(),
2029 var->getQualifierLoc(), iv, var->getInnerLocStart(),
2030 var->getType(), VK_LValue);
2031 } else {
2032 unsupported(stmt->getInit());
2033 return NULL;
2036 isl_int_init(inc);
2037 if (!check_increment(stmt, iv, inc)) {
2038 isl_int_clear(inc);
2039 return NULL;
2042 is_unsigned = iv->getType()->isUnsignedIntegerType();
2044 assigned_value.erase(iv);
2045 clear_assignments clear(assigned_value);
2046 clear.TraverseStmt(stmt->getBody());
2048 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2050 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
2051 if (is_one)
2052 domain = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
2053 lhs, rhs, init);
2054 else {
2055 isl_pw_aff *lb = extract_affine(rhs);
2056 domain = strided_domain(isl_id_copy(id), lb, inc);
2059 scop = extract(stmt->getBody());
2061 cond = try_extract_nested_condition(stmt->getCond());
2062 if (cond && !is_nested_allowed(cond, scop)) {
2063 isl_set_free(cond);
2064 cond = NULL;
2067 if (!cond)
2068 cond = extract_condition(stmt->getCond());
2069 cond = embed(cond, isl_id_copy(id));
2070 domain = embed(domain, isl_id_copy(id));
2071 is_simple = is_simple_bound(cond, inc);
2072 if (is_unsigned &&
2073 (!is_simple || !is_one || can_wrap(cond, iv, inc))) {
2074 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2075 cond = isl_set_apply(cond, isl_map_reverse(isl_map_copy(wrap)));
2076 is_simple = is_simple && is_simple_bound(cond, inc);
2078 if (!is_simple)
2079 cond = valid_for_each_iteration(cond,
2080 isl_set_copy(domain), inc);
2081 domain = isl_set_intersect(domain, cond);
2082 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2083 dim = isl_space_from_domain(isl_set_get_space(domain));
2084 dim = isl_space_add_dims(dim, isl_dim_out, 1);
2085 sched = isl_map_universe(dim);
2086 if (isl_int_is_pos(inc))
2087 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2088 else
2089 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2091 if (is_unsigned && !is_simple) {
2092 wrap = isl_map_set_dim_id(wrap,
2093 isl_dim_out, 0, isl_id_copy(id));
2094 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2095 domain = isl_set_apply(domain, isl_map_copy(wrap));
2096 sched = isl_map_apply_domain(sched, wrap);
2097 } else
2098 isl_map_free(wrap);
2100 scop = pet_scop_embed(scop, domain, sched, id);
2101 scop = resolve_nested(scop);
2102 clear_assignment(assigned_value, iv);
2104 isl_int_clear(inc);
2105 return scop;
2108 struct pet_scop *PetScan::extract(CompoundStmt *stmt)
2110 return extract(stmt->children());
2113 /* Does "id" refer to a nested access?
2115 static bool is_nested_parameter(__isl_keep isl_id *id)
2117 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2120 /* Does parameter "pos" of "space" refer to a nested access?
2122 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2124 bool nested;
2125 isl_id *id;
2127 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2128 nested = is_nested_parameter(id);
2129 isl_id_free(id);
2131 return nested;
2134 /* Does parameter "pos" of "map" refer to a nested access?
2136 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2138 bool nested;
2139 isl_id *id;
2141 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2142 nested = is_nested_parameter(id);
2143 isl_id_free(id);
2145 return nested;
2148 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2150 static int n_nested_parameter(__isl_keep isl_space *space)
2152 int n = 0;
2153 int nparam;
2155 nparam = isl_space_dim(space, isl_dim_param);
2156 for (int i = 0; i < nparam; ++i)
2157 if (is_nested_parameter(space, i))
2158 ++n;
2160 return n;
2163 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2165 static int n_nested_parameter(__isl_keep isl_map *map)
2167 isl_space *space;
2168 int n;
2170 space = isl_map_get_space(map);
2171 n = n_nested_parameter(space);
2172 isl_space_free(space);
2174 return n;
2177 /* For each nested access parameter in "space",
2178 * construct a corresponding pet_expr, place it in args and
2179 * record its position in "param2pos".
2180 * "n_arg" is the number of elements that are already in args.
2181 * The position recorded in "param2pos" takes this number into account.
2182 * If the pet_expr corresponding to a parameter is identical to
2183 * the pet_expr corresponding to an earlier parameter, then these two
2184 * parameters are made to refer to the same element in args.
2186 * Return the final number of elements in args or -1 if an error has occurred.
2188 int PetScan::extract_nested(__isl_keep isl_space *space,
2189 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
2191 int nparam;
2193 nparam = isl_space_dim(space, isl_dim_param);
2194 for (int i = 0; i < nparam; ++i) {
2195 int j;
2196 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2197 Expr *nested;
2199 if (!is_nested_parameter(id)) {
2200 isl_id_free(id);
2201 continue;
2204 nested = (Expr *) isl_id_get_user(id);
2205 args[n_arg] = extract_expr(nested);
2206 if (!args[n_arg])
2207 return -1;
2209 for (j = 0; j < n_arg; ++j)
2210 if (pet_expr_is_equal(args[j], args[n_arg]))
2211 break;
2213 if (j < n_arg) {
2214 pet_expr_free(args[n_arg]);
2215 args[n_arg] = NULL;
2216 param2pos[i] = j;
2217 } else
2218 param2pos[i] = n_arg++;
2220 isl_id_free(id);
2223 return n_arg;
2226 /* For each nested access parameter in the access relations in "expr",
2227 * construct a corresponding pet_expr, place it in expr->args and
2228 * record its position in "param2pos".
2229 * n is the number of nested access parameters.
2231 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
2232 std::map<int,int> &param2pos)
2234 isl_space *space;
2236 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
2237 expr->n_arg = n;
2238 if (!expr->args)
2239 goto error;
2241 space = isl_map_get_space(expr->acc.access);
2242 n = extract_nested(space, 0, expr->args, param2pos);
2243 isl_space_free(space);
2245 if (n < 0)
2246 goto error;
2248 expr->n_arg = n;
2249 return expr;
2250 error:
2251 pet_expr_free(expr);
2252 return NULL;
2255 /* Look for parameters in any access relation in "expr" that
2256 * refer to nested accesses. In particular, these are
2257 * parameters with no name.
2259 * If there are any such parameters, then the domain of the access
2260 * relation, which is still [] at this point, is replaced by
2261 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2262 * (after identifying identical nested accesses).
2263 * The parameters are then equated to the corresponding t dimensions
2264 * and subsequently projected out.
2265 * param2pos maps the position of the parameter to the position
2266 * of the corresponding t dimension.
2268 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
2270 int n;
2271 int nparam;
2272 int n_in;
2273 isl_space *dim;
2274 isl_map *map;
2275 std::map<int,int> param2pos;
2277 if (!expr)
2278 return expr;
2280 for (int i = 0; i < expr->n_arg; ++i) {
2281 expr->args[i] = resolve_nested(expr->args[i]);
2282 if (!expr->args[i]) {
2283 pet_expr_free(expr);
2284 return NULL;
2288 if (expr->type != pet_expr_access)
2289 return expr;
2291 n = n_nested_parameter(expr->acc.access);
2292 if (n == 0)
2293 return expr;
2295 expr = extract_nested(expr, n, param2pos);
2296 if (!expr)
2297 return NULL;
2299 n = expr->n_arg;
2300 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
2301 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
2302 dim = isl_map_get_space(expr->acc.access);
2303 dim = isl_space_domain(dim);
2304 dim = isl_space_from_domain(dim);
2305 dim = isl_space_add_dims(dim, isl_dim_out, n);
2306 map = isl_map_universe(dim);
2307 map = isl_map_domain_map(map);
2308 map = isl_map_reverse(map);
2309 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
2311 for (int i = nparam - 1; i >= 0; --i) {
2312 isl_id *id = isl_map_get_dim_id(expr->acc.access,
2313 isl_dim_param, i);
2314 if (!is_nested_parameter(id)) {
2315 isl_id_free(id);
2316 continue;
2319 expr->acc.access = isl_map_equate(expr->acc.access,
2320 isl_dim_param, i, isl_dim_in,
2321 n_in + param2pos[i]);
2322 expr->acc.access = isl_map_project_out(expr->acc.access,
2323 isl_dim_param, i, 1);
2325 isl_id_free(id);
2328 return expr;
2329 error:
2330 pet_expr_free(expr);
2331 return NULL;
2334 /* Convert a top-level pet_expr to a pet_scop with one statement.
2335 * This mainly involves resolving nested expression parameters
2336 * and setting the name of the iteration space.
2337 * The name is given by "label" if it is non-NULL. Otherwise,
2338 * it is of the form S_<n_stmt>.
2340 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
2341 __isl_take isl_id *label)
2343 struct pet_stmt *ps;
2344 SourceLocation loc = stmt->getLocStart();
2345 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2347 expr = resolve_nested(expr);
2348 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
2349 return pet_scop_from_pet_stmt(ctx, ps);
2352 /* Check if we can extract an affine expression from "expr".
2353 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2354 * We turn on autodetection so that we won't generate any warnings
2355 * and turn off nesting, so that we won't accept any non-affine constructs.
2357 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
2359 isl_pw_aff *pwaff;
2360 int save_autodetect = autodetect;
2361 bool save_nesting = nesting_enabled;
2363 autodetect = 1;
2364 nesting_enabled = false;
2366 pwaff = extract_affine(expr);
2368 autodetect = save_autodetect;
2369 nesting_enabled = save_nesting;
2371 return pwaff;
2374 /* Check whether "expr" is an affine expression.
2376 bool PetScan::is_affine(Expr *expr)
2378 isl_pw_aff *pwaff;
2380 pwaff = try_extract_affine(expr);
2381 isl_pw_aff_free(pwaff);
2383 return pwaff != NULL;
2386 /* Check whether "expr" is an affine constraint.
2387 * We turn on autodetection so that we won't generate any warnings
2388 * and turn off nesting, so that we won't accept any non-affine constructs.
2390 bool PetScan::is_affine_condition(Expr *expr)
2392 isl_set *set;
2393 int save_autodetect = autodetect;
2394 bool save_nesting = nesting_enabled;
2396 autodetect = 1;
2397 nesting_enabled = false;
2399 set = extract_condition(expr);
2400 isl_set_free(set);
2402 autodetect = save_autodetect;
2403 nesting_enabled = save_nesting;
2405 return set != NULL;
2408 /* Check if we can extract a condition from "expr".
2409 * Return the condition as an isl_set if we can and NULL otherwise.
2410 * If allow_nested is set, then the condition may involve parameters
2411 * corresponding to nested accesses.
2412 * We turn on autodetection so that we won't generate any warnings.
2414 __isl_give isl_set *PetScan::try_extract_nested_condition(Expr *expr)
2416 isl_set *set;
2417 int save_autodetect = autodetect;
2418 bool save_nesting = nesting_enabled;
2420 autodetect = 1;
2421 nesting_enabled = allow_nested;
2422 set = extract_condition(expr);
2424 autodetect = save_autodetect;
2425 nesting_enabled = save_nesting;
2427 return set;
2430 /* If the top-level expression of "stmt" is an assignment, then
2431 * return that assignment as a BinaryOperator.
2432 * Otherwise return NULL.
2434 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
2436 BinaryOperator *ass;
2438 if (!stmt)
2439 return NULL;
2440 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
2441 return NULL;
2443 ass = cast<BinaryOperator>(stmt);
2444 if(ass->getOpcode() != BO_Assign)
2445 return NULL;
2447 return ass;
2450 /* Check if the given if statement is a conditional assignement
2451 * with a non-affine condition. If so, construct a pet_scop
2452 * corresponding to this conditional assignment. Otherwise return NULL.
2454 * In particular we check if "stmt" is of the form
2456 * if (condition)
2457 * a = f(...);
2458 * else
2459 * a = g(...);
2461 * where a is some array or scalar access.
2462 * The constructed pet_scop then corresponds to the expression
2464 * a = condition ? f(...) : g(...)
2466 * All access relations in f(...) are intersected with condition
2467 * while all access relation in g(...) are intersected with the complement.
2469 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
2471 BinaryOperator *ass_then, *ass_else;
2472 isl_map *write_then, *write_else;
2473 isl_set *cond, *comp;
2474 isl_map *map, *map_true, *map_false;
2475 int equal;
2476 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
2477 bool save_nesting = nesting_enabled;
2479 ass_then = top_assignment_or_null(stmt->getThen());
2480 ass_else = top_assignment_or_null(stmt->getElse());
2482 if (!ass_then || !ass_else)
2483 return NULL;
2485 if (is_affine_condition(stmt->getCond()))
2486 return NULL;
2488 write_then = extract_access(ass_then->getLHS());
2489 write_else = extract_access(ass_else->getLHS());
2491 equal = isl_map_is_equal(write_then, write_else);
2492 isl_map_free(write_else);
2493 if (equal < 0 || !equal) {
2494 isl_map_free(write_then);
2495 return NULL;
2498 nesting_enabled = allow_nested;
2499 cond = extract_condition(stmt->getCond());
2500 nesting_enabled = save_nesting;
2501 comp = isl_set_complement(isl_set_copy(cond));
2502 map_true = isl_map_from_domain(isl_set_from_params(isl_set_copy(cond)));
2503 map_true = isl_map_add_dims(map_true, isl_dim_out, 1);
2504 map_true = isl_map_fix_si(map_true, isl_dim_out, 0, 1);
2505 map_false = isl_map_from_domain(isl_set_from_params(isl_set_copy(comp)));
2506 map_false = isl_map_add_dims(map_false, isl_dim_out, 1);
2507 map_false = isl_map_fix_si(map_false, isl_dim_out, 0, 0);
2508 map = isl_map_union_disjoint(map_true, map_false);
2510 pe_cond = pet_expr_from_access(map);
2512 pe_then = extract_expr(ass_then->getRHS());
2513 pe_then = pet_expr_restrict(pe_then, cond);
2514 pe_else = extract_expr(ass_else->getRHS());
2515 pe_else = pet_expr_restrict(pe_else, comp);
2517 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
2518 pe_write = pet_expr_from_access(write_then);
2519 if (pe_write) {
2520 pe_write->acc.write = 1;
2521 pe_write->acc.read = 0;
2523 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
2524 return extract(stmt, pe);
2527 /* Create an access to a virtual array representing the result
2528 * of a condition.
2529 * Unlike other accessed data, the id of the array is NULL as
2530 * there is no ValueDecl in the program corresponding to the virtual
2531 * array.
2532 * The array starts out as a scalar, but grows along with the
2533 * statement writing to the array in pet_scop_embed.
2535 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2537 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2538 isl_id *id;
2539 char name[50];
2541 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2542 id = isl_id_alloc(ctx, name, NULL);
2543 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2544 return isl_map_universe(dim);
2547 /* Create a pet_scop with a single statement evaluating "cond"
2548 * and writing the result to a virtual scalar, as expressed by
2549 * "access".
2551 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
2552 __isl_take isl_map *access)
2554 struct pet_expr *expr, *write;
2555 struct pet_stmt *ps;
2556 SourceLocation loc = cond->getLocStart();
2557 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2559 write = pet_expr_from_access(access);
2560 if (write) {
2561 write->acc.write = 1;
2562 write->acc.read = 0;
2564 expr = extract_expr(cond);
2565 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
2566 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
2567 return pet_scop_from_pet_stmt(ctx, ps);
2570 /* Add an array with the given extend ("access") to the list
2571 * of arrays in "scop" and return the extended pet_scop.
2572 * The array is marked as attaining values 0 and 1 only.
2574 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2575 __isl_keep isl_map *access)
2577 isl_ctx *ctx = isl_map_get_ctx(access);
2578 isl_space *dim;
2579 struct pet_array **arrays;
2580 struct pet_array *array;
2582 if (!scop)
2583 return NULL;
2584 if (!ctx)
2585 goto error;
2587 arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2588 scop->n_array + 1);
2589 if (!arrays)
2590 goto error;
2591 scop->arrays = arrays;
2593 array = isl_calloc_type(ctx, struct pet_array);
2594 if (!array)
2595 goto error;
2597 array->extent = isl_map_range(isl_map_copy(access));
2598 dim = isl_space_params_alloc(ctx, 0);
2599 array->context = isl_set_universe(dim);
2600 dim = isl_space_set_alloc(ctx, 0, 1);
2601 array->value_bounds = isl_set_universe(dim);
2602 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2603 isl_dim_set, 0, 0);
2604 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2605 isl_dim_set, 0, 1);
2606 array->element_type = strdup("int");
2608 scop->arrays[scop->n_array] = array;
2609 scop->n_array++;
2611 if (!array->extent || !array->context)
2612 goto error;
2614 return scop;
2615 error:
2616 pet_scop_free(scop);
2617 return NULL;
2620 extern "C" {
2621 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
2622 void *user);
2625 /* Apply the map pointed to by "user" to the domain of the access
2626 * relation, thereby embedding it in the range of the map.
2627 * The domain of both relations is the zero-dimensional domain.
2629 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
2631 isl_map *map = (isl_map *) user;
2633 return isl_map_apply_domain(access, isl_map_copy(map));
2636 /* Apply "map" to all access relations in "expr".
2638 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
2640 return pet_expr_foreach_access(expr, &embed_access, map);
2643 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2645 static int n_nested_parameter(__isl_keep isl_set *set)
2647 isl_space *space;
2648 int n;
2650 space = isl_set_get_space(set);
2651 n = n_nested_parameter(space);
2652 isl_space_free(space);
2654 return n;
2657 /* Remove all parameters from "map" that refer to nested accesses.
2659 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
2661 int nparam;
2662 isl_space *space;
2664 space = isl_map_get_space(map);
2665 nparam = isl_space_dim(space, isl_dim_param);
2666 for (int i = nparam - 1; i >= 0; --i)
2667 if (is_nested_parameter(space, i))
2668 map = isl_map_project_out(map, isl_dim_param, i, 1);
2669 isl_space_free(space);
2671 return map;
2674 extern "C" {
2675 static __isl_give isl_map *access_remove_nested_parameters(
2676 __isl_take isl_map *access, void *user);
2679 static __isl_give isl_map *access_remove_nested_parameters(
2680 __isl_take isl_map *access, void *user)
2682 return remove_nested_parameters(access);
2685 /* Remove all nested access parameters from the schedule and all
2686 * accesses of "stmt".
2687 * There is no need to remove them from the domain as these parameters
2688 * have already been removed from the domain when this function is called.
2690 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
2692 if (!stmt)
2693 return NULL;
2694 stmt->schedule = remove_nested_parameters(stmt->schedule);
2695 stmt->body = pet_expr_foreach_access(stmt->body,
2696 &access_remove_nested_parameters, NULL);
2697 if (!stmt->schedule || !stmt->body)
2698 goto error;
2699 for (int i = 0; i < stmt->n_arg; ++i) {
2700 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
2701 &access_remove_nested_parameters, NULL);
2702 if (!stmt->args[i])
2703 goto error;
2706 return stmt;
2707 error:
2708 pet_stmt_free(stmt);
2709 return NULL;
2712 /* For each nested access parameter in the domain of "stmt",
2713 * construct a corresponding pet_expr, place it in stmt->args and
2714 * record its position in "param2pos".
2715 * n is the number of nested access parameters.
2717 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
2718 std::map<int,int> &param2pos)
2720 isl_space *space;
2721 unsigned n_arg;
2722 struct pet_expr **args;
2724 n_arg = stmt->n_arg;
2725 args = isl_realloc_array(ctx, stmt->args, struct pet_expr *, n_arg + n);
2726 if (!args)
2727 goto error;
2728 stmt->args = args;
2729 stmt->n_arg += n;
2731 space = isl_set_get_space(stmt->domain);
2732 n = extract_nested(space, n_arg, stmt->args, param2pos);
2733 isl_space_free(space);
2735 if (n < 0)
2736 goto error;
2738 stmt->n_arg = n;
2739 return stmt;
2740 error:
2741 pet_stmt_free(stmt);
2742 return NULL;
2745 /* Look for parameters in the iteration domain of "stmt" taht
2746 * refer to nested accesses. In particular, these are
2747 * parameters with no name.
2749 * If there are any such parameters, then as many extra variables
2750 * (after identifying identical nested accesses) are added to the
2751 * range of the map wrapped inside the domain.
2752 * If the original domain is not a wrapped map, then a new wrapped
2753 * map is created with zero output dimensions.
2754 * The parameters are then equated to the corresponding output dimensions
2755 * and subsequently projected out, from the iteration domain,
2756 * the schedule and the access relations.
2757 * For each of the output dimensions, a corresponding argument
2758 * expression is added. Initially they are created with
2759 * a zero-dimensional domain, so they have to be embedded
2760 * in the current iteration domain.
2761 * param2pos maps the position of the parameter to the position
2762 * of the corresponding output dimension in the wrapped map.
2764 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
2766 int n;
2767 int nparam;
2768 unsigned n_arg;
2769 isl_map *map;
2770 std::map<int,int> param2pos;
2772 if (!stmt)
2773 return NULL;
2775 n = n_nested_parameter(stmt->domain);
2776 if (n == 0)
2777 return stmt;
2779 n_arg = stmt->n_arg;
2780 stmt = extract_nested(stmt, n, param2pos);
2781 if (!stmt)
2782 return NULL;
2784 n = stmt->n_arg - n_arg;
2785 nparam = isl_set_dim(stmt->domain, isl_dim_param);
2786 if (isl_set_is_wrapping(stmt->domain))
2787 map = isl_set_unwrap(stmt->domain);
2788 else
2789 map = isl_map_from_domain(stmt->domain);
2790 map = isl_map_add_dims(map, isl_dim_out, n);
2792 for (int i = nparam - 1; i >= 0; --i) {
2793 isl_id *id;
2795 if (!is_nested_parameter(map, i))
2796 continue;
2798 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
2799 isl_dim_out);
2800 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
2801 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
2802 param2pos[i]);
2803 map = isl_map_project_out(map, isl_dim_param, i, 1);
2806 stmt->domain = isl_map_wrap(map);
2808 map = isl_set_unwrap(isl_set_copy(stmt->domain));
2809 map = isl_map_from_range(isl_map_domain(map));
2810 for (int pos = n_arg; pos < stmt->n_arg; ++pos)
2811 stmt->args[pos] = embed(stmt->args[pos], map);
2812 isl_map_free(map);
2814 stmt = remove_nested_parameters(stmt);
2816 return stmt;
2817 error:
2818 pet_stmt_free(stmt);
2819 return NULL;
2822 /* For each statement in "scop", move the parameters that correspond
2823 * to nested access into the ranges of the domains and create
2824 * corresponding argument expressions.
2826 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
2828 if (!scop)
2829 return NULL;
2831 for (int i = 0; i < scop->n_stmt; ++i) {
2832 scop->stmts[i] = resolve_nested(scop->stmts[i]);
2833 if (!scop->stmts[i])
2834 goto error;
2837 return scop;
2838 error:
2839 pet_scop_free(scop);
2840 return NULL;
2843 /* Does "space" involve any parameters that refer to nested
2844 * accesses, i.e., parameters with no name?
2846 static bool has_nested(__isl_keep isl_space *space)
2848 int nparam;
2850 nparam = isl_space_dim(space, isl_dim_param);
2851 for (int i = 0; i < nparam; ++i)
2852 if (is_nested_parameter(space, i))
2853 return true;
2855 return false;
2858 /* Does "set" involve any parameters that refer to nested
2859 * accesses, i.e., parameters with no name?
2861 static bool has_nested(__isl_keep isl_set *set)
2863 isl_space *space;
2864 bool nested;
2866 space = isl_set_get_space(set);
2867 nested = has_nested(space);
2868 isl_space_free(space);
2870 return nested;
2873 /* Given an access expression "expr", is the variable accessed by
2874 * "expr" assigned anywhere inside "scop"?
2876 static bool is_assigned(pet_expr *expr, pet_scop *scop)
2878 bool assigned = false;
2879 isl_id *id;
2881 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
2882 assigned = pet_scop_writes(scop, id);
2883 isl_id_free(id);
2885 return assigned;
2888 /* Are all nested access parameters in "set" allowed given "scop".
2889 * In particular, is none of them written by anywhere inside "scop".
2891 bool PetScan::is_nested_allowed(__isl_keep isl_set *set, pet_scop *scop)
2893 int nparam;
2895 nparam = isl_set_dim(set, isl_dim_param);
2896 for (int i = 0; i < nparam; ++i) {
2897 Expr *nested;
2898 isl_id *id = isl_set_get_dim_id(set, isl_dim_param, i);
2899 pet_expr *expr;
2900 bool allowed;
2902 if (!is_nested_parameter(id)) {
2903 isl_id_free(id);
2904 continue;
2907 nested = (Expr *) isl_id_get_user(id);
2908 expr = extract_expr(nested);
2909 allowed = expr && expr->type == pet_expr_access &&
2910 !is_assigned(expr, scop);
2912 pet_expr_free(expr);
2913 isl_id_free(id);
2915 if (!allowed)
2916 return false;
2919 return true;
2922 /* Construct a pet_scop for an if statement.
2924 * If the condition fits the pattern of a conditional assignment,
2925 * then it is handled by extract_conditional_assignment.
2926 * Otherwise, we do the following.
2928 * If the condition is affine, then the condition is added
2929 * to the iteration domains of the then branch, while the
2930 * opposite of the condition in added to the iteration domains
2931 * of the else branch, if any.
2932 * We allow the condition to be dynamic, i.e., to refer to
2933 * scalars or array elements that may be written to outside
2934 * of the given if statement. These nested accesses are then represented
2935 * as output dimensions in the wrapping iteration domain.
2936 * If it also written _inside_ the then or else branch, then
2937 * we treat the condition as non-affine.
2938 * As explained below, this will introduce an extra statement.
2939 * For aesthetic reasons, we want this statement to have a statement
2940 * number that is lower than those of the then and else branches.
2941 * In order to evaluate if will need such a statement, however, we
2942 * first construct scops for the then and else branches.
2943 * We therefore reserve a statement number if we might have to
2944 * introduce such an extra statement.
2946 * If the condition is not affine, then we create a separate
2947 * statement that write the result of the condition to a virtual scalar.
2948 * A constraint requiring the value of this virtual scalar to be one
2949 * is added to the iteration domains of the then branch.
2950 * Similarly, a constraint requiring the value of this virtual scalar
2951 * to be zero is added to the iteration domains of the else branch, if any.
2952 * We adjust the schedules to ensure that the virtual scalar is written
2953 * before it is read.
2955 struct pet_scop *PetScan::extract(IfStmt *stmt)
2957 struct pet_scop *scop_then, *scop_else, *scop;
2958 assigned_value_cache cache(assigned_value);
2959 isl_map *test_access = NULL;
2960 isl_set *cond;
2961 int stmt_id;
2963 scop = extract_conditional_assignment(stmt);
2964 if (scop)
2965 return scop;
2967 cond = try_extract_nested_condition(stmt->getCond());
2968 if (allow_nested && (!cond || has_nested(cond)))
2969 stmt_id = n_stmt++;
2971 scop_then = extract(stmt->getThen());
2973 if (stmt->getElse()) {
2974 scop_else = extract(stmt->getElse());
2975 if (autodetect) {
2976 if (scop_then && !scop_else) {
2977 partial = true;
2978 isl_set_free(cond);
2979 return scop_then;
2981 if (!scop_then && scop_else) {
2982 partial = true;
2983 isl_set_free(cond);
2984 return scop_else;
2989 if (cond &&
2990 (!is_nested_allowed(cond, scop_then) ||
2991 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
2992 isl_set_free(cond);
2993 cond = NULL;
2995 if (allow_nested && !cond) {
2996 int save_n_stmt = n_stmt;
2997 test_access = create_test_access(ctx, n_test++);
2998 n_stmt = stmt_id;
2999 scop = extract_non_affine_condition(stmt->getCond(),
3000 isl_map_copy(test_access));
3001 n_stmt = save_n_stmt;
3002 scop = scop_add_array(scop, test_access);
3003 if (!scop) {
3004 pet_scop_free(scop_then);
3005 pet_scop_free(scop_else);
3006 isl_map_free(test_access);
3007 return NULL;
3011 if (!scop) {
3012 if (!cond)
3013 cond = extract_condition(stmt->getCond());
3014 scop = pet_scop_restrict(scop_then, isl_set_copy(cond));
3016 if (stmt->getElse()) {
3017 cond = isl_set_complement(cond);
3018 scop_else = pet_scop_restrict(scop_else, cond);
3019 scop = pet_scop_add(ctx, scop, scop_else);
3020 } else
3021 isl_set_free(cond);
3022 scop = resolve_nested(scop);
3023 } else {
3024 scop = pet_scop_prefix(scop, 0);
3025 scop_then = pet_scop_prefix(scop_then, 1);
3026 scop_then = pet_scop_filter(scop_then,
3027 isl_map_copy(test_access), 1);
3028 scop = pet_scop_add(ctx, scop, scop_then);
3029 if (stmt->getElse()) {
3030 scop_else = pet_scop_prefix(scop_else, 1);
3031 scop_else = pet_scop_filter(scop_else, test_access, 0);
3032 scop = pet_scop_add(ctx, scop, scop_else);
3033 } else
3034 isl_map_free(test_access);
3037 return scop;
3040 /* Try and construct a pet_scop for a label statement.
3041 * We currently only allow labels on expression statements.
3043 struct pet_scop *PetScan::extract(LabelStmt *stmt)
3045 isl_id *label;
3046 Stmt *sub;
3048 sub = stmt->getSubStmt();
3049 if (!isa<Expr>(sub)) {
3050 unsupported(stmt);
3051 return NULL;
3054 label = isl_id_alloc(ctx, stmt->getName(), NULL);
3056 return extract(sub, extract_expr(cast<Expr>(sub)), label);
3059 /* Try and construct a pet_scop corresponding to "stmt".
3061 struct pet_scop *PetScan::extract(Stmt *stmt)
3063 if (isa<Expr>(stmt))
3064 return extract(stmt, extract_expr(cast<Expr>(stmt)));
3066 switch (stmt->getStmtClass()) {
3067 case Stmt::WhileStmtClass:
3068 return extract(cast<WhileStmt>(stmt));
3069 case Stmt::ForStmtClass:
3070 return extract_for(cast<ForStmt>(stmt));
3071 case Stmt::IfStmtClass:
3072 return extract(cast<IfStmt>(stmt));
3073 case Stmt::CompoundStmtClass:
3074 return extract(cast<CompoundStmt>(stmt));
3075 case Stmt::LabelStmtClass:
3076 return extract(cast<LabelStmt>(stmt));
3077 default:
3078 unsupported(stmt);
3081 return NULL;
3084 /* Try and construct a pet_scop corresponding to (part of)
3085 * a sequence of statements.
3087 struct pet_scop *PetScan::extract(StmtRange stmt_range)
3089 pet_scop *scop;
3090 StmtIterator i;
3091 int j;
3092 bool partial_range = false;
3094 scop = pet_scop_empty(ctx);
3095 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
3096 Stmt *child = *i;
3097 struct pet_scop *scop_i;
3098 scop_i = extract(child);
3099 if (scop && partial) {
3100 pet_scop_free(scop_i);
3101 break;
3103 scop_i = pet_scop_prefix(scop_i, j);
3104 if (autodetect) {
3105 if (scop_i)
3106 scop = pet_scop_add(ctx, scop, scop_i);
3107 else
3108 partial_range = true;
3109 if (scop->n_stmt != 0 && !scop_i)
3110 partial = true;
3111 } else {
3112 scop = pet_scop_add(ctx, scop, scop_i);
3114 if (partial)
3115 break;
3118 if (scop && partial_range)
3119 partial = true;
3121 return scop;
3124 /* Check if the scop marked by the user is exactly this Stmt
3125 * or part of this Stmt.
3126 * If so, return a pet_scop corresponding to the marked region.
3127 * Otherwise, return NULL.
3129 struct pet_scop *PetScan::scan(Stmt *stmt)
3131 SourceManager &SM = PP.getSourceManager();
3132 unsigned start_off, end_off;
3134 start_off = SM.getFileOffset(stmt->getLocStart());
3135 end_off = SM.getFileOffset(stmt->getLocEnd());
3137 if (start_off > loc.end)
3138 return NULL;
3139 if (end_off < loc.start)
3140 return NULL;
3141 if (start_off >= loc.start && end_off <= loc.end) {
3142 return extract(stmt);
3145 StmtIterator start;
3146 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
3147 Stmt *child = *start;
3148 if (!child)
3149 continue;
3150 start_off = SM.getFileOffset(child->getLocStart());
3151 end_off = SM.getFileOffset(child->getLocEnd());
3152 if (start_off < loc.start && end_off > loc.end)
3153 return scan(child);
3154 if (start_off >= loc.start)
3155 break;
3158 StmtIterator end;
3159 for (end = start; end != stmt->child_end(); ++end) {
3160 Stmt *child = *end;
3161 start_off = SM.getFileOffset(child->getLocStart());
3162 if (start_off >= loc.end)
3163 break;
3166 return extract(StmtRange(start, end));
3169 /* Set the size of index "pos" of "array" to "size".
3170 * In particular, add a constraint of the form
3172 * i_pos < size
3174 * to array->extent and a constraint of the form
3176 * size >= 0
3178 * to array->context.
3180 static struct pet_array *update_size(struct pet_array *array, int pos,
3181 __isl_take isl_pw_aff *size)
3183 isl_set *valid;
3184 isl_set *univ;
3185 isl_set *bound;
3186 isl_space *dim;
3187 isl_aff *aff;
3188 isl_pw_aff *index;
3189 isl_id *id;
3191 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
3192 array->context = isl_set_intersect(array->context, valid);
3194 dim = isl_set_get_space(array->extent);
3195 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
3196 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
3197 univ = isl_set_universe(isl_aff_get_domain_space(aff));
3198 index = isl_pw_aff_alloc(univ, aff);
3200 size = isl_pw_aff_add_dims(size, isl_dim_in,
3201 isl_set_dim(array->extent, isl_dim_set));
3202 id = isl_set_get_tuple_id(array->extent);
3203 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
3204 bound = isl_pw_aff_lt_set(index, size);
3206 array->extent = isl_set_intersect(array->extent, bound);
3208 if (!array->context || !array->extent)
3209 goto error;
3211 return array;
3212 error:
3213 pet_array_free(array);
3214 return NULL;
3217 /* Figure out the size of the array at position "pos" and all
3218 * subsequent positions from "type" and update "array" accordingly.
3220 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
3221 const Type *type, int pos)
3223 const ArrayType *atype;
3224 isl_pw_aff *size;
3226 if (!array)
3227 return NULL;
3229 if (type->isPointerType()) {
3230 type = type->getPointeeType().getTypePtr();
3231 return set_upper_bounds(array, type, pos + 1);
3233 if (!type->isArrayType())
3234 return array;
3236 type = type->getCanonicalTypeInternal().getTypePtr();
3237 atype = cast<ArrayType>(type);
3239 if (type->isConstantArrayType()) {
3240 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
3241 size = extract_affine(ca->getSize());
3242 array = update_size(array, pos, size);
3243 } else if (type->isVariableArrayType()) {
3244 const VariableArrayType *vla = cast<VariableArrayType>(atype);
3245 size = extract_affine(vla->getSizeExpr());
3246 array = update_size(array, pos, size);
3249 type = atype->getElementType().getTypePtr();
3251 return set_upper_bounds(array, type, pos + 1);
3254 /* Construct and return a pet_array corresponding to the variable "decl".
3255 * In particular, initialize array->extent to
3257 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3259 * and then call set_upper_bounds to set the upper bounds on the indices
3260 * based on the type of the variable.
3262 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
3264 struct pet_array *array;
3265 QualType qt = decl->getType();
3266 const Type *type = qt.getTypePtr();
3267 int depth = array_depth(type);
3268 QualType base = base_type(qt);
3269 string name;
3270 isl_id *id;
3271 isl_space *dim;
3273 array = isl_calloc_type(ctx, struct pet_array);
3274 if (!array)
3275 return NULL;
3277 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
3278 dim = isl_space_set_alloc(ctx, 0, depth);
3279 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
3281 array->extent = isl_set_nat_universe(dim);
3283 dim = isl_space_params_alloc(ctx, 0);
3284 array->context = isl_set_universe(dim);
3286 array = set_upper_bounds(array, type, 0);
3287 if (!array)
3288 return NULL;
3290 name = base.getAsString();
3291 array->element_type = strdup(name.c_str());
3293 return array;
3296 /* Construct a list of pet_arrays, one for each array (or scalar)
3297 * accessed inside "scop" add this list to "scop" and return the result.
3299 * The context of "scop" is updated with the intesection of
3300 * the contexts of all arrays, i.e., constraints on the parameters
3301 * that ensure that the arrays have a valid (non-negative) size.
3303 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
3305 int i;
3306 set<ValueDecl *> arrays;
3307 set<ValueDecl *>::iterator it;
3308 int n_array;
3309 struct pet_array **scop_arrays;
3311 if (!scop)
3312 return NULL;
3314 pet_scop_collect_arrays(scop, arrays);
3315 if (arrays.size() == 0)
3316 return scop;
3318 n_array = scop->n_array;
3320 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3321 n_array + arrays.size());
3322 if (!scop_arrays)
3323 goto error;
3324 scop->arrays = scop_arrays;
3326 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3327 struct pet_array *array;
3328 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
3329 if (!scop->arrays[n_array + i])
3330 goto error;
3331 scop->n_array++;
3332 scop->context = isl_set_intersect(scop->context,
3333 isl_set_copy(array->context));
3334 if (!scop->context)
3335 goto error;
3338 return scop;
3339 error:
3340 pet_scop_free(scop);
3341 return NULL;
3344 /* Construct a pet_scop from the given function.
3346 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3348 pet_scop *scop;
3349 Stmt *stmt;
3351 stmt = fd->getBody();
3353 if (autodetect)
3354 scop = extract(stmt);
3355 else
3356 scop = scan(stmt);
3357 scop = pet_scop_detect_parameter_accesses(scop);
3358 scop = scan_arrays(scop);
3360 return scop;