extract out pet_stmt_is_assign
[pet.git] / scan.cc
blob80c420d725cafcdd18202f603f2917461873739a
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2014 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 "clang.h"
51 #include "options.h"
52 #include "scan.h"
53 #include "scop.h"
54 #include "scop_plus.h"
56 #include "config.h"
58 using namespace std;
59 using namespace clang;
61 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
62 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
64 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
65 SourceLocation(), var, false, var->getInnerLocStart(),
66 var->getType(), VK_LValue);
68 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
69 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
71 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
72 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
73 VK_LValue);
75 #else
76 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
78 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
79 var, var->getInnerLocStart(), var->getType(), VK_LValue);
81 #endif
83 /* Check if the element type corresponding to the given array type
84 * has a const qualifier.
86 static bool const_base(QualType qt)
88 const Type *type = qt.getTypePtr();
90 if (type->isPointerType())
91 return const_base(type->getPointeeType());
92 if (type->isArrayType()) {
93 const ArrayType *atype;
94 type = type->getCanonicalTypeInternal().getTypePtr();
95 atype = cast<ArrayType>(type);
96 return const_base(atype->getElementType());
99 return qt.isConstQualified();
102 /* Mark "decl" as having an unknown value in "assigned_value".
104 * If no (known or unknown) value was assigned to "decl" before,
105 * then it may have been treated as a parameter before and may
106 * therefore appear in a value assigned to another variable.
107 * If so, this assignment needs to be turned into an unknown value too.
109 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
110 ValueDecl *decl)
112 map<ValueDecl *, isl_pw_aff *>::iterator it;
114 it = assigned_value.find(decl);
116 assigned_value[decl] = NULL;
118 if (it != assigned_value.end())
119 return;
121 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
122 isl_pw_aff *pa = it->second;
123 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
125 for (int i = 0; i < nparam; ++i) {
126 isl_id *id;
128 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
129 continue;
130 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
131 if (isl_id_get_user(id) == decl)
132 it->second = NULL;
133 isl_id_free(id);
138 /* Look for any assignments to scalar variables in part of the parse
139 * tree and set assigned_value to NULL for each of them.
140 * Also reset assigned_value if the address of a scalar variable
141 * is being taken. As an exception, if the address is passed to a function
142 * that is declared to receive a const pointer, then assigned_value is
143 * not reset.
145 * This ensures that we won't use any previously stored value
146 * in the current subtree and its parents.
148 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
149 map<ValueDecl *, isl_pw_aff *> &assigned_value;
150 set<UnaryOperator *> skip;
152 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
153 assigned_value(assigned_value) {}
155 /* Check for "address of" operators whose value is passed
156 * to a const pointer argument and add them to "skip", so that
157 * we can skip them in VisitUnaryOperator.
159 bool VisitCallExpr(CallExpr *expr) {
160 FunctionDecl *fd;
161 fd = expr->getDirectCallee();
162 if (!fd)
163 return true;
164 for (int i = 0; i < expr->getNumArgs(); ++i) {
165 Expr *arg = expr->getArg(i);
166 UnaryOperator *op;
167 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
168 ImplicitCastExpr *ice;
169 ice = cast<ImplicitCastExpr>(arg);
170 arg = ice->getSubExpr();
172 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
173 continue;
174 op = cast<UnaryOperator>(arg);
175 if (op->getOpcode() != UO_AddrOf)
176 continue;
177 if (const_base(fd->getParamDecl(i)->getType()))
178 skip.insert(op);
180 return true;
183 bool VisitUnaryOperator(UnaryOperator *expr) {
184 Expr *arg;
185 DeclRefExpr *ref;
186 ValueDecl *decl;
188 switch (expr->getOpcode()) {
189 case UO_AddrOf:
190 case UO_PostInc:
191 case UO_PostDec:
192 case UO_PreInc:
193 case UO_PreDec:
194 break;
195 default:
196 return true;
198 if (skip.find(expr) != skip.end())
199 return true;
201 arg = expr->getSubExpr();
202 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
203 return true;
204 ref = cast<DeclRefExpr>(arg);
205 decl = ref->getDecl();
206 clear_assignment(assigned_value, decl);
207 return true;
210 bool VisitBinaryOperator(BinaryOperator *expr) {
211 Expr *lhs;
212 DeclRefExpr *ref;
213 ValueDecl *decl;
215 if (!expr->isAssignmentOp())
216 return true;
217 lhs = expr->getLHS();
218 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
219 return true;
220 ref = cast<DeclRefExpr>(lhs);
221 decl = ref->getDecl();
222 clear_assignment(assigned_value, decl);
223 return true;
227 /* Keep a copy of the currently assigned values.
229 * Any variable that is assigned a value inside the current scope
230 * is removed again when we leave the scope (either because it wasn't
231 * stored in the cache or because it has a different value in the cache).
233 struct assigned_value_cache {
234 map<ValueDecl *, isl_pw_aff *> &assigned_value;
235 map<ValueDecl *, isl_pw_aff *> cache;
237 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
238 assigned_value(assigned_value), cache(assigned_value) {}
239 ~assigned_value_cache() {
240 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
241 for (it = assigned_value.begin(); it != assigned_value.end();
242 ++it) {
243 if (!it->second ||
244 (cache.find(it->first) != cache.end() &&
245 cache[it->first] != it->second))
246 cache[it->first] = NULL;
248 assigned_value = cache;
252 /* Insert an expression into the collection of expressions,
253 * provided it is not already in there.
254 * The isl_pw_affs are freed in the destructor.
256 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
258 std::set<isl_pw_aff *>::iterator it;
260 if (expressions.find(expr) == expressions.end())
261 expressions.insert(expr);
262 else
263 isl_pw_aff_free(expr);
266 PetScan::~PetScan()
268 std::set<isl_pw_aff *>::iterator it;
270 for (it = expressions.begin(); it != expressions.end(); ++it)
271 isl_pw_aff_free(*it);
273 isl_union_map_free(value_bounds);
276 /* Report a diagnostic, unless autodetect is set.
278 void PetScan::report(Stmt *stmt, unsigned id)
280 if (options->autodetect)
281 return;
283 SourceLocation loc = stmt->getLocStart();
284 DiagnosticsEngine &diag = PP.getDiagnostics();
285 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
288 /* Called if we found something we (currently) cannot handle.
289 * We'll provide more informative warnings later.
291 * We only actually complain if autodetect is false.
293 void PetScan::unsupported(Stmt *stmt)
295 DiagnosticsEngine &diag = PP.getDiagnostics();
296 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
297 "unsupported");
298 report(stmt, id);
301 /* Report a missing prototype, unless autodetect is set.
303 void PetScan::report_prototype_required(Stmt *stmt)
305 DiagnosticsEngine &diag = PP.getDiagnostics();
306 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
307 "prototype required");
308 report(stmt, id);
311 /* Report a missing increment, unless autodetect is set.
313 void PetScan::report_missing_increment(Stmt *stmt)
315 DiagnosticsEngine &diag = PP.getDiagnostics();
316 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
317 "missing increment");
318 report(stmt, id);
321 /* Extract an integer from "expr".
323 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
325 const Type *type = expr->getType().getTypePtr();
326 int is_signed = type->hasSignedIntegerRepresentation();
327 llvm::APInt val = expr->getValue();
328 int is_negative = is_signed && val.isNegative();
329 isl_val *v;
331 if (is_negative)
332 val = -val;
334 v = extract_unsigned(ctx, val);
336 if (is_negative)
337 v = isl_val_neg(v);
338 return v;
341 /* Extract an integer from "val", which is assumed to be non-negative.
343 __isl_give isl_val *PetScan::extract_unsigned(isl_ctx *ctx,
344 const llvm::APInt &val)
346 unsigned n;
347 const uint64_t *data;
349 data = val.getRawData();
350 n = val.getNumWords();
351 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
354 /* Extract an integer from "expr".
355 * Return NULL if "expr" does not (obviously) represent an integer.
357 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
359 return extract_int(expr->getSubExpr());
362 /* Extract an integer from "expr".
363 * Return NULL if "expr" does not (obviously) represent an integer.
365 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
367 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
368 return extract_int(ctx, cast<IntegerLiteral>(expr));
369 if (expr->getStmtClass() == Stmt::ParenExprClass)
370 return extract_int(cast<ParenExpr>(expr));
372 unsupported(expr);
373 return NULL;
376 /* Extract an affine expression from the IntegerLiteral "expr".
378 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
380 isl_space *dim = isl_space_params_alloc(ctx, 0);
381 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
382 isl_aff *aff = isl_aff_zero_on_domain(ls);
383 isl_set *dom = isl_set_universe(dim);
384 isl_val *v;
386 v = extract_int(expr);
387 aff = isl_aff_add_constant_val(aff, v);
389 return isl_pw_aff_alloc(dom, aff);
392 /* Extract an affine expression from the APInt "val", which is assumed
393 * to be non-negative.
395 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
397 isl_space *dim = isl_space_params_alloc(ctx, 0);
398 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
399 isl_aff *aff = isl_aff_zero_on_domain(ls);
400 isl_set *dom = isl_set_universe(dim);
401 isl_val *v;
403 v = extract_unsigned(ctx, val);
404 aff = isl_aff_add_constant_val(aff, v);
406 return isl_pw_aff_alloc(dom, aff);
409 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
411 return extract_affine(expr->getSubExpr());
414 static unsigned get_type_size(ValueDecl *decl)
416 return decl->getASTContext().getIntWidth(decl->getType());
419 /* Bound parameter "pos" of "set" to the possible values of "decl".
421 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
422 unsigned pos, ValueDecl *decl)
424 unsigned width;
425 isl_ctx *ctx;
426 isl_val *bound;
428 ctx = isl_set_get_ctx(set);
429 width = get_type_size(decl);
430 if (decl->getType()->isUnsignedIntegerType()) {
431 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
432 bound = isl_val_int_from_ui(ctx, width);
433 bound = isl_val_2exp(bound);
434 bound = isl_val_sub_ui(bound, 1);
435 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
436 } else {
437 bound = isl_val_int_from_ui(ctx, width - 1);
438 bound = isl_val_2exp(bound);
439 bound = isl_val_sub_ui(bound, 1);
440 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
441 isl_val_copy(bound));
442 bound = isl_val_neg(bound);
443 bound = isl_val_sub_ui(bound, 1);
444 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
447 return set;
450 /* Extract an affine expression from the DeclRefExpr "expr".
452 * If the variable has been assigned a value, then we check whether
453 * we know what (affine) value was assigned.
454 * If so, we return this value. Otherwise we convert "expr"
455 * to an extra parameter (provided nesting_enabled is set).
457 * Otherwise, we simply return an expression that is equal
458 * to a parameter corresponding to the referenced variable.
460 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
462 ValueDecl *decl = expr->getDecl();
463 const Type *type = decl->getType().getTypePtr();
464 isl_id *id;
465 isl_space *dim;
466 isl_aff *aff;
467 isl_set *dom;
469 if (!type->isIntegerType()) {
470 unsupported(expr);
471 return NULL;
474 if (assigned_value.find(decl) != assigned_value.end()) {
475 if (assigned_value[decl])
476 return isl_pw_aff_copy(assigned_value[decl]);
477 else
478 return nested_access(expr);
481 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
482 dim = isl_space_params_alloc(ctx, 1);
484 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
486 dom = isl_set_universe(isl_space_copy(dim));
487 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
488 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
490 return isl_pw_aff_alloc(dom, aff);
493 /* Extract an affine expression from an integer division operation.
494 * In particular, if "expr" is lhs/rhs, then return
496 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
498 * The second argument (rhs) is required to be a (positive) integer constant.
500 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
502 int is_cst;
503 isl_pw_aff *rhs, *lhs;
505 rhs = extract_affine(expr->getRHS());
506 is_cst = isl_pw_aff_is_cst(rhs);
507 if (is_cst < 0 || !is_cst) {
508 isl_pw_aff_free(rhs);
509 if (!is_cst)
510 unsupported(expr);
511 return NULL;
514 lhs = extract_affine(expr->getLHS());
516 return isl_pw_aff_tdiv_q(lhs, rhs);
519 /* Extract an affine expression from a modulo operation.
520 * In particular, if "expr" is lhs/rhs, then return
522 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
524 * The second argument (rhs) is required to be a (positive) integer constant.
526 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
528 int is_cst;
529 isl_pw_aff *rhs, *lhs;
531 rhs = extract_affine(expr->getRHS());
532 is_cst = isl_pw_aff_is_cst(rhs);
533 if (is_cst < 0 || !is_cst) {
534 isl_pw_aff_free(rhs);
535 if (!is_cst)
536 unsupported(expr);
537 return NULL;
540 lhs = extract_affine(expr->getLHS());
542 return isl_pw_aff_tdiv_r(lhs, rhs);
545 /* Extract an affine expression from a multiplication operation.
546 * This is only allowed if at least one of the two arguments
547 * is a (piecewise) constant.
549 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
551 isl_pw_aff *lhs;
552 isl_pw_aff *rhs;
554 lhs = extract_affine(expr->getLHS());
555 rhs = extract_affine(expr->getRHS());
557 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
558 isl_pw_aff_free(lhs);
559 isl_pw_aff_free(rhs);
560 unsupported(expr);
561 return NULL;
564 return isl_pw_aff_mul(lhs, rhs);
567 /* Extract an affine expression from an addition or subtraction operation.
569 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
571 isl_pw_aff *lhs;
572 isl_pw_aff *rhs;
574 lhs = extract_affine(expr->getLHS());
575 rhs = extract_affine(expr->getRHS());
577 switch (expr->getOpcode()) {
578 case BO_Add:
579 return isl_pw_aff_add(lhs, rhs);
580 case BO_Sub:
581 return isl_pw_aff_sub(lhs, rhs);
582 default:
583 isl_pw_aff_free(lhs);
584 isl_pw_aff_free(rhs);
585 return NULL;
590 /* Compute
592 * pwaff mod 2^width
594 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
595 unsigned width)
597 isl_ctx *ctx;
598 isl_val *mod;
600 ctx = isl_pw_aff_get_ctx(pwaff);
601 mod = isl_val_int_from_ui(ctx, width);
602 mod = isl_val_2exp(mod);
604 pwaff = isl_pw_aff_mod_val(pwaff, mod);
606 return pwaff;
609 /* Limit the domain of "pwaff" to those elements where the function
610 * value satisfies
612 * 2^{width-1} <= pwaff < 2^{width-1}
614 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
615 unsigned width)
617 isl_ctx *ctx;
618 isl_val *v;
619 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
620 isl_local_space *ls = isl_local_space_from_space(space);
621 isl_aff *bound;
622 isl_set *dom;
623 isl_pw_aff *b;
625 ctx = isl_pw_aff_get_ctx(pwaff);
626 v = isl_val_int_from_ui(ctx, width - 1);
627 v = isl_val_2exp(v);
629 bound = isl_aff_zero_on_domain(ls);
630 bound = isl_aff_add_constant_val(bound, v);
631 b = isl_pw_aff_from_aff(bound);
633 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
634 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
636 b = isl_pw_aff_neg(b);
637 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
638 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
640 return pwaff;
643 /* Handle potential overflows on signed computations.
645 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
646 * the we adjust the domain of "pa" to avoid overflows.
648 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
649 unsigned width)
651 if (options->signed_overflow == PET_OVERFLOW_AVOID)
652 pa = avoid_overflow(pa, width);
654 return pa;
657 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
659 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
660 __isl_take isl_set *dom)
662 isl_pw_aff *pa;
663 pa = isl_set_indicator_function(set);
664 pa = isl_pw_aff_intersect_domain(pa, isl_set_coalesce(dom));
665 return pa;
668 /* Extract an affine expression from some binary operations.
669 * If the result of the expression is unsigned, then we wrap it
670 * based on the size of the type. Otherwise, we ensure that
671 * no overflow occurs.
673 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
675 isl_pw_aff *res;
676 unsigned width;
678 switch (expr->getOpcode()) {
679 case BO_Add:
680 case BO_Sub:
681 res = extract_affine_add(expr);
682 break;
683 case BO_Div:
684 res = extract_affine_div(expr);
685 break;
686 case BO_Rem:
687 res = extract_affine_mod(expr);
688 break;
689 case BO_Mul:
690 res = extract_affine_mul(expr);
691 break;
692 case BO_LT:
693 case BO_LE:
694 case BO_GT:
695 case BO_GE:
696 case BO_EQ:
697 case BO_NE:
698 case BO_LAnd:
699 case BO_LOr:
700 return extract_condition(expr);
701 default:
702 unsupported(expr);
703 return NULL;
706 width = ast_context.getIntWidth(expr->getType());
707 if (expr->getType()->isUnsignedIntegerType())
708 res = wrap(res, width);
709 else
710 res = signed_overflow(res, width);
712 return res;
715 /* Extract an affine expression from a negation operation.
717 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
719 if (expr->getOpcode() == UO_Minus)
720 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
721 if (expr->getOpcode() == UO_LNot)
722 return extract_condition(expr);
724 unsupported(expr);
725 return NULL;
728 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
730 return extract_affine(expr->getSubExpr());
733 /* Extract an affine expression from some special function calls.
734 * In particular, we handle "min", "max", "ceild", "floord",
735 * "intMod", "intFloor" and "intCeil".
736 * In case of the latter five, the second argument needs to be
737 * a (positive) integer constant.
739 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
741 FunctionDecl *fd;
742 string name;
743 isl_pw_aff *aff1, *aff2;
745 fd = expr->getDirectCallee();
746 if (!fd) {
747 unsupported(expr);
748 return NULL;
751 name = fd->getDeclName().getAsString();
752 if (!(expr->getNumArgs() == 2 && name == "min") &&
753 !(expr->getNumArgs() == 2 && name == "max") &&
754 !(expr->getNumArgs() == 2 && name == "intMod") &&
755 !(expr->getNumArgs() == 2 && name == "intFloor") &&
756 !(expr->getNumArgs() == 2 && name == "intCeil") &&
757 !(expr->getNumArgs() == 2 && name == "floord") &&
758 !(expr->getNumArgs() == 2 && name == "ceild")) {
759 unsupported(expr);
760 return NULL;
763 if (name == "min" || name == "max") {
764 aff1 = extract_affine(expr->getArg(0));
765 aff2 = extract_affine(expr->getArg(1));
767 if (name == "min")
768 aff1 = isl_pw_aff_min(aff1, aff2);
769 else
770 aff1 = isl_pw_aff_max(aff1, aff2);
771 } else if (name == "intMod") {
772 isl_val *v;
773 Expr *arg2 = expr->getArg(1);
775 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
776 unsupported(expr);
777 return NULL;
779 aff1 = extract_affine(expr->getArg(0));
780 v = extract_int(cast<IntegerLiteral>(arg2));
781 aff1 = isl_pw_aff_mod_val(aff1, v);
782 } else if (name == "floord" || name == "ceild" ||
783 name == "intFloor" || name == "intCeil") {
784 isl_val *v;
785 Expr *arg2 = expr->getArg(1);
787 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
788 unsupported(expr);
789 return NULL;
791 aff1 = extract_affine(expr->getArg(0));
792 v = extract_int(cast<IntegerLiteral>(arg2));
793 aff1 = isl_pw_aff_scale_down_val(aff1, v);
794 if (name == "floord" || name == "intFloor")
795 aff1 = isl_pw_aff_floor(aff1);
796 else
797 aff1 = isl_pw_aff_ceil(aff1);
798 } else {
799 unsupported(expr);
800 return NULL;
803 return aff1;
806 /* This method is called when we come across an access that is
807 * nested in what is supposed to be an affine expression.
808 * If nesting is allowed, we return a new parameter that corresponds
809 * to this nested access. Otherwise, we simply complain.
811 * Note that we currently don't allow nested accesses themselves
812 * to contain any nested accesses, so we check if we can extract
813 * the access without any nesting and complain if we can't.
815 * The new parameter is resolved in resolve_nested.
817 isl_pw_aff *PetScan::nested_access(Expr *expr)
819 isl_id *id;
820 isl_space *dim;
821 isl_aff *aff;
822 isl_set *dom;
823 isl_multi_pw_aff *index;
825 if (!nesting_enabled) {
826 unsupported(expr);
827 return NULL;
830 allow_nested = false;
831 index = extract_index(expr);
832 allow_nested = true;
833 if (!index) {
834 unsupported(expr);
835 return NULL;
837 isl_multi_pw_aff_free(index);
839 id = isl_id_alloc(ctx, NULL, expr);
840 dim = isl_space_params_alloc(ctx, 1);
842 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
844 dom = isl_set_universe(isl_space_copy(dim));
845 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
846 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
848 return isl_pw_aff_alloc(dom, aff);
851 /* Affine expressions are not supposed to contain array accesses,
852 * but if nesting is allowed, we return a parameter corresponding
853 * to the array access.
855 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
857 return nested_access(expr);
860 /* Affine expressions are not supposed to contain member accesses,
861 * but if nesting is allowed, we return a parameter corresponding
862 * to the member access.
864 __isl_give isl_pw_aff *PetScan::extract_affine(MemberExpr *expr)
866 return nested_access(expr);
869 /* Extract an affine expression from a conditional operation.
871 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
873 isl_pw_aff *cond, *lhs, *rhs;
875 cond = extract_condition(expr->getCond());
876 lhs = extract_affine(expr->getTrueExpr());
877 rhs = extract_affine(expr->getFalseExpr());
879 return isl_pw_aff_cond(cond, lhs, rhs);
882 /* Extract an affine expression, if possible, from "expr".
883 * Otherwise return NULL.
885 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
887 switch (expr->getStmtClass()) {
888 case Stmt::ImplicitCastExprClass:
889 return extract_affine(cast<ImplicitCastExpr>(expr));
890 case Stmt::IntegerLiteralClass:
891 return extract_affine(cast<IntegerLiteral>(expr));
892 case Stmt::DeclRefExprClass:
893 return extract_affine(cast<DeclRefExpr>(expr));
894 case Stmt::BinaryOperatorClass:
895 return extract_affine(cast<BinaryOperator>(expr));
896 case Stmt::UnaryOperatorClass:
897 return extract_affine(cast<UnaryOperator>(expr));
898 case Stmt::ParenExprClass:
899 return extract_affine(cast<ParenExpr>(expr));
900 case Stmt::CallExprClass:
901 return extract_affine(cast<CallExpr>(expr));
902 case Stmt::ArraySubscriptExprClass:
903 return extract_affine(cast<ArraySubscriptExpr>(expr));
904 case Stmt::MemberExprClass:
905 return extract_affine(cast<MemberExpr>(expr));
906 case Stmt::ConditionalOperatorClass:
907 return extract_affine(cast<ConditionalOperator>(expr));
908 default:
909 unsupported(expr);
911 return NULL;
914 __isl_give isl_multi_pw_aff *PetScan::extract_index(ImplicitCastExpr *expr)
916 return extract_index(expr->getSubExpr());
919 /* Return the depth of an array of the given type.
921 static int array_depth(const Type *type)
923 if (type->isPointerType())
924 return 1 + array_depth(type->getPointeeType().getTypePtr());
925 if (type->isArrayType()) {
926 const ArrayType *atype;
927 type = type->getCanonicalTypeInternal().getTypePtr();
928 atype = cast<ArrayType>(type);
929 return 1 + array_depth(atype->getElementType().getTypePtr());
931 return 0;
934 /* Return the depth of the array accessed by the index expression "index".
935 * If "index" is an affine expression, i.e., if it does not access
936 * any array, then return 1.
937 * If "index" represent a member access, i.e., if its range is a wrapped
938 * relation, then return the sum of the depth of the array of structures
939 * and that of the member inside the structure.
941 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
943 isl_id *id;
944 ValueDecl *decl;
946 if (!index)
947 return -1;
949 if (isl_multi_pw_aff_range_is_wrapping(index)) {
950 int domain_depth, range_depth;
951 isl_multi_pw_aff *domain, *range;
953 domain = isl_multi_pw_aff_copy(index);
954 domain = isl_multi_pw_aff_range_factor_domain(domain);
955 domain_depth = extract_depth(domain);
956 isl_multi_pw_aff_free(domain);
957 range = isl_multi_pw_aff_copy(index);
958 range = isl_multi_pw_aff_range_factor_range(range);
959 range_depth = extract_depth(range);
960 isl_multi_pw_aff_free(range);
962 return domain_depth + range_depth;
965 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
966 return 1;
968 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
969 if (!id)
970 return -1;
971 decl = (ValueDecl *) isl_id_get_user(id);
972 isl_id_free(id);
974 return array_depth(decl->getType().getTypePtr());
977 /* Extract an index expression from a reference to a variable.
978 * If the variable has name "A", then the returned index expression
979 * is of the form
981 * { [] -> A[] }
983 __isl_give isl_multi_pw_aff *PetScan::extract_index(DeclRefExpr *expr)
985 return extract_index(expr->getDecl());
988 /* Extract an index expression from a variable.
989 * If the variable has name "A", then the returned index expression
990 * is of the form
992 * { [] -> A[] }
994 __isl_give isl_multi_pw_aff *PetScan::extract_index(ValueDecl *decl)
996 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
997 isl_space *space = isl_space_alloc(ctx, 0, 0, 0);
999 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1001 return isl_multi_pw_aff_zero(space);
1004 /* Extract an index expression from an integer contant.
1005 * If the value of the constant is "v", then the returned access relation
1006 * is
1008 * { [] -> [v] }
1010 __isl_give isl_multi_pw_aff *PetScan::extract_index(IntegerLiteral *expr)
1012 isl_multi_pw_aff *mpa;
1014 mpa = isl_multi_pw_aff_from_pw_aff(extract_affine(expr));
1015 mpa = isl_multi_pw_aff_from_range(mpa);
1016 return mpa;
1019 /* Try and extract an index expression from the given Expr.
1020 * Return NULL if it doesn't work out.
1022 __isl_give isl_multi_pw_aff *PetScan::extract_index(Expr *expr)
1024 switch (expr->getStmtClass()) {
1025 case Stmt::ImplicitCastExprClass:
1026 return extract_index(cast<ImplicitCastExpr>(expr));
1027 case Stmt::DeclRefExprClass:
1028 return extract_index(cast<DeclRefExpr>(expr));
1029 case Stmt::ArraySubscriptExprClass:
1030 return extract_index(cast<ArraySubscriptExpr>(expr));
1031 case Stmt::IntegerLiteralClass:
1032 return extract_index(cast<IntegerLiteral>(expr));
1033 case Stmt::MemberExprClass:
1034 return extract_index(cast<MemberExpr>(expr));
1035 default:
1036 unsupported(expr);
1038 return NULL;
1041 /* Given a partial index expression "base" and an extra index "index",
1042 * append the extra index to "base" and return the result.
1043 * Additionally, add the constraints that the extra index is non-negative.
1044 * If "index" represent a member access, i.e., if its range is a wrapped
1045 * relation, then we recursively extend the range of this nested relation.
1047 static __isl_give isl_multi_pw_aff *subscript(__isl_take isl_multi_pw_aff *base,
1048 __isl_take isl_pw_aff *index)
1050 isl_id *id;
1051 isl_set *domain;
1052 isl_multi_pw_aff *access;
1053 int member_access;
1055 member_access = isl_multi_pw_aff_range_is_wrapping(base);
1056 if (member_access < 0)
1057 goto error;
1058 if (member_access) {
1059 isl_multi_pw_aff *domain, *range;
1060 isl_id *id;
1062 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_out);
1063 domain = isl_multi_pw_aff_copy(base);
1064 domain = isl_multi_pw_aff_range_factor_domain(domain);
1065 range = isl_multi_pw_aff_range_factor_range(base);
1066 range = subscript(range, index);
1067 access = isl_multi_pw_aff_range_product(domain, range);
1068 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_out, id);
1069 return access;
1072 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_set);
1073 index = isl_pw_aff_from_range(index);
1074 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
1075 index = isl_pw_aff_intersect_domain(index, domain);
1076 access = isl_multi_pw_aff_from_pw_aff(index);
1077 access = isl_multi_pw_aff_flat_range_product(base, access);
1078 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_set, id);
1080 return access;
1081 error:
1082 isl_multi_pw_aff_free(base);
1083 isl_pw_aff_free(index);
1084 return NULL;
1087 /* Extract an index expression from the given array subscript expression.
1088 * If nesting is allowed in general, then we turn it on while
1089 * examining the index expression.
1091 * We first extract an index expression from the base.
1092 * This will result in an index expression with a range that corresponds
1093 * to the earlier indices.
1094 * We then extract the current index, restrict its domain
1095 * to those values that result in a non-negative index and
1096 * append the index to the base index expression.
1098 __isl_give isl_multi_pw_aff *PetScan::extract_index(ArraySubscriptExpr *expr)
1100 Expr *base = expr->getBase();
1101 Expr *idx = expr->getIdx();
1102 isl_pw_aff *index;
1103 isl_multi_pw_aff *base_access;
1104 isl_multi_pw_aff *access;
1105 bool save_nesting = nesting_enabled;
1107 nesting_enabled = allow_nested;
1109 base_access = extract_index(base);
1110 index = extract_affine(idx);
1112 nesting_enabled = save_nesting;
1114 access = subscript(base_access, index);
1116 return access;
1119 /* Construct a name for a member access by concatenating the name
1120 * of the array of structures and the member, separated by an underscore.
1122 * The caller is responsible for freeing the result.
1124 static char *member_access_name(isl_ctx *ctx, const char *base,
1125 const char *field)
1127 int len;
1128 char *name;
1130 len = strlen(base) + 1 + strlen(field);
1131 name = isl_alloc_array(ctx, char, len + 1);
1132 if (!name)
1133 return NULL;
1134 snprintf(name, len + 1, "%s_%s", base, field);
1136 return name;
1139 /* Given an index expression "base" for an element of an array of structures
1140 * and an expression "field" for the field member being accessed, construct
1141 * an index expression for an access to that member of the given structure.
1142 * In particular, take the range product of "base" and "field" and
1143 * attach a name to the result.
1145 static __isl_give isl_multi_pw_aff *member(__isl_take isl_multi_pw_aff *base,
1146 __isl_take isl_multi_pw_aff *field)
1148 isl_ctx *ctx;
1149 isl_multi_pw_aff *access;
1150 const char *base_name, *field_name;
1151 char *name;
1153 ctx = isl_multi_pw_aff_get_ctx(base);
1155 base_name = isl_multi_pw_aff_get_tuple_name(base, isl_dim_out);
1156 field_name = isl_multi_pw_aff_get_tuple_name(field, isl_dim_out);
1157 name = member_access_name(ctx, base_name, field_name);
1159 access = isl_multi_pw_aff_range_product(base, field);
1161 access = isl_multi_pw_aff_set_tuple_name(access, isl_dim_out, name);
1162 free(name);
1164 return access;
1167 /* Extract an index expression from a member expression.
1169 * If the base access (to the structure containing the member)
1170 * is of the form
1172 * [] -> A[..]
1174 * and the member is called "f", then the member access is of
1175 * the form
1177 * [] -> A_f[A[..] -> f[]]
1179 * If the member access is to an anonymous struct, then simply return
1181 * [] -> A[..]
1183 * If the member access in the source code is of the form
1185 * A->f
1187 * then it is treated as
1189 * A[0].f
1191 __isl_give isl_multi_pw_aff *PetScan::extract_index(MemberExpr *expr)
1193 Expr *base = expr->getBase();
1194 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
1195 isl_multi_pw_aff *base_access, *field_access;
1196 isl_id *id;
1197 isl_space *space;
1199 base_access = extract_index(base);
1201 if (expr->isArrow()) {
1202 isl_space *space = isl_space_params_alloc(ctx, 0);
1203 isl_local_space *ls = isl_local_space_from_space(space);
1204 isl_aff *aff = isl_aff_zero_on_domain(ls);
1205 isl_pw_aff *index = isl_pw_aff_from_aff(aff);
1206 base_access = subscript(base_access, index);
1209 if (field->isAnonymousStructOrUnion())
1210 return base_access;
1212 id = isl_id_alloc(ctx, field->getName().str().c_str(), field);
1213 space = isl_multi_pw_aff_get_domain_space(base_access);
1214 space = isl_space_from_domain(space);
1215 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1216 field_access = isl_multi_pw_aff_zero(space);
1218 return member(base_access, field_access);
1221 /* Check if "expr" calls function "minmax" with two arguments and if so
1222 * make lhs and rhs refer to these two arguments.
1224 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1226 CallExpr *call;
1227 FunctionDecl *fd;
1228 string name;
1230 if (expr->getStmtClass() != Stmt::CallExprClass)
1231 return false;
1233 call = cast<CallExpr>(expr);
1234 fd = call->getDirectCallee();
1235 if (!fd)
1236 return false;
1238 if (call->getNumArgs() != 2)
1239 return false;
1241 name = fd->getDeclName().getAsString();
1242 if (name != minmax)
1243 return false;
1245 lhs = call->getArg(0);
1246 rhs = call->getArg(1);
1248 return true;
1251 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1252 * lhs and rhs refer to the two arguments.
1254 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1256 return is_minmax(expr, "min", lhs, rhs);
1259 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1260 * lhs and rhs refer to the two arguments.
1262 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1264 return is_minmax(expr, "max", lhs, rhs);
1267 /* Return "lhs && rhs", defined on the shared definition domain.
1269 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1270 __isl_take isl_pw_aff *rhs)
1272 isl_set *cond;
1273 isl_set *dom;
1275 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1276 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1277 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1278 isl_pw_aff_non_zero_set(rhs));
1279 return indicator_function(cond, dom);
1282 /* Return "lhs && rhs", with shortcut semantics.
1283 * That is, if lhs is false, then the result is defined even if rhs is not.
1284 * In practice, we compute lhs ? rhs : lhs.
1286 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1287 __isl_take isl_pw_aff *rhs)
1289 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1292 /* Return "lhs || rhs", with shortcut semantics.
1293 * That is, if lhs is true, then the result is defined even if rhs is not.
1294 * In practice, we compute lhs ? lhs : rhs.
1296 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1297 __isl_take isl_pw_aff *rhs)
1299 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1302 /* Extract an affine expressions representing the comparison "LHS op RHS"
1303 * "comp" is the original statement that "LHS op RHS" is derived from
1304 * and is used for diagnostics.
1306 * If the comparison is of the form
1308 * a <= min(b,c)
1310 * then the expression is constructed as the conjunction of
1311 * the comparisons
1313 * a <= b and a <= c
1315 * A similar optimization is performed for max(a,b) <= c.
1316 * We do this because that will lead to simpler representations
1317 * of the expression.
1318 * If isl is ever enhanced to explicitly deal with min and max expressions,
1319 * this optimization can be removed.
1321 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1322 Expr *LHS, Expr *RHS, Stmt *comp)
1324 isl_pw_aff *lhs;
1325 isl_pw_aff *rhs;
1326 isl_pw_aff *res;
1327 isl_set *cond;
1328 isl_set *dom;
1330 if (op == BO_GT)
1331 return extract_comparison(BO_LT, RHS, LHS, comp);
1332 if (op == BO_GE)
1333 return extract_comparison(BO_LE, RHS, LHS, comp);
1335 if (op == BO_LT || op == BO_LE) {
1336 Expr *expr1, *expr2;
1337 if (is_min(RHS, expr1, expr2)) {
1338 lhs = extract_comparison(op, LHS, expr1, comp);
1339 rhs = extract_comparison(op, LHS, expr2, comp);
1340 return pw_aff_and(lhs, rhs);
1342 if (is_max(LHS, expr1, expr2)) {
1343 lhs = extract_comparison(op, expr1, RHS, comp);
1344 rhs = extract_comparison(op, expr2, RHS, comp);
1345 return pw_aff_and(lhs, rhs);
1349 lhs = extract_affine(LHS);
1350 rhs = extract_affine(RHS);
1352 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1353 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1355 switch (op) {
1356 case BO_LT:
1357 cond = isl_pw_aff_lt_set(lhs, rhs);
1358 break;
1359 case BO_LE:
1360 cond = isl_pw_aff_le_set(lhs, rhs);
1361 break;
1362 case BO_EQ:
1363 cond = isl_pw_aff_eq_set(lhs, rhs);
1364 break;
1365 case BO_NE:
1366 cond = isl_pw_aff_ne_set(lhs, rhs);
1367 break;
1368 default:
1369 isl_pw_aff_free(lhs);
1370 isl_pw_aff_free(rhs);
1371 isl_set_free(dom);
1372 unsupported(comp);
1373 return NULL;
1376 cond = isl_set_coalesce(cond);
1377 res = indicator_function(cond, dom);
1379 return res;
1382 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1384 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1385 comp->getRHS(), comp);
1388 /* Extract an affine expression representing the negation (logical not)
1389 * of a subexpression.
1391 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1393 isl_set *set_cond, *dom;
1394 isl_pw_aff *cond, *res;
1396 cond = extract_condition(op->getSubExpr());
1398 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1400 set_cond = isl_pw_aff_zero_set(cond);
1402 res = indicator_function(set_cond, dom);
1404 return res;
1407 /* Extract an affine expression representing the disjunction (logical or)
1408 * or conjunction (logical and) of two subexpressions.
1410 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1412 isl_pw_aff *lhs, *rhs;
1414 lhs = extract_condition(comp->getLHS());
1415 rhs = extract_condition(comp->getRHS());
1417 switch (comp->getOpcode()) {
1418 case BO_LAnd:
1419 return pw_aff_and_then(lhs, rhs);
1420 case BO_LOr:
1421 return pw_aff_or_else(lhs, rhs);
1422 default:
1423 isl_pw_aff_free(lhs);
1424 isl_pw_aff_free(rhs);
1427 unsupported(comp);
1428 return NULL;
1431 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1433 switch (expr->getOpcode()) {
1434 case UO_LNot:
1435 return extract_boolean(expr);
1436 default:
1437 unsupported(expr);
1438 return NULL;
1442 /* Extract the affine expression "expr != 0 ? 1 : 0".
1444 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1446 isl_pw_aff *res;
1447 isl_set *set, *dom;
1449 res = extract_affine(expr);
1451 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1452 set = isl_pw_aff_non_zero_set(res);
1454 res = indicator_function(set, dom);
1456 return res;
1459 /* Extract an affine expression from a boolean expression.
1460 * In particular, return the expression "expr ? 1 : 0".
1462 * If the expression doesn't look like a condition, we assume it
1463 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1465 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1467 BinaryOperator *comp;
1469 if (!expr) {
1470 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1471 return indicator_function(u, isl_set_copy(u));
1474 if (expr->getStmtClass() == Stmt::ParenExprClass)
1475 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1477 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1478 return extract_condition(cast<UnaryOperator>(expr));
1480 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1481 return extract_implicit_condition(expr);
1483 comp = cast<BinaryOperator>(expr);
1484 switch (comp->getOpcode()) {
1485 case BO_LT:
1486 case BO_LE:
1487 case BO_GT:
1488 case BO_GE:
1489 case BO_EQ:
1490 case BO_NE:
1491 return extract_comparison(comp);
1492 case BO_LAnd:
1493 case BO_LOr:
1494 return extract_boolean(comp);
1495 default:
1496 return extract_implicit_condition(expr);
1500 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1502 switch (kind) {
1503 case UO_Minus:
1504 return pet_op_minus;
1505 case UO_Not:
1506 return pet_op_not;
1507 case UO_LNot:
1508 return pet_op_lnot;
1509 case UO_PostInc:
1510 return pet_op_post_inc;
1511 case UO_PostDec:
1512 return pet_op_post_dec;
1513 case UO_PreInc:
1514 return pet_op_pre_inc;
1515 case UO_PreDec:
1516 return pet_op_pre_dec;
1517 default:
1518 return pet_op_last;
1522 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1524 switch (kind) {
1525 case BO_AddAssign:
1526 return pet_op_add_assign;
1527 case BO_SubAssign:
1528 return pet_op_sub_assign;
1529 case BO_MulAssign:
1530 return pet_op_mul_assign;
1531 case BO_DivAssign:
1532 return pet_op_div_assign;
1533 case BO_Assign:
1534 return pet_op_assign;
1535 case BO_Add:
1536 return pet_op_add;
1537 case BO_Sub:
1538 return pet_op_sub;
1539 case BO_Mul:
1540 return pet_op_mul;
1541 case BO_Div:
1542 return pet_op_div;
1543 case BO_Rem:
1544 return pet_op_mod;
1545 case BO_Shl:
1546 return pet_op_shl;
1547 case BO_Shr:
1548 return pet_op_shr;
1549 case BO_EQ:
1550 return pet_op_eq;
1551 case BO_NE:
1552 return pet_op_ne;
1553 case BO_LE:
1554 return pet_op_le;
1555 case BO_GE:
1556 return pet_op_ge;
1557 case BO_LT:
1558 return pet_op_lt;
1559 case BO_GT:
1560 return pet_op_gt;
1561 case BO_And:
1562 return pet_op_and;
1563 case BO_Xor:
1564 return pet_op_xor;
1565 case BO_Or:
1566 return pet_op_or;
1567 case BO_LAnd:
1568 return pet_op_land;
1569 case BO_LOr:
1570 return pet_op_lor;
1571 default:
1572 return pet_op_last;
1576 /* Construct a pet_expr representing a unary operator expression.
1578 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1580 struct pet_expr *arg;
1581 enum pet_op_type op;
1583 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1584 if (op == pet_op_last) {
1585 unsupported(expr);
1586 return NULL;
1589 arg = extract_expr(expr->getSubExpr());
1591 if (expr->isIncrementDecrementOp() &&
1592 arg && arg->type == pet_expr_access) {
1593 mark_write(arg);
1594 arg->acc.read = 1;
1597 return pet_expr_new_unary(ctx, op, arg);
1600 /* Mark the given access pet_expr as a write.
1601 * If a scalar is being accessed, then mark its value
1602 * as unknown in assigned_value.
1604 void PetScan::mark_write(struct pet_expr *access)
1606 isl_id *id;
1607 ValueDecl *decl;
1609 if (!access)
1610 return;
1612 access->acc.write = 1;
1613 access->acc.read = 0;
1615 if (!pet_expr_is_scalar_access(access))
1616 return;
1618 id = pet_expr_access_get_id(access);
1619 decl = (ValueDecl *) isl_id_get_user(id);
1620 clear_assignment(assigned_value, decl);
1621 isl_id_free(id);
1624 /* Assign "rhs" to "lhs".
1626 * In particular, if "lhs" is a scalar variable, then mark
1627 * the variable as having been assigned. If, furthermore, "rhs"
1628 * is an affine expression, then keep track of this value in assigned_value
1629 * so that we can plug it in when we later come across the same variable.
1631 void PetScan::assign(struct pet_expr *lhs, Expr *rhs)
1633 isl_id *id;
1634 ValueDecl *decl;
1635 isl_pw_aff *pa;
1637 if (!lhs)
1638 return;
1639 if (!pet_expr_is_scalar_access(lhs))
1640 return;
1642 id = pet_expr_access_get_id(lhs);
1643 decl = (ValueDecl *) isl_id_get_user(id);
1644 isl_id_free(id);
1646 pa = try_extract_affine(rhs);
1647 clear_assignment(assigned_value, decl);
1648 if (!pa)
1649 return;
1650 assigned_value[decl] = pa;
1651 insert_expression(pa);
1654 /* Construct a pet_expr representing a binary operator expression.
1656 * If the top level operator is an assignment and the LHS is an access,
1657 * then we mark that access as a write. If the operator is a compound
1658 * assignment, the access is marked as both a read and a write.
1660 * If "expr" assigns something to a scalar variable, then we mark
1661 * the variable as having been assigned. If, furthermore, the expression
1662 * is affine, then keep track of this value in assigned_value
1663 * so that we can plug it in when we later come across the same variable.
1665 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1667 struct pet_expr *lhs, *rhs;
1668 enum pet_op_type op;
1670 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1671 if (op == pet_op_last) {
1672 unsupported(expr);
1673 return NULL;
1676 lhs = extract_expr(expr->getLHS());
1677 rhs = extract_expr(expr->getRHS());
1679 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1680 mark_write(lhs);
1681 if (expr->isCompoundAssignmentOp())
1682 lhs->acc.read = 1;
1685 if (expr->getOpcode() == BO_Assign)
1686 assign(lhs, expr->getRHS());
1688 return pet_expr_new_binary(ctx, op, lhs, rhs);
1691 /* Construct a pet_scop with a single statement killing the entire
1692 * array "array".
1694 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1696 isl_id *id;
1697 isl_space *space;
1698 isl_multi_pw_aff *index;
1699 isl_map *access;
1700 struct pet_expr *expr;
1702 if (!array)
1703 return NULL;
1704 access = isl_map_from_range(isl_set_copy(array->extent));
1705 id = isl_set_get_tuple_id(array->extent);
1706 space = isl_space_alloc(ctx, 0, 0, 0);
1707 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1708 index = isl_multi_pw_aff_zero(space);
1709 expr = pet_expr_kill_from_access_and_index(access, index);
1710 return extract(stmt, expr);
1713 /* Construct a pet_scop for a (single) variable declaration.
1715 * The scop contains the variable being declared (as an array)
1716 * and a statement killing the array.
1718 * If the variable is initialized in the AST, then the scop
1719 * also contains an assignment to the variable.
1721 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1723 Decl *decl;
1724 VarDecl *vd;
1725 struct pet_expr *lhs, *rhs, *pe;
1726 struct pet_scop *scop_decl, *scop;
1727 struct pet_array *array;
1729 if (!stmt->isSingleDecl()) {
1730 unsupported(stmt);
1731 return NULL;
1734 decl = stmt->getSingleDecl();
1735 vd = cast<VarDecl>(decl);
1737 array = extract_array(ctx, vd, NULL);
1738 if (array)
1739 array->declared = 1;
1740 scop_decl = kill(stmt, array);
1741 scop_decl = pet_scop_add_array(scop_decl, array);
1743 if (!vd->getInit())
1744 return scop_decl;
1746 lhs = extract_access_expr(vd);
1747 rhs = extract_expr(vd->getInit());
1749 mark_write(lhs);
1750 assign(lhs, vd->getInit());
1752 pe = pet_expr_new_binary(ctx, pet_op_assign, lhs, rhs);
1753 scop = extract(stmt, pe);
1755 scop_decl = pet_scop_prefix(scop_decl, 0);
1756 scop = pet_scop_prefix(scop, 1);
1758 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1760 return scop;
1763 /* Construct a pet_expr representing a conditional operation.
1765 * We first try to extract the condition as an affine expression.
1766 * If that fails, we construct a pet_expr tree representing the condition.
1768 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1770 struct pet_expr *cond, *lhs, *rhs;
1771 isl_pw_aff *pa;
1773 pa = try_extract_affine(expr->getCond());
1774 if (pa) {
1775 isl_multi_pw_aff *test = isl_multi_pw_aff_from_pw_aff(pa);
1776 test = isl_multi_pw_aff_from_range(test);
1777 cond = pet_expr_from_index(test);
1778 } else
1779 cond = extract_expr(expr->getCond());
1780 lhs = extract_expr(expr->getTrueExpr());
1781 rhs = extract_expr(expr->getFalseExpr());
1783 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1786 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1788 return extract_expr(expr->getSubExpr());
1791 /* Construct a pet_expr representing a floating point value.
1793 * If the floating point literal does not appear in a macro,
1794 * then we use the original representation in the source code
1795 * as the string representation. Otherwise, we use the pretty
1796 * printer to produce a string representation.
1798 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1800 double d;
1801 string s;
1802 const LangOptions &LO = PP.getLangOpts();
1803 SourceLocation loc = expr->getLocation();
1805 if (!loc.isMacroID()) {
1806 SourceManager &SM = PP.getSourceManager();
1807 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1808 s = string(SM.getCharacterData(loc), len);
1809 } else {
1810 llvm::raw_string_ostream S(s);
1811 expr->printPretty(S, 0, PrintingPolicy(LO));
1812 S.str();
1814 d = expr->getValueAsApproximateDouble();
1815 return pet_expr_new_double(ctx, d, s.c_str());
1818 /* Extract an index expression from "expr" and then convert it into
1819 * an access pet_expr.
1821 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1823 isl_multi_pw_aff *index;
1824 struct pet_expr *pe;
1825 int depth;
1827 index = extract_index(expr);
1828 depth = extract_depth(index);
1830 pe = pet_expr_from_index_and_depth(index, depth);
1832 return pe;
1835 /* Extract an index expression from "decl" and then convert it into
1836 * an access pet_expr.
1838 struct pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1840 isl_multi_pw_aff *index;
1841 struct pet_expr *pe;
1842 int depth;
1844 index = extract_index(decl);
1845 depth = extract_depth(index);
1847 pe = pet_expr_from_index_and_depth(index, depth);
1849 return pe;
1852 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1854 return extract_expr(expr->getSubExpr());
1857 /* Extract an assume statement from the argument "expr"
1858 * of a __pencil_assume statement.
1860 struct pet_expr *PetScan::extract_assume(Expr *expr)
1862 isl_pw_aff *cond;
1863 struct pet_expr *res;
1865 cond = try_extract_affine_condition(expr);
1866 if (!cond) {
1867 res = extract_expr(expr);
1868 } else {
1869 isl_multi_pw_aff *index;
1870 index = isl_multi_pw_aff_from_pw_aff(cond);
1871 index = isl_multi_pw_aff_from_range(index);
1872 res = pet_expr_from_index(index);
1874 return pet_expr_new_unary(ctx, pet_op_assume, res);
1877 /* Construct a pet_expr corresponding to the function call argument "expr".
1878 * The argument appears in position "pos" of a call to function "fd".
1880 * If we are passing along a pointer to an array element
1881 * or an entire row or even higher dimensional slice of an array,
1882 * then the function being called may write into the array.
1884 * We assume here that if the function is declared to take a pointer
1885 * to a const type, then the function will perform a read
1886 * and that otherwise, it will perform a write.
1888 struct pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
1889 Expr *expr)
1891 struct pet_expr *res;
1892 int is_addr = 0;
1893 pet_expr *main_arg;
1894 Stmt::StmtClass sc;
1896 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
1897 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
1898 expr = ice->getSubExpr();
1900 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
1901 UnaryOperator *op = cast<UnaryOperator>(expr);
1902 if (op->getOpcode() == UO_AddrOf) {
1903 is_addr = 1;
1904 expr = op->getSubExpr();
1907 res = extract_expr(expr);
1908 main_arg = res;
1909 if (is_addr)
1910 res = pet_expr_new_unary(ctx, pet_op_address_of, res);
1911 if (!res)
1912 return NULL;
1913 sc = expr->getStmtClass();
1914 if ((sc == Stmt::ArraySubscriptExprClass ||
1915 sc == Stmt::MemberExprClass) &&
1916 array_depth(expr->getType().getTypePtr()) > 0)
1917 is_addr = 1;
1918 if (is_addr && main_arg->type == pet_expr_access) {
1919 ParmVarDecl *parm;
1920 if (!fd->hasPrototype()) {
1921 report_prototype_required(expr);
1922 return pet_expr_free(res);
1924 parm = fd->getParamDecl(pos);
1925 if (!const_base(parm->getType()))
1926 mark_write(main_arg);
1929 return res;
1932 /* Construct a pet_expr representing a function call.
1934 * In the special case of a "call" to __pencil_assume,
1935 * construct an assume expression instead.
1937 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1939 struct pet_expr *res = NULL;
1940 FunctionDecl *fd;
1941 string name;
1942 unsigned n_arg;
1944 fd = expr->getDirectCallee();
1945 if (!fd) {
1946 unsupported(expr);
1947 return NULL;
1950 name = fd->getDeclName().getAsString();
1951 n_arg = expr->getNumArgs();
1953 if (n_arg == 1 && name == "__pencil_assume")
1954 return extract_assume(expr->getArg(0));
1956 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1957 if (!res)
1958 return NULL;
1960 for (int i = 0; i < n_arg; ++i) {
1961 Expr *arg = expr->getArg(i);
1962 res->args[i] = PetScan::extract_argument(fd, i, arg);
1963 if (!res->args[i])
1964 goto error;
1967 return res;
1968 error:
1969 pet_expr_free(res);
1970 return NULL;
1973 /* Construct a pet_expr representing a (C style) cast.
1975 struct pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1977 struct pet_expr *arg;
1978 QualType type;
1980 arg = extract_expr(expr->getSubExpr());
1981 if (!arg)
1982 return NULL;
1984 type = expr->getTypeAsWritten();
1985 return pet_expr_new_cast(ctx, type.getAsString().c_str(), arg);
1988 /* Try and construct a pet_expr representing "expr".
1990 struct pet_expr *PetScan::extract_expr(Expr *expr)
1992 switch (expr->getStmtClass()) {
1993 case Stmt::UnaryOperatorClass:
1994 return extract_expr(cast<UnaryOperator>(expr));
1995 case Stmt::CompoundAssignOperatorClass:
1996 case Stmt::BinaryOperatorClass:
1997 return extract_expr(cast<BinaryOperator>(expr));
1998 case Stmt::ImplicitCastExprClass:
1999 return extract_expr(cast<ImplicitCastExpr>(expr));
2000 case Stmt::ArraySubscriptExprClass:
2001 case Stmt::DeclRefExprClass:
2002 case Stmt::IntegerLiteralClass:
2003 case Stmt::MemberExprClass:
2004 return extract_access_expr(expr);
2005 case Stmt::FloatingLiteralClass:
2006 return extract_expr(cast<FloatingLiteral>(expr));
2007 case Stmt::ParenExprClass:
2008 return extract_expr(cast<ParenExpr>(expr));
2009 case Stmt::ConditionalOperatorClass:
2010 return extract_expr(cast<ConditionalOperator>(expr));
2011 case Stmt::CallExprClass:
2012 return extract_expr(cast<CallExpr>(expr));
2013 case Stmt::CStyleCastExprClass:
2014 return extract_expr(cast<CStyleCastExpr>(expr));
2015 default:
2016 unsupported(expr);
2018 return NULL;
2021 /* Check if the given initialization statement is an assignment.
2022 * If so, return that assignment. Otherwise return NULL.
2024 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
2026 BinaryOperator *ass;
2028 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
2029 return NULL;
2031 ass = cast<BinaryOperator>(init);
2032 if (ass->getOpcode() != BO_Assign)
2033 return NULL;
2035 return ass;
2038 /* Check if the given initialization statement is a declaration
2039 * of a single variable.
2040 * If so, return that declaration. Otherwise return NULL.
2042 Decl *PetScan::initialization_declaration(Stmt *init)
2044 DeclStmt *decl;
2046 if (init->getStmtClass() != Stmt::DeclStmtClass)
2047 return NULL;
2049 decl = cast<DeclStmt>(init);
2051 if (!decl->isSingleDecl())
2052 return NULL;
2054 return decl->getSingleDecl();
2057 /* Given the assignment operator in the initialization of a for loop,
2058 * extract the induction variable, i.e., the (integer)variable being
2059 * assigned.
2061 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
2063 Expr *lhs;
2064 DeclRefExpr *ref;
2065 ValueDecl *decl;
2066 const Type *type;
2068 lhs = init->getLHS();
2069 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2070 unsupported(init);
2071 return NULL;
2074 ref = cast<DeclRefExpr>(lhs);
2075 decl = ref->getDecl();
2076 type = decl->getType().getTypePtr();
2078 if (!type->isIntegerType()) {
2079 unsupported(lhs);
2080 return NULL;
2083 return decl;
2086 /* Given the initialization statement of a for loop and the single
2087 * declaration in this initialization statement,
2088 * extract the induction variable, i.e., the (integer) variable being
2089 * declared.
2091 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
2093 VarDecl *vd;
2095 vd = cast<VarDecl>(decl);
2097 const QualType type = vd->getType();
2098 if (!type->isIntegerType()) {
2099 unsupported(init);
2100 return NULL;
2103 if (!vd->getInit()) {
2104 unsupported(init);
2105 return NULL;
2108 return vd;
2111 /* Check that op is of the form iv++ or iv--.
2112 * Return an affine expression "1" or "-1" accordingly.
2114 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
2115 clang::UnaryOperator *op, clang::ValueDecl *iv)
2117 Expr *sub;
2118 DeclRefExpr *ref;
2119 isl_space *space;
2120 isl_aff *aff;
2122 if (!op->isIncrementDecrementOp()) {
2123 unsupported(op);
2124 return NULL;
2127 sub = op->getSubExpr();
2128 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
2129 unsupported(op);
2130 return NULL;
2133 ref = cast<DeclRefExpr>(sub);
2134 if (ref->getDecl() != iv) {
2135 unsupported(op);
2136 return NULL;
2139 space = isl_space_params_alloc(ctx, 0);
2140 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2142 if (op->isIncrementOp())
2143 aff = isl_aff_add_constant_si(aff, 1);
2144 else
2145 aff = isl_aff_add_constant_si(aff, -1);
2147 return isl_pw_aff_from_aff(aff);
2150 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
2151 * has a single constant expression, then put this constant in *user.
2152 * The caller is assumed to have checked that this function will
2153 * be called exactly once.
2155 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
2156 void *user)
2158 isl_val **inc = (isl_val **)user;
2159 int res = 0;
2161 if (isl_aff_is_cst(aff))
2162 *inc = isl_aff_get_constant_val(aff);
2163 else
2164 res = -1;
2166 isl_set_free(set);
2167 isl_aff_free(aff);
2169 return res;
2172 /* Check if op is of the form
2174 * iv = iv + inc
2176 * and return inc as an affine expression.
2178 * We extract an affine expression from the RHS, subtract iv and return
2179 * the result.
2181 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
2182 clang::ValueDecl *iv)
2184 Expr *lhs;
2185 DeclRefExpr *ref;
2186 isl_id *id;
2187 isl_space *dim;
2188 isl_aff *aff;
2189 isl_pw_aff *val;
2191 if (op->getOpcode() != BO_Assign) {
2192 unsupported(op);
2193 return NULL;
2196 lhs = op->getLHS();
2197 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2198 unsupported(op);
2199 return NULL;
2202 ref = cast<DeclRefExpr>(lhs);
2203 if (ref->getDecl() != iv) {
2204 unsupported(op);
2205 return NULL;
2208 val = extract_affine(op->getRHS());
2210 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2212 dim = isl_space_params_alloc(ctx, 1);
2213 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2214 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2215 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2217 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
2219 return val;
2222 /* Check that op is of the form iv += cst or iv -= cst
2223 * and return an affine expression corresponding oto cst or -cst accordingly.
2225 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
2226 CompoundAssignOperator *op, clang::ValueDecl *iv)
2228 Expr *lhs;
2229 DeclRefExpr *ref;
2230 bool neg = false;
2231 isl_pw_aff *val;
2232 BinaryOperatorKind opcode;
2234 opcode = op->getOpcode();
2235 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
2236 unsupported(op);
2237 return NULL;
2239 if (opcode == BO_SubAssign)
2240 neg = true;
2242 lhs = op->getLHS();
2243 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2244 unsupported(op);
2245 return NULL;
2248 ref = cast<DeclRefExpr>(lhs);
2249 if (ref->getDecl() != iv) {
2250 unsupported(op);
2251 return NULL;
2254 val = extract_affine(op->getRHS());
2255 if (neg)
2256 val = isl_pw_aff_neg(val);
2258 return val;
2261 /* Check that the increment of the given for loop increments
2262 * (or decrements) the induction variable "iv" and return
2263 * the increment as an affine expression if successful.
2265 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
2266 ValueDecl *iv)
2268 Stmt *inc = stmt->getInc();
2270 if (!inc) {
2271 report_missing_increment(stmt);
2272 return NULL;
2275 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
2276 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
2277 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
2278 return extract_compound_increment(
2279 cast<CompoundAssignOperator>(inc), iv);
2280 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
2281 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
2283 unsupported(inc);
2284 return NULL;
2287 /* Embed the given iteration domain in an extra outer loop
2288 * with induction variable "var".
2289 * If this variable appeared as a parameter in the constraints,
2290 * it is replaced by the new outermost dimension.
2292 static __isl_give isl_set *embed(__isl_take isl_set *set,
2293 __isl_take isl_id *var)
2295 int pos;
2297 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
2298 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
2299 if (pos >= 0) {
2300 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
2301 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2304 isl_id_free(var);
2305 return set;
2308 /* Return those elements in the space of "cond" that come after
2309 * (based on "sign") an element in "cond".
2311 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
2313 isl_map *previous_to_this;
2315 if (sign > 0)
2316 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
2317 else
2318 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
2320 cond = isl_set_apply(cond, previous_to_this);
2322 return cond;
2325 /* Create the infinite iteration domain
2327 * { [id] : id >= 0 }
2329 * If "scop" has an affine skip of type pet_skip_later,
2330 * then remove those iterations i that have an earlier iteration
2331 * where the skip condition is satisfied, meaning that iteration i
2332 * is not executed.
2333 * Since we are dealing with a loop without loop iterator,
2334 * the skip condition cannot refer to the current loop iterator and
2335 * so effectively, the returned set is of the form
2337 * { [0]; [id] : id >= 1 and not skip }
2339 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
2340 struct pet_scop *scop)
2342 isl_ctx *ctx = isl_id_get_ctx(id);
2343 isl_set *domain;
2344 isl_set *skip;
2346 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
2347 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
2349 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
2350 return domain;
2352 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2353 skip = embed(skip, isl_id_copy(id));
2354 skip = isl_set_intersect(skip , isl_set_copy(domain));
2355 domain = isl_set_subtract(domain, after(skip, 1));
2357 return domain;
2360 /* Create an identity affine expression on the space containing "domain",
2361 * which is assumed to be one-dimensional.
2363 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
2365 isl_local_space *ls;
2367 ls = isl_local_space_from_space(isl_set_get_space(domain));
2368 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
2371 /* Create an affine expression that maps elements
2372 * of a single-dimensional array "id_test" to the previous element
2373 * (according to "inc"), provided this element belongs to "domain".
2374 * That is, create the affine expression
2376 * { id[x] -> id[x - inc] : x - inc in domain }
2378 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
2379 __isl_take isl_set *domain, __isl_take isl_val *inc)
2381 isl_space *space;
2382 isl_local_space *ls;
2383 isl_aff *aff;
2384 isl_multi_pw_aff *prev;
2386 space = isl_set_get_space(domain);
2387 ls = isl_local_space_from_space(space);
2388 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2389 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
2390 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
2391 domain = isl_set_preimage_multi_pw_aff(domain,
2392 isl_multi_pw_aff_copy(prev));
2393 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
2394 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
2396 return prev;
2399 /* Add an implication to "scop" expressing that if an element of
2400 * virtual array "id_test" has value "satisfied" then all previous elements
2401 * of this array also have that value. The set of previous elements
2402 * is bounded by "domain". If "sign" is negative then the iterator
2403 * is decreasing and we express that all subsequent array elements
2404 * (but still defined previously) have the same value.
2406 static struct pet_scop *add_implication(struct pet_scop *scop,
2407 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
2408 int satisfied)
2410 isl_space *space;
2411 isl_map *map;
2413 domain = isl_set_set_tuple_id(domain, id_test);
2414 space = isl_set_get_space(domain);
2415 if (sign > 0)
2416 map = isl_map_lex_ge(space);
2417 else
2418 map = isl_map_lex_le(space);
2419 map = isl_map_intersect_range(map, domain);
2420 scop = pet_scop_add_implication(scop, map, satisfied);
2422 return scop;
2425 /* Add a filter to "scop" that imposes that it is only executed
2426 * when the variable identified by "id_test" has a zero value
2427 * for all previous iterations of "domain".
2429 * In particular, add a filter that imposes that the array
2430 * has a zero value at the previous iteration of domain and
2431 * add an implication that implies that it then has that
2432 * value for all previous iterations.
2434 static struct pet_scop *scop_add_break(struct pet_scop *scop,
2435 __isl_take isl_id *id_test, __isl_take isl_set *domain,
2436 __isl_take isl_val *inc)
2438 isl_multi_pw_aff *prev;
2439 int sign = isl_val_sgn(inc);
2441 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2442 scop = add_implication(scop, id_test, domain, sign, 0);
2443 scop = pet_scop_filter(scop, prev, 0);
2445 return scop;
2448 /* Construct a pet_scop for an infinite loop around the given body.
2450 * We extract a pet_scop for the body and then embed it in a loop with
2451 * iteration domain
2453 * { [t] : t >= 0 }
2455 * and schedule
2457 * { [t] -> [t] }
2459 * If the body contains any break, then it is taken into
2460 * account in infinite_domain (if the skip condition is affine)
2461 * or in scop_add_break (if the skip condition is not affine).
2463 * If we were only able to extract part of the body, then simply
2464 * return that part.
2466 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2468 isl_id *id, *id_test;
2469 isl_set *domain;
2470 isl_aff *ident;
2471 struct pet_scop *scop;
2472 bool has_var_break;
2474 scop = extract(body);
2475 if (!scop)
2476 return NULL;
2477 if (partial)
2478 return scop;
2480 id = isl_id_alloc(ctx, "t", NULL);
2481 domain = infinite_domain(isl_id_copy(id), scop);
2482 ident = identity_aff(domain);
2484 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2485 if (has_var_break)
2486 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
2488 scop = pet_scop_embed(scop, isl_set_copy(domain),
2489 isl_map_from_aff(isl_aff_copy(ident)), ident, id);
2490 if (has_var_break)
2491 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
2492 else
2493 isl_set_free(domain);
2495 return scop;
2498 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2500 * for (;;)
2501 * body
2504 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2506 clear_assignments clear(assigned_value);
2507 clear.TraverseStmt(stmt->getBody());
2509 return extract_infinite_loop(stmt->getBody());
2512 /* Create an index expression for an access to a virtual array
2513 * representing the result of a condition.
2514 * Unlike other accessed data, the id of the array is NULL as
2515 * there is no ValueDecl in the program corresponding to the virtual
2516 * array.
2517 * The array starts out as a scalar, but grows along with the
2518 * statement writing to the array in pet_scop_embed.
2520 static __isl_give isl_multi_pw_aff *create_test_index(isl_ctx *ctx, int test_nr)
2522 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2523 isl_id *id;
2524 char name[50];
2526 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2527 id = isl_id_alloc(ctx, name, NULL);
2528 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2529 return isl_multi_pw_aff_zero(dim);
2532 /* Add an array with the given extent (range of "index") to the list
2533 * of arrays in "scop" and return the extended pet_scop.
2534 * The array is marked as attaining values 0 and 1 only and
2535 * as each element being assigned at most once.
2537 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2538 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
2540 isl_ctx *ctx = isl_multi_pw_aff_get_ctx(index);
2541 isl_space *dim;
2542 struct pet_array *array;
2543 isl_map *access;
2545 if (!scop)
2546 return NULL;
2547 if (!ctx)
2548 goto error;
2550 array = isl_calloc_type(ctx, struct pet_array);
2551 if (!array)
2552 goto error;
2554 access = isl_map_from_multi_pw_aff(isl_multi_pw_aff_copy(index));
2555 array->extent = isl_map_range(access);
2556 dim = isl_space_params_alloc(ctx, 0);
2557 array->context = isl_set_universe(dim);
2558 dim = isl_space_set_alloc(ctx, 0, 1);
2559 array->value_bounds = isl_set_universe(dim);
2560 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2561 isl_dim_set, 0, 0);
2562 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2563 isl_dim_set, 0, 1);
2564 array->element_type = strdup("int");
2565 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2566 array->uniquely_defined = 1;
2568 if (!array->extent || !array->context)
2569 array = pet_array_free(array);
2571 scop = pet_scop_add_array(scop, array);
2573 return scop;
2574 error:
2575 pet_scop_free(scop);
2576 return NULL;
2579 /* Construct a pet_scop for a while loop of the form
2581 * while (pa)
2582 * body
2584 * In particular, construct a scop for an infinite loop around body and
2585 * intersect the domain with the affine expression.
2586 * Note that this intersection may result in an empty loop.
2588 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2589 Stmt *body)
2591 struct pet_scop *scop;
2592 isl_set *dom;
2593 isl_set *valid;
2595 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2596 dom = isl_pw_aff_non_zero_set(pa);
2597 scop = extract_infinite_loop(body);
2598 scop = pet_scop_restrict(scop, dom);
2599 scop = pet_scop_restrict_context(scop, valid);
2601 return scop;
2604 /* Construct a scop for a while, given the scops for the condition
2605 * and the body, the filter identifier and the iteration domain of
2606 * the while loop.
2608 * In particular, the scop for the condition is filtered to depend
2609 * on "id_test" evaluating to true for all previous iterations
2610 * of the loop, while the scop for the body is filtered to depend
2611 * on "id_test" evaluating to true for all iterations up to the
2612 * current iteration.
2613 * The actual filter only imposes that this virtual array has
2614 * value one on the previous or the current iteration.
2615 * The fact that this condition also applies to the previous
2616 * iterations is enforced by an implication.
2618 * These filtered scops are then combined into a single scop.
2620 * "sign" is positive if the iterator increases and negative
2621 * if it decreases.
2623 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2624 struct pet_scop *scop_body, __isl_take isl_id *id_test,
2625 __isl_take isl_set *domain, __isl_take isl_val *inc)
2627 isl_ctx *ctx = isl_set_get_ctx(domain);
2628 isl_space *space;
2629 isl_multi_pw_aff *test_index;
2630 isl_multi_pw_aff *prev;
2631 int sign = isl_val_sgn(inc);
2632 struct pet_scop *scop;
2634 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2635 scop_cond = pet_scop_filter(scop_cond, prev, 1);
2637 space = isl_space_map_from_set(isl_set_get_space(domain));
2638 test_index = isl_multi_pw_aff_identity(space);
2639 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
2640 isl_id_copy(id_test));
2641 scop_body = pet_scop_filter(scop_body, test_index, 1);
2643 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
2644 scop = add_implication(scop, id_test, domain, sign, 1);
2646 return scop;
2649 /* Check if the while loop is of the form
2651 * while (affine expression)
2652 * body
2654 * If so, call extract_affine_while to construct a scop.
2656 * Otherwise, construct a generic while scop, with iteration domain
2657 * { [t] : t >= 0 }. The scop consists of two parts, one for
2658 * evaluating the condition and one for the body.
2659 * The schedule is adjusted to reflect that the condition is evaluated
2660 * before the body is executed and the body is filtered to depend
2661 * on the result of the condition evaluating to true on all iterations
2662 * up to the current iteration, while the evaluation of the condition itself
2663 * is filtered to depend on the result of the condition evaluating to true
2664 * on all previous iterations.
2665 * The context of the scop representing the body is dropped
2666 * because we don't know how many times the body will be executed,
2667 * if at all.
2669 * If the body contains any break, then it is taken into
2670 * account in infinite_domain (if the skip condition is affine)
2671 * or in scop_add_break (if the skip condition is not affine).
2673 * If we were only able to extract part of the body, then simply
2674 * return that part.
2676 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2678 Expr *cond;
2679 int test_nr, stmt_nr;
2680 isl_id *id, *id_test, *id_break_test;
2681 isl_multi_pw_aff *test_index;
2682 isl_set *domain;
2683 isl_aff *ident;
2684 isl_pw_aff *pa;
2685 struct pet_scop *scop, *scop_body;
2686 bool has_var_break;
2688 cond = stmt->getCond();
2689 if (!cond) {
2690 unsupported(stmt);
2691 return NULL;
2694 clear_assignments clear(assigned_value);
2695 clear.TraverseStmt(stmt->getBody());
2697 pa = try_extract_affine_condition(cond);
2698 if (pa)
2699 return extract_affine_while(pa, stmt->getBody());
2701 if (!allow_nested) {
2702 unsupported(stmt);
2703 return NULL;
2706 test_nr = n_test++;
2707 stmt_nr = n_stmt++;
2708 scop_body = extract(stmt->getBody());
2709 if (partial)
2710 return scop_body;
2712 test_index = create_test_index(ctx, test_nr);
2713 scop = extract_non_affine_condition(cond, stmt_nr,
2714 isl_multi_pw_aff_copy(test_index));
2715 scop = scop_add_array(scop, test_index, ast_context);
2716 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2717 isl_multi_pw_aff_free(test_index);
2719 id = isl_id_alloc(ctx, "t", NULL);
2720 domain = infinite_domain(isl_id_copy(id), scop_body);
2721 ident = identity_aff(domain);
2723 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2724 if (has_var_break)
2725 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2727 scop = pet_scop_prefix(scop, 0);
2728 scop = pet_scop_embed(scop, isl_set_copy(domain),
2729 isl_map_from_aff(isl_aff_copy(ident)),
2730 isl_aff_copy(ident), isl_id_copy(id));
2731 scop_body = pet_scop_reset_context(scop_body);
2732 scop_body = pet_scop_prefix(scop_body, 1);
2733 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2734 isl_map_from_aff(isl_aff_copy(ident)), ident, id);
2736 if (has_var_break) {
2737 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2738 isl_set_copy(domain), isl_val_one(ctx));
2739 scop_body = scop_add_break(scop_body, id_break_test,
2740 isl_set_copy(domain), isl_val_one(ctx));
2742 scop = scop_add_while(scop, scop_body, id_test, domain,
2743 isl_val_one(ctx));
2745 return scop;
2748 /* Check whether "cond" expresses a simple loop bound
2749 * on the only set dimension.
2750 * In particular, if "up" is set then "cond" should contain only
2751 * upper bounds on the set dimension.
2752 * Otherwise, it should contain only lower bounds.
2754 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2756 if (isl_val_is_pos(inc))
2757 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2758 else
2759 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2762 /* Extend a condition on a given iteration of a loop to one that
2763 * imposes the same condition on all previous iterations.
2764 * "domain" expresses the lower [upper] bound on the iterations
2765 * when inc is positive [negative].
2767 * In particular, we construct the condition (when inc is positive)
2769 * forall i' : (domain(i') and i' <= i) => cond(i')
2771 * which is equivalent to
2773 * not exists i' : domain(i') and i' <= i and not cond(i')
2775 * We construct this set by negating cond, applying a map
2777 * { [i'] -> [i] : domain(i') and i' <= i }
2779 * and then negating the result again.
2781 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2782 __isl_take isl_set *domain, __isl_take isl_val *inc)
2784 isl_map *previous_to_this;
2786 if (isl_val_is_pos(inc))
2787 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2788 else
2789 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2791 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2793 cond = isl_set_complement(cond);
2794 cond = isl_set_apply(cond, previous_to_this);
2795 cond = isl_set_complement(cond);
2797 isl_val_free(inc);
2799 return cond;
2802 /* Construct a domain of the form
2804 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2806 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2807 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2809 isl_aff *aff;
2810 isl_space *dim;
2811 isl_set *set;
2813 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2814 dim = isl_pw_aff_get_domain_space(init);
2815 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2816 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2817 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2819 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2820 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2821 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2822 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2824 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2826 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2828 return isl_set_params(set);
2831 /* Assuming "cond" represents a bound on a loop where the loop
2832 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2833 * is possible.
2835 * Under the given assumptions, wrapping is only possible if "cond" allows
2836 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2837 * increasing iterator and 0 in case of a decreasing iterator.
2839 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2840 __isl_keep isl_val *inc)
2842 bool cw;
2843 isl_ctx *ctx;
2844 isl_val *limit;
2845 isl_set *test;
2847 test = isl_set_copy(cond);
2849 ctx = isl_set_get_ctx(test);
2850 if (isl_val_is_neg(inc))
2851 limit = isl_val_zero(ctx);
2852 else {
2853 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2854 limit = isl_val_2exp(limit);
2855 limit = isl_val_sub_ui(limit, 1);
2858 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2859 cw = !isl_set_is_empty(test);
2860 isl_set_free(test);
2862 return cw;
2865 /* Given a one-dimensional space, construct the following affine expression
2866 * on this space
2868 * { [v] -> [v mod 2^width] }
2870 * where width is the number of bits used to represent the values
2871 * of the unsigned variable "iv".
2873 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2874 ValueDecl *iv)
2876 isl_ctx *ctx;
2877 isl_val *mod;
2878 isl_aff *aff;
2880 ctx = isl_space_get_ctx(dim);
2881 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2882 mod = isl_val_2exp(mod);
2884 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2885 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2886 aff = isl_aff_mod_val(aff, mod);
2888 return aff;
2891 /* Project out the parameter "id" from "set".
2893 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2894 __isl_keep isl_id *id)
2896 int pos;
2898 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2899 if (pos >= 0)
2900 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2902 return set;
2905 /* Compute the set of parameters for which "set1" is a subset of "set2".
2907 * set1 is a subset of set2 if
2909 * forall i in set1 : i in set2
2911 * or
2913 * not exists i in set1 and i not in set2
2915 * i.e.,
2917 * not exists i in set1 \ set2
2919 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2920 __isl_take isl_set *set2)
2922 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2925 /* Compute the set of parameter values for which "cond" holds
2926 * on the next iteration for each element of "dom".
2928 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2929 * and then compute the set of parameters for which the result is a subset
2930 * of "cond".
2932 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2933 __isl_take isl_set *dom, __isl_take isl_val *inc)
2935 isl_space *space;
2936 isl_aff *aff;
2937 isl_map *next;
2939 space = isl_set_get_space(dom);
2940 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2941 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2942 aff = isl_aff_add_constant_val(aff, inc);
2943 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2945 dom = isl_set_apply(dom, next);
2947 return enforce_subset(dom, cond);
2950 /* Does "id" refer to a nested access?
2952 static bool is_nested_parameter(__isl_keep isl_id *id)
2954 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2957 /* Does parameter "pos" of "space" refer to a nested access?
2959 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2961 bool nested;
2962 isl_id *id;
2964 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2965 nested = is_nested_parameter(id);
2966 isl_id_free(id);
2968 return nested;
2971 /* Does "space" involve any parameters that refer to nested
2972 * accesses, i.e., parameters with no name?
2974 static bool has_nested(__isl_keep isl_space *space)
2976 int nparam;
2978 nparam = isl_space_dim(space, isl_dim_param);
2979 for (int i = 0; i < nparam; ++i)
2980 if (is_nested_parameter(space, i))
2981 return true;
2983 return false;
2986 /* Does "pa" involve any parameters that refer to nested
2987 * accesses, i.e., parameters with no name?
2989 static bool has_nested(__isl_keep isl_pw_aff *pa)
2991 isl_space *space;
2992 bool nested;
2994 space = isl_pw_aff_get_space(pa);
2995 nested = has_nested(space);
2996 isl_space_free(space);
2998 return nested;
3001 /* Construct a pet_scop for a for statement.
3002 * The for loop is required to be of the form
3004 * for (i = init; condition; ++i)
3006 * or
3008 * for (i = init; condition; --i)
3010 * The initialization of the for loop should either be an assignment
3011 * to an integer variable, or a declaration of such a variable with
3012 * initialization.
3014 * The condition is allowed to contain nested accesses, provided
3015 * they are not being written to inside the body of the loop.
3016 * Otherwise, or if the condition is otherwise non-affine, the for loop is
3017 * essentially treated as a while loop, with iteration domain
3018 * { [i] : i >= init }.
3020 * We extract a pet_scop for the body and then embed it in a loop with
3021 * iteration domain and schedule
3023 * { [i] : i >= init and condition' }
3024 * { [i] -> [i] }
3026 * or
3028 * { [i] : i <= init and condition' }
3029 * { [i] -> [-i] }
3031 * Where condition' is equal to condition if the latter is
3032 * a simple upper [lower] bound and a condition that is extended
3033 * to apply to all previous iterations otherwise.
3035 * If the condition is non-affine, then we drop the condition from the
3036 * iteration domain and instead create a separate statement
3037 * for evaluating the condition. The body is then filtered to depend
3038 * on the result of the condition evaluating to true on all iterations
3039 * up to the current iteration, while the evaluation the condition itself
3040 * is filtered to depend on the result of the condition evaluating to true
3041 * on all previous iterations.
3042 * The context of the scop representing the body is dropped
3043 * because we don't know how many times the body will be executed,
3044 * if at all.
3046 * If the stride of the loop is not 1, then "i >= init" is replaced by
3048 * (exists a: i = init + stride * a and a >= 0)
3050 * If the loop iterator i is unsigned, then wrapping may occur.
3051 * We therefore use a virtual iterator instead that does not wrap.
3052 * However, the condition in the code applies
3053 * to the wrapped value, so we need to change condition(i)
3054 * into condition([i % 2^width]). Similarly, we replace all accesses
3055 * to the original iterator by the wrapping of the virtual iterator.
3056 * Note that there may be no need to perform this final wrapping
3057 * if the loop condition (after wrapping) satisfies certain conditions.
3058 * However, the is_simple_bound condition is not enough since it doesn't
3059 * check if there even is an upper bound.
3061 * Wrapping on unsigned iterators can be avoided entirely if
3062 * loop condition is simple, the loop iterator is incremented
3063 * [decremented] by one and the last value before wrapping cannot
3064 * possibly satisfy the loop condition.
3066 * Before extracting a pet_scop from the body we remove all
3067 * assignments in assigned_value to variables that are assigned
3068 * somewhere in the body of the loop.
3070 * Valid parameters for a for loop are those for which the initial
3071 * value itself, the increment on each domain iteration and
3072 * the condition on both the initial value and
3073 * the result of incrementing the iterator for each iteration of the domain
3074 * can be evaluated.
3075 * If the loop condition is non-affine, then we only consider validity
3076 * of the initial value.
3078 * If the body contains any break, then we keep track of it in "skip"
3079 * (if the skip condition is affine) or it is handled in scop_add_break
3080 * (if the skip condition is not affine).
3081 * Note that the affine break condition needs to be considered with
3082 * respect to previous iterations in the virtual domain (if any).
3084 * If we were only able to extract part of the body, then simply
3085 * return that part.
3087 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
3089 BinaryOperator *ass;
3090 Decl *decl;
3091 Stmt *init;
3092 Expr *lhs, *rhs;
3093 ValueDecl *iv;
3094 isl_space *space;
3095 isl_set *domain;
3096 isl_map *sched;
3097 isl_set *cond = NULL;
3098 isl_set *skip = NULL;
3099 isl_id *id, *id_test = NULL, *id_break_test;
3100 struct pet_scop *scop, *scop_cond = NULL;
3101 assigned_value_cache cache(assigned_value);
3102 isl_val *inc;
3103 bool was_assigned;
3104 bool is_one;
3105 bool is_unsigned;
3106 bool is_simple;
3107 bool is_virtual;
3108 bool has_affine_break;
3109 bool has_var_break;
3110 isl_aff *wrap = NULL;
3111 isl_pw_aff *pa, *pa_inc, *init_val;
3112 isl_set *valid_init;
3113 isl_set *valid_cond;
3114 isl_set *valid_cond_init;
3115 isl_set *valid_cond_next;
3116 isl_set *valid_inc;
3117 int stmt_id;
3119 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
3120 return extract_infinite_for(stmt);
3122 init = stmt->getInit();
3123 if (!init) {
3124 unsupported(stmt);
3125 return NULL;
3127 if ((ass = initialization_assignment(init)) != NULL) {
3128 iv = extract_induction_variable(ass);
3129 if (!iv)
3130 return NULL;
3131 lhs = ass->getLHS();
3132 rhs = ass->getRHS();
3133 } else if ((decl = initialization_declaration(init)) != NULL) {
3134 VarDecl *var = extract_induction_variable(init, decl);
3135 if (!var)
3136 return NULL;
3137 iv = var;
3138 rhs = var->getInit();
3139 lhs = create_DeclRefExpr(var);
3140 } else {
3141 unsupported(stmt->getInit());
3142 return NULL;
3145 assigned_value.erase(iv);
3146 clear_assignments clear(assigned_value);
3147 clear.TraverseStmt(stmt->getBody());
3149 was_assigned = assigned_value.find(iv) != assigned_value.end();
3150 clear_assignment(assigned_value, iv);
3151 init_val = extract_affine(rhs);
3152 if (!was_assigned)
3153 assigned_value.erase(iv);
3154 if (!init_val)
3155 return NULL;
3157 pa_inc = extract_increment(stmt, iv);
3158 if (!pa_inc) {
3159 isl_pw_aff_free(init_val);
3160 return NULL;
3163 inc = NULL;
3164 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
3165 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
3166 isl_pw_aff_free(init_val);
3167 isl_pw_aff_free(pa_inc);
3168 unsupported(stmt->getInc());
3169 isl_val_free(inc);
3170 return NULL;
3173 pa = try_extract_nested_condition(stmt->getCond());
3174 if (allow_nested && (!pa || has_nested(pa)))
3175 stmt_id = n_stmt++;
3177 scop = extract(stmt->getBody());
3178 if (partial) {
3179 isl_pw_aff_free(init_val);
3180 isl_pw_aff_free(pa_inc);
3181 isl_pw_aff_free(pa);
3182 isl_val_free(inc);
3183 return scop;
3186 valid_inc = isl_pw_aff_domain(pa_inc);
3188 is_unsigned = iv->getType()->isUnsignedIntegerType();
3190 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
3192 has_affine_break = scop &&
3193 pet_scop_has_affine_skip(scop, pet_skip_later);
3194 if (has_affine_break)
3195 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
3196 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
3197 if (has_var_break)
3198 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
3200 if (pa && !is_nested_allowed(pa, scop)) {
3201 isl_pw_aff_free(pa);
3202 pa = NULL;
3205 if (!allow_nested && !pa)
3206 pa = try_extract_affine_condition(stmt->getCond());
3207 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3208 cond = isl_pw_aff_non_zero_set(pa);
3209 if (allow_nested && !cond) {
3210 isl_multi_pw_aff *test_index;
3211 int save_n_stmt = n_stmt;
3212 test_index = create_test_index(ctx, n_test++);
3213 n_stmt = stmt_id;
3214 scop_cond = extract_non_affine_condition(stmt->getCond(),
3215 n_stmt++, isl_multi_pw_aff_copy(test_index));
3216 n_stmt = save_n_stmt;
3217 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
3218 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
3219 isl_dim_out);
3220 isl_multi_pw_aff_free(test_index);
3221 scop_cond = pet_scop_prefix(scop_cond, 0);
3222 scop = pet_scop_reset_context(scop);
3223 scop = pet_scop_prefix(scop, 1);
3224 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
3227 cond = embed(cond, isl_id_copy(id));
3228 skip = embed(skip, isl_id_copy(id));
3229 valid_cond = isl_set_coalesce(valid_cond);
3230 valid_cond = embed(valid_cond, isl_id_copy(id));
3231 valid_inc = embed(valid_inc, isl_id_copy(id));
3232 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
3233 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
3235 valid_cond_init = enforce_subset(
3236 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
3237 isl_set_copy(valid_cond));
3238 if (is_one && !is_virtual) {
3239 isl_pw_aff_free(init_val);
3240 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
3241 lhs, rhs, init);
3242 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3243 valid_init = set_project_out_by_id(valid_init, id);
3244 domain = isl_pw_aff_non_zero_set(pa);
3245 } else {
3246 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
3247 domain = strided_domain(isl_id_copy(id), init_val,
3248 isl_val_copy(inc));
3251 domain = embed(domain, isl_id_copy(id));
3252 if (is_virtual) {
3253 isl_map *rev_wrap;
3254 wrap = compute_wrapping(isl_set_get_space(cond), iv);
3255 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
3256 rev_wrap = isl_map_reverse(rev_wrap);
3257 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
3258 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
3259 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
3260 valid_inc = isl_set_apply(valid_inc, rev_wrap);
3262 is_simple = is_simple_bound(cond, inc);
3263 if (!is_simple) {
3264 cond = isl_set_gist(cond, isl_set_copy(domain));
3265 is_simple = is_simple_bound(cond, inc);
3267 if (!is_simple)
3268 cond = valid_for_each_iteration(cond,
3269 isl_set_copy(domain), isl_val_copy(inc));
3270 domain = isl_set_intersect(domain, cond);
3271 if (has_affine_break) {
3272 skip = isl_set_intersect(skip , isl_set_copy(domain));
3273 skip = after(skip, isl_val_sgn(inc));
3274 domain = isl_set_subtract(domain, skip);
3276 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
3277 space = isl_space_from_domain(isl_set_get_space(domain));
3278 space = isl_space_add_dims(space, isl_dim_out, 1);
3279 sched = isl_map_universe(space);
3280 if (isl_val_is_pos(inc))
3281 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
3282 else
3283 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
3285 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
3286 isl_val_copy(inc));
3287 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
3289 if (!is_virtual)
3290 wrap = identity_aff(domain);
3292 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
3293 isl_map_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
3294 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
3295 scop = resolve_nested(scop);
3296 if (has_var_break)
3297 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
3298 isl_val_copy(inc));
3299 if (id_test) {
3300 scop = scop_add_while(scop_cond, scop, id_test, domain,
3301 isl_val_copy(inc));
3302 isl_set_free(valid_inc);
3303 } else {
3304 scop = pet_scop_restrict_context(scop, valid_inc);
3305 scop = pet_scop_restrict_context(scop, valid_cond_next);
3306 scop = pet_scop_restrict_context(scop, valid_cond_init);
3307 isl_set_free(domain);
3309 clear_assignment(assigned_value, iv);
3311 isl_val_free(inc);
3313 scop = pet_scop_restrict_context(scop, valid_init);
3315 return scop;
3318 /* Try and construct a pet_scop corresponding to a compound statement.
3320 * "skip_declarations" is set if we should skip initial declarations
3321 * in the children of the compound statements. This then implies
3322 * that this sequence of children should not be treated as a block
3323 * since the initial statements may be skipped.
3325 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
3327 return extract(stmt->children(), !skip_declarations, skip_declarations);
3330 /* Does parameter "pos" of "map" refer to a nested access?
3332 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
3334 bool nested;
3335 isl_id *id;
3337 id = isl_map_get_dim_id(map, isl_dim_param, pos);
3338 nested = is_nested_parameter(id);
3339 isl_id_free(id);
3341 return nested;
3344 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
3346 static int n_nested_parameter(__isl_keep isl_space *space)
3348 int n = 0;
3349 int nparam;
3351 nparam = isl_space_dim(space, isl_dim_param);
3352 for (int i = 0; i < nparam; ++i)
3353 if (is_nested_parameter(space, i))
3354 ++n;
3356 return n;
3359 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
3361 static int n_nested_parameter(__isl_keep isl_map *map)
3363 isl_space *space;
3364 int n;
3366 space = isl_map_get_space(map);
3367 n = n_nested_parameter(space);
3368 isl_space_free(space);
3370 return n;
3373 /* For each nested access parameter in "space",
3374 * construct a corresponding pet_expr, place it in args and
3375 * record its position in "param2pos".
3376 * "n_arg" is the number of elements that are already in args.
3377 * The position recorded in "param2pos" takes this number into account.
3378 * If the pet_expr corresponding to a parameter is identical to
3379 * the pet_expr corresponding to an earlier parameter, then these two
3380 * parameters are made to refer to the same element in args.
3382 * Return the final number of elements in args or -1 if an error has occurred.
3384 int PetScan::extract_nested(__isl_keep isl_space *space,
3385 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
3387 int nparam;
3389 nparam = isl_space_dim(space, isl_dim_param);
3390 for (int i = 0; i < nparam; ++i) {
3391 int j;
3392 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3393 Expr *nested;
3395 if (!is_nested_parameter(id)) {
3396 isl_id_free(id);
3397 continue;
3400 nested = (Expr *) isl_id_get_user(id);
3401 args[n_arg] = extract_expr(nested);
3402 isl_id_free(id);
3403 if (!args[n_arg])
3404 return -1;
3406 for (j = 0; j < n_arg; ++j)
3407 if (pet_expr_is_equal(args[j], args[n_arg]))
3408 break;
3410 if (j < n_arg) {
3411 pet_expr_free(args[n_arg]);
3412 args[n_arg] = NULL;
3413 param2pos[i] = j;
3414 } else
3415 param2pos[i] = n_arg++;
3418 return n_arg;
3421 /* For each nested access parameter in the access relations in "expr",
3422 * construct a corresponding pet_expr, place it in expr->args and
3423 * record its position in "param2pos".
3424 * n is the number of nested access parameters.
3426 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
3427 std::map<int,int> &param2pos)
3429 isl_space *space;
3431 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
3432 expr->n_arg = n;
3433 if (!expr->args)
3434 goto error;
3436 space = isl_map_get_space(expr->acc.access);
3437 n = extract_nested(space, 0, expr->args, param2pos);
3438 isl_space_free(space);
3440 if (n < 0)
3441 goto error;
3443 expr->n_arg = n;
3444 return expr;
3445 error:
3446 pet_expr_free(expr);
3447 return NULL;
3450 /* Look for parameters in any access relation in "expr" that
3451 * refer to nested accesses. In particular, these are
3452 * parameters with no name.
3454 * If there are any such parameters, then the domain of the index
3455 * expression and the access relation, which is still [] at this point,
3456 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
3457 * (after identifying identical nested accesses).
3459 * This transformation is performed in several steps.
3460 * We first extract the arguments in extract_nested.
3461 * param2pos maps the original parameter position to the position
3462 * of the argument.
3463 * Then we move these parameters to input dimensions.
3464 * t2pos maps the positions of these temporary input dimensions
3465 * to the positions of the corresponding arguments.
3466 * Finally, we express these temporary dimensions in terms of the domain
3467 * [[] -> [t_1,...,t_n]] and precompose index expression and access
3468 * relations with this function.
3470 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
3472 int n;
3473 int nparam;
3474 isl_space *space;
3475 isl_local_space *ls;
3476 isl_aff *aff;
3477 isl_multi_aff *ma;
3478 std::map<int,int> param2pos;
3479 std::map<int,int> t2pos;
3481 if (!expr)
3482 return expr;
3484 for (int i = 0; i < expr->n_arg; ++i) {
3485 expr->args[i] = resolve_nested(expr->args[i]);
3486 if (!expr->args[i]) {
3487 pet_expr_free(expr);
3488 return NULL;
3492 if (expr->type != pet_expr_access)
3493 return expr;
3495 n = n_nested_parameter(expr->acc.access);
3496 if (n == 0)
3497 return expr;
3499 expr = extract_nested(expr, n, param2pos);
3500 if (!expr)
3501 return NULL;
3503 expr = pet_expr_access_align_params(expr);
3504 if (!expr)
3505 return NULL;
3506 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
3508 n = 0;
3509 for (int i = nparam - 1; i >= 0; --i) {
3510 isl_id *id = isl_map_get_dim_id(expr->acc.access,
3511 isl_dim_param, i);
3512 if (!is_nested_parameter(id)) {
3513 isl_id_free(id);
3514 continue;
3517 expr->acc.access = isl_map_move_dims(expr->acc.access,
3518 isl_dim_in, n, isl_dim_param, i, 1);
3519 expr->acc.index = isl_multi_pw_aff_move_dims(expr->acc.index,
3520 isl_dim_in, n, isl_dim_param, i, 1);
3521 t2pos[n] = param2pos[i];
3522 n++;
3524 isl_id_free(id);
3527 space = isl_multi_pw_aff_get_space(expr->acc.index);
3528 space = isl_space_set_from_params(isl_space_params(space));
3529 space = isl_space_add_dims(space, isl_dim_set, expr->n_arg);
3530 space = isl_space_wrap(isl_space_from_range(space));
3531 ls = isl_local_space_from_space(isl_space_copy(space));
3532 space = isl_space_from_domain(space);
3533 space = isl_space_add_dims(space, isl_dim_out, n);
3534 ma = isl_multi_aff_zero(space);
3536 for (int i = 0; i < n; ++i) {
3537 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3538 isl_dim_set, t2pos[i]);
3539 ma = isl_multi_aff_set_aff(ma, i, aff);
3541 isl_local_space_free(ls);
3543 expr->acc.access = isl_map_preimage_domain_multi_aff(expr->acc.access,
3544 isl_multi_aff_copy(ma));
3545 expr->acc.index = isl_multi_pw_aff_pullback_multi_aff(expr->acc.index,
3546 ma);
3548 return expr;
3551 /* Return the file offset of the expansion location of "Loc".
3553 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3555 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3558 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3560 /* Return a SourceLocation for the location after the first semicolon
3561 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3562 * call it and also skip trailing spaces and newline.
3564 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3565 const LangOptions &LO)
3567 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3570 #else
3572 /* Return a SourceLocation for the location after the first semicolon
3573 * after "loc". If Lexer::findLocationAfterToken is not available,
3574 * we look in the underlying character data for the first semicolon.
3576 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3577 const LangOptions &LO)
3579 const char *semi;
3580 const char *s = SM.getCharacterData(loc);
3582 semi = strchr(s, ';');
3583 if (!semi)
3584 return SourceLocation();
3585 return loc.getFileLocWithOffset(semi + 1 - s);
3588 #endif
3590 /* If the token at "loc" is the first token on the line, then return
3591 * a location referring to the start of the line.
3592 * Otherwise, return "loc".
3594 * This function is used to extend a scop to the start of the line
3595 * if the first token of the scop is also the first token on the line.
3597 * We look for the first token on the line. If its location is equal to "loc",
3598 * then the latter is the location of the first token on the line.
3600 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3601 SourceManager &SM, const LangOptions &LO)
3603 std::pair<FileID, unsigned> file_offset_pair;
3604 llvm::StringRef file;
3605 const char *pos;
3606 Token tok;
3607 SourceLocation token_loc, line_loc;
3608 int col;
3610 loc = SM.getExpansionLoc(loc);
3611 col = SM.getExpansionColumnNumber(loc);
3612 line_loc = loc.getLocWithOffset(1 - col);
3613 file_offset_pair = SM.getDecomposedLoc(line_loc);
3614 file = SM.getBufferData(file_offset_pair.first, NULL);
3615 pos = file.data() + file_offset_pair.second;
3617 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3618 file.begin(), pos, file.end());
3619 lexer.LexFromRawLexer(tok);
3620 token_loc = tok.getLocation();
3622 if (token_loc == loc)
3623 return line_loc;
3624 else
3625 return loc;
3628 /* Update start and end of "scop" to include the region covered by "range".
3629 * If "skip_semi" is set, then we assume "range" is followed by
3630 * a semicolon and also include this semicolon.
3632 struct pet_scop *PetScan::update_scop_start_end(struct pet_scop *scop,
3633 SourceRange range, bool skip_semi)
3635 SourceLocation loc = range.getBegin();
3636 SourceManager &SM = PP.getSourceManager();
3637 const LangOptions &LO = PP.getLangOpts();
3638 unsigned start, end;
3640 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3641 start = getExpansionOffset(SM, loc);
3642 loc = range.getEnd();
3643 if (skip_semi)
3644 loc = location_after_semi(loc, SM, LO);
3645 else
3646 loc = PP.getLocForEndOfToken(loc);
3647 end = getExpansionOffset(SM, loc);
3649 scop = pet_scop_update_start_end(scop, start, end);
3650 return scop;
3653 /* Convert a top-level pet_expr to a pet_scop with one statement.
3654 * This mainly involves resolving nested expression parameters
3655 * and setting the name of the iteration space.
3656 * The name is given by "label" if it is non-NULL. Otherwise,
3657 * it is of the form S_<n_stmt>.
3658 * start and end of the pet_scop are derived from those of "stmt".
3659 * If "stmt" is an expression statement, then its range does not
3660 * include the semicolon, while it should be included in the pet_scop.
3662 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
3663 __isl_take isl_id *label)
3665 struct pet_stmt *ps;
3666 struct pet_scop *scop;
3667 SourceLocation loc = stmt->getLocStart();
3668 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3669 bool skip_semi;
3671 expr = resolve_nested(expr);
3672 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
3673 scop = pet_scop_from_pet_stmt(ctx, ps);
3675 skip_semi = isa<Expr>(stmt);
3676 scop = update_scop_start_end(scop, stmt->getSourceRange(), skip_semi);
3677 return scop;
3680 /* Check if we can extract an affine expression from "expr".
3681 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3682 * We turn on autodetection so that we won't generate any warnings
3683 * and turn off nesting, so that we won't accept any non-affine constructs.
3685 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3687 isl_pw_aff *pwaff;
3688 int save_autodetect = options->autodetect;
3689 bool save_nesting = nesting_enabled;
3691 options->autodetect = 1;
3692 nesting_enabled = false;
3694 pwaff = extract_affine(expr);
3696 options->autodetect = save_autodetect;
3697 nesting_enabled = save_nesting;
3699 return pwaff;
3702 /* Check if we can extract an affine constraint from "expr".
3703 * Return the constraint as an isl_set if we can and NULL otherwise.
3704 * We turn on autodetection so that we won't generate any warnings
3705 * and turn off nesting, so that we won't accept any non-affine constructs.
3707 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3709 isl_pw_aff *cond;
3710 int save_autodetect = options->autodetect;
3711 bool save_nesting = nesting_enabled;
3713 options->autodetect = 1;
3714 nesting_enabled = false;
3716 cond = extract_condition(expr);
3718 options->autodetect = save_autodetect;
3719 nesting_enabled = save_nesting;
3721 return cond;
3724 /* Check whether "expr" is an affine constraint.
3726 bool PetScan::is_affine_condition(Expr *expr)
3728 isl_pw_aff *cond;
3730 cond = try_extract_affine_condition(expr);
3731 isl_pw_aff_free(cond);
3733 return cond != NULL;
3736 /* Check if we can extract a condition from "expr".
3737 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3738 * If allow_nested is set, then the condition may involve parameters
3739 * corresponding to nested accesses.
3740 * We turn on autodetection so that we won't generate any warnings.
3742 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3744 isl_pw_aff *cond;
3745 int save_autodetect = options->autodetect;
3746 bool save_nesting = nesting_enabled;
3748 options->autodetect = 1;
3749 nesting_enabled = allow_nested;
3750 cond = extract_condition(expr);
3752 options->autodetect = save_autodetect;
3753 nesting_enabled = save_nesting;
3755 return cond;
3758 /* If the top-level expression of "stmt" is an assignment, then
3759 * return that assignment as a BinaryOperator.
3760 * Otherwise return NULL.
3762 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3764 BinaryOperator *ass;
3766 if (!stmt)
3767 return NULL;
3768 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3769 return NULL;
3771 ass = cast<BinaryOperator>(stmt);
3772 if(ass->getOpcode() != BO_Assign)
3773 return NULL;
3775 return ass;
3778 /* Check if the given if statement is a conditional assignement
3779 * with a non-affine condition. If so, construct a pet_scop
3780 * corresponding to this conditional assignment. Otherwise return NULL.
3782 * In particular we check if "stmt" is of the form
3784 * if (condition)
3785 * a = f(...);
3786 * else
3787 * a = g(...);
3789 * where a is some array or scalar access.
3790 * The constructed pet_scop then corresponds to the expression
3792 * a = condition ? f(...) : g(...)
3794 * All access relations in f(...) are intersected with condition
3795 * while all access relation in g(...) are intersected with the complement.
3797 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3799 BinaryOperator *ass_then, *ass_else;
3800 isl_multi_pw_aff *write_then, *write_else;
3801 isl_set *cond, *comp;
3802 isl_multi_pw_aff *index;
3803 isl_pw_aff *pa;
3804 int equal;
3805 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3806 bool save_nesting = nesting_enabled;
3808 if (!options->detect_conditional_assignment)
3809 return NULL;
3811 ass_then = top_assignment_or_null(stmt->getThen());
3812 ass_else = top_assignment_or_null(stmt->getElse());
3814 if (!ass_then || !ass_else)
3815 return NULL;
3817 if (is_affine_condition(stmt->getCond()))
3818 return NULL;
3820 write_then = extract_index(ass_then->getLHS());
3821 write_else = extract_index(ass_else->getLHS());
3823 equal = isl_multi_pw_aff_plain_is_equal(write_then, write_else);
3824 isl_multi_pw_aff_free(write_else);
3825 if (equal < 0 || !equal) {
3826 isl_multi_pw_aff_free(write_then);
3827 return NULL;
3830 nesting_enabled = allow_nested;
3831 pa = extract_condition(stmt->getCond());
3832 nesting_enabled = save_nesting;
3833 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3834 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3835 index = isl_multi_pw_aff_from_range(isl_multi_pw_aff_from_pw_aff(pa));
3837 pe_cond = pet_expr_from_index(index);
3839 pe_then = extract_expr(ass_then->getRHS());
3840 pe_then = pet_expr_restrict(pe_then, cond);
3841 pe_else = extract_expr(ass_else->getRHS());
3842 pe_else = pet_expr_restrict(pe_else, comp);
3844 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
3845 pe_write = pet_expr_from_index_and_depth(write_then,
3846 extract_depth(write_then));
3847 if (pe_write) {
3848 pe_write->acc.write = 1;
3849 pe_write->acc.read = 0;
3851 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
3852 return extract(stmt, pe);
3855 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3856 * evaluating "cond" and writing the result to a virtual scalar,
3857 * as expressed by "index".
3859 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond, int stmt_nr,
3860 __isl_take isl_multi_pw_aff *index)
3862 struct pet_expr *expr, *write;
3863 struct pet_stmt *ps;
3864 SourceLocation loc = cond->getLocStart();
3865 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3867 write = pet_expr_from_index(index);
3868 if (write) {
3869 write->acc.write = 1;
3870 write->acc.read = 0;
3872 expr = extract_expr(cond);
3873 expr = resolve_nested(expr);
3874 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
3875 ps = pet_stmt_from_pet_expr(ctx, line, NULL, stmt_nr, expr);
3876 return pet_scop_from_pet_stmt(ctx, ps);
3879 extern "C" {
3880 static struct pet_expr *embed_access(struct pet_expr *expr, void *user);
3883 /* Precompose the access relation and the index expression associated
3884 * to "expr" with the function pointed to by "user",
3885 * thereby embedding the access relation in the domain of this function.
3886 * The initial domain of the access relation and the index expression
3887 * is the zero-dimensional domain.
3889 static struct pet_expr *embed_access(struct pet_expr *expr, void *user)
3891 isl_multi_aff *ma = (isl_multi_aff *) user;
3893 expr->acc.access = isl_map_preimage_domain_multi_aff(expr->acc.access,
3894 isl_multi_aff_copy(ma));
3895 expr->acc.index = isl_multi_pw_aff_pullback_multi_aff(expr->acc.index,
3896 isl_multi_aff_copy(ma));
3897 if (!expr->acc.access || !expr->acc.index)
3898 goto error;
3900 return expr;
3901 error:
3902 pet_expr_free(expr);
3903 return NULL;
3906 /* Precompose all access relations in "expr" with "ma", thereby
3907 * embedding them in the domain of "ma".
3909 static struct pet_expr *embed(struct pet_expr *expr,
3910 __isl_keep isl_multi_aff *ma)
3912 return pet_expr_map_access(expr, &embed_access, ma);
3915 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3917 static int n_nested_parameter(__isl_keep isl_set *set)
3919 isl_space *space;
3920 int n;
3922 space = isl_set_get_space(set);
3923 n = n_nested_parameter(space);
3924 isl_space_free(space);
3926 return n;
3929 /* Remove all parameters from "map" that refer to nested accesses.
3931 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
3933 int nparam;
3934 isl_space *space;
3936 space = isl_map_get_space(map);
3937 nparam = isl_space_dim(space, isl_dim_param);
3938 for (int i = nparam - 1; i >= 0; --i)
3939 if (is_nested_parameter(space, i))
3940 map = isl_map_project_out(map, isl_dim_param, i, 1);
3941 isl_space_free(space);
3943 return map;
3946 /* Remove all parameters from "mpa" that refer to nested accesses.
3948 static __isl_give isl_multi_pw_aff *remove_nested_parameters(
3949 __isl_take isl_multi_pw_aff *mpa)
3951 int nparam;
3952 isl_space *space;
3954 space = isl_multi_pw_aff_get_space(mpa);
3955 nparam = isl_space_dim(space, isl_dim_param);
3956 for (int i = nparam - 1; i >= 0; --i) {
3957 if (!is_nested_parameter(space, i))
3958 continue;
3959 mpa = isl_multi_pw_aff_drop_dims(mpa, isl_dim_param, i, 1);
3961 isl_space_free(space);
3963 return mpa;
3966 /* Remove all parameters from the index expression and access relation of "expr"
3967 * that refer to nested accesses.
3969 static struct pet_expr *remove_nested_parameters(struct pet_expr *expr)
3971 expr->acc.access = remove_nested_parameters(expr->acc.access);
3972 expr->acc.index = remove_nested_parameters(expr->acc.index);
3973 if (!expr->acc.access || !expr->acc.index)
3974 goto error;
3976 return expr;
3977 error:
3978 pet_expr_free(expr);
3979 return NULL;
3982 extern "C" {
3983 static struct pet_expr *expr_remove_nested_parameters(
3984 struct pet_expr *expr, void *user);
3987 static struct pet_expr *expr_remove_nested_parameters(
3988 struct pet_expr *expr, void *user)
3990 return remove_nested_parameters(expr);
3993 /* Remove all nested access parameters from the schedule and all
3994 * accesses of "stmt".
3995 * There is no need to remove them from the domain as these parameters
3996 * have already been removed from the domain when this function is called.
3998 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
4000 if (!stmt)
4001 return NULL;
4002 stmt->schedule = remove_nested_parameters(stmt->schedule);
4003 stmt->body = pet_expr_map_access(stmt->body,
4004 &expr_remove_nested_parameters, NULL);
4005 if (!stmt->schedule || !stmt->body)
4006 goto error;
4007 for (int i = 0; i < stmt->n_arg; ++i) {
4008 stmt->args[i] = pet_expr_map_access(stmt->args[i],
4009 &expr_remove_nested_parameters, NULL);
4010 if (!stmt->args[i])
4011 goto error;
4014 return stmt;
4015 error:
4016 pet_stmt_free(stmt);
4017 return NULL;
4020 /* For each nested access parameter in the domain of "stmt",
4021 * construct a corresponding pet_expr, place it before the original
4022 * elements in stmt->args and record its position in "param2pos".
4023 * n is the number of nested access parameters.
4025 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
4026 std::map<int,int> &param2pos)
4028 int i;
4029 isl_space *space;
4030 int n_arg;
4031 struct pet_expr **args;
4033 n_arg = stmt->n_arg;
4034 args = isl_calloc_array(ctx, struct pet_expr *, n + n_arg);
4035 if (!args)
4036 goto error;
4038 space = isl_set_get_space(stmt->domain);
4039 n_arg = extract_nested(space, 0, args, param2pos);
4040 isl_space_free(space);
4042 if (n_arg < 0)
4043 goto error;
4045 for (i = 0; i < stmt->n_arg; ++i)
4046 args[n_arg + i] = stmt->args[i];
4047 free(stmt->args);
4048 stmt->args = args;
4049 stmt->n_arg += n_arg;
4051 return stmt;
4052 error:
4053 if (args) {
4054 for (i = 0; i < n; ++i)
4055 pet_expr_free(args[i]);
4056 free(args);
4058 pet_stmt_free(stmt);
4059 return NULL;
4062 /* Check whether any of the arguments i of "stmt" starting at position "n"
4063 * is equal to one of the first "n" arguments j.
4064 * If so, combine the constraints on arguments i and j and remove
4065 * argument i.
4067 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
4069 int i, j;
4070 isl_map *map;
4072 if (!stmt)
4073 return NULL;
4074 if (n == 0)
4075 return stmt;
4076 if (n == stmt->n_arg)
4077 return stmt;
4079 map = isl_set_unwrap(stmt->domain);
4081 for (i = stmt->n_arg - 1; i >= n; --i) {
4082 for (j = 0; j < n; ++j)
4083 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
4084 break;
4085 if (j >= n)
4086 continue;
4088 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
4089 map = isl_map_project_out(map, isl_dim_out, i, 1);
4091 pet_expr_free(stmt->args[i]);
4092 for (j = i; j + 1 < stmt->n_arg; ++j)
4093 stmt->args[j] = stmt->args[j + 1];
4094 stmt->n_arg--;
4097 stmt->domain = isl_map_wrap(map);
4098 if (!stmt->domain)
4099 goto error;
4100 return stmt;
4101 error:
4102 pet_stmt_free(stmt);
4103 return NULL;
4106 /* Look for parameters in the iteration domain of "stmt" that
4107 * refer to nested accesses. In particular, these are
4108 * parameters with no name.
4110 * If there are any such parameters, then as many extra variables
4111 * (after identifying identical nested accesses) are inserted in the
4112 * range of the map wrapped inside the domain, before the original variables.
4113 * If the original domain is not a wrapped map, then a new wrapped
4114 * map is created with zero output dimensions.
4115 * The parameters are then equated to the corresponding output dimensions
4116 * and subsequently projected out, from the iteration domain,
4117 * the schedule and the access relations.
4118 * For each of the output dimensions, a corresponding argument
4119 * expression is inserted. Initially they are created with
4120 * a zero-dimensional domain, so they have to be embedded
4121 * in the current iteration domain.
4122 * param2pos maps the position of the parameter to the position
4123 * of the corresponding output dimension in the wrapped map.
4125 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
4127 int n;
4128 int nparam;
4129 unsigned n_arg;
4130 isl_map *map;
4131 isl_space *space;
4132 isl_multi_aff *ma;
4133 std::map<int,int> param2pos;
4135 if (!stmt)
4136 return NULL;
4138 n = n_nested_parameter(stmt->domain);
4139 if (n == 0)
4140 return stmt;
4142 n_arg = stmt->n_arg;
4143 stmt = extract_nested(stmt, n, param2pos);
4144 if (!stmt)
4145 return NULL;
4147 n = stmt->n_arg - n_arg;
4148 nparam = isl_set_dim(stmt->domain, isl_dim_param);
4149 if (isl_set_is_wrapping(stmt->domain))
4150 map = isl_set_unwrap(stmt->domain);
4151 else
4152 map = isl_map_from_domain(stmt->domain);
4153 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
4155 for (int i = nparam - 1; i >= 0; --i) {
4156 isl_id *id;
4158 if (!is_nested_parameter(map, i))
4159 continue;
4161 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
4162 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
4163 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
4164 param2pos[i]);
4165 map = isl_map_project_out(map, isl_dim_param, i, 1);
4168 stmt->domain = isl_map_wrap(map);
4170 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
4171 space = isl_space_from_domain(isl_space_domain(space));
4172 ma = isl_multi_aff_zero(space);
4173 for (int pos = 0; pos < n; ++pos)
4174 stmt->args[pos] = embed(stmt->args[pos], ma);
4175 isl_multi_aff_free(ma);
4177 stmt = remove_nested_parameters(stmt);
4178 stmt = remove_duplicate_arguments(stmt, n);
4180 return stmt;
4183 /* For each statement in "scop", move the parameters that correspond
4184 * to nested access into the ranges of the domains and create
4185 * corresponding argument expressions.
4187 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
4189 if (!scop)
4190 return NULL;
4192 for (int i = 0; i < scop->n_stmt; ++i) {
4193 scop->stmts[i] = resolve_nested(scop->stmts[i]);
4194 if (!scop->stmts[i])
4195 goto error;
4198 return scop;
4199 error:
4200 pet_scop_free(scop);
4201 return NULL;
4204 /* Given an access expression "expr", is the variable accessed by
4205 * "expr" assigned anywhere inside "scop"?
4207 static bool is_assigned(pet_expr *expr, pet_scop *scop)
4209 bool assigned = false;
4210 isl_id *id;
4212 id = pet_expr_access_get_id(expr);
4213 assigned = pet_scop_writes(scop, id);
4214 isl_id_free(id);
4216 return assigned;
4219 /* Are all nested access parameters in "pa" allowed given "scop".
4220 * In particular, is none of them written by anywhere inside "scop".
4222 * If "scop" has any skip conditions, then no nested access parameters
4223 * are allowed. In particular, if there is any nested access in a guard
4224 * for a piece of code containing a "continue", then we want to introduce
4225 * a separate statement for evaluating this guard so that we can express
4226 * that the result is false for all previous iterations.
4228 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
4230 int nparam;
4232 if (!scop)
4233 return true;
4235 if (!has_nested(pa))
4236 return true;
4238 if (pet_scop_has_skip(scop, pet_skip_now))
4239 return false;
4241 nparam = isl_pw_aff_dim(pa, isl_dim_param);
4242 for (int i = 0; i < nparam; ++i) {
4243 Expr *nested;
4244 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
4245 pet_expr *expr;
4246 bool allowed;
4248 if (!is_nested_parameter(id)) {
4249 isl_id_free(id);
4250 continue;
4253 nested = (Expr *) isl_id_get_user(id);
4254 expr = extract_expr(nested);
4255 allowed = expr && expr->type == pet_expr_access &&
4256 !is_assigned(expr, scop);
4258 pet_expr_free(expr);
4259 isl_id_free(id);
4261 if (!allowed)
4262 return false;
4265 return true;
4268 /* Do we need to construct a skip condition of the given type
4269 * on an if statement, given that the if condition is non-affine?
4271 * pet_scop_filter_skip can only handle the case where the if condition
4272 * holds (the then branch) and the skip condition is universal.
4273 * In any other case, we need to construct a new skip condition.
4275 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
4276 bool have_else, enum pet_skip type)
4278 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
4279 return true;
4280 if (scop_then && pet_scop_has_skip(scop_then, type) &&
4281 !pet_scop_has_universal_skip(scop_then, type))
4282 return true;
4283 return false;
4286 /* Do we need to construct a skip condition of the given type
4287 * on an if statement, given that the if condition is affine?
4289 * There is no need to construct a new skip condition if all
4290 * the skip conditions are affine.
4292 static bool need_skip_aff(struct pet_scop *scop_then,
4293 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
4295 if (scop_then && pet_scop_has_var_skip(scop_then, type))
4296 return true;
4297 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
4298 return true;
4299 return false;
4302 /* Do we need to construct a skip condition of the given type
4303 * on an if statement?
4305 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
4306 bool have_else, enum pet_skip type, bool affine)
4308 if (affine)
4309 return need_skip_aff(scop_then, scop_else, have_else, type);
4310 else
4311 return need_skip(scop_then, scop_else, have_else, type);
4314 /* Construct an affine expression pet_expr that evaluates
4315 * to the constant "val".
4317 static struct pet_expr *universally(isl_ctx *ctx, int val)
4319 isl_local_space *ls;
4320 isl_aff *aff;
4321 isl_multi_pw_aff *mpa;
4323 ls = isl_local_space_from_space(isl_space_set_alloc(ctx, 0, 0));
4324 aff = isl_aff_val_on_domain(ls, isl_val_int_from_si(ctx, val));
4325 mpa = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4327 return pet_expr_from_index(mpa);
4330 /* Construct an affine expression pet_expr that evaluates
4331 * to the constant 1.
4333 static struct pet_expr *universally_true(isl_ctx *ctx)
4335 return universally(ctx, 1);
4338 /* Construct an affine expression pet_expr that evaluates
4339 * to the constant 0.
4341 static struct pet_expr *universally_false(isl_ctx *ctx)
4343 return universally(ctx, 0);
4346 /* Given an index expression "test_index" for the if condition,
4347 * an index expression "skip_index" for the skip condition and
4348 * scops for the then and else branches, construct a scop for
4349 * computing "skip_index".
4351 * The computed scop contains a single statement that essentially does
4353 * skip_index = test_cond ? skip_cond_then : skip_cond_else
4355 * If the skip conditions of the then and/or else branch are not affine,
4356 * then they need to be filtered by test_index.
4357 * If they are missing, then this means the skip condition is false.
4359 * Since we are constructing a skip condition for the if statement,
4360 * the skip conditions on the then and else branches are removed.
4362 static struct pet_scop *extract_skip(PetScan *scan,
4363 __isl_take isl_multi_pw_aff *test_index,
4364 __isl_take isl_multi_pw_aff *skip_index,
4365 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
4366 enum pet_skip type)
4368 struct pet_expr *expr_then, *expr_else, *expr, *expr_skip;
4369 struct pet_stmt *stmt;
4370 struct pet_scop *scop;
4371 isl_ctx *ctx = scan->ctx;
4373 if (!scop_then)
4374 goto error;
4375 if (have_else && !scop_else)
4376 goto error;
4378 if (pet_scop_has_skip(scop_then, type)) {
4379 expr_then = pet_scop_get_skip_expr(scop_then, type);
4380 pet_scop_reset_skip(scop_then, type);
4381 if (!pet_expr_is_affine(expr_then))
4382 expr_then = pet_expr_filter(expr_then,
4383 isl_multi_pw_aff_copy(test_index), 1);
4384 } else
4385 expr_then = universally_false(ctx);
4387 if (have_else && pet_scop_has_skip(scop_else, type)) {
4388 expr_else = pet_scop_get_skip_expr(scop_else, type);
4389 pet_scop_reset_skip(scop_else, type);
4390 if (!pet_expr_is_affine(expr_else))
4391 expr_else = pet_expr_filter(expr_else,
4392 isl_multi_pw_aff_copy(test_index), 0);
4393 } else
4394 expr_else = universally_false(ctx);
4396 expr = pet_expr_from_index(test_index);
4397 expr = pet_expr_new_ternary(ctx, expr, expr_then, expr_else);
4398 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4399 if (expr_skip) {
4400 expr_skip->acc.write = 1;
4401 expr_skip->acc.read = 0;
4403 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4404 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, scan->n_stmt++, expr);
4406 scop = pet_scop_from_pet_stmt(ctx, stmt);
4407 scop = scop_add_array(scop, skip_index, scan->ast_context);
4408 isl_multi_pw_aff_free(skip_index);
4410 return scop;
4411 error:
4412 isl_multi_pw_aff_free(test_index);
4413 isl_multi_pw_aff_free(skip_index);
4414 return NULL;
4417 /* Is scop's skip_now condition equal to its skip_later condition?
4418 * In particular, this means that it either has no skip_now condition
4419 * or both a skip_now and a skip_later condition (that are equal to each other).
4421 static bool skip_equals_skip_later(struct pet_scop *scop)
4423 int has_skip_now, has_skip_later;
4424 int equal;
4425 isl_multi_pw_aff *skip_now, *skip_later;
4427 if (!scop)
4428 return false;
4429 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
4430 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
4431 if (has_skip_now != has_skip_later)
4432 return false;
4433 if (!has_skip_now)
4434 return true;
4436 skip_now = pet_scop_get_skip(scop, pet_skip_now);
4437 skip_later = pet_scop_get_skip(scop, pet_skip_later);
4438 equal = isl_multi_pw_aff_is_equal(skip_now, skip_later);
4439 isl_multi_pw_aff_free(skip_now);
4440 isl_multi_pw_aff_free(skip_later);
4442 return equal;
4445 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
4447 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
4449 pet_scop_reset_skip(scop1, pet_skip_later);
4450 pet_scop_reset_skip(scop2, pet_skip_later);
4453 /* Structure that handles the construction of skip conditions.
4455 * scop_then and scop_else represent the then and else branches
4456 * of the if statement
4458 * skip[type] is true if we need to construct a skip condition of that type
4459 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
4460 * are equal to each other
4461 * index[type] is an index expression from a zero-dimension domain
4462 * to the virtual array representing the skip condition
4463 * scop[type] is a scop for computing the skip condition
4465 struct pet_skip_info {
4466 isl_ctx *ctx;
4468 bool skip[2];
4469 bool equal;
4470 isl_multi_pw_aff *index[2];
4471 struct pet_scop *scop[2];
4473 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
4475 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
4478 /* Structure that handles the construction of skip conditions on if statements.
4480 * scop_then and scop_else represent the then and else branches
4481 * of the if statement
4483 struct pet_skip_info_if : public pet_skip_info {
4484 struct pet_scop *scop_then, *scop_else;
4485 bool have_else;
4487 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4488 struct pet_scop *scop_else, bool have_else, bool affine);
4489 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index,
4490 enum pet_skip type);
4491 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index);
4492 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
4493 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4494 int offset);
4495 struct pet_scop *add(struct pet_scop *scop, int offset);
4498 /* Initialize a pet_skip_info_if structure based on the then and else branches
4499 * and based on whether the if condition is affine or not.
4501 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4502 struct pet_scop *scop_else, bool have_else, bool affine) :
4503 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
4504 have_else(have_else)
4506 skip[pet_skip_now] =
4507 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
4508 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
4509 (!have_else || skip_equals_skip_later(scop_else));
4510 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4511 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
4514 /* If we need to construct a skip condition of the given type,
4515 * then do so now.
4517 * "mpa" represents the if condition.
4519 void pet_skip_info_if::extract(PetScan *scan,
4520 __isl_keep isl_multi_pw_aff *mpa, enum pet_skip type)
4522 isl_ctx *ctx;
4524 if (!skip[type])
4525 return;
4527 ctx = isl_multi_pw_aff_get_ctx(mpa);
4528 index[type] = create_test_index(ctx, scan->n_test++);
4529 scop[type] = extract_skip(scan, isl_multi_pw_aff_copy(mpa),
4530 isl_multi_pw_aff_copy(index[type]),
4531 scop_then, scop_else, have_else, type);
4534 /* Construct the required skip conditions, given the if condition "index".
4536 void pet_skip_info_if::extract(PetScan *scan,
4537 __isl_keep isl_multi_pw_aff *index)
4539 extract(scan, index, pet_skip_now);
4540 extract(scan, index, pet_skip_later);
4541 if (equal)
4542 drop_skip_later(scop_then, scop_else);
4545 /* Construct the required skip conditions, given the if condition "cond".
4547 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
4549 isl_multi_pw_aff *test;
4551 if (!skip[pet_skip_now] && !skip[pet_skip_later])
4552 return;
4554 test = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_copy(cond));
4555 test = isl_multi_pw_aff_from_range(test);
4556 extract(scan, test);
4557 isl_multi_pw_aff_free(test);
4560 /* Add the computed skip condition of the give type to "main" and
4561 * add the scop for computing the condition at the given offset.
4563 * If equal is set, then we only computed a skip condition for pet_skip_now,
4564 * but we also need to set it as main's pet_skip_later.
4566 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
4567 enum pet_skip type, int offset)
4569 if (!skip[type])
4570 return main;
4572 scop[type] = pet_scop_prefix(scop[type], offset);
4573 main = pet_scop_add_par(ctx, main, scop[type]);
4574 scop[type] = NULL;
4576 if (equal)
4577 main = pet_scop_set_skip(main, pet_skip_later,
4578 isl_multi_pw_aff_copy(index[type]));
4580 main = pet_scop_set_skip(main, type, index[type]);
4581 index[type] = NULL;
4583 return main;
4586 /* Add the computed skip conditions to "main" and
4587 * add the scops for computing the conditions at the given offset.
4589 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
4591 scop = add(scop, pet_skip_now, offset);
4592 scop = add(scop, pet_skip_later, offset);
4594 return scop;
4597 /* Construct a pet_scop for a non-affine if statement.
4599 * We create a separate statement that writes the result
4600 * of the non-affine condition to a virtual scalar.
4601 * A constraint requiring the value of this virtual scalar to be one
4602 * is added to the iteration domains of the then branch.
4603 * Similarly, a constraint requiring the value of this virtual scalar
4604 * to be zero is added to the iteration domains of the else branch, if any.
4605 * We adjust the schedules to ensure that the virtual scalar is written
4606 * before it is read.
4608 * If there are any breaks or continues in the then and/or else
4609 * branches, then we may have to compute a new skip condition.
4610 * This is handled using a pet_skip_info_if object.
4611 * On initialization, the object checks if skip conditions need
4612 * to be computed. If so, it does so in "extract" and adds them in "add".
4614 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
4615 struct pet_scop *scop_then, struct pet_scop *scop_else,
4616 bool have_else, int stmt_id)
4618 struct pet_scop *scop;
4619 isl_multi_pw_aff *test_index;
4620 int save_n_stmt = n_stmt;
4622 test_index = create_test_index(ctx, n_test++);
4623 n_stmt = stmt_id;
4624 scop = extract_non_affine_condition(cond, n_stmt++,
4625 isl_multi_pw_aff_copy(test_index));
4626 n_stmt = save_n_stmt;
4627 scop = scop_add_array(scop, test_index, ast_context);
4629 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
4630 skip.extract(this, test_index);
4632 scop = pet_scop_prefix(scop, 0);
4633 scop_then = pet_scop_prefix(scop_then, 1);
4634 scop_then = pet_scop_filter(scop_then,
4635 isl_multi_pw_aff_copy(test_index), 1);
4636 if (have_else) {
4637 scop_else = pet_scop_prefix(scop_else, 1);
4638 scop_else = pet_scop_filter(scop_else, test_index, 0);
4639 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
4640 } else
4641 isl_multi_pw_aff_free(test_index);
4643 scop = pet_scop_add_seq(ctx, scop, scop_then);
4645 scop = skip.add(scop, 2);
4647 return scop;
4650 /* Construct a pet_scop for an if statement.
4652 * If the condition fits the pattern of a conditional assignment,
4653 * then it is handled by extract_conditional_assignment.
4654 * Otherwise, we do the following.
4656 * If the condition is affine, then the condition is added
4657 * to the iteration domains of the then branch, while the
4658 * opposite of the condition in added to the iteration domains
4659 * of the else branch, if any.
4660 * We allow the condition to be dynamic, i.e., to refer to
4661 * scalars or array elements that may be written to outside
4662 * of the given if statement. These nested accesses are then represented
4663 * as output dimensions in the wrapping iteration domain.
4664 * If it is also written _inside_ the then or else branch, then
4665 * we treat the condition as non-affine.
4666 * As explained in extract_non_affine_if, this will introduce
4667 * an extra statement.
4668 * For aesthetic reasons, we want this statement to have a statement
4669 * number that is lower than those of the then and else branches.
4670 * In order to evaluate if we will need such a statement, however, we
4671 * first construct scops for the then and else branches.
4672 * We therefore reserve a statement number if we might have to
4673 * introduce such an extra statement.
4675 * If the condition is not affine, then the scop is created in
4676 * extract_non_affine_if.
4678 * If there are any breaks or continues in the then and/or else
4679 * branches, then we may have to compute a new skip condition.
4680 * This is handled using a pet_skip_info_if object.
4681 * On initialization, the object checks if skip conditions need
4682 * to be computed. If so, it does so in "extract" and adds them in "add".
4684 struct pet_scop *PetScan::extract(IfStmt *stmt)
4686 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4687 isl_pw_aff *cond;
4688 int stmt_id;
4689 isl_set *set;
4690 isl_set *valid;
4692 clear_assignments clear(assigned_value);
4693 clear.TraverseStmt(stmt->getThen());
4694 if (stmt->getElse())
4695 clear.TraverseStmt(stmt->getElse());
4697 scop = extract_conditional_assignment(stmt);
4698 if (scop)
4699 return scop;
4701 cond = try_extract_nested_condition(stmt->getCond());
4702 if (allow_nested && (!cond || has_nested(cond)))
4703 stmt_id = n_stmt++;
4706 assigned_value_cache cache(assigned_value);
4707 scop_then = extract(stmt->getThen());
4710 if (stmt->getElse()) {
4711 assigned_value_cache cache(assigned_value);
4712 scop_else = extract(stmt->getElse());
4713 if (options->autodetect) {
4714 if (scop_then && !scop_else) {
4715 partial = true;
4716 isl_pw_aff_free(cond);
4717 return scop_then;
4719 if (!scop_then && scop_else) {
4720 partial = true;
4721 isl_pw_aff_free(cond);
4722 return scop_else;
4727 if (cond &&
4728 (!is_nested_allowed(cond, scop_then) ||
4729 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4730 isl_pw_aff_free(cond);
4731 cond = NULL;
4733 if (allow_nested && !cond)
4734 return extract_non_affine_if(stmt->getCond(), scop_then,
4735 scop_else, stmt->getElse(), stmt_id);
4737 if (!cond)
4738 cond = extract_condition(stmt->getCond());
4740 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4741 skip.extract(this, cond);
4743 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4744 set = isl_pw_aff_non_zero_set(cond);
4745 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4747 if (stmt->getElse()) {
4748 set = isl_set_subtract(isl_set_copy(valid), set);
4749 scop_else = pet_scop_restrict(scop_else, set);
4750 scop = pet_scop_add_par(ctx, scop, scop_else);
4751 } else
4752 isl_set_free(set);
4753 scop = resolve_nested(scop);
4754 scop = pet_scop_restrict_context(scop, valid);
4756 if (skip)
4757 scop = pet_scop_prefix(scop, 0);
4758 scop = skip.add(scop, 1);
4760 return scop;
4763 /* Try and construct a pet_scop for a label statement.
4764 * We currently only allow labels on expression statements.
4766 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4768 isl_id *label;
4769 Stmt *sub;
4771 sub = stmt->getSubStmt();
4772 if (!isa<Expr>(sub)) {
4773 unsupported(stmt);
4774 return NULL;
4777 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4779 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4782 /* Return a one-dimensional multi piecewise affine expression that is equal
4783 * to the constant 1 and is defined over a zero-dimensional domain.
4785 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
4787 isl_space *space;
4788 isl_local_space *ls;
4789 isl_aff *aff;
4791 space = isl_space_set_alloc(ctx, 0, 0);
4792 ls = isl_local_space_from_space(space);
4793 aff = isl_aff_zero_on_domain(ls);
4794 aff = isl_aff_set_constant_si(aff, 1);
4796 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4799 /* Construct a pet_scop for a continue statement.
4801 * We simply create an empty scop with a universal pet_skip_now
4802 * skip condition. This skip condition will then be taken into
4803 * account by the enclosing loop construct, possibly after
4804 * being incorporated into outer skip conditions.
4806 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4808 pet_scop *scop;
4810 scop = pet_scop_empty(ctx);
4811 if (!scop)
4812 return NULL;
4814 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
4816 return scop;
4819 /* Construct a pet_scop for a break statement.
4821 * We simply create an empty scop with both a universal pet_skip_now
4822 * skip condition and a universal pet_skip_later skip condition.
4823 * These skip conditions will then be taken into
4824 * account by the enclosing loop construct, possibly after
4825 * being incorporated into outer skip conditions.
4827 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4829 pet_scop *scop;
4830 isl_multi_pw_aff *skip;
4832 scop = pet_scop_empty(ctx);
4833 if (!scop)
4834 return NULL;
4836 skip = one_mpa(ctx);
4837 scop = pet_scop_set_skip(scop, pet_skip_now,
4838 isl_multi_pw_aff_copy(skip));
4839 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
4841 return scop;
4844 /* Try and construct a pet_scop corresponding to "stmt".
4846 * If "stmt" is a compound statement, then "skip_declarations"
4847 * indicates whether we should skip initial declarations in the
4848 * compound statement.
4850 * If the constructed pet_scop is not a (possibly) partial representation
4851 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4852 * In particular, if skip_declarations is set, then we may have skipped
4853 * declarations inside "stmt" and so the pet_scop may not represent
4854 * the entire "stmt".
4855 * Note that this function may be called with "stmt" referring to the entire
4856 * body of the function, including the outer braces. In such cases,
4857 * skip_declarations will be set and the braces will not be taken into
4858 * account in scop->start and scop->end.
4860 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
4862 struct pet_scop *scop;
4864 if (isa<Expr>(stmt))
4865 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4867 switch (stmt->getStmtClass()) {
4868 case Stmt::WhileStmtClass:
4869 scop = extract(cast<WhileStmt>(stmt));
4870 break;
4871 case Stmt::ForStmtClass:
4872 scop = extract_for(cast<ForStmt>(stmt));
4873 break;
4874 case Stmt::IfStmtClass:
4875 scop = extract(cast<IfStmt>(stmt));
4876 break;
4877 case Stmt::CompoundStmtClass:
4878 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
4879 break;
4880 case Stmt::LabelStmtClass:
4881 scop = extract(cast<LabelStmt>(stmt));
4882 break;
4883 case Stmt::ContinueStmtClass:
4884 scop = extract(cast<ContinueStmt>(stmt));
4885 break;
4886 case Stmt::BreakStmtClass:
4887 scop = extract(cast<BreakStmt>(stmt));
4888 break;
4889 case Stmt::DeclStmtClass:
4890 scop = extract(cast<DeclStmt>(stmt));
4891 break;
4892 default:
4893 unsupported(stmt);
4894 return NULL;
4897 if (partial || skip_declarations)
4898 return scop;
4900 scop = update_scop_start_end(scop, stmt->getSourceRange(), false);
4902 return scop;
4905 /* Do we need to construct a skip condition of the given type
4906 * on a sequence of statements?
4908 * There is no need to construct a new skip condition if only
4909 * only of the two statements has a skip condition or if both
4910 * of their skip conditions are affine.
4912 * In principle we also don't need a new continuation variable if
4913 * the continuation of scop2 is affine, but then we would need
4914 * to allow more complicated forms of continuations.
4916 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4917 enum pet_skip type)
4919 if (!scop1 || !pet_scop_has_skip(scop1, type))
4920 return false;
4921 if (!scop2 || !pet_scop_has_skip(scop2, type))
4922 return false;
4923 if (pet_scop_has_affine_skip(scop1, type) &&
4924 pet_scop_has_affine_skip(scop2, type))
4925 return false;
4926 return true;
4929 /* Construct a scop for computing the skip condition of the given type and
4930 * with index expression "skip_index" for a sequence of two scops "scop1"
4931 * and "scop2".
4933 * The computed scop contains a single statement that essentially does
4935 * skip_index = skip_cond_1 ? 1 : skip_cond_2
4937 * or, in other words, skip_cond1 || skip_cond2.
4938 * In this expression, skip_cond_2 is filtered to reflect that it is
4939 * only evaluated when skip_cond_1 is false.
4941 * The skip condition on scop1 is not removed because it still needs
4942 * to be applied to scop2 when these two scops are combined.
4944 static struct pet_scop *extract_skip_seq(PetScan *ps,
4945 __isl_take isl_multi_pw_aff *skip_index,
4946 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4948 struct pet_expr *expr1, *expr2, *expr, *expr_skip;
4949 struct pet_stmt *stmt;
4950 struct pet_scop *scop;
4951 isl_ctx *ctx = ps->ctx;
4953 if (!scop1 || !scop2)
4954 goto error;
4956 expr1 = pet_scop_get_skip_expr(scop1, type);
4957 expr2 = pet_scop_get_skip_expr(scop2, type);
4958 pet_scop_reset_skip(scop2, type);
4960 expr2 = pet_expr_filter(expr2,
4961 isl_multi_pw_aff_copy(expr1->acc.index), 0);
4963 expr = universally_true(ctx);
4964 expr = pet_expr_new_ternary(ctx, expr1, expr, expr2);
4965 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4966 if (expr_skip) {
4967 expr_skip->acc.write = 1;
4968 expr_skip->acc.read = 0;
4970 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4971 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, ps->n_stmt++, expr);
4973 scop = pet_scop_from_pet_stmt(ctx, stmt);
4974 scop = scop_add_array(scop, skip_index, ps->ast_context);
4975 isl_multi_pw_aff_free(skip_index);
4977 return scop;
4978 error:
4979 isl_multi_pw_aff_free(skip_index);
4980 return NULL;
4983 /* Structure that handles the construction of skip conditions
4984 * on sequences of statements.
4986 * scop1 and scop2 represent the two statements that are combined
4988 struct pet_skip_info_seq : public pet_skip_info {
4989 struct pet_scop *scop1, *scop2;
4991 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4992 struct pet_scop *scop2);
4993 void extract(PetScan *scan, enum pet_skip type);
4994 void extract(PetScan *scan);
4995 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4996 int offset);
4997 struct pet_scop *add(struct pet_scop *scop, int offset);
5000 /* Initialize a pet_skip_info_seq structure based on
5001 * on the two statements that are going to be combined.
5003 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
5004 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
5006 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
5007 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
5008 skip_equals_skip_later(scop2);
5009 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
5010 need_skip_seq(scop1, scop2, pet_skip_later);
5013 /* If we need to construct a skip condition of the given type,
5014 * then do so now.
5016 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
5018 if (!skip[type])
5019 return;
5021 index[type] = create_test_index(ctx, scan->n_test++);
5022 scop[type] = extract_skip_seq(scan, isl_multi_pw_aff_copy(index[type]),
5023 scop1, scop2, type);
5026 /* Construct the required skip conditions.
5028 void pet_skip_info_seq::extract(PetScan *scan)
5030 extract(scan, pet_skip_now);
5031 extract(scan, pet_skip_later);
5032 if (equal)
5033 drop_skip_later(scop1, scop2);
5036 /* Add the computed skip condition of the given type to "main" and
5037 * add the scop for computing the condition at the given offset (the statement
5038 * number). Within this offset, the condition is computed at position 1
5039 * to ensure that it is computed after the corresponding statement.
5041 * If equal is set, then we only computed a skip condition for pet_skip_now,
5042 * but we also need to set it as main's pet_skip_later.
5044 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
5045 enum pet_skip type, int offset)
5047 if (!skip[type])
5048 return main;
5050 scop[type] = pet_scop_prefix(scop[type], 1);
5051 scop[type] = pet_scop_prefix(scop[type], offset);
5052 main = pet_scop_add_par(ctx, main, scop[type]);
5053 scop[type] = NULL;
5055 if (equal)
5056 main = pet_scop_set_skip(main, pet_skip_later,
5057 isl_multi_pw_aff_copy(index[type]));
5059 main = pet_scop_set_skip(main, type, index[type]);
5060 index[type] = NULL;
5062 return main;
5065 /* Add the computed skip conditions to "main" and
5066 * add the scops for computing the conditions at the given offset.
5068 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
5070 scop = add(scop, pet_skip_now, offset);
5071 scop = add(scop, pet_skip_later, offset);
5073 return scop;
5076 /* Extract a clone of the kill statement in "scop".
5077 * "scop" is expected to have been created from a DeclStmt
5078 * and should have the kill as its first statement.
5080 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
5082 struct pet_expr *kill;
5083 struct pet_stmt *stmt;
5084 isl_multi_pw_aff *index;
5085 isl_map *access;
5087 if (!scop)
5088 return NULL;
5089 if (scop->n_stmt < 1)
5090 isl_die(ctx, isl_error_internal,
5091 "expecting at least one statement", return NULL);
5092 stmt = scop->stmts[0];
5093 if (!pet_stmt_is_kill(stmt))
5094 isl_die(ctx, isl_error_internal,
5095 "expecting kill statement", return NULL);
5097 index = isl_multi_pw_aff_copy(stmt->body->args[0]->acc.index);
5098 access = isl_map_copy(stmt->body->args[0]->acc.access);
5099 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
5100 access = isl_map_reset_tuple_id(access, isl_dim_in);
5101 kill = pet_expr_kill_from_access_and_index(access, index);
5102 return pet_stmt_from_pet_expr(ctx, stmt->line, NULL, n_stmt++, kill);
5105 /* Mark all arrays in "scop" as being exposed.
5107 static struct pet_scop *mark_exposed(struct pet_scop *scop)
5109 if (!scop)
5110 return NULL;
5111 for (int i = 0; i < scop->n_array; ++i)
5112 scop->arrays[i]->exposed = 1;
5113 return scop;
5116 /* Try and construct a pet_scop corresponding to (part of)
5117 * a sequence of statements.
5119 * "block" is set if the sequence respresents the children of
5120 * a compound statement.
5121 * "skip_declarations" is set if we should skip initial declarations
5122 * in the sequence of statements.
5124 * If there are any breaks or continues in the individual statements,
5125 * then we may have to compute a new skip condition.
5126 * This is handled using a pet_skip_info_seq object.
5127 * On initialization, the object checks if skip conditions need
5128 * to be computed. If so, it does so in "extract" and adds them in "add".
5130 * If "block" is set, then we need to insert kill statements at
5131 * the end of the block for any array that has been declared by
5132 * one of the statements in the sequence. Each of these declarations
5133 * results in the construction of a kill statement at the place
5134 * of the declaration, so we simply collect duplicates of
5135 * those kill statements and append these duplicates to the constructed scop.
5137 * If "block" is not set, then any array declared by one of the statements
5138 * in the sequence is marked as being exposed.
5140 * If autodetect is set, then we allow the extraction of only a subrange
5141 * of the sequence of statements. However, if there is at least one statement
5142 * for which we could not construct a scop and the final range contains
5143 * either no statements or at least one kill, then we discard the entire
5144 * range.
5146 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
5147 bool skip_declarations)
5149 pet_scop *scop;
5150 StmtIterator i;
5151 int j;
5152 bool partial_range = false;
5153 set<struct pet_stmt *> kills;
5154 set<struct pet_stmt *>::iterator it;
5156 scop = pet_scop_empty(ctx);
5157 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
5158 Stmt *child = *i;
5159 struct pet_scop *scop_i;
5161 if (scop->n_stmt == 0 && skip_declarations &&
5162 child->getStmtClass() == Stmt::DeclStmtClass)
5163 continue;
5165 scop_i = extract(child);
5166 if (scop->n_stmt != 0 && partial) {
5167 pet_scop_free(scop_i);
5168 break;
5170 pet_skip_info_seq skip(ctx, scop, scop_i);
5171 skip.extract(this);
5172 if (skip)
5173 scop_i = pet_scop_prefix(scop_i, 0);
5174 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
5175 if (block)
5176 kills.insert(extract_kill(scop_i));
5177 else
5178 scop_i = mark_exposed(scop_i);
5180 scop_i = pet_scop_prefix(scop_i, j);
5181 if (options->autodetect) {
5182 if (scop_i)
5183 scop = pet_scop_add_seq(ctx, scop, scop_i);
5184 else
5185 partial_range = true;
5186 if (scop->n_stmt != 0 && !scop_i)
5187 partial = true;
5188 } else {
5189 scop = pet_scop_add_seq(ctx, scop, scop_i);
5192 scop = skip.add(scop, j);
5194 if (partial || !scop)
5195 break;
5198 for (it = kills.begin(); it != kills.end(); ++it) {
5199 pet_scop *scop_j;
5200 scop_j = pet_scop_from_pet_stmt(ctx, *it);
5201 scop_j = pet_scop_prefix(scop_j, j);
5202 scop = pet_scop_add_seq(ctx, scop, scop_j);
5205 if (scop && partial_range) {
5206 if (scop->n_stmt == 0 || kills.size() != 0) {
5207 pet_scop_free(scop);
5208 return NULL;
5210 partial = true;
5213 return scop;
5216 /* Check if the scop marked by the user is exactly this Stmt
5217 * or part of this Stmt.
5218 * If so, return a pet_scop corresponding to the marked region.
5219 * Otherwise, return NULL.
5221 struct pet_scop *PetScan::scan(Stmt *stmt)
5223 SourceManager &SM = PP.getSourceManager();
5224 unsigned start_off, end_off;
5226 start_off = getExpansionOffset(SM, stmt->getLocStart());
5227 end_off = getExpansionOffset(SM, stmt->getLocEnd());
5229 if (start_off > loc.end)
5230 return NULL;
5231 if (end_off < loc.start)
5232 return NULL;
5233 if (start_off >= loc.start && end_off <= loc.end) {
5234 return extract(stmt);
5237 StmtIterator start;
5238 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
5239 Stmt *child = *start;
5240 if (!child)
5241 continue;
5242 start_off = getExpansionOffset(SM, child->getLocStart());
5243 end_off = getExpansionOffset(SM, child->getLocEnd());
5244 if (start_off < loc.start && end_off >= loc.end)
5245 return scan(child);
5246 if (start_off >= loc.start)
5247 break;
5250 StmtIterator end;
5251 for (end = start; end != stmt->child_end(); ++end) {
5252 Stmt *child = *end;
5253 start_off = SM.getFileOffset(child->getLocStart());
5254 if (start_off >= loc.end)
5255 break;
5258 return extract(StmtRange(start, end), false, false);
5261 /* Set the size of index "pos" of "array" to "size".
5262 * In particular, add a constraint of the form
5264 * i_pos < size
5266 * to array->extent and a constraint of the form
5268 * size >= 0
5270 * to array->context.
5272 static struct pet_array *update_size(struct pet_array *array, int pos,
5273 __isl_take isl_pw_aff *size)
5275 isl_set *valid;
5276 isl_set *univ;
5277 isl_set *bound;
5278 isl_space *dim;
5279 isl_aff *aff;
5280 isl_pw_aff *index;
5281 isl_id *id;
5283 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
5284 array->context = isl_set_intersect(array->context, valid);
5286 dim = isl_set_get_space(array->extent);
5287 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
5288 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
5289 univ = isl_set_universe(isl_aff_get_domain_space(aff));
5290 index = isl_pw_aff_alloc(univ, aff);
5292 size = isl_pw_aff_add_dims(size, isl_dim_in,
5293 isl_set_dim(array->extent, isl_dim_set));
5294 id = isl_set_get_tuple_id(array->extent);
5295 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
5296 bound = isl_pw_aff_lt_set(index, size);
5298 array->extent = isl_set_intersect(array->extent, bound);
5300 if (!array->context || !array->extent)
5301 goto error;
5303 return array;
5304 error:
5305 pet_array_free(array);
5306 return NULL;
5309 /* Figure out the size of the array at position "pos" and all
5310 * subsequent positions from "type" and update "array" accordingly.
5312 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
5313 const Type *type, int pos)
5315 const ArrayType *atype;
5316 isl_pw_aff *size;
5318 if (!array)
5319 return NULL;
5321 if (type->isPointerType()) {
5322 type = type->getPointeeType().getTypePtr();
5323 return set_upper_bounds(array, type, pos + 1);
5325 if (!type->isArrayType())
5326 return array;
5328 type = type->getCanonicalTypeInternal().getTypePtr();
5329 atype = cast<ArrayType>(type);
5331 if (type->isConstantArrayType()) {
5332 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
5333 size = extract_affine(ca->getSize());
5334 array = update_size(array, pos, size);
5335 } else if (type->isVariableArrayType()) {
5336 const VariableArrayType *vla = cast<VariableArrayType>(atype);
5337 size = extract_affine(vla->getSizeExpr());
5338 array = update_size(array, pos, size);
5341 type = atype->getElementType().getTypePtr();
5343 return set_upper_bounds(array, type, pos + 1);
5346 /* Is "T" the type of a variable length array with static size?
5348 static bool is_vla_with_static_size(QualType T)
5350 const VariableArrayType *vlatype;
5352 if (!T->isVariableArrayType())
5353 return false;
5354 vlatype = cast<VariableArrayType>(T);
5355 return vlatype->getSizeModifier() == VariableArrayType::Static;
5358 /* Return the type of "decl" as an array.
5360 * In particular, if "decl" is a parameter declaration that
5361 * is a variable length array with a static size, then
5362 * return the original type (i.e., the variable length array).
5363 * Otherwise, return the type of decl.
5365 static QualType get_array_type(ValueDecl *decl)
5367 ParmVarDecl *parm;
5368 QualType T;
5370 parm = dyn_cast<ParmVarDecl>(decl);
5371 if (!parm)
5372 return decl->getType();
5374 T = parm->getOriginalType();
5375 if (!is_vla_with_static_size(T))
5376 return decl->getType();
5377 return T;
5380 /* Does "decl" have definition that we can keep track of in a pet_type?
5382 static bool has_printable_definition(RecordDecl *decl)
5384 if (!decl->getDeclName())
5385 return false;
5386 return decl->getLexicalDeclContext() == decl->getDeclContext();
5389 /* Construct and return a pet_array corresponding to the variable "decl".
5390 * In particular, initialize array->extent to
5392 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
5394 * and then call set_upper_bounds to set the upper bounds on the indices
5395 * based on the type of the variable.
5397 * If the base type is that of a record with a top-level definition and
5398 * if "types" is not null, then the RecordDecl corresponding to the type
5399 * is added to "types".
5401 * If the base type is that of a record with no top-level definition,
5402 * then we replace it by "<subfield>".
5404 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
5405 lex_recorddecl_set *types)
5407 struct pet_array *array;
5408 QualType qt = get_array_type(decl);
5409 const Type *type = qt.getTypePtr();
5410 int depth = array_depth(type);
5411 QualType base = pet_clang_base_type(qt);
5412 string name;
5413 isl_id *id;
5414 isl_space *dim;
5416 array = isl_calloc_type(ctx, struct pet_array);
5417 if (!array)
5418 return NULL;
5420 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
5421 dim = isl_space_set_alloc(ctx, 0, depth);
5422 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
5424 array->extent = isl_set_nat_universe(dim);
5426 dim = isl_space_params_alloc(ctx, 0);
5427 array->context = isl_set_universe(dim);
5429 array = set_upper_bounds(array, type, 0);
5430 if (!array)
5431 return NULL;
5433 name = base.getAsString();
5435 if (types && base->isRecordType()) {
5436 RecordDecl *decl = pet_clang_record_decl(base);
5437 if (has_printable_definition(decl))
5438 types->insert(decl);
5439 else
5440 name = "<subfield>";
5443 array->element_type = strdup(name.c_str());
5444 array->element_is_record = base->isRecordType();
5445 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
5447 return array;
5450 /* Construct and return a pet_array corresponding to the sequence
5451 * of declarations "decls".
5452 * If the sequence contains a single declaration, then it corresponds
5453 * to a simple array access. Otherwise, it corresponds to a member access,
5454 * with the declaration for the substructure following that of the containing
5455 * structure in the sequence of declarations.
5456 * We start with the outermost substructure and then combine it with
5457 * information from the inner structures.
5459 * Additionally, keep track of all required types in "types".
5461 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
5462 vector<ValueDecl *> decls, lex_recorddecl_set *types)
5464 struct pet_array *array;
5465 vector<ValueDecl *>::iterator it;
5467 it = decls.begin();
5469 array = extract_array(ctx, *it, types);
5471 for (++it; it != decls.end(); ++it) {
5472 struct pet_array *parent;
5473 const char *base_name, *field_name;
5474 char *product_name;
5476 parent = array;
5477 array = extract_array(ctx, *it, types);
5478 if (!array)
5479 return pet_array_free(parent);
5481 base_name = isl_set_get_tuple_name(parent->extent);
5482 field_name = isl_set_get_tuple_name(array->extent);
5483 product_name = member_access_name(ctx, base_name, field_name);
5485 array->extent = isl_set_product(isl_set_copy(parent->extent),
5486 array->extent);
5487 if (product_name)
5488 array->extent = isl_set_set_tuple_name(array->extent,
5489 product_name);
5490 array->context = isl_set_intersect(array->context,
5491 isl_set_copy(parent->context));
5493 pet_array_free(parent);
5494 free(product_name);
5496 if (!array->extent || !array->context || !product_name)
5497 return pet_array_free(array);
5500 return array;
5503 /* Add a pet_type corresponding to "decl" to "scop, provided
5504 * it is a member of "types" and it has not been added before
5505 * (i.e., it is not a member of "types_done".
5507 * Since we want the user to be able to print the types
5508 * in the order in which they appear in the scop, we need to
5509 * make sure that types of fields in a structure appear before
5510 * that structure. We therefore call ourselves recursively
5511 * on the types of all record subfields.
5513 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
5514 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
5515 lex_recorddecl_set &types_done)
5517 string s;
5518 llvm::raw_string_ostream S(s);
5519 RecordDecl::field_iterator it;
5521 if (types.find(decl) == types.end())
5522 return scop;
5523 if (types_done.find(decl) != types_done.end())
5524 return scop;
5526 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
5527 RecordDecl *record;
5528 QualType type = it->getType();
5530 if (!type->isRecordType())
5531 continue;
5532 record = pet_clang_record_decl(type);
5533 scop = add_type(ctx, scop, record, PP, types, types_done);
5536 if (strlen(decl->getName().str().c_str()) == 0)
5537 return scop;
5539 decl->print(S, PrintingPolicy(PP.getLangOpts()));
5540 S.str();
5542 scop->types[scop->n_type] = pet_type_alloc(ctx,
5543 decl->getName().str().c_str(), s.c_str());
5544 if (!scop->types[scop->n_type])
5545 return pet_scop_free(scop);
5547 types_done.insert(decl);
5549 scop->n_type++;
5551 return scop;
5554 /* Construct a list of pet_arrays, one for each array (or scalar)
5555 * accessed inside "scop", add this list to "scop" and return the result.
5557 * The context of "scop" is updated with the intersection of
5558 * the contexts of all arrays, i.e., constraints on the parameters
5559 * that ensure that the arrays have a valid (non-negative) size.
5561 * If the any of the extracted arrays refers to a member access,
5562 * then also add the required types to "scop".
5564 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
5566 int i;
5567 set<vector<ValueDecl *> > arrays;
5568 set<vector<ValueDecl *> >::iterator it;
5569 lex_recorddecl_set types;
5570 lex_recorddecl_set types_done;
5571 lex_recorddecl_set::iterator types_it;
5572 int n_array;
5573 struct pet_array **scop_arrays;
5575 if (!scop)
5576 return NULL;
5578 pet_scop_collect_arrays(scop, arrays);
5579 if (arrays.size() == 0)
5580 return scop;
5582 n_array = scop->n_array;
5584 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
5585 n_array + arrays.size());
5586 if (!scop_arrays)
5587 goto error;
5588 scop->arrays = scop_arrays;
5590 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
5591 struct pet_array *array;
5592 array = extract_array(ctx, *it, &types);
5593 scop->arrays[n_array + i] = array;
5594 if (!scop->arrays[n_array + i])
5595 goto error;
5596 scop->n_array++;
5597 scop->context = isl_set_intersect(scop->context,
5598 isl_set_copy(array->context));
5599 if (!scop->context)
5600 goto error;
5603 if (types.size() == 0)
5604 return scop;
5606 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
5607 if (!scop->types)
5608 goto error;
5610 for (types_it = types.begin(); types_it != types.end(); ++types_it)
5611 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
5613 return scop;
5614 error:
5615 pet_scop_free(scop);
5616 return NULL;
5619 /* Bound all parameters in scop->context to the possible values
5620 * of the corresponding C variable.
5622 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
5624 int n;
5626 if (!scop)
5627 return NULL;
5629 n = isl_set_dim(scop->context, isl_dim_param);
5630 for (int i = 0; i < n; ++i) {
5631 isl_id *id;
5632 ValueDecl *decl;
5634 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
5635 if (is_nested_parameter(id)) {
5636 isl_id_free(id);
5637 isl_die(isl_set_get_ctx(scop->context),
5638 isl_error_internal,
5639 "unresolved nested parameter", goto error);
5641 decl = (ValueDecl *) isl_id_get_user(id);
5642 isl_id_free(id);
5644 scop->context = set_parameter_bounds(scop->context, i, decl);
5646 if (!scop->context)
5647 goto error;
5650 return scop;
5651 error:
5652 pet_scop_free(scop);
5653 return NULL;
5656 /* Construct a pet_scop from the given function.
5658 * If the scop was delimited by scop and endscop pragmas, then we override
5659 * the file offsets by those derived from the pragmas.
5661 struct pet_scop *PetScan::scan(FunctionDecl *fd)
5663 pet_scop *scop;
5664 Stmt *stmt;
5666 stmt = fd->getBody();
5668 if (options->autodetect)
5669 scop = extract(stmt, true);
5670 else {
5671 scop = scan(stmt);
5672 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
5674 scop = pet_scop_detect_parameter_accesses(scop);
5675 scop = scan_arrays(scop);
5676 scop = add_parameter_bounds(scop);
5677 scop = pet_scop_gist(scop, value_bounds);
5679 return scop;