update isl for isl_val_int_from_chunks
[pet.git] / scan.cc
blob1bef8bed37d3bd5c47ea57d6e4f5efe1246eb298
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012 Ecole Normale Superieure. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
32 * Leiden University.
33 */
35 #include <string.h>
36 #include <set>
37 #include <map>
38 #include <iostream>
39 #include <llvm/Support/raw_ostream.h>
40 #include <clang/AST/ASTContext.h>
41 #include <clang/AST/ASTDiagnostic.h>
42 #include <clang/AST/Expr.h>
43 #include <clang/AST/RecursiveASTVisitor.h>
45 #include <isl/id.h>
46 #include <isl/space.h>
47 #include <isl/aff.h>
48 #include <isl/set.h>
50 #include "options.h"
51 #include "scan.h"
52 #include "scop.h"
53 #include "scop_plus.h"
55 #include "config.h"
57 using namespace std;
58 using namespace clang;
60 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
61 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
63 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
64 SourceLocation(), var, false, var->getInnerLocStart(),
65 var->getType(), VK_LValue);
67 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
68 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
70 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
71 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
72 VK_LValue);
74 #else
75 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
77 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
78 var, var->getInnerLocStart(), var->getType(), VK_LValue);
80 #endif
82 /* Check if the element type corresponding to the given array type
83 * has a const qualifier.
85 static bool const_base(QualType qt)
87 const Type *type = qt.getTypePtr();
89 if (type->isPointerType())
90 return const_base(type->getPointeeType());
91 if (type->isArrayType()) {
92 const ArrayType *atype;
93 type = type->getCanonicalTypeInternal().getTypePtr();
94 atype = cast<ArrayType>(type);
95 return const_base(atype->getElementType());
98 return qt.isConstQualified();
101 /* Mark "decl" as having an unknown value in "assigned_value".
103 * If no (known or unknown) value was assigned to "decl" before,
104 * then it may have been treated as a parameter before and may
105 * therefore appear in a value assigned to another variable.
106 * If so, this assignment needs to be turned into an unknown value too.
108 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
109 ValueDecl *decl)
111 map<ValueDecl *, isl_pw_aff *>::iterator it;
113 it = assigned_value.find(decl);
115 assigned_value[decl] = NULL;
117 if (it == assigned_value.end())
118 return;
120 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
121 isl_pw_aff *pa = it->second;
122 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
124 for (int i = 0; i < nparam; ++i) {
125 isl_id *id;
127 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
128 continue;
129 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
130 if (isl_id_get_user(id) == decl)
131 it->second = NULL;
132 isl_id_free(id);
137 /* Look for any assignments to scalar variables in part of the parse
138 * tree and set assigned_value to NULL for each of them.
139 * Also reset assigned_value if the address of a scalar variable
140 * is being taken. As an exception, if the address is passed to a function
141 * that is declared to receive a const pointer, then assigned_value is
142 * not reset.
144 * This ensures that we won't use any previously stored value
145 * in the current subtree and its parents.
147 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
148 map<ValueDecl *, isl_pw_aff *> &assigned_value;
149 set<UnaryOperator *> skip;
151 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
152 assigned_value(assigned_value) {}
154 /* Check for "address of" operators whose value is passed
155 * to a const pointer argument and add them to "skip", so that
156 * we can skip them in VisitUnaryOperator.
158 bool VisitCallExpr(CallExpr *expr) {
159 FunctionDecl *fd;
160 fd = expr->getDirectCallee();
161 if (!fd)
162 return true;
163 for (int i = 0; i < expr->getNumArgs(); ++i) {
164 Expr *arg = expr->getArg(i);
165 UnaryOperator *op;
166 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
167 ImplicitCastExpr *ice;
168 ice = cast<ImplicitCastExpr>(arg);
169 arg = ice->getSubExpr();
171 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
172 continue;
173 op = cast<UnaryOperator>(arg);
174 if (op->getOpcode() != UO_AddrOf)
175 continue;
176 if (const_base(fd->getParamDecl(i)->getType()))
177 skip.insert(op);
179 return true;
182 bool VisitUnaryOperator(UnaryOperator *expr) {
183 Expr *arg;
184 DeclRefExpr *ref;
185 ValueDecl *decl;
187 switch (expr->getOpcode()) {
188 case UO_AddrOf:
189 case UO_PostInc:
190 case UO_PostDec:
191 case UO_PreInc:
192 case UO_PreDec:
193 break;
194 default:
195 return true;
197 if (skip.find(expr) != skip.end())
198 return true;
200 arg = expr->getSubExpr();
201 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
202 return true;
203 ref = cast<DeclRefExpr>(arg);
204 decl = ref->getDecl();
205 clear_assignment(assigned_value, decl);
206 return true;
209 bool VisitBinaryOperator(BinaryOperator *expr) {
210 Expr *lhs;
211 DeclRefExpr *ref;
212 ValueDecl *decl;
214 if (!expr->isAssignmentOp())
215 return true;
216 lhs = expr->getLHS();
217 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
218 return true;
219 ref = cast<DeclRefExpr>(lhs);
220 decl = ref->getDecl();
221 clear_assignment(assigned_value, decl);
222 return true;
226 /* Keep a copy of the currently assigned values.
228 * Any variable that is assigned a value inside the current scope
229 * is removed again when we leave the scope (either because it wasn't
230 * stored in the cache or because it has a different value in the cache).
232 struct assigned_value_cache {
233 map<ValueDecl *, isl_pw_aff *> &assigned_value;
234 map<ValueDecl *, isl_pw_aff *> cache;
236 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
237 assigned_value(assigned_value), cache(assigned_value) {}
238 ~assigned_value_cache() {
239 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
240 for (it = assigned_value.begin(); it != assigned_value.end();
241 ++it) {
242 if (!it->second ||
243 (cache.find(it->first) != cache.end() &&
244 cache[it->first] != it->second))
245 cache[it->first] = NULL;
247 assigned_value = cache;
251 /* Insert an expression into the collection of expressions,
252 * provided it is not already in there.
253 * The isl_pw_affs are freed in the destructor.
255 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
257 std::set<isl_pw_aff *>::iterator it;
259 if (expressions.find(expr) == expressions.end())
260 expressions.insert(expr);
261 else
262 isl_pw_aff_free(expr);
265 PetScan::~PetScan()
267 std::set<isl_pw_aff *>::iterator it;
269 for (it = expressions.begin(); it != expressions.end(); ++it)
270 isl_pw_aff_free(*it);
272 isl_union_map_free(value_bounds);
275 /* Called if we found something we (currently) cannot handle.
276 * We'll provide more informative warnings later.
278 * We only actually complain if autodetect is false.
280 void PetScan::unsupported(Stmt *stmt, const char *msg)
282 if (options->autodetect)
283 return;
285 SourceLocation loc = stmt->getLocStart();
286 DiagnosticsEngine &diag = PP.getDiagnostics();
287 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
288 msg ? msg : "unsupported");
289 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
292 /* Extract an integer from "expr".
294 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
296 const Type *type = expr->getType().getTypePtr();
297 int is_signed = type->hasSignedIntegerRepresentation();
299 if (is_signed) {
300 int64_t i = expr->getValue().getSExtValue();
301 return isl_val_int_from_si(ctx, i);
302 } else {
303 uint64_t i = expr->getValue().getZExtValue();
304 return isl_val_int_from_ui(ctx, i);
308 /* Extract an integer from "expr".
309 * Return NULL if "expr" does not (obviously) represent an integer.
311 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
313 return extract_int(expr->getSubExpr());
316 /* Extract an integer from "expr".
317 * Return NULL if "expr" does not (obviously) represent an integer.
319 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
321 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
322 return extract_int(ctx, cast<IntegerLiteral>(expr));
323 if (expr->getStmtClass() == Stmt::ParenExprClass)
324 return extract_int(cast<ParenExpr>(expr));
326 unsupported(expr);
327 return NULL;
330 /* Extract an affine expression from the IntegerLiteral "expr".
332 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
334 isl_space *dim = isl_space_params_alloc(ctx, 0);
335 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
336 isl_aff *aff = isl_aff_zero_on_domain(ls);
337 isl_set *dom = isl_set_universe(dim);
338 isl_val *v;
340 v = extract_int(expr);
341 aff = isl_aff_add_constant_val(aff, v);
343 return isl_pw_aff_alloc(dom, aff);
346 /* Extract an affine expression from the APInt "val".
348 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
350 isl_space *dim = isl_space_params_alloc(ctx, 0);
351 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
352 isl_aff *aff = isl_aff_zero_on_domain(ls);
353 isl_set *dom = isl_set_universe(dim);
354 isl_val *v;
356 v = isl_val_int_from_ui(ctx, val.getZExtValue());
357 aff = isl_aff_add_constant_val(aff, v);
359 return isl_pw_aff_alloc(dom, aff);
362 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
364 return extract_affine(expr->getSubExpr());
367 static unsigned get_type_size(ValueDecl *decl)
369 return decl->getASTContext().getIntWidth(decl->getType());
372 /* Bound parameter "pos" of "set" to the possible values of "decl".
374 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
375 unsigned pos, ValueDecl *decl)
377 unsigned width;
378 isl_ctx *ctx;
379 isl_val *bound;
381 ctx = isl_set_get_ctx(set);
382 width = get_type_size(decl);
383 if (decl->getType()->isUnsignedIntegerType()) {
384 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
385 bound = isl_val_int_from_ui(ctx, width);
386 bound = isl_val_2exp(bound);
387 bound = isl_val_sub_ui(bound, 1);
388 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
389 } else {
390 bound = isl_val_int_from_ui(ctx, width - 1);
391 bound = isl_val_2exp(bound);
392 bound = isl_val_sub_ui(bound, 1);
393 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
394 isl_val_copy(bound));
395 bound = isl_val_neg(bound);
396 bound = isl_val_sub_ui(bound, 1);
397 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
400 return set;
403 /* Extract an affine expression from the DeclRefExpr "expr".
405 * If the variable has been assigned a value, then we check whether
406 * we know what (affine) value was assigned.
407 * If so, we return this value. Otherwise we convert "expr"
408 * to an extra parameter (provided nesting_enabled is set).
410 * Otherwise, we simply return an expression that is equal
411 * to a parameter corresponding to the referenced variable.
413 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
415 ValueDecl *decl = expr->getDecl();
416 const Type *type = decl->getType().getTypePtr();
417 isl_id *id;
418 isl_space *dim;
419 isl_aff *aff;
420 isl_set *dom;
422 if (!type->isIntegerType()) {
423 unsupported(expr);
424 return NULL;
427 if (assigned_value.find(decl) != assigned_value.end()) {
428 if (assigned_value[decl])
429 return isl_pw_aff_copy(assigned_value[decl]);
430 else
431 return nested_access(expr);
434 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
435 dim = isl_space_params_alloc(ctx, 1);
437 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
439 dom = isl_set_universe(isl_space_copy(dim));
440 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
441 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
443 return isl_pw_aff_alloc(dom, aff);
446 /* Extract an affine expression from an integer division operation.
447 * In particular, if "expr" is lhs/rhs, then return
449 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
451 * The second argument (rhs) is required to be a (positive) integer constant.
453 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
455 int is_cst;
456 isl_pw_aff *rhs, *lhs;
458 rhs = extract_affine(expr->getRHS());
459 is_cst = isl_pw_aff_is_cst(rhs);
460 if (is_cst < 0 || !is_cst) {
461 isl_pw_aff_free(rhs);
462 if (!is_cst)
463 unsupported(expr);
464 return NULL;
467 lhs = extract_affine(expr->getLHS());
469 return isl_pw_aff_tdiv_q(lhs, rhs);
472 /* Extract an affine expression from a modulo operation.
473 * In particular, if "expr" is lhs/rhs, then return
475 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
477 * The second argument (rhs) is required to be a (positive) integer constant.
479 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
481 int is_cst;
482 isl_pw_aff *rhs, *lhs;
484 rhs = extract_affine(expr->getRHS());
485 is_cst = isl_pw_aff_is_cst(rhs);
486 if (is_cst < 0 || !is_cst) {
487 isl_pw_aff_free(rhs);
488 if (!is_cst)
489 unsupported(expr);
490 return NULL;
493 lhs = extract_affine(expr->getLHS());
495 return isl_pw_aff_tdiv_r(lhs, rhs);
498 /* Extract an affine expression from a multiplication operation.
499 * This is only allowed if at least one of the two arguments
500 * is a (piecewise) constant.
502 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
504 isl_pw_aff *lhs;
505 isl_pw_aff *rhs;
507 lhs = extract_affine(expr->getLHS());
508 rhs = extract_affine(expr->getRHS());
510 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
511 isl_pw_aff_free(lhs);
512 isl_pw_aff_free(rhs);
513 unsupported(expr);
514 return NULL;
517 return isl_pw_aff_mul(lhs, rhs);
520 /* Extract an affine expression from an addition or subtraction operation.
522 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
524 isl_pw_aff *lhs;
525 isl_pw_aff *rhs;
527 lhs = extract_affine(expr->getLHS());
528 rhs = extract_affine(expr->getRHS());
530 switch (expr->getOpcode()) {
531 case BO_Add:
532 return isl_pw_aff_add(lhs, rhs);
533 case BO_Sub:
534 return isl_pw_aff_sub(lhs, rhs);
535 default:
536 isl_pw_aff_free(lhs);
537 isl_pw_aff_free(rhs);
538 return NULL;
543 /* Compute
545 * pwaff mod 2^width
547 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
548 unsigned width)
550 isl_ctx *ctx;
551 isl_val *mod;
553 ctx = isl_pw_aff_get_ctx(pwaff);
554 mod = isl_val_int_from_ui(ctx, width);
555 mod = isl_val_2exp(mod);
557 pwaff = isl_pw_aff_mod_val(pwaff, mod);
559 return pwaff;
562 /* Limit the domain of "pwaff" to those elements where the function
563 * value satisfies
565 * 2^{width-1} <= pwaff < 2^{width-1}
567 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
568 unsigned width)
570 isl_ctx *ctx;
571 isl_val *v;
572 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
573 isl_local_space *ls = isl_local_space_from_space(space);
574 isl_aff *bound;
575 isl_set *dom;
576 isl_pw_aff *b;
578 ctx = isl_pw_aff_get_ctx(pwaff);
579 v = isl_val_int_from_ui(ctx, width - 1);
580 v = isl_val_2exp(v);
582 bound = isl_aff_zero_on_domain(ls);
583 bound = isl_aff_add_constant_val(bound, v);
584 b = isl_pw_aff_from_aff(bound);
586 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
587 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
589 b = isl_pw_aff_neg(b);
590 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
591 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
593 return pwaff;
596 /* Handle potential overflows on signed computations.
598 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
599 * the we adjust the domain of "pa" to avoid overflows.
601 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
602 unsigned width)
604 if (options->signed_overflow == PET_OVERFLOW_AVOID)
605 pa = avoid_overflow(pa, width);
607 return pa;
610 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
612 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
613 __isl_take isl_set *dom)
615 isl_pw_aff *pa;
616 pa = isl_set_indicator_function(set);
617 pa = isl_pw_aff_intersect_domain(pa, dom);
618 return pa;
621 /* Extract an affine expression from some binary operations.
622 * If the result of the expression is unsigned, then we wrap it
623 * based on the size of the type. Otherwise, we ensure that
624 * no overflow occurs.
626 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
628 isl_pw_aff *res;
629 unsigned width;
631 switch (expr->getOpcode()) {
632 case BO_Add:
633 case BO_Sub:
634 res = extract_affine_add(expr);
635 break;
636 case BO_Div:
637 res = extract_affine_div(expr);
638 break;
639 case BO_Rem:
640 res = extract_affine_mod(expr);
641 break;
642 case BO_Mul:
643 res = extract_affine_mul(expr);
644 break;
645 case BO_LT:
646 case BO_LE:
647 case BO_GT:
648 case BO_GE:
649 case BO_EQ:
650 case BO_NE:
651 case BO_LAnd:
652 case BO_LOr:
653 return extract_condition(expr);
654 default:
655 unsupported(expr);
656 return NULL;
659 width = ast_context.getIntWidth(expr->getType());
660 if (expr->getType()->isUnsignedIntegerType())
661 res = wrap(res, width);
662 else
663 res = signed_overflow(res, width);
665 return res;
668 /* Extract an affine expression from a negation operation.
670 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
672 if (expr->getOpcode() == UO_Minus)
673 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
674 if (expr->getOpcode() == UO_LNot)
675 return extract_condition(expr);
677 unsupported(expr);
678 return NULL;
681 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
683 return extract_affine(expr->getSubExpr());
686 /* Extract an affine expression from some special function calls.
687 * In particular, we handle "min", "max", "ceild" and "floord".
688 * In case of the latter two, the second argument needs to be
689 * a (positive) integer constant.
691 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
693 FunctionDecl *fd;
694 string name;
695 isl_pw_aff *aff1, *aff2;
697 fd = expr->getDirectCallee();
698 if (!fd) {
699 unsupported(expr);
700 return NULL;
703 name = fd->getDeclName().getAsString();
704 if (!(expr->getNumArgs() == 2 && name == "min") &&
705 !(expr->getNumArgs() == 2 && name == "max") &&
706 !(expr->getNumArgs() == 2 && name == "floord") &&
707 !(expr->getNumArgs() == 2 && name == "ceild")) {
708 unsupported(expr);
709 return NULL;
712 if (name == "min" || name == "max") {
713 aff1 = extract_affine(expr->getArg(0));
714 aff2 = extract_affine(expr->getArg(1));
716 if (name == "min")
717 aff1 = isl_pw_aff_min(aff1, aff2);
718 else
719 aff1 = isl_pw_aff_max(aff1, aff2);
720 } else if (name == "floord" || name == "ceild") {
721 isl_val *v;
722 Expr *arg2 = expr->getArg(1);
724 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
725 unsupported(expr);
726 return NULL;
728 aff1 = extract_affine(expr->getArg(0));
729 v = extract_int(cast<IntegerLiteral>(arg2));
730 aff1 = isl_pw_aff_scale_down_val(aff1, v);
731 if (name == "floord")
732 aff1 = isl_pw_aff_floor(aff1);
733 else
734 aff1 = isl_pw_aff_ceil(aff1);
735 } else {
736 unsupported(expr);
737 return NULL;
740 return aff1;
743 /* This method is called when we come across an access that is
744 * nested in what is supposed to be an affine expression.
745 * If nesting is allowed, we return a new parameter that corresponds
746 * to this nested access. Otherwise, we simply complain.
748 * Note that we currently don't allow nested accesses themselves
749 * to contain any nested accesses, so we check if we can extract
750 * the access without any nesting and complain if we can't.
752 * The new parameter is resolved in resolve_nested.
754 isl_pw_aff *PetScan::nested_access(Expr *expr)
756 isl_id *id;
757 isl_space *dim;
758 isl_aff *aff;
759 isl_set *dom;
760 isl_map *access;
762 if (!nesting_enabled) {
763 unsupported(expr);
764 return NULL;
767 allow_nested = false;
768 access = extract_access(expr);
769 allow_nested = true;
770 if (!access) {
771 unsupported(expr);
772 return NULL;
774 isl_map_free(access);
776 id = isl_id_alloc(ctx, NULL, expr);
777 dim = isl_space_params_alloc(ctx, 1);
779 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
781 dom = isl_set_universe(isl_space_copy(dim));
782 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
783 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
785 return isl_pw_aff_alloc(dom, aff);
788 /* Affine expressions are not supposed to contain array accesses,
789 * but if nesting is allowed, we return a parameter corresponding
790 * to the array access.
792 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
794 return nested_access(expr);
797 /* Extract an affine expression from a conditional operation.
799 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
801 isl_pw_aff *cond, *lhs, *rhs, *res;
803 cond = extract_condition(expr->getCond());
804 lhs = extract_affine(expr->getTrueExpr());
805 rhs = extract_affine(expr->getFalseExpr());
807 return isl_pw_aff_cond(cond, lhs, rhs);
810 /* Extract an affine expression, if possible, from "expr".
811 * Otherwise return NULL.
813 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
815 switch (expr->getStmtClass()) {
816 case Stmt::ImplicitCastExprClass:
817 return extract_affine(cast<ImplicitCastExpr>(expr));
818 case Stmt::IntegerLiteralClass:
819 return extract_affine(cast<IntegerLiteral>(expr));
820 case Stmt::DeclRefExprClass:
821 return extract_affine(cast<DeclRefExpr>(expr));
822 case Stmt::BinaryOperatorClass:
823 return extract_affine(cast<BinaryOperator>(expr));
824 case Stmt::UnaryOperatorClass:
825 return extract_affine(cast<UnaryOperator>(expr));
826 case Stmt::ParenExprClass:
827 return extract_affine(cast<ParenExpr>(expr));
828 case Stmt::CallExprClass:
829 return extract_affine(cast<CallExpr>(expr));
830 case Stmt::ArraySubscriptExprClass:
831 return extract_affine(cast<ArraySubscriptExpr>(expr));
832 case Stmt::ConditionalOperatorClass:
833 return extract_affine(cast<ConditionalOperator>(expr));
834 default:
835 unsupported(expr);
837 return NULL;
840 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
842 return extract_access(expr->getSubExpr());
845 /* Return the depth of an array of the given type.
847 static int array_depth(const Type *type)
849 if (type->isPointerType())
850 return 1 + array_depth(type->getPointeeType().getTypePtr());
851 if (type->isArrayType()) {
852 const ArrayType *atype;
853 type = type->getCanonicalTypeInternal().getTypePtr();
854 atype = cast<ArrayType>(type);
855 return 1 + array_depth(atype->getElementType().getTypePtr());
857 return 0;
860 /* Return the element type of the given array type.
862 static QualType base_type(QualType qt)
864 const Type *type = qt.getTypePtr();
866 if (type->isPointerType())
867 return base_type(type->getPointeeType());
868 if (type->isArrayType()) {
869 const ArrayType *atype;
870 type = type->getCanonicalTypeInternal().getTypePtr();
871 atype = cast<ArrayType>(type);
872 return base_type(atype->getElementType());
874 return qt;
877 /* Extract an access relation from a reference to a variable.
878 * If the variable has name "A" and its type corresponds to an
879 * array of depth d, then the returned access relation is of the
880 * form
882 * { [] -> A[i_1,...,i_d] }
884 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
886 return extract_access(expr->getDecl());
889 /* Extract an access relation from a variable.
890 * If the variable has name "A" and its type corresponds to an
891 * array of depth d, then the returned access relation is of the
892 * form
894 * { [] -> A[i_1,...,i_d] }
896 __isl_give isl_map *PetScan::extract_access(ValueDecl *decl)
898 int depth = array_depth(decl->getType().getTypePtr());
899 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
900 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
901 isl_map *access_rel;
903 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
905 access_rel = isl_map_universe(dim);
907 return access_rel;
910 /* Extract an access relation from an integer contant.
911 * If the value of the constant is "v", then the returned access relation
912 * is
914 * { [] -> [v] }
916 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
918 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
921 /* Try and extract an access relation from the given Expr.
922 * Return NULL if it doesn't work out.
924 __isl_give isl_map *PetScan::extract_access(Expr *expr)
926 switch (expr->getStmtClass()) {
927 case Stmt::ImplicitCastExprClass:
928 return extract_access(cast<ImplicitCastExpr>(expr));
929 case Stmt::DeclRefExprClass:
930 return extract_access(cast<DeclRefExpr>(expr));
931 case Stmt::ArraySubscriptExprClass:
932 return extract_access(cast<ArraySubscriptExpr>(expr));
933 case Stmt::IntegerLiteralClass:
934 return extract_access(cast<IntegerLiteral>(expr));
935 default:
936 unsupported(expr);
938 return NULL;
941 /* Assign the affine expression "index" to the output dimension "pos" of "map",
942 * restrict the domain to those values that result in a non-negative index
943 * and return the result.
945 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
946 __isl_take isl_pw_aff *index)
948 isl_map *index_map;
949 int len = isl_map_dim(map, isl_dim_out);
950 isl_id *id;
951 isl_set *domain;
953 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
954 index = isl_pw_aff_intersect_domain(index, domain);
955 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
956 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
957 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
958 id = isl_map_get_tuple_id(map, isl_dim_out);
959 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
961 map = isl_map_intersect(map, index_map);
963 return map;
966 /* Extract an access relation from the given array subscript expression.
967 * If nesting is allowed in general, then we turn it on while
968 * examining the index expression.
970 * We first extract an access relation from the base.
971 * This will result in an access relation with a range that corresponds
972 * to the array being accessed and with earlier indices filled in already.
973 * We then extract the current index and fill that in as well.
974 * The position of the current index is based on the type of base.
975 * If base is the actual array variable, then the depth of this type
976 * will be the same as the depth of the array and we will fill in
977 * the first array index.
978 * Otherwise, the depth of the base type will be smaller and we will fill
979 * in a later index.
981 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
983 Expr *base = expr->getBase();
984 Expr *idx = expr->getIdx();
985 isl_pw_aff *index;
986 isl_map *base_access;
987 isl_map *access;
988 int depth = array_depth(base->getType().getTypePtr());
989 int pos;
990 bool save_nesting = nesting_enabled;
992 nesting_enabled = allow_nested;
994 base_access = extract_access(base);
995 index = extract_affine(idx);
997 nesting_enabled = save_nesting;
999 pos = isl_map_dim(base_access, isl_dim_out) - depth;
1000 access = set_index(base_access, pos, index);
1002 return access;
1005 /* Check if "expr" calls function "minmax" with two arguments and if so
1006 * make lhs and rhs refer to these two arguments.
1008 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1010 CallExpr *call;
1011 FunctionDecl *fd;
1012 string name;
1014 if (expr->getStmtClass() != Stmt::CallExprClass)
1015 return false;
1017 call = cast<CallExpr>(expr);
1018 fd = call->getDirectCallee();
1019 if (!fd)
1020 return false;
1022 if (call->getNumArgs() != 2)
1023 return false;
1025 name = fd->getDeclName().getAsString();
1026 if (name != minmax)
1027 return false;
1029 lhs = call->getArg(0);
1030 rhs = call->getArg(1);
1032 return true;
1035 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1036 * lhs and rhs refer to the two arguments.
1038 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1040 return is_minmax(expr, "min", lhs, rhs);
1043 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1044 * lhs and rhs refer to the two arguments.
1046 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1048 return is_minmax(expr, "max", lhs, rhs);
1051 /* Return "lhs && rhs", defined on the shared definition domain.
1053 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1054 __isl_take isl_pw_aff *rhs)
1056 isl_set *cond;
1057 isl_set *dom;
1059 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1060 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1061 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1062 isl_pw_aff_non_zero_set(rhs));
1063 return indicator_function(cond, dom);
1066 /* Return "lhs && rhs", with shortcut semantics.
1067 * That is, if lhs is false, then the result is defined even if rhs is not.
1068 * In practice, we compute lhs ? rhs : lhs.
1070 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1071 __isl_take isl_pw_aff *rhs)
1073 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1076 /* Return "lhs || rhs", with shortcut semantics.
1077 * That is, if lhs is true, then the result is defined even if rhs is not.
1078 * In practice, we compute lhs ? lhs : rhs.
1080 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1081 __isl_take isl_pw_aff *rhs)
1083 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1086 /* Extract an affine expressions representing the comparison "LHS op RHS"
1087 * "comp" is the original statement that "LHS op RHS" is derived from
1088 * and is used for diagnostics.
1090 * If the comparison is of the form
1092 * a <= min(b,c)
1094 * then the expression is constructed as the conjunction of
1095 * the comparisons
1097 * a <= b and a <= c
1099 * A similar optimization is performed for max(a,b) <= c.
1100 * We do this because that will lead to simpler representations
1101 * of the expression.
1102 * If isl is ever enhanced to explicitly deal with min and max expressions,
1103 * this optimization can be removed.
1105 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1106 Expr *LHS, Expr *RHS, Stmt *comp)
1108 isl_pw_aff *lhs;
1109 isl_pw_aff *rhs;
1110 isl_pw_aff *res;
1111 isl_set *cond;
1112 isl_set *dom;
1114 if (op == BO_GT)
1115 return extract_comparison(BO_LT, RHS, LHS, comp);
1116 if (op == BO_GE)
1117 return extract_comparison(BO_LE, RHS, LHS, comp);
1119 if (op == BO_LT || op == BO_LE) {
1120 Expr *expr1, *expr2;
1121 if (is_min(RHS, expr1, expr2)) {
1122 lhs = extract_comparison(op, LHS, expr1, comp);
1123 rhs = extract_comparison(op, LHS, expr2, comp);
1124 return pw_aff_and(lhs, rhs);
1126 if (is_max(LHS, expr1, expr2)) {
1127 lhs = extract_comparison(op, expr1, RHS, comp);
1128 rhs = extract_comparison(op, expr2, RHS, comp);
1129 return pw_aff_and(lhs, rhs);
1133 lhs = extract_affine(LHS);
1134 rhs = extract_affine(RHS);
1136 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1137 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1139 switch (op) {
1140 case BO_LT:
1141 cond = isl_pw_aff_lt_set(lhs, rhs);
1142 break;
1143 case BO_LE:
1144 cond = isl_pw_aff_le_set(lhs, rhs);
1145 break;
1146 case BO_EQ:
1147 cond = isl_pw_aff_eq_set(lhs, rhs);
1148 break;
1149 case BO_NE:
1150 cond = isl_pw_aff_ne_set(lhs, rhs);
1151 break;
1152 default:
1153 isl_pw_aff_free(lhs);
1154 isl_pw_aff_free(rhs);
1155 isl_set_free(dom);
1156 unsupported(comp);
1157 return NULL;
1160 cond = isl_set_coalesce(cond);
1161 res = indicator_function(cond, dom);
1163 return res;
1166 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1168 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1169 comp->getRHS(), comp);
1172 /* Extract an affine expression representing the negation (logical not)
1173 * of a subexpression.
1175 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1177 isl_set *set_cond, *dom;
1178 isl_pw_aff *cond, *res;
1180 cond = extract_condition(op->getSubExpr());
1182 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1184 set_cond = isl_pw_aff_zero_set(cond);
1186 res = indicator_function(set_cond, dom);
1188 return res;
1191 /* Extract an affine expression representing the disjunction (logical or)
1192 * or conjunction (logical and) of two subexpressions.
1194 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1196 isl_pw_aff *lhs, *rhs;
1198 lhs = extract_condition(comp->getLHS());
1199 rhs = extract_condition(comp->getRHS());
1201 switch (comp->getOpcode()) {
1202 case BO_LAnd:
1203 return pw_aff_and_then(lhs, rhs);
1204 case BO_LOr:
1205 return pw_aff_or_else(lhs, rhs);
1206 default:
1207 isl_pw_aff_free(lhs);
1208 isl_pw_aff_free(rhs);
1211 unsupported(comp);
1212 return NULL;
1215 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1217 switch (expr->getOpcode()) {
1218 case UO_LNot:
1219 return extract_boolean(expr);
1220 default:
1221 unsupported(expr);
1222 return NULL;
1226 /* Extract the affine expression "expr != 0 ? 1 : 0".
1228 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1230 isl_pw_aff *res;
1231 isl_set *set, *dom;
1233 res = extract_affine(expr);
1235 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1236 set = isl_pw_aff_non_zero_set(res);
1238 res = indicator_function(set, dom);
1240 return res;
1243 /* Extract an affine expression from a boolean expression.
1244 * In particular, return the expression "expr ? 1 : 0".
1246 * If the expression doesn't look like a condition, we assume it
1247 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1249 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1251 BinaryOperator *comp;
1253 if (!expr) {
1254 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1255 return indicator_function(u, isl_set_copy(u));
1258 if (expr->getStmtClass() == Stmt::ParenExprClass)
1259 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1261 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1262 return extract_condition(cast<UnaryOperator>(expr));
1264 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1265 return extract_implicit_condition(expr);
1267 comp = cast<BinaryOperator>(expr);
1268 switch (comp->getOpcode()) {
1269 case BO_LT:
1270 case BO_LE:
1271 case BO_GT:
1272 case BO_GE:
1273 case BO_EQ:
1274 case BO_NE:
1275 return extract_comparison(comp);
1276 case BO_LAnd:
1277 case BO_LOr:
1278 return extract_boolean(comp);
1279 default:
1280 return extract_implicit_condition(expr);
1284 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1286 switch (kind) {
1287 case UO_Minus:
1288 return pet_op_minus;
1289 case UO_PostInc:
1290 return pet_op_post_inc;
1291 case UO_PostDec:
1292 return pet_op_post_dec;
1293 case UO_PreInc:
1294 return pet_op_pre_inc;
1295 case UO_PreDec:
1296 return pet_op_pre_dec;
1297 default:
1298 return pet_op_last;
1302 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1304 switch (kind) {
1305 case BO_AddAssign:
1306 return pet_op_add_assign;
1307 case BO_SubAssign:
1308 return pet_op_sub_assign;
1309 case BO_MulAssign:
1310 return pet_op_mul_assign;
1311 case BO_DivAssign:
1312 return pet_op_div_assign;
1313 case BO_Assign:
1314 return pet_op_assign;
1315 case BO_Add:
1316 return pet_op_add;
1317 case BO_Sub:
1318 return pet_op_sub;
1319 case BO_Mul:
1320 return pet_op_mul;
1321 case BO_Div:
1322 return pet_op_div;
1323 case BO_Rem:
1324 return pet_op_mod;
1325 case BO_EQ:
1326 return pet_op_eq;
1327 case BO_LE:
1328 return pet_op_le;
1329 case BO_LT:
1330 return pet_op_lt;
1331 case BO_GT:
1332 return pet_op_gt;
1333 default:
1334 return pet_op_last;
1338 /* Construct a pet_expr representing a unary operator expression.
1340 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1342 struct pet_expr *arg;
1343 enum pet_op_type op;
1345 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1346 if (op == pet_op_last) {
1347 unsupported(expr);
1348 return NULL;
1351 arg = extract_expr(expr->getSubExpr());
1353 if (expr->isIncrementDecrementOp() &&
1354 arg && arg->type == pet_expr_access) {
1355 mark_write(arg);
1356 arg->acc.read = 1;
1359 return pet_expr_new_unary(ctx, op, arg);
1362 /* Mark the given access pet_expr as a write.
1363 * If a scalar is being accessed, then mark its value
1364 * as unknown in assigned_value.
1366 void PetScan::mark_write(struct pet_expr *access)
1368 isl_id *id;
1369 ValueDecl *decl;
1371 if (!access)
1372 return;
1374 access->acc.write = 1;
1375 access->acc.read = 0;
1377 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1378 return;
1380 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1381 decl = (ValueDecl *) isl_id_get_user(id);
1382 clear_assignment(assigned_value, decl);
1383 isl_id_free(id);
1386 /* Assign "rhs" to "lhs".
1388 * In particular, if "lhs" is a scalar variable, then mark
1389 * the variable as having been assigned. If, furthermore, "rhs"
1390 * is an affine expression, then keep track of this value in assigned_value
1391 * so that we can plug it in when we later come across the same variable.
1393 void PetScan::assign(struct pet_expr *lhs, Expr *rhs)
1395 isl_id *id;
1396 ValueDecl *decl;
1397 isl_pw_aff *pa;
1399 if (!lhs)
1400 return;
1401 if (lhs->type != pet_expr_access)
1402 return;
1403 if (isl_map_dim(lhs->acc.access, isl_dim_out) != 0)
1404 return;
1406 id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1407 decl = (ValueDecl *) isl_id_get_user(id);
1408 isl_id_free(id);
1410 pa = try_extract_affine(rhs);
1411 clear_assignment(assigned_value, decl);
1412 if (!pa)
1413 return;
1414 assigned_value[decl] = pa;
1415 insert_expression(pa);
1418 /* Construct a pet_expr representing a binary operator expression.
1420 * If the top level operator is an assignment and the LHS is an access,
1421 * then we mark that access as a write. If the operator is a compound
1422 * assignment, the access is marked as both a read and a write.
1424 * If "expr" assigns something to a scalar variable, then we mark
1425 * the variable as having been assigned. If, furthermore, the expression
1426 * is affine, then keep track of this value in assigned_value
1427 * so that we can plug it in when we later come across the same variable.
1429 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1431 struct pet_expr *lhs, *rhs;
1432 enum pet_op_type op;
1434 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1435 if (op == pet_op_last) {
1436 unsupported(expr);
1437 return NULL;
1440 lhs = extract_expr(expr->getLHS());
1441 rhs = extract_expr(expr->getRHS());
1443 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1444 mark_write(lhs);
1445 if (expr->isCompoundAssignmentOp())
1446 lhs->acc.read = 1;
1449 if (expr->getOpcode() == BO_Assign)
1450 assign(lhs, expr->getRHS());
1452 return pet_expr_new_binary(ctx, op, lhs, rhs);
1455 /* Construct a pet_scop with a single statement killing the entire
1456 * array "array".
1458 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1460 isl_map *access;
1461 struct pet_expr *expr;
1463 if (!array)
1464 return NULL;
1465 access = isl_map_from_range(isl_set_copy(array->extent));
1466 expr = pet_expr_kill_from_access(access);
1467 return extract(stmt, expr);
1470 /* Construct a pet_scop for a (single) variable declaration.
1472 * The scop contains the variable being declared (as an array)
1473 * and a statement killing the array.
1475 * If the variable is initialized in the AST, then the scop
1476 * also contains an assignment to the variable.
1478 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1480 Decl *decl;
1481 VarDecl *vd;
1482 struct pet_expr *lhs, *rhs, *pe;
1483 struct pet_scop *scop_decl, *scop;
1484 struct pet_array *array;
1486 if (!stmt->isSingleDecl()) {
1487 unsupported(stmt);
1488 return NULL;
1491 decl = stmt->getSingleDecl();
1492 vd = cast<VarDecl>(decl);
1494 array = extract_array(ctx, vd);
1495 if (array)
1496 array->declared = 1;
1497 scop_decl = kill(stmt, array);
1498 scop_decl = pet_scop_add_array(scop_decl, array);
1500 if (!vd->getInit())
1501 return scop_decl;
1503 lhs = pet_expr_from_access(extract_access(vd));
1504 rhs = extract_expr(vd->getInit());
1506 mark_write(lhs);
1507 assign(lhs, vd->getInit());
1509 pe = pet_expr_new_binary(ctx, pet_op_assign, lhs, rhs);
1510 scop = extract(stmt, pe);
1512 scop_decl = pet_scop_prefix(scop_decl, 0);
1513 scop = pet_scop_prefix(scop, 1);
1515 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1517 return scop;
1520 /* Construct a pet_expr representing a conditional operation.
1522 * We first try to extract the condition as an affine expression.
1523 * If that fails, we construct a pet_expr tree representing the condition.
1525 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1527 struct pet_expr *cond, *lhs, *rhs;
1528 isl_pw_aff *pa;
1530 pa = try_extract_affine(expr->getCond());
1531 if (pa) {
1532 isl_set *test = isl_set_from_pw_aff(pa);
1533 cond = pet_expr_from_access(isl_map_from_range(test));
1534 } else
1535 cond = extract_expr(expr->getCond());
1536 lhs = extract_expr(expr->getTrueExpr());
1537 rhs = extract_expr(expr->getFalseExpr());
1539 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1542 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1544 return extract_expr(expr->getSubExpr());
1547 /* Construct a pet_expr representing a floating point value.
1549 * If the floating point literal does not appear in a macro,
1550 * then we use the original representation in the source code
1551 * as the string representation. Otherwise, we use the pretty
1552 * printer to produce a string representation.
1554 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1556 double d;
1557 string s;
1558 const LangOptions &LO = PP.getLangOpts();
1559 SourceLocation loc = expr->getLocation();
1561 if (!loc.isMacroID()) {
1562 SourceManager &SM = PP.getSourceManager();
1563 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1564 s = string(SM.getCharacterData(loc), len);
1565 } else {
1566 llvm::raw_string_ostream S(s);
1567 expr->printPretty(S, 0, PrintingPolicy(LO));
1568 S.str();
1570 d = expr->getValueAsApproximateDouble();
1571 return pet_expr_new_double(ctx, d, s.c_str());
1574 /* Extract an access relation from "expr" and then convert it into
1575 * a pet_expr.
1577 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1579 isl_map *access;
1580 struct pet_expr *pe;
1582 access = extract_access(expr);
1584 pe = pet_expr_from_access(access);
1586 return pe;
1589 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1591 return extract_expr(expr->getSubExpr());
1594 /* Construct a pet_expr representing a function call.
1596 * If we are passing along a pointer to an array element
1597 * or an entire row or even higher dimensional slice of an array,
1598 * then the function being called may write into the array.
1600 * We assume here that if the function is declared to take a pointer
1601 * to a const type, then the function will perform a read
1602 * and that otherwise, it will perform a write.
1604 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1606 struct pet_expr *res = NULL;
1607 FunctionDecl *fd;
1608 string name;
1610 fd = expr->getDirectCallee();
1611 if (!fd) {
1612 unsupported(expr);
1613 return NULL;
1616 name = fd->getDeclName().getAsString();
1617 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1618 if (!res)
1619 return NULL;
1621 for (int i = 0; i < expr->getNumArgs(); ++i) {
1622 Expr *arg = expr->getArg(i);
1623 int is_addr = 0;
1624 pet_expr *main_arg;
1626 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1627 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1628 arg = ice->getSubExpr();
1630 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1631 UnaryOperator *op = cast<UnaryOperator>(arg);
1632 if (op->getOpcode() == UO_AddrOf) {
1633 is_addr = 1;
1634 arg = op->getSubExpr();
1637 res->args[i] = PetScan::extract_expr(arg);
1638 main_arg = res->args[i];
1639 if (is_addr)
1640 res->args[i] = pet_expr_new_unary(ctx,
1641 pet_op_address_of, res->args[i]);
1642 if (!res->args[i])
1643 goto error;
1644 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1645 array_depth(arg->getType().getTypePtr()) > 0)
1646 is_addr = 1;
1647 if (is_addr && main_arg->type == pet_expr_access) {
1648 ParmVarDecl *parm;
1649 if (!fd->hasPrototype()) {
1650 unsupported(expr, "prototype required");
1651 goto error;
1653 parm = fd->getParamDecl(i);
1654 if (!const_base(parm->getType()))
1655 mark_write(main_arg);
1659 return res;
1660 error:
1661 pet_expr_free(res);
1662 return NULL;
1665 /* Construct a pet_expr representing a (C style) cast.
1667 struct pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1669 struct pet_expr *arg;
1670 QualType type;
1672 arg = extract_expr(expr->getSubExpr());
1673 if (!arg)
1674 return NULL;
1676 type = expr->getTypeAsWritten();
1677 return pet_expr_new_cast(ctx, type.getAsString().c_str(), arg);
1680 /* Try and onstruct a pet_expr representing "expr".
1682 struct pet_expr *PetScan::extract_expr(Expr *expr)
1684 switch (expr->getStmtClass()) {
1685 case Stmt::UnaryOperatorClass:
1686 return extract_expr(cast<UnaryOperator>(expr));
1687 case Stmt::CompoundAssignOperatorClass:
1688 case Stmt::BinaryOperatorClass:
1689 return extract_expr(cast<BinaryOperator>(expr));
1690 case Stmt::ImplicitCastExprClass:
1691 return extract_expr(cast<ImplicitCastExpr>(expr));
1692 case Stmt::ArraySubscriptExprClass:
1693 case Stmt::DeclRefExprClass:
1694 case Stmt::IntegerLiteralClass:
1695 return extract_access_expr(expr);
1696 case Stmt::FloatingLiteralClass:
1697 return extract_expr(cast<FloatingLiteral>(expr));
1698 case Stmt::ParenExprClass:
1699 return extract_expr(cast<ParenExpr>(expr));
1700 case Stmt::ConditionalOperatorClass:
1701 return extract_expr(cast<ConditionalOperator>(expr));
1702 case Stmt::CallExprClass:
1703 return extract_expr(cast<CallExpr>(expr));
1704 case Stmt::CStyleCastExprClass:
1705 return extract_expr(cast<CStyleCastExpr>(expr));
1706 default:
1707 unsupported(expr);
1709 return NULL;
1712 /* Check if the given initialization statement is an assignment.
1713 * If so, return that assignment. Otherwise return NULL.
1715 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1717 BinaryOperator *ass;
1719 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1720 return NULL;
1722 ass = cast<BinaryOperator>(init);
1723 if (ass->getOpcode() != BO_Assign)
1724 return NULL;
1726 return ass;
1729 /* Check if the given initialization statement is a declaration
1730 * of a single variable.
1731 * If so, return that declaration. Otherwise return NULL.
1733 Decl *PetScan::initialization_declaration(Stmt *init)
1735 DeclStmt *decl;
1737 if (init->getStmtClass() != Stmt::DeclStmtClass)
1738 return NULL;
1740 decl = cast<DeclStmt>(init);
1742 if (!decl->isSingleDecl())
1743 return NULL;
1745 return decl->getSingleDecl();
1748 /* Given the assignment operator in the initialization of a for loop,
1749 * extract the induction variable, i.e., the (integer)variable being
1750 * assigned.
1752 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1754 Expr *lhs;
1755 DeclRefExpr *ref;
1756 ValueDecl *decl;
1757 const Type *type;
1759 lhs = init->getLHS();
1760 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1761 unsupported(init);
1762 return NULL;
1765 ref = cast<DeclRefExpr>(lhs);
1766 decl = ref->getDecl();
1767 type = decl->getType().getTypePtr();
1769 if (!type->isIntegerType()) {
1770 unsupported(lhs);
1771 return NULL;
1774 return decl;
1777 /* Given the initialization statement of a for loop and the single
1778 * declaration in this initialization statement,
1779 * extract the induction variable, i.e., the (integer) variable being
1780 * declared.
1782 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1784 VarDecl *vd;
1786 vd = cast<VarDecl>(decl);
1788 const QualType type = vd->getType();
1789 if (!type->isIntegerType()) {
1790 unsupported(init);
1791 return NULL;
1794 if (!vd->getInit()) {
1795 unsupported(init);
1796 return NULL;
1799 return vd;
1802 /* Check that op is of the form iv++ or iv--.
1803 * Return an affine expression "1" or "-1" accordingly.
1805 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
1806 clang::UnaryOperator *op, clang::ValueDecl *iv)
1808 Expr *sub;
1809 DeclRefExpr *ref;
1810 isl_space *space;
1811 isl_aff *aff;
1813 if (!op->isIncrementDecrementOp()) {
1814 unsupported(op);
1815 return NULL;
1818 sub = op->getSubExpr();
1819 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1820 unsupported(op);
1821 return NULL;
1824 ref = cast<DeclRefExpr>(sub);
1825 if (ref->getDecl() != iv) {
1826 unsupported(op);
1827 return NULL;
1830 space = isl_space_params_alloc(ctx, 0);
1831 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1833 if (op->isIncrementOp())
1834 aff = isl_aff_add_constant_si(aff, 1);
1835 else
1836 aff = isl_aff_add_constant_si(aff, -1);
1838 return isl_pw_aff_from_aff(aff);
1841 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1842 * has a single constant expression, then put this constant in *user.
1843 * The caller is assumed to have checked that this function will
1844 * be called exactly once.
1846 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1847 void *user)
1849 isl_val **inc = (isl_val **)user;
1850 int res = 0;
1852 if (isl_aff_is_cst(aff))
1853 *inc = isl_aff_get_constant_val(aff);
1854 else
1855 res = -1;
1857 isl_set_free(set);
1858 isl_aff_free(aff);
1860 return res;
1863 /* Check if op is of the form
1865 * iv = iv + inc
1867 * and return inc as an affine expression.
1869 * We extract an affine expression from the RHS, subtract iv and return
1870 * the result.
1872 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
1873 clang::ValueDecl *iv)
1875 Expr *lhs;
1876 DeclRefExpr *ref;
1877 isl_id *id;
1878 isl_space *dim;
1879 isl_aff *aff;
1880 isl_pw_aff *val;
1882 if (op->getOpcode() != BO_Assign) {
1883 unsupported(op);
1884 return NULL;
1887 lhs = op->getLHS();
1888 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1889 unsupported(op);
1890 return NULL;
1893 ref = cast<DeclRefExpr>(lhs);
1894 if (ref->getDecl() != iv) {
1895 unsupported(op);
1896 return NULL;
1899 val = extract_affine(op->getRHS());
1901 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1903 dim = isl_space_params_alloc(ctx, 1);
1904 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1905 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1906 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1908 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1910 return val;
1913 /* Check that op is of the form iv += cst or iv -= cst
1914 * and return an affine expression corresponding oto cst or -cst accordingly.
1916 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
1917 CompoundAssignOperator *op, clang::ValueDecl *iv)
1919 Expr *lhs;
1920 DeclRefExpr *ref;
1921 bool neg = false;
1922 isl_pw_aff *val;
1923 BinaryOperatorKind opcode;
1925 opcode = op->getOpcode();
1926 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1927 unsupported(op);
1928 return NULL;
1930 if (opcode == BO_SubAssign)
1931 neg = true;
1933 lhs = op->getLHS();
1934 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1935 unsupported(op);
1936 return NULL;
1939 ref = cast<DeclRefExpr>(lhs);
1940 if (ref->getDecl() != iv) {
1941 unsupported(op);
1942 return NULL;
1945 val = extract_affine(op->getRHS());
1946 if (neg)
1947 val = isl_pw_aff_neg(val);
1949 return val;
1952 /* Check that the increment of the given for loop increments
1953 * (or decrements) the induction variable "iv" and return
1954 * the increment as an affine expression if successful.
1956 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
1957 ValueDecl *iv)
1959 Stmt *inc = stmt->getInc();
1961 if (!inc) {
1962 unsupported(stmt);
1963 return NULL;
1966 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1967 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1968 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1969 return extract_compound_increment(
1970 cast<CompoundAssignOperator>(inc), iv);
1971 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1972 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1974 unsupported(inc);
1975 return NULL;
1978 /* Embed the given iteration domain in an extra outer loop
1979 * with induction variable "var".
1980 * If this variable appeared as a parameter in the constraints,
1981 * it is replaced by the new outermost dimension.
1983 static __isl_give isl_set *embed(__isl_take isl_set *set,
1984 __isl_take isl_id *var)
1986 int pos;
1988 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1989 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1990 if (pos >= 0) {
1991 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1992 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1995 isl_id_free(var);
1996 return set;
1999 /* Return those elements in the space of "cond" that come after
2000 * (based on "sign") an element in "cond".
2002 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
2004 isl_map *previous_to_this;
2006 if (sign > 0)
2007 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
2008 else
2009 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
2011 cond = isl_set_apply(cond, previous_to_this);
2013 return cond;
2016 /* Create the infinite iteration domain
2018 * { [id] : id >= 0 }
2020 * If "scop" has an affine skip of type pet_skip_later,
2021 * then remove those iterations i that have an earlier iteration
2022 * where the skip condition is satisfied, meaning that iteration i
2023 * is not executed.
2024 * Since we are dealing with a loop without loop iterator,
2025 * the skip condition cannot refer to the current loop iterator and
2026 * so effectively, the returned set is of the form
2028 * { [0]; [id] : id >= 1 and not skip }
2030 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
2031 struct pet_scop *scop)
2033 isl_ctx *ctx = isl_id_get_ctx(id);
2034 isl_set *domain;
2035 isl_set *skip;
2037 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
2038 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
2040 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
2041 return domain;
2043 skip = pet_scop_get_skip(scop, pet_skip_later);
2044 skip = isl_set_fix_si(skip, isl_dim_set, 0, 1);
2045 skip = isl_set_params(skip);
2046 skip = embed(skip, isl_id_copy(id));
2047 skip = isl_set_intersect(skip , isl_set_copy(domain));
2048 domain = isl_set_subtract(domain, after(skip, 1));
2050 return domain;
2053 /* Create an identity mapping on the space containing "domain".
2055 static __isl_give isl_map *identity_map(__isl_keep isl_set *domain)
2057 isl_space *space;
2058 isl_map *id;
2060 space = isl_space_map_from_set(isl_set_get_space(domain));
2061 id = isl_map_identity(space);
2063 return id;
2066 /* Add a filter to "scop" that imposes that it is only executed
2067 * when "break_access" has a zero value for all previous iterations
2068 * of "domain".
2070 * The input "break_access" has a zero-dimensional domain and range.
2072 static struct pet_scop *scop_add_break(struct pet_scop *scop,
2073 __isl_take isl_map *break_access, __isl_take isl_set *domain, int sign)
2075 isl_ctx *ctx = isl_set_get_ctx(domain);
2076 isl_id *id_test;
2077 isl_map *prev;
2079 id_test = isl_map_get_tuple_id(break_access, isl_dim_out);
2080 break_access = isl_map_add_dims(break_access, isl_dim_in, 1);
2081 break_access = isl_map_add_dims(break_access, isl_dim_out, 1);
2082 break_access = isl_map_intersect_range(break_access, domain);
2083 break_access = isl_map_set_tuple_id(break_access, isl_dim_out, id_test);
2084 if (sign > 0)
2085 prev = isl_map_lex_gt_first(isl_map_get_space(break_access), 1);
2086 else
2087 prev = isl_map_lex_lt_first(isl_map_get_space(break_access), 1);
2088 break_access = isl_map_intersect(break_access, prev);
2089 scop = pet_scop_filter(scop, break_access, 0);
2090 scop = pet_scop_merge_filters(scop);
2092 return scop;
2095 /* Construct a pet_scop for an infinite loop around the given body.
2097 * We extract a pet_scop for the body and then embed it in a loop with
2098 * iteration domain
2100 * { [t] : t >= 0 }
2102 * and schedule
2104 * { [t] -> [t] }
2106 * If the body contains any break, then it is taken into
2107 * account in infinite_domain (if the skip condition is affine)
2108 * or in scop_add_break (if the skip condition is not affine).
2110 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2112 isl_id *id;
2113 isl_set *domain;
2114 isl_map *ident;
2115 isl_map *access;
2116 struct pet_scop *scop;
2117 bool has_var_break;
2119 scop = extract(body);
2120 if (!scop)
2121 return NULL;
2123 id = isl_id_alloc(ctx, "t", NULL);
2124 domain = infinite_domain(isl_id_copy(id), scop);
2125 ident = identity_map(domain);
2127 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2128 if (has_var_break)
2129 access = pet_scop_get_skip_map(scop, pet_skip_later);
2131 scop = pet_scop_embed(scop, isl_set_copy(domain),
2132 isl_map_copy(ident), ident, id);
2133 if (has_var_break)
2134 scop = scop_add_break(scop, access, domain, 1);
2135 else
2136 isl_set_free(domain);
2138 return scop;
2141 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2143 * for (;;)
2144 * body
2147 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2149 return extract_infinite_loop(stmt->getBody());
2152 /* Create an access to a virtual array representing the result
2153 * of a condition.
2154 * Unlike other accessed data, the id of the array is NULL as
2155 * there is no ValueDecl in the program corresponding to the virtual
2156 * array.
2157 * The array starts out as a scalar, but grows along with the
2158 * statement writing to the array in pet_scop_embed.
2160 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2162 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2163 isl_id *id;
2164 char name[50];
2166 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2167 id = isl_id_alloc(ctx, name, NULL);
2168 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2169 return isl_map_universe(dim);
2172 /* Add an array with the given extent ("access") to the list
2173 * of arrays in "scop" and return the extended pet_scop.
2174 * The array is marked as attaining values 0 and 1 only and
2175 * as each element being assigned at most once.
2177 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2178 __isl_keep isl_map *access, clang::ASTContext &ast_ctx)
2180 isl_ctx *ctx = isl_map_get_ctx(access);
2181 isl_space *dim;
2182 struct pet_array *array;
2184 if (!scop)
2185 return NULL;
2186 if (!ctx)
2187 goto error;
2189 array = isl_calloc_type(ctx, struct pet_array);
2190 if (!array)
2191 goto error;
2193 array->extent = isl_map_range(isl_map_copy(access));
2194 dim = isl_space_params_alloc(ctx, 0);
2195 array->context = isl_set_universe(dim);
2196 dim = isl_space_set_alloc(ctx, 0, 1);
2197 array->value_bounds = isl_set_universe(dim);
2198 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2199 isl_dim_set, 0, 0);
2200 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2201 isl_dim_set, 0, 1);
2202 array->element_type = strdup("int");
2203 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2204 array->uniquely_defined = 1;
2206 if (!array->extent || !array->context)
2207 array = pet_array_free(array);
2209 scop = pet_scop_add_array(scop, array);
2211 return scop;
2212 error:
2213 pet_scop_free(scop);
2214 return NULL;
2217 /* Construct a pet_scop for a while loop of the form
2219 * while (pa)
2220 * body
2222 * In particular, construct a scop for an infinite loop around body and
2223 * intersect the domain with the affine expression.
2224 * Note that this intersection may result in an empty loop.
2226 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2227 Stmt *body)
2229 struct pet_scop *scop;
2230 isl_set *dom;
2231 isl_set *valid;
2233 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2234 dom = isl_pw_aff_non_zero_set(pa);
2235 scop = extract_infinite_loop(body);
2236 scop = pet_scop_restrict(scop, dom);
2237 scop = pet_scop_restrict_context(scop, valid);
2239 return scop;
2242 /* Construct a scop for a while, given the scops for the condition
2243 * and the body, the filter access and the iteration domain of
2244 * the while loop.
2246 * In particular, the scop for the condition is filtered to depend
2247 * on "test_access" evaluating to true for all previous iterations
2248 * of the loop, while the scop for the body is filtered to depend
2249 * on "test_access" evaluating to true for all iterations up to the
2250 * current iteration.
2252 * These filtered scops are then combined into a single scop.
2254 * "sign" is positive if the iterator increases and negative
2255 * if it decreases.
2257 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2258 struct pet_scop *scop_body, __isl_take isl_map *test_access,
2259 __isl_take isl_set *domain, int sign)
2261 isl_ctx *ctx = isl_set_get_ctx(domain);
2262 isl_id *id_test;
2263 isl_map *prev;
2265 id_test = isl_map_get_tuple_id(test_access, isl_dim_out);
2266 test_access = isl_map_add_dims(test_access, isl_dim_in, 1);
2267 test_access = isl_map_add_dims(test_access, isl_dim_out, 1);
2268 test_access = isl_map_intersect_range(test_access, domain);
2269 test_access = isl_map_set_tuple_id(test_access, isl_dim_out, id_test);
2270 if (sign > 0)
2271 prev = isl_map_lex_ge_first(isl_map_get_space(test_access), 1);
2272 else
2273 prev = isl_map_lex_le_first(isl_map_get_space(test_access), 1);
2274 test_access = isl_map_intersect(test_access, prev);
2275 scop_body = pet_scop_filter(scop_body, isl_map_copy(test_access), 1);
2276 if (sign > 0)
2277 prev = isl_map_lex_gt_first(isl_map_get_space(test_access), 1);
2278 else
2279 prev = isl_map_lex_lt_first(isl_map_get_space(test_access), 1);
2280 test_access = isl_map_intersect(test_access, prev);
2281 scop_cond = pet_scop_filter(scop_cond, test_access, 1);
2283 return pet_scop_add_seq(ctx, scop_cond, scop_body);
2286 /* Check if the while loop is of the form
2288 * while (affine expression)
2289 * body
2291 * If so, call extract_affine_while to construct a scop.
2293 * Otherwise, construct a generic while scop, with iteration domain
2294 * { [t] : t >= 0 }. The scop consists of two parts, one for
2295 * evaluating the condition and one for the body.
2296 * The schedule is adjusted to reflect that the condition is evaluated
2297 * before the body is executed and the body is filtered to depend
2298 * on the result of the condition evaluating to true on all iterations
2299 * up to the current iteration, while the evaluation the condition itself
2300 * is filtered to depend on the result of the condition evaluating to true
2301 * on all previous iterations.
2302 * The context of the scop representing the body is dropped
2303 * because we don't know how many times the body will be executed,
2304 * if at all.
2306 * If the body contains any break, then it is taken into
2307 * account in infinite_domain (if the skip condition is affine)
2308 * or in scop_add_break (if the skip condition is not affine).
2310 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2312 Expr *cond;
2313 isl_id *id;
2314 isl_map *test_access;
2315 isl_set *domain;
2316 isl_map *ident;
2317 isl_pw_aff *pa;
2318 struct pet_scop *scop, *scop_body;
2319 bool has_var_break;
2320 isl_map *break_access;
2322 cond = stmt->getCond();
2323 if (!cond) {
2324 unsupported(stmt);
2325 return NULL;
2328 clear_assignments clear(assigned_value);
2329 clear.TraverseStmt(stmt->getBody());
2331 pa = try_extract_affine_condition(cond);
2332 if (pa)
2333 return extract_affine_while(pa, stmt->getBody());
2335 if (!allow_nested) {
2336 unsupported(stmt);
2337 return NULL;
2340 test_access = create_test_access(ctx, n_test++);
2341 scop = extract_non_affine_condition(cond, isl_map_copy(test_access));
2342 scop = scop_add_array(scop, test_access, ast_context);
2343 scop_body = extract(stmt->getBody());
2345 id = isl_id_alloc(ctx, "t", NULL);
2346 domain = infinite_domain(isl_id_copy(id), scop_body);
2347 ident = identity_map(domain);
2349 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2350 if (has_var_break)
2351 break_access = pet_scop_get_skip_map(scop_body, pet_skip_later);
2353 scop = pet_scop_prefix(scop, 0);
2354 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_map_copy(ident),
2355 isl_map_copy(ident), isl_id_copy(id));
2356 scop_body = pet_scop_reset_context(scop_body);
2357 scop_body = pet_scop_prefix(scop_body, 1);
2358 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2359 isl_map_copy(ident), ident, id);
2361 if (has_var_break) {
2362 scop = scop_add_break(scop, isl_map_copy(break_access),
2363 isl_set_copy(domain), 1);
2364 scop_body = scop_add_break(scop_body, break_access,
2365 isl_set_copy(domain), 1);
2367 scop = scop_add_while(scop, scop_body, test_access, domain, 1);
2369 return scop;
2372 /* Check whether "cond" expresses a simple loop bound
2373 * on the only set dimension.
2374 * In particular, if "up" is set then "cond" should contain only
2375 * upper bounds on the set dimension.
2376 * Otherwise, it should contain only lower bounds.
2378 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2380 if (isl_val_is_pos(inc))
2381 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2382 else
2383 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2386 /* Extend a condition on a given iteration of a loop to one that
2387 * imposes the same condition on all previous iterations.
2388 * "domain" expresses the lower [upper] bound on the iterations
2389 * when inc is positive [negative].
2391 * In particular, we construct the condition (when inc is positive)
2393 * forall i' : (domain(i') and i' <= i) => cond(i')
2395 * which is equivalent to
2397 * not exists i' : domain(i') and i' <= i and not cond(i')
2399 * We construct this set by negating cond, applying a map
2401 * { [i'] -> [i] : domain(i') and i' <= i }
2403 * and then negating the result again.
2405 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2406 __isl_take isl_set *domain, __isl_take isl_val *inc)
2408 isl_map *previous_to_this;
2410 if (isl_val_is_pos(inc))
2411 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2412 else
2413 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2415 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2417 cond = isl_set_complement(cond);
2418 cond = isl_set_apply(cond, previous_to_this);
2419 cond = isl_set_complement(cond);
2421 isl_val_free(inc);
2423 return cond;
2426 /* Construct a domain of the form
2428 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2430 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2431 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2433 isl_aff *aff;
2434 isl_space *dim;
2435 isl_set *set;
2437 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2438 dim = isl_pw_aff_get_domain_space(init);
2439 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2440 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2441 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2443 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2444 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2445 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2446 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2448 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2450 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2452 return isl_set_params(set);
2455 /* Assuming "cond" represents a bound on a loop where the loop
2456 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2457 * is possible.
2459 * Under the given assumptions, wrapping is only possible if "cond" allows
2460 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2461 * increasing iterator and 0 in case of a decreasing iterator.
2463 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2464 __isl_keep isl_val *inc)
2466 bool cw;
2467 isl_ctx *ctx;
2468 isl_val *limit;
2469 isl_set *test;
2471 test = isl_set_copy(cond);
2473 ctx = isl_set_get_ctx(test);
2474 if (isl_val_is_neg(inc))
2475 limit = isl_val_zero(ctx);
2476 else {
2477 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2478 limit = isl_val_2exp(limit);
2479 limit = isl_val_sub_ui(limit, 1);
2482 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2483 cw = !isl_set_is_empty(test);
2484 isl_set_free(test);
2486 return cw;
2489 /* Given a one-dimensional space, construct the following mapping on this
2490 * space
2492 * { [v] -> [v mod 2^width] }
2494 * where width is the number of bits used to represent the values
2495 * of the unsigned variable "iv".
2497 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
2498 ValueDecl *iv)
2500 isl_ctx *ctx;
2501 isl_val *mod;
2502 isl_aff *aff;
2503 isl_map *map;
2505 ctx = isl_space_get_ctx(dim);
2506 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2507 mod = isl_val_2exp(mod);
2509 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2510 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2511 aff = isl_aff_mod_val(aff, mod);
2513 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2514 map = isl_map_reverse(map);
2517 /* Project out the parameter "id" from "set".
2519 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2520 __isl_keep isl_id *id)
2522 int pos;
2524 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2525 if (pos >= 0)
2526 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2528 return set;
2531 /* Compute the set of parameters for which "set1" is a subset of "set2".
2533 * set1 is a subset of set2 if
2535 * forall i in set1 : i in set2
2537 * or
2539 * not exists i in set1 and i not in set2
2541 * i.e.,
2543 * not exists i in set1 \ set2
2545 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2546 __isl_take isl_set *set2)
2548 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2551 /* Compute the set of parameter values for which "cond" holds
2552 * on the next iteration for each element of "dom".
2554 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2555 * and then compute the set of parameters for which the result is a subset
2556 * of "cond".
2558 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2559 __isl_take isl_set *dom, __isl_take isl_val *inc)
2561 isl_space *space;
2562 isl_aff *aff;
2563 isl_map *next;
2565 space = isl_set_get_space(dom);
2566 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2567 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2568 aff = isl_aff_add_constant_val(aff, inc);
2569 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2571 dom = isl_set_apply(dom, next);
2573 return enforce_subset(dom, cond);
2576 /* Does "id" refer to a nested access?
2578 static bool is_nested_parameter(__isl_keep isl_id *id)
2580 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2583 /* Does parameter "pos" of "space" refer to a nested access?
2585 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2587 bool nested;
2588 isl_id *id;
2590 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2591 nested = is_nested_parameter(id);
2592 isl_id_free(id);
2594 return nested;
2597 /* Does "space" involve any parameters that refer to nested
2598 * accesses, i.e., parameters with no name?
2600 static bool has_nested(__isl_keep isl_space *space)
2602 int nparam;
2604 nparam = isl_space_dim(space, isl_dim_param);
2605 for (int i = 0; i < nparam; ++i)
2606 if (is_nested_parameter(space, i))
2607 return true;
2609 return false;
2612 /* Does "pa" involve any parameters that refer to nested
2613 * accesses, i.e., parameters with no name?
2615 static bool has_nested(__isl_keep isl_pw_aff *pa)
2617 isl_space *space;
2618 bool nested;
2620 space = isl_pw_aff_get_space(pa);
2621 nested = has_nested(space);
2622 isl_space_free(space);
2624 return nested;
2627 /* Construct a pet_scop for a for statement.
2628 * The for loop is required to be of the form
2630 * for (i = init; condition; ++i)
2632 * or
2634 * for (i = init; condition; --i)
2636 * The initialization of the for loop should either be an assignment
2637 * to an integer variable, or a declaration of such a variable with
2638 * initialization.
2640 * The condition is allowed to contain nested accesses, provided
2641 * they are not being written to inside the body of the loop.
2642 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2643 * essentially treated as a while loop, with iteration domain
2644 * { [i] : i >= init }.
2646 * We extract a pet_scop for the body and then embed it in a loop with
2647 * iteration domain and schedule
2649 * { [i] : i >= init and condition' }
2650 * { [i] -> [i] }
2652 * or
2654 * { [i] : i <= init and condition' }
2655 * { [i] -> [-i] }
2657 * Where condition' is equal to condition if the latter is
2658 * a simple upper [lower] bound and a condition that is extended
2659 * to apply to all previous iterations otherwise.
2661 * If the condition is non-affine, then we drop the condition from the
2662 * iteration domain and instead create a separate statement
2663 * for evaluating the condition. The body is then filtered to depend
2664 * on the result of the condition evaluating to true on all iterations
2665 * up to the current iteration, while the evaluation the condition itself
2666 * is filtered to depend on the result of the condition evaluating to true
2667 * on all previous iterations.
2668 * The context of the scop representing the body is dropped
2669 * because we don't know how many times the body will be executed,
2670 * if at all.
2672 * If the stride of the loop is not 1, then "i >= init" is replaced by
2674 * (exists a: i = init + stride * a and a >= 0)
2676 * If the loop iterator i is unsigned, then wrapping may occur.
2677 * During the computation, we work with a virtual iterator that
2678 * does not wrap. However, the condition in the code applies
2679 * to the wrapped value, so we need to change condition(i)
2680 * into condition([i % 2^width]).
2681 * After computing the virtual domain and schedule, we apply
2682 * the function { [v] -> [v % 2^width] } to the domain and the domain
2683 * of the schedule. In order not to lose any information, we also
2684 * need to intersect the domain of the schedule with the virtual domain
2685 * first, since some iterations in the wrapped domain may be scheduled
2686 * several times, typically an infinite number of times.
2687 * Note that there may be no need to perform this final wrapping
2688 * if the loop condition (after wrapping) satisfies certain conditions.
2689 * However, the is_simple_bound condition is not enough since it doesn't
2690 * check if there even is an upper bound.
2692 * If the loop condition is non-affine, then we keep the virtual
2693 * iterator in the iteration domain and instead replace all accesses
2694 * to the original iterator by the wrapping of the virtual iterator.
2696 * Wrapping on unsigned iterators can be avoided entirely if
2697 * loop condition is simple, the loop iterator is incremented
2698 * [decremented] by one and the last value before wrapping cannot
2699 * possibly satisfy the loop condition.
2701 * Before extracting a pet_scop from the body we remove all
2702 * assignments in assigned_value to variables that are assigned
2703 * somewhere in the body of the loop.
2705 * Valid parameters for a for loop are those for which the initial
2706 * value itself, the increment on each domain iteration and
2707 * the condition on both the initial value and
2708 * the result of incrementing the iterator for each iteration of the domain
2709 * can be evaluated.
2710 * If the loop condition is non-affine, then we only consider validity
2711 * of the initial value.
2713 * If the body contains any break, then we keep track of it in "skip"
2714 * (if the skip condition is affine) or it is handled in scop_add_break
2715 * (if the skip condition is not affine).
2716 * Note that the affine break condition needs to be considered with
2717 * respect to previous iterations in the virtual domain (if any)
2718 * and that the domain needs to be kept virtual if there is a non-affine
2719 * break condition.
2721 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2723 BinaryOperator *ass;
2724 Decl *decl;
2725 Stmt *init;
2726 Expr *lhs, *rhs;
2727 ValueDecl *iv;
2728 isl_space *space;
2729 isl_set *domain;
2730 isl_map *sched;
2731 isl_set *cond = NULL;
2732 isl_set *skip = NULL;
2733 isl_id *id;
2734 struct pet_scop *scop, *scop_cond = NULL;
2735 assigned_value_cache cache(assigned_value);
2736 isl_val *inc;
2737 bool is_one;
2738 bool is_unsigned;
2739 bool is_simple;
2740 bool is_virtual;
2741 bool keep_virtual = false;
2742 bool has_affine_break;
2743 bool has_var_break;
2744 isl_map *wrap = NULL;
2745 isl_pw_aff *pa, *pa_inc, *init_val;
2746 isl_set *valid_init;
2747 isl_set *valid_cond;
2748 isl_set *valid_cond_init;
2749 isl_set *valid_cond_next;
2750 isl_set *valid_inc;
2751 isl_map *test_access = NULL, *break_access = NULL;
2752 int stmt_id;
2754 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2755 return extract_infinite_for(stmt);
2757 init = stmt->getInit();
2758 if (!init) {
2759 unsupported(stmt);
2760 return NULL;
2762 if ((ass = initialization_assignment(init)) != NULL) {
2763 iv = extract_induction_variable(ass);
2764 if (!iv)
2765 return NULL;
2766 lhs = ass->getLHS();
2767 rhs = ass->getRHS();
2768 } else if ((decl = initialization_declaration(init)) != NULL) {
2769 VarDecl *var = extract_induction_variable(init, decl);
2770 if (!var)
2771 return NULL;
2772 iv = var;
2773 rhs = var->getInit();
2774 lhs = create_DeclRefExpr(var);
2775 } else {
2776 unsupported(stmt->getInit());
2777 return NULL;
2780 pa_inc = extract_increment(stmt, iv);
2781 if (!pa_inc)
2782 return NULL;
2784 inc = NULL;
2785 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
2786 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
2787 isl_pw_aff_free(pa_inc);
2788 unsupported(stmt->getInc());
2789 isl_val_free(inc);
2790 return NULL;
2792 valid_inc = isl_pw_aff_domain(pa_inc);
2794 is_unsigned = iv->getType()->isUnsignedIntegerType();
2796 assigned_value.erase(iv);
2797 clear_assignments clear(assigned_value);
2798 clear.TraverseStmt(stmt->getBody());
2800 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2802 pa = try_extract_nested_condition(stmt->getCond());
2803 if (allow_nested && (!pa || has_nested(pa)))
2804 stmt_id = n_stmt++;
2806 scop = extract(stmt->getBody());
2808 has_affine_break = scop &&
2809 pet_scop_has_affine_skip(scop, pet_skip_later);
2810 if (has_affine_break) {
2811 skip = pet_scop_get_skip(scop, pet_skip_later);
2812 skip = isl_set_fix_si(skip, isl_dim_set, 0, 1);
2813 skip = isl_set_params(skip);
2815 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
2816 if (has_var_break) {
2817 break_access = pet_scop_get_skip_map(scop, pet_skip_later);
2818 keep_virtual = true;
2821 if (pa && !is_nested_allowed(pa, scop)) {
2822 isl_pw_aff_free(pa);
2823 pa = NULL;
2826 if (!allow_nested && !pa)
2827 pa = try_extract_affine_condition(stmt->getCond());
2828 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2829 cond = isl_pw_aff_non_zero_set(pa);
2830 if (allow_nested && !cond) {
2831 int save_n_stmt = n_stmt;
2832 test_access = create_test_access(ctx, n_test++);
2833 n_stmt = stmt_id;
2834 scop_cond = extract_non_affine_condition(stmt->getCond(),
2835 isl_map_copy(test_access));
2836 n_stmt = save_n_stmt;
2837 scop_cond = scop_add_array(scop_cond, test_access, ast_context);
2838 scop_cond = pet_scop_prefix(scop_cond, 0);
2839 scop = pet_scop_reset_context(scop);
2840 scop = pet_scop_prefix(scop, 1);
2841 keep_virtual = true;
2842 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2845 cond = embed(cond, isl_id_copy(id));
2846 skip = embed(skip, isl_id_copy(id));
2847 valid_cond = isl_set_coalesce(valid_cond);
2848 valid_cond = embed(valid_cond, isl_id_copy(id));
2849 valid_inc = embed(valid_inc, isl_id_copy(id));
2850 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
2851 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2853 init_val = extract_affine(rhs);
2854 valid_cond_init = enforce_subset(
2855 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
2856 isl_set_copy(valid_cond));
2857 if (is_one && !is_virtual) {
2858 isl_pw_aff_free(init_val);
2859 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
2860 lhs, rhs, init);
2861 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2862 valid_init = set_project_out_by_id(valid_init, id);
2863 domain = isl_pw_aff_non_zero_set(pa);
2864 } else {
2865 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2866 domain = strided_domain(isl_id_copy(id), init_val,
2867 isl_val_copy(inc));
2870 domain = embed(domain, isl_id_copy(id));
2871 if (is_virtual) {
2872 isl_map *rev_wrap;
2873 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2874 rev_wrap = isl_map_reverse(isl_map_copy(wrap));
2875 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2876 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
2877 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2878 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2880 is_simple = is_simple_bound(cond, inc);
2881 if (!is_simple) {
2882 cond = isl_set_gist(cond, isl_set_copy(domain));
2883 is_simple = is_simple_bound(cond, inc);
2885 if (!is_simple)
2886 cond = valid_for_each_iteration(cond,
2887 isl_set_copy(domain), isl_val_copy(inc));
2888 domain = isl_set_intersect(domain, cond);
2889 if (has_affine_break) {
2890 skip = isl_set_intersect(skip , isl_set_copy(domain));
2891 skip = after(skip, isl_val_sgn(inc));
2892 domain = isl_set_subtract(domain, skip);
2894 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2895 space = isl_space_from_domain(isl_set_get_space(domain));
2896 space = isl_space_add_dims(space, isl_dim_out, 1);
2897 sched = isl_map_universe(space);
2898 if (isl_val_is_pos(inc))
2899 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2900 else
2901 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2903 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
2904 isl_val_copy(inc));
2905 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2907 if (is_virtual && !keep_virtual) {
2908 wrap = isl_map_set_dim_id(wrap,
2909 isl_dim_out, 0, isl_id_copy(id));
2910 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2911 domain = isl_set_apply(domain, isl_map_copy(wrap));
2912 sched = isl_map_apply_domain(sched, wrap);
2914 if (!(is_virtual && keep_virtual)) {
2915 space = isl_set_get_space(domain);
2916 wrap = isl_map_identity(isl_space_map_from_set(space));
2919 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
2920 isl_map_copy(sched), isl_map_copy(wrap), isl_id_copy(id));
2921 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
2922 scop = resolve_nested(scop);
2923 if (has_var_break)
2924 scop = scop_add_break(scop, break_access, isl_set_copy(domain),
2925 isl_val_sgn(inc));
2926 if (test_access) {
2927 scop = scop_add_while(scop_cond, scop, test_access, domain,
2928 isl_val_sgn(inc));
2929 isl_set_free(valid_inc);
2930 } else {
2931 scop = pet_scop_restrict_context(scop, valid_inc);
2932 scop = pet_scop_restrict_context(scop, valid_cond_next);
2933 scop = pet_scop_restrict_context(scop, valid_cond_init);
2934 isl_set_free(domain);
2936 clear_assignment(assigned_value, iv);
2938 isl_val_free(inc);
2940 scop = pet_scop_restrict_context(scop, valid_init);
2942 return scop;
2945 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
2947 return extract(stmt->children(), true, skip_declarations);
2950 /* Does parameter "pos" of "map" refer to a nested access?
2952 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2954 bool nested;
2955 isl_id *id;
2957 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2958 nested = is_nested_parameter(id);
2959 isl_id_free(id);
2961 return nested;
2964 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2966 static int n_nested_parameter(__isl_keep isl_space *space)
2968 int n = 0;
2969 int nparam;
2971 nparam = isl_space_dim(space, isl_dim_param);
2972 for (int i = 0; i < nparam; ++i)
2973 if (is_nested_parameter(space, i))
2974 ++n;
2976 return n;
2979 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2981 static int n_nested_parameter(__isl_keep isl_map *map)
2983 isl_space *space;
2984 int n;
2986 space = isl_map_get_space(map);
2987 n = n_nested_parameter(space);
2988 isl_space_free(space);
2990 return n;
2993 /* For each nested access parameter in "space",
2994 * construct a corresponding pet_expr, place it in args and
2995 * record its position in "param2pos".
2996 * "n_arg" is the number of elements that are already in args.
2997 * The position recorded in "param2pos" takes this number into account.
2998 * If the pet_expr corresponding to a parameter is identical to
2999 * the pet_expr corresponding to an earlier parameter, then these two
3000 * parameters are made to refer to the same element in args.
3002 * Return the final number of elements in args or -1 if an error has occurred.
3004 int PetScan::extract_nested(__isl_keep isl_space *space,
3005 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
3007 int nparam;
3009 nparam = isl_space_dim(space, isl_dim_param);
3010 for (int i = 0; i < nparam; ++i) {
3011 int j;
3012 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3013 Expr *nested;
3015 if (!is_nested_parameter(id)) {
3016 isl_id_free(id);
3017 continue;
3020 nested = (Expr *) isl_id_get_user(id);
3021 args[n_arg] = extract_expr(nested);
3022 if (!args[n_arg])
3023 return -1;
3025 for (j = 0; j < n_arg; ++j)
3026 if (pet_expr_is_equal(args[j], args[n_arg]))
3027 break;
3029 if (j < n_arg) {
3030 pet_expr_free(args[n_arg]);
3031 args[n_arg] = NULL;
3032 param2pos[i] = j;
3033 } else
3034 param2pos[i] = n_arg++;
3036 isl_id_free(id);
3039 return n_arg;
3042 /* For each nested access parameter in the access relations in "expr",
3043 * construct a corresponding pet_expr, place it in expr->args and
3044 * record its position in "param2pos".
3045 * n is the number of nested access parameters.
3047 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
3048 std::map<int,int> &param2pos)
3050 isl_space *space;
3052 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
3053 expr->n_arg = n;
3054 if (!expr->args)
3055 goto error;
3057 space = isl_map_get_space(expr->acc.access);
3058 n = extract_nested(space, 0, expr->args, param2pos);
3059 isl_space_free(space);
3061 if (n < 0)
3062 goto error;
3064 expr->n_arg = n;
3065 return expr;
3066 error:
3067 pet_expr_free(expr);
3068 return NULL;
3071 /* Look for parameters in any access relation in "expr" that
3072 * refer to nested accesses. In particular, these are
3073 * parameters with no name.
3075 * If there are any such parameters, then the domain of the access
3076 * relation, which is still [] at this point, is replaced by
3077 * [[] -> [t_1,...,t_n]], with n the number of these parameters
3078 * (after identifying identical nested accesses).
3079 * The parameters are then equated to the corresponding t dimensions
3080 * and subsequently projected out.
3081 * param2pos maps the position of the parameter to the position
3082 * of the corresponding t dimension.
3084 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
3086 int n;
3087 int nparam;
3088 int n_in;
3089 isl_space *dim;
3090 isl_map *map;
3091 std::map<int,int> param2pos;
3093 if (!expr)
3094 return expr;
3096 for (int i = 0; i < expr->n_arg; ++i) {
3097 expr->args[i] = resolve_nested(expr->args[i]);
3098 if (!expr->args[i]) {
3099 pet_expr_free(expr);
3100 return NULL;
3104 if (expr->type != pet_expr_access)
3105 return expr;
3107 n = n_nested_parameter(expr->acc.access);
3108 if (n == 0)
3109 return expr;
3111 expr = extract_nested(expr, n, param2pos);
3112 if (!expr)
3113 return NULL;
3115 n = expr->n_arg;
3116 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
3117 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
3118 dim = isl_map_get_space(expr->acc.access);
3119 dim = isl_space_domain(dim);
3120 dim = isl_space_from_domain(dim);
3121 dim = isl_space_add_dims(dim, isl_dim_out, n);
3122 map = isl_map_universe(dim);
3123 map = isl_map_domain_map(map);
3124 map = isl_map_reverse(map);
3125 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
3127 for (int i = nparam - 1; i >= 0; --i) {
3128 isl_id *id = isl_map_get_dim_id(expr->acc.access,
3129 isl_dim_param, i);
3130 if (!is_nested_parameter(id)) {
3131 isl_id_free(id);
3132 continue;
3135 expr->acc.access = isl_map_equate(expr->acc.access,
3136 isl_dim_param, i, isl_dim_in,
3137 n_in + param2pos[i]);
3138 expr->acc.access = isl_map_project_out(expr->acc.access,
3139 isl_dim_param, i, 1);
3141 isl_id_free(id);
3144 return expr;
3145 error:
3146 pet_expr_free(expr);
3147 return NULL;
3150 /* Return the file offset of the expansion location of "Loc".
3152 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3154 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3157 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3159 /* Return a SourceLocation for the location after the first semicolon
3160 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3161 * call it and also skip trailing spaces and newline.
3163 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3164 const LangOptions &LO)
3166 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3169 #else
3171 /* Return a SourceLocation for the location after the first semicolon
3172 * after "loc". If Lexer::findLocationAfterToken is not available,
3173 * we look in the underlying character data for the first semicolon.
3175 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3176 const LangOptions &LO)
3178 const char *semi;
3179 const char *s = SM.getCharacterData(loc);
3181 semi = strchr(s, ';');
3182 if (!semi)
3183 return SourceLocation();
3184 return loc.getFileLocWithOffset(semi + 1 - s);
3187 #endif
3189 /* If the token at "loc" is the first token on the line, then return
3190 * a location referring to the start of the line.
3191 * Otherwise, return "loc".
3193 * This function is used to extend a scop to the start of the line
3194 * if the first token of the scop is also the first token on the line.
3196 * We look for the first token on the line. If its location is equal to "loc",
3197 * then the latter is the location of the first token on the line.
3199 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3200 SourceManager &SM, const LangOptions &LO)
3202 std::pair<FileID, unsigned> file_offset_pair;
3203 llvm::StringRef file;
3204 const char *pos;
3205 Token tok;
3206 SourceLocation token_loc, line_loc;
3207 int col;
3209 loc = SM.getExpansionLoc(loc);
3210 col = SM.getExpansionColumnNumber(loc);
3211 line_loc = loc.getLocWithOffset(1 - col);
3212 file_offset_pair = SM.getDecomposedLoc(line_loc);
3213 file = SM.getBufferData(file_offset_pair.first, NULL);
3214 pos = file.data() + file_offset_pair.second;
3216 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3217 file.begin(), pos, file.end());
3218 lexer.LexFromRawLexer(tok);
3219 token_loc = tok.getLocation();
3221 if (token_loc == loc)
3222 return line_loc;
3223 else
3224 return loc;
3227 /* Convert a top-level pet_expr to a pet_scop with one statement.
3228 * This mainly involves resolving nested expression parameters
3229 * and setting the name of the iteration space.
3230 * The name is given by "label" if it is non-NULL. Otherwise,
3231 * it is of the form S_<n_stmt>.
3232 * start and end of the pet_scop are derived from those of "stmt".
3234 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
3235 __isl_take isl_id *label)
3237 struct pet_stmt *ps;
3238 struct pet_scop *scop;
3239 SourceLocation loc = stmt->getLocStart();
3240 SourceManager &SM = PP.getSourceManager();
3241 const LangOptions &LO = PP.getLangOpts();
3242 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3243 unsigned start, end;
3245 expr = resolve_nested(expr);
3246 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
3247 scop = pet_scop_from_pet_stmt(ctx, ps);
3249 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3250 start = getExpansionOffset(SM, loc);
3251 loc = stmt->getLocEnd();
3252 loc = location_after_semi(loc, SM, LO);
3253 end = getExpansionOffset(SM, loc);
3255 scop = pet_scop_update_start_end(scop, start, end);
3256 return scop;
3259 /* Check if we can extract an affine expression from "expr".
3260 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3261 * We turn on autodetection so that we won't generate any warnings
3262 * and turn off nesting, so that we won't accept any non-affine constructs.
3264 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3266 isl_pw_aff *pwaff;
3267 int save_autodetect = options->autodetect;
3268 bool save_nesting = nesting_enabled;
3270 options->autodetect = 1;
3271 nesting_enabled = false;
3273 pwaff = extract_affine(expr);
3275 options->autodetect = save_autodetect;
3276 nesting_enabled = save_nesting;
3278 return pwaff;
3281 /* Check whether "expr" is an affine expression.
3283 bool PetScan::is_affine(Expr *expr)
3285 isl_pw_aff *pwaff;
3287 pwaff = try_extract_affine(expr);
3288 isl_pw_aff_free(pwaff);
3290 return pwaff != NULL;
3293 /* Check if we can extract an affine constraint from "expr".
3294 * Return the constraint as an isl_set if we can and NULL otherwise.
3295 * We turn on autodetection so that we won't generate any warnings
3296 * and turn off nesting, so that we won't accept any non-affine constructs.
3298 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3300 isl_pw_aff *cond;
3301 int save_autodetect = options->autodetect;
3302 bool save_nesting = nesting_enabled;
3304 options->autodetect = 1;
3305 nesting_enabled = false;
3307 cond = extract_condition(expr);
3309 options->autodetect = save_autodetect;
3310 nesting_enabled = save_nesting;
3312 return cond;
3315 /* Check whether "expr" is an affine constraint.
3317 bool PetScan::is_affine_condition(Expr *expr)
3319 isl_pw_aff *cond;
3321 cond = try_extract_affine_condition(expr);
3322 isl_pw_aff_free(cond);
3324 return cond != NULL;
3327 /* Check if we can extract a condition from "expr".
3328 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3329 * If allow_nested is set, then the condition may involve parameters
3330 * corresponding to nested accesses.
3331 * We turn on autodetection so that we won't generate any warnings.
3333 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3335 isl_pw_aff *cond;
3336 int save_autodetect = options->autodetect;
3337 bool save_nesting = nesting_enabled;
3339 options->autodetect = 1;
3340 nesting_enabled = allow_nested;
3341 cond = extract_condition(expr);
3343 options->autodetect = save_autodetect;
3344 nesting_enabled = save_nesting;
3346 return cond;
3349 /* If the top-level expression of "stmt" is an assignment, then
3350 * return that assignment as a BinaryOperator.
3351 * Otherwise return NULL.
3353 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3355 BinaryOperator *ass;
3357 if (!stmt)
3358 return NULL;
3359 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3360 return NULL;
3362 ass = cast<BinaryOperator>(stmt);
3363 if(ass->getOpcode() != BO_Assign)
3364 return NULL;
3366 return ass;
3369 /* Check if the given if statement is a conditional assignement
3370 * with a non-affine condition. If so, construct a pet_scop
3371 * corresponding to this conditional assignment. Otherwise return NULL.
3373 * In particular we check if "stmt" is of the form
3375 * if (condition)
3376 * a = f(...);
3377 * else
3378 * a = g(...);
3380 * where a is some array or scalar access.
3381 * The constructed pet_scop then corresponds to the expression
3383 * a = condition ? f(...) : g(...)
3385 * All access relations in f(...) are intersected with condition
3386 * while all access relation in g(...) are intersected with the complement.
3388 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3390 BinaryOperator *ass_then, *ass_else;
3391 isl_map *write_then, *write_else;
3392 isl_set *cond, *comp;
3393 isl_map *map;
3394 isl_pw_aff *pa;
3395 int equal;
3396 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3397 bool save_nesting = nesting_enabled;
3399 if (!options->detect_conditional_assignment)
3400 return NULL;
3402 ass_then = top_assignment_or_null(stmt->getThen());
3403 ass_else = top_assignment_or_null(stmt->getElse());
3405 if (!ass_then || !ass_else)
3406 return NULL;
3408 if (is_affine_condition(stmt->getCond()))
3409 return NULL;
3411 write_then = extract_access(ass_then->getLHS());
3412 write_else = extract_access(ass_else->getLHS());
3414 equal = isl_map_is_equal(write_then, write_else);
3415 isl_map_free(write_else);
3416 if (equal < 0 || !equal) {
3417 isl_map_free(write_then);
3418 return NULL;
3421 nesting_enabled = allow_nested;
3422 pa = extract_condition(stmt->getCond());
3423 nesting_enabled = save_nesting;
3424 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3425 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3426 map = isl_map_from_range(isl_set_from_pw_aff(pa));
3428 pe_cond = pet_expr_from_access(map);
3430 pe_then = extract_expr(ass_then->getRHS());
3431 pe_then = pet_expr_restrict(pe_then, cond);
3432 pe_else = extract_expr(ass_else->getRHS());
3433 pe_else = pet_expr_restrict(pe_else, comp);
3435 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
3436 pe_write = pet_expr_from_access(write_then);
3437 if (pe_write) {
3438 pe_write->acc.write = 1;
3439 pe_write->acc.read = 0;
3441 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
3442 return extract(stmt, pe);
3445 /* Create a pet_scop with a single statement evaluating "cond"
3446 * and writing the result to a virtual scalar, as expressed by
3447 * "access".
3449 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
3450 __isl_take isl_map *access)
3452 struct pet_expr *expr, *write;
3453 struct pet_stmt *ps;
3454 struct pet_scop *scop;
3455 SourceLocation loc = cond->getLocStart();
3456 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3458 write = pet_expr_from_access(access);
3459 if (write) {
3460 write->acc.write = 1;
3461 write->acc.read = 0;
3463 expr = extract_expr(cond);
3464 expr = resolve_nested(expr);
3465 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
3466 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
3467 scop = pet_scop_from_pet_stmt(ctx, ps);
3468 scop = resolve_nested(scop);
3470 return scop;
3473 extern "C" {
3474 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
3475 void *user);
3478 /* Apply the map pointed to by "user" to the domain of the access
3479 * relation, thereby embedding it in the range of the map.
3480 * The domain of both relations is the zero-dimensional domain.
3482 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
3484 isl_map *map = (isl_map *) user;
3486 return isl_map_apply_domain(access, isl_map_copy(map));
3489 /* Apply "map" to all access relations in "expr".
3491 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
3493 return pet_expr_foreach_access(expr, &embed_access, map);
3496 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3498 static int n_nested_parameter(__isl_keep isl_set *set)
3500 isl_space *space;
3501 int n;
3503 space = isl_set_get_space(set);
3504 n = n_nested_parameter(space);
3505 isl_space_free(space);
3507 return n;
3510 /* Remove all parameters from "map" that refer to nested accesses.
3512 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
3514 int nparam;
3515 isl_space *space;
3517 space = isl_map_get_space(map);
3518 nparam = isl_space_dim(space, isl_dim_param);
3519 for (int i = nparam - 1; i >= 0; --i)
3520 if (is_nested_parameter(space, i))
3521 map = isl_map_project_out(map, isl_dim_param, i, 1);
3522 isl_space_free(space);
3524 return map;
3527 extern "C" {
3528 static __isl_give isl_map *access_remove_nested_parameters(
3529 __isl_take isl_map *access, void *user);
3532 static __isl_give isl_map *access_remove_nested_parameters(
3533 __isl_take isl_map *access, void *user)
3535 return remove_nested_parameters(access);
3538 /* Remove all nested access parameters from the schedule and all
3539 * accesses of "stmt".
3540 * There is no need to remove them from the domain as these parameters
3541 * have already been removed from the domain when this function is called.
3543 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
3545 if (!stmt)
3546 return NULL;
3547 stmt->schedule = remove_nested_parameters(stmt->schedule);
3548 stmt->body = pet_expr_foreach_access(stmt->body,
3549 &access_remove_nested_parameters, NULL);
3550 if (!stmt->schedule || !stmt->body)
3551 goto error;
3552 for (int i = 0; i < stmt->n_arg; ++i) {
3553 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
3554 &access_remove_nested_parameters, NULL);
3555 if (!stmt->args[i])
3556 goto error;
3559 return stmt;
3560 error:
3561 pet_stmt_free(stmt);
3562 return NULL;
3565 /* For each nested access parameter in the domain of "stmt",
3566 * construct a corresponding pet_expr, place it before the original
3567 * elements in stmt->args and record its position in "param2pos".
3568 * n is the number of nested access parameters.
3570 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3571 std::map<int,int> &param2pos)
3573 int i;
3574 isl_space *space;
3575 int n_arg;
3576 struct pet_expr **args;
3578 n_arg = stmt->n_arg;
3579 args = isl_calloc_array(ctx, struct pet_expr *, n + n_arg);
3580 if (!args)
3581 goto error;
3583 space = isl_set_get_space(stmt->domain);
3584 n_arg = extract_nested(space, 0, args, param2pos);
3585 isl_space_free(space);
3587 if (n_arg < 0)
3588 goto error;
3590 for (i = 0; i < stmt->n_arg; ++i)
3591 args[n_arg + i] = stmt->args[i];
3592 free(stmt->args);
3593 stmt->args = args;
3594 stmt->n_arg += n_arg;
3596 return stmt;
3597 error:
3598 if (args) {
3599 for (i = 0; i < n; ++i)
3600 pet_expr_free(args[i]);
3601 free(args);
3603 pet_stmt_free(stmt);
3604 return NULL;
3607 /* Check whether any of the arguments i of "stmt" starting at position "n"
3608 * is equal to one of the first "n" arguments j.
3609 * If so, combine the constraints on arguments i and j and remove
3610 * argument i.
3612 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3614 int i, j;
3615 isl_map *map;
3617 if (!stmt)
3618 return NULL;
3619 if (n == 0)
3620 return stmt;
3621 if (n == stmt->n_arg)
3622 return stmt;
3624 map = isl_set_unwrap(stmt->domain);
3626 for (i = stmt->n_arg - 1; i >= n; --i) {
3627 for (j = 0; j < n; ++j)
3628 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3629 break;
3630 if (j >= n)
3631 continue;
3633 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3634 map = isl_map_project_out(map, isl_dim_out, i, 1);
3636 pet_expr_free(stmt->args[i]);
3637 for (j = i; j + 1 < stmt->n_arg; ++j)
3638 stmt->args[j] = stmt->args[j + 1];
3639 stmt->n_arg--;
3642 stmt->domain = isl_map_wrap(map);
3643 if (!stmt->domain)
3644 goto error;
3645 return stmt;
3646 error:
3647 pet_stmt_free(stmt);
3648 return NULL;
3651 /* Look for parameters in the iteration domain of "stmt" that
3652 * refer to nested accesses. In particular, these are
3653 * parameters with no name.
3655 * If there are any such parameters, then as many extra variables
3656 * (after identifying identical nested accesses) are inserted in the
3657 * range of the map wrapped inside the domain, before the original variables.
3658 * If the original domain is not a wrapped map, then a new wrapped
3659 * map is created with zero output dimensions.
3660 * The parameters are then equated to the corresponding output dimensions
3661 * and subsequently projected out, from the iteration domain,
3662 * the schedule and the access relations.
3663 * For each of the output dimensions, a corresponding argument
3664 * expression is inserted. Initially they are created with
3665 * a zero-dimensional domain, so they have to be embedded
3666 * in the current iteration domain.
3667 * param2pos maps the position of the parameter to the position
3668 * of the corresponding output dimension in the wrapped map.
3670 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3672 int n;
3673 int nparam;
3674 unsigned n_arg;
3675 isl_map *map;
3676 std::map<int,int> param2pos;
3678 if (!stmt)
3679 return NULL;
3681 n = n_nested_parameter(stmt->domain);
3682 if (n == 0)
3683 return stmt;
3685 n_arg = stmt->n_arg;
3686 stmt = extract_nested(stmt, n, param2pos);
3687 if (!stmt)
3688 return NULL;
3690 n = stmt->n_arg - n_arg;
3691 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3692 if (isl_set_is_wrapping(stmt->domain))
3693 map = isl_set_unwrap(stmt->domain);
3694 else
3695 map = isl_map_from_domain(stmt->domain);
3696 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3698 for (int i = nparam - 1; i >= 0; --i) {
3699 isl_id *id;
3701 if (!is_nested_parameter(map, i))
3702 continue;
3704 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
3705 isl_dim_out);
3706 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3707 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3708 param2pos[i]);
3709 map = isl_map_project_out(map, isl_dim_param, i, 1);
3712 stmt->domain = isl_map_wrap(map);
3714 map = isl_set_unwrap(isl_set_copy(stmt->domain));
3715 map = isl_map_from_range(isl_map_domain(map));
3716 for (int pos = 0; pos < n; ++pos)
3717 stmt->args[pos] = embed(stmt->args[pos], map);
3718 isl_map_free(map);
3720 stmt = remove_nested_parameters(stmt);
3721 stmt = remove_duplicate_arguments(stmt, n);
3723 return stmt;
3724 error:
3725 pet_stmt_free(stmt);
3726 return NULL;
3729 /* For each statement in "scop", move the parameters that correspond
3730 * to nested access into the ranges of the domains and create
3731 * corresponding argument expressions.
3733 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3735 if (!scop)
3736 return NULL;
3738 for (int i = 0; i < scop->n_stmt; ++i) {
3739 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3740 if (!scop->stmts[i])
3741 goto error;
3744 return scop;
3745 error:
3746 pet_scop_free(scop);
3747 return NULL;
3750 /* Given an access expression "expr", is the variable accessed by
3751 * "expr" assigned anywhere inside "scop"?
3753 static bool is_assigned(pet_expr *expr, pet_scop *scop)
3755 bool assigned = false;
3756 isl_id *id;
3758 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
3759 assigned = pet_scop_writes(scop, id);
3760 isl_id_free(id);
3762 return assigned;
3765 /* Are all nested access parameters in "pa" allowed given "scop".
3766 * In particular, is none of them written by anywhere inside "scop".
3768 * If "scop" has any skip conditions, then no nested access parameters
3769 * are allowed. In particular, if there is any nested access in a guard
3770 * for a piece of code containing a "continue", then we want to introduce
3771 * a separate statement for evaluating this guard so that we can express
3772 * that the result is false for all previous iterations.
3774 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3776 int nparam;
3778 if (!scop)
3779 return true;
3781 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3782 for (int i = 0; i < nparam; ++i) {
3783 Expr *nested;
3784 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3785 pet_expr *expr;
3786 bool allowed;
3788 if (!is_nested_parameter(id)) {
3789 isl_id_free(id);
3790 continue;
3793 if (pet_scop_has_skip(scop, pet_skip_now)) {
3794 isl_id_free(id);
3795 return false;
3798 nested = (Expr *) isl_id_get_user(id);
3799 expr = extract_expr(nested);
3800 allowed = expr && expr->type == pet_expr_access &&
3801 !is_assigned(expr, scop);
3803 pet_expr_free(expr);
3804 isl_id_free(id);
3806 if (!allowed)
3807 return false;
3810 return true;
3813 /* Do we need to construct a skip condition of the given type
3814 * on an if statement, given that the if condition is non-affine?
3816 * pet_scop_filter_skip can only handle the case where the if condition
3817 * holds (the then branch) and the skip condition is universal.
3818 * In any other case, we need to construct a new skip condition.
3820 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3821 bool have_else, enum pet_skip type)
3823 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
3824 return true;
3825 if (scop_then && pet_scop_has_skip(scop_then, type) &&
3826 !pet_scop_has_universal_skip(scop_then, type))
3827 return true;
3828 return false;
3831 /* Do we need to construct a skip condition of the given type
3832 * on an if statement, given that the if condition is affine?
3834 * There is no need to construct a new skip condition if all
3835 * the skip conditions are affine.
3837 static bool need_skip_aff(struct pet_scop *scop_then,
3838 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
3840 if (scop_then && pet_scop_has_var_skip(scop_then, type))
3841 return true;
3842 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
3843 return true;
3844 return false;
3847 /* Do we need to construct a skip condition of the given type
3848 * on an if statement?
3850 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3851 bool have_else, enum pet_skip type, bool affine)
3853 if (affine)
3854 return need_skip_aff(scop_then, scop_else, have_else, type);
3855 else
3856 return need_skip(scop_then, scop_else, have_else, type);
3859 /* Construct an affine expression pet_expr that evaluates
3860 * to the constant "val".
3862 static struct pet_expr *universally(isl_ctx *ctx, int val)
3864 isl_space *space;
3865 isl_map *map;
3867 space = isl_space_alloc(ctx, 0, 0, 1);
3868 map = isl_map_universe(space);
3869 map = isl_map_fix_si(map, isl_dim_out, 0, val);
3871 return pet_expr_from_access(map);
3874 /* Construct an affine expression pet_expr that evaluates
3875 * to the constant 1.
3877 static struct pet_expr *universally_true(isl_ctx *ctx)
3879 return universally(ctx, 1);
3882 /* Construct an affine expression pet_expr that evaluates
3883 * to the constant 0.
3885 static struct pet_expr *universally_false(isl_ctx *ctx)
3887 return universally(ctx, 0);
3890 /* Given an access relation "test_access" for the if condition,
3891 * an access relation "skip_access" for the skip condition and
3892 * scops for the then and else branches, construct a scop for
3893 * computing "skip_access".
3895 * The computed scop contains a single statement that essentially does
3897 * skip_cond = test_cond ? skip_cond_then : skip_cond_else
3899 * If the skip conditions of the then and/or else branch are not affine,
3900 * then they need to be filtered by test_access.
3901 * If they are missing, then this means the skip condition is false.
3903 * Since we are constructing a skip condition for the if statement,
3904 * the skip conditions on the then and else branches are removed.
3906 static struct pet_scop *extract_skip(PetScan *scan,
3907 __isl_take isl_map *test_access, __isl_take isl_map *skip_access,
3908 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
3909 enum pet_skip type)
3911 struct pet_expr *expr_then, *expr_else, *expr, *expr_skip;
3912 struct pet_stmt *stmt;
3913 struct pet_scop *scop;
3914 isl_ctx *ctx = scan->ctx;
3916 if (!scop_then)
3917 goto error;
3918 if (have_else && !scop_else)
3919 goto error;
3921 if (pet_scop_has_skip(scop_then, type)) {
3922 expr_then = pet_scop_get_skip_expr(scop_then, type);
3923 pet_scop_reset_skip(scop_then, type);
3924 if (!pet_expr_is_affine(expr_then))
3925 expr_then = pet_expr_filter(expr_then,
3926 isl_map_copy(test_access), 1);
3927 } else
3928 expr_then = universally_false(ctx);
3930 if (have_else && pet_scop_has_skip(scop_else, type)) {
3931 expr_else = pet_scop_get_skip_expr(scop_else, type);
3932 pet_scop_reset_skip(scop_else, type);
3933 if (!pet_expr_is_affine(expr_else))
3934 expr_else = pet_expr_filter(expr_else,
3935 isl_map_copy(test_access), 0);
3936 } else
3937 expr_else = universally_false(ctx);
3939 expr = pet_expr_from_access(test_access);
3940 expr = pet_expr_new_ternary(ctx, expr, expr_then, expr_else);
3941 expr_skip = pet_expr_from_access(isl_map_copy(skip_access));
3942 if (expr_skip) {
3943 expr_skip->acc.write = 1;
3944 expr_skip->acc.read = 0;
3946 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
3947 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, scan->n_stmt++, expr);
3949 scop = pet_scop_from_pet_stmt(ctx, stmt);
3950 scop = scop_add_array(scop, skip_access, scan->ast_context);
3951 isl_map_free(skip_access);
3953 return scop;
3954 error:
3955 isl_map_free(test_access);
3956 isl_map_free(skip_access);
3957 return NULL;
3960 /* Is scop's skip_now condition equal to its skip_later condition?
3961 * In particular, this means that it either has no skip_now condition
3962 * or both a skip_now and a skip_later condition (that are equal to each other).
3964 static bool skip_equals_skip_later(struct pet_scop *scop)
3966 int has_skip_now, has_skip_later;
3967 int equal;
3968 isl_set *skip_now, *skip_later;
3970 if (!scop)
3971 return false;
3972 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
3973 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
3974 if (has_skip_now != has_skip_later)
3975 return false;
3976 if (!has_skip_now)
3977 return true;
3979 skip_now = pet_scop_get_skip(scop, pet_skip_now);
3980 skip_later = pet_scop_get_skip(scop, pet_skip_later);
3981 equal = isl_set_is_equal(skip_now, skip_later);
3982 isl_set_free(skip_now);
3983 isl_set_free(skip_later);
3985 return equal;
3988 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
3990 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
3992 pet_scop_reset_skip(scop1, pet_skip_later);
3993 pet_scop_reset_skip(scop2, pet_skip_later);
3996 /* Structure that handles the construction of skip conditions.
3998 * scop_then and scop_else represent the then and else branches
3999 * of the if statement
4001 * skip[type] is true if we need to construct a skip condition of that type
4002 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
4003 * are equal to each other
4004 * access[type] is the virtual array representing the skip condition
4005 * scop[type] is a scop for computing the skip condition
4007 struct pet_skip_info {
4008 isl_ctx *ctx;
4010 bool skip[2];
4011 bool equal;
4012 isl_map *access[2];
4013 struct pet_scop *scop[2];
4015 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
4017 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
4020 /* Structure that handles the construction of skip conditions on if statements.
4022 * scop_then and scop_else represent the then and else branches
4023 * of the if statement
4025 struct pet_skip_info_if : public pet_skip_info {
4026 struct pet_scop *scop_then, *scop_else;
4027 bool have_else;
4029 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4030 struct pet_scop *scop_else, bool have_else, bool affine);
4031 void extract(PetScan *scan, __isl_keep isl_map *access,
4032 enum pet_skip type);
4033 void extract(PetScan *scan, __isl_keep isl_map *access);
4034 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
4035 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4036 int offset);
4037 struct pet_scop *add(struct pet_scop *scop, int offset);
4040 /* Initialize a pet_skip_info_if structure based on the then and else branches
4041 * and based on whether the if condition is affine or not.
4043 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4044 struct pet_scop *scop_else, bool have_else, bool affine) :
4045 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
4046 have_else(have_else)
4048 skip[pet_skip_now] =
4049 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
4050 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
4051 (!have_else || skip_equals_skip_later(scop_else));
4052 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4053 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
4056 /* If we need to construct a skip condition of the given type,
4057 * then do so now.
4059 * "map" represents the if condition.
4061 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_map *map,
4062 enum pet_skip type)
4064 if (!skip[type])
4065 return;
4067 access[type] = create_test_access(isl_map_get_ctx(map), scan->n_test++);
4068 scop[type] = extract_skip(scan, isl_map_copy(map),
4069 isl_map_copy(access[type]),
4070 scop_then, scop_else, have_else, type);
4073 /* Construct the required skip conditions, given the if condition "map".
4075 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_map *map)
4077 extract(scan, map, pet_skip_now);
4078 extract(scan, map, pet_skip_later);
4079 if (equal)
4080 drop_skip_later(scop_then, scop_else);
4083 /* Construct the required skip conditions, given the if condition "cond".
4085 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
4087 isl_set *test_set;
4088 isl_map *test;
4090 if (!skip[pet_skip_now] && !skip[pet_skip_later])
4091 return;
4093 test_set = isl_set_from_pw_aff(isl_pw_aff_copy(cond));
4094 test = isl_map_from_range(test_set);
4095 extract(scan, test);
4096 isl_map_free(test);
4099 /* Add the computed skip condition of the give type to "main" and
4100 * add the scop for computing the condition at the given offset.
4102 * If equal is set, then we only computed a skip condition for pet_skip_now,
4103 * but we also need to set it as main's pet_skip_later.
4105 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
4106 enum pet_skip type, int offset)
4108 isl_set *skip_set;
4110 if (!skip[type])
4111 return main;
4113 skip_set = isl_map_range(access[type]);
4114 access[type] = NULL;
4115 scop[type] = pet_scop_prefix(scop[type], offset);
4116 main = pet_scop_add_par(ctx, main, scop[type]);
4117 scop[type] = NULL;
4119 if (equal)
4120 main = pet_scop_set_skip(main, pet_skip_later,
4121 isl_set_copy(skip_set));
4123 main = pet_scop_set_skip(main, type, skip_set);
4125 return main;
4128 /* Add the computed skip conditions to "main" and
4129 * add the scops for computing the conditions at the given offset.
4131 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
4133 scop = add(scop, pet_skip_now, offset);
4134 scop = add(scop, pet_skip_later, offset);
4136 return scop;
4139 /* Construct a pet_scop for a non-affine if statement.
4141 * We create a separate statement that writes the result
4142 * of the non-affine condition to a virtual scalar.
4143 * A constraint requiring the value of this virtual scalar to be one
4144 * is added to the iteration domains of the then branch.
4145 * Similarly, a constraint requiring the value of this virtual scalar
4146 * to be zero is added to the iteration domains of the else branch, if any.
4147 * We adjust the schedules to ensure that the virtual scalar is written
4148 * before it is read.
4150 * If there are any breaks or continues in the then and/or else
4151 * branches, then we may have to compute a new skip condition.
4152 * This is handled using a pet_skip_info_if object.
4153 * On initialization, the object checks if skip conditions need
4154 * to be computed. If so, it does so in "extract" and adds them in "add".
4156 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
4157 struct pet_scop *scop_then, struct pet_scop *scop_else,
4158 bool have_else, int stmt_id)
4160 struct pet_scop *scop;
4161 isl_map *test_access;
4162 int save_n_stmt = n_stmt;
4164 test_access = create_test_access(ctx, n_test++);
4165 n_stmt = stmt_id;
4166 scop = extract_non_affine_condition(cond, isl_map_copy(test_access));
4167 n_stmt = save_n_stmt;
4168 scop = scop_add_array(scop, test_access, ast_context);
4170 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
4171 skip.extract(this, test_access);
4173 scop = pet_scop_prefix(scop, 0);
4174 scop_then = pet_scop_prefix(scop_then, 1);
4175 scop_then = pet_scop_filter(scop_then, isl_map_copy(test_access), 1);
4176 if (have_else) {
4177 scop_else = pet_scop_prefix(scop_else, 1);
4178 scop_else = pet_scop_filter(scop_else, test_access, 0);
4179 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
4180 } else
4181 isl_map_free(test_access);
4183 scop = pet_scop_add_seq(ctx, scop, scop_then);
4185 scop = skip.add(scop, 2);
4187 return scop;
4190 /* Construct a pet_scop for an if statement.
4192 * If the condition fits the pattern of a conditional assignment,
4193 * then it is handled by extract_conditional_assignment.
4194 * Otherwise, we do the following.
4196 * If the condition is affine, then the condition is added
4197 * to the iteration domains of the then branch, while the
4198 * opposite of the condition in added to the iteration domains
4199 * of the else branch, if any.
4200 * We allow the condition to be dynamic, i.e., to refer to
4201 * scalars or array elements that may be written to outside
4202 * of the given if statement. These nested accesses are then represented
4203 * as output dimensions in the wrapping iteration domain.
4204 * If it also written _inside_ the then or else branch, then
4205 * we treat the condition as non-affine.
4206 * As explained in extract_non_affine_if, this will introduce
4207 * an extra statement.
4208 * For aesthetic reasons, we want this statement to have a statement
4209 * number that is lower than those of the then and else branches.
4210 * In order to evaluate if will need such a statement, however, we
4211 * first construct scops for the then and else branches.
4212 * We therefore reserve a statement number if we might have to
4213 * introduce such an extra statement.
4215 * If the condition is not affine, then the scop is created in
4216 * extract_non_affine_if.
4218 * If there are any breaks or continues in the then and/or else
4219 * branches, then we may have to compute a new skip condition.
4220 * This is handled using a pet_skip_info_if object.
4221 * On initialization, the object checks if skip conditions need
4222 * to be computed. If so, it does so in "extract" and adds them in "add".
4224 struct pet_scop *PetScan::extract(IfStmt *stmt)
4226 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4227 isl_pw_aff *cond;
4228 int stmt_id;
4229 isl_set *set;
4230 isl_set *valid;
4232 scop = extract_conditional_assignment(stmt);
4233 if (scop)
4234 return scop;
4236 cond = try_extract_nested_condition(stmt->getCond());
4237 if (allow_nested && (!cond || has_nested(cond)))
4238 stmt_id = n_stmt++;
4241 assigned_value_cache cache(assigned_value);
4242 scop_then = extract(stmt->getThen());
4245 if (stmt->getElse()) {
4246 assigned_value_cache cache(assigned_value);
4247 scop_else = extract(stmt->getElse());
4248 if (options->autodetect) {
4249 if (scop_then && !scop_else) {
4250 partial = true;
4251 isl_pw_aff_free(cond);
4252 return scop_then;
4254 if (!scop_then && scop_else) {
4255 partial = true;
4256 isl_pw_aff_free(cond);
4257 return scop_else;
4262 if (cond &&
4263 (!is_nested_allowed(cond, scop_then) ||
4264 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4265 isl_pw_aff_free(cond);
4266 cond = NULL;
4268 if (allow_nested && !cond)
4269 return extract_non_affine_if(stmt->getCond(), scop_then,
4270 scop_else, stmt->getElse(), stmt_id);
4272 if (!cond)
4273 cond = extract_condition(stmt->getCond());
4275 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4276 skip.extract(this, cond);
4278 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4279 set = isl_pw_aff_non_zero_set(cond);
4280 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4282 if (stmt->getElse()) {
4283 set = isl_set_subtract(isl_set_copy(valid), set);
4284 scop_else = pet_scop_restrict(scop_else, set);
4285 scop = pet_scop_add_par(ctx, scop, scop_else);
4286 } else
4287 isl_set_free(set);
4288 scop = resolve_nested(scop);
4289 scop = pet_scop_restrict_context(scop, valid);
4291 if (skip)
4292 scop = pet_scop_prefix(scop, 0);
4293 scop = skip.add(scop, 1);
4295 return scop;
4298 /* Try and construct a pet_scop for a label statement.
4299 * We currently only allow labels on expression statements.
4301 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4303 isl_id *label;
4304 Stmt *sub;
4306 sub = stmt->getSubStmt();
4307 if (!isa<Expr>(sub)) {
4308 unsupported(stmt);
4309 return NULL;
4312 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4314 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4317 /* Construct a pet_scop for a continue statement.
4319 * We simply create an empty scop with a universal pet_skip_now
4320 * skip condition. This skip condition will then be taken into
4321 * account by the enclosing loop construct, possibly after
4322 * being incorporated into outer skip conditions.
4324 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4326 pet_scop *scop;
4327 isl_space *space;
4328 isl_set *set;
4330 scop = pet_scop_empty(ctx);
4331 if (!scop)
4332 return NULL;
4334 space = isl_space_set_alloc(ctx, 0, 1);
4335 set = isl_set_universe(space);
4336 set = isl_set_fix_si(set, isl_dim_set, 0, 1);
4337 scop = pet_scop_set_skip(scop, pet_skip_now, set);
4339 return scop;
4342 /* Construct a pet_scop for a break statement.
4344 * We simply create an empty scop with both a universal pet_skip_now
4345 * skip condition and a universal pet_skip_later skip condition.
4346 * These skip conditions will then be taken into
4347 * account by the enclosing loop construct, possibly after
4348 * being incorporated into outer skip conditions.
4350 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4352 pet_scop *scop;
4353 isl_space *space;
4354 isl_set *set;
4356 scop = pet_scop_empty(ctx);
4357 if (!scop)
4358 return NULL;
4360 space = isl_space_set_alloc(ctx, 0, 1);
4361 set = isl_set_universe(space);
4362 set = isl_set_fix_si(set, isl_dim_set, 0, 1);
4363 scop = pet_scop_set_skip(scop, pet_skip_now, isl_set_copy(set));
4364 scop = pet_scop_set_skip(scop, pet_skip_later, set);
4366 return scop;
4369 /* Try and construct a pet_scop corresponding to "stmt".
4371 * If "stmt" is a compound statement, then "skip_declarations"
4372 * indicates whether we should skip initial declarations in the
4373 * compound statement.
4375 * If the constructed pet_scop is not a (possibly) partial representation
4376 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4377 * In particular, if skip_declarations, then we may have skipped declarations
4378 * inside "stmt" and so the pet_scop may not represent the entire "stmt".
4379 * Note that this function may be called with "stmt" referring to the entire
4380 * body of the function, including the outer braces. In such cases,
4381 * skip_declarations will be set and the braces will not be taken into
4382 * account in scop->start and scop->end.
4384 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
4386 struct pet_scop *scop;
4387 unsigned start, end;
4388 SourceLocation loc;
4389 SourceManager &SM = PP.getSourceManager();
4390 const LangOptions &LO = PP.getLangOpts();
4392 if (isa<Expr>(stmt))
4393 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4395 switch (stmt->getStmtClass()) {
4396 case Stmt::WhileStmtClass:
4397 scop = extract(cast<WhileStmt>(stmt));
4398 break;
4399 case Stmt::ForStmtClass:
4400 scop = extract_for(cast<ForStmt>(stmt));
4401 break;
4402 case Stmt::IfStmtClass:
4403 scop = extract(cast<IfStmt>(stmt));
4404 break;
4405 case Stmt::CompoundStmtClass:
4406 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
4407 break;
4408 case Stmt::LabelStmtClass:
4409 scop = extract(cast<LabelStmt>(stmt));
4410 break;
4411 case Stmt::ContinueStmtClass:
4412 scop = extract(cast<ContinueStmt>(stmt));
4413 break;
4414 case Stmt::BreakStmtClass:
4415 scop = extract(cast<BreakStmt>(stmt));
4416 break;
4417 case Stmt::DeclStmtClass:
4418 scop = extract(cast<DeclStmt>(stmt));
4419 break;
4420 default:
4421 unsupported(stmt);
4422 return NULL;
4425 if (partial || skip_declarations)
4426 return scop;
4428 loc = stmt->getLocStart();
4429 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
4430 start = getExpansionOffset(SM, loc);
4431 loc = PP.getLocForEndOfToken(stmt->getLocEnd());
4432 end = getExpansionOffset(SM, loc);
4433 scop = pet_scop_update_start_end(scop, start, end);
4435 return scop;
4438 /* Do we need to construct a skip condition of the given type
4439 * on a sequence of statements?
4441 * There is no need to construct a new skip condition if only
4442 * only of the two statements has a skip condition or if both
4443 * of their skip conditions are affine.
4445 * In principle we also don't need a new continuation variable if
4446 * the continuation of scop2 is affine, but then we would need
4447 * to allow more complicated forms of continuations.
4449 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4450 enum pet_skip type)
4452 if (!scop1 || !pet_scop_has_skip(scop1, type))
4453 return false;
4454 if (!scop2 || !pet_scop_has_skip(scop2, type))
4455 return false;
4456 if (pet_scop_has_affine_skip(scop1, type) &&
4457 pet_scop_has_affine_skip(scop2, type))
4458 return false;
4459 return true;
4462 /* Construct a scop for computing the skip condition of the given type and
4463 * with access relation "skip_access" for a sequence of two scops "scop1"
4464 * and "scop2".
4466 * The computed scop contains a single statement that essentially does
4468 * skip_cond = skip_cond_1 ? 1 : skip_cond_2
4470 * or, in other words, skip_cond1 || skip_cond2.
4471 * In this expression, skip_cond_2 is filtered to reflect that it is
4472 * only evaluated when skip_cond_1 is false.
4474 * The skip condition on scop1 is not removed because it still needs
4475 * to be applied to scop2 when these two scops are combined.
4477 static struct pet_scop *extract_skip_seq(PetScan *ps,
4478 __isl_take isl_map *skip_access,
4479 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4481 isl_map *access;
4482 struct pet_expr *expr1, *expr2, *expr, *expr_skip;
4483 struct pet_stmt *stmt;
4484 struct pet_scop *scop;
4485 isl_ctx *ctx = ps->ctx;
4487 if (!scop1 || !scop2)
4488 goto error;
4490 expr1 = pet_scop_get_skip_expr(scop1, type);
4491 expr2 = pet_scop_get_skip_expr(scop2, type);
4492 pet_scop_reset_skip(scop2, type);
4494 expr2 = pet_expr_filter(expr2, isl_map_copy(expr1->acc.access), 0);
4496 expr = universally_true(ctx);
4497 expr = pet_expr_new_ternary(ctx, expr1, expr, expr2);
4498 expr_skip = pet_expr_from_access(isl_map_copy(skip_access));
4499 if (expr_skip) {
4500 expr_skip->acc.write = 1;
4501 expr_skip->acc.read = 0;
4503 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4504 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, ps->n_stmt++, expr);
4506 scop = pet_scop_from_pet_stmt(ctx, stmt);
4507 scop = scop_add_array(scop, skip_access, ps->ast_context);
4508 isl_map_free(skip_access);
4510 return scop;
4511 error:
4512 isl_map_free(skip_access);
4513 return NULL;
4516 /* Structure that handles the construction of skip conditions
4517 * on sequences of statements.
4519 * scop1 and scop2 represent the two statements that are combined
4521 struct pet_skip_info_seq : public pet_skip_info {
4522 struct pet_scop *scop1, *scop2;
4524 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4525 struct pet_scop *scop2);
4526 void extract(PetScan *scan, enum pet_skip type);
4527 void extract(PetScan *scan);
4528 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4529 int offset);
4530 struct pet_scop *add(struct pet_scop *scop, int offset);
4533 /* Initialize a pet_skip_info_seq structure based on
4534 * on the two statements that are going to be combined.
4536 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4537 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
4539 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
4540 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
4541 skip_equals_skip_later(scop2);
4542 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4543 need_skip_seq(scop1, scop2, pet_skip_later);
4546 /* If we need to construct a skip condition of the given type,
4547 * then do so now.
4549 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
4551 if (!skip[type])
4552 return;
4554 access[type] = create_test_access(ctx, scan->n_test++);
4555 scop[type] = extract_skip_seq(scan, isl_map_copy(access[type]),
4556 scop1, scop2, type);
4559 /* Construct the required skip conditions.
4561 void pet_skip_info_seq::extract(PetScan *scan)
4563 extract(scan, pet_skip_now);
4564 extract(scan, pet_skip_later);
4565 if (equal)
4566 drop_skip_later(scop1, scop2);
4569 /* Add the computed skip condition of the given type to "main" and
4570 * add the scop for computing the condition at the given offset (the statement
4571 * number). Within this offset, the condition is computed at position 1
4572 * to ensure that it is computed after the corresponding statement.
4574 * If equal is set, then we only computed a skip condition for pet_skip_now,
4575 * but we also need to set it as main's pet_skip_later.
4577 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
4578 enum pet_skip type, int offset)
4580 isl_set *skip_set;
4582 if (!skip[type])
4583 return main;
4585 skip_set = isl_map_range(access[type]);
4586 access[type] = NULL;
4587 scop[type] = pet_scop_prefix(scop[type], 1);
4588 scop[type] = pet_scop_prefix(scop[type], offset);
4589 main = pet_scop_add_par(ctx, main, scop[type]);
4590 scop[type] = NULL;
4592 if (equal)
4593 main = pet_scop_set_skip(main, pet_skip_later,
4594 isl_set_copy(skip_set));
4596 main = pet_scop_set_skip(main, type, skip_set);
4598 return main;
4601 /* Add the computed skip conditions to "main" and
4602 * add the scops for computing the conditions at the given offset.
4604 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
4606 scop = add(scop, pet_skip_now, offset);
4607 scop = add(scop, pet_skip_later, offset);
4609 return scop;
4612 /* Extract a clone of the kill statement in "scop".
4613 * "scop" is expected to have been created from a DeclStmt
4614 * and should have the kill as its first statement.
4616 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
4618 struct pet_expr *kill;
4619 struct pet_stmt *stmt;
4620 isl_map *access;
4622 if (!scop)
4623 return NULL;
4624 if (scop->n_stmt < 1)
4625 isl_die(ctx, isl_error_internal,
4626 "expecting at least one statement", return NULL);
4627 stmt = scop->stmts[0];
4628 if (stmt->body->type != pet_expr_unary ||
4629 stmt->body->op != pet_op_kill)
4630 isl_die(ctx, isl_error_internal,
4631 "expecting kill statement", return NULL);
4633 access = isl_map_copy(stmt->body->args[0]->acc.access);
4634 access = isl_map_reset_tuple_id(access, isl_dim_in);
4635 kill = pet_expr_kill_from_access(access);
4636 return pet_stmt_from_pet_expr(ctx, stmt->line, NULL, n_stmt++, kill);
4639 /* Mark all arrays in "scop" as being exposed.
4641 static struct pet_scop *mark_exposed(struct pet_scop *scop)
4643 if (!scop)
4644 return NULL;
4645 for (int i = 0; i < scop->n_array; ++i)
4646 scop->arrays[i]->exposed = 1;
4647 return scop;
4650 /* Try and construct a pet_scop corresponding to (part of)
4651 * a sequence of statements.
4653 * "block" is set if the sequence respresents the children of
4654 * a compound statement.
4655 * "skip_declarations" is set if we should skip initial declarations
4656 * in the sequence of statements.
4658 * If there are any breaks or continues in the individual statements,
4659 * then we may have to compute a new skip condition.
4660 * This is handled using a pet_skip_info_seq object.
4661 * On initialization, the object checks if skip conditions need
4662 * to be computed. If so, it does so in "extract" and adds them in "add".
4664 * If "block" is set, then we need to insert kill statements at
4665 * the end of the block for any array that has been declared by
4666 * one of the statements in the sequence. Each of these declarations
4667 * results in the construction of a kill statement at the place
4668 * of the declaration, so we simply collect duplicates of
4669 * those kill statements and append these duplicates to the constructed scop.
4671 * If "block" is not set, then any array declared by one of the statements
4672 * in the sequence is marked as being exposed.
4674 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
4675 bool skip_declarations)
4677 pet_scop *scop;
4678 StmtIterator i;
4679 int j;
4680 bool partial_range = false;
4681 set<struct pet_stmt *> kills;
4682 set<struct pet_stmt *>::iterator it;
4684 scop = pet_scop_empty(ctx);
4685 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4686 Stmt *child = *i;
4687 struct pet_scop *scop_i;
4689 if (skip_declarations &&
4690 child->getStmtClass() == Stmt::DeclStmtClass)
4691 continue;
4693 scop_i = extract(child);
4694 if (scop && partial) {
4695 pet_scop_free(scop_i);
4696 break;
4698 pet_skip_info_seq skip(ctx, scop, scop_i);
4699 skip.extract(this);
4700 if (skip)
4701 scop_i = pet_scop_prefix(scop_i, 0);
4702 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4703 if (block)
4704 kills.insert(extract_kill(scop_i));
4705 else
4706 scop_i = mark_exposed(scop_i);
4708 scop_i = pet_scop_prefix(scop_i, j);
4709 if (options->autodetect) {
4710 if (scop_i)
4711 scop = pet_scop_add_seq(ctx, scop, scop_i);
4712 else
4713 partial_range = true;
4714 if (scop->n_stmt != 0 && !scop_i)
4715 partial = true;
4716 } else {
4717 scop = pet_scop_add_seq(ctx, scop, scop_i);
4720 scop = skip.add(scop, j);
4722 if (partial)
4723 break;
4726 for (it = kills.begin(); it != kills.end(); ++it) {
4727 pet_scop *scop_j;
4728 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4729 scop_j = pet_scop_prefix(scop_j, j);
4730 scop = pet_scop_add_seq(ctx, scop, scop_j);
4733 if (scop && partial_range)
4734 partial = true;
4736 return scop;
4739 /* Check if the scop marked by the user is exactly this Stmt
4740 * or part of this Stmt.
4741 * If so, return a pet_scop corresponding to the marked region.
4742 * Otherwise, return NULL.
4744 struct pet_scop *PetScan::scan(Stmt *stmt)
4746 SourceManager &SM = PP.getSourceManager();
4747 unsigned start_off, end_off;
4749 start_off = getExpansionOffset(SM, stmt->getLocStart());
4750 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4752 if (start_off > loc.end)
4753 return NULL;
4754 if (end_off < loc.start)
4755 return NULL;
4756 if (start_off >= loc.start && end_off <= loc.end) {
4757 return extract(stmt);
4760 StmtIterator start;
4761 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4762 Stmt *child = *start;
4763 if (!child)
4764 continue;
4765 start_off = getExpansionOffset(SM, child->getLocStart());
4766 end_off = getExpansionOffset(SM, child->getLocEnd());
4767 if (start_off < loc.start && end_off > loc.end)
4768 return scan(child);
4769 if (start_off >= loc.start)
4770 break;
4773 StmtIterator end;
4774 for (end = start; end != stmt->child_end(); ++end) {
4775 Stmt *child = *end;
4776 start_off = SM.getFileOffset(child->getLocStart());
4777 if (start_off >= loc.end)
4778 break;
4781 return extract(StmtRange(start, end), false, false);
4784 /* Set the size of index "pos" of "array" to "size".
4785 * In particular, add a constraint of the form
4787 * i_pos < size
4789 * to array->extent and a constraint of the form
4791 * size >= 0
4793 * to array->context.
4795 static struct pet_array *update_size(struct pet_array *array, int pos,
4796 __isl_take isl_pw_aff *size)
4798 isl_set *valid;
4799 isl_set *univ;
4800 isl_set *bound;
4801 isl_space *dim;
4802 isl_aff *aff;
4803 isl_pw_aff *index;
4804 isl_id *id;
4806 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
4807 array->context = isl_set_intersect(array->context, valid);
4809 dim = isl_set_get_space(array->extent);
4810 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
4811 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
4812 univ = isl_set_universe(isl_aff_get_domain_space(aff));
4813 index = isl_pw_aff_alloc(univ, aff);
4815 size = isl_pw_aff_add_dims(size, isl_dim_in,
4816 isl_set_dim(array->extent, isl_dim_set));
4817 id = isl_set_get_tuple_id(array->extent);
4818 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
4819 bound = isl_pw_aff_lt_set(index, size);
4821 array->extent = isl_set_intersect(array->extent, bound);
4823 if (!array->context || !array->extent)
4824 goto error;
4826 return array;
4827 error:
4828 pet_array_free(array);
4829 return NULL;
4832 /* Figure out the size of the array at position "pos" and all
4833 * subsequent positions from "type" and update "array" accordingly.
4835 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
4836 const Type *type, int pos)
4838 const ArrayType *atype;
4839 isl_pw_aff *size;
4841 if (!array)
4842 return NULL;
4844 if (type->isPointerType()) {
4845 type = type->getPointeeType().getTypePtr();
4846 return set_upper_bounds(array, type, pos + 1);
4848 if (!type->isArrayType())
4849 return array;
4851 type = type->getCanonicalTypeInternal().getTypePtr();
4852 atype = cast<ArrayType>(type);
4854 if (type->isConstantArrayType()) {
4855 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
4856 size = extract_affine(ca->getSize());
4857 array = update_size(array, pos, size);
4858 } else if (type->isVariableArrayType()) {
4859 const VariableArrayType *vla = cast<VariableArrayType>(atype);
4860 size = extract_affine(vla->getSizeExpr());
4861 array = update_size(array, pos, size);
4864 type = atype->getElementType().getTypePtr();
4866 return set_upper_bounds(array, type, pos + 1);
4869 /* Is "T" the type of a variable length array with static size?
4871 static bool is_vla_with_static_size(QualType T)
4873 const VariableArrayType *vlatype;
4875 if (!T->isVariableArrayType())
4876 return false;
4877 vlatype = cast<VariableArrayType>(T);
4878 return vlatype->getSizeModifier() == VariableArrayType::Static;
4881 /* Return the type of "decl" as an array.
4883 * In particular, if "decl" is a parameter declaration that
4884 * is a variable length array with a static size, then
4885 * return the original type (i.e., the variable length array).
4886 * Otherwise, return the type of decl.
4888 static QualType get_array_type(ValueDecl *decl)
4890 ParmVarDecl *parm;
4891 QualType T;
4893 parm = dyn_cast<ParmVarDecl>(decl);
4894 if (!parm)
4895 return decl->getType();
4897 T = parm->getOriginalType();
4898 if (!is_vla_with_static_size(T))
4899 return decl->getType();
4900 return T;
4903 /* Construct and return a pet_array corresponding to the variable "decl".
4904 * In particular, initialize array->extent to
4906 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4908 * and then call set_upper_bounds to set the upper bounds on the indices
4909 * based on the type of the variable.
4911 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
4913 struct pet_array *array;
4914 QualType qt = get_array_type(decl);
4915 const Type *type = qt.getTypePtr();
4916 int depth = array_depth(type);
4917 QualType base = base_type(qt);
4918 string name;
4919 isl_id *id;
4920 isl_space *dim;
4922 array = isl_calloc_type(ctx, struct pet_array);
4923 if (!array)
4924 return NULL;
4926 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
4927 dim = isl_space_set_alloc(ctx, 0, depth);
4928 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
4930 array->extent = isl_set_nat_universe(dim);
4932 dim = isl_space_params_alloc(ctx, 0);
4933 array->context = isl_set_universe(dim);
4935 array = set_upper_bounds(array, type, 0);
4936 if (!array)
4937 return NULL;
4939 name = base.getAsString();
4940 array->element_type = strdup(name.c_str());
4941 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
4943 return array;
4946 /* Construct a list of pet_arrays, one for each array (or scalar)
4947 * accessed inside "scop", add this list to "scop" and return the result.
4949 * The context of "scop" is updated with the intersection of
4950 * the contexts of all arrays, i.e., constraints on the parameters
4951 * that ensure that the arrays have a valid (non-negative) size.
4953 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
4955 int i;
4956 set<ValueDecl *> arrays;
4957 set<ValueDecl *>::iterator it;
4958 int n_array;
4959 struct pet_array **scop_arrays;
4961 if (!scop)
4962 return NULL;
4964 pet_scop_collect_arrays(scop, arrays);
4965 if (arrays.size() == 0)
4966 return scop;
4968 n_array = scop->n_array;
4970 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
4971 n_array + arrays.size());
4972 if (!scop_arrays)
4973 goto error;
4974 scop->arrays = scop_arrays;
4976 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
4977 struct pet_array *array;
4978 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
4979 if (!scop->arrays[n_array + i])
4980 goto error;
4981 scop->n_array++;
4982 scop->context = isl_set_intersect(scop->context,
4983 isl_set_copy(array->context));
4984 if (!scop->context)
4985 goto error;
4988 return scop;
4989 error:
4990 pet_scop_free(scop);
4991 return NULL;
4994 /* Bound all parameters in scop->context to the possible values
4995 * of the corresponding C variable.
4997 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
4999 int n;
5001 if (!scop)
5002 return NULL;
5004 n = isl_set_dim(scop->context, isl_dim_param);
5005 for (int i = 0; i < n; ++i) {
5006 isl_id *id;
5007 ValueDecl *decl;
5009 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
5010 if (is_nested_parameter(id)) {
5011 isl_id_free(id);
5012 isl_die(isl_set_get_ctx(scop->context),
5013 isl_error_internal,
5014 "unresolved nested parameter", goto error);
5016 decl = (ValueDecl *) isl_id_get_user(id);
5017 isl_id_free(id);
5019 scop->context = set_parameter_bounds(scop->context, i, decl);
5021 if (!scop->context)
5022 goto error;
5025 return scop;
5026 error:
5027 pet_scop_free(scop);
5028 return NULL;
5031 /* Construct a pet_scop from the given function.
5033 * If the scop was delimited by scop and endscop pragmas, then we override
5034 * the file offsets by those derived from the pragmas.
5036 struct pet_scop *PetScan::scan(FunctionDecl *fd)
5038 pet_scop *scop;
5039 Stmt *stmt;
5041 stmt = fd->getBody();
5043 if (options->autodetect)
5044 scop = extract(stmt, true);
5045 else {
5046 scop = scan(stmt);
5047 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
5049 scop = pet_scop_detect_parameter_accesses(scop);
5050 scop = scan_arrays(scop);
5051 scop = add_parameter_bounds(scop);
5052 scop = pet_scop_gist(scop, value_bounds);
5054 return scop;