97dcebe1dd51080d1d61aae6ea517a98d3c2b178
[pet.git] / scan.cc
blob97dcebe1dd51080d1d61aae6ea517a98d3c2b178
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;
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 /* Given a partial index expression "base" and an extra index "index",
982 * append the extra index to "base" and return the result.
983 * Additionally, add the constraints that the extra index is non-negative.
985 static __isl_give isl_multi_pw_aff *subscript(__isl_take isl_multi_pw_aff *base,
986 __isl_take isl_pw_aff *index)
988 isl_id *id;
989 isl_set *domain;
990 isl_multi_pw_aff *access;
992 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_set);
993 index = isl_pw_aff_from_range(index);
994 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
995 index = isl_pw_aff_intersect_domain(index, domain);
996 access = isl_multi_pw_aff_from_pw_aff(index);
997 access = isl_multi_pw_aff_flat_range_product(base, access);
998 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_set, id);
1000 return access;
1003 /* Extract an index expression from the given array subscript expression.
1004 * If nesting is allowed in general, then we turn it on while
1005 * examining the index expression.
1007 * We first extract an index expression from the base.
1008 * This will result in an index expression with a range that corresponds
1009 * to the earlier indices.
1010 * We then extract the current index, restrict its domain
1011 * to those values that result in a non-negative index and
1012 * append the index to the base index expression.
1014 __isl_give isl_multi_pw_aff *PetScan::extract_index(ArraySubscriptExpr *expr)
1016 Expr *base = expr->getBase();
1017 Expr *idx = expr->getIdx();
1018 isl_pw_aff *index;
1019 isl_multi_pw_aff *base_access;
1020 isl_multi_pw_aff *access;
1021 bool save_nesting = nesting_enabled;
1023 nesting_enabled = allow_nested;
1025 base_access = extract_index(base);
1026 index = extract_affine(idx);
1028 nesting_enabled = save_nesting;
1030 access = subscript(base_access, index);
1032 return access;
1035 /* Check if "expr" calls function "minmax" with two arguments and if so
1036 * make lhs and rhs refer to these two arguments.
1038 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1040 CallExpr *call;
1041 FunctionDecl *fd;
1042 string name;
1044 if (expr->getStmtClass() != Stmt::CallExprClass)
1045 return false;
1047 call = cast<CallExpr>(expr);
1048 fd = call->getDirectCallee();
1049 if (!fd)
1050 return false;
1052 if (call->getNumArgs() != 2)
1053 return false;
1055 name = fd->getDeclName().getAsString();
1056 if (name != minmax)
1057 return false;
1059 lhs = call->getArg(0);
1060 rhs = call->getArg(1);
1062 return true;
1065 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1066 * lhs and rhs refer to the two arguments.
1068 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1070 return is_minmax(expr, "min", lhs, rhs);
1073 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1074 * lhs and rhs refer to the two arguments.
1076 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1078 return is_minmax(expr, "max", lhs, rhs);
1081 /* Return "lhs && rhs", defined on the shared definition domain.
1083 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1084 __isl_take isl_pw_aff *rhs)
1086 isl_set *cond;
1087 isl_set *dom;
1089 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1090 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1091 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1092 isl_pw_aff_non_zero_set(rhs));
1093 return indicator_function(cond, dom);
1096 /* Return "lhs && rhs", with shortcut semantics.
1097 * That is, if lhs is false, then the result is defined even if rhs is not.
1098 * In practice, we compute lhs ? rhs : lhs.
1100 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1101 __isl_take isl_pw_aff *rhs)
1103 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1106 /* Return "lhs || rhs", with shortcut semantics.
1107 * That is, if lhs is true, then the result is defined even if rhs is not.
1108 * In practice, we compute lhs ? lhs : rhs.
1110 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1111 __isl_take isl_pw_aff *rhs)
1113 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1116 /* Extract an affine expressions representing the comparison "LHS op RHS"
1117 * "comp" is the original statement that "LHS op RHS" is derived from
1118 * and is used for diagnostics.
1120 * If the comparison is of the form
1122 * a <= min(b,c)
1124 * then the expression is constructed as the conjunction of
1125 * the comparisons
1127 * a <= b and a <= c
1129 * A similar optimization is performed for max(a,b) <= c.
1130 * We do this because that will lead to simpler representations
1131 * of the expression.
1132 * If isl is ever enhanced to explicitly deal with min and max expressions,
1133 * this optimization can be removed.
1135 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1136 Expr *LHS, Expr *RHS, Stmt *comp)
1138 isl_pw_aff *lhs;
1139 isl_pw_aff *rhs;
1140 isl_pw_aff *res;
1141 isl_set *cond;
1142 isl_set *dom;
1144 if (op == BO_GT)
1145 return extract_comparison(BO_LT, RHS, LHS, comp);
1146 if (op == BO_GE)
1147 return extract_comparison(BO_LE, RHS, LHS, comp);
1149 if (op == BO_LT || op == BO_LE) {
1150 Expr *expr1, *expr2;
1151 if (is_min(RHS, expr1, expr2)) {
1152 lhs = extract_comparison(op, LHS, expr1, comp);
1153 rhs = extract_comparison(op, LHS, expr2, comp);
1154 return pw_aff_and(lhs, rhs);
1156 if (is_max(LHS, expr1, expr2)) {
1157 lhs = extract_comparison(op, expr1, RHS, comp);
1158 rhs = extract_comparison(op, expr2, RHS, comp);
1159 return pw_aff_and(lhs, rhs);
1163 lhs = extract_affine(LHS);
1164 rhs = extract_affine(RHS);
1166 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1167 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1169 switch (op) {
1170 case BO_LT:
1171 cond = isl_pw_aff_lt_set(lhs, rhs);
1172 break;
1173 case BO_LE:
1174 cond = isl_pw_aff_le_set(lhs, rhs);
1175 break;
1176 case BO_EQ:
1177 cond = isl_pw_aff_eq_set(lhs, rhs);
1178 break;
1179 case BO_NE:
1180 cond = isl_pw_aff_ne_set(lhs, rhs);
1181 break;
1182 default:
1183 isl_pw_aff_free(lhs);
1184 isl_pw_aff_free(rhs);
1185 isl_set_free(dom);
1186 unsupported(comp);
1187 return NULL;
1190 cond = isl_set_coalesce(cond);
1191 res = indicator_function(cond, dom);
1193 return res;
1196 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1198 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1199 comp->getRHS(), comp);
1202 /* Extract an affine expression representing the negation (logical not)
1203 * of a subexpression.
1205 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1207 isl_set *set_cond, *dom;
1208 isl_pw_aff *cond, *res;
1210 cond = extract_condition(op->getSubExpr());
1212 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1214 set_cond = isl_pw_aff_zero_set(cond);
1216 res = indicator_function(set_cond, dom);
1218 return res;
1221 /* Extract an affine expression representing the disjunction (logical or)
1222 * or conjunction (logical and) of two subexpressions.
1224 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1226 isl_pw_aff *lhs, *rhs;
1228 lhs = extract_condition(comp->getLHS());
1229 rhs = extract_condition(comp->getRHS());
1231 switch (comp->getOpcode()) {
1232 case BO_LAnd:
1233 return pw_aff_and_then(lhs, rhs);
1234 case BO_LOr:
1235 return pw_aff_or_else(lhs, rhs);
1236 default:
1237 isl_pw_aff_free(lhs);
1238 isl_pw_aff_free(rhs);
1241 unsupported(comp);
1242 return NULL;
1245 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1247 switch (expr->getOpcode()) {
1248 case UO_LNot:
1249 return extract_boolean(expr);
1250 default:
1251 unsupported(expr);
1252 return NULL;
1256 /* Extract the affine expression "expr != 0 ? 1 : 0".
1258 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1260 isl_pw_aff *res;
1261 isl_set *set, *dom;
1263 res = extract_affine(expr);
1265 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1266 set = isl_pw_aff_non_zero_set(res);
1268 res = indicator_function(set, dom);
1270 return res;
1273 /* Extract an affine expression from a boolean expression.
1274 * In particular, return the expression "expr ? 1 : 0".
1276 * If the expression doesn't look like a condition, we assume it
1277 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1279 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1281 BinaryOperator *comp;
1283 if (!expr) {
1284 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1285 return indicator_function(u, isl_set_copy(u));
1288 if (expr->getStmtClass() == Stmt::ParenExprClass)
1289 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1291 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1292 return extract_condition(cast<UnaryOperator>(expr));
1294 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1295 return extract_implicit_condition(expr);
1297 comp = cast<BinaryOperator>(expr);
1298 switch (comp->getOpcode()) {
1299 case BO_LT:
1300 case BO_LE:
1301 case BO_GT:
1302 case BO_GE:
1303 case BO_EQ:
1304 case BO_NE:
1305 return extract_comparison(comp);
1306 case BO_LAnd:
1307 case BO_LOr:
1308 return extract_boolean(comp);
1309 default:
1310 return extract_implicit_condition(expr);
1314 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1316 switch (kind) {
1317 case UO_Minus:
1318 return pet_op_minus;
1319 case UO_PostInc:
1320 return pet_op_post_inc;
1321 case UO_PostDec:
1322 return pet_op_post_dec;
1323 case UO_PreInc:
1324 return pet_op_pre_inc;
1325 case UO_PreDec:
1326 return pet_op_pre_dec;
1327 default:
1328 return pet_op_last;
1332 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1334 switch (kind) {
1335 case BO_AddAssign:
1336 return pet_op_add_assign;
1337 case BO_SubAssign:
1338 return pet_op_sub_assign;
1339 case BO_MulAssign:
1340 return pet_op_mul_assign;
1341 case BO_DivAssign:
1342 return pet_op_div_assign;
1343 case BO_Assign:
1344 return pet_op_assign;
1345 case BO_Add:
1346 return pet_op_add;
1347 case BO_Sub:
1348 return pet_op_sub;
1349 case BO_Mul:
1350 return pet_op_mul;
1351 case BO_Div:
1352 return pet_op_div;
1353 case BO_Rem:
1354 return pet_op_mod;
1355 case BO_EQ:
1356 return pet_op_eq;
1357 case BO_LE:
1358 return pet_op_le;
1359 case BO_LT:
1360 return pet_op_lt;
1361 case BO_GT:
1362 return pet_op_gt;
1363 default:
1364 return pet_op_last;
1368 /* Construct a pet_expr representing a unary operator expression.
1370 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1372 struct pet_expr *arg;
1373 enum pet_op_type op;
1375 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1376 if (op == pet_op_last) {
1377 unsupported(expr);
1378 return NULL;
1381 arg = extract_expr(expr->getSubExpr());
1383 if (expr->isIncrementDecrementOp() &&
1384 arg && arg->type == pet_expr_access) {
1385 mark_write(arg);
1386 arg->acc.read = 1;
1389 return pet_expr_new_unary(ctx, op, arg);
1392 /* Mark the given access pet_expr as a write.
1393 * If a scalar is being accessed, then mark its value
1394 * as unknown in assigned_value.
1396 void PetScan::mark_write(struct pet_expr *access)
1398 isl_id *id;
1399 ValueDecl *decl;
1401 if (!access)
1402 return;
1404 access->acc.write = 1;
1405 access->acc.read = 0;
1407 if (!pet_expr_is_scalar_access(access))
1408 return;
1410 id = pet_expr_access_get_id(access);
1411 decl = (ValueDecl *) isl_id_get_user(id);
1412 clear_assignment(assigned_value, decl);
1413 isl_id_free(id);
1416 /* Assign "rhs" to "lhs".
1418 * In particular, if "lhs" is a scalar variable, then mark
1419 * the variable as having been assigned. If, furthermore, "rhs"
1420 * is an affine expression, then keep track of this value in assigned_value
1421 * so that we can plug it in when we later come across the same variable.
1423 void PetScan::assign(struct pet_expr *lhs, Expr *rhs)
1425 isl_id *id;
1426 ValueDecl *decl;
1427 isl_pw_aff *pa;
1429 if (!lhs)
1430 return;
1431 if (!pet_expr_is_scalar_access(lhs))
1432 return;
1434 id = pet_expr_access_get_id(lhs);
1435 decl = (ValueDecl *) isl_id_get_user(id);
1436 isl_id_free(id);
1438 pa = try_extract_affine(rhs);
1439 clear_assignment(assigned_value, decl);
1440 if (!pa)
1441 return;
1442 assigned_value[decl] = pa;
1443 insert_expression(pa);
1446 /* Construct a pet_expr representing a binary operator expression.
1448 * If the top level operator is an assignment and the LHS is an access,
1449 * then we mark that access as a write. If the operator is a compound
1450 * assignment, the access is marked as both a read and a write.
1452 * If "expr" assigns something to a scalar variable, then we mark
1453 * the variable as having been assigned. If, furthermore, the expression
1454 * is affine, then keep track of this value in assigned_value
1455 * so that we can plug it in when we later come across the same variable.
1457 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1459 struct pet_expr *lhs, *rhs;
1460 enum pet_op_type op;
1462 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1463 if (op == pet_op_last) {
1464 unsupported(expr);
1465 return NULL;
1468 lhs = extract_expr(expr->getLHS());
1469 rhs = extract_expr(expr->getRHS());
1471 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1472 mark_write(lhs);
1473 if (expr->isCompoundAssignmentOp())
1474 lhs->acc.read = 1;
1477 if (expr->getOpcode() == BO_Assign)
1478 assign(lhs, expr->getRHS());
1480 return pet_expr_new_binary(ctx, op, lhs, rhs);
1483 /* Construct a pet_scop with a single statement killing the entire
1484 * array "array".
1486 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1488 isl_id *id;
1489 isl_space *space;
1490 isl_multi_pw_aff *index;
1491 isl_map *access;
1492 struct pet_expr *expr;
1494 if (!array)
1495 return NULL;
1496 access = isl_map_from_range(isl_set_copy(array->extent));
1497 id = isl_set_get_tuple_id(array->extent);
1498 space = isl_space_alloc(ctx, 0, 0, 0);
1499 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1500 index = isl_multi_pw_aff_zero(space);
1501 expr = pet_expr_kill_from_access_and_index(access, index);
1502 return extract(stmt, expr);
1505 /* Construct a pet_scop for a (single) variable declaration.
1507 * The scop contains the variable being declared (as an array)
1508 * and a statement killing the array.
1510 * If the variable is initialized in the AST, then the scop
1511 * also contains an assignment to the variable.
1513 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1515 Decl *decl;
1516 VarDecl *vd;
1517 struct pet_expr *lhs, *rhs, *pe;
1518 struct pet_scop *scop_decl, *scop;
1519 struct pet_array *array;
1521 if (!stmt->isSingleDecl()) {
1522 unsupported(stmt);
1523 return NULL;
1526 decl = stmt->getSingleDecl();
1527 vd = cast<VarDecl>(decl);
1529 array = extract_array(ctx, vd);
1530 if (array)
1531 array->declared = 1;
1532 scop_decl = kill(stmt, array);
1533 scop_decl = pet_scop_add_array(scop_decl, array);
1535 if (!vd->getInit())
1536 return scop_decl;
1538 lhs = extract_access_expr(vd);
1539 rhs = extract_expr(vd->getInit());
1541 mark_write(lhs);
1542 assign(lhs, vd->getInit());
1544 pe = pet_expr_new_binary(ctx, pet_op_assign, lhs, rhs);
1545 scop = extract(stmt, pe);
1547 scop_decl = pet_scop_prefix(scop_decl, 0);
1548 scop = pet_scop_prefix(scop, 1);
1550 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1552 return scop;
1555 /* Construct a pet_expr representing a conditional operation.
1557 * We first try to extract the condition as an affine expression.
1558 * If that fails, we construct a pet_expr tree representing the condition.
1560 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1562 struct pet_expr *cond, *lhs, *rhs;
1563 isl_pw_aff *pa;
1565 pa = try_extract_affine(expr->getCond());
1566 if (pa) {
1567 isl_multi_pw_aff *test = isl_multi_pw_aff_from_pw_aff(pa);
1568 test = isl_multi_pw_aff_from_range(test);
1569 cond = pet_expr_from_index(test);
1570 } else
1571 cond = extract_expr(expr->getCond());
1572 lhs = extract_expr(expr->getTrueExpr());
1573 rhs = extract_expr(expr->getFalseExpr());
1575 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1578 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1580 return extract_expr(expr->getSubExpr());
1583 /* Construct a pet_expr representing a floating point value.
1585 * If the floating point literal does not appear in a macro,
1586 * then we use the original representation in the source code
1587 * as the string representation. Otherwise, we use the pretty
1588 * printer to produce a string representation.
1590 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1592 double d;
1593 string s;
1594 const LangOptions &LO = PP.getLangOpts();
1595 SourceLocation loc = expr->getLocation();
1597 if (!loc.isMacroID()) {
1598 SourceManager &SM = PP.getSourceManager();
1599 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1600 s = string(SM.getCharacterData(loc), len);
1601 } else {
1602 llvm::raw_string_ostream S(s);
1603 expr->printPretty(S, 0, PrintingPolicy(LO));
1604 S.str();
1606 d = expr->getValueAsApproximateDouble();
1607 return pet_expr_new_double(ctx, d, s.c_str());
1610 /* Extract an index expression from "expr" and then convert it into
1611 * an access pet_expr.
1613 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1615 isl_multi_pw_aff *index;
1616 struct pet_expr *pe;
1617 int depth;
1619 index = extract_index(expr);
1620 depth = extract_depth(index);
1622 pe = pet_expr_from_index_and_depth(index, depth);
1624 return pe;
1627 /* Extract an index expression from "decl" and then convert it into
1628 * an access pet_expr.
1630 struct pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1632 isl_multi_pw_aff *index;
1633 struct pet_expr *pe;
1634 int depth;
1636 index = extract_index(decl);
1637 depth = extract_depth(index);
1639 pe = pet_expr_from_index_and_depth(index, depth);
1641 return pe;
1644 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1646 return extract_expr(expr->getSubExpr());
1649 /* Construct a pet_expr representing a function call.
1651 * If we are passing along a pointer to an array element
1652 * or an entire row or even higher dimensional slice of an array,
1653 * then the function being called may write into the array.
1655 * We assume here that if the function is declared to take a pointer
1656 * to a const type, then the function will perform a read
1657 * and that otherwise, it will perform a write.
1659 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1661 struct pet_expr *res = NULL;
1662 FunctionDecl *fd;
1663 string name;
1665 fd = expr->getDirectCallee();
1666 if (!fd) {
1667 unsupported(expr);
1668 return NULL;
1671 name = fd->getDeclName().getAsString();
1672 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1673 if (!res)
1674 return NULL;
1676 for (int i = 0; i < expr->getNumArgs(); ++i) {
1677 Expr *arg = expr->getArg(i);
1678 int is_addr = 0;
1679 pet_expr *main_arg;
1681 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1682 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1683 arg = ice->getSubExpr();
1685 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1686 UnaryOperator *op = cast<UnaryOperator>(arg);
1687 if (op->getOpcode() == UO_AddrOf) {
1688 is_addr = 1;
1689 arg = op->getSubExpr();
1692 res->args[i] = PetScan::extract_expr(arg);
1693 main_arg = res->args[i];
1694 if (is_addr)
1695 res->args[i] = pet_expr_new_unary(ctx,
1696 pet_op_address_of, res->args[i]);
1697 if (!res->args[i])
1698 goto error;
1699 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1700 array_depth(arg->getType().getTypePtr()) > 0)
1701 is_addr = 1;
1702 if (is_addr && main_arg->type == pet_expr_access) {
1703 ParmVarDecl *parm;
1704 if (!fd->hasPrototype()) {
1705 unsupported(expr, "prototype required");
1706 goto error;
1708 parm = fd->getParamDecl(i);
1709 if (!const_base(parm->getType()))
1710 mark_write(main_arg);
1714 return res;
1715 error:
1716 pet_expr_free(res);
1717 return NULL;
1720 /* Construct a pet_expr representing a (C style) cast.
1722 struct pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1724 struct pet_expr *arg;
1725 QualType type;
1727 arg = extract_expr(expr->getSubExpr());
1728 if (!arg)
1729 return NULL;
1731 type = expr->getTypeAsWritten();
1732 return pet_expr_new_cast(ctx, type.getAsString().c_str(), arg);
1735 /* Try and onstruct a pet_expr representing "expr".
1737 struct pet_expr *PetScan::extract_expr(Expr *expr)
1739 switch (expr->getStmtClass()) {
1740 case Stmt::UnaryOperatorClass:
1741 return extract_expr(cast<UnaryOperator>(expr));
1742 case Stmt::CompoundAssignOperatorClass:
1743 case Stmt::BinaryOperatorClass:
1744 return extract_expr(cast<BinaryOperator>(expr));
1745 case Stmt::ImplicitCastExprClass:
1746 return extract_expr(cast<ImplicitCastExpr>(expr));
1747 case Stmt::ArraySubscriptExprClass:
1748 case Stmt::DeclRefExprClass:
1749 case Stmt::IntegerLiteralClass:
1750 return extract_access_expr(expr);
1751 case Stmt::FloatingLiteralClass:
1752 return extract_expr(cast<FloatingLiteral>(expr));
1753 case Stmt::ParenExprClass:
1754 return extract_expr(cast<ParenExpr>(expr));
1755 case Stmt::ConditionalOperatorClass:
1756 return extract_expr(cast<ConditionalOperator>(expr));
1757 case Stmt::CallExprClass:
1758 return extract_expr(cast<CallExpr>(expr));
1759 case Stmt::CStyleCastExprClass:
1760 return extract_expr(cast<CStyleCastExpr>(expr));
1761 default:
1762 unsupported(expr);
1764 return NULL;
1767 /* Check if the given initialization statement is an assignment.
1768 * If so, return that assignment. Otherwise return NULL.
1770 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1772 BinaryOperator *ass;
1774 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1775 return NULL;
1777 ass = cast<BinaryOperator>(init);
1778 if (ass->getOpcode() != BO_Assign)
1779 return NULL;
1781 return ass;
1784 /* Check if the given initialization statement is a declaration
1785 * of a single variable.
1786 * If so, return that declaration. Otherwise return NULL.
1788 Decl *PetScan::initialization_declaration(Stmt *init)
1790 DeclStmt *decl;
1792 if (init->getStmtClass() != Stmt::DeclStmtClass)
1793 return NULL;
1795 decl = cast<DeclStmt>(init);
1797 if (!decl->isSingleDecl())
1798 return NULL;
1800 return decl->getSingleDecl();
1803 /* Given the assignment operator in the initialization of a for loop,
1804 * extract the induction variable, i.e., the (integer)variable being
1805 * assigned.
1807 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1809 Expr *lhs;
1810 DeclRefExpr *ref;
1811 ValueDecl *decl;
1812 const Type *type;
1814 lhs = init->getLHS();
1815 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1816 unsupported(init);
1817 return NULL;
1820 ref = cast<DeclRefExpr>(lhs);
1821 decl = ref->getDecl();
1822 type = decl->getType().getTypePtr();
1824 if (!type->isIntegerType()) {
1825 unsupported(lhs);
1826 return NULL;
1829 return decl;
1832 /* Given the initialization statement of a for loop and the single
1833 * declaration in this initialization statement,
1834 * extract the induction variable, i.e., the (integer) variable being
1835 * declared.
1837 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1839 VarDecl *vd;
1841 vd = cast<VarDecl>(decl);
1843 const QualType type = vd->getType();
1844 if (!type->isIntegerType()) {
1845 unsupported(init);
1846 return NULL;
1849 if (!vd->getInit()) {
1850 unsupported(init);
1851 return NULL;
1854 return vd;
1857 /* Check that op is of the form iv++ or iv--.
1858 * Return an affine expression "1" or "-1" accordingly.
1860 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
1861 clang::UnaryOperator *op, clang::ValueDecl *iv)
1863 Expr *sub;
1864 DeclRefExpr *ref;
1865 isl_space *space;
1866 isl_aff *aff;
1868 if (!op->isIncrementDecrementOp()) {
1869 unsupported(op);
1870 return NULL;
1873 sub = op->getSubExpr();
1874 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1875 unsupported(op);
1876 return NULL;
1879 ref = cast<DeclRefExpr>(sub);
1880 if (ref->getDecl() != iv) {
1881 unsupported(op);
1882 return NULL;
1885 space = isl_space_params_alloc(ctx, 0);
1886 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1888 if (op->isIncrementOp())
1889 aff = isl_aff_add_constant_si(aff, 1);
1890 else
1891 aff = isl_aff_add_constant_si(aff, -1);
1893 return isl_pw_aff_from_aff(aff);
1896 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1897 * has a single constant expression, then put this constant in *user.
1898 * The caller is assumed to have checked that this function will
1899 * be called exactly once.
1901 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1902 void *user)
1904 isl_val **inc = (isl_val **)user;
1905 int res = 0;
1907 if (isl_aff_is_cst(aff))
1908 *inc = isl_aff_get_constant_val(aff);
1909 else
1910 res = -1;
1912 isl_set_free(set);
1913 isl_aff_free(aff);
1915 return res;
1918 /* Check if op is of the form
1920 * iv = iv + inc
1922 * and return inc as an affine expression.
1924 * We extract an affine expression from the RHS, subtract iv and return
1925 * the result.
1927 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
1928 clang::ValueDecl *iv)
1930 Expr *lhs;
1931 DeclRefExpr *ref;
1932 isl_id *id;
1933 isl_space *dim;
1934 isl_aff *aff;
1935 isl_pw_aff *val;
1937 if (op->getOpcode() != BO_Assign) {
1938 unsupported(op);
1939 return NULL;
1942 lhs = op->getLHS();
1943 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1944 unsupported(op);
1945 return NULL;
1948 ref = cast<DeclRefExpr>(lhs);
1949 if (ref->getDecl() != iv) {
1950 unsupported(op);
1951 return NULL;
1954 val = extract_affine(op->getRHS());
1956 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1958 dim = isl_space_params_alloc(ctx, 1);
1959 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1960 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1961 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1963 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1965 return val;
1968 /* Check that op is of the form iv += cst or iv -= cst
1969 * and return an affine expression corresponding oto cst or -cst accordingly.
1971 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
1972 CompoundAssignOperator *op, clang::ValueDecl *iv)
1974 Expr *lhs;
1975 DeclRefExpr *ref;
1976 bool neg = false;
1977 isl_pw_aff *val;
1978 BinaryOperatorKind opcode;
1980 opcode = op->getOpcode();
1981 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1982 unsupported(op);
1983 return NULL;
1985 if (opcode == BO_SubAssign)
1986 neg = true;
1988 lhs = op->getLHS();
1989 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1990 unsupported(op);
1991 return NULL;
1994 ref = cast<DeclRefExpr>(lhs);
1995 if (ref->getDecl() != iv) {
1996 unsupported(op);
1997 return NULL;
2000 val = extract_affine(op->getRHS());
2001 if (neg)
2002 val = isl_pw_aff_neg(val);
2004 return val;
2007 /* Check that the increment of the given for loop increments
2008 * (or decrements) the induction variable "iv" and return
2009 * the increment as an affine expression if successful.
2011 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
2012 ValueDecl *iv)
2014 Stmt *inc = stmt->getInc();
2016 if (!inc) {
2017 unsupported(stmt);
2018 return NULL;
2021 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
2022 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
2023 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
2024 return extract_compound_increment(
2025 cast<CompoundAssignOperator>(inc), iv);
2026 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
2027 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
2029 unsupported(inc);
2030 return NULL;
2033 /* Embed the given iteration domain in an extra outer loop
2034 * with induction variable "var".
2035 * If this variable appeared as a parameter in the constraints,
2036 * it is replaced by the new outermost dimension.
2038 static __isl_give isl_set *embed(__isl_take isl_set *set,
2039 __isl_take isl_id *var)
2041 int pos;
2043 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
2044 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
2045 if (pos >= 0) {
2046 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
2047 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2050 isl_id_free(var);
2051 return set;
2054 /* Return those elements in the space of "cond" that come after
2055 * (based on "sign") an element in "cond".
2057 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
2059 isl_map *previous_to_this;
2061 if (sign > 0)
2062 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
2063 else
2064 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
2066 cond = isl_set_apply(cond, previous_to_this);
2068 return cond;
2071 /* Create the infinite iteration domain
2073 * { [id] : id >= 0 }
2075 * If "scop" has an affine skip of type pet_skip_later,
2076 * then remove those iterations i that have an earlier iteration
2077 * where the skip condition is satisfied, meaning that iteration i
2078 * is not executed.
2079 * Since we are dealing with a loop without loop iterator,
2080 * the skip condition cannot refer to the current loop iterator and
2081 * so effectively, the returned set is of the form
2083 * { [0]; [id] : id >= 1 and not skip }
2085 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
2086 struct pet_scop *scop)
2088 isl_ctx *ctx = isl_id_get_ctx(id);
2089 isl_set *domain;
2090 isl_set *skip;
2092 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
2093 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
2095 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
2096 return domain;
2098 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2099 skip = embed(skip, isl_id_copy(id));
2100 skip = isl_set_intersect(skip , isl_set_copy(domain));
2101 domain = isl_set_subtract(domain, after(skip, 1));
2103 return domain;
2106 /* Create an identity affine expression on the space containing "domain",
2107 * which is assumed to be one-dimensional.
2109 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
2111 isl_local_space *ls;
2113 ls = isl_local_space_from_space(isl_set_get_space(domain));
2114 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
2117 /* Create an affine expression that maps elements
2118 * of a single-dimensional array "id_test" to the previous element
2119 * (according to "inc"), provided this element belongs to "domain".
2120 * That is, create the affine expression
2122 * { id[x] -> id[x - inc] : x - inc in domain }
2124 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
2125 __isl_take isl_set *domain, __isl_take isl_val *inc)
2127 isl_space *space;
2128 isl_local_space *ls;
2129 isl_aff *aff;
2130 isl_multi_pw_aff *prev;
2132 space = isl_set_get_space(domain);
2133 ls = isl_local_space_from_space(space);
2134 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2135 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
2136 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
2137 domain = isl_set_preimage_multi_pw_aff(domain,
2138 isl_multi_pw_aff_copy(prev));
2139 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
2140 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
2142 return prev;
2145 /* Add an implication to "scop" expressing that if an element of
2146 * virtual array "id_test" has value "satisfied" then all previous elements
2147 * of this array also have that value. The set of previous elements
2148 * is bounded by "domain". If "sign" is negative then iterator
2149 * is decreasing and we express that all subsequent array elements
2150 * (but still defined previously) have the same value.
2152 static struct pet_scop *add_implication(struct pet_scop *scop,
2153 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
2154 int satisfied)
2156 isl_space *space;
2157 isl_map *map;
2159 domain = isl_set_set_tuple_id(domain, id_test);
2160 space = isl_set_get_space(domain);
2161 if (sign > 0)
2162 map = isl_map_lex_ge(space);
2163 else
2164 map = isl_map_lex_le(space);
2165 map = isl_map_intersect_range(map, domain);
2166 scop = pet_scop_add_implication(scop, map, satisfied);
2168 return scop;
2171 /* Add a filter to "scop" that imposes that it is only executed
2172 * when the variable identified by "id_test" has a zero value
2173 * for all previous iterations of "domain".
2175 * In particular, add a filter that imposes that the array
2176 * has a zero value at the previous iteration of domain and
2177 * add an implication that implies that it then has that
2178 * value for all previous iterations.
2180 static struct pet_scop *scop_add_break(struct pet_scop *scop,
2181 __isl_take isl_id *id_test, __isl_take isl_set *domain,
2182 __isl_take isl_val *inc)
2184 isl_multi_pw_aff *prev;
2185 int sign = isl_val_sgn(inc);
2187 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2188 scop = add_implication(scop, id_test, domain, sign, 0);
2189 scop = pet_scop_filter(scop, prev, 0);
2191 return scop;
2194 /* Construct a pet_scop for an infinite loop around the given body.
2196 * We extract a pet_scop for the body and then embed it in a loop with
2197 * iteration domain
2199 * { [t] : t >= 0 }
2201 * and schedule
2203 * { [t] -> [t] }
2205 * If the body contains any break, then it is taken into
2206 * account in infinite_domain (if the skip condition is affine)
2207 * or in scop_add_break (if the skip condition is not affine).
2209 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2211 isl_id *id, *id_test;
2212 isl_set *domain;
2213 isl_aff *ident;
2214 struct pet_scop *scop;
2215 bool has_var_break;
2217 scop = extract(body);
2218 if (!scop)
2219 return NULL;
2221 id = isl_id_alloc(ctx, "t", NULL);
2222 domain = infinite_domain(isl_id_copy(id), scop);
2223 ident = identity_aff(domain);
2225 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2226 if (has_var_break)
2227 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
2229 scop = pet_scop_embed(scop, isl_set_copy(domain),
2230 isl_map_from_aff(isl_aff_copy(ident)), ident, id);
2231 if (has_var_break)
2232 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
2233 else
2234 isl_set_free(domain);
2236 return scop;
2239 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2241 * for (;;)
2242 * body
2245 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2247 return extract_infinite_loop(stmt->getBody());
2250 /* Create an index expression for an access to a virtual array
2251 * representing the result of a condition.
2252 * Unlike other accessed data, the id of the array is NULL as
2253 * there is no ValueDecl in the program corresponding to the virtual
2254 * array.
2255 * The array starts out as a scalar, but grows along with the
2256 * statement writing to the array in pet_scop_embed.
2258 static __isl_give isl_multi_pw_aff *create_test_index(isl_ctx *ctx, int test_nr)
2260 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2261 isl_id *id;
2262 char name[50];
2264 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2265 id = isl_id_alloc(ctx, name, NULL);
2266 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2267 return isl_multi_pw_aff_zero(dim);
2270 /* Add an array with the given extent (range of "index") to the list
2271 * of arrays in "scop" and return the extended pet_scop.
2272 * The array is marked as attaining values 0 and 1 only and
2273 * as each element being assigned at most once.
2275 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2276 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
2278 isl_ctx *ctx = isl_multi_pw_aff_get_ctx(index);
2279 isl_space *dim;
2280 struct pet_array *array;
2281 isl_map *access;
2283 if (!scop)
2284 return NULL;
2285 if (!ctx)
2286 goto error;
2288 array = isl_calloc_type(ctx, struct pet_array);
2289 if (!array)
2290 goto error;
2292 access = isl_map_from_multi_pw_aff(isl_multi_pw_aff_copy(index));
2293 array->extent = isl_map_range(access);
2294 dim = isl_space_params_alloc(ctx, 0);
2295 array->context = isl_set_universe(dim);
2296 dim = isl_space_set_alloc(ctx, 0, 1);
2297 array->value_bounds = isl_set_universe(dim);
2298 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2299 isl_dim_set, 0, 0);
2300 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2301 isl_dim_set, 0, 1);
2302 array->element_type = strdup("int");
2303 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2304 array->uniquely_defined = 1;
2306 if (!array->extent || !array->context)
2307 array = pet_array_free(array);
2309 scop = pet_scop_add_array(scop, array);
2311 return scop;
2312 error:
2313 pet_scop_free(scop);
2314 return NULL;
2317 /* Construct a pet_scop for a while loop of the form
2319 * while (pa)
2320 * body
2322 * In particular, construct a scop for an infinite loop around body and
2323 * intersect the domain with the affine expression.
2324 * Note that this intersection may result in an empty loop.
2326 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2327 Stmt *body)
2329 struct pet_scop *scop;
2330 isl_set *dom;
2331 isl_set *valid;
2333 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2334 dom = isl_pw_aff_non_zero_set(pa);
2335 scop = extract_infinite_loop(body);
2336 scop = pet_scop_restrict(scop, dom);
2337 scop = pet_scop_restrict_context(scop, valid);
2339 return scop;
2342 /* Construct a scop for a while, given the scops for the condition
2343 * and the body, the filter identifier and the iteration domain of
2344 * the while loop.
2346 * In particular, the scop for the condition is filtered to depend
2347 * on "id_test" evaluating to true for all previous iterations
2348 * of the loop, while the scop for the body is filtered to depend
2349 * on "id_test" evaluating to true for all iterations up to the
2350 * current iteration.
2351 * The actual filter only imposes that this virtual array has
2352 * value one on the previous or the current iteration.
2353 * The fact that this condition also applies to the previous
2354 * iterations is enforced by an implication.
2356 * These filtered scops are then combined into a single scop.
2358 * "sign" is positive if the iterator increases and negative
2359 * if it decreases.
2361 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2362 struct pet_scop *scop_body, __isl_take isl_id *id_test,
2363 __isl_take isl_set *domain, __isl_take isl_val *inc)
2365 isl_ctx *ctx = isl_set_get_ctx(domain);
2366 isl_space *space;
2367 isl_multi_pw_aff *test_index;
2368 isl_multi_pw_aff *prev;
2369 int sign = isl_val_sgn(inc);
2370 struct pet_scop *scop;
2372 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2373 scop_cond = pet_scop_filter(scop_cond, prev, 1);
2375 space = isl_space_map_from_set(isl_set_get_space(domain));
2376 test_index = isl_multi_pw_aff_identity(space);
2377 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
2378 isl_id_copy(id_test));
2379 scop_body = pet_scop_filter(scop_body, test_index, 1);
2381 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
2382 scop = add_implication(scop, id_test, domain, sign, 1);
2384 return scop;
2387 /* Check if the while loop is of the form
2389 * while (affine expression)
2390 * body
2392 * If so, call extract_affine_while to construct a scop.
2394 * Otherwise, construct a generic while scop, with iteration domain
2395 * { [t] : t >= 0 }. The scop consists of two parts, one for
2396 * evaluating the condition and one for the body.
2397 * The schedule is adjusted to reflect that the condition is evaluated
2398 * before the body is executed and the body is filtered to depend
2399 * on the result of the condition evaluating to true on all iterations
2400 * up to the current iteration, while the evaluation the condition itself
2401 * is filtered to depend on the result of the condition evaluating to true
2402 * on all previous iterations.
2403 * The context of the scop representing the body is dropped
2404 * because we don't know how many times the body will be executed,
2405 * if at all.
2407 * If the body contains any break, then it is taken into
2408 * account in infinite_domain (if the skip condition is affine)
2409 * or in scop_add_break (if the skip condition is not affine).
2411 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2413 Expr *cond;
2414 isl_id *id, *id_test, *id_break_test;
2415 isl_multi_pw_aff *test_index;
2416 isl_set *domain;
2417 isl_aff *ident;
2418 isl_pw_aff *pa;
2419 struct pet_scop *scop, *scop_body;
2420 bool has_var_break;
2422 cond = stmt->getCond();
2423 if (!cond) {
2424 unsupported(stmt);
2425 return NULL;
2428 clear_assignments clear(assigned_value);
2429 clear.TraverseStmt(stmt->getBody());
2431 pa = try_extract_affine_condition(cond);
2432 if (pa)
2433 return extract_affine_while(pa, stmt->getBody());
2435 if (!allow_nested) {
2436 unsupported(stmt);
2437 return NULL;
2440 test_index = create_test_index(ctx, n_test++);
2441 scop = extract_non_affine_condition(cond,
2442 isl_multi_pw_aff_copy(test_index));
2443 scop = scop_add_array(scop, test_index, ast_context);
2444 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2445 isl_multi_pw_aff_free(test_index);
2446 scop_body = extract(stmt->getBody());
2448 id = isl_id_alloc(ctx, "t", NULL);
2449 domain = infinite_domain(isl_id_copy(id), scop_body);
2450 ident = identity_aff(domain);
2452 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2453 if (has_var_break)
2454 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2456 scop = pet_scop_prefix(scop, 0);
2457 scop = pet_scop_embed(scop, isl_set_copy(domain),
2458 isl_map_from_aff(isl_aff_copy(ident)),
2459 isl_aff_copy(ident), isl_id_copy(id));
2460 scop_body = pet_scop_reset_context(scop_body);
2461 scop_body = pet_scop_prefix(scop_body, 1);
2462 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2463 isl_map_from_aff(isl_aff_copy(ident)), ident, id);
2465 if (has_var_break) {
2466 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2467 isl_set_copy(domain), isl_val_one(ctx));
2468 scop_body = scop_add_break(scop_body, id_break_test,
2469 isl_set_copy(domain), isl_val_one(ctx));
2471 scop = scop_add_while(scop, scop_body, id_test, domain,
2472 isl_val_one(ctx));
2474 return scop;
2477 /* Check whether "cond" expresses a simple loop bound
2478 * on the only set dimension.
2479 * In particular, if "up" is set then "cond" should contain only
2480 * upper bounds on the set dimension.
2481 * Otherwise, it should contain only lower bounds.
2483 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2485 if (isl_val_is_pos(inc))
2486 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2487 else
2488 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2491 /* Extend a condition on a given iteration of a loop to one that
2492 * imposes the same condition on all previous iterations.
2493 * "domain" expresses the lower [upper] bound on the iterations
2494 * when inc is positive [negative].
2496 * In particular, we construct the condition (when inc is positive)
2498 * forall i' : (domain(i') and i' <= i) => cond(i')
2500 * which is equivalent to
2502 * not exists i' : domain(i') and i' <= i and not cond(i')
2504 * We construct this set by negating cond, applying a map
2506 * { [i'] -> [i] : domain(i') and i' <= i }
2508 * and then negating the result again.
2510 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2511 __isl_take isl_set *domain, __isl_take isl_val *inc)
2513 isl_map *previous_to_this;
2515 if (isl_val_is_pos(inc))
2516 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2517 else
2518 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2520 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2522 cond = isl_set_complement(cond);
2523 cond = isl_set_apply(cond, previous_to_this);
2524 cond = isl_set_complement(cond);
2526 isl_val_free(inc);
2528 return cond;
2531 /* Construct a domain of the form
2533 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2535 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2536 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2538 isl_aff *aff;
2539 isl_space *dim;
2540 isl_set *set;
2542 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2543 dim = isl_pw_aff_get_domain_space(init);
2544 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2545 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2546 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2548 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2549 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2550 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2551 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2553 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2555 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2557 return isl_set_params(set);
2560 /* Assuming "cond" represents a bound on a loop where the loop
2561 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2562 * is possible.
2564 * Under the given assumptions, wrapping is only possible if "cond" allows
2565 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2566 * increasing iterator and 0 in case of a decreasing iterator.
2568 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2569 __isl_keep isl_val *inc)
2571 bool cw;
2572 isl_ctx *ctx;
2573 isl_val *limit;
2574 isl_set *test;
2576 test = isl_set_copy(cond);
2578 ctx = isl_set_get_ctx(test);
2579 if (isl_val_is_neg(inc))
2580 limit = isl_val_zero(ctx);
2581 else {
2582 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2583 limit = isl_val_2exp(limit);
2584 limit = isl_val_sub_ui(limit, 1);
2587 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2588 cw = !isl_set_is_empty(test);
2589 isl_set_free(test);
2591 return cw;
2594 /* Given a one-dimensional space, construct the following affine expression
2595 * on this space
2597 * { [v] -> [v mod 2^width] }
2599 * where width is the number of bits used to represent the values
2600 * of the unsigned variable "iv".
2602 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2603 ValueDecl *iv)
2605 isl_ctx *ctx;
2606 isl_val *mod;
2607 isl_aff *aff;
2609 ctx = isl_space_get_ctx(dim);
2610 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2611 mod = isl_val_2exp(mod);
2613 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2614 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2615 aff = isl_aff_mod_val(aff, mod);
2617 return aff;
2620 /* Project out the parameter "id" from "set".
2622 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2623 __isl_keep isl_id *id)
2625 int pos;
2627 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2628 if (pos >= 0)
2629 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2631 return set;
2634 /* Compute the set of parameters for which "set1" is a subset of "set2".
2636 * set1 is a subset of set2 if
2638 * forall i in set1 : i in set2
2640 * or
2642 * not exists i in set1 and i not in set2
2644 * i.e.,
2646 * not exists i in set1 \ set2
2648 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2649 __isl_take isl_set *set2)
2651 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2654 /* Compute the set of parameter values for which "cond" holds
2655 * on the next iteration for each element of "dom".
2657 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2658 * and then compute the set of parameters for which the result is a subset
2659 * of "cond".
2661 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2662 __isl_take isl_set *dom, __isl_take isl_val *inc)
2664 isl_space *space;
2665 isl_aff *aff;
2666 isl_map *next;
2668 space = isl_set_get_space(dom);
2669 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2670 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2671 aff = isl_aff_add_constant_val(aff, inc);
2672 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2674 dom = isl_set_apply(dom, next);
2676 return enforce_subset(dom, cond);
2679 /* Does "id" refer to a nested access?
2681 static bool is_nested_parameter(__isl_keep isl_id *id)
2683 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2686 /* Does parameter "pos" of "space" refer to a nested access?
2688 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2690 bool nested;
2691 isl_id *id;
2693 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2694 nested = is_nested_parameter(id);
2695 isl_id_free(id);
2697 return nested;
2700 /* Does "space" involve any parameters that refer to nested
2701 * accesses, i.e., parameters with no name?
2703 static bool has_nested(__isl_keep isl_space *space)
2705 int nparam;
2707 nparam = isl_space_dim(space, isl_dim_param);
2708 for (int i = 0; i < nparam; ++i)
2709 if (is_nested_parameter(space, i))
2710 return true;
2712 return false;
2715 /* Does "pa" involve any parameters that refer to nested
2716 * accesses, i.e., parameters with no name?
2718 static bool has_nested(__isl_keep isl_pw_aff *pa)
2720 isl_space *space;
2721 bool nested;
2723 space = isl_pw_aff_get_space(pa);
2724 nested = has_nested(space);
2725 isl_space_free(space);
2727 return nested;
2730 /* Construct a pet_scop for a for statement.
2731 * The for loop is required to be of the form
2733 * for (i = init; condition; ++i)
2735 * or
2737 * for (i = init; condition; --i)
2739 * The initialization of the for loop should either be an assignment
2740 * to an integer variable, or a declaration of such a variable with
2741 * initialization.
2743 * The condition is allowed to contain nested accesses, provided
2744 * they are not being written to inside the body of the loop.
2745 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2746 * essentially treated as a while loop, with iteration domain
2747 * { [i] : i >= init }.
2749 * We extract a pet_scop for the body and then embed it in a loop with
2750 * iteration domain and schedule
2752 * { [i] : i >= init and condition' }
2753 * { [i] -> [i] }
2755 * or
2757 * { [i] : i <= init and condition' }
2758 * { [i] -> [-i] }
2760 * Where condition' is equal to condition if the latter is
2761 * a simple upper [lower] bound and a condition that is extended
2762 * to apply to all previous iterations otherwise.
2764 * If the condition is non-affine, then we drop the condition from the
2765 * iteration domain and instead create a separate statement
2766 * for evaluating the condition. The body is then filtered to depend
2767 * on the result of the condition evaluating to true on all iterations
2768 * up to the current iteration, while the evaluation the condition itself
2769 * is filtered to depend on the result of the condition evaluating to true
2770 * on all previous iterations.
2771 * The context of the scop representing the body is dropped
2772 * because we don't know how many times the body will be executed,
2773 * if at all.
2775 * If the stride of the loop is not 1, then "i >= init" is replaced by
2777 * (exists a: i = init + stride * a and a >= 0)
2779 * If the loop iterator i is unsigned, then wrapping may occur.
2780 * During the computation, we work with a virtual iterator that
2781 * does not wrap. However, the condition in the code applies
2782 * to the wrapped value, so we need to change condition(i)
2783 * into condition([i % 2^width]).
2784 * After computing the virtual domain and schedule, we apply
2785 * the function { [v] -> [v % 2^width] } to the domain and the domain
2786 * of the schedule. In order not to lose any information, we also
2787 * need to intersect the domain of the schedule with the virtual domain
2788 * first, since some iterations in the wrapped domain may be scheduled
2789 * several times, typically an infinite number of times.
2790 * Note that there may be no need to perform this final wrapping
2791 * if the loop condition (after wrapping) satisfies certain conditions.
2792 * However, the is_simple_bound condition is not enough since it doesn't
2793 * check if there even is an upper bound.
2795 * If the loop condition is non-affine, then we keep the virtual
2796 * iterator in the iteration domain and instead replace all accesses
2797 * to the original iterator by the wrapping of the virtual iterator.
2799 * Wrapping on unsigned iterators can be avoided entirely if
2800 * loop condition is simple, the loop iterator is incremented
2801 * [decremented] by one and the last value before wrapping cannot
2802 * possibly satisfy the loop condition.
2804 * Before extracting a pet_scop from the body we remove all
2805 * assignments in assigned_value to variables that are assigned
2806 * somewhere in the body of the loop.
2808 * Valid parameters for a for loop are those for which the initial
2809 * value itself, the increment on each domain iteration and
2810 * the condition on both the initial value and
2811 * the result of incrementing the iterator for each iteration of the domain
2812 * can be evaluated.
2813 * If the loop condition is non-affine, then we only consider validity
2814 * of the initial value.
2816 * If the body contains any break, then we keep track of it in "skip"
2817 * (if the skip condition is affine) or it is handled in scop_add_break
2818 * (if the skip condition is not affine).
2819 * Note that the affine break condition needs to be considered with
2820 * respect to previous iterations in the virtual domain (if any)
2821 * and that the domain needs to be kept virtual if there is a non-affine
2822 * break condition.
2824 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2826 BinaryOperator *ass;
2827 Decl *decl;
2828 Stmt *init;
2829 Expr *lhs, *rhs;
2830 ValueDecl *iv;
2831 isl_space *space;
2832 isl_set *domain;
2833 isl_map *sched;
2834 isl_set *cond = NULL;
2835 isl_set *skip = NULL;
2836 isl_id *id, *id_test = NULL, *id_break_test;
2837 struct pet_scop *scop, *scop_cond = NULL;
2838 assigned_value_cache cache(assigned_value);
2839 isl_val *inc;
2840 bool is_one;
2841 bool is_unsigned;
2842 bool is_simple;
2843 bool is_virtual;
2844 bool keep_virtual = false;
2845 bool has_affine_break;
2846 bool has_var_break;
2847 isl_aff *wrap = NULL;
2848 isl_pw_aff *pa, *pa_inc, *init_val;
2849 isl_set *valid_init;
2850 isl_set *valid_cond;
2851 isl_set *valid_cond_init;
2852 isl_set *valid_cond_next;
2853 isl_set *valid_inc;
2854 int stmt_id;
2856 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2857 return extract_infinite_for(stmt);
2859 init = stmt->getInit();
2860 if (!init) {
2861 unsupported(stmt);
2862 return NULL;
2864 if ((ass = initialization_assignment(init)) != NULL) {
2865 iv = extract_induction_variable(ass);
2866 if (!iv)
2867 return NULL;
2868 lhs = ass->getLHS();
2869 rhs = ass->getRHS();
2870 } else if ((decl = initialization_declaration(init)) != NULL) {
2871 VarDecl *var = extract_induction_variable(init, decl);
2872 if (!var)
2873 return NULL;
2874 iv = var;
2875 rhs = var->getInit();
2876 lhs = create_DeclRefExpr(var);
2877 } else {
2878 unsupported(stmt->getInit());
2879 return NULL;
2882 pa_inc = extract_increment(stmt, iv);
2883 if (!pa_inc)
2884 return NULL;
2886 inc = NULL;
2887 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
2888 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
2889 isl_pw_aff_free(pa_inc);
2890 unsupported(stmt->getInc());
2891 isl_val_free(inc);
2892 return NULL;
2894 valid_inc = isl_pw_aff_domain(pa_inc);
2896 is_unsigned = iv->getType()->isUnsignedIntegerType();
2898 assigned_value.erase(iv);
2899 clear_assignments clear(assigned_value);
2900 clear.TraverseStmt(stmt->getBody());
2902 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2904 pa = try_extract_nested_condition(stmt->getCond());
2905 if (allow_nested && (!pa || has_nested(pa)))
2906 stmt_id = n_stmt++;
2908 scop = extract(stmt->getBody());
2910 has_affine_break = scop &&
2911 pet_scop_has_affine_skip(scop, pet_skip_later);
2912 if (has_affine_break)
2913 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2914 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
2915 if (has_var_break) {
2916 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
2917 keep_virtual = true;
2920 if (pa && !is_nested_allowed(pa, scop)) {
2921 isl_pw_aff_free(pa);
2922 pa = NULL;
2925 if (!allow_nested && !pa)
2926 pa = try_extract_affine_condition(stmt->getCond());
2927 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2928 cond = isl_pw_aff_non_zero_set(pa);
2929 if (allow_nested && !cond) {
2930 isl_multi_pw_aff *test_index;
2931 int save_n_stmt = n_stmt;
2932 test_index = create_test_index(ctx, n_test++);
2933 n_stmt = stmt_id;
2934 scop_cond = extract_non_affine_condition(stmt->getCond(),
2935 isl_multi_pw_aff_copy(test_index));
2936 n_stmt = save_n_stmt;
2937 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
2938 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
2939 isl_dim_out);
2940 isl_multi_pw_aff_free(test_index);
2941 scop_cond = pet_scop_prefix(scop_cond, 0);
2942 scop = pet_scop_reset_context(scop);
2943 scop = pet_scop_prefix(scop, 1);
2944 keep_virtual = true;
2945 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2948 cond = embed(cond, isl_id_copy(id));
2949 skip = embed(skip, isl_id_copy(id));
2950 valid_cond = isl_set_coalesce(valid_cond);
2951 valid_cond = embed(valid_cond, isl_id_copy(id));
2952 valid_inc = embed(valid_inc, isl_id_copy(id));
2953 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
2954 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2956 init_val = extract_affine(rhs);
2957 valid_cond_init = enforce_subset(
2958 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
2959 isl_set_copy(valid_cond));
2960 if (is_one && !is_virtual) {
2961 isl_pw_aff_free(init_val);
2962 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
2963 lhs, rhs, init);
2964 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2965 valid_init = set_project_out_by_id(valid_init, id);
2966 domain = isl_pw_aff_non_zero_set(pa);
2967 } else {
2968 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2969 domain = strided_domain(isl_id_copy(id), init_val,
2970 isl_val_copy(inc));
2973 domain = embed(domain, isl_id_copy(id));
2974 if (is_virtual) {
2975 isl_map *rev_wrap;
2976 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2977 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
2978 rev_wrap = isl_map_reverse(rev_wrap);
2979 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2980 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
2981 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2982 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2984 is_simple = is_simple_bound(cond, inc);
2985 if (!is_simple) {
2986 cond = isl_set_gist(cond, isl_set_copy(domain));
2987 is_simple = is_simple_bound(cond, inc);
2989 if (!is_simple)
2990 cond = valid_for_each_iteration(cond,
2991 isl_set_copy(domain), isl_val_copy(inc));
2992 domain = isl_set_intersect(domain, cond);
2993 if (has_affine_break) {
2994 skip = isl_set_intersect(skip , isl_set_copy(domain));
2995 skip = after(skip, isl_val_sgn(inc));
2996 domain = isl_set_subtract(domain, skip);
2998 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2999 space = isl_space_from_domain(isl_set_get_space(domain));
3000 space = isl_space_add_dims(space, isl_dim_out, 1);
3001 sched = isl_map_universe(space);
3002 if (isl_val_is_pos(inc))
3003 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
3004 else
3005 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
3007 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
3008 isl_val_copy(inc));
3009 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
3011 if (is_virtual && !keep_virtual) {
3012 isl_map *wrap_map = isl_map_from_aff(wrap);
3013 wrap_map = isl_map_set_dim_id(wrap_map,
3014 isl_dim_out, 0, isl_id_copy(id));
3015 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
3016 domain = isl_set_apply(domain, isl_map_copy(wrap_map));
3017 sched = isl_map_apply_domain(sched, wrap_map);
3019 if (!(is_virtual && keep_virtual))
3020 wrap = identity_aff(domain);
3022 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
3023 isl_map_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
3024 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
3025 scop = resolve_nested(scop);
3026 if (has_var_break)
3027 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
3028 isl_val_copy(inc));
3029 if (id_test) {
3030 scop = scop_add_while(scop_cond, scop, id_test, domain,
3031 isl_val_copy(inc));
3032 isl_set_free(valid_inc);
3033 } else {
3034 scop = pet_scop_restrict_context(scop, valid_inc);
3035 scop = pet_scop_restrict_context(scop, valid_cond_next);
3036 scop = pet_scop_restrict_context(scop, valid_cond_init);
3037 isl_set_free(domain);
3039 clear_assignment(assigned_value, iv);
3041 isl_val_free(inc);
3043 scop = pet_scop_restrict_context(scop, valid_init);
3045 return scop;
3048 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
3050 return extract(stmt->children(), true, skip_declarations);
3053 /* Does parameter "pos" of "map" refer to a nested access?
3055 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
3057 bool nested;
3058 isl_id *id;
3060 id = isl_map_get_dim_id(map, isl_dim_param, pos);
3061 nested = is_nested_parameter(id);
3062 isl_id_free(id);
3064 return nested;
3067 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
3069 static int n_nested_parameter(__isl_keep isl_space *space)
3071 int n = 0;
3072 int nparam;
3074 nparam = isl_space_dim(space, isl_dim_param);
3075 for (int i = 0; i < nparam; ++i)
3076 if (is_nested_parameter(space, i))
3077 ++n;
3079 return n;
3082 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
3084 static int n_nested_parameter(__isl_keep isl_map *map)
3086 isl_space *space;
3087 int n;
3089 space = isl_map_get_space(map);
3090 n = n_nested_parameter(space);
3091 isl_space_free(space);
3093 return n;
3096 /* For each nested access parameter in "space",
3097 * construct a corresponding pet_expr, place it in args and
3098 * record its position in "param2pos".
3099 * "n_arg" is the number of elements that are already in args.
3100 * The position recorded in "param2pos" takes this number into account.
3101 * If the pet_expr corresponding to a parameter is identical to
3102 * the pet_expr corresponding to an earlier parameter, then these two
3103 * parameters are made to refer to the same element in args.
3105 * Return the final number of elements in args or -1 if an error has occurred.
3107 int PetScan::extract_nested(__isl_keep isl_space *space,
3108 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
3110 int nparam;
3112 nparam = isl_space_dim(space, isl_dim_param);
3113 for (int i = 0; i < nparam; ++i) {
3114 int j;
3115 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3116 Expr *nested;
3118 if (!is_nested_parameter(id)) {
3119 isl_id_free(id);
3120 continue;
3123 nested = (Expr *) isl_id_get_user(id);
3124 args[n_arg] = extract_expr(nested);
3125 if (!args[n_arg])
3126 return -1;
3128 for (j = 0; j < n_arg; ++j)
3129 if (pet_expr_is_equal(args[j], args[n_arg]))
3130 break;
3132 if (j < n_arg) {
3133 pet_expr_free(args[n_arg]);
3134 args[n_arg] = NULL;
3135 param2pos[i] = j;
3136 } else
3137 param2pos[i] = n_arg++;
3139 isl_id_free(id);
3142 return n_arg;
3145 /* For each nested access parameter in the access relations in "expr",
3146 * construct a corresponding pet_expr, place it in expr->args and
3147 * record its position in "param2pos".
3148 * n is the number of nested access parameters.
3150 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
3151 std::map<int,int> &param2pos)
3153 isl_space *space;
3155 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
3156 expr->n_arg = n;
3157 if (!expr->args)
3158 goto error;
3160 space = isl_map_get_space(expr->acc.access);
3161 n = extract_nested(space, 0, expr->args, param2pos);
3162 isl_space_free(space);
3164 if (n < 0)
3165 goto error;
3167 expr->n_arg = n;
3168 return expr;
3169 error:
3170 pet_expr_free(expr);
3171 return NULL;
3174 /* Look for parameters in any access relation in "expr" that
3175 * refer to nested accesses. In particular, these are
3176 * parameters with no name.
3178 * If there are any such parameters, then the domain of the index
3179 * expression and the access relation, which is still [] at this point,
3180 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
3181 * (after identifying identical nested accesses).
3183 * This transformation is performed in several steps.
3184 * We first extract the arguments in extract_nested.
3185 * param2pos maps the original parameter position to the position
3186 * of the argument.
3187 * Then we move these parameters to input dimension.
3188 * t2pos maps the positions of these temporary input dimensions
3189 * to the positions of the corresponding arguments.
3190 * Finally, we express there temporary dimensions in term of the domain
3191 * [[] -> [t_1,...,t_n]] and precompose index expression and access
3192 * relations with this function.
3194 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
3196 int n;
3197 int nparam;
3198 isl_space *space;
3199 isl_local_space *ls;
3200 isl_aff *aff;
3201 isl_multi_aff *ma;
3202 std::map<int,int> param2pos;
3203 std::map<int,int> t2pos;
3205 if (!expr)
3206 return expr;
3208 for (int i = 0; i < expr->n_arg; ++i) {
3209 expr->args[i] = resolve_nested(expr->args[i]);
3210 if (!expr->args[i]) {
3211 pet_expr_free(expr);
3212 return NULL;
3216 if (expr->type != pet_expr_access)
3217 return expr;
3219 n = n_nested_parameter(expr->acc.access);
3220 if (n == 0)
3221 return expr;
3223 expr = extract_nested(expr, n, param2pos);
3224 if (!expr)
3225 return NULL;
3227 expr = pet_expr_access_align_params(expr);
3228 if (!expr)
3229 return NULL;
3230 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
3232 n = 0;
3233 for (int i = nparam - 1; i >= 0; --i) {
3234 isl_id *id = isl_map_get_dim_id(expr->acc.access,
3235 isl_dim_param, i);
3236 if (!is_nested_parameter(id)) {
3237 isl_id_free(id);
3238 continue;
3241 expr->acc.access = isl_map_move_dims(expr->acc.access,
3242 isl_dim_in, n, isl_dim_param, i, 1);
3243 expr->acc.index = isl_multi_pw_aff_move_dims(expr->acc.index,
3244 isl_dim_in, n, isl_dim_param, i, 1);
3245 t2pos[n] = param2pos[i];
3246 n++;
3248 isl_id_free(id);
3251 space = isl_multi_pw_aff_get_space(expr->acc.index);
3252 space = isl_space_set_from_params(isl_space_params(space));
3253 space = isl_space_add_dims(space, isl_dim_set, expr->n_arg);
3254 space = isl_space_wrap(isl_space_from_range(space));
3255 ls = isl_local_space_from_space(isl_space_copy(space));
3256 space = isl_space_from_domain(space);
3257 space = isl_space_add_dims(space, isl_dim_out, n);
3258 ma = isl_multi_aff_zero(space);
3260 for (int i = 0; i < n; ++i) {
3261 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3262 isl_dim_set, t2pos[i]);
3263 ma = isl_multi_aff_set_aff(ma, i, aff);
3265 isl_local_space_free(ls);
3267 expr->acc.access = isl_map_preimage_domain_multi_aff(expr->acc.access,
3268 isl_multi_aff_copy(ma));
3269 expr->acc.index = isl_multi_pw_aff_pullback_multi_aff(expr->acc.index,
3270 ma);
3272 return expr;
3275 /* Return the file offset of the expansion location of "Loc".
3277 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3279 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3282 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3284 /* Return a SourceLocation for the location after the first semicolon
3285 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3286 * call it and also skip trailing spaces and newline.
3288 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3289 const LangOptions &LO)
3291 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3294 #else
3296 /* Return a SourceLocation for the location after the first semicolon
3297 * after "loc". If Lexer::findLocationAfterToken is not available,
3298 * we look in the underlying character data for the first semicolon.
3300 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3301 const LangOptions &LO)
3303 const char *semi;
3304 const char *s = SM.getCharacterData(loc);
3306 semi = strchr(s, ';');
3307 if (!semi)
3308 return SourceLocation();
3309 return loc.getFileLocWithOffset(semi + 1 - s);
3312 #endif
3314 /* If the token at "loc" is the first token on the line, then return
3315 * a location referring to the start of the line.
3316 * Otherwise, return "loc".
3318 * This function is used to extend a scop to the start of the line
3319 * if the first token of the scop is also the first token on the line.
3321 * We look for the first token on the line. If its location is equal to "loc",
3322 * then the latter is the location of the first token on the line.
3324 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3325 SourceManager &SM, const LangOptions &LO)
3327 std::pair<FileID, unsigned> file_offset_pair;
3328 llvm::StringRef file;
3329 const char *pos;
3330 Token tok;
3331 SourceLocation token_loc, line_loc;
3332 int col;
3334 loc = SM.getExpansionLoc(loc);
3335 col = SM.getExpansionColumnNumber(loc);
3336 line_loc = loc.getLocWithOffset(1 - col);
3337 file_offset_pair = SM.getDecomposedLoc(line_loc);
3338 file = SM.getBufferData(file_offset_pair.first, NULL);
3339 pos = file.data() + file_offset_pair.second;
3341 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3342 file.begin(), pos, file.end());
3343 lexer.LexFromRawLexer(tok);
3344 token_loc = tok.getLocation();
3346 if (token_loc == loc)
3347 return line_loc;
3348 else
3349 return loc;
3352 /* Convert a top-level pet_expr to a pet_scop with one statement.
3353 * This mainly involves resolving nested expression parameters
3354 * and setting the name of the iteration space.
3355 * The name is given by "label" if it is non-NULL. Otherwise,
3356 * it is of the form S_<n_stmt>.
3357 * start and end of the pet_scop are derived from those of "stmt".
3359 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
3360 __isl_take isl_id *label)
3362 struct pet_stmt *ps;
3363 struct pet_scop *scop;
3364 SourceLocation loc = stmt->getLocStart();
3365 SourceManager &SM = PP.getSourceManager();
3366 const LangOptions &LO = PP.getLangOpts();
3367 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3368 unsigned start, end;
3370 expr = resolve_nested(expr);
3371 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
3372 scop = pet_scop_from_pet_stmt(ctx, ps);
3374 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3375 start = getExpansionOffset(SM, loc);
3376 loc = stmt->getLocEnd();
3377 loc = location_after_semi(loc, SM, LO);
3378 end = getExpansionOffset(SM, loc);
3380 scop = pet_scop_update_start_end(scop, start, end);
3381 return scop;
3384 /* Check if we can extract an affine expression from "expr".
3385 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3386 * We turn on autodetection so that we won't generate any warnings
3387 * and turn off nesting, so that we won't accept any non-affine constructs.
3389 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3391 isl_pw_aff *pwaff;
3392 int save_autodetect = options->autodetect;
3393 bool save_nesting = nesting_enabled;
3395 options->autodetect = 1;
3396 nesting_enabled = false;
3398 pwaff = extract_affine(expr);
3400 options->autodetect = save_autodetect;
3401 nesting_enabled = save_nesting;
3403 return pwaff;
3406 /* Check whether "expr" is an affine expression.
3408 bool PetScan::is_affine(Expr *expr)
3410 isl_pw_aff *pwaff;
3412 pwaff = try_extract_affine(expr);
3413 isl_pw_aff_free(pwaff);
3415 return pwaff != NULL;
3418 /* Check if we can extract an affine constraint from "expr".
3419 * Return the constraint as an isl_set if we can and NULL otherwise.
3420 * We turn on autodetection so that we won't generate any warnings
3421 * and turn off nesting, so that we won't accept any non-affine constructs.
3423 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3425 isl_pw_aff *cond;
3426 int save_autodetect = options->autodetect;
3427 bool save_nesting = nesting_enabled;
3429 options->autodetect = 1;
3430 nesting_enabled = false;
3432 cond = extract_condition(expr);
3434 options->autodetect = save_autodetect;
3435 nesting_enabled = save_nesting;
3437 return cond;
3440 /* Check whether "expr" is an affine constraint.
3442 bool PetScan::is_affine_condition(Expr *expr)
3444 isl_pw_aff *cond;
3446 cond = try_extract_affine_condition(expr);
3447 isl_pw_aff_free(cond);
3449 return cond != NULL;
3452 /* Check if we can extract a condition from "expr".
3453 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3454 * If allow_nested is set, then the condition may involve parameters
3455 * corresponding to nested accesses.
3456 * We turn on autodetection so that we won't generate any warnings.
3458 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3460 isl_pw_aff *cond;
3461 int save_autodetect = options->autodetect;
3462 bool save_nesting = nesting_enabled;
3464 options->autodetect = 1;
3465 nesting_enabled = allow_nested;
3466 cond = extract_condition(expr);
3468 options->autodetect = save_autodetect;
3469 nesting_enabled = save_nesting;
3471 return cond;
3474 /* If the top-level expression of "stmt" is an assignment, then
3475 * return that assignment as a BinaryOperator.
3476 * Otherwise return NULL.
3478 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3480 BinaryOperator *ass;
3482 if (!stmt)
3483 return NULL;
3484 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3485 return NULL;
3487 ass = cast<BinaryOperator>(stmt);
3488 if(ass->getOpcode() != BO_Assign)
3489 return NULL;
3491 return ass;
3494 /* Check if the given if statement is a conditional assignement
3495 * with a non-affine condition. If so, construct a pet_scop
3496 * corresponding to this conditional assignment. Otherwise return NULL.
3498 * In particular we check if "stmt" is of the form
3500 * if (condition)
3501 * a = f(...);
3502 * else
3503 * a = g(...);
3505 * where a is some array or scalar access.
3506 * The constructed pet_scop then corresponds to the expression
3508 * a = condition ? f(...) : g(...)
3510 * All access relations in f(...) are intersected with condition
3511 * while all access relation in g(...) are intersected with the complement.
3513 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3515 BinaryOperator *ass_then, *ass_else;
3516 isl_multi_pw_aff *write_then, *write_else;
3517 isl_set *cond, *comp;
3518 isl_multi_pw_aff *index;
3519 isl_pw_aff *pa;
3520 int equal;
3521 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3522 bool save_nesting = nesting_enabled;
3524 if (!options->detect_conditional_assignment)
3525 return NULL;
3527 ass_then = top_assignment_or_null(stmt->getThen());
3528 ass_else = top_assignment_or_null(stmt->getElse());
3530 if (!ass_then || !ass_else)
3531 return NULL;
3533 if (is_affine_condition(stmt->getCond()))
3534 return NULL;
3536 write_then = extract_index(ass_then->getLHS());
3537 write_else = extract_index(ass_else->getLHS());
3539 equal = isl_multi_pw_aff_plain_is_equal(write_then, write_else);
3540 isl_multi_pw_aff_free(write_else);
3541 if (equal < 0 || !equal) {
3542 isl_multi_pw_aff_free(write_then);
3543 return NULL;
3546 nesting_enabled = allow_nested;
3547 pa = extract_condition(stmt->getCond());
3548 nesting_enabled = save_nesting;
3549 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3550 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3551 index = isl_multi_pw_aff_from_range(isl_multi_pw_aff_from_pw_aff(pa));
3553 pe_cond = pet_expr_from_index(index);
3555 pe_then = extract_expr(ass_then->getRHS());
3556 pe_then = pet_expr_restrict(pe_then, cond);
3557 pe_else = extract_expr(ass_else->getRHS());
3558 pe_else = pet_expr_restrict(pe_else, comp);
3560 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
3561 pe_write = pet_expr_from_index_and_depth(write_then,
3562 extract_depth(write_then));
3563 if (pe_write) {
3564 pe_write->acc.write = 1;
3565 pe_write->acc.read = 0;
3567 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
3568 return extract(stmt, pe);
3571 /* Create a pet_scop with a single statement evaluating "cond"
3572 * and writing the result to a virtual scalar, as expressed by
3573 * "index".
3575 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
3576 __isl_take isl_multi_pw_aff *index)
3578 struct pet_expr *expr, *write;
3579 struct pet_stmt *ps;
3580 struct pet_scop *scop;
3581 SourceLocation loc = cond->getLocStart();
3582 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3584 write = pet_expr_from_index(index);
3585 if (write) {
3586 write->acc.write = 1;
3587 write->acc.read = 0;
3589 expr = extract_expr(cond);
3590 expr = resolve_nested(expr);
3591 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
3592 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
3593 scop = pet_scop_from_pet_stmt(ctx, ps);
3594 scop = resolve_nested(scop);
3596 return scop;
3599 extern "C" {
3600 static struct pet_expr *embed_access(struct pet_expr *expr, void *user);
3603 /* Precompose the access relation and the index expression associated
3604 * to "expr" with the function pointed to by "user",
3605 * thereby embedding the access relation in the domain of this function.
3606 * The initial domain of the access relation and the index expression
3607 * is the zero-dimensional domain.
3609 static struct pet_expr *embed_access(struct pet_expr *expr, void *user)
3611 isl_multi_aff *ma = (isl_multi_aff *) user;
3613 expr->acc.access = isl_map_preimage_domain_multi_aff(expr->acc.access,
3614 isl_multi_aff_copy(ma));
3615 expr->acc.index = isl_multi_pw_aff_pullback_multi_aff(expr->acc.index,
3616 isl_multi_aff_copy(ma));
3617 if (!expr->acc.access || !expr->acc.index)
3618 goto error;
3620 return expr;
3621 error:
3622 pet_expr_free(expr);
3623 return NULL;
3626 /* Precompose all access relations in "expr" with "ma", thereby
3627 * embedding them in the domain of "ma".
3629 static struct pet_expr *embed(struct pet_expr *expr,
3630 __isl_keep isl_multi_aff *ma)
3632 return pet_expr_map_access(expr, &embed_access, ma);
3635 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3637 static int n_nested_parameter(__isl_keep isl_set *set)
3639 isl_space *space;
3640 int n;
3642 space = isl_set_get_space(set);
3643 n = n_nested_parameter(space);
3644 isl_space_free(space);
3646 return n;
3649 /* Remove all parameters from "map" that refer to nested accesses.
3651 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
3653 int nparam;
3654 isl_space *space;
3656 space = isl_map_get_space(map);
3657 nparam = isl_space_dim(space, isl_dim_param);
3658 for (int i = nparam - 1; i >= 0; --i)
3659 if (is_nested_parameter(space, i))
3660 map = isl_map_project_out(map, isl_dim_param, i, 1);
3661 isl_space_free(space);
3663 return map;
3666 /* Remove all parameters from "mpa" that refer to nested accesses.
3668 static __isl_give isl_multi_pw_aff *remove_nested_parameters(
3669 __isl_take isl_multi_pw_aff *mpa)
3671 int nparam;
3672 isl_space *space;
3674 space = isl_multi_pw_aff_get_space(mpa);
3675 nparam = isl_space_dim(space, isl_dim_param);
3676 for (int i = nparam - 1; i >= 0; --i) {
3677 if (!is_nested_parameter(space, i))
3678 continue;
3679 mpa = isl_multi_pw_aff_drop_dims(mpa, isl_dim_param, i, 1);
3681 isl_space_free(space);
3683 return mpa;
3686 /* Remove all parameters from the index expression and access relation of "expr"
3687 * that refer to nested accesses.
3689 static struct pet_expr *remove_nested_parameters(struct pet_expr *expr)
3691 expr->acc.access = remove_nested_parameters(expr->acc.access);
3692 expr->acc.index = remove_nested_parameters(expr->acc.index);
3693 if (!expr->acc.access || !expr->acc.index)
3694 goto error;
3696 return expr;
3697 error:
3698 pet_expr_free(expr);
3699 return NULL;
3702 extern "C" {
3703 static struct pet_expr *expr_remove_nested_parameters(
3704 struct pet_expr *expr, void *user);
3707 static struct pet_expr *expr_remove_nested_parameters(
3708 struct pet_expr *expr, void *user)
3710 return remove_nested_parameters(expr);
3713 /* Remove all nested access parameters from the schedule and all
3714 * accesses of "stmt".
3715 * There is no need to remove them from the domain as these parameters
3716 * have already been removed from the domain when this function is called.
3718 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
3720 if (!stmt)
3721 return NULL;
3722 stmt->schedule = remove_nested_parameters(stmt->schedule);
3723 stmt->body = pet_expr_map_access(stmt->body,
3724 &expr_remove_nested_parameters, NULL);
3725 if (!stmt->schedule || !stmt->body)
3726 goto error;
3727 for (int i = 0; i < stmt->n_arg; ++i) {
3728 stmt->args[i] = pet_expr_map_access(stmt->args[i],
3729 &expr_remove_nested_parameters, NULL);
3730 if (!stmt->args[i])
3731 goto error;
3734 return stmt;
3735 error:
3736 pet_stmt_free(stmt);
3737 return NULL;
3740 /* For each nested access parameter in the domain of "stmt",
3741 * construct a corresponding pet_expr, place it before the original
3742 * elements in stmt->args and record its position in "param2pos".
3743 * n is the number of nested access parameters.
3745 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3746 std::map<int,int> &param2pos)
3748 int i;
3749 isl_space *space;
3750 int n_arg;
3751 struct pet_expr **args;
3753 n_arg = stmt->n_arg;
3754 args = isl_calloc_array(ctx, struct pet_expr *, n + n_arg);
3755 if (!args)
3756 goto error;
3758 space = isl_set_get_space(stmt->domain);
3759 n_arg = extract_nested(space, 0, args, param2pos);
3760 isl_space_free(space);
3762 if (n_arg < 0)
3763 goto error;
3765 for (i = 0; i < stmt->n_arg; ++i)
3766 args[n_arg + i] = stmt->args[i];
3767 free(stmt->args);
3768 stmt->args = args;
3769 stmt->n_arg += n_arg;
3771 return stmt;
3772 error:
3773 if (args) {
3774 for (i = 0; i < n; ++i)
3775 pet_expr_free(args[i]);
3776 free(args);
3778 pet_stmt_free(stmt);
3779 return NULL;
3782 /* Check whether any of the arguments i of "stmt" starting at position "n"
3783 * is equal to one of the first "n" arguments j.
3784 * If so, combine the constraints on arguments i and j and remove
3785 * argument i.
3787 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3789 int i, j;
3790 isl_map *map;
3792 if (!stmt)
3793 return NULL;
3794 if (n == 0)
3795 return stmt;
3796 if (n == stmt->n_arg)
3797 return stmt;
3799 map = isl_set_unwrap(stmt->domain);
3801 for (i = stmt->n_arg - 1; i >= n; --i) {
3802 for (j = 0; j < n; ++j)
3803 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3804 break;
3805 if (j >= n)
3806 continue;
3808 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3809 map = isl_map_project_out(map, isl_dim_out, i, 1);
3811 pet_expr_free(stmt->args[i]);
3812 for (j = i; j + 1 < stmt->n_arg; ++j)
3813 stmt->args[j] = stmt->args[j + 1];
3814 stmt->n_arg--;
3817 stmt->domain = isl_map_wrap(map);
3818 if (!stmt->domain)
3819 goto error;
3820 return stmt;
3821 error:
3822 pet_stmt_free(stmt);
3823 return NULL;
3826 /* Look for parameters in the iteration domain of "stmt" that
3827 * refer to nested accesses. In particular, these are
3828 * parameters with no name.
3830 * If there are any such parameters, then as many extra variables
3831 * (after identifying identical nested accesses) are inserted in the
3832 * range of the map wrapped inside the domain, before the original variables.
3833 * If the original domain is not a wrapped map, then a new wrapped
3834 * map is created with zero output dimensions.
3835 * The parameters are then equated to the corresponding output dimensions
3836 * and subsequently projected out, from the iteration domain,
3837 * the schedule and the access relations.
3838 * For each of the output dimensions, a corresponding argument
3839 * expression is inserted. Initially they are created with
3840 * a zero-dimensional domain, so they have to be embedded
3841 * in the current iteration domain.
3842 * param2pos maps the position of the parameter to the position
3843 * of the corresponding output dimension in the wrapped map.
3845 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3847 int n;
3848 int nparam;
3849 unsigned n_arg;
3850 isl_map *map;
3851 isl_space *space;
3852 isl_multi_aff *ma;
3853 std::map<int,int> param2pos;
3855 if (!stmt)
3856 return NULL;
3858 n = n_nested_parameter(stmt->domain);
3859 if (n == 0)
3860 return stmt;
3862 n_arg = stmt->n_arg;
3863 stmt = extract_nested(stmt, n, param2pos);
3864 if (!stmt)
3865 return NULL;
3867 n = stmt->n_arg - n_arg;
3868 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3869 if (isl_set_is_wrapping(stmt->domain))
3870 map = isl_set_unwrap(stmt->domain);
3871 else
3872 map = isl_map_from_domain(stmt->domain);
3873 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3875 for (int i = nparam - 1; i >= 0; --i) {
3876 isl_id *id;
3878 if (!is_nested_parameter(map, i))
3879 continue;
3881 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
3882 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3883 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3884 param2pos[i]);
3885 map = isl_map_project_out(map, isl_dim_param, i, 1);
3888 stmt->domain = isl_map_wrap(map);
3890 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
3891 space = isl_space_from_domain(isl_space_domain(space));
3892 ma = isl_multi_aff_zero(space);
3893 for (int pos = 0; pos < n; ++pos)
3894 stmt->args[pos] = embed(stmt->args[pos], ma);
3895 isl_multi_aff_free(ma);
3897 stmt = remove_nested_parameters(stmt);
3898 stmt = remove_duplicate_arguments(stmt, n);
3900 return stmt;
3903 /* For each statement in "scop", move the parameters that correspond
3904 * to nested access into the ranges of the domains and create
3905 * corresponding argument expressions.
3907 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3909 if (!scop)
3910 return NULL;
3912 for (int i = 0; i < scop->n_stmt; ++i) {
3913 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3914 if (!scop->stmts[i])
3915 goto error;
3918 return scop;
3919 error:
3920 pet_scop_free(scop);
3921 return NULL;
3924 /* Given an access expression "expr", is the variable accessed by
3925 * "expr" assigned anywhere inside "scop"?
3927 static bool is_assigned(pet_expr *expr, pet_scop *scop)
3929 bool assigned = false;
3930 isl_id *id;
3932 id = pet_expr_access_get_id(expr);
3933 assigned = pet_scop_writes(scop, id);
3934 isl_id_free(id);
3936 return assigned;
3939 /* Are all nested access parameters in "pa" allowed given "scop".
3940 * In particular, is none of them written by anywhere inside "scop".
3942 * If "scop" has any skip conditions, then no nested access parameters
3943 * are allowed. In particular, if there is any nested access in a guard
3944 * for a piece of code containing a "continue", then we want to introduce
3945 * a separate statement for evaluating this guard so that we can express
3946 * that the result is false for all previous iterations.
3948 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3950 int nparam;
3952 if (!scop)
3953 return true;
3955 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3956 for (int i = 0; i < nparam; ++i) {
3957 Expr *nested;
3958 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3959 pet_expr *expr;
3960 bool allowed;
3962 if (!is_nested_parameter(id)) {
3963 isl_id_free(id);
3964 continue;
3967 if (pet_scop_has_skip(scop, pet_skip_now)) {
3968 isl_id_free(id);
3969 return false;
3972 nested = (Expr *) isl_id_get_user(id);
3973 expr = extract_expr(nested);
3974 allowed = expr && expr->type == pet_expr_access &&
3975 !is_assigned(expr, scop);
3977 pet_expr_free(expr);
3978 isl_id_free(id);
3980 if (!allowed)
3981 return false;
3984 return true;
3987 /* Do we need to construct a skip condition of the given type
3988 * on an if statement, given that the if condition is non-affine?
3990 * pet_scop_filter_skip can only handle the case where the if condition
3991 * holds (the then branch) and the skip condition is universal.
3992 * In any other case, we need to construct a new skip condition.
3994 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3995 bool have_else, enum pet_skip type)
3997 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
3998 return true;
3999 if (scop_then && pet_scop_has_skip(scop_then, type) &&
4000 !pet_scop_has_universal_skip(scop_then, type))
4001 return true;
4002 return false;
4005 /* Do we need to construct a skip condition of the given type
4006 * on an if statement, given that the if condition is affine?
4008 * There is no need to construct a new skip condition if all
4009 * the skip conditions are affine.
4011 static bool need_skip_aff(struct pet_scop *scop_then,
4012 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
4014 if (scop_then && pet_scop_has_var_skip(scop_then, type))
4015 return true;
4016 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
4017 return true;
4018 return false;
4021 /* Do we need to construct a skip condition of the given type
4022 * on an if statement?
4024 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
4025 bool have_else, enum pet_skip type, bool affine)
4027 if (affine)
4028 return need_skip_aff(scop_then, scop_else, have_else, type);
4029 else
4030 return need_skip(scop_then, scop_else, have_else, type);
4033 /* Construct an affine expression pet_expr that evaluates
4034 * to the constant "val".
4036 static struct pet_expr *universally(isl_ctx *ctx, int val)
4038 isl_local_space *ls;
4039 isl_aff *aff;
4040 isl_multi_pw_aff *mpa;
4042 ls = isl_local_space_from_space(isl_space_set_alloc(ctx, 0, 0));
4043 aff = isl_aff_val_on_domain(ls, isl_val_int_from_si(ctx, val));
4044 mpa = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4046 return pet_expr_from_index(mpa);
4049 /* Construct an affine expression pet_expr that evaluates
4050 * to the constant 1.
4052 static struct pet_expr *universally_true(isl_ctx *ctx)
4054 return universally(ctx, 1);
4057 /* Construct an affine expression pet_expr that evaluates
4058 * to the constant 0.
4060 static struct pet_expr *universally_false(isl_ctx *ctx)
4062 return universally(ctx, 0);
4065 /* Given an index expression "test_index" for the if condition,
4066 * an index expression "skip_index" for the skip condition and
4067 * scops for the then and else branches, construct a scop for
4068 * computing "skip_index".
4070 * The computed scop contains a single statement that essentially does
4072 * skip_index = test_cond ? skip_cond_then : skip_cond_else
4074 * If the skip conditions of the then and/or else branch are not affine,
4075 * then they need to be filtered by test_index.
4076 * If they are missing, then this means the skip condition is false.
4078 * Since we are constructing a skip condition for the if statement,
4079 * the skip conditions on the then and else branches are removed.
4081 static struct pet_scop *extract_skip(PetScan *scan,
4082 __isl_take isl_multi_pw_aff *test_index,
4083 __isl_take isl_multi_pw_aff *skip_index,
4084 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
4085 enum pet_skip type)
4087 struct pet_expr *expr_then, *expr_else, *expr, *expr_skip;
4088 struct pet_stmt *stmt;
4089 struct pet_scop *scop;
4090 isl_ctx *ctx = scan->ctx;
4092 if (!scop_then)
4093 goto error;
4094 if (have_else && !scop_else)
4095 goto error;
4097 if (pet_scop_has_skip(scop_then, type)) {
4098 expr_then = pet_scop_get_skip_expr(scop_then, type);
4099 pet_scop_reset_skip(scop_then, type);
4100 if (!pet_expr_is_affine(expr_then))
4101 expr_then = pet_expr_filter(expr_then,
4102 isl_multi_pw_aff_copy(test_index), 1);
4103 } else
4104 expr_then = universally_false(ctx);
4106 if (have_else && pet_scop_has_skip(scop_else, type)) {
4107 expr_else = pet_scop_get_skip_expr(scop_else, type);
4108 pet_scop_reset_skip(scop_else, type);
4109 if (!pet_expr_is_affine(expr_else))
4110 expr_else = pet_expr_filter(expr_else,
4111 isl_multi_pw_aff_copy(test_index), 0);
4112 } else
4113 expr_else = universally_false(ctx);
4115 expr = pet_expr_from_index(test_index);
4116 expr = pet_expr_new_ternary(ctx, expr, expr_then, expr_else);
4117 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4118 if (expr_skip) {
4119 expr_skip->acc.write = 1;
4120 expr_skip->acc.read = 0;
4122 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4123 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, scan->n_stmt++, expr);
4125 scop = pet_scop_from_pet_stmt(ctx, stmt);
4126 scop = scop_add_array(scop, skip_index, scan->ast_context);
4127 isl_multi_pw_aff_free(skip_index);
4129 return scop;
4130 error:
4131 isl_multi_pw_aff_free(test_index);
4132 isl_multi_pw_aff_free(skip_index);
4133 return NULL;
4136 /* Is scop's skip_now condition equal to its skip_later condition?
4137 * In particular, this means that it either has no skip_now condition
4138 * or both a skip_now and a skip_later condition (that are equal to each other).
4140 static bool skip_equals_skip_later(struct pet_scop *scop)
4142 int has_skip_now, has_skip_later;
4143 int equal;
4144 isl_multi_pw_aff *skip_now, *skip_later;
4146 if (!scop)
4147 return false;
4148 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
4149 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
4150 if (has_skip_now != has_skip_later)
4151 return false;
4152 if (!has_skip_now)
4153 return true;
4155 skip_now = pet_scop_get_skip(scop, pet_skip_now);
4156 skip_later = pet_scop_get_skip(scop, pet_skip_later);
4157 equal = isl_multi_pw_aff_is_equal(skip_now, skip_later);
4158 isl_multi_pw_aff_free(skip_now);
4159 isl_multi_pw_aff_free(skip_later);
4161 return equal;
4164 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
4166 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
4168 pet_scop_reset_skip(scop1, pet_skip_later);
4169 pet_scop_reset_skip(scop2, pet_skip_later);
4172 /* Structure that handles the construction of skip conditions.
4174 * scop_then and scop_else represent the then and else branches
4175 * of the if statement
4177 * skip[type] is true if we need to construct a skip condition of that type
4178 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
4179 * are equal to each other
4180 * index[type] is an index expression from a zero-dimension domain
4181 * to the virtual array representing the skip condition
4182 * scop[type] is a scop for computing the skip condition
4184 struct pet_skip_info {
4185 isl_ctx *ctx;
4187 bool skip[2];
4188 bool equal;
4189 isl_multi_pw_aff *index[2];
4190 struct pet_scop *scop[2];
4192 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
4194 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
4197 /* Structure that handles the construction of skip conditions on if statements.
4199 * scop_then and scop_else represent the then and else branches
4200 * of the if statement
4202 struct pet_skip_info_if : public pet_skip_info {
4203 struct pet_scop *scop_then, *scop_else;
4204 bool have_else;
4206 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4207 struct pet_scop *scop_else, bool have_else, bool affine);
4208 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index,
4209 enum pet_skip type);
4210 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index);
4211 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
4212 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4213 int offset);
4214 struct pet_scop *add(struct pet_scop *scop, int offset);
4217 /* Initialize a pet_skip_info_if structure based on the then and else branches
4218 * and based on whether the if condition is affine or not.
4220 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4221 struct pet_scop *scop_else, bool have_else, bool affine) :
4222 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
4223 have_else(have_else)
4225 skip[pet_skip_now] =
4226 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
4227 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
4228 (!have_else || skip_equals_skip_later(scop_else));
4229 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4230 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
4233 /* If we need to construct a skip condition of the given type,
4234 * then do so now.
4236 * "mpa" represents the if condition.
4238 void pet_skip_info_if::extract(PetScan *scan,
4239 __isl_keep isl_multi_pw_aff *mpa, enum pet_skip type)
4241 isl_ctx *ctx;
4243 if (!skip[type])
4244 return;
4246 ctx = isl_multi_pw_aff_get_ctx(mpa);
4247 index[type] = create_test_index(ctx, scan->n_test++);
4248 scop[type] = extract_skip(scan, isl_multi_pw_aff_copy(mpa),
4249 isl_multi_pw_aff_copy(index[type]),
4250 scop_then, scop_else, have_else, type);
4253 /* Construct the required skip conditions, given the if condition "index".
4255 void pet_skip_info_if::extract(PetScan *scan,
4256 __isl_keep isl_multi_pw_aff *index)
4258 extract(scan, index, pet_skip_now);
4259 extract(scan, index, pet_skip_later);
4260 if (equal)
4261 drop_skip_later(scop_then, scop_else);
4264 /* Construct the required skip conditions, given the if condition "cond".
4266 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
4268 isl_multi_pw_aff *test;
4270 if (!skip[pet_skip_now] && !skip[pet_skip_later])
4271 return;
4273 test = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_copy(cond));
4274 test = isl_multi_pw_aff_from_range(test);
4275 extract(scan, test);
4276 isl_multi_pw_aff_free(test);
4279 /* Add the computed skip condition of the give type to "main" and
4280 * add the scop for computing the condition at the given offset.
4282 * If equal is set, then we only computed a skip condition for pet_skip_now,
4283 * but we also need to set it as main's pet_skip_later.
4285 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
4286 enum pet_skip type, int offset)
4288 if (!skip[type])
4289 return main;
4291 scop[type] = pet_scop_prefix(scop[type], offset);
4292 main = pet_scop_add_par(ctx, main, scop[type]);
4293 scop[type] = NULL;
4295 if (equal)
4296 main = pet_scop_set_skip(main, pet_skip_later,
4297 isl_multi_pw_aff_copy(index[type]));
4299 main = pet_scop_set_skip(main, type, index[type]);
4300 index[type] = NULL;
4302 return main;
4305 /* Add the computed skip conditions to "main" and
4306 * add the scops for computing the conditions at the given offset.
4308 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
4310 scop = add(scop, pet_skip_now, offset);
4311 scop = add(scop, pet_skip_later, offset);
4313 return scop;
4316 /* Construct a pet_scop for a non-affine if statement.
4318 * We create a separate statement that writes the result
4319 * of the non-affine condition to a virtual scalar.
4320 * A constraint requiring the value of this virtual scalar to be one
4321 * is added to the iteration domains of the then branch.
4322 * Similarly, a constraint requiring the value of this virtual scalar
4323 * to be zero is added to the iteration domains of the else branch, if any.
4324 * We adjust the schedules to ensure that the virtual scalar is written
4325 * before it is read.
4327 * If there are any breaks or continues in the then and/or else
4328 * branches, then we may have to compute a new skip condition.
4329 * This is handled using a pet_skip_info_if object.
4330 * On initialization, the object checks if skip conditions need
4331 * to be computed. If so, it does so in "extract" and adds them in "add".
4333 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
4334 struct pet_scop *scop_then, struct pet_scop *scop_else,
4335 bool have_else, int stmt_id)
4337 struct pet_scop *scop;
4338 isl_multi_pw_aff *test_index;
4339 int save_n_stmt = n_stmt;
4341 test_index = create_test_index(ctx, n_test++);
4342 n_stmt = stmt_id;
4343 scop = extract_non_affine_condition(cond,
4344 isl_multi_pw_aff_copy(test_index));
4345 n_stmt = save_n_stmt;
4346 scop = scop_add_array(scop, test_index, ast_context);
4348 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
4349 skip.extract(this, test_index);
4351 scop = pet_scop_prefix(scop, 0);
4352 scop_then = pet_scop_prefix(scop_then, 1);
4353 scop_then = pet_scop_filter(scop_then,
4354 isl_multi_pw_aff_copy(test_index), 1);
4355 if (have_else) {
4356 scop_else = pet_scop_prefix(scop_else, 1);
4357 scop_else = pet_scop_filter(scop_else, test_index, 0);
4358 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
4359 } else
4360 isl_multi_pw_aff_free(test_index);
4362 scop = pet_scop_add_seq(ctx, scop, scop_then);
4364 scop = skip.add(scop, 2);
4366 return scop;
4369 /* Construct a pet_scop for an if statement.
4371 * If the condition fits the pattern of a conditional assignment,
4372 * then it is handled by extract_conditional_assignment.
4373 * Otherwise, we do the following.
4375 * If the condition is affine, then the condition is added
4376 * to the iteration domains of the then branch, while the
4377 * opposite of the condition in added to the iteration domains
4378 * of the else branch, if any.
4379 * We allow the condition to be dynamic, i.e., to refer to
4380 * scalars or array elements that may be written to outside
4381 * of the given if statement. These nested accesses are then represented
4382 * as output dimensions in the wrapping iteration domain.
4383 * If it also written _inside_ the then or else branch, then
4384 * we treat the condition as non-affine.
4385 * As explained in extract_non_affine_if, this will introduce
4386 * an extra statement.
4387 * For aesthetic reasons, we want this statement to have a statement
4388 * number that is lower than those of the then and else branches.
4389 * In order to evaluate if will need such a statement, however, we
4390 * first construct scops for the then and else branches.
4391 * We therefore reserve a statement number if we might have to
4392 * introduce such an extra statement.
4394 * If the condition is not affine, then the scop is created in
4395 * extract_non_affine_if.
4397 * If there are any breaks or continues in the then and/or else
4398 * branches, then we may have to compute a new skip condition.
4399 * This is handled using a pet_skip_info_if object.
4400 * On initialization, the object checks if skip conditions need
4401 * to be computed. If so, it does so in "extract" and adds them in "add".
4403 struct pet_scop *PetScan::extract(IfStmt *stmt)
4405 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4406 isl_pw_aff *cond;
4407 int stmt_id;
4408 isl_set *set;
4409 isl_set *valid;
4411 scop = extract_conditional_assignment(stmt);
4412 if (scop)
4413 return scop;
4415 cond = try_extract_nested_condition(stmt->getCond());
4416 if (allow_nested && (!cond || has_nested(cond)))
4417 stmt_id = n_stmt++;
4420 assigned_value_cache cache(assigned_value);
4421 scop_then = extract(stmt->getThen());
4424 if (stmt->getElse()) {
4425 assigned_value_cache cache(assigned_value);
4426 scop_else = extract(stmt->getElse());
4427 if (options->autodetect) {
4428 if (scop_then && !scop_else) {
4429 partial = true;
4430 isl_pw_aff_free(cond);
4431 return scop_then;
4433 if (!scop_then && scop_else) {
4434 partial = true;
4435 isl_pw_aff_free(cond);
4436 return scop_else;
4441 if (cond &&
4442 (!is_nested_allowed(cond, scop_then) ||
4443 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4444 isl_pw_aff_free(cond);
4445 cond = NULL;
4447 if (allow_nested && !cond)
4448 return extract_non_affine_if(stmt->getCond(), scop_then,
4449 scop_else, stmt->getElse(), stmt_id);
4451 if (!cond)
4452 cond = extract_condition(stmt->getCond());
4454 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4455 skip.extract(this, cond);
4457 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4458 set = isl_pw_aff_non_zero_set(cond);
4459 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4461 if (stmt->getElse()) {
4462 set = isl_set_subtract(isl_set_copy(valid), set);
4463 scop_else = pet_scop_restrict(scop_else, set);
4464 scop = pet_scop_add_par(ctx, scop, scop_else);
4465 } else
4466 isl_set_free(set);
4467 scop = resolve_nested(scop);
4468 scop = pet_scop_restrict_context(scop, valid);
4470 if (skip)
4471 scop = pet_scop_prefix(scop, 0);
4472 scop = skip.add(scop, 1);
4474 return scop;
4477 /* Try and construct a pet_scop for a label statement.
4478 * We currently only allow labels on expression statements.
4480 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4482 isl_id *label;
4483 Stmt *sub;
4485 sub = stmt->getSubStmt();
4486 if (!isa<Expr>(sub)) {
4487 unsupported(stmt);
4488 return NULL;
4491 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4493 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4496 /* Return a one-dimensional multi piecewise affine expression that is equal
4497 * to the constant 1 and is defined over a zero-dimensional domain.
4499 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
4501 isl_space *space;
4502 isl_local_space *ls;
4503 isl_aff *aff;
4505 space = isl_space_set_alloc(ctx, 0, 0);
4506 ls = isl_local_space_from_space(space);
4507 aff = isl_aff_zero_on_domain(ls);
4508 aff = isl_aff_set_constant_si(aff, 1);
4510 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4513 /* Construct a pet_scop for a continue statement.
4515 * We simply create an empty scop with a universal pet_skip_now
4516 * skip condition. This skip condition will then be taken into
4517 * account by the enclosing loop construct, possibly after
4518 * being incorporated into outer skip conditions.
4520 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4522 pet_scop *scop;
4524 scop = pet_scop_empty(ctx);
4525 if (!scop)
4526 return NULL;
4528 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
4530 return scop;
4533 /* Construct a pet_scop for a break statement.
4535 * We simply create an empty scop with both a universal pet_skip_now
4536 * skip condition and a universal pet_skip_later skip condition.
4537 * These skip conditions will then be taken into
4538 * account by the enclosing loop construct, possibly after
4539 * being incorporated into outer skip conditions.
4541 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4543 pet_scop *scop;
4544 isl_multi_pw_aff *skip;
4546 scop = pet_scop_empty(ctx);
4547 if (!scop)
4548 return NULL;
4550 skip = one_mpa(ctx);
4551 scop = pet_scop_set_skip(scop, pet_skip_now,
4552 isl_multi_pw_aff_copy(skip));
4553 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
4555 return scop;
4558 /* Try and construct a pet_scop corresponding to "stmt".
4560 * If "stmt" is a compound statement, then "skip_declarations"
4561 * indicates whether we should skip initial declarations in the
4562 * compound statement.
4564 * If the constructed pet_scop is not a (possibly) partial representation
4565 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4566 * In particular, if skip_declarations, then we may have skipped declarations
4567 * inside "stmt" and so the pet_scop may not represent the entire "stmt".
4568 * Note that this function may be called with "stmt" referring to the entire
4569 * body of the function, including the outer braces. In such cases,
4570 * skip_declarations will be set and the braces will not be taken into
4571 * account in scop->start and scop->end.
4573 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
4575 struct pet_scop *scop;
4576 unsigned start, end;
4577 SourceLocation loc;
4578 SourceManager &SM = PP.getSourceManager();
4579 const LangOptions &LO = PP.getLangOpts();
4581 if (isa<Expr>(stmt))
4582 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4584 switch (stmt->getStmtClass()) {
4585 case Stmt::WhileStmtClass:
4586 scop = extract(cast<WhileStmt>(stmt));
4587 break;
4588 case Stmt::ForStmtClass:
4589 scop = extract_for(cast<ForStmt>(stmt));
4590 break;
4591 case Stmt::IfStmtClass:
4592 scop = extract(cast<IfStmt>(stmt));
4593 break;
4594 case Stmt::CompoundStmtClass:
4595 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
4596 break;
4597 case Stmt::LabelStmtClass:
4598 scop = extract(cast<LabelStmt>(stmt));
4599 break;
4600 case Stmt::ContinueStmtClass:
4601 scop = extract(cast<ContinueStmt>(stmt));
4602 break;
4603 case Stmt::BreakStmtClass:
4604 scop = extract(cast<BreakStmt>(stmt));
4605 break;
4606 case Stmt::DeclStmtClass:
4607 scop = extract(cast<DeclStmt>(stmt));
4608 break;
4609 default:
4610 unsupported(stmt);
4611 return NULL;
4614 if (partial || skip_declarations)
4615 return scop;
4617 loc = stmt->getLocStart();
4618 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
4619 start = getExpansionOffset(SM, loc);
4620 loc = PP.getLocForEndOfToken(stmt->getLocEnd());
4621 end = getExpansionOffset(SM, loc);
4622 scop = pet_scop_update_start_end(scop, start, end);
4624 return scop;
4627 /* Do we need to construct a skip condition of the given type
4628 * on a sequence of statements?
4630 * There is no need to construct a new skip condition if only
4631 * only of the two statements has a skip condition or if both
4632 * of their skip conditions are affine.
4634 * In principle we also don't need a new continuation variable if
4635 * the continuation of scop2 is affine, but then we would need
4636 * to allow more complicated forms of continuations.
4638 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4639 enum pet_skip type)
4641 if (!scop1 || !pet_scop_has_skip(scop1, type))
4642 return false;
4643 if (!scop2 || !pet_scop_has_skip(scop2, type))
4644 return false;
4645 if (pet_scop_has_affine_skip(scop1, type) &&
4646 pet_scop_has_affine_skip(scop2, type))
4647 return false;
4648 return true;
4651 /* Construct a scop for computing the skip condition of the given type and
4652 * with index expression "skip_index" for a sequence of two scops "scop1"
4653 * and "scop2".
4655 * The computed scop contains a single statement that essentially does
4657 * skip_index = skip_cond_1 ? 1 : skip_cond_2
4659 * or, in other words, skip_cond1 || skip_cond2.
4660 * In this expression, skip_cond_2 is filtered to reflect that it is
4661 * only evaluated when skip_cond_1 is false.
4663 * The skip condition on scop1 is not removed because it still needs
4664 * to be applied to scop2 when these two scops are combined.
4666 static struct pet_scop *extract_skip_seq(PetScan *ps,
4667 __isl_take isl_multi_pw_aff *skip_index,
4668 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4670 struct pet_expr *expr1, *expr2, *expr, *expr_skip;
4671 struct pet_stmt *stmt;
4672 struct pet_scop *scop;
4673 isl_ctx *ctx = ps->ctx;
4675 if (!scop1 || !scop2)
4676 goto error;
4678 expr1 = pet_scop_get_skip_expr(scop1, type);
4679 expr2 = pet_scop_get_skip_expr(scop2, type);
4680 pet_scop_reset_skip(scop2, type);
4682 expr2 = pet_expr_filter(expr2,
4683 isl_multi_pw_aff_copy(expr1->acc.index), 0);
4685 expr = universally_true(ctx);
4686 expr = pet_expr_new_ternary(ctx, expr1, expr, expr2);
4687 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4688 if (expr_skip) {
4689 expr_skip->acc.write = 1;
4690 expr_skip->acc.read = 0;
4692 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4693 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, ps->n_stmt++, expr);
4695 scop = pet_scop_from_pet_stmt(ctx, stmt);
4696 scop = scop_add_array(scop, skip_index, ps->ast_context);
4697 isl_multi_pw_aff_free(skip_index);
4699 return scop;
4700 error:
4701 isl_multi_pw_aff_free(skip_index);
4702 return NULL;
4705 /* Structure that handles the construction of skip conditions
4706 * on sequences of statements.
4708 * scop1 and scop2 represent the two statements that are combined
4710 struct pet_skip_info_seq : public pet_skip_info {
4711 struct pet_scop *scop1, *scop2;
4713 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4714 struct pet_scop *scop2);
4715 void extract(PetScan *scan, enum pet_skip type);
4716 void extract(PetScan *scan);
4717 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4718 int offset);
4719 struct pet_scop *add(struct pet_scop *scop, int offset);
4722 /* Initialize a pet_skip_info_seq structure based on
4723 * on the two statements that are going to be combined.
4725 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4726 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
4728 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
4729 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
4730 skip_equals_skip_later(scop2);
4731 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4732 need_skip_seq(scop1, scop2, pet_skip_later);
4735 /* If we need to construct a skip condition of the given type,
4736 * then do so now.
4738 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
4740 if (!skip[type])
4741 return;
4743 index[type] = create_test_index(ctx, scan->n_test++);
4744 scop[type] = extract_skip_seq(scan, isl_multi_pw_aff_copy(index[type]),
4745 scop1, scop2, type);
4748 /* Construct the required skip conditions.
4750 void pet_skip_info_seq::extract(PetScan *scan)
4752 extract(scan, pet_skip_now);
4753 extract(scan, pet_skip_later);
4754 if (equal)
4755 drop_skip_later(scop1, scop2);
4758 /* Add the computed skip condition of the given type to "main" and
4759 * add the scop for computing the condition at the given offset (the statement
4760 * number). Within this offset, the condition is computed at position 1
4761 * to ensure that it is computed after the corresponding statement.
4763 * If equal is set, then we only computed a skip condition for pet_skip_now,
4764 * but we also need to set it as main's pet_skip_later.
4766 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
4767 enum pet_skip type, int offset)
4769 if (!skip[type])
4770 return main;
4772 scop[type] = pet_scop_prefix(scop[type], 1);
4773 scop[type] = pet_scop_prefix(scop[type], offset);
4774 main = pet_scop_add_par(ctx, main, scop[type]);
4775 scop[type] = NULL;
4777 if (equal)
4778 main = pet_scop_set_skip(main, pet_skip_later,
4779 isl_multi_pw_aff_copy(index[type]));
4781 main = pet_scop_set_skip(main, type, index[type]);
4782 index[type] = NULL;
4784 return main;
4787 /* Add the computed skip conditions to "main" and
4788 * add the scops for computing the conditions at the given offset.
4790 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
4792 scop = add(scop, pet_skip_now, offset);
4793 scop = add(scop, pet_skip_later, offset);
4795 return scop;
4798 /* Extract a clone of the kill statement in "scop".
4799 * "scop" is expected to have been created from a DeclStmt
4800 * and should have the kill as its first statement.
4802 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
4804 struct pet_expr *kill;
4805 struct pet_stmt *stmt;
4806 isl_multi_pw_aff *index;
4807 isl_map *access;
4809 if (!scop)
4810 return NULL;
4811 if (scop->n_stmt < 1)
4812 isl_die(ctx, isl_error_internal,
4813 "expecting at least one statement", return NULL);
4814 stmt = scop->stmts[0];
4815 if (stmt->body->type != pet_expr_unary ||
4816 stmt->body->op != pet_op_kill)
4817 isl_die(ctx, isl_error_internal,
4818 "expecting kill statement", return NULL);
4820 index = isl_multi_pw_aff_copy(stmt->body->args[0]->acc.index);
4821 access = isl_map_copy(stmt->body->args[0]->acc.access);
4822 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
4823 access = isl_map_reset_tuple_id(access, isl_dim_in);
4824 kill = pet_expr_kill_from_access_and_index(access, index);
4825 return pet_stmt_from_pet_expr(ctx, stmt->line, NULL, n_stmt++, kill);
4828 /* Mark all arrays in "scop" as being exposed.
4830 static struct pet_scop *mark_exposed(struct pet_scop *scop)
4832 if (!scop)
4833 return NULL;
4834 for (int i = 0; i < scop->n_array; ++i)
4835 scop->arrays[i]->exposed = 1;
4836 return scop;
4839 /* Try and construct a pet_scop corresponding to (part of)
4840 * a sequence of statements.
4842 * "block" is set if the sequence respresents the children of
4843 * a compound statement.
4844 * "skip_declarations" is set if we should skip initial declarations
4845 * in the sequence of statements.
4847 * If there are any breaks or continues in the individual statements,
4848 * then we may have to compute a new skip condition.
4849 * This is handled using a pet_skip_info_seq object.
4850 * On initialization, the object checks if skip conditions need
4851 * to be computed. If so, it does so in "extract" and adds them in "add".
4853 * If "block" is set, then we need to insert kill statements at
4854 * the end of the block for any array that has been declared by
4855 * one of the statements in the sequence. Each of these declarations
4856 * results in the construction of a kill statement at the place
4857 * of the declaration, so we simply collect duplicates of
4858 * those kill statements and append these duplicates to the constructed scop.
4860 * If "block" is not set, then any array declared by one of the statements
4861 * in the sequence is marked as being exposed.
4863 * If autodetect is set, then we allow the extraction of only a subrange
4864 * of the sequence of statements. However, if there is at least one statement
4865 * for which we could not construct a scop and the final range contains
4866 * either no statements or at least one kill, then we discard the entire
4867 * range.
4869 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
4870 bool skip_declarations)
4872 pet_scop *scop;
4873 StmtIterator i;
4874 int j;
4875 bool partial_range = false;
4876 set<struct pet_stmt *> kills;
4877 set<struct pet_stmt *>::iterator it;
4879 scop = pet_scop_empty(ctx);
4880 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4881 Stmt *child = *i;
4882 struct pet_scop *scop_i;
4884 if (skip_declarations &&
4885 child->getStmtClass() == Stmt::DeclStmtClass)
4886 continue;
4888 scop_i = extract(child);
4889 if (scop->n_stmt != 0 && partial) {
4890 pet_scop_free(scop_i);
4891 break;
4893 pet_skip_info_seq skip(ctx, scop, scop_i);
4894 skip.extract(this);
4895 if (skip)
4896 scop_i = pet_scop_prefix(scop_i, 0);
4897 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4898 if (block)
4899 kills.insert(extract_kill(scop_i));
4900 else
4901 scop_i = mark_exposed(scop_i);
4903 scop_i = pet_scop_prefix(scop_i, j);
4904 if (options->autodetect) {
4905 if (scop_i)
4906 scop = pet_scop_add_seq(ctx, scop, scop_i);
4907 else
4908 partial_range = true;
4909 if (scop->n_stmt != 0 && !scop_i)
4910 partial = true;
4911 } else {
4912 scop = pet_scop_add_seq(ctx, scop, scop_i);
4915 scop = skip.add(scop, j);
4917 if (partial || !scop)
4918 break;
4921 for (it = kills.begin(); it != kills.end(); ++it) {
4922 pet_scop *scop_j;
4923 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4924 scop_j = pet_scop_prefix(scop_j, j);
4925 scop = pet_scop_add_seq(ctx, scop, scop_j);
4928 if (scop && partial_range) {
4929 if (scop->n_stmt == 0 || kills.size() != 0) {
4930 pet_scop_free(scop);
4931 return NULL;
4933 partial = true;
4936 return scop;
4939 /* Check if the scop marked by the user is exactly this Stmt
4940 * or part of this Stmt.
4941 * If so, return a pet_scop corresponding to the marked region.
4942 * Otherwise, return NULL.
4944 struct pet_scop *PetScan::scan(Stmt *stmt)
4946 SourceManager &SM = PP.getSourceManager();
4947 unsigned start_off, end_off;
4949 start_off = getExpansionOffset(SM, stmt->getLocStart());
4950 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4952 if (start_off > loc.end)
4953 return NULL;
4954 if (end_off < loc.start)
4955 return NULL;
4956 if (start_off >= loc.start && end_off <= loc.end) {
4957 return extract(stmt);
4960 StmtIterator start;
4961 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4962 Stmt *child = *start;
4963 if (!child)
4964 continue;
4965 start_off = getExpansionOffset(SM, child->getLocStart());
4966 end_off = getExpansionOffset(SM, child->getLocEnd());
4967 if (start_off < loc.start && end_off >= loc.end)
4968 return scan(child);
4969 if (start_off >= loc.start)
4970 break;
4973 StmtIterator end;
4974 for (end = start; end != stmt->child_end(); ++end) {
4975 Stmt *child = *end;
4976 start_off = SM.getFileOffset(child->getLocStart());
4977 if (start_off >= loc.end)
4978 break;
4981 return extract(StmtRange(start, end), false, false);
4984 /* Set the size of index "pos" of "array" to "size".
4985 * In particular, add a constraint of the form
4987 * i_pos < size
4989 * to array->extent and a constraint of the form
4991 * size >= 0
4993 * to array->context.
4995 static struct pet_array *update_size(struct pet_array *array, int pos,
4996 __isl_take isl_pw_aff *size)
4998 isl_set *valid;
4999 isl_set *univ;
5000 isl_set *bound;
5001 isl_space *dim;
5002 isl_aff *aff;
5003 isl_pw_aff *index;
5004 isl_id *id;
5006 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
5007 array->context = isl_set_intersect(array->context, valid);
5009 dim = isl_set_get_space(array->extent);
5010 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
5011 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
5012 univ = isl_set_universe(isl_aff_get_domain_space(aff));
5013 index = isl_pw_aff_alloc(univ, aff);
5015 size = isl_pw_aff_add_dims(size, isl_dim_in,
5016 isl_set_dim(array->extent, isl_dim_set));
5017 id = isl_set_get_tuple_id(array->extent);
5018 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
5019 bound = isl_pw_aff_lt_set(index, size);
5021 array->extent = isl_set_intersect(array->extent, bound);
5023 if (!array->context || !array->extent)
5024 goto error;
5026 return array;
5027 error:
5028 pet_array_free(array);
5029 return NULL;
5032 /* Figure out the size of the array at position "pos" and all
5033 * subsequent positions from "type" and update "array" accordingly.
5035 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
5036 const Type *type, int pos)
5038 const ArrayType *atype;
5039 isl_pw_aff *size;
5041 if (!array)
5042 return NULL;
5044 if (type->isPointerType()) {
5045 type = type->getPointeeType().getTypePtr();
5046 return set_upper_bounds(array, type, pos + 1);
5048 if (!type->isArrayType())
5049 return array;
5051 type = type->getCanonicalTypeInternal().getTypePtr();
5052 atype = cast<ArrayType>(type);
5054 if (type->isConstantArrayType()) {
5055 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
5056 size = extract_affine(ca->getSize());
5057 array = update_size(array, pos, size);
5058 } else if (type->isVariableArrayType()) {
5059 const VariableArrayType *vla = cast<VariableArrayType>(atype);
5060 size = extract_affine(vla->getSizeExpr());
5061 array = update_size(array, pos, size);
5064 type = atype->getElementType().getTypePtr();
5066 return set_upper_bounds(array, type, pos + 1);
5069 /* Is "T" the type of a variable length array with static size?
5071 static bool is_vla_with_static_size(QualType T)
5073 const VariableArrayType *vlatype;
5075 if (!T->isVariableArrayType())
5076 return false;
5077 vlatype = cast<VariableArrayType>(T);
5078 return vlatype->getSizeModifier() == VariableArrayType::Static;
5081 /* Return the type of "decl" as an array.
5083 * In particular, if "decl" is a parameter declaration that
5084 * is a variable length array with a static size, then
5085 * return the original type (i.e., the variable length array).
5086 * Otherwise, return the type of decl.
5088 static QualType get_array_type(ValueDecl *decl)
5090 ParmVarDecl *parm;
5091 QualType T;
5093 parm = dyn_cast<ParmVarDecl>(decl);
5094 if (!parm)
5095 return decl->getType();
5097 T = parm->getOriginalType();
5098 if (!is_vla_with_static_size(T))
5099 return decl->getType();
5100 return T;
5103 /* Construct and return a pet_array corresponding to the variable "decl".
5104 * In particular, initialize array->extent to
5106 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
5108 * and then call set_upper_bounds to set the upper bounds on the indices
5109 * based on the type of the variable.
5111 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
5113 struct pet_array *array;
5114 QualType qt = get_array_type(decl);
5115 const Type *type = qt.getTypePtr();
5116 int depth = array_depth(type);
5117 QualType base = base_type(qt);
5118 string name;
5119 isl_id *id;
5120 isl_space *dim;
5122 array = isl_calloc_type(ctx, struct pet_array);
5123 if (!array)
5124 return NULL;
5126 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
5127 dim = isl_space_set_alloc(ctx, 0, depth);
5128 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
5130 array->extent = isl_set_nat_universe(dim);
5132 dim = isl_space_params_alloc(ctx, 0);
5133 array->context = isl_set_universe(dim);
5135 array = set_upper_bounds(array, type, 0);
5136 if (!array)
5137 return NULL;
5139 name = base.getAsString();
5140 array->element_type = strdup(name.c_str());
5141 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
5143 return array;
5146 /* Construct a list of pet_arrays, one for each array (or scalar)
5147 * accessed inside "scop", add this list to "scop" and return the result.
5149 * The context of "scop" is updated with the intersection of
5150 * the contexts of all arrays, i.e., constraints on the parameters
5151 * that ensure that the arrays have a valid (non-negative) size.
5153 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
5155 int i;
5156 set<ValueDecl *> arrays;
5157 set<ValueDecl *>::iterator it;
5158 int n_array;
5159 struct pet_array **scop_arrays;
5161 if (!scop)
5162 return NULL;
5164 pet_scop_collect_arrays(scop, arrays);
5165 if (arrays.size() == 0)
5166 return scop;
5168 n_array = scop->n_array;
5170 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
5171 n_array + arrays.size());
5172 if (!scop_arrays)
5173 goto error;
5174 scop->arrays = scop_arrays;
5176 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
5177 struct pet_array *array;
5178 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
5179 if (!scop->arrays[n_array + i])
5180 goto error;
5181 scop->n_array++;
5182 scop->context = isl_set_intersect(scop->context,
5183 isl_set_copy(array->context));
5184 if (!scop->context)
5185 goto error;
5188 return scop;
5189 error:
5190 pet_scop_free(scop);
5191 return NULL;
5194 /* Bound all parameters in scop->context to the possible values
5195 * of the corresponding C variable.
5197 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
5199 int n;
5201 if (!scop)
5202 return NULL;
5204 n = isl_set_dim(scop->context, isl_dim_param);
5205 for (int i = 0; i < n; ++i) {
5206 isl_id *id;
5207 ValueDecl *decl;
5209 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
5210 if (is_nested_parameter(id)) {
5211 isl_id_free(id);
5212 isl_die(isl_set_get_ctx(scop->context),
5213 isl_error_internal,
5214 "unresolved nested parameter", goto error);
5216 decl = (ValueDecl *) isl_id_get_user(id);
5217 isl_id_free(id);
5219 scop->context = set_parameter_bounds(scop->context, i, decl);
5221 if (!scop->context)
5222 goto error;
5225 return scop;
5226 error:
5227 pet_scop_free(scop);
5228 return NULL;
5231 /* Construct a pet_scop from the given function.
5233 * If the scop was delimited by scop and endscop pragmas, then we override
5234 * the file offsets by those derived from the pragmas.
5236 struct pet_scop *PetScan::scan(FunctionDecl *fd)
5238 pet_scop *scop;
5239 Stmt *stmt;
5241 stmt = fd->getBody();
5243 if (options->autodetect)
5244 scop = extract(stmt, true);
5245 else {
5246 scop = scan(stmt);
5247 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
5249 scop = pet_scop_detect_parameter_accesses(scop);
5250 scop = scan_arrays(scop);
5251 scop = add_parameter_bounds(scop);
5252 scop = pet_scop_gist(scop, value_bounds);
5254 return scop;