export pet_expr_foreach_access_expr
[pet.git] / scan.cc
blobdb494c00e565820b143ae65e6391366e74d0a3d8
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 "expr.h"
52 #include "options.h"
53 #include "scan.h"
54 #include "scop.h"
55 #include "scop_plus.h"
57 #include "config.h"
59 using namespace std;
60 using namespace clang;
62 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
63 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
65 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
66 SourceLocation(), var, false, var->getInnerLocStart(),
67 var->getType(), VK_LValue);
69 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
70 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
72 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
73 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
74 VK_LValue);
76 #else
77 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
79 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
80 var, var->getInnerLocStart(), var->getType(), VK_LValue);
82 #endif
84 /* Check if the element type corresponding to the given array type
85 * has a const qualifier.
87 static bool const_base(QualType qt)
89 const Type *type = qt.getTypePtr();
91 if (type->isPointerType())
92 return const_base(type->getPointeeType());
93 if (type->isArrayType()) {
94 const ArrayType *atype;
95 type = type->getCanonicalTypeInternal().getTypePtr();
96 atype = cast<ArrayType>(type);
97 return const_base(atype->getElementType());
100 return qt.isConstQualified();
103 /* Mark "decl" as having an unknown value in "assigned_value".
105 * If no (known or unknown) value was assigned to "decl" before,
106 * then it may have been treated as a parameter before and may
107 * therefore appear in a value assigned to another variable.
108 * If so, this assignment needs to be turned into an unknown value too.
110 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
111 ValueDecl *decl)
113 map<ValueDecl *, isl_pw_aff *>::iterator it;
115 it = assigned_value.find(decl);
117 assigned_value[decl] = NULL;
119 if (it != assigned_value.end())
120 return;
122 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
123 isl_pw_aff *pa = it->second;
124 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
126 for (int i = 0; i < nparam; ++i) {
127 isl_id *id;
129 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
130 continue;
131 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
132 if (isl_id_get_user(id) == decl)
133 it->second = NULL;
134 isl_id_free(id);
139 /* Look for any assignments to scalar variables in part of the parse
140 * tree and set assigned_value to NULL for each of them.
141 * Also reset assigned_value if the address of a scalar variable
142 * is being taken. As an exception, if the address is passed to a function
143 * that is declared to receive a const pointer, then assigned_value is
144 * not reset.
146 * This ensures that we won't use any previously stored value
147 * in the current subtree and its parents.
149 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
150 map<ValueDecl *, isl_pw_aff *> &assigned_value;
151 set<UnaryOperator *> skip;
153 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
154 assigned_value(assigned_value) {}
156 /* Check for "address of" operators whose value is passed
157 * to a const pointer argument and add them to "skip", so that
158 * we can skip them in VisitUnaryOperator.
160 bool VisitCallExpr(CallExpr *expr) {
161 FunctionDecl *fd;
162 fd = expr->getDirectCallee();
163 if (!fd)
164 return true;
165 for (int i = 0; i < expr->getNumArgs(); ++i) {
166 Expr *arg = expr->getArg(i);
167 UnaryOperator *op;
168 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
169 ImplicitCastExpr *ice;
170 ice = cast<ImplicitCastExpr>(arg);
171 arg = ice->getSubExpr();
173 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
174 continue;
175 op = cast<UnaryOperator>(arg);
176 if (op->getOpcode() != UO_AddrOf)
177 continue;
178 if (const_base(fd->getParamDecl(i)->getType()))
179 skip.insert(op);
181 return true;
184 bool VisitUnaryOperator(UnaryOperator *expr) {
185 Expr *arg;
186 DeclRefExpr *ref;
187 ValueDecl *decl;
189 switch (expr->getOpcode()) {
190 case UO_AddrOf:
191 case UO_PostInc:
192 case UO_PostDec:
193 case UO_PreInc:
194 case UO_PreDec:
195 break;
196 default:
197 return true;
199 if (skip.find(expr) != skip.end())
200 return true;
202 arg = expr->getSubExpr();
203 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
204 return true;
205 ref = cast<DeclRefExpr>(arg);
206 decl = ref->getDecl();
207 clear_assignment(assigned_value, decl);
208 return true;
211 bool VisitBinaryOperator(BinaryOperator *expr) {
212 Expr *lhs;
213 DeclRefExpr *ref;
214 ValueDecl *decl;
216 if (!expr->isAssignmentOp())
217 return true;
218 lhs = expr->getLHS();
219 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
220 return true;
221 ref = cast<DeclRefExpr>(lhs);
222 decl = ref->getDecl();
223 clear_assignment(assigned_value, decl);
224 return true;
228 /* Keep a copy of the currently assigned values.
230 * Any variable that is assigned a value inside the current scope
231 * is removed again when we leave the scope (either because it wasn't
232 * stored in the cache or because it has a different value in the cache).
234 struct assigned_value_cache {
235 map<ValueDecl *, isl_pw_aff *> &assigned_value;
236 map<ValueDecl *, isl_pw_aff *> cache;
238 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
239 assigned_value(assigned_value), cache(assigned_value) {}
240 ~assigned_value_cache() {
241 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
242 for (it = assigned_value.begin(); it != assigned_value.end();
243 ++it) {
244 if (!it->second ||
245 (cache.find(it->first) != cache.end() &&
246 cache[it->first] != it->second))
247 cache[it->first] = NULL;
249 assigned_value = cache;
253 /* Insert an expression into the collection of expressions,
254 * provided it is not already in there.
255 * The isl_pw_affs are freed in the destructor.
257 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
259 std::set<isl_pw_aff *>::iterator it;
261 if (expressions.find(expr) == expressions.end())
262 expressions.insert(expr);
263 else
264 isl_pw_aff_free(expr);
267 PetScan::~PetScan()
269 std::set<isl_pw_aff *>::iterator it;
271 for (it = expressions.begin(); it != expressions.end(); ++it)
272 isl_pw_aff_free(*it);
274 isl_union_map_free(value_bounds);
277 /* Report a diagnostic, unless autodetect is set.
279 void PetScan::report(Stmt *stmt, unsigned id)
281 if (options->autodetect)
282 return;
284 SourceLocation loc = stmt->getLocStart();
285 DiagnosticsEngine &diag = PP.getDiagnostics();
286 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
289 /* Called if we found something we (currently) cannot handle.
290 * We'll provide more informative warnings later.
292 * We only actually complain if autodetect is false.
294 void PetScan::unsupported(Stmt *stmt)
296 DiagnosticsEngine &diag = PP.getDiagnostics();
297 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
298 "unsupported");
299 report(stmt, id);
302 /* Report a missing prototype, unless autodetect is set.
304 void PetScan::report_prototype_required(Stmt *stmt)
306 DiagnosticsEngine &diag = PP.getDiagnostics();
307 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
308 "prototype required");
309 report(stmt, id);
312 /* Report a missing increment, unless autodetect is set.
314 void PetScan::report_missing_increment(Stmt *stmt)
316 DiagnosticsEngine &diag = PP.getDiagnostics();
317 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
318 "missing increment");
319 report(stmt, id);
322 /* Extract an integer from "expr".
324 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
326 const Type *type = expr->getType().getTypePtr();
327 int is_signed = type->hasSignedIntegerRepresentation();
328 llvm::APInt val = expr->getValue();
329 int is_negative = is_signed && val.isNegative();
330 isl_val *v;
332 if (is_negative)
333 val = -val;
335 v = extract_unsigned(ctx, val);
337 if (is_negative)
338 v = isl_val_neg(v);
339 return v;
342 /* Extract an integer from "val", which is assumed to be non-negative.
344 __isl_give isl_val *PetScan::extract_unsigned(isl_ctx *ctx,
345 const llvm::APInt &val)
347 unsigned n;
348 const uint64_t *data;
350 data = val.getRawData();
351 n = val.getNumWords();
352 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
355 /* Extract an integer from "expr".
356 * Return NULL if "expr" does not (obviously) represent an integer.
358 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
360 return extract_int(expr->getSubExpr());
363 /* Extract an integer from "expr".
364 * Return NULL if "expr" does not (obviously) represent an integer.
366 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
368 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
369 return extract_int(ctx, cast<IntegerLiteral>(expr));
370 if (expr->getStmtClass() == Stmt::ParenExprClass)
371 return extract_int(cast<ParenExpr>(expr));
373 unsupported(expr);
374 return NULL;
377 /* Extract an affine expression from the IntegerLiteral "expr".
379 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
381 isl_space *dim = isl_space_params_alloc(ctx, 0);
382 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
383 isl_aff *aff = isl_aff_zero_on_domain(ls);
384 isl_set *dom = isl_set_universe(dim);
385 isl_val *v;
387 v = extract_int(expr);
388 aff = isl_aff_add_constant_val(aff, v);
390 return isl_pw_aff_alloc(dom, aff);
393 /* Extract an affine expression from the APInt "val", which is assumed
394 * to be non-negative.
396 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
398 isl_space *dim = isl_space_params_alloc(ctx, 0);
399 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
400 isl_aff *aff = isl_aff_zero_on_domain(ls);
401 isl_set *dom = isl_set_universe(dim);
402 isl_val *v;
404 v = extract_unsigned(ctx, val);
405 aff = isl_aff_add_constant_val(aff, v);
407 return isl_pw_aff_alloc(dom, aff);
410 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
412 return extract_affine(expr->getSubExpr());
415 static unsigned get_type_size(ValueDecl *decl)
417 return decl->getASTContext().getIntWidth(decl->getType());
420 /* Bound parameter "pos" of "set" to the possible values of "decl".
422 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
423 unsigned pos, ValueDecl *decl)
425 unsigned width;
426 isl_ctx *ctx;
427 isl_val *bound;
429 ctx = isl_set_get_ctx(set);
430 width = get_type_size(decl);
431 if (decl->getType()->isUnsignedIntegerType()) {
432 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
433 bound = isl_val_int_from_ui(ctx, width);
434 bound = isl_val_2exp(bound);
435 bound = isl_val_sub_ui(bound, 1);
436 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
437 } else {
438 bound = isl_val_int_from_ui(ctx, width - 1);
439 bound = isl_val_2exp(bound);
440 bound = isl_val_sub_ui(bound, 1);
441 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
442 isl_val_copy(bound));
443 bound = isl_val_neg(bound);
444 bound = isl_val_sub_ui(bound, 1);
445 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
448 return set;
451 /* Extract an affine expression from the DeclRefExpr "expr".
453 * If the variable has been assigned a value, then we check whether
454 * we know what (affine) value was assigned.
455 * If so, we return this value. Otherwise we convert "expr"
456 * to an extra parameter (provided nesting_enabled is set).
458 * Otherwise, we simply return an expression that is equal
459 * to a parameter corresponding to the referenced variable.
461 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
463 ValueDecl *decl = expr->getDecl();
464 const Type *type = decl->getType().getTypePtr();
465 isl_id *id;
466 isl_space *dim;
467 isl_aff *aff;
468 isl_set *dom;
470 if (!type->isIntegerType()) {
471 unsupported(expr);
472 return NULL;
475 if (assigned_value.find(decl) != assigned_value.end()) {
476 if (assigned_value[decl])
477 return isl_pw_aff_copy(assigned_value[decl]);
478 else
479 return nested_access(expr);
482 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
483 dim = isl_space_params_alloc(ctx, 1);
485 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
487 dom = isl_set_universe(isl_space_copy(dim));
488 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
489 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
491 return isl_pw_aff_alloc(dom, aff);
494 /* Extract an affine expression from an integer division operation.
495 * In particular, if "expr" is lhs/rhs, then return
497 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
499 * The second argument (rhs) is required to be a (positive) integer constant.
501 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
503 int is_cst;
504 isl_pw_aff *rhs, *lhs;
506 rhs = extract_affine(expr->getRHS());
507 is_cst = isl_pw_aff_is_cst(rhs);
508 if (is_cst < 0 || !is_cst) {
509 isl_pw_aff_free(rhs);
510 if (!is_cst)
511 unsupported(expr);
512 return NULL;
515 lhs = extract_affine(expr->getLHS());
517 return isl_pw_aff_tdiv_q(lhs, rhs);
520 /* Extract an affine expression from a modulo operation.
521 * In particular, if "expr" is lhs/rhs, then return
523 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
525 * The second argument (rhs) is required to be a (positive) integer constant.
527 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
529 int is_cst;
530 isl_pw_aff *rhs, *lhs;
532 rhs = extract_affine(expr->getRHS());
533 is_cst = isl_pw_aff_is_cst(rhs);
534 if (is_cst < 0 || !is_cst) {
535 isl_pw_aff_free(rhs);
536 if (!is_cst)
537 unsupported(expr);
538 return NULL;
541 lhs = extract_affine(expr->getLHS());
543 return isl_pw_aff_tdiv_r(lhs, rhs);
546 /* Extract an affine expression from a multiplication operation.
547 * This is only allowed if at least one of the two arguments
548 * is a (piecewise) constant.
550 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
552 isl_pw_aff *lhs;
553 isl_pw_aff *rhs;
555 lhs = extract_affine(expr->getLHS());
556 rhs = extract_affine(expr->getRHS());
558 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
559 isl_pw_aff_free(lhs);
560 isl_pw_aff_free(rhs);
561 unsupported(expr);
562 return NULL;
565 return isl_pw_aff_mul(lhs, rhs);
568 /* Extract an affine expression from an addition or subtraction operation.
570 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
572 isl_pw_aff *lhs;
573 isl_pw_aff *rhs;
575 lhs = extract_affine(expr->getLHS());
576 rhs = extract_affine(expr->getRHS());
578 switch (expr->getOpcode()) {
579 case BO_Add:
580 return isl_pw_aff_add(lhs, rhs);
581 case BO_Sub:
582 return isl_pw_aff_sub(lhs, rhs);
583 default:
584 isl_pw_aff_free(lhs);
585 isl_pw_aff_free(rhs);
586 return NULL;
591 /* Compute
593 * pwaff mod 2^width
595 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
596 unsigned width)
598 isl_ctx *ctx;
599 isl_val *mod;
601 ctx = isl_pw_aff_get_ctx(pwaff);
602 mod = isl_val_int_from_ui(ctx, width);
603 mod = isl_val_2exp(mod);
605 pwaff = isl_pw_aff_mod_val(pwaff, mod);
607 return pwaff;
610 /* Limit the domain of "pwaff" to those elements where the function
611 * value satisfies
613 * 2^{width-1} <= pwaff < 2^{width-1}
615 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
616 unsigned width)
618 isl_ctx *ctx;
619 isl_val *v;
620 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
621 isl_local_space *ls = isl_local_space_from_space(space);
622 isl_aff *bound;
623 isl_set *dom;
624 isl_pw_aff *b;
626 ctx = isl_pw_aff_get_ctx(pwaff);
627 v = isl_val_int_from_ui(ctx, width - 1);
628 v = isl_val_2exp(v);
630 bound = isl_aff_zero_on_domain(ls);
631 bound = isl_aff_add_constant_val(bound, v);
632 b = isl_pw_aff_from_aff(bound);
634 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
635 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
637 b = isl_pw_aff_neg(b);
638 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
639 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
641 return pwaff;
644 /* Handle potential overflows on signed computations.
646 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
647 * the we adjust the domain of "pa" to avoid overflows.
649 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
650 unsigned width)
652 if (options->signed_overflow == PET_OVERFLOW_AVOID)
653 pa = avoid_overflow(pa, width);
655 return pa;
658 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
660 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
661 __isl_take isl_set *dom)
663 isl_pw_aff *pa;
664 pa = isl_set_indicator_function(set);
665 pa = isl_pw_aff_intersect_domain(pa, isl_set_coalesce(dom));
666 return pa;
669 /* Extract an affine expression from some binary operations.
670 * If the result of the expression is unsigned, then we wrap it
671 * based on the size of the type. Otherwise, we ensure that
672 * no overflow occurs.
674 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
676 isl_pw_aff *res;
677 unsigned width;
679 switch (expr->getOpcode()) {
680 case BO_Add:
681 case BO_Sub:
682 res = extract_affine_add(expr);
683 break;
684 case BO_Div:
685 res = extract_affine_div(expr);
686 break;
687 case BO_Rem:
688 res = extract_affine_mod(expr);
689 break;
690 case BO_Mul:
691 res = extract_affine_mul(expr);
692 break;
693 case BO_LT:
694 case BO_LE:
695 case BO_GT:
696 case BO_GE:
697 case BO_EQ:
698 case BO_NE:
699 case BO_LAnd:
700 case BO_LOr:
701 return extract_condition(expr);
702 default:
703 unsupported(expr);
704 return NULL;
707 width = ast_context.getIntWidth(expr->getType());
708 if (expr->getType()->isUnsignedIntegerType())
709 res = wrap(res, width);
710 else
711 res = signed_overflow(res, width);
713 return res;
716 /* Extract an affine expression from a negation operation.
718 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
720 if (expr->getOpcode() == UO_Minus)
721 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
722 if (expr->getOpcode() == UO_LNot)
723 return extract_condition(expr);
725 unsupported(expr);
726 return NULL;
729 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
731 return extract_affine(expr->getSubExpr());
734 /* Extract an affine expression from some special function calls.
735 * In particular, we handle "min", "max", "ceild", "floord",
736 * "intMod", "intFloor" and "intCeil".
737 * In case of the latter five, the second argument needs to be
738 * a (positive) integer constant.
740 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
742 FunctionDecl *fd;
743 string name;
744 isl_pw_aff *aff1, *aff2;
746 fd = expr->getDirectCallee();
747 if (!fd) {
748 unsupported(expr);
749 return NULL;
752 name = fd->getDeclName().getAsString();
753 if (!(expr->getNumArgs() == 2 && name == "min") &&
754 !(expr->getNumArgs() == 2 && name == "max") &&
755 !(expr->getNumArgs() == 2 && name == "intMod") &&
756 !(expr->getNumArgs() == 2 && name == "intFloor") &&
757 !(expr->getNumArgs() == 2 && name == "intCeil") &&
758 !(expr->getNumArgs() == 2 && name == "floord") &&
759 !(expr->getNumArgs() == 2 && name == "ceild")) {
760 unsupported(expr);
761 return NULL;
764 if (name == "min" || name == "max") {
765 aff1 = extract_affine(expr->getArg(0));
766 aff2 = extract_affine(expr->getArg(1));
768 if (name == "min")
769 aff1 = isl_pw_aff_min(aff1, aff2);
770 else
771 aff1 = isl_pw_aff_max(aff1, aff2);
772 } else if (name == "intMod") {
773 isl_val *v;
774 Expr *arg2 = expr->getArg(1);
776 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
777 unsupported(expr);
778 return NULL;
780 aff1 = extract_affine(expr->getArg(0));
781 v = extract_int(cast<IntegerLiteral>(arg2));
782 aff1 = isl_pw_aff_mod_val(aff1, v);
783 } else if (name == "floord" || name == "ceild" ||
784 name == "intFloor" || name == "intCeil") {
785 isl_val *v;
786 Expr *arg2 = expr->getArg(1);
788 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
789 unsupported(expr);
790 return NULL;
792 aff1 = extract_affine(expr->getArg(0));
793 v = extract_int(cast<IntegerLiteral>(arg2));
794 aff1 = isl_pw_aff_scale_down_val(aff1, v);
795 if (name == "floord" || name == "intFloor")
796 aff1 = isl_pw_aff_floor(aff1);
797 else
798 aff1 = isl_pw_aff_ceil(aff1);
799 } else {
800 unsupported(expr);
801 return NULL;
804 return aff1;
807 /* This method is called when we come across an access that is
808 * nested in what is supposed to be an affine expression.
809 * If nesting is allowed, we return a new parameter that corresponds
810 * to this nested access. Otherwise, we simply complain.
812 * Note that we currently don't allow nested accesses themselves
813 * to contain any nested accesses, so we check if we can extract
814 * the access without any nesting and complain if we can't.
816 * The new parameter is resolved in resolve_nested.
818 isl_pw_aff *PetScan::nested_access(Expr *expr)
820 isl_id *id;
821 isl_space *dim;
822 isl_aff *aff;
823 isl_set *dom;
824 isl_multi_pw_aff *index;
826 if (!nesting_enabled) {
827 unsupported(expr);
828 return NULL;
831 allow_nested = false;
832 index = extract_index(expr);
833 allow_nested = true;
834 if (!index) {
835 unsupported(expr);
836 return NULL;
838 isl_multi_pw_aff_free(index);
840 id = isl_id_alloc(ctx, NULL, expr);
841 dim = isl_space_params_alloc(ctx, 1);
843 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
845 dom = isl_set_universe(isl_space_copy(dim));
846 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
847 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
849 return isl_pw_aff_alloc(dom, aff);
852 /* Affine expressions are not supposed to contain array accesses,
853 * but if nesting is allowed, we return a parameter corresponding
854 * to the array access.
856 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
858 return nested_access(expr);
861 /* Affine expressions are not supposed to contain member accesses,
862 * but if nesting is allowed, we return a parameter corresponding
863 * to the member access.
865 __isl_give isl_pw_aff *PetScan::extract_affine(MemberExpr *expr)
867 return nested_access(expr);
870 /* Extract an affine expression from a conditional operation.
872 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
874 isl_pw_aff *cond, *lhs, *rhs;
876 cond = extract_condition(expr->getCond());
877 lhs = extract_affine(expr->getTrueExpr());
878 rhs = extract_affine(expr->getFalseExpr());
880 return isl_pw_aff_cond(cond, lhs, rhs);
883 /* Extract an affine expression, if possible, from "expr".
884 * Otherwise return NULL.
886 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
888 switch (expr->getStmtClass()) {
889 case Stmt::ImplicitCastExprClass:
890 return extract_affine(cast<ImplicitCastExpr>(expr));
891 case Stmt::IntegerLiteralClass:
892 return extract_affine(cast<IntegerLiteral>(expr));
893 case Stmt::DeclRefExprClass:
894 return extract_affine(cast<DeclRefExpr>(expr));
895 case Stmt::BinaryOperatorClass:
896 return extract_affine(cast<BinaryOperator>(expr));
897 case Stmt::UnaryOperatorClass:
898 return extract_affine(cast<UnaryOperator>(expr));
899 case Stmt::ParenExprClass:
900 return extract_affine(cast<ParenExpr>(expr));
901 case Stmt::CallExprClass:
902 return extract_affine(cast<CallExpr>(expr));
903 case Stmt::ArraySubscriptExprClass:
904 return extract_affine(cast<ArraySubscriptExpr>(expr));
905 case Stmt::MemberExprClass:
906 return extract_affine(cast<MemberExpr>(expr));
907 case Stmt::ConditionalOperatorClass:
908 return extract_affine(cast<ConditionalOperator>(expr));
909 default:
910 unsupported(expr);
912 return NULL;
915 __isl_give isl_multi_pw_aff *PetScan::extract_index(ImplicitCastExpr *expr)
917 return extract_index(expr->getSubExpr());
920 /* Return the depth of an array of the given type.
922 static int array_depth(const Type *type)
924 if (type->isPointerType())
925 return 1 + array_depth(type->getPointeeType().getTypePtr());
926 if (type->isArrayType()) {
927 const ArrayType *atype;
928 type = type->getCanonicalTypeInternal().getTypePtr();
929 atype = cast<ArrayType>(type);
930 return 1 + array_depth(atype->getElementType().getTypePtr());
932 return 0;
935 /* Return the depth of the array accessed by the index expression "index".
936 * If "index" is an affine expression, i.e., if it does not access
937 * any array, then return 1.
938 * If "index" represent a member access, i.e., if its range is a wrapped
939 * relation, then return the sum of the depth of the array of structures
940 * and that of the member inside the structure.
942 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
944 isl_id *id;
945 ValueDecl *decl;
947 if (!index)
948 return -1;
950 if (isl_multi_pw_aff_range_is_wrapping(index)) {
951 int domain_depth, range_depth;
952 isl_multi_pw_aff *domain, *range;
954 domain = isl_multi_pw_aff_copy(index);
955 domain = isl_multi_pw_aff_range_factor_domain(domain);
956 domain_depth = extract_depth(domain);
957 isl_multi_pw_aff_free(domain);
958 range = isl_multi_pw_aff_copy(index);
959 range = isl_multi_pw_aff_range_factor_range(range);
960 range_depth = extract_depth(range);
961 isl_multi_pw_aff_free(range);
963 return domain_depth + range_depth;
966 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
967 return 1;
969 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
970 if (!id)
971 return -1;
972 decl = (ValueDecl *) isl_id_get_user(id);
973 isl_id_free(id);
975 return array_depth(decl->getType().getTypePtr());
978 /* Extract an index expression from a reference to a variable.
979 * If the variable has name "A", then the returned index expression
980 * is of the form
982 * { [] -> A[] }
984 __isl_give isl_multi_pw_aff *PetScan::extract_index(DeclRefExpr *expr)
986 return extract_index(expr->getDecl());
989 /* Extract an index expression from a variable.
990 * If the variable has name "A", then the returned index expression
991 * is of the form
993 * { [] -> A[] }
995 __isl_give isl_multi_pw_aff *PetScan::extract_index(ValueDecl *decl)
997 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
998 isl_space *space = isl_space_alloc(ctx, 0, 0, 0);
1000 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1002 return isl_multi_pw_aff_zero(space);
1005 /* Extract an index expression from an integer contant.
1006 * If the value of the constant is "v", then the returned access relation
1007 * is
1009 * { [] -> [v] }
1011 __isl_give isl_multi_pw_aff *PetScan::extract_index(IntegerLiteral *expr)
1013 isl_multi_pw_aff *mpa;
1015 mpa = isl_multi_pw_aff_from_pw_aff(extract_affine(expr));
1016 mpa = isl_multi_pw_aff_from_range(mpa);
1017 return mpa;
1020 /* Try and extract an index expression from the given Expr.
1021 * Return NULL if it doesn't work out.
1023 __isl_give isl_multi_pw_aff *PetScan::extract_index(Expr *expr)
1025 switch (expr->getStmtClass()) {
1026 case Stmt::ImplicitCastExprClass:
1027 return extract_index(cast<ImplicitCastExpr>(expr));
1028 case Stmt::DeclRefExprClass:
1029 return extract_index(cast<DeclRefExpr>(expr));
1030 case Stmt::ArraySubscriptExprClass:
1031 return extract_index(cast<ArraySubscriptExpr>(expr));
1032 case Stmt::IntegerLiteralClass:
1033 return extract_index(cast<IntegerLiteral>(expr));
1034 case Stmt::MemberExprClass:
1035 return extract_index(cast<MemberExpr>(expr));
1036 default:
1037 unsupported(expr);
1039 return NULL;
1042 /* Given a partial index expression "base" and an extra index "index",
1043 * append the extra index to "base" and return the result.
1044 * Additionally, add the constraints that the extra index is non-negative.
1045 * If "index" represent a member access, i.e., if its range is a wrapped
1046 * relation, then we recursively extend the range of this nested relation.
1048 static __isl_give isl_multi_pw_aff *subscript(__isl_take isl_multi_pw_aff *base,
1049 __isl_take isl_pw_aff *index)
1051 isl_id *id;
1052 isl_set *domain;
1053 isl_multi_pw_aff *access;
1054 int member_access;
1056 member_access = isl_multi_pw_aff_range_is_wrapping(base);
1057 if (member_access < 0)
1058 goto error;
1059 if (member_access) {
1060 isl_multi_pw_aff *domain, *range;
1061 isl_id *id;
1063 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_out);
1064 domain = isl_multi_pw_aff_copy(base);
1065 domain = isl_multi_pw_aff_range_factor_domain(domain);
1066 range = isl_multi_pw_aff_range_factor_range(base);
1067 range = subscript(range, index);
1068 access = isl_multi_pw_aff_range_product(domain, range);
1069 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_out, id);
1070 return access;
1073 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_set);
1074 index = isl_pw_aff_from_range(index);
1075 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
1076 index = isl_pw_aff_intersect_domain(index, domain);
1077 access = isl_multi_pw_aff_from_pw_aff(index);
1078 access = isl_multi_pw_aff_flat_range_product(base, access);
1079 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_set, id);
1081 return access;
1082 error:
1083 isl_multi_pw_aff_free(base);
1084 isl_pw_aff_free(index);
1085 return NULL;
1088 /* Extract an index expression from the given array subscript expression.
1089 * If nesting is allowed in general, then we turn it on while
1090 * examining the index expression.
1092 * We first extract an index expression from the base.
1093 * This will result in an index expression with a range that corresponds
1094 * to the earlier indices.
1095 * We then extract the current index, restrict its domain
1096 * to those values that result in a non-negative index and
1097 * append the index to the base index expression.
1099 __isl_give isl_multi_pw_aff *PetScan::extract_index(ArraySubscriptExpr *expr)
1101 Expr *base = expr->getBase();
1102 Expr *idx = expr->getIdx();
1103 isl_pw_aff *index;
1104 isl_multi_pw_aff *base_access;
1105 isl_multi_pw_aff *access;
1106 bool save_nesting = nesting_enabled;
1108 nesting_enabled = allow_nested;
1110 base_access = extract_index(base);
1111 index = extract_affine(idx);
1113 nesting_enabled = save_nesting;
1115 access = subscript(base_access, index);
1117 return access;
1120 /* Construct a name for a member access by concatenating the name
1121 * of the array of structures and the member, separated by an underscore.
1123 * The caller is responsible for freeing the result.
1125 static char *member_access_name(isl_ctx *ctx, const char *base,
1126 const char *field)
1128 int len;
1129 char *name;
1131 len = strlen(base) + 1 + strlen(field);
1132 name = isl_alloc_array(ctx, char, len + 1);
1133 if (!name)
1134 return NULL;
1135 snprintf(name, len + 1, "%s_%s", base, field);
1137 return name;
1140 /* Given an index expression "base" for an element of an array of structures
1141 * and an expression "field" for the field member being accessed, construct
1142 * an index expression for an access to that member of the given structure.
1143 * In particular, take the range product of "base" and "field" and
1144 * attach a name to the result.
1146 static __isl_give isl_multi_pw_aff *member(__isl_take isl_multi_pw_aff *base,
1147 __isl_take isl_multi_pw_aff *field)
1149 isl_ctx *ctx;
1150 isl_multi_pw_aff *access;
1151 const char *base_name, *field_name;
1152 char *name;
1154 ctx = isl_multi_pw_aff_get_ctx(base);
1156 base_name = isl_multi_pw_aff_get_tuple_name(base, isl_dim_out);
1157 field_name = isl_multi_pw_aff_get_tuple_name(field, isl_dim_out);
1158 name = member_access_name(ctx, base_name, field_name);
1160 access = isl_multi_pw_aff_range_product(base, field);
1162 access = isl_multi_pw_aff_set_tuple_name(access, isl_dim_out, name);
1163 free(name);
1165 return access;
1168 /* Extract an index expression from a member expression.
1170 * If the base access (to the structure containing the member)
1171 * is of the form
1173 * [] -> A[..]
1175 * and the member is called "f", then the member access is of
1176 * the form
1178 * [] -> A_f[A[..] -> f[]]
1180 * If the member access is to an anonymous struct, then simply return
1182 * [] -> A[..]
1184 * If the member access in the source code is of the form
1186 * A->f
1188 * then it is treated as
1190 * A[0].f
1192 __isl_give isl_multi_pw_aff *PetScan::extract_index(MemberExpr *expr)
1194 Expr *base = expr->getBase();
1195 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
1196 isl_multi_pw_aff *base_access, *field_access;
1197 isl_id *id;
1198 isl_space *space;
1200 base_access = extract_index(base);
1202 if (expr->isArrow()) {
1203 isl_space *space = isl_space_params_alloc(ctx, 0);
1204 isl_local_space *ls = isl_local_space_from_space(space);
1205 isl_aff *aff = isl_aff_zero_on_domain(ls);
1206 isl_pw_aff *index = isl_pw_aff_from_aff(aff);
1207 base_access = subscript(base_access, index);
1210 if (field->isAnonymousStructOrUnion())
1211 return base_access;
1213 id = isl_id_alloc(ctx, field->getName().str().c_str(), field);
1214 space = isl_multi_pw_aff_get_domain_space(base_access);
1215 space = isl_space_from_domain(space);
1216 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1217 field_access = isl_multi_pw_aff_zero(space);
1219 return member(base_access, field_access);
1222 /* Check if "expr" calls function "minmax" with two arguments and if so
1223 * make lhs and rhs refer to these two arguments.
1225 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1227 CallExpr *call;
1228 FunctionDecl *fd;
1229 string name;
1231 if (expr->getStmtClass() != Stmt::CallExprClass)
1232 return false;
1234 call = cast<CallExpr>(expr);
1235 fd = call->getDirectCallee();
1236 if (!fd)
1237 return false;
1239 if (call->getNumArgs() != 2)
1240 return false;
1242 name = fd->getDeclName().getAsString();
1243 if (name != minmax)
1244 return false;
1246 lhs = call->getArg(0);
1247 rhs = call->getArg(1);
1249 return true;
1252 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1253 * lhs and rhs refer to the two arguments.
1255 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1257 return is_minmax(expr, "min", lhs, rhs);
1260 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1261 * lhs and rhs refer to the two arguments.
1263 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1265 return is_minmax(expr, "max", lhs, rhs);
1268 /* Return "lhs && rhs", defined on the shared definition domain.
1270 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1271 __isl_take isl_pw_aff *rhs)
1273 isl_set *cond;
1274 isl_set *dom;
1276 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1277 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1278 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1279 isl_pw_aff_non_zero_set(rhs));
1280 return indicator_function(cond, dom);
1283 /* Return "lhs && rhs", with shortcut semantics.
1284 * That is, if lhs is false, then the result is defined even if rhs is not.
1285 * In practice, we compute lhs ? rhs : lhs.
1287 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1288 __isl_take isl_pw_aff *rhs)
1290 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1293 /* Return "lhs || rhs", with shortcut semantics.
1294 * That is, if lhs is true, then the result is defined even if rhs is not.
1295 * In practice, we compute lhs ? lhs : rhs.
1297 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1298 __isl_take isl_pw_aff *rhs)
1300 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1303 /* Extract an affine expressions representing the comparison "LHS op RHS"
1304 * "comp" is the original statement that "LHS op RHS" is derived from
1305 * and is used for diagnostics.
1307 * If the comparison is of the form
1309 * a <= min(b,c)
1311 * then the expression is constructed as the conjunction of
1312 * the comparisons
1314 * a <= b and a <= c
1316 * A similar optimization is performed for max(a,b) <= c.
1317 * We do this because that will lead to simpler representations
1318 * of the expression.
1319 * If isl is ever enhanced to explicitly deal with min and max expressions,
1320 * this optimization can be removed.
1322 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1323 Expr *LHS, Expr *RHS, Stmt *comp)
1325 isl_pw_aff *lhs;
1326 isl_pw_aff *rhs;
1327 isl_pw_aff *res;
1328 isl_set *cond;
1329 isl_set *dom;
1331 if (op == BO_GT)
1332 return extract_comparison(BO_LT, RHS, LHS, comp);
1333 if (op == BO_GE)
1334 return extract_comparison(BO_LE, RHS, LHS, comp);
1336 if (op == BO_LT || op == BO_LE) {
1337 Expr *expr1, *expr2;
1338 if (is_min(RHS, expr1, expr2)) {
1339 lhs = extract_comparison(op, LHS, expr1, comp);
1340 rhs = extract_comparison(op, LHS, expr2, comp);
1341 return pw_aff_and(lhs, rhs);
1343 if (is_max(LHS, expr1, expr2)) {
1344 lhs = extract_comparison(op, expr1, RHS, comp);
1345 rhs = extract_comparison(op, expr2, RHS, comp);
1346 return pw_aff_and(lhs, rhs);
1350 lhs = extract_affine(LHS);
1351 rhs = extract_affine(RHS);
1353 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1354 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1356 switch (op) {
1357 case BO_LT:
1358 cond = isl_pw_aff_lt_set(lhs, rhs);
1359 break;
1360 case BO_LE:
1361 cond = isl_pw_aff_le_set(lhs, rhs);
1362 break;
1363 case BO_EQ:
1364 cond = isl_pw_aff_eq_set(lhs, rhs);
1365 break;
1366 case BO_NE:
1367 cond = isl_pw_aff_ne_set(lhs, rhs);
1368 break;
1369 default:
1370 isl_pw_aff_free(lhs);
1371 isl_pw_aff_free(rhs);
1372 isl_set_free(dom);
1373 unsupported(comp);
1374 return NULL;
1377 cond = isl_set_coalesce(cond);
1378 res = indicator_function(cond, dom);
1380 return res;
1383 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1385 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1386 comp->getRHS(), comp);
1389 /* Extract an affine expression representing the negation (logical not)
1390 * of a subexpression.
1392 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1394 isl_set *set_cond, *dom;
1395 isl_pw_aff *cond, *res;
1397 cond = extract_condition(op->getSubExpr());
1399 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1401 set_cond = isl_pw_aff_zero_set(cond);
1403 res = indicator_function(set_cond, dom);
1405 return res;
1408 /* Extract an affine expression representing the disjunction (logical or)
1409 * or conjunction (logical and) of two subexpressions.
1411 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1413 isl_pw_aff *lhs, *rhs;
1415 lhs = extract_condition(comp->getLHS());
1416 rhs = extract_condition(comp->getRHS());
1418 switch (comp->getOpcode()) {
1419 case BO_LAnd:
1420 return pw_aff_and_then(lhs, rhs);
1421 case BO_LOr:
1422 return pw_aff_or_else(lhs, rhs);
1423 default:
1424 isl_pw_aff_free(lhs);
1425 isl_pw_aff_free(rhs);
1428 unsupported(comp);
1429 return NULL;
1432 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1434 switch (expr->getOpcode()) {
1435 case UO_LNot:
1436 return extract_boolean(expr);
1437 default:
1438 unsupported(expr);
1439 return NULL;
1443 /* Extract the affine expression "expr != 0 ? 1 : 0".
1445 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1447 isl_pw_aff *res;
1448 isl_set *set, *dom;
1450 res = extract_affine(expr);
1452 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1453 set = isl_pw_aff_non_zero_set(res);
1455 res = indicator_function(set, dom);
1457 return res;
1460 /* Extract an affine expression from a boolean expression.
1461 * In particular, return the expression "expr ? 1 : 0".
1463 * If the expression doesn't look like a condition, we assume it
1464 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1466 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1468 BinaryOperator *comp;
1470 if (!expr) {
1471 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1472 return indicator_function(u, isl_set_copy(u));
1475 if (expr->getStmtClass() == Stmt::ParenExprClass)
1476 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1478 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1479 return extract_condition(cast<UnaryOperator>(expr));
1481 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1482 return extract_implicit_condition(expr);
1484 comp = cast<BinaryOperator>(expr);
1485 switch (comp->getOpcode()) {
1486 case BO_LT:
1487 case BO_LE:
1488 case BO_GT:
1489 case BO_GE:
1490 case BO_EQ:
1491 case BO_NE:
1492 return extract_comparison(comp);
1493 case BO_LAnd:
1494 case BO_LOr:
1495 return extract_boolean(comp);
1496 default:
1497 return extract_implicit_condition(expr);
1501 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1503 switch (kind) {
1504 case UO_Minus:
1505 return pet_op_minus;
1506 case UO_Not:
1507 return pet_op_not;
1508 case UO_LNot:
1509 return pet_op_lnot;
1510 case UO_PostInc:
1511 return pet_op_post_inc;
1512 case UO_PostDec:
1513 return pet_op_post_dec;
1514 case UO_PreInc:
1515 return pet_op_pre_inc;
1516 case UO_PreDec:
1517 return pet_op_pre_dec;
1518 default:
1519 return pet_op_last;
1523 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1525 switch (kind) {
1526 case BO_AddAssign:
1527 return pet_op_add_assign;
1528 case BO_SubAssign:
1529 return pet_op_sub_assign;
1530 case BO_MulAssign:
1531 return pet_op_mul_assign;
1532 case BO_DivAssign:
1533 return pet_op_div_assign;
1534 case BO_Assign:
1535 return pet_op_assign;
1536 case BO_Add:
1537 return pet_op_add;
1538 case BO_Sub:
1539 return pet_op_sub;
1540 case BO_Mul:
1541 return pet_op_mul;
1542 case BO_Div:
1543 return pet_op_div;
1544 case BO_Rem:
1545 return pet_op_mod;
1546 case BO_Shl:
1547 return pet_op_shl;
1548 case BO_Shr:
1549 return pet_op_shr;
1550 case BO_EQ:
1551 return pet_op_eq;
1552 case BO_NE:
1553 return pet_op_ne;
1554 case BO_LE:
1555 return pet_op_le;
1556 case BO_GE:
1557 return pet_op_ge;
1558 case BO_LT:
1559 return pet_op_lt;
1560 case BO_GT:
1561 return pet_op_gt;
1562 case BO_And:
1563 return pet_op_and;
1564 case BO_Xor:
1565 return pet_op_xor;
1566 case BO_Or:
1567 return pet_op_or;
1568 case BO_LAnd:
1569 return pet_op_land;
1570 case BO_LOr:
1571 return pet_op_lor;
1572 default:
1573 return pet_op_last;
1577 /* Construct a pet_expr representing a unary operator expression.
1579 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1581 struct pet_expr *arg;
1582 enum pet_op_type op;
1584 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1585 if (op == pet_op_last) {
1586 unsupported(expr);
1587 return NULL;
1590 arg = extract_expr(expr->getSubExpr());
1592 if (expr->isIncrementDecrementOp() &&
1593 arg && arg->type == pet_expr_access) {
1594 mark_write(arg);
1595 arg->acc.read = 1;
1598 return pet_expr_new_unary(ctx, op, arg);
1601 /* Mark the given access pet_expr as a write.
1602 * If a scalar is being accessed, then mark its value
1603 * as unknown in assigned_value.
1605 void PetScan::mark_write(struct pet_expr *access)
1607 isl_id *id;
1608 ValueDecl *decl;
1610 if (!access)
1611 return;
1613 access->acc.write = 1;
1614 access->acc.read = 0;
1616 if (!pet_expr_is_scalar_access(access))
1617 return;
1619 id = pet_expr_access_get_id(access);
1620 decl = (ValueDecl *) isl_id_get_user(id);
1621 clear_assignment(assigned_value, decl);
1622 isl_id_free(id);
1625 /* Assign "rhs" to "lhs".
1627 * In particular, if "lhs" is a scalar variable, then mark
1628 * the variable as having been assigned. If, furthermore, "rhs"
1629 * is an affine expression, then keep track of this value in assigned_value
1630 * so that we can plug it in when we later come across the same variable.
1632 void PetScan::assign(struct pet_expr *lhs, Expr *rhs)
1634 isl_id *id;
1635 ValueDecl *decl;
1636 isl_pw_aff *pa;
1638 if (!lhs)
1639 return;
1640 if (!pet_expr_is_scalar_access(lhs))
1641 return;
1643 id = pet_expr_access_get_id(lhs);
1644 decl = (ValueDecl *) isl_id_get_user(id);
1645 isl_id_free(id);
1647 pa = try_extract_affine(rhs);
1648 clear_assignment(assigned_value, decl);
1649 if (!pa)
1650 return;
1651 assigned_value[decl] = pa;
1652 insert_expression(pa);
1655 /* Construct a pet_expr representing a binary operator expression.
1657 * If the top level operator is an assignment and the LHS is an access,
1658 * then we mark that access as a write. If the operator is a compound
1659 * assignment, the access is marked as both a read and a write.
1661 * If "expr" assigns something to a scalar variable, then we mark
1662 * the variable as having been assigned. If, furthermore, the expression
1663 * is affine, then keep track of this value in assigned_value
1664 * so that we can plug it in when we later come across the same variable.
1666 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1668 struct pet_expr *lhs, *rhs;
1669 enum pet_op_type op;
1671 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1672 if (op == pet_op_last) {
1673 unsupported(expr);
1674 return NULL;
1677 lhs = extract_expr(expr->getLHS());
1678 rhs = extract_expr(expr->getRHS());
1680 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1681 mark_write(lhs);
1682 if (expr->isCompoundAssignmentOp())
1683 lhs->acc.read = 1;
1686 if (expr->getOpcode() == BO_Assign)
1687 assign(lhs, expr->getRHS());
1689 return pet_expr_new_binary(ctx, op, lhs, rhs);
1692 /* Construct a pet_scop with a single statement killing the entire
1693 * array "array".
1695 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1697 isl_id *id;
1698 isl_space *space;
1699 isl_multi_pw_aff *index;
1700 isl_map *access;
1701 struct pet_expr *expr;
1703 if (!array)
1704 return NULL;
1705 access = isl_map_from_range(isl_set_copy(array->extent));
1706 id = isl_set_get_tuple_id(array->extent);
1707 space = isl_space_alloc(ctx, 0, 0, 0);
1708 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1709 index = isl_multi_pw_aff_zero(space);
1710 expr = pet_expr_kill_from_access_and_index(access, index);
1711 return extract(stmt, expr);
1714 /* Construct a pet_scop for a (single) variable declaration.
1716 * The scop contains the variable being declared (as an array)
1717 * and a statement killing the array.
1719 * If the variable is initialized in the AST, then the scop
1720 * also contains an assignment to the variable.
1722 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1724 Decl *decl;
1725 VarDecl *vd;
1726 struct pet_expr *lhs, *rhs, *pe;
1727 struct pet_scop *scop_decl, *scop;
1728 struct pet_array *array;
1730 if (!stmt->isSingleDecl()) {
1731 unsupported(stmt);
1732 return NULL;
1735 decl = stmt->getSingleDecl();
1736 vd = cast<VarDecl>(decl);
1738 array = extract_array(ctx, vd, NULL);
1739 if (array)
1740 array->declared = 1;
1741 scop_decl = kill(stmt, array);
1742 scop_decl = pet_scop_add_array(scop_decl, array);
1744 if (!vd->getInit())
1745 return scop_decl;
1747 lhs = extract_access_expr(vd);
1748 rhs = extract_expr(vd->getInit());
1750 mark_write(lhs);
1751 assign(lhs, vd->getInit());
1753 pe = pet_expr_new_binary(ctx, pet_op_assign, lhs, rhs);
1754 scop = extract(stmt, pe);
1756 scop_decl = pet_scop_prefix(scop_decl, 0);
1757 scop = pet_scop_prefix(scop, 1);
1759 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1761 return scop;
1764 /* Construct a pet_expr representing a conditional operation.
1766 * We first try to extract the condition as an affine expression.
1767 * If that fails, we construct a pet_expr tree representing the condition.
1769 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1771 struct pet_expr *cond, *lhs, *rhs;
1772 isl_pw_aff *pa;
1774 pa = try_extract_affine(expr->getCond());
1775 if (pa) {
1776 isl_multi_pw_aff *test = isl_multi_pw_aff_from_pw_aff(pa);
1777 test = isl_multi_pw_aff_from_range(test);
1778 cond = pet_expr_from_index(test);
1779 } else
1780 cond = extract_expr(expr->getCond());
1781 lhs = extract_expr(expr->getTrueExpr());
1782 rhs = extract_expr(expr->getFalseExpr());
1784 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1787 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1789 return extract_expr(expr->getSubExpr());
1792 /* Construct a pet_expr representing a floating point value.
1794 * If the floating point literal does not appear in a macro,
1795 * then we use the original representation in the source code
1796 * as the string representation. Otherwise, we use the pretty
1797 * printer to produce a string representation.
1799 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1801 double d;
1802 string s;
1803 const LangOptions &LO = PP.getLangOpts();
1804 SourceLocation loc = expr->getLocation();
1806 if (!loc.isMacroID()) {
1807 SourceManager &SM = PP.getSourceManager();
1808 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1809 s = string(SM.getCharacterData(loc), len);
1810 } else {
1811 llvm::raw_string_ostream S(s);
1812 expr->printPretty(S, 0, PrintingPolicy(LO));
1813 S.str();
1815 d = expr->getValueAsApproximateDouble();
1816 return pet_expr_new_double(ctx, d, s.c_str());
1819 /* Extract an index expression from "expr" and then convert it into
1820 * an access pet_expr.
1822 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1824 isl_multi_pw_aff *index;
1825 struct pet_expr *pe;
1826 int depth;
1828 index = extract_index(expr);
1829 depth = extract_depth(index);
1831 pe = pet_expr_from_index_and_depth(index, depth);
1833 return pe;
1836 /* Extract an index expression from "decl" and then convert it into
1837 * an access pet_expr.
1839 struct pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1841 isl_multi_pw_aff *index;
1842 struct pet_expr *pe;
1843 int depth;
1845 index = extract_index(decl);
1846 depth = extract_depth(index);
1848 pe = pet_expr_from_index_and_depth(index, depth);
1850 return pe;
1853 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1855 return extract_expr(expr->getSubExpr());
1858 /* Extract an assume statement from the argument "expr"
1859 * of a __pencil_assume statement.
1861 struct pet_expr *PetScan::extract_assume(Expr *expr)
1863 isl_pw_aff *cond;
1864 struct pet_expr *res;
1866 cond = try_extract_affine_condition(expr);
1867 if (!cond) {
1868 res = extract_expr(expr);
1869 } else {
1870 isl_multi_pw_aff *index;
1871 index = isl_multi_pw_aff_from_pw_aff(cond);
1872 index = isl_multi_pw_aff_from_range(index);
1873 res = pet_expr_from_index(index);
1875 return pet_expr_new_unary(ctx, pet_op_assume, res);
1878 /* Construct a pet_expr corresponding to the function call argument "expr".
1879 * The argument appears in position "pos" of a call to function "fd".
1881 * If we are passing along a pointer to an array element
1882 * or an entire row or even higher dimensional slice of an array,
1883 * then the function being called may write into the array.
1885 * We assume here that if the function is declared to take a pointer
1886 * to a const type, then the function will perform a read
1887 * and that otherwise, it will perform a write.
1889 struct pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
1890 Expr *expr)
1892 struct pet_expr *res;
1893 int is_addr = 0;
1894 pet_expr *main_arg;
1895 Stmt::StmtClass sc;
1897 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
1898 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
1899 expr = ice->getSubExpr();
1901 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
1902 UnaryOperator *op = cast<UnaryOperator>(expr);
1903 if (op->getOpcode() == UO_AddrOf) {
1904 is_addr = 1;
1905 expr = op->getSubExpr();
1908 res = extract_expr(expr);
1909 main_arg = res;
1910 if (is_addr)
1911 res = pet_expr_new_unary(ctx, pet_op_address_of, res);
1912 if (!res)
1913 return NULL;
1914 sc = expr->getStmtClass();
1915 if ((sc == Stmt::ArraySubscriptExprClass ||
1916 sc == Stmt::MemberExprClass) &&
1917 array_depth(expr->getType().getTypePtr()) > 0)
1918 is_addr = 1;
1919 if (is_addr && main_arg->type == pet_expr_access) {
1920 ParmVarDecl *parm;
1921 if (!fd->hasPrototype()) {
1922 report_prototype_required(expr);
1923 return pet_expr_free(res);
1925 parm = fd->getParamDecl(pos);
1926 if (!const_base(parm->getType()))
1927 mark_write(main_arg);
1930 return res;
1933 /* Construct a pet_expr representing a function call.
1935 * In the special case of a "call" to __pencil_assume,
1936 * construct an assume expression instead.
1938 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1940 struct pet_expr *res = NULL;
1941 FunctionDecl *fd;
1942 string name;
1943 unsigned n_arg;
1945 fd = expr->getDirectCallee();
1946 if (!fd) {
1947 unsupported(expr);
1948 return NULL;
1951 name = fd->getDeclName().getAsString();
1952 n_arg = expr->getNumArgs();
1954 if (n_arg == 1 && name == "__pencil_assume")
1955 return extract_assume(expr->getArg(0));
1957 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1958 if (!res)
1959 return NULL;
1961 for (int i = 0; i < n_arg; ++i) {
1962 Expr *arg = expr->getArg(i);
1963 res->args[i] = PetScan::extract_argument(fd, i, arg);
1964 if (!res->args[i])
1965 goto error;
1968 return res;
1969 error:
1970 pet_expr_free(res);
1971 return NULL;
1974 /* Construct a pet_expr representing a (C style) cast.
1976 struct pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1978 struct pet_expr *arg;
1979 QualType type;
1981 arg = extract_expr(expr->getSubExpr());
1982 if (!arg)
1983 return NULL;
1985 type = expr->getTypeAsWritten();
1986 return pet_expr_new_cast(ctx, type.getAsString().c_str(), arg);
1989 /* Construct a pet_expr representing an integer.
1991 struct pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1993 return pet_expr_new_int(extract_int(expr));
1996 /* Try and construct a pet_expr representing "expr".
1998 struct pet_expr *PetScan::extract_expr(Expr *expr)
2000 switch (expr->getStmtClass()) {
2001 case Stmt::UnaryOperatorClass:
2002 return extract_expr(cast<UnaryOperator>(expr));
2003 case Stmt::CompoundAssignOperatorClass:
2004 case Stmt::BinaryOperatorClass:
2005 return extract_expr(cast<BinaryOperator>(expr));
2006 case Stmt::ImplicitCastExprClass:
2007 return extract_expr(cast<ImplicitCastExpr>(expr));
2008 case Stmt::ArraySubscriptExprClass:
2009 case Stmt::DeclRefExprClass:
2010 case Stmt::MemberExprClass:
2011 return extract_access_expr(expr);
2012 case Stmt::IntegerLiteralClass:
2013 return extract_expr(cast<IntegerLiteral>(expr));
2014 case Stmt::FloatingLiteralClass:
2015 return extract_expr(cast<FloatingLiteral>(expr));
2016 case Stmt::ParenExprClass:
2017 return extract_expr(cast<ParenExpr>(expr));
2018 case Stmt::ConditionalOperatorClass:
2019 return extract_expr(cast<ConditionalOperator>(expr));
2020 case Stmt::CallExprClass:
2021 return extract_expr(cast<CallExpr>(expr));
2022 case Stmt::CStyleCastExprClass:
2023 return extract_expr(cast<CStyleCastExpr>(expr));
2024 default:
2025 unsupported(expr);
2027 return NULL;
2030 /* Check if the given initialization statement is an assignment.
2031 * If so, return that assignment. Otherwise return NULL.
2033 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
2035 BinaryOperator *ass;
2037 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
2038 return NULL;
2040 ass = cast<BinaryOperator>(init);
2041 if (ass->getOpcode() != BO_Assign)
2042 return NULL;
2044 return ass;
2047 /* Check if the given initialization statement is a declaration
2048 * of a single variable.
2049 * If so, return that declaration. Otherwise return NULL.
2051 Decl *PetScan::initialization_declaration(Stmt *init)
2053 DeclStmt *decl;
2055 if (init->getStmtClass() != Stmt::DeclStmtClass)
2056 return NULL;
2058 decl = cast<DeclStmt>(init);
2060 if (!decl->isSingleDecl())
2061 return NULL;
2063 return decl->getSingleDecl();
2066 /* Given the assignment operator in the initialization of a for loop,
2067 * extract the induction variable, i.e., the (integer)variable being
2068 * assigned.
2070 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
2072 Expr *lhs;
2073 DeclRefExpr *ref;
2074 ValueDecl *decl;
2075 const Type *type;
2077 lhs = init->getLHS();
2078 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2079 unsupported(init);
2080 return NULL;
2083 ref = cast<DeclRefExpr>(lhs);
2084 decl = ref->getDecl();
2085 type = decl->getType().getTypePtr();
2087 if (!type->isIntegerType()) {
2088 unsupported(lhs);
2089 return NULL;
2092 return decl;
2095 /* Given the initialization statement of a for loop and the single
2096 * declaration in this initialization statement,
2097 * extract the induction variable, i.e., the (integer) variable being
2098 * declared.
2100 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
2102 VarDecl *vd;
2104 vd = cast<VarDecl>(decl);
2106 const QualType type = vd->getType();
2107 if (!type->isIntegerType()) {
2108 unsupported(init);
2109 return NULL;
2112 if (!vd->getInit()) {
2113 unsupported(init);
2114 return NULL;
2117 return vd;
2120 /* Check that op is of the form iv++ or iv--.
2121 * Return an affine expression "1" or "-1" accordingly.
2123 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
2124 clang::UnaryOperator *op, clang::ValueDecl *iv)
2126 Expr *sub;
2127 DeclRefExpr *ref;
2128 isl_space *space;
2129 isl_aff *aff;
2131 if (!op->isIncrementDecrementOp()) {
2132 unsupported(op);
2133 return NULL;
2136 sub = op->getSubExpr();
2137 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
2138 unsupported(op);
2139 return NULL;
2142 ref = cast<DeclRefExpr>(sub);
2143 if (ref->getDecl() != iv) {
2144 unsupported(op);
2145 return NULL;
2148 space = isl_space_params_alloc(ctx, 0);
2149 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2151 if (op->isIncrementOp())
2152 aff = isl_aff_add_constant_si(aff, 1);
2153 else
2154 aff = isl_aff_add_constant_si(aff, -1);
2156 return isl_pw_aff_from_aff(aff);
2159 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
2160 * has a single constant expression, then put this constant in *user.
2161 * The caller is assumed to have checked that this function will
2162 * be called exactly once.
2164 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
2165 void *user)
2167 isl_val **inc = (isl_val **)user;
2168 int res = 0;
2170 if (isl_aff_is_cst(aff))
2171 *inc = isl_aff_get_constant_val(aff);
2172 else
2173 res = -1;
2175 isl_set_free(set);
2176 isl_aff_free(aff);
2178 return res;
2181 /* Check if op is of the form
2183 * iv = iv + inc
2185 * and return inc as an affine expression.
2187 * We extract an affine expression from the RHS, subtract iv and return
2188 * the result.
2190 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
2191 clang::ValueDecl *iv)
2193 Expr *lhs;
2194 DeclRefExpr *ref;
2195 isl_id *id;
2196 isl_space *dim;
2197 isl_aff *aff;
2198 isl_pw_aff *val;
2200 if (op->getOpcode() != BO_Assign) {
2201 unsupported(op);
2202 return NULL;
2205 lhs = op->getLHS();
2206 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2207 unsupported(op);
2208 return NULL;
2211 ref = cast<DeclRefExpr>(lhs);
2212 if (ref->getDecl() != iv) {
2213 unsupported(op);
2214 return NULL;
2217 val = extract_affine(op->getRHS());
2219 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2221 dim = isl_space_params_alloc(ctx, 1);
2222 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2223 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2224 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2226 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
2228 return val;
2231 /* Check that op is of the form iv += cst or iv -= cst
2232 * and return an affine expression corresponding oto cst or -cst accordingly.
2234 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
2235 CompoundAssignOperator *op, clang::ValueDecl *iv)
2237 Expr *lhs;
2238 DeclRefExpr *ref;
2239 bool neg = false;
2240 isl_pw_aff *val;
2241 BinaryOperatorKind opcode;
2243 opcode = op->getOpcode();
2244 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
2245 unsupported(op);
2246 return NULL;
2248 if (opcode == BO_SubAssign)
2249 neg = true;
2251 lhs = op->getLHS();
2252 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2253 unsupported(op);
2254 return NULL;
2257 ref = cast<DeclRefExpr>(lhs);
2258 if (ref->getDecl() != iv) {
2259 unsupported(op);
2260 return NULL;
2263 val = extract_affine(op->getRHS());
2264 if (neg)
2265 val = isl_pw_aff_neg(val);
2267 return val;
2270 /* Check that the increment of the given for loop increments
2271 * (or decrements) the induction variable "iv" and return
2272 * the increment as an affine expression if successful.
2274 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
2275 ValueDecl *iv)
2277 Stmt *inc = stmt->getInc();
2279 if (!inc) {
2280 report_missing_increment(stmt);
2281 return NULL;
2284 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
2285 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
2286 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
2287 return extract_compound_increment(
2288 cast<CompoundAssignOperator>(inc), iv);
2289 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
2290 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
2292 unsupported(inc);
2293 return NULL;
2296 /* Embed the given iteration domain in an extra outer loop
2297 * with induction variable "var".
2298 * If this variable appeared as a parameter in the constraints,
2299 * it is replaced by the new outermost dimension.
2301 static __isl_give isl_set *embed(__isl_take isl_set *set,
2302 __isl_take isl_id *var)
2304 int pos;
2306 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
2307 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
2308 if (pos >= 0) {
2309 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
2310 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2313 isl_id_free(var);
2314 return set;
2317 /* Return those elements in the space of "cond" that come after
2318 * (based on "sign") an element in "cond".
2320 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
2322 isl_map *previous_to_this;
2324 if (sign > 0)
2325 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
2326 else
2327 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
2329 cond = isl_set_apply(cond, previous_to_this);
2331 return cond;
2334 /* Create the infinite iteration domain
2336 * { [id] : id >= 0 }
2338 * If "scop" has an affine skip of type pet_skip_later,
2339 * then remove those iterations i that have an earlier iteration
2340 * where the skip condition is satisfied, meaning that iteration i
2341 * is not executed.
2342 * Since we are dealing with a loop without loop iterator,
2343 * the skip condition cannot refer to the current loop iterator and
2344 * so effectively, the returned set is of the form
2346 * { [0]; [id] : id >= 1 and not skip }
2348 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
2349 struct pet_scop *scop)
2351 isl_ctx *ctx = isl_id_get_ctx(id);
2352 isl_set *domain;
2353 isl_set *skip;
2355 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
2356 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
2358 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
2359 return domain;
2361 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2362 skip = embed(skip, isl_id_copy(id));
2363 skip = isl_set_intersect(skip , isl_set_copy(domain));
2364 domain = isl_set_subtract(domain, after(skip, 1));
2366 return domain;
2369 /* Create an identity affine expression on the space containing "domain",
2370 * which is assumed to be one-dimensional.
2372 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
2374 isl_local_space *ls;
2376 ls = isl_local_space_from_space(isl_set_get_space(domain));
2377 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
2380 /* Create an affine expression that maps elements
2381 * of a single-dimensional array "id_test" to the previous element
2382 * (according to "inc"), provided this element belongs to "domain".
2383 * That is, create the affine expression
2385 * { id[x] -> id[x - inc] : x - inc in domain }
2387 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
2388 __isl_take isl_set *domain, __isl_take isl_val *inc)
2390 isl_space *space;
2391 isl_local_space *ls;
2392 isl_aff *aff;
2393 isl_multi_pw_aff *prev;
2395 space = isl_set_get_space(domain);
2396 ls = isl_local_space_from_space(space);
2397 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2398 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
2399 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
2400 domain = isl_set_preimage_multi_pw_aff(domain,
2401 isl_multi_pw_aff_copy(prev));
2402 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
2403 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
2405 return prev;
2408 /* Add an implication to "scop" expressing that if an element of
2409 * virtual array "id_test" has value "satisfied" then all previous elements
2410 * of this array also have that value. The set of previous elements
2411 * is bounded by "domain". If "sign" is negative then the iterator
2412 * is decreasing and we express that all subsequent array elements
2413 * (but still defined previously) have the same value.
2415 static struct pet_scop *add_implication(struct pet_scop *scop,
2416 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
2417 int satisfied)
2419 isl_space *space;
2420 isl_map *map;
2422 domain = isl_set_set_tuple_id(domain, id_test);
2423 space = isl_set_get_space(domain);
2424 if (sign > 0)
2425 map = isl_map_lex_ge(space);
2426 else
2427 map = isl_map_lex_le(space);
2428 map = isl_map_intersect_range(map, domain);
2429 scop = pet_scop_add_implication(scop, map, satisfied);
2431 return scop;
2434 /* Add a filter to "scop" that imposes that it is only executed
2435 * when the variable identified by "id_test" has a zero value
2436 * for all previous iterations of "domain".
2438 * In particular, add a filter that imposes that the array
2439 * has a zero value at the previous iteration of domain and
2440 * add an implication that implies that it then has that
2441 * value for all previous iterations.
2443 static struct pet_scop *scop_add_break(struct pet_scop *scop,
2444 __isl_take isl_id *id_test, __isl_take isl_set *domain,
2445 __isl_take isl_val *inc)
2447 isl_multi_pw_aff *prev;
2448 int sign = isl_val_sgn(inc);
2450 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2451 scop = add_implication(scop, id_test, domain, sign, 0);
2452 scop = pet_scop_filter(scop, prev, 0);
2454 return scop;
2457 /* Construct a pet_scop for an infinite loop around the given body.
2459 * We extract a pet_scop for the body and then embed it in a loop with
2460 * iteration domain
2462 * { [t] : t >= 0 }
2464 * and schedule
2466 * { [t] -> [t] }
2468 * If the body contains any break, then it is taken into
2469 * account in infinite_domain (if the skip condition is affine)
2470 * or in scop_add_break (if the skip condition is not affine).
2472 * If we were only able to extract part of the body, then simply
2473 * return that part.
2475 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2477 isl_id *id, *id_test;
2478 isl_set *domain;
2479 isl_aff *ident;
2480 struct pet_scop *scop;
2481 bool has_var_break;
2483 scop = extract(body);
2484 if (!scop)
2485 return NULL;
2486 if (partial)
2487 return scop;
2489 id = isl_id_alloc(ctx, "t", NULL);
2490 domain = infinite_domain(isl_id_copy(id), scop);
2491 ident = identity_aff(domain);
2493 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2494 if (has_var_break)
2495 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
2497 scop = pet_scop_embed(scop, isl_set_copy(domain),
2498 isl_aff_copy(ident), ident, id);
2499 if (has_var_break)
2500 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
2501 else
2502 isl_set_free(domain);
2504 return scop;
2507 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2509 * for (;;)
2510 * body
2513 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2515 clear_assignments clear(assigned_value);
2516 clear.TraverseStmt(stmt->getBody());
2518 return extract_infinite_loop(stmt->getBody());
2521 /* Create an index expression for an access to a virtual array
2522 * representing the result of a condition.
2523 * Unlike other accessed data, the id of the array is NULL as
2524 * there is no ValueDecl in the program corresponding to the virtual
2525 * array.
2526 * The array starts out as a scalar, but grows along with the
2527 * statement writing to the array in pet_scop_embed.
2529 static __isl_give isl_multi_pw_aff *create_test_index(isl_ctx *ctx, int test_nr)
2531 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2532 isl_id *id;
2533 char name[50];
2535 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2536 id = isl_id_alloc(ctx, name, NULL);
2537 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2538 return isl_multi_pw_aff_zero(dim);
2541 /* Add an array with the given extent (range of "index") to the list
2542 * of arrays in "scop" and return the extended pet_scop.
2543 * The array is marked as attaining values 0 and 1 only and
2544 * as each element being assigned at most once.
2546 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2547 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
2549 isl_ctx *ctx = isl_multi_pw_aff_get_ctx(index);
2550 isl_space *dim;
2551 struct pet_array *array;
2552 isl_map *access;
2554 if (!scop)
2555 return NULL;
2556 if (!ctx)
2557 goto error;
2559 array = isl_calloc_type(ctx, struct pet_array);
2560 if (!array)
2561 goto error;
2563 access = isl_map_from_multi_pw_aff(isl_multi_pw_aff_copy(index));
2564 array->extent = isl_map_range(access);
2565 dim = isl_space_params_alloc(ctx, 0);
2566 array->context = isl_set_universe(dim);
2567 dim = isl_space_set_alloc(ctx, 0, 1);
2568 array->value_bounds = isl_set_universe(dim);
2569 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2570 isl_dim_set, 0, 0);
2571 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2572 isl_dim_set, 0, 1);
2573 array->element_type = strdup("int");
2574 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2575 array->uniquely_defined = 1;
2577 if (!array->extent || !array->context)
2578 array = pet_array_free(array);
2580 scop = pet_scop_add_array(scop, array);
2582 return scop;
2583 error:
2584 pet_scop_free(scop);
2585 return NULL;
2588 /* Construct a pet_scop for a while loop of the form
2590 * while (pa)
2591 * body
2593 * In particular, construct a scop for an infinite loop around body and
2594 * intersect the domain with the affine expression.
2595 * Note that this intersection may result in an empty loop.
2597 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2598 Stmt *body)
2600 struct pet_scop *scop;
2601 isl_set *dom;
2602 isl_set *valid;
2604 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2605 dom = isl_pw_aff_non_zero_set(pa);
2606 scop = extract_infinite_loop(body);
2607 scop = pet_scop_restrict(scop, dom);
2608 scop = pet_scop_restrict_context(scop, valid);
2610 return scop;
2613 /* Construct a scop for a while, given the scops for the condition
2614 * and the body, the filter identifier and the iteration domain of
2615 * the while loop.
2617 * In particular, the scop for the condition is filtered to depend
2618 * on "id_test" evaluating to true for all previous iterations
2619 * of the loop, while the scop for the body is filtered to depend
2620 * on "id_test" evaluating to true for all iterations up to the
2621 * current iteration.
2622 * The actual filter only imposes that this virtual array has
2623 * value one on the previous or the current iteration.
2624 * The fact that this condition also applies to the previous
2625 * iterations is enforced by an implication.
2627 * These filtered scops are then combined into a single scop.
2629 * "sign" is positive if the iterator increases and negative
2630 * if it decreases.
2632 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2633 struct pet_scop *scop_body, __isl_take isl_id *id_test,
2634 __isl_take isl_set *domain, __isl_take isl_val *inc)
2636 isl_ctx *ctx = isl_set_get_ctx(domain);
2637 isl_space *space;
2638 isl_multi_pw_aff *test_index;
2639 isl_multi_pw_aff *prev;
2640 int sign = isl_val_sgn(inc);
2641 struct pet_scop *scop;
2643 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2644 scop_cond = pet_scop_filter(scop_cond, prev, 1);
2646 space = isl_space_map_from_set(isl_set_get_space(domain));
2647 test_index = isl_multi_pw_aff_identity(space);
2648 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
2649 isl_id_copy(id_test));
2650 scop_body = pet_scop_filter(scop_body, test_index, 1);
2652 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
2653 scop = add_implication(scop, id_test, domain, sign, 1);
2655 return scop;
2658 /* Check if the while loop is of the form
2660 * while (affine expression)
2661 * body
2663 * If so, call extract_affine_while to construct a scop.
2665 * Otherwise, construct a generic while scop, with iteration domain
2666 * { [t] : t >= 0 }. The scop consists of two parts, one for
2667 * evaluating the condition and one for the body.
2668 * The schedule is adjusted to reflect that the condition is evaluated
2669 * before the body is executed and the body is filtered to depend
2670 * on the result of the condition evaluating to true on all iterations
2671 * up to the current iteration, while the evaluation of the condition itself
2672 * is filtered to depend on the result of the condition evaluating to true
2673 * on all previous iterations.
2674 * The context of the scop representing the body is dropped
2675 * because we don't know how many times the body will be executed,
2676 * if at all.
2678 * If the body contains any break, then it is taken into
2679 * account in infinite_domain (if the skip condition is affine)
2680 * or in scop_add_break (if the skip condition is not affine).
2682 * If we were only able to extract part of the body, then simply
2683 * return that part.
2685 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2687 Expr *cond;
2688 int test_nr, stmt_nr;
2689 isl_id *id, *id_test, *id_break_test;
2690 isl_multi_pw_aff *test_index;
2691 isl_set *domain;
2692 isl_aff *ident;
2693 isl_pw_aff *pa;
2694 struct pet_scop *scop, *scop_body;
2695 bool has_var_break;
2697 cond = stmt->getCond();
2698 if (!cond) {
2699 unsupported(stmt);
2700 return NULL;
2703 clear_assignments clear(assigned_value);
2704 clear.TraverseStmt(stmt->getBody());
2706 pa = try_extract_affine_condition(cond);
2707 if (pa)
2708 return extract_affine_while(pa, stmt->getBody());
2710 if (!allow_nested) {
2711 unsupported(stmt);
2712 return NULL;
2715 test_nr = n_test++;
2716 stmt_nr = n_stmt++;
2717 scop_body = extract(stmt->getBody());
2718 if (partial)
2719 return scop_body;
2721 test_index = create_test_index(ctx, test_nr);
2722 scop = extract_non_affine_condition(cond, stmt_nr,
2723 isl_multi_pw_aff_copy(test_index));
2724 scop = scop_add_array(scop, test_index, ast_context);
2725 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2726 isl_multi_pw_aff_free(test_index);
2728 id = isl_id_alloc(ctx, "t", NULL);
2729 domain = infinite_domain(isl_id_copy(id), scop_body);
2730 ident = identity_aff(domain);
2732 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2733 if (has_var_break)
2734 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2736 scop = pet_scop_prefix(scop, 0);
2737 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_aff_copy(ident),
2738 isl_aff_copy(ident), isl_id_copy(id));
2739 scop_body = pet_scop_reset_context(scop_body);
2740 scop_body = pet_scop_prefix(scop_body, 1);
2741 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2742 isl_aff_copy(ident), ident, id);
2744 if (has_var_break) {
2745 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2746 isl_set_copy(domain), isl_val_one(ctx));
2747 scop_body = scop_add_break(scop_body, id_break_test,
2748 isl_set_copy(domain), isl_val_one(ctx));
2750 scop = scop_add_while(scop, scop_body, id_test, domain,
2751 isl_val_one(ctx));
2753 return scop;
2756 /* Check whether "cond" expresses a simple loop bound
2757 * on the only set dimension.
2758 * In particular, if "up" is set then "cond" should contain only
2759 * upper bounds on the set dimension.
2760 * Otherwise, it should contain only lower bounds.
2762 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2764 if (isl_val_is_pos(inc))
2765 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2766 else
2767 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2770 /* Extend a condition on a given iteration of a loop to one that
2771 * imposes the same condition on all previous iterations.
2772 * "domain" expresses the lower [upper] bound on the iterations
2773 * when inc is positive [negative].
2775 * In particular, we construct the condition (when inc is positive)
2777 * forall i' : (domain(i') and i' <= i) => cond(i')
2779 * which is equivalent to
2781 * not exists i' : domain(i') and i' <= i and not cond(i')
2783 * We construct this set by negating cond, applying a map
2785 * { [i'] -> [i] : domain(i') and i' <= i }
2787 * and then negating the result again.
2789 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2790 __isl_take isl_set *domain, __isl_take isl_val *inc)
2792 isl_map *previous_to_this;
2794 if (isl_val_is_pos(inc))
2795 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2796 else
2797 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2799 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2801 cond = isl_set_complement(cond);
2802 cond = isl_set_apply(cond, previous_to_this);
2803 cond = isl_set_complement(cond);
2805 isl_val_free(inc);
2807 return cond;
2810 /* Construct a domain of the form
2812 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2814 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2815 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2817 isl_aff *aff;
2818 isl_space *dim;
2819 isl_set *set;
2821 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2822 dim = isl_pw_aff_get_domain_space(init);
2823 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2824 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2825 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2827 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2828 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2829 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2830 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2832 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2834 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2836 return isl_set_params(set);
2839 /* Assuming "cond" represents a bound on a loop where the loop
2840 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2841 * is possible.
2843 * Under the given assumptions, wrapping is only possible if "cond" allows
2844 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2845 * increasing iterator and 0 in case of a decreasing iterator.
2847 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2848 __isl_keep isl_val *inc)
2850 bool cw;
2851 isl_ctx *ctx;
2852 isl_val *limit;
2853 isl_set *test;
2855 test = isl_set_copy(cond);
2857 ctx = isl_set_get_ctx(test);
2858 if (isl_val_is_neg(inc))
2859 limit = isl_val_zero(ctx);
2860 else {
2861 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2862 limit = isl_val_2exp(limit);
2863 limit = isl_val_sub_ui(limit, 1);
2866 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2867 cw = !isl_set_is_empty(test);
2868 isl_set_free(test);
2870 return cw;
2873 /* Given a one-dimensional space, construct the following affine expression
2874 * on this space
2876 * { [v] -> [v mod 2^width] }
2878 * where width is the number of bits used to represent the values
2879 * of the unsigned variable "iv".
2881 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2882 ValueDecl *iv)
2884 isl_ctx *ctx;
2885 isl_val *mod;
2886 isl_aff *aff;
2888 ctx = isl_space_get_ctx(dim);
2889 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2890 mod = isl_val_2exp(mod);
2892 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2893 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2894 aff = isl_aff_mod_val(aff, mod);
2896 return aff;
2899 /* Project out the parameter "id" from "set".
2901 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2902 __isl_keep isl_id *id)
2904 int pos;
2906 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2907 if (pos >= 0)
2908 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2910 return set;
2913 /* Compute the set of parameters for which "set1" is a subset of "set2".
2915 * set1 is a subset of set2 if
2917 * forall i in set1 : i in set2
2919 * or
2921 * not exists i in set1 and i not in set2
2923 * i.e.,
2925 * not exists i in set1 \ set2
2927 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2928 __isl_take isl_set *set2)
2930 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2933 /* Compute the set of parameter values for which "cond" holds
2934 * on the next iteration for each element of "dom".
2936 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2937 * and then compute the set of parameters for which the result is a subset
2938 * of "cond".
2940 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2941 __isl_take isl_set *dom, __isl_take isl_val *inc)
2943 isl_space *space;
2944 isl_aff *aff;
2945 isl_map *next;
2947 space = isl_set_get_space(dom);
2948 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2949 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2950 aff = isl_aff_add_constant_val(aff, inc);
2951 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2953 dom = isl_set_apply(dom, next);
2955 return enforce_subset(dom, cond);
2958 /* Does "id" refer to a nested access?
2960 static bool is_nested_parameter(__isl_keep isl_id *id)
2962 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2965 /* Does parameter "pos" of "space" refer to a nested access?
2967 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2969 bool nested;
2970 isl_id *id;
2972 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2973 nested = is_nested_parameter(id);
2974 isl_id_free(id);
2976 return nested;
2979 /* Does "space" involve any parameters that refer to nested
2980 * accesses, i.e., parameters with no name?
2982 static bool has_nested(__isl_keep isl_space *space)
2984 int nparam;
2986 nparam = isl_space_dim(space, isl_dim_param);
2987 for (int i = 0; i < nparam; ++i)
2988 if (is_nested_parameter(space, i))
2989 return true;
2991 return false;
2994 /* Does "pa" involve any parameters that refer to nested
2995 * accesses, i.e., parameters with no name?
2997 static bool has_nested(__isl_keep isl_pw_aff *pa)
2999 isl_space *space;
3000 bool nested;
3002 space = isl_pw_aff_get_space(pa);
3003 nested = has_nested(space);
3004 isl_space_free(space);
3006 return nested;
3009 /* Construct a pet_scop for a for statement.
3010 * The for loop is required to be of the form
3012 * for (i = init; condition; ++i)
3014 * or
3016 * for (i = init; condition; --i)
3018 * The initialization of the for loop should either be an assignment
3019 * to an integer variable, or a declaration of such a variable with
3020 * initialization.
3022 * The condition is allowed to contain nested accesses, provided
3023 * they are not being written to inside the body of the loop.
3024 * Otherwise, or if the condition is otherwise non-affine, the for loop is
3025 * essentially treated as a while loop, with iteration domain
3026 * { [i] : i >= init }.
3028 * We extract a pet_scop for the body and then embed it in a loop with
3029 * iteration domain and schedule
3031 * { [i] : i >= init and condition' }
3032 * { [i] -> [i] }
3034 * or
3036 * { [i] : i <= init and condition' }
3037 * { [i] -> [-i] }
3039 * Where condition' is equal to condition if the latter is
3040 * a simple upper [lower] bound and a condition that is extended
3041 * to apply to all previous iterations otherwise.
3043 * If the condition is non-affine, then we drop the condition from the
3044 * iteration domain and instead create a separate statement
3045 * for evaluating the condition. The body is then filtered to depend
3046 * on the result of the condition evaluating to true on all iterations
3047 * up to the current iteration, while the evaluation the condition itself
3048 * is filtered to depend on the result of the condition evaluating to true
3049 * on all previous iterations.
3050 * The context of the scop representing the body is dropped
3051 * because we don't know how many times the body will be executed,
3052 * if at all.
3054 * If the stride of the loop is not 1, then "i >= init" is replaced by
3056 * (exists a: i = init + stride * a and a >= 0)
3058 * If the loop iterator i is unsigned, then wrapping may occur.
3059 * We therefore use a virtual iterator instead that does not wrap.
3060 * However, the condition in the code applies
3061 * to the wrapped value, so we need to change condition(i)
3062 * into condition([i % 2^width]). Similarly, we replace all accesses
3063 * to the original iterator by the wrapping of the virtual iterator.
3064 * Note that there may be no need to perform this final wrapping
3065 * if the loop condition (after wrapping) satisfies certain conditions.
3066 * However, the is_simple_bound condition is not enough since it doesn't
3067 * check if there even is an upper bound.
3069 * Wrapping on unsigned iterators can be avoided entirely if
3070 * loop condition is simple, the loop iterator is incremented
3071 * [decremented] by one and the last value before wrapping cannot
3072 * possibly satisfy the loop condition.
3074 * Before extracting a pet_scop from the body we remove all
3075 * assignments in assigned_value to variables that are assigned
3076 * somewhere in the body of the loop.
3078 * Valid parameters for a for loop are those for which the initial
3079 * value itself, the increment on each domain iteration and
3080 * the condition on both the initial value and
3081 * the result of incrementing the iterator for each iteration of the domain
3082 * can be evaluated.
3083 * If the loop condition is non-affine, then we only consider validity
3084 * of the initial value.
3086 * If the body contains any break, then we keep track of it in "skip"
3087 * (if the skip condition is affine) or it is handled in scop_add_break
3088 * (if the skip condition is not affine).
3089 * Note that the affine break condition needs to be considered with
3090 * respect to previous iterations in the virtual domain (if any).
3092 * If we were only able to extract part of the body, then simply
3093 * return that part.
3095 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
3097 BinaryOperator *ass;
3098 Decl *decl;
3099 Stmt *init;
3100 Expr *lhs, *rhs;
3101 ValueDecl *iv;
3102 isl_local_space *ls;
3103 isl_set *domain;
3104 isl_aff *sched;
3105 isl_set *cond = NULL;
3106 isl_set *skip = NULL;
3107 isl_id *id, *id_test = NULL, *id_break_test;
3108 struct pet_scop *scop, *scop_cond = NULL;
3109 assigned_value_cache cache(assigned_value);
3110 isl_val *inc;
3111 bool was_assigned;
3112 bool is_one;
3113 bool is_unsigned;
3114 bool is_simple;
3115 bool is_virtual;
3116 bool has_affine_break;
3117 bool has_var_break;
3118 isl_aff *wrap = NULL;
3119 isl_pw_aff *pa, *pa_inc, *init_val;
3120 isl_set *valid_init;
3121 isl_set *valid_cond;
3122 isl_set *valid_cond_init;
3123 isl_set *valid_cond_next;
3124 isl_set *valid_inc;
3125 int stmt_id;
3127 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
3128 return extract_infinite_for(stmt);
3130 init = stmt->getInit();
3131 if (!init) {
3132 unsupported(stmt);
3133 return NULL;
3135 if ((ass = initialization_assignment(init)) != NULL) {
3136 iv = extract_induction_variable(ass);
3137 if (!iv)
3138 return NULL;
3139 lhs = ass->getLHS();
3140 rhs = ass->getRHS();
3141 } else if ((decl = initialization_declaration(init)) != NULL) {
3142 VarDecl *var = extract_induction_variable(init, decl);
3143 if (!var)
3144 return NULL;
3145 iv = var;
3146 rhs = var->getInit();
3147 lhs = create_DeclRefExpr(var);
3148 } else {
3149 unsupported(stmt->getInit());
3150 return NULL;
3153 assigned_value.erase(iv);
3154 clear_assignments clear(assigned_value);
3155 clear.TraverseStmt(stmt->getBody());
3157 was_assigned = assigned_value.find(iv) != assigned_value.end();
3158 clear_assignment(assigned_value, iv);
3159 init_val = extract_affine(rhs);
3160 if (!was_assigned)
3161 assigned_value.erase(iv);
3162 if (!init_val)
3163 return NULL;
3165 pa_inc = extract_increment(stmt, iv);
3166 if (!pa_inc) {
3167 isl_pw_aff_free(init_val);
3168 return NULL;
3171 inc = NULL;
3172 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
3173 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
3174 isl_pw_aff_free(init_val);
3175 isl_pw_aff_free(pa_inc);
3176 unsupported(stmt->getInc());
3177 isl_val_free(inc);
3178 return NULL;
3181 pa = try_extract_nested_condition(stmt->getCond());
3182 if (allow_nested && (!pa || has_nested(pa)))
3183 stmt_id = n_stmt++;
3185 scop = extract(stmt->getBody());
3186 if (partial) {
3187 isl_pw_aff_free(init_val);
3188 isl_pw_aff_free(pa_inc);
3189 isl_pw_aff_free(pa);
3190 isl_val_free(inc);
3191 return scop;
3194 valid_inc = isl_pw_aff_domain(pa_inc);
3196 is_unsigned = iv->getType()->isUnsignedIntegerType();
3198 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
3200 has_affine_break = scop &&
3201 pet_scop_has_affine_skip(scop, pet_skip_later);
3202 if (has_affine_break)
3203 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
3204 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
3205 if (has_var_break)
3206 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
3208 if (pa && !is_nested_allowed(pa, scop)) {
3209 isl_pw_aff_free(pa);
3210 pa = NULL;
3213 if (!allow_nested && !pa)
3214 pa = try_extract_affine_condition(stmt->getCond());
3215 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3216 cond = isl_pw_aff_non_zero_set(pa);
3217 if (allow_nested && !cond) {
3218 isl_multi_pw_aff *test_index;
3219 int save_n_stmt = n_stmt;
3220 test_index = create_test_index(ctx, n_test++);
3221 n_stmt = stmt_id;
3222 scop_cond = extract_non_affine_condition(stmt->getCond(),
3223 n_stmt++, isl_multi_pw_aff_copy(test_index));
3224 n_stmt = save_n_stmt;
3225 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
3226 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
3227 isl_dim_out);
3228 isl_multi_pw_aff_free(test_index);
3229 scop_cond = pet_scop_prefix(scop_cond, 0);
3230 scop = pet_scop_reset_context(scop);
3231 scop = pet_scop_prefix(scop, 1);
3232 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
3235 cond = embed(cond, isl_id_copy(id));
3236 skip = embed(skip, isl_id_copy(id));
3237 valid_cond = isl_set_coalesce(valid_cond);
3238 valid_cond = embed(valid_cond, isl_id_copy(id));
3239 valid_inc = embed(valid_inc, isl_id_copy(id));
3240 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
3241 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
3243 valid_cond_init = enforce_subset(
3244 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
3245 isl_set_copy(valid_cond));
3246 if (is_one && !is_virtual) {
3247 isl_pw_aff_free(init_val);
3248 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
3249 lhs, rhs, init);
3250 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3251 valid_init = set_project_out_by_id(valid_init, id);
3252 domain = isl_pw_aff_non_zero_set(pa);
3253 } else {
3254 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
3255 domain = strided_domain(isl_id_copy(id), init_val,
3256 isl_val_copy(inc));
3259 domain = embed(domain, isl_id_copy(id));
3260 if (is_virtual) {
3261 isl_map *rev_wrap;
3262 wrap = compute_wrapping(isl_set_get_space(cond), iv);
3263 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
3264 rev_wrap = isl_map_reverse(rev_wrap);
3265 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
3266 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
3267 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
3268 valid_inc = isl_set_apply(valid_inc, rev_wrap);
3270 is_simple = is_simple_bound(cond, inc);
3271 if (!is_simple) {
3272 cond = isl_set_gist(cond, isl_set_copy(domain));
3273 is_simple = is_simple_bound(cond, inc);
3275 if (!is_simple)
3276 cond = valid_for_each_iteration(cond,
3277 isl_set_copy(domain), isl_val_copy(inc));
3278 domain = isl_set_intersect(domain, cond);
3279 if (has_affine_break) {
3280 skip = isl_set_intersect(skip , isl_set_copy(domain));
3281 skip = after(skip, isl_val_sgn(inc));
3282 domain = isl_set_subtract(domain, skip);
3284 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
3285 ls = isl_local_space_from_space(isl_set_get_space(domain));
3286 sched = isl_aff_var_on_domain(ls, isl_dim_set, 0);
3287 if (isl_val_is_neg(inc))
3288 sched = isl_aff_neg(sched);
3290 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
3291 isl_val_copy(inc));
3292 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
3294 if (!is_virtual)
3295 wrap = identity_aff(domain);
3297 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
3298 isl_aff_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
3299 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
3300 scop = resolve_nested(scop);
3301 if (has_var_break)
3302 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
3303 isl_val_copy(inc));
3304 if (id_test) {
3305 scop = scop_add_while(scop_cond, scop, id_test, domain,
3306 isl_val_copy(inc));
3307 isl_set_free(valid_inc);
3308 } else {
3309 scop = pet_scop_restrict_context(scop, valid_inc);
3310 scop = pet_scop_restrict_context(scop, valid_cond_next);
3311 scop = pet_scop_restrict_context(scop, valid_cond_init);
3312 isl_set_free(domain);
3314 clear_assignment(assigned_value, iv);
3316 isl_val_free(inc);
3318 scop = pet_scop_restrict_context(scop, valid_init);
3320 return scop;
3323 /* Try and construct a pet_scop corresponding to a compound statement.
3325 * "skip_declarations" is set if we should skip initial declarations
3326 * in the children of the compound statements. This then implies
3327 * that this sequence of children should not be treated as a block
3328 * since the initial statements may be skipped.
3330 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
3332 return extract(stmt->children(), !skip_declarations, skip_declarations);
3335 /* Does parameter "pos" of "map" refer to a nested access?
3337 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
3339 bool nested;
3340 isl_id *id;
3342 id = isl_map_get_dim_id(map, isl_dim_param, pos);
3343 nested = is_nested_parameter(id);
3344 isl_id_free(id);
3346 return nested;
3349 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
3351 static int n_nested_parameter(__isl_keep isl_space *space)
3353 int n = 0;
3354 int nparam;
3356 nparam = isl_space_dim(space, isl_dim_param);
3357 for (int i = 0; i < nparam; ++i)
3358 if (is_nested_parameter(space, i))
3359 ++n;
3361 return n;
3364 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
3366 static int n_nested_parameter(__isl_keep isl_map *map)
3368 isl_space *space;
3369 int n;
3371 space = isl_map_get_space(map);
3372 n = n_nested_parameter(space);
3373 isl_space_free(space);
3375 return n;
3378 /* For each nested access parameter in "space",
3379 * construct a corresponding pet_expr, place it in args and
3380 * record its position in "param2pos".
3381 * "n_arg" is the number of elements that are already in args.
3382 * The position recorded in "param2pos" takes this number into account.
3383 * If the pet_expr corresponding to a parameter is identical to
3384 * the pet_expr corresponding to an earlier parameter, then these two
3385 * parameters are made to refer to the same element in args.
3387 * Return the final number of elements in args or -1 if an error has occurred.
3389 int PetScan::extract_nested(__isl_keep isl_space *space,
3390 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
3392 int nparam;
3394 nparam = isl_space_dim(space, isl_dim_param);
3395 for (int i = 0; i < nparam; ++i) {
3396 int j;
3397 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3398 Expr *nested;
3400 if (!is_nested_parameter(id)) {
3401 isl_id_free(id);
3402 continue;
3405 nested = (Expr *) isl_id_get_user(id);
3406 args[n_arg] = extract_expr(nested);
3407 isl_id_free(id);
3408 if (!args[n_arg])
3409 return -1;
3411 for (j = 0; j < n_arg; ++j)
3412 if (pet_expr_is_equal(args[j], args[n_arg]))
3413 break;
3415 if (j < n_arg) {
3416 pet_expr_free(args[n_arg]);
3417 args[n_arg] = NULL;
3418 param2pos[i] = j;
3419 } else
3420 param2pos[i] = n_arg++;
3423 return n_arg;
3426 /* For each nested access parameter in the access relations in "expr",
3427 * construct a corresponding pet_expr, place it in expr->args and
3428 * record its position in "param2pos".
3429 * n is the number of nested access parameters.
3431 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
3432 std::map<int,int> &param2pos)
3434 isl_space *space;
3436 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
3437 expr->n_arg = n;
3438 if (!expr->args)
3439 goto error;
3441 space = pet_expr_access_get_parameter_space(expr);
3442 n = extract_nested(space, 0, expr->args, param2pos);
3443 isl_space_free(space);
3445 if (n < 0)
3446 goto error;
3448 expr->n_arg = n;
3449 return expr;
3450 error:
3451 pet_expr_free(expr);
3452 return NULL;
3455 /* Look for parameters in any access relation in "expr" that
3456 * refer to nested accesses. In particular, these are
3457 * parameters with no name.
3459 * If there are any such parameters, then the domain of the index
3460 * expression and the access relation, which is still [] at this point,
3461 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
3462 * (after identifying identical nested accesses).
3464 * This transformation is performed in several steps.
3465 * We first extract the arguments in extract_nested.
3466 * param2pos maps the original parameter position to the position
3467 * of the argument.
3468 * Then we move these parameters to input dimensions.
3469 * t2pos maps the positions of these temporary input dimensions
3470 * to the positions of the corresponding arguments.
3471 * Finally, we express these temporary dimensions in terms of the domain
3472 * [[] -> [t_1,...,t_n]] and precompose index expression and access
3473 * relations with this function.
3475 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
3477 int n;
3478 int nparam;
3479 isl_space *space;
3480 isl_local_space *ls;
3481 isl_aff *aff;
3482 isl_multi_aff *ma;
3483 std::map<int,int> param2pos;
3484 std::map<int,int> t2pos;
3486 if (!expr)
3487 return expr;
3489 for (int i = 0; i < expr->n_arg; ++i) {
3490 expr->args[i] = resolve_nested(expr->args[i]);
3491 if (!expr->args[i]) {
3492 pet_expr_free(expr);
3493 return NULL;
3497 if (expr->type != pet_expr_access)
3498 return expr;
3500 space = pet_expr_access_get_parameter_space(expr);
3501 n = n_nested_parameter(space);
3502 isl_space_free(space);
3503 if (n == 0)
3504 return expr;
3506 expr = extract_nested(expr, n, param2pos);
3507 if (!expr)
3508 return NULL;
3510 expr = pet_expr_access_align_params(expr);
3511 if (!expr)
3512 return NULL;
3514 n = 0;
3515 space = pet_expr_access_get_parameter_space(expr);
3516 nparam = isl_space_dim(space, isl_dim_param);
3517 for (int i = nparam - 1; i >= 0; --i) {
3518 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3519 if (!is_nested_parameter(id)) {
3520 isl_id_free(id);
3521 continue;
3524 expr = pet_expr_access_move_dims(expr,
3525 isl_dim_in, n, isl_dim_param, i, 1);
3526 t2pos[n] = param2pos[i];
3527 n++;
3529 isl_id_free(id);
3531 isl_space_free(space);
3533 space = pet_expr_access_get_parameter_space(expr);
3534 space = isl_space_set_from_params(space);
3535 space = isl_space_add_dims(space, isl_dim_set, expr->n_arg);
3536 space = isl_space_wrap(isl_space_from_range(space));
3537 ls = isl_local_space_from_space(isl_space_copy(space));
3538 space = isl_space_from_domain(space);
3539 space = isl_space_add_dims(space, isl_dim_out, n);
3540 ma = isl_multi_aff_zero(space);
3542 for (int i = 0; i < n; ++i) {
3543 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3544 isl_dim_set, t2pos[i]);
3545 ma = isl_multi_aff_set_aff(ma, i, aff);
3547 isl_local_space_free(ls);
3549 expr = pet_expr_access_pullback_multi_aff(expr, ma);
3551 return expr;
3554 /* Return the file offset of the expansion location of "Loc".
3556 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3558 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3561 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3563 /* Return a SourceLocation for the location after the first semicolon
3564 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3565 * call it and also skip trailing spaces and newline.
3567 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3568 const LangOptions &LO)
3570 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3573 #else
3575 /* Return a SourceLocation for the location after the first semicolon
3576 * after "loc". If Lexer::findLocationAfterToken is not available,
3577 * we look in the underlying character data for the first semicolon.
3579 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3580 const LangOptions &LO)
3582 const char *semi;
3583 const char *s = SM.getCharacterData(loc);
3585 semi = strchr(s, ';');
3586 if (!semi)
3587 return SourceLocation();
3588 return loc.getFileLocWithOffset(semi + 1 - s);
3591 #endif
3593 /* If the token at "loc" is the first token on the line, then return
3594 * a location referring to the start of the line.
3595 * Otherwise, return "loc".
3597 * This function is used to extend a scop to the start of the line
3598 * if the first token of the scop is also the first token on the line.
3600 * We look for the first token on the line. If its location is equal to "loc",
3601 * then the latter is the location of the first token on the line.
3603 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3604 SourceManager &SM, const LangOptions &LO)
3606 std::pair<FileID, unsigned> file_offset_pair;
3607 llvm::StringRef file;
3608 const char *pos;
3609 Token tok;
3610 SourceLocation token_loc, line_loc;
3611 int col;
3613 loc = SM.getExpansionLoc(loc);
3614 col = SM.getExpansionColumnNumber(loc);
3615 line_loc = loc.getLocWithOffset(1 - col);
3616 file_offset_pair = SM.getDecomposedLoc(line_loc);
3617 file = SM.getBufferData(file_offset_pair.first, NULL);
3618 pos = file.data() + file_offset_pair.second;
3620 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3621 file.begin(), pos, file.end());
3622 lexer.LexFromRawLexer(tok);
3623 token_loc = tok.getLocation();
3625 if (token_loc == loc)
3626 return line_loc;
3627 else
3628 return loc;
3631 /* Update start and end of "scop" to include the region covered by "range".
3632 * If "skip_semi" is set, then we assume "range" is followed by
3633 * a semicolon and also include this semicolon.
3635 struct pet_scop *PetScan::update_scop_start_end(struct pet_scop *scop,
3636 SourceRange range, bool skip_semi)
3638 SourceLocation loc = range.getBegin();
3639 SourceManager &SM = PP.getSourceManager();
3640 const LangOptions &LO = PP.getLangOpts();
3641 unsigned start, end;
3643 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3644 start = getExpansionOffset(SM, loc);
3645 loc = range.getEnd();
3646 if (skip_semi)
3647 loc = location_after_semi(loc, SM, LO);
3648 else
3649 loc = PP.getLocForEndOfToken(loc);
3650 end = getExpansionOffset(SM, loc);
3652 scop = pet_scop_update_start_end(scop, start, end);
3653 return scop;
3656 /* Convert a top-level pet_expr to a pet_scop with one statement.
3657 * This mainly involves resolving nested expression parameters
3658 * and setting the name of the iteration space.
3659 * The name is given by "label" if it is non-NULL. Otherwise,
3660 * it is of the form S_<n_stmt>.
3661 * start and end of the pet_scop are derived from those of "stmt".
3662 * If "stmt" is an expression statement, then its range does not
3663 * include the semicolon, while it should be included in the pet_scop.
3665 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
3666 __isl_take isl_id *label)
3668 struct pet_stmt *ps;
3669 struct pet_scop *scop;
3670 SourceLocation loc = stmt->getLocStart();
3671 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3672 bool skip_semi;
3674 expr = resolve_nested(expr);
3675 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
3676 scop = pet_scop_from_pet_stmt(ctx, ps);
3678 skip_semi = isa<Expr>(stmt);
3679 scop = update_scop_start_end(scop, stmt->getSourceRange(), skip_semi);
3680 return scop;
3683 /* Check if we can extract an affine expression from "expr".
3684 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3685 * We turn on autodetection so that we won't generate any warnings
3686 * and turn off nesting, so that we won't accept any non-affine constructs.
3688 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3690 isl_pw_aff *pwaff;
3691 int save_autodetect = options->autodetect;
3692 bool save_nesting = nesting_enabled;
3694 options->autodetect = 1;
3695 nesting_enabled = false;
3697 pwaff = extract_affine(expr);
3699 options->autodetect = save_autodetect;
3700 nesting_enabled = save_nesting;
3702 return pwaff;
3705 /* Check if we can extract an affine constraint from "expr".
3706 * Return the constraint as an isl_set if we can and NULL otherwise.
3707 * We turn on autodetection so that we won't generate any warnings
3708 * and turn off nesting, so that we won't accept any non-affine constructs.
3710 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3712 isl_pw_aff *cond;
3713 int save_autodetect = options->autodetect;
3714 bool save_nesting = nesting_enabled;
3716 options->autodetect = 1;
3717 nesting_enabled = false;
3719 cond = extract_condition(expr);
3721 options->autodetect = save_autodetect;
3722 nesting_enabled = save_nesting;
3724 return cond;
3727 /* Check whether "expr" is an affine constraint.
3729 bool PetScan::is_affine_condition(Expr *expr)
3731 isl_pw_aff *cond;
3733 cond = try_extract_affine_condition(expr);
3734 isl_pw_aff_free(cond);
3736 return cond != NULL;
3739 /* Check if we can extract a condition from "expr".
3740 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3741 * If allow_nested is set, then the condition may involve parameters
3742 * corresponding to nested accesses.
3743 * We turn on autodetection so that we won't generate any warnings.
3745 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3747 isl_pw_aff *cond;
3748 int save_autodetect = options->autodetect;
3749 bool save_nesting = nesting_enabled;
3751 options->autodetect = 1;
3752 nesting_enabled = allow_nested;
3753 cond = extract_condition(expr);
3755 options->autodetect = save_autodetect;
3756 nesting_enabled = save_nesting;
3758 return cond;
3761 /* If the top-level expression of "stmt" is an assignment, then
3762 * return that assignment as a BinaryOperator.
3763 * Otherwise return NULL.
3765 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3767 BinaryOperator *ass;
3769 if (!stmt)
3770 return NULL;
3771 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3772 return NULL;
3774 ass = cast<BinaryOperator>(stmt);
3775 if(ass->getOpcode() != BO_Assign)
3776 return NULL;
3778 return ass;
3781 /* Check if the given if statement is a conditional assignement
3782 * with a non-affine condition. If so, construct a pet_scop
3783 * corresponding to this conditional assignment. Otherwise return NULL.
3785 * In particular we check if "stmt" is of the form
3787 * if (condition)
3788 * a = f(...);
3789 * else
3790 * a = g(...);
3792 * where a is some array or scalar access.
3793 * The constructed pet_scop then corresponds to the expression
3795 * a = condition ? f(...) : g(...)
3797 * All access relations in f(...) are intersected with condition
3798 * while all access relation in g(...) are intersected with the complement.
3800 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3802 BinaryOperator *ass_then, *ass_else;
3803 isl_multi_pw_aff *write_then, *write_else;
3804 isl_set *cond, *comp;
3805 isl_multi_pw_aff *index;
3806 isl_pw_aff *pa;
3807 int equal;
3808 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3809 bool save_nesting = nesting_enabled;
3811 if (!options->detect_conditional_assignment)
3812 return NULL;
3814 ass_then = top_assignment_or_null(stmt->getThen());
3815 ass_else = top_assignment_or_null(stmt->getElse());
3817 if (!ass_then || !ass_else)
3818 return NULL;
3820 if (is_affine_condition(stmt->getCond()))
3821 return NULL;
3823 write_then = extract_index(ass_then->getLHS());
3824 write_else = extract_index(ass_else->getLHS());
3826 equal = isl_multi_pw_aff_plain_is_equal(write_then, write_else);
3827 isl_multi_pw_aff_free(write_else);
3828 if (equal < 0 || !equal) {
3829 isl_multi_pw_aff_free(write_then);
3830 return NULL;
3833 nesting_enabled = allow_nested;
3834 pa = extract_condition(stmt->getCond());
3835 nesting_enabled = save_nesting;
3836 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3837 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3838 index = isl_multi_pw_aff_from_range(isl_multi_pw_aff_from_pw_aff(pa));
3840 pe_cond = pet_expr_from_index(index);
3842 pe_then = extract_expr(ass_then->getRHS());
3843 pe_then = pet_expr_restrict(pe_then, cond);
3844 pe_else = extract_expr(ass_else->getRHS());
3845 pe_else = pet_expr_restrict(pe_else, comp);
3847 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
3848 pe_write = pet_expr_from_index_and_depth(write_then,
3849 extract_depth(write_then));
3850 if (pe_write) {
3851 pe_write->acc.write = 1;
3852 pe_write->acc.read = 0;
3854 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
3855 return extract(stmt, pe);
3858 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3859 * evaluating "cond" and writing the result to a virtual scalar,
3860 * as expressed by "index".
3862 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond, int stmt_nr,
3863 __isl_take isl_multi_pw_aff *index)
3865 struct pet_expr *expr, *write;
3866 struct pet_stmt *ps;
3867 SourceLocation loc = cond->getLocStart();
3868 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3870 write = pet_expr_from_index(index);
3871 if (write) {
3872 write->acc.write = 1;
3873 write->acc.read = 0;
3875 expr = extract_expr(cond);
3876 expr = resolve_nested(expr);
3877 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
3878 ps = pet_stmt_from_pet_expr(ctx, line, NULL, stmt_nr, expr);
3879 return pet_scop_from_pet_stmt(ctx, ps);
3882 extern "C" {
3883 static struct pet_expr *embed_access(struct pet_expr *expr, void *user);
3886 /* Precompose the access relation and the index expression associated
3887 * to "expr" with the function pointed to by "user",
3888 * thereby embedding the access relation in the domain of this function.
3889 * The initial domain of the access relation and the index expression
3890 * is the zero-dimensional domain.
3892 static struct pet_expr *embed_access(struct pet_expr *expr, void *user)
3894 isl_multi_aff *ma = (isl_multi_aff *) user;
3896 return pet_expr_access_pullback_multi_aff(expr, isl_multi_aff_copy(ma));
3899 /* Precompose all access relations in "expr" with "ma", thereby
3900 * embedding them in the domain of "ma".
3902 static struct pet_expr *embed(struct pet_expr *expr,
3903 __isl_keep isl_multi_aff *ma)
3905 return pet_expr_map_access(expr, &embed_access, ma);
3908 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3910 static int n_nested_parameter(__isl_keep isl_set *set)
3912 isl_space *space;
3913 int n;
3915 space = isl_set_get_space(set);
3916 n = n_nested_parameter(space);
3917 isl_space_free(space);
3919 return n;
3922 /* Remove all parameters from "map" that refer to nested accesses.
3924 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
3926 int nparam;
3927 isl_space *space;
3929 space = isl_map_get_space(map);
3930 nparam = isl_space_dim(space, isl_dim_param);
3931 for (int i = nparam - 1; i >= 0; --i)
3932 if (is_nested_parameter(space, i))
3933 map = isl_map_project_out(map, isl_dim_param, i, 1);
3934 isl_space_free(space);
3936 return map;
3939 /* Remove all parameters from "mpa" that refer to nested accesses.
3941 static __isl_give isl_multi_pw_aff *remove_nested_parameters(
3942 __isl_take isl_multi_pw_aff *mpa)
3944 int nparam;
3945 isl_space *space;
3947 space = isl_multi_pw_aff_get_space(mpa);
3948 nparam = isl_space_dim(space, isl_dim_param);
3949 for (int i = nparam - 1; i >= 0; --i) {
3950 if (!is_nested_parameter(space, i))
3951 continue;
3952 mpa = isl_multi_pw_aff_drop_dims(mpa, isl_dim_param, i, 1);
3954 isl_space_free(space);
3956 return mpa;
3959 /* Remove all parameters from the index expression and access relation of "expr"
3960 * that refer to nested accesses.
3962 static struct pet_expr *remove_nested_parameters(struct pet_expr *expr)
3964 expr->acc.access = remove_nested_parameters(expr->acc.access);
3965 expr->acc.index = remove_nested_parameters(expr->acc.index);
3966 if (!expr->acc.access || !expr->acc.index)
3967 goto error;
3969 return expr;
3970 error:
3971 pet_expr_free(expr);
3972 return NULL;
3975 extern "C" {
3976 static struct pet_expr *expr_remove_nested_parameters(
3977 struct pet_expr *expr, void *user);
3980 static struct pet_expr *expr_remove_nested_parameters(
3981 struct pet_expr *expr, void *user)
3983 return remove_nested_parameters(expr);
3986 /* Remove all nested access parameters from the schedule and all
3987 * accesses of "stmt".
3988 * There is no need to remove them from the domain as these parameters
3989 * have already been removed from the domain when this function is called.
3991 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
3993 if (!stmt)
3994 return NULL;
3995 stmt->schedule = remove_nested_parameters(stmt->schedule);
3996 stmt->body = pet_expr_map_access(stmt->body,
3997 &expr_remove_nested_parameters, NULL);
3998 if (!stmt->schedule || !stmt->body)
3999 goto error;
4000 for (int i = 0; i < stmt->n_arg; ++i) {
4001 stmt->args[i] = pet_expr_map_access(stmt->args[i],
4002 &expr_remove_nested_parameters, NULL);
4003 if (!stmt->args[i])
4004 goto error;
4007 return stmt;
4008 error:
4009 pet_stmt_free(stmt);
4010 return NULL;
4013 /* For each nested access parameter in the domain of "stmt",
4014 * construct a corresponding pet_expr, place it before the original
4015 * elements in stmt->args and record its position in "param2pos".
4016 * n is the number of nested access parameters.
4018 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
4019 std::map<int,int> &param2pos)
4021 int i;
4022 isl_space *space;
4023 int n_arg;
4024 struct pet_expr **args;
4026 n_arg = stmt->n_arg;
4027 args = isl_calloc_array(ctx, struct pet_expr *, n + n_arg);
4028 if (!args)
4029 goto error;
4031 space = isl_set_get_space(stmt->domain);
4032 n_arg = extract_nested(space, 0, args, param2pos);
4033 isl_space_free(space);
4035 if (n_arg < 0)
4036 goto error;
4038 for (i = 0; i < stmt->n_arg; ++i)
4039 args[n_arg + i] = stmt->args[i];
4040 free(stmt->args);
4041 stmt->args = args;
4042 stmt->n_arg += n_arg;
4044 return stmt;
4045 error:
4046 if (args) {
4047 for (i = 0; i < n; ++i)
4048 pet_expr_free(args[i]);
4049 free(args);
4051 pet_stmt_free(stmt);
4052 return NULL;
4055 /* Check whether any of the arguments i of "stmt" starting at position "n"
4056 * is equal to one of the first "n" arguments j.
4057 * If so, combine the constraints on arguments i and j and remove
4058 * argument i.
4060 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
4062 int i, j;
4063 isl_map *map;
4065 if (!stmt)
4066 return NULL;
4067 if (n == 0)
4068 return stmt;
4069 if (n == stmt->n_arg)
4070 return stmt;
4072 map = isl_set_unwrap(stmt->domain);
4074 for (i = stmt->n_arg - 1; i >= n; --i) {
4075 for (j = 0; j < n; ++j)
4076 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
4077 break;
4078 if (j >= n)
4079 continue;
4081 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
4082 map = isl_map_project_out(map, isl_dim_out, i, 1);
4084 pet_expr_free(stmt->args[i]);
4085 for (j = i; j + 1 < stmt->n_arg; ++j)
4086 stmt->args[j] = stmt->args[j + 1];
4087 stmt->n_arg--;
4090 stmt->domain = isl_map_wrap(map);
4091 if (!stmt->domain)
4092 goto error;
4093 return stmt;
4094 error:
4095 pet_stmt_free(stmt);
4096 return NULL;
4099 /* Look for parameters in the iteration domain of "stmt" that
4100 * refer to nested accesses. In particular, these are
4101 * parameters with no name.
4103 * If there are any such parameters, then as many extra variables
4104 * (after identifying identical nested accesses) are inserted in the
4105 * range of the map wrapped inside the domain, before the original variables.
4106 * If the original domain is not a wrapped map, then a new wrapped
4107 * map is created with zero output dimensions.
4108 * The parameters are then equated to the corresponding output dimensions
4109 * and subsequently projected out, from the iteration domain,
4110 * the schedule and the access relations.
4111 * For each of the output dimensions, a corresponding argument
4112 * expression is inserted. Initially they are created with
4113 * a zero-dimensional domain, so they have to be embedded
4114 * in the current iteration domain.
4115 * param2pos maps the position of the parameter to the position
4116 * of the corresponding output dimension in the wrapped map.
4118 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
4120 int n;
4121 int nparam;
4122 unsigned n_arg;
4123 isl_map *map;
4124 isl_space *space;
4125 isl_multi_aff *ma;
4126 std::map<int,int> param2pos;
4128 if (!stmt)
4129 return NULL;
4131 n = n_nested_parameter(stmt->domain);
4132 if (n == 0)
4133 return stmt;
4135 n_arg = stmt->n_arg;
4136 stmt = extract_nested(stmt, n, param2pos);
4137 if (!stmt)
4138 return NULL;
4140 n = stmt->n_arg - n_arg;
4141 nparam = isl_set_dim(stmt->domain, isl_dim_param);
4142 if (isl_set_is_wrapping(stmt->domain))
4143 map = isl_set_unwrap(stmt->domain);
4144 else
4145 map = isl_map_from_domain(stmt->domain);
4146 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
4148 for (int i = nparam - 1; i >= 0; --i) {
4149 isl_id *id;
4151 if (!is_nested_parameter(map, i))
4152 continue;
4154 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
4155 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
4156 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
4157 param2pos[i]);
4158 map = isl_map_project_out(map, isl_dim_param, i, 1);
4161 stmt->domain = isl_map_wrap(map);
4163 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
4164 space = isl_space_from_domain(isl_space_domain(space));
4165 ma = isl_multi_aff_zero(space);
4166 for (int pos = 0; pos < n; ++pos)
4167 stmt->args[pos] = embed(stmt->args[pos], ma);
4168 isl_multi_aff_free(ma);
4170 stmt = remove_nested_parameters(stmt);
4171 stmt = remove_duplicate_arguments(stmt, n);
4173 return stmt;
4176 /* For each statement in "scop", move the parameters that correspond
4177 * to nested access into the ranges of the domains and create
4178 * corresponding argument expressions.
4180 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
4182 if (!scop)
4183 return NULL;
4185 for (int i = 0; i < scop->n_stmt; ++i) {
4186 scop->stmts[i] = resolve_nested(scop->stmts[i]);
4187 if (!scop->stmts[i])
4188 goto error;
4191 return scop;
4192 error:
4193 pet_scop_free(scop);
4194 return NULL;
4197 /* Given an access expression "expr", is the variable accessed by
4198 * "expr" assigned anywhere inside "scop"?
4200 static bool is_assigned(pet_expr *expr, pet_scop *scop)
4202 bool assigned = false;
4203 isl_id *id;
4205 id = pet_expr_access_get_id(expr);
4206 assigned = pet_scop_writes(scop, id);
4207 isl_id_free(id);
4209 return assigned;
4212 /* Are all nested access parameters in "pa" allowed given "scop".
4213 * In particular, is none of them written by anywhere inside "scop".
4215 * If "scop" has any skip conditions, then no nested access parameters
4216 * are allowed. In particular, if there is any nested access in a guard
4217 * for a piece of code containing a "continue", then we want to introduce
4218 * a separate statement for evaluating this guard so that we can express
4219 * that the result is false for all previous iterations.
4221 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
4223 int nparam;
4225 if (!scop)
4226 return true;
4228 if (!has_nested(pa))
4229 return true;
4231 if (pet_scop_has_skip(scop, pet_skip_now))
4232 return false;
4234 nparam = isl_pw_aff_dim(pa, isl_dim_param);
4235 for (int i = 0; i < nparam; ++i) {
4236 Expr *nested;
4237 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
4238 pet_expr *expr;
4239 bool allowed;
4241 if (!is_nested_parameter(id)) {
4242 isl_id_free(id);
4243 continue;
4246 nested = (Expr *) isl_id_get_user(id);
4247 expr = extract_expr(nested);
4248 allowed = expr && expr->type == pet_expr_access &&
4249 !is_assigned(expr, scop);
4251 pet_expr_free(expr);
4252 isl_id_free(id);
4254 if (!allowed)
4255 return false;
4258 return true;
4261 /* Do we need to construct a skip condition of the given type
4262 * on an if statement, given that the if condition is non-affine?
4264 * pet_scop_filter_skip can only handle the case where the if condition
4265 * holds (the then branch) and the skip condition is universal.
4266 * In any other case, we need to construct a new skip condition.
4268 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
4269 bool have_else, enum pet_skip type)
4271 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
4272 return true;
4273 if (scop_then && pet_scop_has_skip(scop_then, type) &&
4274 !pet_scop_has_universal_skip(scop_then, type))
4275 return true;
4276 return false;
4279 /* Do we need to construct a skip condition of the given type
4280 * on an if statement, given that the if condition is affine?
4282 * There is no need to construct a new skip condition if all
4283 * the skip conditions are affine.
4285 static bool need_skip_aff(struct pet_scop *scop_then,
4286 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
4288 if (scop_then && pet_scop_has_var_skip(scop_then, type))
4289 return true;
4290 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
4291 return true;
4292 return false;
4295 /* Do we need to construct a skip condition of the given type
4296 * on an if statement?
4298 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
4299 bool have_else, enum pet_skip type, bool affine)
4301 if (affine)
4302 return need_skip_aff(scop_then, scop_else, have_else, type);
4303 else
4304 return need_skip(scop_then, scop_else, have_else, type);
4307 /* Construct an affine expression pet_expr that evaluates
4308 * to the constant "val".
4310 static struct pet_expr *universally(isl_ctx *ctx, int val)
4312 isl_local_space *ls;
4313 isl_aff *aff;
4314 isl_multi_pw_aff *mpa;
4316 ls = isl_local_space_from_space(isl_space_set_alloc(ctx, 0, 0));
4317 aff = isl_aff_val_on_domain(ls, isl_val_int_from_si(ctx, val));
4318 mpa = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4320 return pet_expr_from_index(mpa);
4323 /* Construct an affine expression pet_expr that evaluates
4324 * to the constant 1.
4326 static struct pet_expr *universally_true(isl_ctx *ctx)
4328 return universally(ctx, 1);
4331 /* Construct an affine expression pet_expr that evaluates
4332 * to the constant 0.
4334 static struct pet_expr *universally_false(isl_ctx *ctx)
4336 return universally(ctx, 0);
4339 /* Given an index expression "test_index" for the if condition,
4340 * an index expression "skip_index" for the skip condition and
4341 * scops for the then and else branches, construct a scop for
4342 * computing "skip_index".
4344 * The computed scop contains a single statement that essentially does
4346 * skip_index = test_cond ? skip_cond_then : skip_cond_else
4348 * If the skip conditions of the then and/or else branch are not affine,
4349 * then they need to be filtered by test_index.
4350 * If they are missing, then this means the skip condition is false.
4352 * Since we are constructing a skip condition for the if statement,
4353 * the skip conditions on the then and else branches are removed.
4355 static struct pet_scop *extract_skip(PetScan *scan,
4356 __isl_take isl_multi_pw_aff *test_index,
4357 __isl_take isl_multi_pw_aff *skip_index,
4358 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
4359 enum pet_skip type)
4361 struct pet_expr *expr_then, *expr_else, *expr, *expr_skip;
4362 struct pet_stmt *stmt;
4363 struct pet_scop *scop;
4364 isl_ctx *ctx = scan->ctx;
4366 if (!scop_then)
4367 goto error;
4368 if (have_else && !scop_else)
4369 goto error;
4371 if (pet_scop_has_skip(scop_then, type)) {
4372 expr_then = pet_scop_get_skip_expr(scop_then, type);
4373 pet_scop_reset_skip(scop_then, type);
4374 if (!pet_expr_is_affine(expr_then))
4375 expr_then = pet_expr_filter(expr_then,
4376 isl_multi_pw_aff_copy(test_index), 1);
4377 } else
4378 expr_then = universally_false(ctx);
4380 if (have_else && pet_scop_has_skip(scop_else, type)) {
4381 expr_else = pet_scop_get_skip_expr(scop_else, type);
4382 pet_scop_reset_skip(scop_else, type);
4383 if (!pet_expr_is_affine(expr_else))
4384 expr_else = pet_expr_filter(expr_else,
4385 isl_multi_pw_aff_copy(test_index), 0);
4386 } else
4387 expr_else = universally_false(ctx);
4389 expr = pet_expr_from_index(test_index);
4390 expr = pet_expr_new_ternary(ctx, expr, expr_then, expr_else);
4391 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4392 if (expr_skip) {
4393 expr_skip->acc.write = 1;
4394 expr_skip->acc.read = 0;
4396 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4397 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, scan->n_stmt++, expr);
4399 scop = pet_scop_from_pet_stmt(ctx, stmt);
4400 scop = scop_add_array(scop, skip_index, scan->ast_context);
4401 isl_multi_pw_aff_free(skip_index);
4403 return scop;
4404 error:
4405 isl_multi_pw_aff_free(test_index);
4406 isl_multi_pw_aff_free(skip_index);
4407 return NULL;
4410 /* Is scop's skip_now condition equal to its skip_later condition?
4411 * In particular, this means that it either has no skip_now condition
4412 * or both a skip_now and a skip_later condition (that are equal to each other).
4414 static bool skip_equals_skip_later(struct pet_scop *scop)
4416 int has_skip_now, has_skip_later;
4417 int equal;
4418 isl_multi_pw_aff *skip_now, *skip_later;
4420 if (!scop)
4421 return false;
4422 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
4423 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
4424 if (has_skip_now != has_skip_later)
4425 return false;
4426 if (!has_skip_now)
4427 return true;
4429 skip_now = pet_scop_get_skip(scop, pet_skip_now);
4430 skip_later = pet_scop_get_skip(scop, pet_skip_later);
4431 equal = isl_multi_pw_aff_is_equal(skip_now, skip_later);
4432 isl_multi_pw_aff_free(skip_now);
4433 isl_multi_pw_aff_free(skip_later);
4435 return equal;
4438 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
4440 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
4442 pet_scop_reset_skip(scop1, pet_skip_later);
4443 pet_scop_reset_skip(scop2, pet_skip_later);
4446 /* Structure that handles the construction of skip conditions.
4448 * scop_then and scop_else represent the then and else branches
4449 * of the if statement
4451 * skip[type] is true if we need to construct a skip condition of that type
4452 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
4453 * are equal to each other
4454 * index[type] is an index expression from a zero-dimension domain
4455 * to the virtual array representing the skip condition
4456 * scop[type] is a scop for computing the skip condition
4458 struct pet_skip_info {
4459 isl_ctx *ctx;
4461 bool skip[2];
4462 bool equal;
4463 isl_multi_pw_aff *index[2];
4464 struct pet_scop *scop[2];
4466 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
4468 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
4471 /* Structure that handles the construction of skip conditions on if statements.
4473 * scop_then and scop_else represent the then and else branches
4474 * of the if statement
4476 struct pet_skip_info_if : public pet_skip_info {
4477 struct pet_scop *scop_then, *scop_else;
4478 bool have_else;
4480 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4481 struct pet_scop *scop_else, bool have_else, bool affine);
4482 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index,
4483 enum pet_skip type);
4484 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index);
4485 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
4486 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4487 int offset);
4488 struct pet_scop *add(struct pet_scop *scop, int offset);
4491 /* Initialize a pet_skip_info_if structure based on the then and else branches
4492 * and based on whether the if condition is affine or not.
4494 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4495 struct pet_scop *scop_else, bool have_else, bool affine) :
4496 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
4497 have_else(have_else)
4499 skip[pet_skip_now] =
4500 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
4501 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
4502 (!have_else || skip_equals_skip_later(scop_else));
4503 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4504 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
4507 /* If we need to construct a skip condition of the given type,
4508 * then do so now.
4510 * "mpa" represents the if condition.
4512 void pet_skip_info_if::extract(PetScan *scan,
4513 __isl_keep isl_multi_pw_aff *mpa, enum pet_skip type)
4515 isl_ctx *ctx;
4517 if (!skip[type])
4518 return;
4520 ctx = isl_multi_pw_aff_get_ctx(mpa);
4521 index[type] = create_test_index(ctx, scan->n_test++);
4522 scop[type] = extract_skip(scan, isl_multi_pw_aff_copy(mpa),
4523 isl_multi_pw_aff_copy(index[type]),
4524 scop_then, scop_else, have_else, type);
4527 /* Construct the required skip conditions, given the if condition "index".
4529 void pet_skip_info_if::extract(PetScan *scan,
4530 __isl_keep isl_multi_pw_aff *index)
4532 extract(scan, index, pet_skip_now);
4533 extract(scan, index, pet_skip_later);
4534 if (equal)
4535 drop_skip_later(scop_then, scop_else);
4538 /* Construct the required skip conditions, given the if condition "cond".
4540 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
4542 isl_multi_pw_aff *test;
4544 if (!skip[pet_skip_now] && !skip[pet_skip_later])
4545 return;
4547 test = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_copy(cond));
4548 test = isl_multi_pw_aff_from_range(test);
4549 extract(scan, test);
4550 isl_multi_pw_aff_free(test);
4553 /* Add the computed skip condition of the give type to "main" and
4554 * add the scop for computing the condition at the given offset.
4556 * If equal is set, then we only computed a skip condition for pet_skip_now,
4557 * but we also need to set it as main's pet_skip_later.
4559 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
4560 enum pet_skip type, int offset)
4562 if (!skip[type])
4563 return main;
4565 scop[type] = pet_scop_prefix(scop[type], offset);
4566 main = pet_scop_add_par(ctx, main, scop[type]);
4567 scop[type] = NULL;
4569 if (equal)
4570 main = pet_scop_set_skip(main, pet_skip_later,
4571 isl_multi_pw_aff_copy(index[type]));
4573 main = pet_scop_set_skip(main, type, index[type]);
4574 index[type] = NULL;
4576 return main;
4579 /* Add the computed skip conditions to "main" and
4580 * add the scops for computing the conditions at the given offset.
4582 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
4584 scop = add(scop, pet_skip_now, offset);
4585 scop = add(scop, pet_skip_later, offset);
4587 return scop;
4590 /* Construct a pet_scop for a non-affine if statement.
4592 * We create a separate statement that writes the result
4593 * of the non-affine condition to a virtual scalar.
4594 * A constraint requiring the value of this virtual scalar to be one
4595 * is added to the iteration domains of the then branch.
4596 * Similarly, a constraint requiring the value of this virtual scalar
4597 * to be zero is added to the iteration domains of the else branch, if any.
4598 * We adjust the schedules to ensure that the virtual scalar is written
4599 * before it is read.
4601 * If there are any breaks or continues in the then and/or else
4602 * branches, then we may have to compute a new skip condition.
4603 * This is handled using a pet_skip_info_if object.
4604 * On initialization, the object checks if skip conditions need
4605 * to be computed. If so, it does so in "extract" and adds them in "add".
4607 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
4608 struct pet_scop *scop_then, struct pet_scop *scop_else,
4609 bool have_else, int stmt_id)
4611 struct pet_scop *scop;
4612 isl_multi_pw_aff *test_index;
4613 int save_n_stmt = n_stmt;
4615 test_index = create_test_index(ctx, n_test++);
4616 n_stmt = stmt_id;
4617 scop = extract_non_affine_condition(cond, n_stmt++,
4618 isl_multi_pw_aff_copy(test_index));
4619 n_stmt = save_n_stmt;
4620 scop = scop_add_array(scop, test_index, ast_context);
4622 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
4623 skip.extract(this, test_index);
4625 scop = pet_scop_prefix(scop, 0);
4626 scop_then = pet_scop_prefix(scop_then, 1);
4627 scop_then = pet_scop_filter(scop_then,
4628 isl_multi_pw_aff_copy(test_index), 1);
4629 if (have_else) {
4630 scop_else = pet_scop_prefix(scop_else, 1);
4631 scop_else = pet_scop_filter(scop_else, test_index, 0);
4632 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
4633 } else
4634 isl_multi_pw_aff_free(test_index);
4636 scop = pet_scop_add_seq(ctx, scop, scop_then);
4638 scop = skip.add(scop, 2);
4640 return scop;
4643 /* Construct a pet_scop for an if statement.
4645 * If the condition fits the pattern of a conditional assignment,
4646 * then it is handled by extract_conditional_assignment.
4647 * Otherwise, we do the following.
4649 * If the condition is affine, then the condition is added
4650 * to the iteration domains of the then branch, while the
4651 * opposite of the condition in added to the iteration domains
4652 * of the else branch, if any.
4653 * We allow the condition to be dynamic, i.e., to refer to
4654 * scalars or array elements that may be written to outside
4655 * of the given if statement. These nested accesses are then represented
4656 * as output dimensions in the wrapping iteration domain.
4657 * If it is also written _inside_ the then or else branch, then
4658 * we treat the condition as non-affine.
4659 * As explained in extract_non_affine_if, this will introduce
4660 * an extra statement.
4661 * For aesthetic reasons, we want this statement to have a statement
4662 * number that is lower than those of the then and else branches.
4663 * In order to evaluate if we will need such a statement, however, we
4664 * first construct scops for the then and else branches.
4665 * We therefore reserve a statement number if we might have to
4666 * introduce such an extra statement.
4668 * If the condition is not affine, then the scop is created in
4669 * extract_non_affine_if.
4671 * If there are any breaks or continues in the then and/or else
4672 * branches, then we may have to compute a new skip condition.
4673 * This is handled using a pet_skip_info_if object.
4674 * On initialization, the object checks if skip conditions need
4675 * to be computed. If so, it does so in "extract" and adds them in "add".
4677 struct pet_scop *PetScan::extract(IfStmt *stmt)
4679 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4680 isl_pw_aff *cond;
4681 int stmt_id;
4682 isl_set *set;
4683 isl_set *valid;
4685 clear_assignments clear(assigned_value);
4686 clear.TraverseStmt(stmt->getThen());
4687 if (stmt->getElse())
4688 clear.TraverseStmt(stmt->getElse());
4690 scop = extract_conditional_assignment(stmt);
4691 if (scop)
4692 return scop;
4694 cond = try_extract_nested_condition(stmt->getCond());
4695 if (allow_nested && (!cond || has_nested(cond)))
4696 stmt_id = n_stmt++;
4699 assigned_value_cache cache(assigned_value);
4700 scop_then = extract(stmt->getThen());
4703 if (stmt->getElse()) {
4704 assigned_value_cache cache(assigned_value);
4705 scop_else = extract(stmt->getElse());
4706 if (options->autodetect) {
4707 if (scop_then && !scop_else) {
4708 partial = true;
4709 isl_pw_aff_free(cond);
4710 return scop_then;
4712 if (!scop_then && scop_else) {
4713 partial = true;
4714 isl_pw_aff_free(cond);
4715 return scop_else;
4720 if (cond &&
4721 (!is_nested_allowed(cond, scop_then) ||
4722 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4723 isl_pw_aff_free(cond);
4724 cond = NULL;
4726 if (allow_nested && !cond)
4727 return extract_non_affine_if(stmt->getCond(), scop_then,
4728 scop_else, stmt->getElse(), stmt_id);
4730 if (!cond)
4731 cond = extract_condition(stmt->getCond());
4733 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4734 skip.extract(this, cond);
4736 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4737 set = isl_pw_aff_non_zero_set(cond);
4738 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4740 if (stmt->getElse()) {
4741 set = isl_set_subtract(isl_set_copy(valid), set);
4742 scop_else = pet_scop_restrict(scop_else, set);
4743 scop = pet_scop_add_par(ctx, scop, scop_else);
4744 } else
4745 isl_set_free(set);
4746 scop = resolve_nested(scop);
4747 scop = pet_scop_restrict_context(scop, valid);
4749 if (skip)
4750 scop = pet_scop_prefix(scop, 0);
4751 scop = skip.add(scop, 1);
4753 return scop;
4756 /* Try and construct a pet_scop for a label statement.
4757 * We currently only allow labels on expression statements.
4759 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4761 isl_id *label;
4762 Stmt *sub;
4764 sub = stmt->getSubStmt();
4765 if (!isa<Expr>(sub)) {
4766 unsupported(stmt);
4767 return NULL;
4770 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4772 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4775 /* Return a one-dimensional multi piecewise affine expression that is equal
4776 * to the constant 1 and is defined over a zero-dimensional domain.
4778 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
4780 isl_space *space;
4781 isl_local_space *ls;
4782 isl_aff *aff;
4784 space = isl_space_set_alloc(ctx, 0, 0);
4785 ls = isl_local_space_from_space(space);
4786 aff = isl_aff_zero_on_domain(ls);
4787 aff = isl_aff_set_constant_si(aff, 1);
4789 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4792 /* Construct a pet_scop for a continue statement.
4794 * We simply create an empty scop with a universal pet_skip_now
4795 * skip condition. This skip condition will then be taken into
4796 * account by the enclosing loop construct, possibly after
4797 * being incorporated into outer skip conditions.
4799 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4801 pet_scop *scop;
4803 scop = pet_scop_empty(ctx);
4804 if (!scop)
4805 return NULL;
4807 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
4809 return scop;
4812 /* Construct a pet_scop for a break statement.
4814 * We simply create an empty scop with both a universal pet_skip_now
4815 * skip condition and a universal pet_skip_later skip condition.
4816 * These skip conditions will then be taken into
4817 * account by the enclosing loop construct, possibly after
4818 * being incorporated into outer skip conditions.
4820 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4822 pet_scop *scop;
4823 isl_multi_pw_aff *skip;
4825 scop = pet_scop_empty(ctx);
4826 if (!scop)
4827 return NULL;
4829 skip = one_mpa(ctx);
4830 scop = pet_scop_set_skip(scop, pet_skip_now,
4831 isl_multi_pw_aff_copy(skip));
4832 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
4834 return scop;
4837 /* Try and construct a pet_scop corresponding to "stmt".
4839 * If "stmt" is a compound statement, then "skip_declarations"
4840 * indicates whether we should skip initial declarations in the
4841 * compound statement.
4843 * If the constructed pet_scop is not a (possibly) partial representation
4844 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4845 * In particular, if skip_declarations is set, then we may have skipped
4846 * declarations inside "stmt" and so the pet_scop may not represent
4847 * the entire "stmt".
4848 * Note that this function may be called with "stmt" referring to the entire
4849 * body of the function, including the outer braces. In such cases,
4850 * skip_declarations will be set and the braces will not be taken into
4851 * account in scop->start and scop->end.
4853 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
4855 struct pet_scop *scop;
4857 if (isa<Expr>(stmt))
4858 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4860 switch (stmt->getStmtClass()) {
4861 case Stmt::WhileStmtClass:
4862 scop = extract(cast<WhileStmt>(stmt));
4863 break;
4864 case Stmt::ForStmtClass:
4865 scop = extract_for(cast<ForStmt>(stmt));
4866 break;
4867 case Stmt::IfStmtClass:
4868 scop = extract(cast<IfStmt>(stmt));
4869 break;
4870 case Stmt::CompoundStmtClass:
4871 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
4872 break;
4873 case Stmt::LabelStmtClass:
4874 scop = extract(cast<LabelStmt>(stmt));
4875 break;
4876 case Stmt::ContinueStmtClass:
4877 scop = extract(cast<ContinueStmt>(stmt));
4878 break;
4879 case Stmt::BreakStmtClass:
4880 scop = extract(cast<BreakStmt>(stmt));
4881 break;
4882 case Stmt::DeclStmtClass:
4883 scop = extract(cast<DeclStmt>(stmt));
4884 break;
4885 default:
4886 unsupported(stmt);
4887 return NULL;
4890 if (partial || skip_declarations)
4891 return scop;
4893 scop = update_scop_start_end(scop, stmt->getSourceRange(), false);
4895 return scop;
4898 /* Do we need to construct a skip condition of the given type
4899 * on a sequence of statements?
4901 * There is no need to construct a new skip condition if only
4902 * only of the two statements has a skip condition or if both
4903 * of their skip conditions are affine.
4905 * In principle we also don't need a new continuation variable if
4906 * the continuation of scop2 is affine, but then we would need
4907 * to allow more complicated forms of continuations.
4909 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4910 enum pet_skip type)
4912 if (!scop1 || !pet_scop_has_skip(scop1, type))
4913 return false;
4914 if (!scop2 || !pet_scop_has_skip(scop2, type))
4915 return false;
4916 if (pet_scop_has_affine_skip(scop1, type) &&
4917 pet_scop_has_affine_skip(scop2, type))
4918 return false;
4919 return true;
4922 /* Construct a scop for computing the skip condition of the given type and
4923 * with index expression "skip_index" for a sequence of two scops "scop1"
4924 * and "scop2".
4926 * The computed scop contains a single statement that essentially does
4928 * skip_index = skip_cond_1 ? 1 : skip_cond_2
4930 * or, in other words, skip_cond1 || skip_cond2.
4931 * In this expression, skip_cond_2 is filtered to reflect that it is
4932 * only evaluated when skip_cond_1 is false.
4934 * The skip condition on scop1 is not removed because it still needs
4935 * to be applied to scop2 when these two scops are combined.
4937 static struct pet_scop *extract_skip_seq(PetScan *ps,
4938 __isl_take isl_multi_pw_aff *skip_index,
4939 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4941 struct pet_expr *expr1, *expr2, *expr, *expr_skip;
4942 struct pet_stmt *stmt;
4943 struct pet_scop *scop;
4944 isl_ctx *ctx = ps->ctx;
4946 if (!scop1 || !scop2)
4947 goto error;
4949 expr1 = pet_scop_get_skip_expr(scop1, type);
4950 expr2 = pet_scop_get_skip_expr(scop2, type);
4951 pet_scop_reset_skip(scop2, type);
4953 expr2 = pet_expr_filter(expr2,
4954 isl_multi_pw_aff_copy(expr1->acc.index), 0);
4956 expr = universally_true(ctx);
4957 expr = pet_expr_new_ternary(ctx, expr1, expr, expr2);
4958 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4959 if (expr_skip) {
4960 expr_skip->acc.write = 1;
4961 expr_skip->acc.read = 0;
4963 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4964 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, ps->n_stmt++, expr);
4966 scop = pet_scop_from_pet_stmt(ctx, stmt);
4967 scop = scop_add_array(scop, skip_index, ps->ast_context);
4968 isl_multi_pw_aff_free(skip_index);
4970 return scop;
4971 error:
4972 isl_multi_pw_aff_free(skip_index);
4973 return NULL;
4976 /* Structure that handles the construction of skip conditions
4977 * on sequences of statements.
4979 * scop1 and scop2 represent the two statements that are combined
4981 struct pet_skip_info_seq : public pet_skip_info {
4982 struct pet_scop *scop1, *scop2;
4984 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4985 struct pet_scop *scop2);
4986 void extract(PetScan *scan, enum pet_skip type);
4987 void extract(PetScan *scan);
4988 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4989 int offset);
4990 struct pet_scop *add(struct pet_scop *scop, int offset);
4993 /* Initialize a pet_skip_info_seq structure based on
4994 * on the two statements that are going to be combined.
4996 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4997 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
4999 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
5000 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
5001 skip_equals_skip_later(scop2);
5002 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
5003 need_skip_seq(scop1, scop2, pet_skip_later);
5006 /* If we need to construct a skip condition of the given type,
5007 * then do so now.
5009 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
5011 if (!skip[type])
5012 return;
5014 index[type] = create_test_index(ctx, scan->n_test++);
5015 scop[type] = extract_skip_seq(scan, isl_multi_pw_aff_copy(index[type]),
5016 scop1, scop2, type);
5019 /* Construct the required skip conditions.
5021 void pet_skip_info_seq::extract(PetScan *scan)
5023 extract(scan, pet_skip_now);
5024 extract(scan, pet_skip_later);
5025 if (equal)
5026 drop_skip_later(scop1, scop2);
5029 /* Add the computed skip condition of the given type to "main" and
5030 * add the scop for computing the condition at the given offset (the statement
5031 * number). Within this offset, the condition is computed at position 1
5032 * to ensure that it is computed after the corresponding statement.
5034 * If equal is set, then we only computed a skip condition for pet_skip_now,
5035 * but we also need to set it as main's pet_skip_later.
5037 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
5038 enum pet_skip type, int offset)
5040 if (!skip[type])
5041 return main;
5043 scop[type] = pet_scop_prefix(scop[type], 1);
5044 scop[type] = pet_scop_prefix(scop[type], offset);
5045 main = pet_scop_add_par(ctx, main, scop[type]);
5046 scop[type] = NULL;
5048 if (equal)
5049 main = pet_scop_set_skip(main, pet_skip_later,
5050 isl_multi_pw_aff_copy(index[type]));
5052 main = pet_scop_set_skip(main, type, index[type]);
5053 index[type] = NULL;
5055 return main;
5058 /* Add the computed skip conditions to "main" and
5059 * add the scops for computing the conditions at the given offset.
5061 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
5063 scop = add(scop, pet_skip_now, offset);
5064 scop = add(scop, pet_skip_later, offset);
5066 return scop;
5069 /* Extract a clone of the kill statement in "scop".
5070 * "scop" is expected to have been created from a DeclStmt
5071 * and should have the kill as its first statement.
5073 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
5075 struct pet_expr *kill;
5076 struct pet_stmt *stmt;
5077 isl_multi_pw_aff *index;
5078 isl_map *access;
5080 if (!scop)
5081 return NULL;
5082 if (scop->n_stmt < 1)
5083 isl_die(ctx, isl_error_internal,
5084 "expecting at least one statement", return NULL);
5085 stmt = scop->stmts[0];
5086 if (!pet_stmt_is_kill(stmt))
5087 isl_die(ctx, isl_error_internal,
5088 "expecting kill statement", return NULL);
5090 index = isl_multi_pw_aff_copy(stmt->body->args[0]->acc.index);
5091 access = isl_map_copy(stmt->body->args[0]->acc.access);
5092 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
5093 access = isl_map_reset_tuple_id(access, isl_dim_in);
5094 kill = pet_expr_kill_from_access_and_index(access, index);
5095 return pet_stmt_from_pet_expr(ctx, stmt->line, NULL, n_stmt++, kill);
5098 /* Mark all arrays in "scop" as being exposed.
5100 static struct pet_scop *mark_exposed(struct pet_scop *scop)
5102 if (!scop)
5103 return NULL;
5104 for (int i = 0; i < scop->n_array; ++i)
5105 scop->arrays[i]->exposed = 1;
5106 return scop;
5109 /* Try and construct a pet_scop corresponding to (part of)
5110 * a sequence of statements.
5112 * "block" is set if the sequence respresents the children of
5113 * a compound statement.
5114 * "skip_declarations" is set if we should skip initial declarations
5115 * in the sequence of statements.
5117 * If there are any breaks or continues in the individual statements,
5118 * then we may have to compute a new skip condition.
5119 * This is handled using a pet_skip_info_seq object.
5120 * On initialization, the object checks if skip conditions need
5121 * to be computed. If so, it does so in "extract" and adds them in "add".
5123 * If "block" is set, then we need to insert kill statements at
5124 * the end of the block for any array that has been declared by
5125 * one of the statements in the sequence. Each of these declarations
5126 * results in the construction of a kill statement at the place
5127 * of the declaration, so we simply collect duplicates of
5128 * those kill statements and append these duplicates to the constructed scop.
5130 * If "block" is not set, then any array declared by one of the statements
5131 * in the sequence is marked as being exposed.
5133 * If autodetect is set, then we allow the extraction of only a subrange
5134 * of the sequence of statements. However, if there is at least one statement
5135 * for which we could not construct a scop and the final range contains
5136 * either no statements or at least one kill, then we discard the entire
5137 * range.
5139 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
5140 bool skip_declarations)
5142 pet_scop *scop;
5143 StmtIterator i;
5144 int j;
5145 bool partial_range = false;
5146 set<struct pet_stmt *> kills;
5147 set<struct pet_stmt *>::iterator it;
5149 scop = pet_scop_empty(ctx);
5150 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
5151 Stmt *child = *i;
5152 struct pet_scop *scop_i;
5154 if (scop->n_stmt == 0 && skip_declarations &&
5155 child->getStmtClass() == Stmt::DeclStmtClass)
5156 continue;
5158 scop_i = extract(child);
5159 if (scop->n_stmt != 0 && partial) {
5160 pet_scop_free(scop_i);
5161 break;
5163 pet_skip_info_seq skip(ctx, scop, scop_i);
5164 skip.extract(this);
5165 if (skip)
5166 scop_i = pet_scop_prefix(scop_i, 0);
5167 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
5168 if (block)
5169 kills.insert(extract_kill(scop_i));
5170 else
5171 scop_i = mark_exposed(scop_i);
5173 scop_i = pet_scop_prefix(scop_i, j);
5174 if (options->autodetect) {
5175 if (scop_i)
5176 scop = pet_scop_add_seq(ctx, scop, scop_i);
5177 else
5178 partial_range = true;
5179 if (scop->n_stmt != 0 && !scop_i)
5180 partial = true;
5181 } else {
5182 scop = pet_scop_add_seq(ctx, scop, scop_i);
5185 scop = skip.add(scop, j);
5187 if (partial || !scop)
5188 break;
5191 for (it = kills.begin(); it != kills.end(); ++it) {
5192 pet_scop *scop_j;
5193 scop_j = pet_scop_from_pet_stmt(ctx, *it);
5194 scop_j = pet_scop_prefix(scop_j, j);
5195 scop = pet_scop_add_seq(ctx, scop, scop_j);
5198 if (scop && partial_range) {
5199 if (scop->n_stmt == 0 || kills.size() != 0) {
5200 pet_scop_free(scop);
5201 return NULL;
5203 partial = true;
5206 return scop;
5209 /* Check if the scop marked by the user is exactly this Stmt
5210 * or part of this Stmt.
5211 * If so, return a pet_scop corresponding to the marked region.
5212 * Otherwise, return NULL.
5214 struct pet_scop *PetScan::scan(Stmt *stmt)
5216 SourceManager &SM = PP.getSourceManager();
5217 unsigned start_off, end_off;
5219 start_off = getExpansionOffset(SM, stmt->getLocStart());
5220 end_off = getExpansionOffset(SM, stmt->getLocEnd());
5222 if (start_off > loc.end)
5223 return NULL;
5224 if (end_off < loc.start)
5225 return NULL;
5226 if (start_off >= loc.start && end_off <= loc.end) {
5227 return extract(stmt);
5230 StmtIterator start;
5231 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
5232 Stmt *child = *start;
5233 if (!child)
5234 continue;
5235 start_off = getExpansionOffset(SM, child->getLocStart());
5236 end_off = getExpansionOffset(SM, child->getLocEnd());
5237 if (start_off < loc.start && end_off >= loc.end)
5238 return scan(child);
5239 if (start_off >= loc.start)
5240 break;
5243 StmtIterator end;
5244 for (end = start; end != stmt->child_end(); ++end) {
5245 Stmt *child = *end;
5246 start_off = SM.getFileOffset(child->getLocStart());
5247 if (start_off >= loc.end)
5248 break;
5251 return extract(StmtRange(start, end), false, false);
5254 /* Set the size of index "pos" of "array" to "size".
5255 * In particular, add a constraint of the form
5257 * i_pos < size
5259 * to array->extent and a constraint of the form
5261 * size >= 0
5263 * to array->context.
5265 static struct pet_array *update_size(struct pet_array *array, int pos,
5266 __isl_take isl_pw_aff *size)
5268 isl_set *valid;
5269 isl_set *univ;
5270 isl_set *bound;
5271 isl_space *dim;
5272 isl_aff *aff;
5273 isl_pw_aff *index;
5274 isl_id *id;
5276 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
5277 array->context = isl_set_intersect(array->context, valid);
5279 dim = isl_set_get_space(array->extent);
5280 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
5281 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
5282 univ = isl_set_universe(isl_aff_get_domain_space(aff));
5283 index = isl_pw_aff_alloc(univ, aff);
5285 size = isl_pw_aff_add_dims(size, isl_dim_in,
5286 isl_set_dim(array->extent, isl_dim_set));
5287 id = isl_set_get_tuple_id(array->extent);
5288 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
5289 bound = isl_pw_aff_lt_set(index, size);
5291 array->extent = isl_set_intersect(array->extent, bound);
5293 if (!array->context || !array->extent)
5294 goto error;
5296 return array;
5297 error:
5298 pet_array_free(array);
5299 return NULL;
5302 /* Figure out the size of the array at position "pos" and all
5303 * subsequent positions from "type" and update "array" accordingly.
5305 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
5306 const Type *type, int pos)
5308 const ArrayType *atype;
5309 isl_pw_aff *size;
5311 if (!array)
5312 return NULL;
5314 if (type->isPointerType()) {
5315 type = type->getPointeeType().getTypePtr();
5316 return set_upper_bounds(array, type, pos + 1);
5318 if (!type->isArrayType())
5319 return array;
5321 type = type->getCanonicalTypeInternal().getTypePtr();
5322 atype = cast<ArrayType>(type);
5324 if (type->isConstantArrayType()) {
5325 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
5326 size = extract_affine(ca->getSize());
5327 array = update_size(array, pos, size);
5328 } else if (type->isVariableArrayType()) {
5329 const VariableArrayType *vla = cast<VariableArrayType>(atype);
5330 size = extract_affine(vla->getSizeExpr());
5331 array = update_size(array, pos, size);
5334 type = atype->getElementType().getTypePtr();
5336 return set_upper_bounds(array, type, pos + 1);
5339 /* Is "T" the type of a variable length array with static size?
5341 static bool is_vla_with_static_size(QualType T)
5343 const VariableArrayType *vlatype;
5345 if (!T->isVariableArrayType())
5346 return false;
5347 vlatype = cast<VariableArrayType>(T);
5348 return vlatype->getSizeModifier() == VariableArrayType::Static;
5351 /* Return the type of "decl" as an array.
5353 * In particular, if "decl" is a parameter declaration that
5354 * is a variable length array with a static size, then
5355 * return the original type (i.e., the variable length array).
5356 * Otherwise, return the type of decl.
5358 static QualType get_array_type(ValueDecl *decl)
5360 ParmVarDecl *parm;
5361 QualType T;
5363 parm = dyn_cast<ParmVarDecl>(decl);
5364 if (!parm)
5365 return decl->getType();
5367 T = parm->getOriginalType();
5368 if (!is_vla_with_static_size(T))
5369 return decl->getType();
5370 return T;
5373 /* Does "decl" have definition that we can keep track of in a pet_type?
5375 static bool has_printable_definition(RecordDecl *decl)
5377 if (!decl->getDeclName())
5378 return false;
5379 return decl->getLexicalDeclContext() == decl->getDeclContext();
5382 /* Construct and return a pet_array corresponding to the variable "decl".
5383 * In particular, initialize array->extent to
5385 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
5387 * and then call set_upper_bounds to set the upper bounds on the indices
5388 * based on the type of the variable.
5390 * If the base type is that of a record with a top-level definition and
5391 * if "types" is not null, then the RecordDecl corresponding to the type
5392 * is added to "types".
5394 * If the base type is that of a record with no top-level definition,
5395 * then we replace it by "<subfield>".
5397 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
5398 lex_recorddecl_set *types)
5400 struct pet_array *array;
5401 QualType qt = get_array_type(decl);
5402 const Type *type = qt.getTypePtr();
5403 int depth = array_depth(type);
5404 QualType base = pet_clang_base_type(qt);
5405 string name;
5406 isl_id *id;
5407 isl_space *dim;
5409 array = isl_calloc_type(ctx, struct pet_array);
5410 if (!array)
5411 return NULL;
5413 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
5414 dim = isl_space_set_alloc(ctx, 0, depth);
5415 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
5417 array->extent = isl_set_nat_universe(dim);
5419 dim = isl_space_params_alloc(ctx, 0);
5420 array->context = isl_set_universe(dim);
5422 array = set_upper_bounds(array, type, 0);
5423 if (!array)
5424 return NULL;
5426 name = base.getAsString();
5428 if (types && base->isRecordType()) {
5429 RecordDecl *decl = pet_clang_record_decl(base);
5430 if (has_printable_definition(decl))
5431 types->insert(decl);
5432 else
5433 name = "<subfield>";
5436 array->element_type = strdup(name.c_str());
5437 array->element_is_record = base->isRecordType();
5438 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
5440 return array;
5443 /* Construct and return a pet_array corresponding to the sequence
5444 * of declarations "decls".
5445 * If the sequence contains a single declaration, then it corresponds
5446 * to a simple array access. Otherwise, it corresponds to a member access,
5447 * with the declaration for the substructure following that of the containing
5448 * structure in the sequence of declarations.
5449 * We start with the outermost substructure and then combine it with
5450 * information from the inner structures.
5452 * Additionally, keep track of all required types in "types".
5454 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
5455 vector<ValueDecl *> decls, lex_recorddecl_set *types)
5457 struct pet_array *array;
5458 vector<ValueDecl *>::iterator it;
5460 it = decls.begin();
5462 array = extract_array(ctx, *it, types);
5464 for (++it; it != decls.end(); ++it) {
5465 struct pet_array *parent;
5466 const char *base_name, *field_name;
5467 char *product_name;
5469 parent = array;
5470 array = extract_array(ctx, *it, types);
5471 if (!array)
5472 return pet_array_free(parent);
5474 base_name = isl_set_get_tuple_name(parent->extent);
5475 field_name = isl_set_get_tuple_name(array->extent);
5476 product_name = member_access_name(ctx, base_name, field_name);
5478 array->extent = isl_set_product(isl_set_copy(parent->extent),
5479 array->extent);
5480 if (product_name)
5481 array->extent = isl_set_set_tuple_name(array->extent,
5482 product_name);
5483 array->context = isl_set_intersect(array->context,
5484 isl_set_copy(parent->context));
5486 pet_array_free(parent);
5487 free(product_name);
5489 if (!array->extent || !array->context || !product_name)
5490 return pet_array_free(array);
5493 return array;
5496 /* Add a pet_type corresponding to "decl" to "scop, provided
5497 * it is a member of "types" and it has not been added before
5498 * (i.e., it is not a member of "types_done".
5500 * Since we want the user to be able to print the types
5501 * in the order in which they appear in the scop, we need to
5502 * make sure that types of fields in a structure appear before
5503 * that structure. We therefore call ourselves recursively
5504 * on the types of all record subfields.
5506 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
5507 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
5508 lex_recorddecl_set &types_done)
5510 string s;
5511 llvm::raw_string_ostream S(s);
5512 RecordDecl::field_iterator it;
5514 if (types.find(decl) == types.end())
5515 return scop;
5516 if (types_done.find(decl) != types_done.end())
5517 return scop;
5519 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
5520 RecordDecl *record;
5521 QualType type = it->getType();
5523 if (!type->isRecordType())
5524 continue;
5525 record = pet_clang_record_decl(type);
5526 scop = add_type(ctx, scop, record, PP, types, types_done);
5529 if (strlen(decl->getName().str().c_str()) == 0)
5530 return scop;
5532 decl->print(S, PrintingPolicy(PP.getLangOpts()));
5533 S.str();
5535 scop->types[scop->n_type] = pet_type_alloc(ctx,
5536 decl->getName().str().c_str(), s.c_str());
5537 if (!scop->types[scop->n_type])
5538 return pet_scop_free(scop);
5540 types_done.insert(decl);
5542 scop->n_type++;
5544 return scop;
5547 /* Construct a list of pet_arrays, one for each array (or scalar)
5548 * accessed inside "scop", add this list to "scop" and return the result.
5550 * The context of "scop" is updated with the intersection of
5551 * the contexts of all arrays, i.e., constraints on the parameters
5552 * that ensure that the arrays have a valid (non-negative) size.
5554 * If the any of the extracted arrays refers to a member access,
5555 * then also add the required types to "scop".
5557 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
5559 int i;
5560 set<vector<ValueDecl *> > arrays;
5561 set<vector<ValueDecl *> >::iterator it;
5562 lex_recorddecl_set types;
5563 lex_recorddecl_set types_done;
5564 lex_recorddecl_set::iterator types_it;
5565 int n_array;
5566 struct pet_array **scop_arrays;
5568 if (!scop)
5569 return NULL;
5571 pet_scop_collect_arrays(scop, arrays);
5572 if (arrays.size() == 0)
5573 return scop;
5575 n_array = scop->n_array;
5577 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
5578 n_array + arrays.size());
5579 if (!scop_arrays)
5580 goto error;
5581 scop->arrays = scop_arrays;
5583 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
5584 struct pet_array *array;
5585 array = extract_array(ctx, *it, &types);
5586 scop->arrays[n_array + i] = array;
5587 if (!scop->arrays[n_array + i])
5588 goto error;
5589 scop->n_array++;
5590 scop->context = isl_set_intersect(scop->context,
5591 isl_set_copy(array->context));
5592 if (!scop->context)
5593 goto error;
5596 if (types.size() == 0)
5597 return scop;
5599 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
5600 if (!scop->types)
5601 goto error;
5603 for (types_it = types.begin(); types_it != types.end(); ++types_it)
5604 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
5606 return scop;
5607 error:
5608 pet_scop_free(scop);
5609 return NULL;
5612 /* Bound all parameters in scop->context to the possible values
5613 * of the corresponding C variable.
5615 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
5617 int n;
5619 if (!scop)
5620 return NULL;
5622 n = isl_set_dim(scop->context, isl_dim_param);
5623 for (int i = 0; i < n; ++i) {
5624 isl_id *id;
5625 ValueDecl *decl;
5627 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
5628 if (is_nested_parameter(id)) {
5629 isl_id_free(id);
5630 isl_die(isl_set_get_ctx(scop->context),
5631 isl_error_internal,
5632 "unresolved nested parameter", goto error);
5634 decl = (ValueDecl *) isl_id_get_user(id);
5635 isl_id_free(id);
5637 scop->context = set_parameter_bounds(scop->context, i, decl);
5639 if (!scop->context)
5640 goto error;
5643 return scop;
5644 error:
5645 pet_scop_free(scop);
5646 return NULL;
5649 /* Construct a pet_scop from the given function.
5651 * If the scop was delimited by scop and endscop pragmas, then we override
5652 * the file offsets by those derived from the pragmas.
5654 struct pet_scop *PetScan::scan(FunctionDecl *fd)
5656 pet_scop *scop;
5657 Stmt *stmt;
5659 stmt = fd->getBody();
5661 if (options->autodetect)
5662 scop = extract(stmt, true);
5663 else {
5664 scop = scan(stmt);
5665 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
5667 scop = pet_scop_detect_parameter_accesses(scop);
5668 scop = scan_arrays(scop);
5669 scop = add_parameter_bounds(scop);
5670 scop = pet_scop_gist(scop, value_bounds);
5672 return scop;