scan.cc: extract_depth: use correct dimension type
[pet.git] / scan.cc
blob494f2392bbf1862ecfafd1c6f5340e3be204e2eb
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2013 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();
298 llvm::APInt val = expr->getValue();
299 int is_negative = is_signed && val.isNegative();
300 isl_val *v;
302 if (is_negative)
303 val = -val;
305 v = extract_unsigned(ctx, val);
307 if (is_negative)
308 v = isl_val_neg(v);
309 return v;
312 /* Extract an integer from "val", which assumed to be non-negative.
314 __isl_give isl_val *PetScan::extract_unsigned(isl_ctx *ctx,
315 const llvm::APInt &val)
317 unsigned n;
318 const uint64_t *data;
320 data = val.getRawData();
321 n = val.getNumWords();
322 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
325 /* Extract an integer from "expr".
326 * Return NULL if "expr" does not (obviously) represent an integer.
328 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
330 return extract_int(expr->getSubExpr());
333 /* Extract an integer from "expr".
334 * Return NULL if "expr" does not (obviously) represent an integer.
336 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
338 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
339 return extract_int(ctx, cast<IntegerLiteral>(expr));
340 if (expr->getStmtClass() == Stmt::ParenExprClass)
341 return extract_int(cast<ParenExpr>(expr));
343 unsupported(expr);
344 return NULL;
347 /* Extract an affine expression from the IntegerLiteral "expr".
349 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
351 isl_space *dim = isl_space_params_alloc(ctx, 0);
352 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
353 isl_aff *aff = isl_aff_zero_on_domain(ls);
354 isl_set *dom = isl_set_universe(dim);
355 isl_val *v;
357 v = extract_int(expr);
358 aff = isl_aff_add_constant_val(aff, v);
360 return isl_pw_aff_alloc(dom, aff);
363 /* Extract an affine expression from the APInt "val", which is assumed
364 * to be non-negative.
366 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
368 isl_space *dim = isl_space_params_alloc(ctx, 0);
369 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
370 isl_aff *aff = isl_aff_zero_on_domain(ls);
371 isl_set *dom = isl_set_universe(dim);
372 isl_val *v;
374 v = extract_unsigned(ctx, val);
375 aff = isl_aff_add_constant_val(aff, v);
377 return isl_pw_aff_alloc(dom, aff);
380 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
382 return extract_affine(expr->getSubExpr());
385 static unsigned get_type_size(ValueDecl *decl)
387 return decl->getASTContext().getIntWidth(decl->getType());
390 /* Bound parameter "pos" of "set" to the possible values of "decl".
392 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
393 unsigned pos, ValueDecl *decl)
395 unsigned width;
396 isl_ctx *ctx;
397 isl_val *bound;
399 ctx = isl_set_get_ctx(set);
400 width = get_type_size(decl);
401 if (decl->getType()->isUnsignedIntegerType()) {
402 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
403 bound = isl_val_int_from_ui(ctx, width);
404 bound = isl_val_2exp(bound);
405 bound = isl_val_sub_ui(bound, 1);
406 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
407 } else {
408 bound = isl_val_int_from_ui(ctx, width - 1);
409 bound = isl_val_2exp(bound);
410 bound = isl_val_sub_ui(bound, 1);
411 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
412 isl_val_copy(bound));
413 bound = isl_val_neg(bound);
414 bound = isl_val_sub_ui(bound, 1);
415 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
418 return set;
421 /* Extract an affine expression from the DeclRefExpr "expr".
423 * If the variable has been assigned a value, then we check whether
424 * we know what (affine) value was assigned.
425 * If so, we return this value. Otherwise we convert "expr"
426 * to an extra parameter (provided nesting_enabled is set).
428 * Otherwise, we simply return an expression that is equal
429 * to a parameter corresponding to the referenced variable.
431 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
433 ValueDecl *decl = expr->getDecl();
434 const Type *type = decl->getType().getTypePtr();
435 isl_id *id;
436 isl_space *dim;
437 isl_aff *aff;
438 isl_set *dom;
440 if (!type->isIntegerType()) {
441 unsupported(expr);
442 return NULL;
445 if (assigned_value.find(decl) != assigned_value.end()) {
446 if (assigned_value[decl])
447 return isl_pw_aff_copy(assigned_value[decl]);
448 else
449 return nested_access(expr);
452 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
453 dim = isl_space_params_alloc(ctx, 1);
455 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
457 dom = isl_set_universe(isl_space_copy(dim));
458 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
459 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
461 return isl_pw_aff_alloc(dom, aff);
464 /* Extract an affine expression from an integer division operation.
465 * In particular, if "expr" is lhs/rhs, then return
467 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
469 * The second argument (rhs) is required to be a (positive) integer constant.
471 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
473 int is_cst;
474 isl_pw_aff *rhs, *lhs;
476 rhs = extract_affine(expr->getRHS());
477 is_cst = isl_pw_aff_is_cst(rhs);
478 if (is_cst < 0 || !is_cst) {
479 isl_pw_aff_free(rhs);
480 if (!is_cst)
481 unsupported(expr);
482 return NULL;
485 lhs = extract_affine(expr->getLHS());
487 return isl_pw_aff_tdiv_q(lhs, rhs);
490 /* Extract an affine expression from a modulo operation.
491 * In particular, if "expr" is lhs/rhs, then return
493 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
495 * The second argument (rhs) is required to be a (positive) integer constant.
497 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
499 int is_cst;
500 isl_pw_aff *rhs, *lhs;
502 rhs = extract_affine(expr->getRHS());
503 is_cst = isl_pw_aff_is_cst(rhs);
504 if (is_cst < 0 || !is_cst) {
505 isl_pw_aff_free(rhs);
506 if (!is_cst)
507 unsupported(expr);
508 return NULL;
511 lhs = extract_affine(expr->getLHS());
513 return isl_pw_aff_tdiv_r(lhs, rhs);
516 /* Extract an affine expression from a multiplication operation.
517 * This is only allowed if at least one of the two arguments
518 * is a (piecewise) constant.
520 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
522 isl_pw_aff *lhs;
523 isl_pw_aff *rhs;
525 lhs = extract_affine(expr->getLHS());
526 rhs = extract_affine(expr->getRHS());
528 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
529 isl_pw_aff_free(lhs);
530 isl_pw_aff_free(rhs);
531 unsupported(expr);
532 return NULL;
535 return isl_pw_aff_mul(lhs, rhs);
538 /* Extract an affine expression from an addition or subtraction operation.
540 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
542 isl_pw_aff *lhs;
543 isl_pw_aff *rhs;
545 lhs = extract_affine(expr->getLHS());
546 rhs = extract_affine(expr->getRHS());
548 switch (expr->getOpcode()) {
549 case BO_Add:
550 return isl_pw_aff_add(lhs, rhs);
551 case BO_Sub:
552 return isl_pw_aff_sub(lhs, rhs);
553 default:
554 isl_pw_aff_free(lhs);
555 isl_pw_aff_free(rhs);
556 return NULL;
561 /* Compute
563 * pwaff mod 2^width
565 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
566 unsigned width)
568 isl_ctx *ctx;
569 isl_val *mod;
571 ctx = isl_pw_aff_get_ctx(pwaff);
572 mod = isl_val_int_from_ui(ctx, width);
573 mod = isl_val_2exp(mod);
575 pwaff = isl_pw_aff_mod_val(pwaff, mod);
577 return pwaff;
580 /* Limit the domain of "pwaff" to those elements where the function
581 * value satisfies
583 * 2^{width-1} <= pwaff < 2^{width-1}
585 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
586 unsigned width)
588 isl_ctx *ctx;
589 isl_val *v;
590 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
591 isl_local_space *ls = isl_local_space_from_space(space);
592 isl_aff *bound;
593 isl_set *dom;
594 isl_pw_aff *b;
596 ctx = isl_pw_aff_get_ctx(pwaff);
597 v = isl_val_int_from_ui(ctx, width - 1);
598 v = isl_val_2exp(v);
600 bound = isl_aff_zero_on_domain(ls);
601 bound = isl_aff_add_constant_val(bound, v);
602 b = isl_pw_aff_from_aff(bound);
604 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
605 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
607 b = isl_pw_aff_neg(b);
608 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
609 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
611 return pwaff;
614 /* Handle potential overflows on signed computations.
616 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
617 * the we adjust the domain of "pa" to avoid overflows.
619 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
620 unsigned width)
622 if (options->signed_overflow == PET_OVERFLOW_AVOID)
623 pa = avoid_overflow(pa, width);
625 return pa;
628 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
630 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
631 __isl_take isl_set *dom)
633 isl_pw_aff *pa;
634 pa = isl_set_indicator_function(set);
635 pa = isl_pw_aff_intersect_domain(pa, dom);
636 return pa;
639 /* Extract an affine expression from some binary operations.
640 * If the result of the expression is unsigned, then we wrap it
641 * based on the size of the type. Otherwise, we ensure that
642 * no overflow occurs.
644 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
646 isl_pw_aff *res;
647 unsigned width;
649 switch (expr->getOpcode()) {
650 case BO_Add:
651 case BO_Sub:
652 res = extract_affine_add(expr);
653 break;
654 case BO_Div:
655 res = extract_affine_div(expr);
656 break;
657 case BO_Rem:
658 res = extract_affine_mod(expr);
659 break;
660 case BO_Mul:
661 res = extract_affine_mul(expr);
662 break;
663 case BO_LT:
664 case BO_LE:
665 case BO_GT:
666 case BO_GE:
667 case BO_EQ:
668 case BO_NE:
669 case BO_LAnd:
670 case BO_LOr:
671 return extract_condition(expr);
672 default:
673 unsupported(expr);
674 return NULL;
677 width = ast_context.getIntWidth(expr->getType());
678 if (expr->getType()->isUnsignedIntegerType())
679 res = wrap(res, width);
680 else
681 res = signed_overflow(res, width);
683 return res;
686 /* Extract an affine expression from a negation operation.
688 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
690 if (expr->getOpcode() == UO_Minus)
691 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
692 if (expr->getOpcode() == UO_LNot)
693 return extract_condition(expr);
695 unsupported(expr);
696 return NULL;
699 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
701 return extract_affine(expr->getSubExpr());
704 /* Extract an affine expression from some special function calls.
705 * In particular, we handle "min", "max", "ceild" and "floord".
706 * In case of the latter two, the second argument needs to be
707 * a (positive) integer constant.
709 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
711 FunctionDecl *fd;
712 string name;
713 isl_pw_aff *aff1, *aff2;
715 fd = expr->getDirectCallee();
716 if (!fd) {
717 unsupported(expr);
718 return NULL;
721 name = fd->getDeclName().getAsString();
722 if (!(expr->getNumArgs() == 2 && name == "min") &&
723 !(expr->getNumArgs() == 2 && name == "max") &&
724 !(expr->getNumArgs() == 2 && name == "floord") &&
725 !(expr->getNumArgs() == 2 && name == "ceild")) {
726 unsupported(expr);
727 return NULL;
730 if (name == "min" || name == "max") {
731 aff1 = extract_affine(expr->getArg(0));
732 aff2 = extract_affine(expr->getArg(1));
734 if (name == "min")
735 aff1 = isl_pw_aff_min(aff1, aff2);
736 else
737 aff1 = isl_pw_aff_max(aff1, aff2);
738 } else if (name == "floord" || name == "ceild") {
739 isl_val *v;
740 Expr *arg2 = expr->getArg(1);
742 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
743 unsupported(expr);
744 return NULL;
746 aff1 = extract_affine(expr->getArg(0));
747 v = extract_int(cast<IntegerLiteral>(arg2));
748 aff1 = isl_pw_aff_scale_down_val(aff1, v);
749 if (name == "floord")
750 aff1 = isl_pw_aff_floor(aff1);
751 else
752 aff1 = isl_pw_aff_ceil(aff1);
753 } else {
754 unsupported(expr);
755 return NULL;
758 return aff1;
761 /* This method is called when we come across an access that is
762 * nested in what is supposed to be an affine expression.
763 * If nesting is allowed, we return a new parameter that corresponds
764 * to this nested access. Otherwise, we simply complain.
766 * Note that we currently don't allow nested accesses themselves
767 * to contain any nested accesses, so we check if we can extract
768 * the access without any nesting and complain if we can't.
770 * The new parameter is resolved in resolve_nested.
772 isl_pw_aff *PetScan::nested_access(Expr *expr)
774 isl_id *id;
775 isl_space *dim;
776 isl_aff *aff;
777 isl_set *dom;
778 isl_multi_pw_aff *index;
780 if (!nesting_enabled) {
781 unsupported(expr);
782 return NULL;
785 allow_nested = false;
786 index = extract_index(expr);
787 allow_nested = true;
788 if (!index) {
789 unsupported(expr);
790 return NULL;
792 isl_multi_pw_aff_free(index);
794 id = isl_id_alloc(ctx, NULL, expr);
795 dim = isl_space_params_alloc(ctx, 1);
797 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
799 dom = isl_set_universe(isl_space_copy(dim));
800 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
801 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
803 return isl_pw_aff_alloc(dom, aff);
806 /* Affine expressions are not supposed to contain array accesses,
807 * but if nesting is allowed, we return a parameter corresponding
808 * to the array access.
810 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
812 return nested_access(expr);
815 /* Extract an affine expression from a conditional operation.
817 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
819 isl_pw_aff *cond, *lhs, *rhs, *res;
821 cond = extract_condition(expr->getCond());
822 lhs = extract_affine(expr->getTrueExpr());
823 rhs = extract_affine(expr->getFalseExpr());
825 return isl_pw_aff_cond(cond, lhs, rhs);
828 /* Extract an affine expression, if possible, from "expr".
829 * Otherwise return NULL.
831 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
833 switch (expr->getStmtClass()) {
834 case Stmt::ImplicitCastExprClass:
835 return extract_affine(cast<ImplicitCastExpr>(expr));
836 case Stmt::IntegerLiteralClass:
837 return extract_affine(cast<IntegerLiteral>(expr));
838 case Stmt::DeclRefExprClass:
839 return extract_affine(cast<DeclRefExpr>(expr));
840 case Stmt::BinaryOperatorClass:
841 return extract_affine(cast<BinaryOperator>(expr));
842 case Stmt::UnaryOperatorClass:
843 return extract_affine(cast<UnaryOperator>(expr));
844 case Stmt::ParenExprClass:
845 return extract_affine(cast<ParenExpr>(expr));
846 case Stmt::CallExprClass:
847 return extract_affine(cast<CallExpr>(expr));
848 case Stmt::ArraySubscriptExprClass:
849 return extract_affine(cast<ArraySubscriptExpr>(expr));
850 case Stmt::ConditionalOperatorClass:
851 return extract_affine(cast<ConditionalOperator>(expr));
852 default:
853 unsupported(expr);
855 return NULL;
858 __isl_give isl_multi_pw_aff *PetScan::extract_index(ImplicitCastExpr *expr)
860 return extract_index(expr->getSubExpr());
863 /* Return the depth of an array of the given type.
865 static int array_depth(const Type *type)
867 if (type->isPointerType())
868 return 1 + array_depth(type->getPointeeType().getTypePtr());
869 if (type->isArrayType()) {
870 const ArrayType *atype;
871 type = type->getCanonicalTypeInternal().getTypePtr();
872 atype = cast<ArrayType>(type);
873 return 1 + array_depth(atype->getElementType().getTypePtr());
875 return 0;
878 /* Return the depth of the array accessed by the index expression "index".
879 * If "index" is an affine expression, i.e., if it does not access
880 * any array, then return 1.
882 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
884 isl_id *id;
885 ValueDecl *decl;
887 if (!index)
888 return -1;
890 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
891 return 1;
893 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
894 if (!id)
895 return -1;
896 decl = (ValueDecl *) isl_id_get_user(id);
897 isl_id_free(id);
899 return array_depth(decl->getType().getTypePtr());
902 /* Return the element type of the given array type.
904 static QualType base_type(QualType qt)
906 const Type *type = qt.getTypePtr();
908 if (type->isPointerType())
909 return base_type(type->getPointeeType());
910 if (type->isArrayType()) {
911 const ArrayType *atype;
912 type = type->getCanonicalTypeInternal().getTypePtr();
913 atype = cast<ArrayType>(type);
914 return base_type(atype->getElementType());
916 return qt;
919 /* Extract an index expression from a reference to a variable.
920 * If the variable has name "A", then the returned index expression
921 * is of the form
923 * { [] -> A[] }
925 __isl_give isl_multi_pw_aff *PetScan::extract_index(DeclRefExpr *expr)
927 return extract_index(expr->getDecl());
930 /* Extract an index expression from a variable.
931 * If the variable has name "A", then the returned index expression
932 * is of the form
934 * { [] -> A[] }
936 __isl_give isl_multi_pw_aff *PetScan::extract_index(ValueDecl *decl)
938 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
939 isl_space *space = isl_space_alloc(ctx, 0, 0, 0);
941 space = isl_space_set_tuple_id(space, isl_dim_out, id);
943 return isl_multi_pw_aff_zero(space);
946 /* Extract an index expression from an integer contant.
947 * If the value of the constant is "v", then the returned access relation
948 * is
950 * { [] -> [v] }
952 __isl_give isl_multi_pw_aff *PetScan::extract_index(IntegerLiteral *expr)
954 isl_multi_pw_aff *mpa;
956 mpa = isl_multi_pw_aff_from_pw_aff(extract_affine(expr));
957 mpa = isl_multi_pw_aff_from_range(mpa);
958 return mpa;
961 /* Try and extract an index expression from the given Expr.
962 * Return NULL if it doesn't work out.
964 __isl_give isl_multi_pw_aff *PetScan::extract_index(Expr *expr)
966 switch (expr->getStmtClass()) {
967 case Stmt::ImplicitCastExprClass:
968 return extract_index(cast<ImplicitCastExpr>(expr));
969 case Stmt::DeclRefExprClass:
970 return extract_index(cast<DeclRefExpr>(expr));
971 case Stmt::ArraySubscriptExprClass:
972 return extract_index(cast<ArraySubscriptExpr>(expr));
973 case Stmt::IntegerLiteralClass:
974 return extract_index(cast<IntegerLiteral>(expr));
975 default:
976 unsupported(expr);
978 return NULL;
981 /* Extract an index expression from the given array subscript expression.
982 * If nesting is allowed in general, then we turn it on while
983 * examining the index expression.
985 * We first extract an index expression from the base.
986 * This will result in an index expression with a range that corresponds
987 * to the earlier indices.
988 * We then extract the current index, restrict its domain
989 * to those values that result in a non-negative index and
990 * append the index to the base index expression.
992 __isl_give isl_multi_pw_aff *PetScan::extract_index(ArraySubscriptExpr *expr)
994 Expr *base = expr->getBase();
995 Expr *idx = expr->getIdx();
996 isl_pw_aff *index;
997 isl_set *domain;
998 isl_multi_pw_aff *base_access;
999 isl_multi_pw_aff *access;
1000 isl_id *id;
1001 bool save_nesting = nesting_enabled;
1003 nesting_enabled = allow_nested;
1005 base_access = extract_index(base);
1006 index = extract_affine(idx);
1008 nesting_enabled = save_nesting;
1010 id = isl_multi_pw_aff_get_tuple_id(base_access, isl_dim_set);
1011 index = isl_pw_aff_from_range(index);
1012 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
1013 index = isl_pw_aff_intersect_domain(index, domain);
1014 access = isl_multi_pw_aff_from_pw_aff(index);
1015 access = isl_multi_pw_aff_flat_range_product(base_access, access);
1016 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_set, id);
1018 return access;
1021 /* Check if "expr" calls function "minmax" with two arguments and if so
1022 * make lhs and rhs refer to these two arguments.
1024 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1026 CallExpr *call;
1027 FunctionDecl *fd;
1028 string name;
1030 if (expr->getStmtClass() != Stmt::CallExprClass)
1031 return false;
1033 call = cast<CallExpr>(expr);
1034 fd = call->getDirectCallee();
1035 if (!fd)
1036 return false;
1038 if (call->getNumArgs() != 2)
1039 return false;
1041 name = fd->getDeclName().getAsString();
1042 if (name != minmax)
1043 return false;
1045 lhs = call->getArg(0);
1046 rhs = call->getArg(1);
1048 return true;
1051 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1052 * lhs and rhs refer to the two arguments.
1054 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1056 return is_minmax(expr, "min", lhs, rhs);
1059 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1060 * lhs and rhs refer to the two arguments.
1062 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1064 return is_minmax(expr, "max", lhs, rhs);
1067 /* Return "lhs && rhs", defined on the shared definition domain.
1069 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1070 __isl_take isl_pw_aff *rhs)
1072 isl_set *cond;
1073 isl_set *dom;
1075 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1076 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1077 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1078 isl_pw_aff_non_zero_set(rhs));
1079 return indicator_function(cond, dom);
1082 /* Return "lhs && rhs", with shortcut semantics.
1083 * That is, if lhs is false, then the result is defined even if rhs is not.
1084 * In practice, we compute lhs ? rhs : lhs.
1086 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1087 __isl_take isl_pw_aff *rhs)
1089 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1092 /* Return "lhs || rhs", with shortcut semantics.
1093 * That is, if lhs is true, then the result is defined even if rhs is not.
1094 * In practice, we compute lhs ? lhs : rhs.
1096 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1097 __isl_take isl_pw_aff *rhs)
1099 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1102 /* Extract an affine expressions representing the comparison "LHS op RHS"
1103 * "comp" is the original statement that "LHS op RHS" is derived from
1104 * and is used for diagnostics.
1106 * If the comparison is of the form
1108 * a <= min(b,c)
1110 * then the expression is constructed as the conjunction of
1111 * the comparisons
1113 * a <= b and a <= c
1115 * A similar optimization is performed for max(a,b) <= c.
1116 * We do this because that will lead to simpler representations
1117 * of the expression.
1118 * If isl is ever enhanced to explicitly deal with min and max expressions,
1119 * this optimization can be removed.
1121 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1122 Expr *LHS, Expr *RHS, Stmt *comp)
1124 isl_pw_aff *lhs;
1125 isl_pw_aff *rhs;
1126 isl_pw_aff *res;
1127 isl_set *cond;
1128 isl_set *dom;
1130 if (op == BO_GT)
1131 return extract_comparison(BO_LT, RHS, LHS, comp);
1132 if (op == BO_GE)
1133 return extract_comparison(BO_LE, RHS, LHS, comp);
1135 if (op == BO_LT || op == BO_LE) {
1136 Expr *expr1, *expr2;
1137 if (is_min(RHS, expr1, expr2)) {
1138 lhs = extract_comparison(op, LHS, expr1, comp);
1139 rhs = extract_comparison(op, LHS, expr2, comp);
1140 return pw_aff_and(lhs, rhs);
1142 if (is_max(LHS, expr1, expr2)) {
1143 lhs = extract_comparison(op, expr1, RHS, comp);
1144 rhs = extract_comparison(op, expr2, RHS, comp);
1145 return pw_aff_and(lhs, rhs);
1149 lhs = extract_affine(LHS);
1150 rhs = extract_affine(RHS);
1152 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1153 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1155 switch (op) {
1156 case BO_LT:
1157 cond = isl_pw_aff_lt_set(lhs, rhs);
1158 break;
1159 case BO_LE:
1160 cond = isl_pw_aff_le_set(lhs, rhs);
1161 break;
1162 case BO_EQ:
1163 cond = isl_pw_aff_eq_set(lhs, rhs);
1164 break;
1165 case BO_NE:
1166 cond = isl_pw_aff_ne_set(lhs, rhs);
1167 break;
1168 default:
1169 isl_pw_aff_free(lhs);
1170 isl_pw_aff_free(rhs);
1171 isl_set_free(dom);
1172 unsupported(comp);
1173 return NULL;
1176 cond = isl_set_coalesce(cond);
1177 res = indicator_function(cond, dom);
1179 return res;
1182 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1184 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1185 comp->getRHS(), comp);
1188 /* Extract an affine expression representing the negation (logical not)
1189 * of a subexpression.
1191 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1193 isl_set *set_cond, *dom;
1194 isl_pw_aff *cond, *res;
1196 cond = extract_condition(op->getSubExpr());
1198 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1200 set_cond = isl_pw_aff_zero_set(cond);
1202 res = indicator_function(set_cond, dom);
1204 return res;
1207 /* Extract an affine expression representing the disjunction (logical or)
1208 * or conjunction (logical and) of two subexpressions.
1210 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1212 isl_pw_aff *lhs, *rhs;
1214 lhs = extract_condition(comp->getLHS());
1215 rhs = extract_condition(comp->getRHS());
1217 switch (comp->getOpcode()) {
1218 case BO_LAnd:
1219 return pw_aff_and_then(lhs, rhs);
1220 case BO_LOr:
1221 return pw_aff_or_else(lhs, rhs);
1222 default:
1223 isl_pw_aff_free(lhs);
1224 isl_pw_aff_free(rhs);
1227 unsupported(comp);
1228 return NULL;
1231 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1233 switch (expr->getOpcode()) {
1234 case UO_LNot:
1235 return extract_boolean(expr);
1236 default:
1237 unsupported(expr);
1238 return NULL;
1242 /* Extract the affine expression "expr != 0 ? 1 : 0".
1244 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1246 isl_pw_aff *res;
1247 isl_set *set, *dom;
1249 res = extract_affine(expr);
1251 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1252 set = isl_pw_aff_non_zero_set(res);
1254 res = indicator_function(set, dom);
1256 return res;
1259 /* Extract an affine expression from a boolean expression.
1260 * In particular, return the expression "expr ? 1 : 0".
1262 * If the expression doesn't look like a condition, we assume it
1263 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1265 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1267 BinaryOperator *comp;
1269 if (!expr) {
1270 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1271 return indicator_function(u, isl_set_copy(u));
1274 if (expr->getStmtClass() == Stmt::ParenExprClass)
1275 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1277 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1278 return extract_condition(cast<UnaryOperator>(expr));
1280 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1281 return extract_implicit_condition(expr);
1283 comp = cast<BinaryOperator>(expr);
1284 switch (comp->getOpcode()) {
1285 case BO_LT:
1286 case BO_LE:
1287 case BO_GT:
1288 case BO_GE:
1289 case BO_EQ:
1290 case BO_NE:
1291 return extract_comparison(comp);
1292 case BO_LAnd:
1293 case BO_LOr:
1294 return extract_boolean(comp);
1295 default:
1296 return extract_implicit_condition(expr);
1300 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1302 switch (kind) {
1303 case UO_Minus:
1304 return pet_op_minus;
1305 case UO_PostInc:
1306 return pet_op_post_inc;
1307 case UO_PostDec:
1308 return pet_op_post_dec;
1309 case UO_PreInc:
1310 return pet_op_pre_inc;
1311 case UO_PreDec:
1312 return pet_op_pre_dec;
1313 default:
1314 return pet_op_last;
1318 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1320 switch (kind) {
1321 case BO_AddAssign:
1322 return pet_op_add_assign;
1323 case BO_SubAssign:
1324 return pet_op_sub_assign;
1325 case BO_MulAssign:
1326 return pet_op_mul_assign;
1327 case BO_DivAssign:
1328 return pet_op_div_assign;
1329 case BO_Assign:
1330 return pet_op_assign;
1331 case BO_Add:
1332 return pet_op_add;
1333 case BO_Sub:
1334 return pet_op_sub;
1335 case BO_Mul:
1336 return pet_op_mul;
1337 case BO_Div:
1338 return pet_op_div;
1339 case BO_Rem:
1340 return pet_op_mod;
1341 case BO_EQ:
1342 return pet_op_eq;
1343 case BO_LE:
1344 return pet_op_le;
1345 case BO_LT:
1346 return pet_op_lt;
1347 case BO_GT:
1348 return pet_op_gt;
1349 default:
1350 return pet_op_last;
1354 /* Construct a pet_expr representing a unary operator expression.
1356 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1358 struct pet_expr *arg;
1359 enum pet_op_type op;
1361 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1362 if (op == pet_op_last) {
1363 unsupported(expr);
1364 return NULL;
1367 arg = extract_expr(expr->getSubExpr());
1369 if (expr->isIncrementDecrementOp() &&
1370 arg && arg->type == pet_expr_access) {
1371 mark_write(arg);
1372 arg->acc.read = 1;
1375 return pet_expr_new_unary(ctx, op, arg);
1378 /* Mark the given access pet_expr as a write.
1379 * If a scalar is being accessed, then mark its value
1380 * as unknown in assigned_value.
1382 void PetScan::mark_write(struct pet_expr *access)
1384 isl_id *id;
1385 ValueDecl *decl;
1387 if (!access)
1388 return;
1390 access->acc.write = 1;
1391 access->acc.read = 0;
1393 if (!pet_expr_is_scalar_access(access))
1394 return;
1396 id = pet_expr_access_get_id(access);
1397 decl = (ValueDecl *) isl_id_get_user(id);
1398 clear_assignment(assigned_value, decl);
1399 isl_id_free(id);
1402 /* Assign "rhs" to "lhs".
1404 * In particular, if "lhs" is a scalar variable, then mark
1405 * the variable as having been assigned. If, furthermore, "rhs"
1406 * is an affine expression, then keep track of this value in assigned_value
1407 * so that we can plug it in when we later come across the same variable.
1409 void PetScan::assign(struct pet_expr *lhs, Expr *rhs)
1411 isl_id *id;
1412 ValueDecl *decl;
1413 isl_pw_aff *pa;
1415 if (!lhs)
1416 return;
1417 if (!pet_expr_is_scalar_access(lhs))
1418 return;
1420 id = pet_expr_access_get_id(lhs);
1421 decl = (ValueDecl *) isl_id_get_user(id);
1422 isl_id_free(id);
1424 pa = try_extract_affine(rhs);
1425 clear_assignment(assigned_value, decl);
1426 if (!pa)
1427 return;
1428 assigned_value[decl] = pa;
1429 insert_expression(pa);
1432 /* Construct a pet_expr representing a binary operator expression.
1434 * If the top level operator is an assignment and the LHS is an access,
1435 * then we mark that access as a write. If the operator is a compound
1436 * assignment, the access is marked as both a read and a write.
1438 * If "expr" assigns something to a scalar variable, then we mark
1439 * the variable as having been assigned. If, furthermore, the expression
1440 * is affine, then keep track of this value in assigned_value
1441 * so that we can plug it in when we later come across the same variable.
1443 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1445 struct pet_expr *lhs, *rhs;
1446 enum pet_op_type op;
1448 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1449 if (op == pet_op_last) {
1450 unsupported(expr);
1451 return NULL;
1454 lhs = extract_expr(expr->getLHS());
1455 rhs = extract_expr(expr->getRHS());
1457 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1458 mark_write(lhs);
1459 if (expr->isCompoundAssignmentOp())
1460 lhs->acc.read = 1;
1463 if (expr->getOpcode() == BO_Assign)
1464 assign(lhs, expr->getRHS());
1466 return pet_expr_new_binary(ctx, op, lhs, rhs);
1469 /* Construct a pet_scop with a single statement killing the entire
1470 * array "array".
1472 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1474 isl_id *id;
1475 isl_space *space;
1476 isl_multi_pw_aff *index;
1477 isl_map *access;
1478 struct pet_expr *expr;
1480 if (!array)
1481 return NULL;
1482 access = isl_map_from_range(isl_set_copy(array->extent));
1483 id = isl_set_get_tuple_id(array->extent);
1484 space = isl_space_alloc(ctx, 0, 0, 0);
1485 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1486 index = isl_multi_pw_aff_zero(space);
1487 expr = pet_expr_kill_from_access_and_index(access, index);
1488 return extract(stmt, expr);
1491 /* Construct a pet_scop for a (single) variable declaration.
1493 * The scop contains the variable being declared (as an array)
1494 * and a statement killing the array.
1496 * If the variable is initialized in the AST, then the scop
1497 * also contains an assignment to the variable.
1499 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1501 Decl *decl;
1502 VarDecl *vd;
1503 struct pet_expr *lhs, *rhs, *pe;
1504 struct pet_scop *scop_decl, *scop;
1505 struct pet_array *array;
1507 if (!stmt->isSingleDecl()) {
1508 unsupported(stmt);
1509 return NULL;
1512 decl = stmt->getSingleDecl();
1513 vd = cast<VarDecl>(decl);
1515 array = extract_array(ctx, vd);
1516 if (array)
1517 array->declared = 1;
1518 scop_decl = kill(stmt, array);
1519 scop_decl = pet_scop_add_array(scop_decl, array);
1521 if (!vd->getInit())
1522 return scop_decl;
1524 lhs = extract_access_expr(vd);
1525 rhs = extract_expr(vd->getInit());
1527 mark_write(lhs);
1528 assign(lhs, vd->getInit());
1530 pe = pet_expr_new_binary(ctx, pet_op_assign, lhs, rhs);
1531 scop = extract(stmt, pe);
1533 scop_decl = pet_scop_prefix(scop_decl, 0);
1534 scop = pet_scop_prefix(scop, 1);
1536 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1538 return scop;
1541 /* Construct a pet_expr representing a conditional operation.
1543 * We first try to extract the condition as an affine expression.
1544 * If that fails, we construct a pet_expr tree representing the condition.
1546 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1548 struct pet_expr *cond, *lhs, *rhs;
1549 isl_pw_aff *pa;
1551 pa = try_extract_affine(expr->getCond());
1552 if (pa) {
1553 isl_multi_pw_aff *test = isl_multi_pw_aff_from_pw_aff(pa);
1554 test = isl_multi_pw_aff_from_range(test);
1555 cond = pet_expr_from_index(test);
1556 } else
1557 cond = extract_expr(expr->getCond());
1558 lhs = extract_expr(expr->getTrueExpr());
1559 rhs = extract_expr(expr->getFalseExpr());
1561 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1564 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1566 return extract_expr(expr->getSubExpr());
1569 /* Construct a pet_expr representing a floating point value.
1571 * If the floating point literal does not appear in a macro,
1572 * then we use the original representation in the source code
1573 * as the string representation. Otherwise, we use the pretty
1574 * printer to produce a string representation.
1576 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1578 double d;
1579 string s;
1580 const LangOptions &LO = PP.getLangOpts();
1581 SourceLocation loc = expr->getLocation();
1583 if (!loc.isMacroID()) {
1584 SourceManager &SM = PP.getSourceManager();
1585 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1586 s = string(SM.getCharacterData(loc), len);
1587 } else {
1588 llvm::raw_string_ostream S(s);
1589 expr->printPretty(S, 0, PrintingPolicy(LO));
1590 S.str();
1592 d = expr->getValueAsApproximateDouble();
1593 return pet_expr_new_double(ctx, d, s.c_str());
1596 /* Extract an index expression from "expr" and then convert it into
1597 * an access pet_expr.
1599 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1601 isl_multi_pw_aff *index;
1602 struct pet_expr *pe;
1603 int depth;
1605 index = extract_index(expr);
1606 depth = extract_depth(index);
1608 pe = pet_expr_from_index_and_depth(index, depth);
1610 return pe;
1613 /* Extract an index expression from "decl" and then convert it into
1614 * an access pet_expr.
1616 struct pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1618 isl_multi_pw_aff *index;
1619 struct pet_expr *pe;
1620 int depth;
1622 index = extract_index(decl);
1623 depth = extract_depth(index);
1625 pe = pet_expr_from_index_and_depth(index, depth);
1627 return pe;
1630 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1632 return extract_expr(expr->getSubExpr());
1635 /* Construct a pet_expr representing a function call.
1637 * If we are passing along a pointer to an array element
1638 * or an entire row or even higher dimensional slice of an array,
1639 * then the function being called may write into the array.
1641 * We assume here that if the function is declared to take a pointer
1642 * to a const type, then the function will perform a read
1643 * and that otherwise, it will perform a write.
1645 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1647 struct pet_expr *res = NULL;
1648 FunctionDecl *fd;
1649 string name;
1651 fd = expr->getDirectCallee();
1652 if (!fd) {
1653 unsupported(expr);
1654 return NULL;
1657 name = fd->getDeclName().getAsString();
1658 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1659 if (!res)
1660 return NULL;
1662 for (int i = 0; i < expr->getNumArgs(); ++i) {
1663 Expr *arg = expr->getArg(i);
1664 int is_addr = 0;
1665 pet_expr *main_arg;
1667 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1668 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1669 arg = ice->getSubExpr();
1671 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1672 UnaryOperator *op = cast<UnaryOperator>(arg);
1673 if (op->getOpcode() == UO_AddrOf) {
1674 is_addr = 1;
1675 arg = op->getSubExpr();
1678 res->args[i] = PetScan::extract_expr(arg);
1679 main_arg = res->args[i];
1680 if (is_addr)
1681 res->args[i] = pet_expr_new_unary(ctx,
1682 pet_op_address_of, res->args[i]);
1683 if (!res->args[i])
1684 goto error;
1685 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1686 array_depth(arg->getType().getTypePtr()) > 0)
1687 is_addr = 1;
1688 if (is_addr && main_arg->type == pet_expr_access) {
1689 ParmVarDecl *parm;
1690 if (!fd->hasPrototype()) {
1691 unsupported(expr, "prototype required");
1692 goto error;
1694 parm = fd->getParamDecl(i);
1695 if (!const_base(parm->getType()))
1696 mark_write(main_arg);
1700 return res;
1701 error:
1702 pet_expr_free(res);
1703 return NULL;
1706 /* Construct a pet_expr representing a (C style) cast.
1708 struct pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1710 struct pet_expr *arg;
1711 QualType type;
1713 arg = extract_expr(expr->getSubExpr());
1714 if (!arg)
1715 return NULL;
1717 type = expr->getTypeAsWritten();
1718 return pet_expr_new_cast(ctx, type.getAsString().c_str(), arg);
1721 /* Try and onstruct a pet_expr representing "expr".
1723 struct pet_expr *PetScan::extract_expr(Expr *expr)
1725 switch (expr->getStmtClass()) {
1726 case Stmt::UnaryOperatorClass:
1727 return extract_expr(cast<UnaryOperator>(expr));
1728 case Stmt::CompoundAssignOperatorClass:
1729 case Stmt::BinaryOperatorClass:
1730 return extract_expr(cast<BinaryOperator>(expr));
1731 case Stmt::ImplicitCastExprClass:
1732 return extract_expr(cast<ImplicitCastExpr>(expr));
1733 case Stmt::ArraySubscriptExprClass:
1734 case Stmt::DeclRefExprClass:
1735 case Stmt::IntegerLiteralClass:
1736 return extract_access_expr(expr);
1737 case Stmt::FloatingLiteralClass:
1738 return extract_expr(cast<FloatingLiteral>(expr));
1739 case Stmt::ParenExprClass:
1740 return extract_expr(cast<ParenExpr>(expr));
1741 case Stmt::ConditionalOperatorClass:
1742 return extract_expr(cast<ConditionalOperator>(expr));
1743 case Stmt::CallExprClass:
1744 return extract_expr(cast<CallExpr>(expr));
1745 case Stmt::CStyleCastExprClass:
1746 return extract_expr(cast<CStyleCastExpr>(expr));
1747 default:
1748 unsupported(expr);
1750 return NULL;
1753 /* Check if the given initialization statement is an assignment.
1754 * If so, return that assignment. Otherwise return NULL.
1756 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1758 BinaryOperator *ass;
1760 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1761 return NULL;
1763 ass = cast<BinaryOperator>(init);
1764 if (ass->getOpcode() != BO_Assign)
1765 return NULL;
1767 return ass;
1770 /* Check if the given initialization statement is a declaration
1771 * of a single variable.
1772 * If so, return that declaration. Otherwise return NULL.
1774 Decl *PetScan::initialization_declaration(Stmt *init)
1776 DeclStmt *decl;
1778 if (init->getStmtClass() != Stmt::DeclStmtClass)
1779 return NULL;
1781 decl = cast<DeclStmt>(init);
1783 if (!decl->isSingleDecl())
1784 return NULL;
1786 return decl->getSingleDecl();
1789 /* Given the assignment operator in the initialization of a for loop,
1790 * extract the induction variable, i.e., the (integer)variable being
1791 * assigned.
1793 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1795 Expr *lhs;
1796 DeclRefExpr *ref;
1797 ValueDecl *decl;
1798 const Type *type;
1800 lhs = init->getLHS();
1801 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1802 unsupported(init);
1803 return NULL;
1806 ref = cast<DeclRefExpr>(lhs);
1807 decl = ref->getDecl();
1808 type = decl->getType().getTypePtr();
1810 if (!type->isIntegerType()) {
1811 unsupported(lhs);
1812 return NULL;
1815 return decl;
1818 /* Given the initialization statement of a for loop and the single
1819 * declaration in this initialization statement,
1820 * extract the induction variable, i.e., the (integer) variable being
1821 * declared.
1823 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1825 VarDecl *vd;
1827 vd = cast<VarDecl>(decl);
1829 const QualType type = vd->getType();
1830 if (!type->isIntegerType()) {
1831 unsupported(init);
1832 return NULL;
1835 if (!vd->getInit()) {
1836 unsupported(init);
1837 return NULL;
1840 return vd;
1843 /* Check that op is of the form iv++ or iv--.
1844 * Return an affine expression "1" or "-1" accordingly.
1846 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
1847 clang::UnaryOperator *op, clang::ValueDecl *iv)
1849 Expr *sub;
1850 DeclRefExpr *ref;
1851 isl_space *space;
1852 isl_aff *aff;
1854 if (!op->isIncrementDecrementOp()) {
1855 unsupported(op);
1856 return NULL;
1859 sub = op->getSubExpr();
1860 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1861 unsupported(op);
1862 return NULL;
1865 ref = cast<DeclRefExpr>(sub);
1866 if (ref->getDecl() != iv) {
1867 unsupported(op);
1868 return NULL;
1871 space = isl_space_params_alloc(ctx, 0);
1872 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1874 if (op->isIncrementOp())
1875 aff = isl_aff_add_constant_si(aff, 1);
1876 else
1877 aff = isl_aff_add_constant_si(aff, -1);
1879 return isl_pw_aff_from_aff(aff);
1882 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1883 * has a single constant expression, then put this constant in *user.
1884 * The caller is assumed to have checked that this function will
1885 * be called exactly once.
1887 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1888 void *user)
1890 isl_val **inc = (isl_val **)user;
1891 int res = 0;
1893 if (isl_aff_is_cst(aff))
1894 *inc = isl_aff_get_constant_val(aff);
1895 else
1896 res = -1;
1898 isl_set_free(set);
1899 isl_aff_free(aff);
1901 return res;
1904 /* Check if op is of the form
1906 * iv = iv + inc
1908 * and return inc as an affine expression.
1910 * We extract an affine expression from the RHS, subtract iv and return
1911 * the result.
1913 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
1914 clang::ValueDecl *iv)
1916 Expr *lhs;
1917 DeclRefExpr *ref;
1918 isl_id *id;
1919 isl_space *dim;
1920 isl_aff *aff;
1921 isl_pw_aff *val;
1923 if (op->getOpcode() != BO_Assign) {
1924 unsupported(op);
1925 return NULL;
1928 lhs = op->getLHS();
1929 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1930 unsupported(op);
1931 return NULL;
1934 ref = cast<DeclRefExpr>(lhs);
1935 if (ref->getDecl() != iv) {
1936 unsupported(op);
1937 return NULL;
1940 val = extract_affine(op->getRHS());
1942 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1944 dim = isl_space_params_alloc(ctx, 1);
1945 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1946 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1947 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1949 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1951 return val;
1954 /* Check that op is of the form iv += cst or iv -= cst
1955 * and return an affine expression corresponding oto cst or -cst accordingly.
1957 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
1958 CompoundAssignOperator *op, clang::ValueDecl *iv)
1960 Expr *lhs;
1961 DeclRefExpr *ref;
1962 bool neg = false;
1963 isl_pw_aff *val;
1964 BinaryOperatorKind opcode;
1966 opcode = op->getOpcode();
1967 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1968 unsupported(op);
1969 return NULL;
1971 if (opcode == BO_SubAssign)
1972 neg = true;
1974 lhs = op->getLHS();
1975 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1976 unsupported(op);
1977 return NULL;
1980 ref = cast<DeclRefExpr>(lhs);
1981 if (ref->getDecl() != iv) {
1982 unsupported(op);
1983 return NULL;
1986 val = extract_affine(op->getRHS());
1987 if (neg)
1988 val = isl_pw_aff_neg(val);
1990 return val;
1993 /* Check that the increment of the given for loop increments
1994 * (or decrements) the induction variable "iv" and return
1995 * the increment as an affine expression if successful.
1997 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
1998 ValueDecl *iv)
2000 Stmt *inc = stmt->getInc();
2002 if (!inc) {
2003 unsupported(stmt);
2004 return NULL;
2007 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
2008 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
2009 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
2010 return extract_compound_increment(
2011 cast<CompoundAssignOperator>(inc), iv);
2012 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
2013 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
2015 unsupported(inc);
2016 return NULL;
2019 /* Embed the given iteration domain in an extra outer loop
2020 * with induction variable "var".
2021 * If this variable appeared as a parameter in the constraints,
2022 * it is replaced by the new outermost dimension.
2024 static __isl_give isl_set *embed(__isl_take isl_set *set,
2025 __isl_take isl_id *var)
2027 int pos;
2029 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
2030 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
2031 if (pos >= 0) {
2032 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
2033 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2036 isl_id_free(var);
2037 return set;
2040 /* Return those elements in the space of "cond" that come after
2041 * (based on "sign") an element in "cond".
2043 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
2045 isl_map *previous_to_this;
2047 if (sign > 0)
2048 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
2049 else
2050 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
2052 cond = isl_set_apply(cond, previous_to_this);
2054 return cond;
2057 /* Create the infinite iteration domain
2059 * { [id] : id >= 0 }
2061 * If "scop" has an affine skip of type pet_skip_later,
2062 * then remove those iterations i that have an earlier iteration
2063 * where the skip condition is satisfied, meaning that iteration i
2064 * is not executed.
2065 * Since we are dealing with a loop without loop iterator,
2066 * the skip condition cannot refer to the current loop iterator and
2067 * so effectively, the returned set is of the form
2069 * { [0]; [id] : id >= 1 and not skip }
2071 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
2072 struct pet_scop *scop)
2074 isl_ctx *ctx = isl_id_get_ctx(id);
2075 isl_set *domain;
2076 isl_set *skip;
2078 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
2079 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
2081 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
2082 return domain;
2084 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2085 skip = embed(skip, isl_id_copy(id));
2086 skip = isl_set_intersect(skip , isl_set_copy(domain));
2087 domain = isl_set_subtract(domain, after(skip, 1));
2089 return domain;
2092 /* Create an identity affine expression on the space containing "domain",
2093 * which is assumed to be one-dimensional.
2095 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
2097 isl_local_space *ls;
2099 ls = isl_local_space_from_space(isl_set_get_space(domain));
2100 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
2103 /* Create an affine expression that maps elements
2104 * of a single-dimensional array "id_test" to the previous element
2105 * (according to "inc"), provided this element belongs to "domain".
2106 * That is, create the affine expression
2108 * { id[x] -> id[x - inc] : x - inc in domain }
2110 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
2111 __isl_take isl_set *domain, __isl_take isl_val *inc)
2113 isl_space *space;
2114 isl_local_space *ls;
2115 isl_aff *aff;
2116 isl_multi_pw_aff *prev;
2118 space = isl_set_get_space(domain);
2119 ls = isl_local_space_from_space(space);
2120 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2121 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
2122 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
2123 domain = isl_set_preimage_multi_pw_aff(domain,
2124 isl_multi_pw_aff_copy(prev));
2125 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
2126 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
2128 return prev;
2131 /* Add an implication to "scop" expressing that if an element of
2132 * virtual array "id_test" has value "satisfied" then all previous elements
2133 * of this array also have that value. The set of previous elements
2134 * is bounded by "domain". If "sign" is negative then iterator
2135 * is decreasing and we express that all subsequent array elements
2136 * (but still defined previously) have the same value.
2138 static struct pet_scop *add_implication(struct pet_scop *scop,
2139 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
2140 int satisfied)
2142 isl_space *space;
2143 isl_map *map;
2145 domain = isl_set_set_tuple_id(domain, id_test);
2146 space = isl_set_get_space(domain);
2147 if (sign > 0)
2148 map = isl_map_lex_ge(space);
2149 else
2150 map = isl_map_lex_le(space);
2151 map = isl_map_intersect_range(map, domain);
2152 scop = pet_scop_add_implication(scop, map, satisfied);
2154 return scop;
2157 /* Add a filter to "scop" that imposes that it is only executed
2158 * when the variable identified by "id_test" has a zero value
2159 * for all previous iterations of "domain".
2161 * In particular, add a filter that imposes that the array
2162 * has a zero value at the previous iteration of domain and
2163 * add an implication that implies that it then has that
2164 * value for all previous iterations.
2166 static struct pet_scop *scop_add_break(struct pet_scop *scop,
2167 __isl_take isl_id *id_test, __isl_take isl_set *domain,
2168 __isl_take isl_val *inc)
2170 isl_multi_pw_aff *prev;
2171 int sign = isl_val_sgn(inc);
2173 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2174 scop = add_implication(scop, id_test, domain, sign, 0);
2175 scop = pet_scop_filter(scop, prev, 0);
2177 return scop;
2180 /* Construct a pet_scop for an infinite loop around the given body.
2182 * We extract a pet_scop for the body and then embed it in a loop with
2183 * iteration domain
2185 * { [t] : t >= 0 }
2187 * and schedule
2189 * { [t] -> [t] }
2191 * If the body contains any break, then it is taken into
2192 * account in infinite_domain (if the skip condition is affine)
2193 * or in scop_add_break (if the skip condition is not affine).
2195 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2197 isl_id *id, *id_test;
2198 isl_set *domain;
2199 isl_aff *ident;
2200 struct pet_scop *scop;
2201 bool has_var_break;
2203 scop = extract(body);
2204 if (!scop)
2205 return NULL;
2207 id = isl_id_alloc(ctx, "t", NULL);
2208 domain = infinite_domain(isl_id_copy(id), scop);
2209 ident = identity_aff(domain);
2211 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2212 if (has_var_break)
2213 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
2215 scop = pet_scop_embed(scop, isl_set_copy(domain),
2216 isl_map_from_aff(isl_aff_copy(ident)), ident, id);
2217 if (has_var_break)
2218 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
2219 else
2220 isl_set_free(domain);
2222 return scop;
2225 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2227 * for (;;)
2228 * body
2231 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2233 return extract_infinite_loop(stmt->getBody());
2236 /* Create an index expression for an access to a virtual array
2237 * representing the result of a condition.
2238 * Unlike other accessed data, the id of the array is NULL as
2239 * there is no ValueDecl in the program corresponding to the virtual
2240 * array.
2241 * The array starts out as a scalar, but grows along with the
2242 * statement writing to the array in pet_scop_embed.
2244 static __isl_give isl_multi_pw_aff *create_test_index(isl_ctx *ctx, int test_nr)
2246 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2247 isl_id *id;
2248 char name[50];
2250 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2251 id = isl_id_alloc(ctx, name, NULL);
2252 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2253 return isl_multi_pw_aff_zero(dim);
2256 /* Add an array with the given extent (range of "index") to the list
2257 * of arrays in "scop" and return the extended pet_scop.
2258 * The array is marked as attaining values 0 and 1 only and
2259 * as each element being assigned at most once.
2261 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2262 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
2264 isl_ctx *ctx = isl_multi_pw_aff_get_ctx(index);
2265 isl_space *dim;
2266 struct pet_array *array;
2267 isl_map *access;
2269 if (!scop)
2270 return NULL;
2271 if (!ctx)
2272 goto error;
2274 array = isl_calloc_type(ctx, struct pet_array);
2275 if (!array)
2276 goto error;
2278 access = isl_map_from_multi_pw_aff(isl_multi_pw_aff_copy(index));
2279 array->extent = isl_map_range(access);
2280 dim = isl_space_params_alloc(ctx, 0);
2281 array->context = isl_set_universe(dim);
2282 dim = isl_space_set_alloc(ctx, 0, 1);
2283 array->value_bounds = isl_set_universe(dim);
2284 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2285 isl_dim_set, 0, 0);
2286 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2287 isl_dim_set, 0, 1);
2288 array->element_type = strdup("int");
2289 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2290 array->uniquely_defined = 1;
2292 if (!array->extent || !array->context)
2293 array = pet_array_free(array);
2295 scop = pet_scop_add_array(scop, array);
2297 return scop;
2298 error:
2299 pet_scop_free(scop);
2300 return NULL;
2303 /* Construct a pet_scop for a while loop of the form
2305 * while (pa)
2306 * body
2308 * In particular, construct a scop for an infinite loop around body and
2309 * intersect the domain with the affine expression.
2310 * Note that this intersection may result in an empty loop.
2312 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2313 Stmt *body)
2315 struct pet_scop *scop;
2316 isl_set *dom;
2317 isl_set *valid;
2319 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2320 dom = isl_pw_aff_non_zero_set(pa);
2321 scop = extract_infinite_loop(body);
2322 scop = pet_scop_restrict(scop, dom);
2323 scop = pet_scop_restrict_context(scop, valid);
2325 return scop;
2328 /* Construct a scop for a while, given the scops for the condition
2329 * and the body, the filter identifier and the iteration domain of
2330 * the while loop.
2332 * In particular, the scop for the condition is filtered to depend
2333 * on "id_test" evaluating to true for all previous iterations
2334 * of the loop, while the scop for the body is filtered to depend
2335 * on "id_test" evaluating to true for all iterations up to the
2336 * current iteration.
2337 * The actual filter only imposes that this virtual array has
2338 * value one on the previous or the current iteration.
2339 * The fact that this condition also applies to the previous
2340 * iterations is enforced by an implication.
2342 * These filtered scops are then combined into a single scop.
2344 * "sign" is positive if the iterator increases and negative
2345 * if it decreases.
2347 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2348 struct pet_scop *scop_body, __isl_take isl_id *id_test,
2349 __isl_take isl_set *domain, __isl_take isl_val *inc)
2351 isl_ctx *ctx = isl_set_get_ctx(domain);
2352 isl_space *space;
2353 isl_multi_pw_aff *test_index;
2354 isl_multi_pw_aff *prev;
2355 int sign = isl_val_sgn(inc);
2356 struct pet_scop *scop;
2358 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2359 scop_cond = pet_scop_filter(scop_cond, prev, 1);
2361 space = isl_space_map_from_set(isl_set_get_space(domain));
2362 test_index = isl_multi_pw_aff_identity(space);
2363 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
2364 isl_id_copy(id_test));
2365 scop_body = pet_scop_filter(scop_body, test_index, 1);
2367 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
2368 scop = add_implication(scop, id_test, domain, sign, 1);
2370 return scop;
2373 /* Check if the while loop is of the form
2375 * while (affine expression)
2376 * body
2378 * If so, call extract_affine_while to construct a scop.
2380 * Otherwise, construct a generic while scop, with iteration domain
2381 * { [t] : t >= 0 }. The scop consists of two parts, one for
2382 * evaluating the condition and one for the body.
2383 * The schedule is adjusted to reflect that the condition is evaluated
2384 * before the body is executed and the body is filtered to depend
2385 * on the result of the condition evaluating to true on all iterations
2386 * up to the current iteration, while the evaluation the condition itself
2387 * is filtered to depend on the result of the condition evaluating to true
2388 * on all previous iterations.
2389 * The context of the scop representing the body is dropped
2390 * because we don't know how many times the body will be executed,
2391 * if at all.
2393 * If the body contains any break, then it is taken into
2394 * account in infinite_domain (if the skip condition is affine)
2395 * or in scop_add_break (if the skip condition is not affine).
2397 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2399 Expr *cond;
2400 isl_id *id, *id_test, *id_break_test;
2401 isl_multi_pw_aff *test_index;
2402 isl_set *domain;
2403 isl_aff *ident;
2404 isl_pw_aff *pa;
2405 struct pet_scop *scop, *scop_body;
2406 bool has_var_break;
2408 cond = stmt->getCond();
2409 if (!cond) {
2410 unsupported(stmt);
2411 return NULL;
2414 clear_assignments clear(assigned_value);
2415 clear.TraverseStmt(stmt->getBody());
2417 pa = try_extract_affine_condition(cond);
2418 if (pa)
2419 return extract_affine_while(pa, stmt->getBody());
2421 if (!allow_nested) {
2422 unsupported(stmt);
2423 return NULL;
2426 test_index = create_test_index(ctx, n_test++);
2427 scop = extract_non_affine_condition(cond,
2428 isl_multi_pw_aff_copy(test_index));
2429 scop = scop_add_array(scop, test_index, ast_context);
2430 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2431 isl_multi_pw_aff_free(test_index);
2432 scop_body = extract(stmt->getBody());
2434 id = isl_id_alloc(ctx, "t", NULL);
2435 domain = infinite_domain(isl_id_copy(id), scop_body);
2436 ident = identity_aff(domain);
2438 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2439 if (has_var_break)
2440 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2442 scop = pet_scop_prefix(scop, 0);
2443 scop = pet_scop_embed(scop, isl_set_copy(domain),
2444 isl_map_from_aff(isl_aff_copy(ident)),
2445 isl_aff_copy(ident), isl_id_copy(id));
2446 scop_body = pet_scop_reset_context(scop_body);
2447 scop_body = pet_scop_prefix(scop_body, 1);
2448 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2449 isl_map_from_aff(isl_aff_copy(ident)), ident, id);
2451 if (has_var_break) {
2452 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2453 isl_set_copy(domain), isl_val_one(ctx));
2454 scop_body = scop_add_break(scop_body, id_break_test,
2455 isl_set_copy(domain), isl_val_one(ctx));
2457 scop = scop_add_while(scop, scop_body, id_test, domain,
2458 isl_val_one(ctx));
2460 return scop;
2463 /* Check whether "cond" expresses a simple loop bound
2464 * on the only set dimension.
2465 * In particular, if "up" is set then "cond" should contain only
2466 * upper bounds on the set dimension.
2467 * Otherwise, it should contain only lower bounds.
2469 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2471 if (isl_val_is_pos(inc))
2472 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2473 else
2474 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2477 /* Extend a condition on a given iteration of a loop to one that
2478 * imposes the same condition on all previous iterations.
2479 * "domain" expresses the lower [upper] bound on the iterations
2480 * when inc is positive [negative].
2482 * In particular, we construct the condition (when inc is positive)
2484 * forall i' : (domain(i') and i' <= i) => cond(i')
2486 * which is equivalent to
2488 * not exists i' : domain(i') and i' <= i and not cond(i')
2490 * We construct this set by negating cond, applying a map
2492 * { [i'] -> [i] : domain(i') and i' <= i }
2494 * and then negating the result again.
2496 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2497 __isl_take isl_set *domain, __isl_take isl_val *inc)
2499 isl_map *previous_to_this;
2501 if (isl_val_is_pos(inc))
2502 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2503 else
2504 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2506 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2508 cond = isl_set_complement(cond);
2509 cond = isl_set_apply(cond, previous_to_this);
2510 cond = isl_set_complement(cond);
2512 isl_val_free(inc);
2514 return cond;
2517 /* Construct a domain of the form
2519 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2521 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2522 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2524 isl_aff *aff;
2525 isl_space *dim;
2526 isl_set *set;
2528 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2529 dim = isl_pw_aff_get_domain_space(init);
2530 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2531 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2532 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2534 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2535 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2536 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2537 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2539 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2541 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2543 return isl_set_params(set);
2546 /* Assuming "cond" represents a bound on a loop where the loop
2547 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2548 * is possible.
2550 * Under the given assumptions, wrapping is only possible if "cond" allows
2551 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2552 * increasing iterator and 0 in case of a decreasing iterator.
2554 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2555 __isl_keep isl_val *inc)
2557 bool cw;
2558 isl_ctx *ctx;
2559 isl_val *limit;
2560 isl_set *test;
2562 test = isl_set_copy(cond);
2564 ctx = isl_set_get_ctx(test);
2565 if (isl_val_is_neg(inc))
2566 limit = isl_val_zero(ctx);
2567 else {
2568 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2569 limit = isl_val_2exp(limit);
2570 limit = isl_val_sub_ui(limit, 1);
2573 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2574 cw = !isl_set_is_empty(test);
2575 isl_set_free(test);
2577 return cw;
2580 /* Given a one-dimensional space, construct the following affine expression
2581 * on this space
2583 * { [v] -> [v mod 2^width] }
2585 * where width is the number of bits used to represent the values
2586 * of the unsigned variable "iv".
2588 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2589 ValueDecl *iv)
2591 isl_ctx *ctx;
2592 isl_val *mod;
2593 isl_aff *aff;
2594 isl_map *map;
2596 ctx = isl_space_get_ctx(dim);
2597 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2598 mod = isl_val_2exp(mod);
2600 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2601 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2602 aff = isl_aff_mod_val(aff, mod);
2604 return aff;
2607 /* Project out the parameter "id" from "set".
2609 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2610 __isl_keep isl_id *id)
2612 int pos;
2614 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2615 if (pos >= 0)
2616 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2618 return set;
2621 /* Compute the set of parameters for which "set1" is a subset of "set2".
2623 * set1 is a subset of set2 if
2625 * forall i in set1 : i in set2
2627 * or
2629 * not exists i in set1 and i not in set2
2631 * i.e.,
2633 * not exists i in set1 \ set2
2635 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2636 __isl_take isl_set *set2)
2638 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2641 /* Compute the set of parameter values for which "cond" holds
2642 * on the next iteration for each element of "dom".
2644 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2645 * and then compute the set of parameters for which the result is a subset
2646 * of "cond".
2648 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2649 __isl_take isl_set *dom, __isl_take isl_val *inc)
2651 isl_space *space;
2652 isl_aff *aff;
2653 isl_map *next;
2655 space = isl_set_get_space(dom);
2656 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2657 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2658 aff = isl_aff_add_constant_val(aff, inc);
2659 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2661 dom = isl_set_apply(dom, next);
2663 return enforce_subset(dom, cond);
2666 /* Does "id" refer to a nested access?
2668 static bool is_nested_parameter(__isl_keep isl_id *id)
2670 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2673 /* Does parameter "pos" of "space" refer to a nested access?
2675 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2677 bool nested;
2678 isl_id *id;
2680 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2681 nested = is_nested_parameter(id);
2682 isl_id_free(id);
2684 return nested;
2687 /* Does "space" involve any parameters that refer to nested
2688 * accesses, i.e., parameters with no name?
2690 static bool has_nested(__isl_keep isl_space *space)
2692 int nparam;
2694 nparam = isl_space_dim(space, isl_dim_param);
2695 for (int i = 0; i < nparam; ++i)
2696 if (is_nested_parameter(space, i))
2697 return true;
2699 return false;
2702 /* Does "pa" involve any parameters that refer to nested
2703 * accesses, i.e., parameters with no name?
2705 static bool has_nested(__isl_keep isl_pw_aff *pa)
2707 isl_space *space;
2708 bool nested;
2710 space = isl_pw_aff_get_space(pa);
2711 nested = has_nested(space);
2712 isl_space_free(space);
2714 return nested;
2717 /* Construct a pet_scop for a for statement.
2718 * The for loop is required to be of the form
2720 * for (i = init; condition; ++i)
2722 * or
2724 * for (i = init; condition; --i)
2726 * The initialization of the for loop should either be an assignment
2727 * to an integer variable, or a declaration of such a variable with
2728 * initialization.
2730 * The condition is allowed to contain nested accesses, provided
2731 * they are not being written to inside the body of the loop.
2732 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2733 * essentially treated as a while loop, with iteration domain
2734 * { [i] : i >= init }.
2736 * We extract a pet_scop for the body and then embed it in a loop with
2737 * iteration domain and schedule
2739 * { [i] : i >= init and condition' }
2740 * { [i] -> [i] }
2742 * or
2744 * { [i] : i <= init and condition' }
2745 * { [i] -> [-i] }
2747 * Where condition' is equal to condition if the latter is
2748 * a simple upper [lower] bound and a condition that is extended
2749 * to apply to all previous iterations otherwise.
2751 * If the condition is non-affine, then we drop the condition from the
2752 * iteration domain and instead create a separate statement
2753 * for evaluating the condition. The body is then filtered to depend
2754 * on the result of the condition evaluating to true on all iterations
2755 * up to the current iteration, while the evaluation the condition itself
2756 * is filtered to depend on the result of the condition evaluating to true
2757 * on all previous iterations.
2758 * The context of the scop representing the body is dropped
2759 * because we don't know how many times the body will be executed,
2760 * if at all.
2762 * If the stride of the loop is not 1, then "i >= init" is replaced by
2764 * (exists a: i = init + stride * a and a >= 0)
2766 * If the loop iterator i is unsigned, then wrapping may occur.
2767 * During the computation, we work with a virtual iterator that
2768 * does not wrap. However, the condition in the code applies
2769 * to the wrapped value, so we need to change condition(i)
2770 * into condition([i % 2^width]).
2771 * After computing the virtual domain and schedule, we apply
2772 * the function { [v] -> [v % 2^width] } to the domain and the domain
2773 * of the schedule. In order not to lose any information, we also
2774 * need to intersect the domain of the schedule with the virtual domain
2775 * first, since some iterations in the wrapped domain may be scheduled
2776 * several times, typically an infinite number of times.
2777 * Note that there may be no need to perform this final wrapping
2778 * if the loop condition (after wrapping) satisfies certain conditions.
2779 * However, the is_simple_bound condition is not enough since it doesn't
2780 * check if there even is an upper bound.
2782 * If the loop condition is non-affine, then we keep the virtual
2783 * iterator in the iteration domain and instead replace all accesses
2784 * to the original iterator by the wrapping of the virtual iterator.
2786 * Wrapping on unsigned iterators can be avoided entirely if
2787 * loop condition is simple, the loop iterator is incremented
2788 * [decremented] by one and the last value before wrapping cannot
2789 * possibly satisfy the loop condition.
2791 * Before extracting a pet_scop from the body we remove all
2792 * assignments in assigned_value to variables that are assigned
2793 * somewhere in the body of the loop.
2795 * Valid parameters for a for loop are those for which the initial
2796 * value itself, the increment on each domain iteration and
2797 * the condition on both the initial value and
2798 * the result of incrementing the iterator for each iteration of the domain
2799 * can be evaluated.
2800 * If the loop condition is non-affine, then we only consider validity
2801 * of the initial value.
2803 * If the body contains any break, then we keep track of it in "skip"
2804 * (if the skip condition is affine) or it is handled in scop_add_break
2805 * (if the skip condition is not affine).
2806 * Note that the affine break condition needs to be considered with
2807 * respect to previous iterations in the virtual domain (if any)
2808 * and that the domain needs to be kept virtual if there is a non-affine
2809 * break condition.
2811 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2813 BinaryOperator *ass;
2814 Decl *decl;
2815 Stmt *init;
2816 Expr *lhs, *rhs;
2817 ValueDecl *iv;
2818 isl_space *space;
2819 isl_set *domain;
2820 isl_map *sched;
2821 isl_set *cond = NULL;
2822 isl_set *skip = NULL;
2823 isl_id *id, *id_test = NULL, *id_break_test;
2824 struct pet_scop *scop, *scop_cond = NULL;
2825 assigned_value_cache cache(assigned_value);
2826 isl_val *inc;
2827 bool is_one;
2828 bool is_unsigned;
2829 bool is_simple;
2830 bool is_virtual;
2831 bool keep_virtual = false;
2832 bool has_affine_break;
2833 bool has_var_break;
2834 isl_aff *wrap = NULL;
2835 isl_pw_aff *pa, *pa_inc, *init_val;
2836 isl_set *valid_init;
2837 isl_set *valid_cond;
2838 isl_set *valid_cond_init;
2839 isl_set *valid_cond_next;
2840 isl_set *valid_inc;
2841 int stmt_id;
2843 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2844 return extract_infinite_for(stmt);
2846 init = stmt->getInit();
2847 if (!init) {
2848 unsupported(stmt);
2849 return NULL;
2851 if ((ass = initialization_assignment(init)) != NULL) {
2852 iv = extract_induction_variable(ass);
2853 if (!iv)
2854 return NULL;
2855 lhs = ass->getLHS();
2856 rhs = ass->getRHS();
2857 } else if ((decl = initialization_declaration(init)) != NULL) {
2858 VarDecl *var = extract_induction_variable(init, decl);
2859 if (!var)
2860 return NULL;
2861 iv = var;
2862 rhs = var->getInit();
2863 lhs = create_DeclRefExpr(var);
2864 } else {
2865 unsupported(stmt->getInit());
2866 return NULL;
2869 pa_inc = extract_increment(stmt, iv);
2870 if (!pa_inc)
2871 return NULL;
2873 inc = NULL;
2874 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
2875 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
2876 isl_pw_aff_free(pa_inc);
2877 unsupported(stmt->getInc());
2878 isl_val_free(inc);
2879 return NULL;
2881 valid_inc = isl_pw_aff_domain(pa_inc);
2883 is_unsigned = iv->getType()->isUnsignedIntegerType();
2885 assigned_value.erase(iv);
2886 clear_assignments clear(assigned_value);
2887 clear.TraverseStmt(stmt->getBody());
2889 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2891 pa = try_extract_nested_condition(stmt->getCond());
2892 if (allow_nested && (!pa || has_nested(pa)))
2893 stmt_id = n_stmt++;
2895 scop = extract(stmt->getBody());
2897 has_affine_break = scop &&
2898 pet_scop_has_affine_skip(scop, pet_skip_later);
2899 if (has_affine_break)
2900 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2901 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
2902 if (has_var_break) {
2903 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
2904 keep_virtual = true;
2907 if (pa && !is_nested_allowed(pa, scop)) {
2908 isl_pw_aff_free(pa);
2909 pa = NULL;
2912 if (!allow_nested && !pa)
2913 pa = try_extract_affine_condition(stmt->getCond());
2914 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2915 cond = isl_pw_aff_non_zero_set(pa);
2916 if (allow_nested && !cond) {
2917 isl_multi_pw_aff *test_index;
2918 int save_n_stmt = n_stmt;
2919 test_index = create_test_index(ctx, n_test++);
2920 n_stmt = stmt_id;
2921 scop_cond = extract_non_affine_condition(stmt->getCond(),
2922 isl_multi_pw_aff_copy(test_index));
2923 n_stmt = save_n_stmt;
2924 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
2925 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
2926 isl_dim_out);
2927 isl_multi_pw_aff_free(test_index);
2928 scop_cond = pet_scop_prefix(scop_cond, 0);
2929 scop = pet_scop_reset_context(scop);
2930 scop = pet_scop_prefix(scop, 1);
2931 keep_virtual = true;
2932 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2935 cond = embed(cond, isl_id_copy(id));
2936 skip = embed(skip, isl_id_copy(id));
2937 valid_cond = isl_set_coalesce(valid_cond);
2938 valid_cond = embed(valid_cond, isl_id_copy(id));
2939 valid_inc = embed(valid_inc, isl_id_copy(id));
2940 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
2941 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2943 init_val = extract_affine(rhs);
2944 valid_cond_init = enforce_subset(
2945 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
2946 isl_set_copy(valid_cond));
2947 if (is_one && !is_virtual) {
2948 isl_pw_aff_free(init_val);
2949 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
2950 lhs, rhs, init);
2951 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2952 valid_init = set_project_out_by_id(valid_init, id);
2953 domain = isl_pw_aff_non_zero_set(pa);
2954 } else {
2955 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2956 domain = strided_domain(isl_id_copy(id), init_val,
2957 isl_val_copy(inc));
2960 domain = embed(domain, isl_id_copy(id));
2961 if (is_virtual) {
2962 isl_map *rev_wrap;
2963 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2964 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
2965 rev_wrap = isl_map_reverse(rev_wrap);
2966 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2967 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
2968 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2969 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2971 is_simple = is_simple_bound(cond, inc);
2972 if (!is_simple) {
2973 cond = isl_set_gist(cond, isl_set_copy(domain));
2974 is_simple = is_simple_bound(cond, inc);
2976 if (!is_simple)
2977 cond = valid_for_each_iteration(cond,
2978 isl_set_copy(domain), isl_val_copy(inc));
2979 domain = isl_set_intersect(domain, cond);
2980 if (has_affine_break) {
2981 skip = isl_set_intersect(skip , isl_set_copy(domain));
2982 skip = after(skip, isl_val_sgn(inc));
2983 domain = isl_set_subtract(domain, skip);
2985 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2986 space = isl_space_from_domain(isl_set_get_space(domain));
2987 space = isl_space_add_dims(space, isl_dim_out, 1);
2988 sched = isl_map_universe(space);
2989 if (isl_val_is_pos(inc))
2990 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2991 else
2992 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2994 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
2995 isl_val_copy(inc));
2996 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2998 if (is_virtual && !keep_virtual) {
2999 isl_map *wrap_map = isl_map_from_aff(wrap);
3000 wrap_map = isl_map_set_dim_id(wrap_map,
3001 isl_dim_out, 0, isl_id_copy(id));
3002 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
3003 domain = isl_set_apply(domain, isl_map_copy(wrap_map));
3004 sched = isl_map_apply_domain(sched, wrap_map);
3006 if (!(is_virtual && keep_virtual))
3007 wrap = identity_aff(domain);
3009 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
3010 isl_map_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
3011 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
3012 scop = resolve_nested(scop);
3013 if (has_var_break)
3014 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
3015 isl_val_copy(inc));
3016 if (id_test) {
3017 scop = scop_add_while(scop_cond, scop, id_test, domain,
3018 isl_val_copy(inc));
3019 isl_set_free(valid_inc);
3020 } else {
3021 scop = pet_scop_restrict_context(scop, valid_inc);
3022 scop = pet_scop_restrict_context(scop, valid_cond_next);
3023 scop = pet_scop_restrict_context(scop, valid_cond_init);
3024 isl_set_free(domain);
3026 clear_assignment(assigned_value, iv);
3028 isl_val_free(inc);
3030 scop = pet_scop_restrict_context(scop, valid_init);
3032 return scop;
3035 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
3037 return extract(stmt->children(), true, skip_declarations);
3040 /* Does parameter "pos" of "map" refer to a nested access?
3042 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
3044 bool nested;
3045 isl_id *id;
3047 id = isl_map_get_dim_id(map, isl_dim_param, pos);
3048 nested = is_nested_parameter(id);
3049 isl_id_free(id);
3051 return nested;
3054 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
3056 static int n_nested_parameter(__isl_keep isl_space *space)
3058 int n = 0;
3059 int nparam;
3061 nparam = isl_space_dim(space, isl_dim_param);
3062 for (int i = 0; i < nparam; ++i)
3063 if (is_nested_parameter(space, i))
3064 ++n;
3066 return n;
3069 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
3071 static int n_nested_parameter(__isl_keep isl_map *map)
3073 isl_space *space;
3074 int n;
3076 space = isl_map_get_space(map);
3077 n = n_nested_parameter(space);
3078 isl_space_free(space);
3080 return n;
3083 /* For each nested access parameter in "space",
3084 * construct a corresponding pet_expr, place it in args and
3085 * record its position in "param2pos".
3086 * "n_arg" is the number of elements that are already in args.
3087 * The position recorded in "param2pos" takes this number into account.
3088 * If the pet_expr corresponding to a parameter is identical to
3089 * the pet_expr corresponding to an earlier parameter, then these two
3090 * parameters are made to refer to the same element in args.
3092 * Return the final number of elements in args or -1 if an error has occurred.
3094 int PetScan::extract_nested(__isl_keep isl_space *space,
3095 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
3097 int nparam;
3099 nparam = isl_space_dim(space, isl_dim_param);
3100 for (int i = 0; i < nparam; ++i) {
3101 int j;
3102 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3103 Expr *nested;
3105 if (!is_nested_parameter(id)) {
3106 isl_id_free(id);
3107 continue;
3110 nested = (Expr *) isl_id_get_user(id);
3111 args[n_arg] = extract_expr(nested);
3112 if (!args[n_arg])
3113 return -1;
3115 for (j = 0; j < n_arg; ++j)
3116 if (pet_expr_is_equal(args[j], args[n_arg]))
3117 break;
3119 if (j < n_arg) {
3120 pet_expr_free(args[n_arg]);
3121 args[n_arg] = NULL;
3122 param2pos[i] = j;
3123 } else
3124 param2pos[i] = n_arg++;
3126 isl_id_free(id);
3129 return n_arg;
3132 /* For each nested access parameter in the access relations in "expr",
3133 * construct a corresponding pet_expr, place it in expr->args and
3134 * record its position in "param2pos".
3135 * n is the number of nested access parameters.
3137 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
3138 std::map<int,int> &param2pos)
3140 isl_space *space;
3142 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
3143 expr->n_arg = n;
3144 if (!expr->args)
3145 goto error;
3147 space = isl_map_get_space(expr->acc.access);
3148 n = extract_nested(space, 0, expr->args, param2pos);
3149 isl_space_free(space);
3151 if (n < 0)
3152 goto error;
3154 expr->n_arg = n;
3155 return expr;
3156 error:
3157 pet_expr_free(expr);
3158 return NULL;
3161 /* Look for parameters in any access relation in "expr" that
3162 * refer to nested accesses. In particular, these are
3163 * parameters with no name.
3165 * If there are any such parameters, then the domain of the index
3166 * expression and the access relation, which is still [] at this point,
3167 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
3168 * (after identifying identical nested accesses).
3170 * This transformation is performed in several steps.
3171 * We first extract the arguments in extract_nested.
3172 * param2pos maps the original parameter position to the position
3173 * of the argument.
3174 * Then we move these parameters to input dimension.
3175 * t2pos maps the positions of these temporary input dimensions
3176 * to the positions of the corresponding arguments.
3177 * Finally, we express there temporary dimensions in term of the domain
3178 * [[] -> [t_1,...,t_n]] and precompose index expression and access
3179 * relations with this function.
3181 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
3183 int n;
3184 int nparam;
3185 isl_space *space;
3186 isl_local_space *ls;
3187 isl_aff *aff;
3188 isl_multi_aff *ma;
3189 std::map<int,int> param2pos;
3190 std::map<int,int> t2pos;
3192 if (!expr)
3193 return expr;
3195 for (int i = 0; i < expr->n_arg; ++i) {
3196 expr->args[i] = resolve_nested(expr->args[i]);
3197 if (!expr->args[i]) {
3198 pet_expr_free(expr);
3199 return NULL;
3203 if (expr->type != pet_expr_access)
3204 return expr;
3206 n = n_nested_parameter(expr->acc.access);
3207 if (n == 0)
3208 return expr;
3210 expr = extract_nested(expr, n, param2pos);
3211 if (!expr)
3212 return NULL;
3214 expr = pet_expr_access_align_params(expr);
3215 if (!expr)
3216 return NULL;
3217 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
3219 n = 0;
3220 for (int i = nparam - 1; i >= 0; --i) {
3221 isl_id *id = isl_map_get_dim_id(expr->acc.access,
3222 isl_dim_param, i);
3223 if (!is_nested_parameter(id)) {
3224 isl_id_free(id);
3225 continue;
3228 expr->acc.access = isl_map_move_dims(expr->acc.access,
3229 isl_dim_in, n, isl_dim_param, i, 1);
3230 expr->acc.index = isl_multi_pw_aff_move_dims(expr->acc.index,
3231 isl_dim_in, n, isl_dim_param, i, 1);
3232 t2pos[n] = param2pos[i];
3233 n++;
3235 isl_id_free(id);
3238 space = isl_multi_pw_aff_get_space(expr->acc.index);
3239 space = isl_space_set_from_params(isl_space_params(space));
3240 space = isl_space_add_dims(space, isl_dim_set, expr->n_arg);
3241 space = isl_space_wrap(isl_space_from_range(space));
3242 ls = isl_local_space_from_space(isl_space_copy(space));
3243 space = isl_space_from_domain(space);
3244 space = isl_space_add_dims(space, isl_dim_out, n);
3245 ma = isl_multi_aff_zero(space);
3247 for (int i = 0; i < n; ++i) {
3248 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3249 isl_dim_set, t2pos[i]);
3250 ma = isl_multi_aff_set_aff(ma, i, aff);
3252 isl_local_space_free(ls);
3254 expr->acc.access = isl_map_preimage_domain_multi_aff(expr->acc.access,
3255 isl_multi_aff_copy(ma));
3256 expr->acc.index = isl_multi_pw_aff_pullback_multi_aff(expr->acc.index,
3257 ma);
3259 return expr;
3260 error:
3261 pet_expr_free(expr);
3262 return NULL;
3265 /* Return the file offset of the expansion location of "Loc".
3267 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3269 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3272 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3274 /* Return a SourceLocation for the location after the first semicolon
3275 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3276 * call it and also skip trailing spaces and newline.
3278 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3279 const LangOptions &LO)
3281 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3284 #else
3286 /* Return a SourceLocation for the location after the first semicolon
3287 * after "loc". If Lexer::findLocationAfterToken is not available,
3288 * we look in the underlying character data for the first semicolon.
3290 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3291 const LangOptions &LO)
3293 const char *semi;
3294 const char *s = SM.getCharacterData(loc);
3296 semi = strchr(s, ';');
3297 if (!semi)
3298 return SourceLocation();
3299 return loc.getFileLocWithOffset(semi + 1 - s);
3302 #endif
3304 /* If the token at "loc" is the first token on the line, then return
3305 * a location referring to the start of the line.
3306 * Otherwise, return "loc".
3308 * This function is used to extend a scop to the start of the line
3309 * if the first token of the scop is also the first token on the line.
3311 * We look for the first token on the line. If its location is equal to "loc",
3312 * then the latter is the location of the first token on the line.
3314 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3315 SourceManager &SM, const LangOptions &LO)
3317 std::pair<FileID, unsigned> file_offset_pair;
3318 llvm::StringRef file;
3319 const char *pos;
3320 Token tok;
3321 SourceLocation token_loc, line_loc;
3322 int col;
3324 loc = SM.getExpansionLoc(loc);
3325 col = SM.getExpansionColumnNumber(loc);
3326 line_loc = loc.getLocWithOffset(1 - col);
3327 file_offset_pair = SM.getDecomposedLoc(line_loc);
3328 file = SM.getBufferData(file_offset_pair.first, NULL);
3329 pos = file.data() + file_offset_pair.second;
3331 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3332 file.begin(), pos, file.end());
3333 lexer.LexFromRawLexer(tok);
3334 token_loc = tok.getLocation();
3336 if (token_loc == loc)
3337 return line_loc;
3338 else
3339 return loc;
3342 /* Convert a top-level pet_expr to a pet_scop with one statement.
3343 * This mainly involves resolving nested expression parameters
3344 * and setting the name of the iteration space.
3345 * The name is given by "label" if it is non-NULL. Otherwise,
3346 * it is of the form S_<n_stmt>.
3347 * start and end of the pet_scop are derived from those of "stmt".
3349 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
3350 __isl_take isl_id *label)
3352 struct pet_stmt *ps;
3353 struct pet_scop *scop;
3354 SourceLocation loc = stmt->getLocStart();
3355 SourceManager &SM = PP.getSourceManager();
3356 const LangOptions &LO = PP.getLangOpts();
3357 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3358 unsigned start, end;
3360 expr = resolve_nested(expr);
3361 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
3362 scop = pet_scop_from_pet_stmt(ctx, ps);
3364 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3365 start = getExpansionOffset(SM, loc);
3366 loc = stmt->getLocEnd();
3367 loc = location_after_semi(loc, SM, LO);
3368 end = getExpansionOffset(SM, loc);
3370 scop = pet_scop_update_start_end(scop, start, end);
3371 return scop;
3374 /* Check if we can extract an affine expression from "expr".
3375 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3376 * We turn on autodetection so that we won't generate any warnings
3377 * and turn off nesting, so that we won't accept any non-affine constructs.
3379 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3381 isl_pw_aff *pwaff;
3382 int save_autodetect = options->autodetect;
3383 bool save_nesting = nesting_enabled;
3385 options->autodetect = 1;
3386 nesting_enabled = false;
3388 pwaff = extract_affine(expr);
3390 options->autodetect = save_autodetect;
3391 nesting_enabled = save_nesting;
3393 return pwaff;
3396 /* Check whether "expr" is an affine expression.
3398 bool PetScan::is_affine(Expr *expr)
3400 isl_pw_aff *pwaff;
3402 pwaff = try_extract_affine(expr);
3403 isl_pw_aff_free(pwaff);
3405 return pwaff != NULL;
3408 /* Check if we can extract an affine constraint from "expr".
3409 * Return the constraint as an isl_set if we can and NULL otherwise.
3410 * We turn on autodetection so that we won't generate any warnings
3411 * and turn off nesting, so that we won't accept any non-affine constructs.
3413 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3415 isl_pw_aff *cond;
3416 int save_autodetect = options->autodetect;
3417 bool save_nesting = nesting_enabled;
3419 options->autodetect = 1;
3420 nesting_enabled = false;
3422 cond = extract_condition(expr);
3424 options->autodetect = save_autodetect;
3425 nesting_enabled = save_nesting;
3427 return cond;
3430 /* Check whether "expr" is an affine constraint.
3432 bool PetScan::is_affine_condition(Expr *expr)
3434 isl_pw_aff *cond;
3436 cond = try_extract_affine_condition(expr);
3437 isl_pw_aff_free(cond);
3439 return cond != NULL;
3442 /* Check if we can extract a condition from "expr".
3443 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3444 * If allow_nested is set, then the condition may involve parameters
3445 * corresponding to nested accesses.
3446 * We turn on autodetection so that we won't generate any warnings.
3448 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3450 isl_pw_aff *cond;
3451 int save_autodetect = options->autodetect;
3452 bool save_nesting = nesting_enabled;
3454 options->autodetect = 1;
3455 nesting_enabled = allow_nested;
3456 cond = extract_condition(expr);
3458 options->autodetect = save_autodetect;
3459 nesting_enabled = save_nesting;
3461 return cond;
3464 /* If the top-level expression of "stmt" is an assignment, then
3465 * return that assignment as a BinaryOperator.
3466 * Otherwise return NULL.
3468 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3470 BinaryOperator *ass;
3472 if (!stmt)
3473 return NULL;
3474 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3475 return NULL;
3477 ass = cast<BinaryOperator>(stmt);
3478 if(ass->getOpcode() != BO_Assign)
3479 return NULL;
3481 return ass;
3484 /* Check if the given if statement is a conditional assignement
3485 * with a non-affine condition. If so, construct a pet_scop
3486 * corresponding to this conditional assignment. Otherwise return NULL.
3488 * In particular we check if "stmt" is of the form
3490 * if (condition)
3491 * a = f(...);
3492 * else
3493 * a = g(...);
3495 * where a is some array or scalar access.
3496 * The constructed pet_scop then corresponds to the expression
3498 * a = condition ? f(...) : g(...)
3500 * All access relations in f(...) are intersected with condition
3501 * while all access relation in g(...) are intersected with the complement.
3503 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3505 BinaryOperator *ass_then, *ass_else;
3506 isl_multi_pw_aff *write_then, *write_else;
3507 isl_set *cond, *comp;
3508 isl_multi_pw_aff *index;
3509 isl_pw_aff *pa;
3510 int equal;
3511 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3512 bool save_nesting = nesting_enabled;
3514 if (!options->detect_conditional_assignment)
3515 return NULL;
3517 ass_then = top_assignment_or_null(stmt->getThen());
3518 ass_else = top_assignment_or_null(stmt->getElse());
3520 if (!ass_then || !ass_else)
3521 return NULL;
3523 if (is_affine_condition(stmt->getCond()))
3524 return NULL;
3526 write_then = extract_index(ass_then->getLHS());
3527 write_else = extract_index(ass_else->getLHS());
3529 equal = isl_multi_pw_aff_plain_is_equal(write_then, write_else);
3530 isl_multi_pw_aff_free(write_else);
3531 if (equal < 0 || !equal) {
3532 isl_multi_pw_aff_free(write_then);
3533 return NULL;
3536 nesting_enabled = allow_nested;
3537 pa = extract_condition(stmt->getCond());
3538 nesting_enabled = save_nesting;
3539 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3540 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3541 index = isl_multi_pw_aff_from_range(isl_multi_pw_aff_from_pw_aff(pa));
3543 pe_cond = pet_expr_from_index(index);
3545 pe_then = extract_expr(ass_then->getRHS());
3546 pe_then = pet_expr_restrict(pe_then, cond);
3547 pe_else = extract_expr(ass_else->getRHS());
3548 pe_else = pet_expr_restrict(pe_else, comp);
3550 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
3551 pe_write = pet_expr_from_index_and_depth(write_then,
3552 extract_depth(write_then));
3553 if (pe_write) {
3554 pe_write->acc.write = 1;
3555 pe_write->acc.read = 0;
3557 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
3558 return extract(stmt, pe);
3561 /* Create a pet_scop with a single statement evaluating "cond"
3562 * and writing the result to a virtual scalar, as expressed by
3563 * "index".
3565 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
3566 __isl_take isl_multi_pw_aff *index)
3568 struct pet_expr *expr, *write;
3569 struct pet_stmt *ps;
3570 struct pet_scop *scop;
3571 SourceLocation loc = cond->getLocStart();
3572 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3574 write = pet_expr_from_index(index);
3575 if (write) {
3576 write->acc.write = 1;
3577 write->acc.read = 0;
3579 expr = extract_expr(cond);
3580 expr = resolve_nested(expr);
3581 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
3582 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
3583 scop = pet_scop_from_pet_stmt(ctx, ps);
3584 scop = resolve_nested(scop);
3586 return scop;
3589 extern "C" {
3590 static struct pet_expr *embed_access(struct pet_expr *expr, void *user);
3593 /* Precompose the access relation and the index expression associated
3594 * to "expr" with the function pointed to by "user",
3595 * thereby embedding the access relation in the domain of this function.
3596 * The initial domain of the access relation and the index expression
3597 * is the zero-dimensional domain.
3599 static struct pet_expr *embed_access(struct pet_expr *expr, void *user)
3601 isl_multi_aff *ma = (isl_multi_aff *) user;
3603 expr->acc.access = isl_map_preimage_domain_multi_aff(expr->acc.access,
3604 isl_multi_aff_copy(ma));
3605 expr->acc.index = isl_multi_pw_aff_pullback_multi_aff(expr->acc.index,
3606 isl_multi_aff_copy(ma));
3607 if (!expr->acc.access || !expr->acc.index)
3608 goto error;
3610 return expr;
3611 error:
3612 pet_expr_free(expr);
3613 return NULL;
3616 /* Precompose all access relations in "expr" with "ma", thereby
3617 * embedding them in the domain of "ma".
3619 static struct pet_expr *embed(struct pet_expr *expr,
3620 __isl_keep isl_multi_aff *ma)
3622 return pet_expr_map_access(expr, &embed_access, ma);
3625 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3627 static int n_nested_parameter(__isl_keep isl_set *set)
3629 isl_space *space;
3630 int n;
3632 space = isl_set_get_space(set);
3633 n = n_nested_parameter(space);
3634 isl_space_free(space);
3636 return n;
3639 /* Remove all parameters from "map" that refer to nested accesses.
3641 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
3643 int nparam;
3644 isl_space *space;
3646 space = isl_map_get_space(map);
3647 nparam = isl_space_dim(space, isl_dim_param);
3648 for (int i = nparam - 1; i >= 0; --i)
3649 if (is_nested_parameter(space, i))
3650 map = isl_map_project_out(map, isl_dim_param, i, 1);
3651 isl_space_free(space);
3653 return map;
3656 /* Remove all parameters from "mpa" that refer to nested accesses.
3658 static __isl_give isl_multi_pw_aff *remove_nested_parameters(
3659 __isl_take isl_multi_pw_aff *mpa)
3661 int nparam;
3662 isl_space *space;
3664 space = isl_multi_pw_aff_get_space(mpa);
3665 nparam = isl_space_dim(space, isl_dim_param);
3666 for (int i = nparam - 1; i >= 0; --i) {
3667 if (!is_nested_parameter(space, i))
3668 continue;
3669 mpa = isl_multi_pw_aff_drop_dims(mpa, isl_dim_param, i, 1);
3671 isl_space_free(space);
3673 return mpa;
3676 /* Remove all parameters from the index expression and access relation of "expr"
3677 * that refer to nested accesses.
3679 static struct pet_expr *remove_nested_parameters(struct pet_expr *expr)
3681 expr->acc.access = remove_nested_parameters(expr->acc.access);
3682 expr->acc.index = remove_nested_parameters(expr->acc.index);
3683 if (!expr->acc.access || !expr->acc.index)
3684 goto error;
3686 return expr;
3687 error:
3688 pet_expr_free(expr);
3689 return NULL;
3692 extern "C" {
3693 static struct pet_expr *expr_remove_nested_parameters(
3694 struct pet_expr *expr, void *user);
3697 static struct pet_expr *expr_remove_nested_parameters(
3698 struct pet_expr *expr, void *user)
3700 return remove_nested_parameters(expr);
3703 /* Remove all nested access parameters from the schedule and all
3704 * accesses of "stmt".
3705 * There is no need to remove them from the domain as these parameters
3706 * have already been removed from the domain when this function is called.
3708 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
3710 if (!stmt)
3711 return NULL;
3712 stmt->schedule = remove_nested_parameters(stmt->schedule);
3713 stmt->body = pet_expr_map_access(stmt->body,
3714 &expr_remove_nested_parameters, NULL);
3715 if (!stmt->schedule || !stmt->body)
3716 goto error;
3717 for (int i = 0; i < stmt->n_arg; ++i) {
3718 stmt->args[i] = pet_expr_map_access(stmt->args[i],
3719 &expr_remove_nested_parameters, NULL);
3720 if (!stmt->args[i])
3721 goto error;
3724 return stmt;
3725 error:
3726 pet_stmt_free(stmt);
3727 return NULL;
3730 /* For each nested access parameter in the domain of "stmt",
3731 * construct a corresponding pet_expr, place it before the original
3732 * elements in stmt->args and record its position in "param2pos".
3733 * n is the number of nested access parameters.
3735 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3736 std::map<int,int> &param2pos)
3738 int i;
3739 isl_space *space;
3740 int n_arg;
3741 struct pet_expr **args;
3743 n_arg = stmt->n_arg;
3744 args = isl_calloc_array(ctx, struct pet_expr *, n + n_arg);
3745 if (!args)
3746 goto error;
3748 space = isl_set_get_space(stmt->domain);
3749 n_arg = extract_nested(space, 0, args, param2pos);
3750 isl_space_free(space);
3752 if (n_arg < 0)
3753 goto error;
3755 for (i = 0; i < stmt->n_arg; ++i)
3756 args[n_arg + i] = stmt->args[i];
3757 free(stmt->args);
3758 stmt->args = args;
3759 stmt->n_arg += n_arg;
3761 return stmt;
3762 error:
3763 if (args) {
3764 for (i = 0; i < n; ++i)
3765 pet_expr_free(args[i]);
3766 free(args);
3768 pet_stmt_free(stmt);
3769 return NULL;
3772 /* Check whether any of the arguments i of "stmt" starting at position "n"
3773 * is equal to one of the first "n" arguments j.
3774 * If so, combine the constraints on arguments i and j and remove
3775 * argument i.
3777 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3779 int i, j;
3780 isl_map *map;
3782 if (!stmt)
3783 return NULL;
3784 if (n == 0)
3785 return stmt;
3786 if (n == stmt->n_arg)
3787 return stmt;
3789 map = isl_set_unwrap(stmt->domain);
3791 for (i = stmt->n_arg - 1; i >= n; --i) {
3792 for (j = 0; j < n; ++j)
3793 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3794 break;
3795 if (j >= n)
3796 continue;
3798 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3799 map = isl_map_project_out(map, isl_dim_out, i, 1);
3801 pet_expr_free(stmt->args[i]);
3802 for (j = i; j + 1 < stmt->n_arg; ++j)
3803 stmt->args[j] = stmt->args[j + 1];
3804 stmt->n_arg--;
3807 stmt->domain = isl_map_wrap(map);
3808 if (!stmt->domain)
3809 goto error;
3810 return stmt;
3811 error:
3812 pet_stmt_free(stmt);
3813 return NULL;
3816 /* Look for parameters in the iteration domain of "stmt" that
3817 * refer to nested accesses. In particular, these are
3818 * parameters with no name.
3820 * If there are any such parameters, then as many extra variables
3821 * (after identifying identical nested accesses) are inserted in the
3822 * range of the map wrapped inside the domain, before the original variables.
3823 * If the original domain is not a wrapped map, then a new wrapped
3824 * map is created with zero output dimensions.
3825 * The parameters are then equated to the corresponding output dimensions
3826 * and subsequently projected out, from the iteration domain,
3827 * the schedule and the access relations.
3828 * For each of the output dimensions, a corresponding argument
3829 * expression is inserted. Initially they are created with
3830 * a zero-dimensional domain, so they have to be embedded
3831 * in the current iteration domain.
3832 * param2pos maps the position of the parameter to the position
3833 * of the corresponding output dimension in the wrapped map.
3835 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3837 int n;
3838 int nparam;
3839 unsigned n_arg;
3840 isl_map *map;
3841 isl_space *space;
3842 isl_multi_aff *ma;
3843 std::map<int,int> param2pos;
3845 if (!stmt)
3846 return NULL;
3848 n = n_nested_parameter(stmt->domain);
3849 if (n == 0)
3850 return stmt;
3852 n_arg = stmt->n_arg;
3853 stmt = extract_nested(stmt, n, param2pos);
3854 if (!stmt)
3855 return NULL;
3857 n = stmt->n_arg - n_arg;
3858 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3859 if (isl_set_is_wrapping(stmt->domain))
3860 map = isl_set_unwrap(stmt->domain);
3861 else
3862 map = isl_map_from_domain(stmt->domain);
3863 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3865 for (int i = nparam - 1; i >= 0; --i) {
3866 isl_id *id;
3868 if (!is_nested_parameter(map, i))
3869 continue;
3871 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
3872 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3873 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3874 param2pos[i]);
3875 map = isl_map_project_out(map, isl_dim_param, i, 1);
3878 stmt->domain = isl_map_wrap(map);
3880 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
3881 space = isl_space_from_domain(isl_space_domain(space));
3882 ma = isl_multi_aff_zero(space);
3883 for (int pos = 0; pos < n; ++pos)
3884 stmt->args[pos] = embed(stmt->args[pos], ma);
3885 isl_multi_aff_free(ma);
3887 stmt = remove_nested_parameters(stmt);
3888 stmt = remove_duplicate_arguments(stmt, n);
3890 return stmt;
3891 error:
3892 pet_stmt_free(stmt);
3893 return NULL;
3896 /* For each statement in "scop", move the parameters that correspond
3897 * to nested access into the ranges of the domains and create
3898 * corresponding argument expressions.
3900 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3902 if (!scop)
3903 return NULL;
3905 for (int i = 0; i < scop->n_stmt; ++i) {
3906 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3907 if (!scop->stmts[i])
3908 goto error;
3911 return scop;
3912 error:
3913 pet_scop_free(scop);
3914 return NULL;
3917 /* Given an access expression "expr", is the variable accessed by
3918 * "expr" assigned anywhere inside "scop"?
3920 static bool is_assigned(pet_expr *expr, pet_scop *scop)
3922 bool assigned = false;
3923 isl_id *id;
3925 id = pet_expr_access_get_id(expr);
3926 assigned = pet_scop_writes(scop, id);
3927 isl_id_free(id);
3929 return assigned;
3932 /* Are all nested access parameters in "pa" allowed given "scop".
3933 * In particular, is none of them written by anywhere inside "scop".
3935 * If "scop" has any skip conditions, then no nested access parameters
3936 * are allowed. In particular, if there is any nested access in a guard
3937 * for a piece of code containing a "continue", then we want to introduce
3938 * a separate statement for evaluating this guard so that we can express
3939 * that the result is false for all previous iterations.
3941 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3943 int nparam;
3945 if (!scop)
3946 return true;
3948 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3949 for (int i = 0; i < nparam; ++i) {
3950 Expr *nested;
3951 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3952 pet_expr *expr;
3953 bool allowed;
3955 if (!is_nested_parameter(id)) {
3956 isl_id_free(id);
3957 continue;
3960 if (pet_scop_has_skip(scop, pet_skip_now)) {
3961 isl_id_free(id);
3962 return false;
3965 nested = (Expr *) isl_id_get_user(id);
3966 expr = extract_expr(nested);
3967 allowed = expr && expr->type == pet_expr_access &&
3968 !is_assigned(expr, scop);
3970 pet_expr_free(expr);
3971 isl_id_free(id);
3973 if (!allowed)
3974 return false;
3977 return true;
3980 /* Do we need to construct a skip condition of the given type
3981 * on an if statement, given that the if condition is non-affine?
3983 * pet_scop_filter_skip can only handle the case where the if condition
3984 * holds (the then branch) and the skip condition is universal.
3985 * In any other case, we need to construct a new skip condition.
3987 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3988 bool have_else, enum pet_skip type)
3990 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
3991 return true;
3992 if (scop_then && pet_scop_has_skip(scop_then, type) &&
3993 !pet_scop_has_universal_skip(scop_then, type))
3994 return true;
3995 return false;
3998 /* Do we need to construct a skip condition of the given type
3999 * on an if statement, given that the if condition is affine?
4001 * There is no need to construct a new skip condition if all
4002 * the skip conditions are affine.
4004 static bool need_skip_aff(struct pet_scop *scop_then,
4005 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
4007 if (scop_then && pet_scop_has_var_skip(scop_then, type))
4008 return true;
4009 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
4010 return true;
4011 return false;
4014 /* Do we need to construct a skip condition of the given type
4015 * on an if statement?
4017 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
4018 bool have_else, enum pet_skip type, bool affine)
4020 if (affine)
4021 return need_skip_aff(scop_then, scop_else, have_else, type);
4022 else
4023 return need_skip(scop_then, scop_else, have_else, type);
4026 /* Construct an affine expression pet_expr that evaluates
4027 * to the constant "val".
4029 static struct pet_expr *universally(isl_ctx *ctx, int val)
4031 isl_local_space *ls;
4032 isl_val *v;
4033 isl_aff *aff;
4034 isl_multi_pw_aff *mpa;
4036 ls = isl_local_space_from_space(isl_space_set_alloc(ctx, 0, 0));
4037 aff = isl_aff_val_on_domain(ls, isl_val_int_from_si(ctx, val));
4038 mpa = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4040 return pet_expr_from_index(mpa);
4043 /* Construct an affine expression pet_expr that evaluates
4044 * to the constant 1.
4046 static struct pet_expr *universally_true(isl_ctx *ctx)
4048 return universally(ctx, 1);
4051 /* Construct an affine expression pet_expr that evaluates
4052 * to the constant 0.
4054 static struct pet_expr *universally_false(isl_ctx *ctx)
4056 return universally(ctx, 0);
4059 /* Given an index expression "test_index" for the if condition,
4060 * an index expression "skip_index" for the skip condition and
4061 * scops for the then and else branches, construct a scop for
4062 * computing "skip_index".
4064 * The computed scop contains a single statement that essentially does
4066 * skip_index = test_cond ? skip_cond_then : skip_cond_else
4068 * If the skip conditions of the then and/or else branch are not affine,
4069 * then they need to be filtered by test_index.
4070 * If they are missing, then this means the skip condition is false.
4072 * Since we are constructing a skip condition for the if statement,
4073 * the skip conditions on the then and else branches are removed.
4075 static struct pet_scop *extract_skip(PetScan *scan,
4076 __isl_take isl_multi_pw_aff *test_index,
4077 __isl_take isl_multi_pw_aff *skip_index,
4078 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
4079 enum pet_skip type)
4081 struct pet_expr *expr_then, *expr_else, *expr, *expr_skip;
4082 struct pet_stmt *stmt;
4083 struct pet_scop *scop;
4084 isl_ctx *ctx = scan->ctx;
4086 if (!scop_then)
4087 goto error;
4088 if (have_else && !scop_else)
4089 goto error;
4091 if (pet_scop_has_skip(scop_then, type)) {
4092 expr_then = pet_scop_get_skip_expr(scop_then, type);
4093 pet_scop_reset_skip(scop_then, type);
4094 if (!pet_expr_is_affine(expr_then))
4095 expr_then = pet_expr_filter(expr_then,
4096 isl_multi_pw_aff_copy(test_index), 1);
4097 } else
4098 expr_then = universally_false(ctx);
4100 if (have_else && pet_scop_has_skip(scop_else, type)) {
4101 expr_else = pet_scop_get_skip_expr(scop_else, type);
4102 pet_scop_reset_skip(scop_else, type);
4103 if (!pet_expr_is_affine(expr_else))
4104 expr_else = pet_expr_filter(expr_else,
4105 isl_multi_pw_aff_copy(test_index), 0);
4106 } else
4107 expr_else = universally_false(ctx);
4109 expr = pet_expr_from_index(test_index);
4110 expr = pet_expr_new_ternary(ctx, expr, expr_then, expr_else);
4111 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4112 if (expr_skip) {
4113 expr_skip->acc.write = 1;
4114 expr_skip->acc.read = 0;
4116 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4117 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, scan->n_stmt++, expr);
4119 scop = pet_scop_from_pet_stmt(ctx, stmt);
4120 scop = scop_add_array(scop, skip_index, scan->ast_context);
4121 isl_multi_pw_aff_free(skip_index);
4123 return scop;
4124 error:
4125 isl_multi_pw_aff_free(test_index);
4126 isl_multi_pw_aff_free(skip_index);
4127 return NULL;
4130 /* Is scop's skip_now condition equal to its skip_later condition?
4131 * In particular, this means that it either has no skip_now condition
4132 * or both a skip_now and a skip_later condition (that are equal to each other).
4134 static bool skip_equals_skip_later(struct pet_scop *scop)
4136 int has_skip_now, has_skip_later;
4137 int equal;
4138 isl_multi_pw_aff *skip_now, *skip_later;
4140 if (!scop)
4141 return false;
4142 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
4143 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
4144 if (has_skip_now != has_skip_later)
4145 return false;
4146 if (!has_skip_now)
4147 return true;
4149 skip_now = pet_scop_get_skip(scop, pet_skip_now);
4150 skip_later = pet_scop_get_skip(scop, pet_skip_later);
4151 equal = isl_multi_pw_aff_is_equal(skip_now, skip_later);
4152 isl_multi_pw_aff_free(skip_now);
4153 isl_multi_pw_aff_free(skip_later);
4155 return equal;
4158 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
4160 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
4162 pet_scop_reset_skip(scop1, pet_skip_later);
4163 pet_scop_reset_skip(scop2, pet_skip_later);
4166 /* Structure that handles the construction of skip conditions.
4168 * scop_then and scop_else represent the then and else branches
4169 * of the if statement
4171 * skip[type] is true if we need to construct a skip condition of that type
4172 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
4173 * are equal to each other
4174 * index[type] is an index expression from a zero-dimension domain
4175 * to the virtual array representing the skip condition
4176 * scop[type] is a scop for computing the skip condition
4178 struct pet_skip_info {
4179 isl_ctx *ctx;
4181 bool skip[2];
4182 bool equal;
4183 isl_multi_pw_aff *index[2];
4184 struct pet_scop *scop[2];
4186 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
4188 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
4191 /* Structure that handles the construction of skip conditions on if statements.
4193 * scop_then and scop_else represent the then and else branches
4194 * of the if statement
4196 struct pet_skip_info_if : public pet_skip_info {
4197 struct pet_scop *scop_then, *scop_else;
4198 bool have_else;
4200 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4201 struct pet_scop *scop_else, bool have_else, bool affine);
4202 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index,
4203 enum pet_skip type);
4204 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index);
4205 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
4206 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4207 int offset);
4208 struct pet_scop *add(struct pet_scop *scop, int offset);
4211 /* Initialize a pet_skip_info_if structure based on the then and else branches
4212 * and based on whether the if condition is affine or not.
4214 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4215 struct pet_scop *scop_else, bool have_else, bool affine) :
4216 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
4217 have_else(have_else)
4219 skip[pet_skip_now] =
4220 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
4221 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
4222 (!have_else || skip_equals_skip_later(scop_else));
4223 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4224 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
4227 /* If we need to construct a skip condition of the given type,
4228 * then do so now.
4230 * "mpa" represents the if condition.
4232 void pet_skip_info_if::extract(PetScan *scan,
4233 __isl_keep isl_multi_pw_aff *mpa, enum pet_skip type)
4235 isl_ctx *ctx;
4237 if (!skip[type])
4238 return;
4240 ctx = isl_multi_pw_aff_get_ctx(mpa);
4241 index[type] = create_test_index(ctx, scan->n_test++);
4242 scop[type] = extract_skip(scan, isl_multi_pw_aff_copy(mpa),
4243 isl_multi_pw_aff_copy(index[type]),
4244 scop_then, scop_else, have_else, type);
4247 /* Construct the required skip conditions, given the if condition "index".
4249 void pet_skip_info_if::extract(PetScan *scan,
4250 __isl_keep isl_multi_pw_aff *index)
4252 extract(scan, index, pet_skip_now);
4253 extract(scan, index, pet_skip_later);
4254 if (equal)
4255 drop_skip_later(scop_then, scop_else);
4258 /* Construct the required skip conditions, given the if condition "cond".
4260 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
4262 isl_multi_pw_aff *test;
4264 if (!skip[pet_skip_now] && !skip[pet_skip_later])
4265 return;
4267 test = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_copy(cond));
4268 test = isl_multi_pw_aff_from_range(test);
4269 extract(scan, test);
4270 isl_multi_pw_aff_free(test);
4273 /* Add the computed skip condition of the give type to "main" and
4274 * add the scop for computing the condition at the given offset.
4276 * If equal is set, then we only computed a skip condition for pet_skip_now,
4277 * but we also need to set it as main's pet_skip_later.
4279 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
4280 enum pet_skip type, int offset)
4282 if (!skip[type])
4283 return main;
4285 scop[type] = pet_scop_prefix(scop[type], offset);
4286 main = pet_scop_add_par(ctx, main, scop[type]);
4287 scop[type] = NULL;
4289 if (equal)
4290 main = pet_scop_set_skip(main, pet_skip_later,
4291 isl_multi_pw_aff_copy(index[type]));
4293 main = pet_scop_set_skip(main, type, index[type]);
4294 index[type] = NULL;
4296 return main;
4299 /* Add the computed skip conditions to "main" and
4300 * add the scops for computing the conditions at the given offset.
4302 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
4304 scop = add(scop, pet_skip_now, offset);
4305 scop = add(scop, pet_skip_later, offset);
4307 return scop;
4310 /* Construct a pet_scop for a non-affine if statement.
4312 * We create a separate statement that writes the result
4313 * of the non-affine condition to a virtual scalar.
4314 * A constraint requiring the value of this virtual scalar to be one
4315 * is added to the iteration domains of the then branch.
4316 * Similarly, a constraint requiring the value of this virtual scalar
4317 * to be zero is added to the iteration domains of the else branch, if any.
4318 * We adjust the schedules to ensure that the virtual scalar is written
4319 * before it is read.
4321 * If there are any breaks or continues in the then and/or else
4322 * branches, then we may have to compute a new skip condition.
4323 * This is handled using a pet_skip_info_if object.
4324 * On initialization, the object checks if skip conditions need
4325 * to be computed. If so, it does so in "extract" and adds them in "add".
4327 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
4328 struct pet_scop *scop_then, struct pet_scop *scop_else,
4329 bool have_else, int stmt_id)
4331 struct pet_scop *scop;
4332 isl_multi_pw_aff *test_index;
4333 int save_n_stmt = n_stmt;
4335 test_index = create_test_index(ctx, n_test++);
4336 n_stmt = stmt_id;
4337 scop = extract_non_affine_condition(cond,
4338 isl_multi_pw_aff_copy(test_index));
4339 n_stmt = save_n_stmt;
4340 scop = scop_add_array(scop, test_index, ast_context);
4342 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
4343 skip.extract(this, test_index);
4345 scop = pet_scop_prefix(scop, 0);
4346 scop_then = pet_scop_prefix(scop_then, 1);
4347 scop_then = pet_scop_filter(scop_then,
4348 isl_multi_pw_aff_copy(test_index), 1);
4349 if (have_else) {
4350 scop_else = pet_scop_prefix(scop_else, 1);
4351 scop_else = pet_scop_filter(scop_else, test_index, 0);
4352 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
4353 } else
4354 isl_multi_pw_aff_free(test_index);
4356 scop = pet_scop_add_seq(ctx, scop, scop_then);
4358 scop = skip.add(scop, 2);
4360 return scop;
4363 /* Construct a pet_scop for an if statement.
4365 * If the condition fits the pattern of a conditional assignment,
4366 * then it is handled by extract_conditional_assignment.
4367 * Otherwise, we do the following.
4369 * If the condition is affine, then the condition is added
4370 * to the iteration domains of the then branch, while the
4371 * opposite of the condition in added to the iteration domains
4372 * of the else branch, if any.
4373 * We allow the condition to be dynamic, i.e., to refer to
4374 * scalars or array elements that may be written to outside
4375 * of the given if statement. These nested accesses are then represented
4376 * as output dimensions in the wrapping iteration domain.
4377 * If it also written _inside_ the then or else branch, then
4378 * we treat the condition as non-affine.
4379 * As explained in extract_non_affine_if, this will introduce
4380 * an extra statement.
4381 * For aesthetic reasons, we want this statement to have a statement
4382 * number that is lower than those of the then and else branches.
4383 * In order to evaluate if will need such a statement, however, we
4384 * first construct scops for the then and else branches.
4385 * We therefore reserve a statement number if we might have to
4386 * introduce such an extra statement.
4388 * If the condition is not affine, then the scop is created in
4389 * extract_non_affine_if.
4391 * If there are any breaks or continues in the then and/or else
4392 * branches, then we may have to compute a new skip condition.
4393 * This is handled using a pet_skip_info_if object.
4394 * On initialization, the object checks if skip conditions need
4395 * to be computed. If so, it does so in "extract" and adds them in "add".
4397 struct pet_scop *PetScan::extract(IfStmt *stmt)
4399 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4400 isl_pw_aff *cond;
4401 int stmt_id;
4402 isl_set *set;
4403 isl_set *valid;
4405 scop = extract_conditional_assignment(stmt);
4406 if (scop)
4407 return scop;
4409 cond = try_extract_nested_condition(stmt->getCond());
4410 if (allow_nested && (!cond || has_nested(cond)))
4411 stmt_id = n_stmt++;
4414 assigned_value_cache cache(assigned_value);
4415 scop_then = extract(stmt->getThen());
4418 if (stmt->getElse()) {
4419 assigned_value_cache cache(assigned_value);
4420 scop_else = extract(stmt->getElse());
4421 if (options->autodetect) {
4422 if (scop_then && !scop_else) {
4423 partial = true;
4424 isl_pw_aff_free(cond);
4425 return scop_then;
4427 if (!scop_then && scop_else) {
4428 partial = true;
4429 isl_pw_aff_free(cond);
4430 return scop_else;
4435 if (cond &&
4436 (!is_nested_allowed(cond, scop_then) ||
4437 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4438 isl_pw_aff_free(cond);
4439 cond = NULL;
4441 if (allow_nested && !cond)
4442 return extract_non_affine_if(stmt->getCond(), scop_then,
4443 scop_else, stmt->getElse(), stmt_id);
4445 if (!cond)
4446 cond = extract_condition(stmt->getCond());
4448 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4449 skip.extract(this, cond);
4451 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4452 set = isl_pw_aff_non_zero_set(cond);
4453 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4455 if (stmt->getElse()) {
4456 set = isl_set_subtract(isl_set_copy(valid), set);
4457 scop_else = pet_scop_restrict(scop_else, set);
4458 scop = pet_scop_add_par(ctx, scop, scop_else);
4459 } else
4460 isl_set_free(set);
4461 scop = resolve_nested(scop);
4462 scop = pet_scop_restrict_context(scop, valid);
4464 if (skip)
4465 scop = pet_scop_prefix(scop, 0);
4466 scop = skip.add(scop, 1);
4468 return scop;
4471 /* Try and construct a pet_scop for a label statement.
4472 * We currently only allow labels on expression statements.
4474 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4476 isl_id *label;
4477 Stmt *sub;
4479 sub = stmt->getSubStmt();
4480 if (!isa<Expr>(sub)) {
4481 unsupported(stmt);
4482 return NULL;
4485 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4487 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4490 /* Return a one-dimensional multi piecewise affine expression that is equal
4491 * to the constant 1 and is defined over a zero-dimensional domain.
4493 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
4495 isl_space *space;
4496 isl_local_space *ls;
4497 isl_aff *aff;
4499 space = isl_space_set_alloc(ctx, 0, 0);
4500 ls = isl_local_space_from_space(space);
4501 aff = isl_aff_zero_on_domain(ls);
4502 aff = isl_aff_set_constant_si(aff, 1);
4504 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4507 /* Construct a pet_scop for a continue statement.
4509 * We simply create an empty scop with a universal pet_skip_now
4510 * skip condition. This skip condition will then be taken into
4511 * account by the enclosing loop construct, possibly after
4512 * being incorporated into outer skip conditions.
4514 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4516 pet_scop *scop;
4518 scop = pet_scop_empty(ctx);
4519 if (!scop)
4520 return NULL;
4522 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
4524 return scop;
4527 /* Construct a pet_scop for a break statement.
4529 * We simply create an empty scop with both a universal pet_skip_now
4530 * skip condition and a universal pet_skip_later skip condition.
4531 * These skip conditions will then be taken into
4532 * account by the enclosing loop construct, possibly after
4533 * being incorporated into outer skip conditions.
4535 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4537 pet_scop *scop;
4538 isl_multi_pw_aff *skip;
4540 scop = pet_scop_empty(ctx);
4541 if (!scop)
4542 return NULL;
4544 skip = one_mpa(ctx);
4545 scop = pet_scop_set_skip(scop, pet_skip_now,
4546 isl_multi_pw_aff_copy(skip));
4547 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
4549 return scop;
4552 /* Try and construct a pet_scop corresponding to "stmt".
4554 * If "stmt" is a compound statement, then "skip_declarations"
4555 * indicates whether we should skip initial declarations in the
4556 * compound statement.
4558 * If the constructed pet_scop is not a (possibly) partial representation
4559 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4560 * In particular, if skip_declarations, then we may have skipped declarations
4561 * inside "stmt" and so the pet_scop may not represent the entire "stmt".
4562 * Note that this function may be called with "stmt" referring to the entire
4563 * body of the function, including the outer braces. In such cases,
4564 * skip_declarations will be set and the braces will not be taken into
4565 * account in scop->start and scop->end.
4567 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
4569 struct pet_scop *scop;
4570 unsigned start, end;
4571 SourceLocation loc;
4572 SourceManager &SM = PP.getSourceManager();
4573 const LangOptions &LO = PP.getLangOpts();
4575 if (isa<Expr>(stmt))
4576 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4578 switch (stmt->getStmtClass()) {
4579 case Stmt::WhileStmtClass:
4580 scop = extract(cast<WhileStmt>(stmt));
4581 break;
4582 case Stmt::ForStmtClass:
4583 scop = extract_for(cast<ForStmt>(stmt));
4584 break;
4585 case Stmt::IfStmtClass:
4586 scop = extract(cast<IfStmt>(stmt));
4587 break;
4588 case Stmt::CompoundStmtClass:
4589 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
4590 break;
4591 case Stmt::LabelStmtClass:
4592 scop = extract(cast<LabelStmt>(stmt));
4593 break;
4594 case Stmt::ContinueStmtClass:
4595 scop = extract(cast<ContinueStmt>(stmt));
4596 break;
4597 case Stmt::BreakStmtClass:
4598 scop = extract(cast<BreakStmt>(stmt));
4599 break;
4600 case Stmt::DeclStmtClass:
4601 scop = extract(cast<DeclStmt>(stmt));
4602 break;
4603 default:
4604 unsupported(stmt);
4605 return NULL;
4608 if (partial || skip_declarations)
4609 return scop;
4611 loc = stmt->getLocStart();
4612 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
4613 start = getExpansionOffset(SM, loc);
4614 loc = PP.getLocForEndOfToken(stmt->getLocEnd());
4615 end = getExpansionOffset(SM, loc);
4616 scop = pet_scop_update_start_end(scop, start, end);
4618 return scop;
4621 /* Do we need to construct a skip condition of the given type
4622 * on a sequence of statements?
4624 * There is no need to construct a new skip condition if only
4625 * only of the two statements has a skip condition or if both
4626 * of their skip conditions are affine.
4628 * In principle we also don't need a new continuation variable if
4629 * the continuation of scop2 is affine, but then we would need
4630 * to allow more complicated forms of continuations.
4632 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4633 enum pet_skip type)
4635 if (!scop1 || !pet_scop_has_skip(scop1, type))
4636 return false;
4637 if (!scop2 || !pet_scop_has_skip(scop2, type))
4638 return false;
4639 if (pet_scop_has_affine_skip(scop1, type) &&
4640 pet_scop_has_affine_skip(scop2, type))
4641 return false;
4642 return true;
4645 /* Construct a scop for computing the skip condition of the given type and
4646 * with index expression "skip_index" for a sequence of two scops "scop1"
4647 * and "scop2".
4649 * The computed scop contains a single statement that essentially does
4651 * skip_index = skip_cond_1 ? 1 : skip_cond_2
4653 * or, in other words, skip_cond1 || skip_cond2.
4654 * In this expression, skip_cond_2 is filtered to reflect that it is
4655 * only evaluated when skip_cond_1 is false.
4657 * The skip condition on scop1 is not removed because it still needs
4658 * to be applied to scop2 when these two scops are combined.
4660 static struct pet_scop *extract_skip_seq(PetScan *ps,
4661 __isl_take isl_multi_pw_aff *skip_index,
4662 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4664 isl_map *access;
4665 struct pet_expr *expr1, *expr2, *expr, *expr_skip;
4666 struct pet_stmt *stmt;
4667 struct pet_scop *scop;
4668 isl_ctx *ctx = ps->ctx;
4670 if (!scop1 || !scop2)
4671 goto error;
4673 expr1 = pet_scop_get_skip_expr(scop1, type);
4674 expr2 = pet_scop_get_skip_expr(scop2, type);
4675 pet_scop_reset_skip(scop2, type);
4677 expr2 = pet_expr_filter(expr2,
4678 isl_multi_pw_aff_copy(expr1->acc.index), 0);
4680 expr = universally_true(ctx);
4681 expr = pet_expr_new_ternary(ctx, expr1, expr, expr2);
4682 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4683 if (expr_skip) {
4684 expr_skip->acc.write = 1;
4685 expr_skip->acc.read = 0;
4687 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4688 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, ps->n_stmt++, expr);
4690 scop = pet_scop_from_pet_stmt(ctx, stmt);
4691 scop = scop_add_array(scop, skip_index, ps->ast_context);
4692 isl_multi_pw_aff_free(skip_index);
4694 return scop;
4695 error:
4696 isl_multi_pw_aff_free(skip_index);
4697 return NULL;
4700 /* Structure that handles the construction of skip conditions
4701 * on sequences of statements.
4703 * scop1 and scop2 represent the two statements that are combined
4705 struct pet_skip_info_seq : public pet_skip_info {
4706 struct pet_scop *scop1, *scop2;
4708 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4709 struct pet_scop *scop2);
4710 void extract(PetScan *scan, enum pet_skip type);
4711 void extract(PetScan *scan);
4712 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4713 int offset);
4714 struct pet_scop *add(struct pet_scop *scop, int offset);
4717 /* Initialize a pet_skip_info_seq structure based on
4718 * on the two statements that are going to be combined.
4720 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4721 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
4723 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
4724 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
4725 skip_equals_skip_later(scop2);
4726 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4727 need_skip_seq(scop1, scop2, pet_skip_later);
4730 /* If we need to construct a skip condition of the given type,
4731 * then do so now.
4733 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
4735 if (!skip[type])
4736 return;
4738 index[type] = create_test_index(ctx, scan->n_test++);
4739 scop[type] = extract_skip_seq(scan, isl_multi_pw_aff_copy(index[type]),
4740 scop1, scop2, type);
4743 /* Construct the required skip conditions.
4745 void pet_skip_info_seq::extract(PetScan *scan)
4747 extract(scan, pet_skip_now);
4748 extract(scan, pet_skip_later);
4749 if (equal)
4750 drop_skip_later(scop1, scop2);
4753 /* Add the computed skip condition of the given type to "main" and
4754 * add the scop for computing the condition at the given offset (the statement
4755 * number). Within this offset, the condition is computed at position 1
4756 * to ensure that it is computed after the corresponding statement.
4758 * If equal is set, then we only computed a skip condition for pet_skip_now,
4759 * but we also need to set it as main's pet_skip_later.
4761 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
4762 enum pet_skip type, int offset)
4764 if (!skip[type])
4765 return main;
4767 scop[type] = pet_scop_prefix(scop[type], 1);
4768 scop[type] = pet_scop_prefix(scop[type], offset);
4769 main = pet_scop_add_par(ctx, main, scop[type]);
4770 scop[type] = NULL;
4772 if (equal)
4773 main = pet_scop_set_skip(main, pet_skip_later,
4774 isl_multi_pw_aff_copy(index[type]));
4776 main = pet_scop_set_skip(main, type, index[type]);
4777 index[type] = NULL;
4779 return main;
4782 /* Add the computed skip conditions to "main" and
4783 * add the scops for computing the conditions at the given offset.
4785 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
4787 scop = add(scop, pet_skip_now, offset);
4788 scop = add(scop, pet_skip_later, offset);
4790 return scop;
4793 /* Extract a clone of the kill statement in "scop".
4794 * "scop" is expected to have been created from a DeclStmt
4795 * and should have the kill as its first statement.
4797 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
4799 struct pet_expr *kill;
4800 struct pet_stmt *stmt;
4801 isl_multi_pw_aff *index;
4802 isl_map *access;
4804 if (!scop)
4805 return NULL;
4806 if (scop->n_stmt < 1)
4807 isl_die(ctx, isl_error_internal,
4808 "expecting at least one statement", return NULL);
4809 stmt = scop->stmts[0];
4810 if (stmt->body->type != pet_expr_unary ||
4811 stmt->body->op != pet_op_kill)
4812 isl_die(ctx, isl_error_internal,
4813 "expecting kill statement", return NULL);
4815 index = isl_multi_pw_aff_copy(stmt->body->args[0]->acc.index);
4816 access = isl_map_copy(stmt->body->args[0]->acc.access);
4817 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
4818 access = isl_map_reset_tuple_id(access, isl_dim_in);
4819 kill = pet_expr_kill_from_access_and_index(access, index);
4820 return pet_stmt_from_pet_expr(ctx, stmt->line, NULL, n_stmt++, kill);
4823 /* Mark all arrays in "scop" as being exposed.
4825 static struct pet_scop *mark_exposed(struct pet_scop *scop)
4827 if (!scop)
4828 return NULL;
4829 for (int i = 0; i < scop->n_array; ++i)
4830 scop->arrays[i]->exposed = 1;
4831 return scop;
4834 /* Try and construct a pet_scop corresponding to (part of)
4835 * a sequence of statements.
4837 * "block" is set if the sequence respresents the children of
4838 * a compound statement.
4839 * "skip_declarations" is set if we should skip initial declarations
4840 * in the sequence of statements.
4842 * If there are any breaks or continues in the individual statements,
4843 * then we may have to compute a new skip condition.
4844 * This is handled using a pet_skip_info_seq object.
4845 * On initialization, the object checks if skip conditions need
4846 * to be computed. If so, it does so in "extract" and adds them in "add".
4848 * If "block" is set, then we need to insert kill statements at
4849 * the end of the block for any array that has been declared by
4850 * one of the statements in the sequence. Each of these declarations
4851 * results in the construction of a kill statement at the place
4852 * of the declaration, so we simply collect duplicates of
4853 * those kill statements and append these duplicates to the constructed scop.
4855 * If "block" is not set, then any array declared by one of the statements
4856 * in the sequence is marked as being exposed.
4858 * If autodetect is set, then we allow the extraction of only a subrange
4859 * of the sequence of statements. However, if there is at least one statement
4860 * for which we could not construct a scop and the final range contains
4861 * either no statements or at least one kill, then we discard the entire
4862 * range.
4864 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
4865 bool skip_declarations)
4867 pet_scop *scop;
4868 StmtIterator i;
4869 int j;
4870 bool partial_range = false;
4871 set<struct pet_stmt *> kills;
4872 set<struct pet_stmt *>::iterator it;
4874 scop = pet_scop_empty(ctx);
4875 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4876 Stmt *child = *i;
4877 struct pet_scop *scop_i;
4879 if (skip_declarations &&
4880 child->getStmtClass() == Stmt::DeclStmtClass)
4881 continue;
4883 scop_i = extract(child);
4884 if (scop->n_stmt != 0 && partial) {
4885 pet_scop_free(scop_i);
4886 break;
4888 pet_skip_info_seq skip(ctx, scop, scop_i);
4889 skip.extract(this);
4890 if (skip)
4891 scop_i = pet_scop_prefix(scop_i, 0);
4892 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4893 if (block)
4894 kills.insert(extract_kill(scop_i));
4895 else
4896 scop_i = mark_exposed(scop_i);
4898 scop_i = pet_scop_prefix(scop_i, j);
4899 if (options->autodetect) {
4900 if (scop_i)
4901 scop = pet_scop_add_seq(ctx, scop, scop_i);
4902 else
4903 partial_range = true;
4904 if (scop->n_stmt != 0 && !scop_i)
4905 partial = true;
4906 } else {
4907 scop = pet_scop_add_seq(ctx, scop, scop_i);
4910 scop = skip.add(scop, j);
4912 if (partial)
4913 break;
4916 for (it = kills.begin(); it != kills.end(); ++it) {
4917 pet_scop *scop_j;
4918 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4919 scop_j = pet_scop_prefix(scop_j, j);
4920 scop = pet_scop_add_seq(ctx, scop, scop_j);
4923 if (scop && partial_range) {
4924 if (scop->n_stmt == 0 || kills.size() != 0) {
4925 pet_scop_free(scop);
4926 return NULL;
4928 partial = true;
4931 return scop;
4934 /* Check if the scop marked by the user is exactly this Stmt
4935 * or part of this Stmt.
4936 * If so, return a pet_scop corresponding to the marked region.
4937 * Otherwise, return NULL.
4939 struct pet_scop *PetScan::scan(Stmt *stmt)
4941 SourceManager &SM = PP.getSourceManager();
4942 unsigned start_off, end_off;
4944 start_off = getExpansionOffset(SM, stmt->getLocStart());
4945 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4947 if (start_off > loc.end)
4948 return NULL;
4949 if (end_off < loc.start)
4950 return NULL;
4951 if (start_off >= loc.start && end_off <= loc.end) {
4952 return extract(stmt);
4955 StmtIterator start;
4956 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4957 Stmt *child = *start;
4958 if (!child)
4959 continue;
4960 start_off = getExpansionOffset(SM, child->getLocStart());
4961 end_off = getExpansionOffset(SM, child->getLocEnd());
4962 if (start_off < loc.start && end_off >= loc.end)
4963 return scan(child);
4964 if (start_off >= loc.start)
4965 break;
4968 StmtIterator end;
4969 for (end = start; end != stmt->child_end(); ++end) {
4970 Stmt *child = *end;
4971 start_off = SM.getFileOffset(child->getLocStart());
4972 if (start_off >= loc.end)
4973 break;
4976 return extract(StmtRange(start, end), false, false);
4979 /* Set the size of index "pos" of "array" to "size".
4980 * In particular, add a constraint of the form
4982 * i_pos < size
4984 * to array->extent and a constraint of the form
4986 * size >= 0
4988 * to array->context.
4990 static struct pet_array *update_size(struct pet_array *array, int pos,
4991 __isl_take isl_pw_aff *size)
4993 isl_set *valid;
4994 isl_set *univ;
4995 isl_set *bound;
4996 isl_space *dim;
4997 isl_aff *aff;
4998 isl_pw_aff *index;
4999 isl_id *id;
5001 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
5002 array->context = isl_set_intersect(array->context, valid);
5004 dim = isl_set_get_space(array->extent);
5005 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
5006 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
5007 univ = isl_set_universe(isl_aff_get_domain_space(aff));
5008 index = isl_pw_aff_alloc(univ, aff);
5010 size = isl_pw_aff_add_dims(size, isl_dim_in,
5011 isl_set_dim(array->extent, isl_dim_set));
5012 id = isl_set_get_tuple_id(array->extent);
5013 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
5014 bound = isl_pw_aff_lt_set(index, size);
5016 array->extent = isl_set_intersect(array->extent, bound);
5018 if (!array->context || !array->extent)
5019 goto error;
5021 return array;
5022 error:
5023 pet_array_free(array);
5024 return NULL;
5027 /* Figure out the size of the array at position "pos" and all
5028 * subsequent positions from "type" and update "array" accordingly.
5030 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
5031 const Type *type, int pos)
5033 const ArrayType *atype;
5034 isl_pw_aff *size;
5036 if (!array)
5037 return NULL;
5039 if (type->isPointerType()) {
5040 type = type->getPointeeType().getTypePtr();
5041 return set_upper_bounds(array, type, pos + 1);
5043 if (!type->isArrayType())
5044 return array;
5046 type = type->getCanonicalTypeInternal().getTypePtr();
5047 atype = cast<ArrayType>(type);
5049 if (type->isConstantArrayType()) {
5050 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
5051 size = extract_affine(ca->getSize());
5052 array = update_size(array, pos, size);
5053 } else if (type->isVariableArrayType()) {
5054 const VariableArrayType *vla = cast<VariableArrayType>(atype);
5055 size = extract_affine(vla->getSizeExpr());
5056 array = update_size(array, pos, size);
5059 type = atype->getElementType().getTypePtr();
5061 return set_upper_bounds(array, type, pos + 1);
5064 /* Is "T" the type of a variable length array with static size?
5066 static bool is_vla_with_static_size(QualType T)
5068 const VariableArrayType *vlatype;
5070 if (!T->isVariableArrayType())
5071 return false;
5072 vlatype = cast<VariableArrayType>(T);
5073 return vlatype->getSizeModifier() == VariableArrayType::Static;
5076 /* Return the type of "decl" as an array.
5078 * In particular, if "decl" is a parameter declaration that
5079 * is a variable length array with a static size, then
5080 * return the original type (i.e., the variable length array).
5081 * Otherwise, return the type of decl.
5083 static QualType get_array_type(ValueDecl *decl)
5085 ParmVarDecl *parm;
5086 QualType T;
5088 parm = dyn_cast<ParmVarDecl>(decl);
5089 if (!parm)
5090 return decl->getType();
5092 T = parm->getOriginalType();
5093 if (!is_vla_with_static_size(T))
5094 return decl->getType();
5095 return T;
5098 /* Construct and return a pet_array corresponding to the variable "decl".
5099 * In particular, initialize array->extent to
5101 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
5103 * and then call set_upper_bounds to set the upper bounds on the indices
5104 * based on the type of the variable.
5106 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
5108 struct pet_array *array;
5109 QualType qt = get_array_type(decl);
5110 const Type *type = qt.getTypePtr();
5111 int depth = array_depth(type);
5112 QualType base = base_type(qt);
5113 string name;
5114 isl_id *id;
5115 isl_space *dim;
5117 array = isl_calloc_type(ctx, struct pet_array);
5118 if (!array)
5119 return NULL;
5121 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
5122 dim = isl_space_set_alloc(ctx, 0, depth);
5123 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
5125 array->extent = isl_set_nat_universe(dim);
5127 dim = isl_space_params_alloc(ctx, 0);
5128 array->context = isl_set_universe(dim);
5130 array = set_upper_bounds(array, type, 0);
5131 if (!array)
5132 return NULL;
5134 name = base.getAsString();
5135 array->element_type = strdup(name.c_str());
5136 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
5138 return array;
5141 /* Construct a list of pet_arrays, one for each array (or scalar)
5142 * accessed inside "scop", add this list to "scop" and return the result.
5144 * The context of "scop" is updated with the intersection of
5145 * the contexts of all arrays, i.e., constraints on the parameters
5146 * that ensure that the arrays have a valid (non-negative) size.
5148 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
5150 int i;
5151 set<ValueDecl *> arrays;
5152 set<ValueDecl *>::iterator it;
5153 int n_array;
5154 struct pet_array **scop_arrays;
5156 if (!scop)
5157 return NULL;
5159 pet_scop_collect_arrays(scop, arrays);
5160 if (arrays.size() == 0)
5161 return scop;
5163 n_array = scop->n_array;
5165 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
5166 n_array + arrays.size());
5167 if (!scop_arrays)
5168 goto error;
5169 scop->arrays = scop_arrays;
5171 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
5172 struct pet_array *array;
5173 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
5174 if (!scop->arrays[n_array + i])
5175 goto error;
5176 scop->n_array++;
5177 scop->context = isl_set_intersect(scop->context,
5178 isl_set_copy(array->context));
5179 if (!scop->context)
5180 goto error;
5183 return scop;
5184 error:
5185 pet_scop_free(scop);
5186 return NULL;
5189 /* Bound all parameters in scop->context to the possible values
5190 * of the corresponding C variable.
5192 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
5194 int n;
5196 if (!scop)
5197 return NULL;
5199 n = isl_set_dim(scop->context, isl_dim_param);
5200 for (int i = 0; i < n; ++i) {
5201 isl_id *id;
5202 ValueDecl *decl;
5204 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
5205 if (is_nested_parameter(id)) {
5206 isl_id_free(id);
5207 isl_die(isl_set_get_ctx(scop->context),
5208 isl_error_internal,
5209 "unresolved nested parameter", goto error);
5211 decl = (ValueDecl *) isl_id_get_user(id);
5212 isl_id_free(id);
5214 scop->context = set_parameter_bounds(scop->context, i, decl);
5216 if (!scop->context)
5217 goto error;
5220 return scop;
5221 error:
5222 pet_scop_free(scop);
5223 return NULL;
5226 /* Construct a pet_scop from the given function.
5228 * If the scop was delimited by scop and endscop pragmas, then we override
5229 * the file offsets by those derived from the pragmas.
5231 struct pet_scop *PetScan::scan(FunctionDecl *fd)
5233 pet_scop *scop;
5234 Stmt *stmt;
5236 stmt = fd->getBody();
5238 if (options->autodetect)
5239 scop = extract(stmt, true);
5240 else {
5241 scop = scan(stmt);
5242 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
5244 scop = pet_scop_detect_parameter_accesses(scop);
5245 scop = scan_arrays(scop);
5246 scop = add_parameter_bounds(scop);
5247 scop = pet_scop_gist(scop, value_bounds);
5249 return scop;