PetScan::extract_argument: avoid modifying part of pet_expr
[pet.git] / scan.cc
blobaa2a512b7067ff84d217c3c320978d49c0b56b67
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 "nest.h"
53 #include "options.h"
54 #include "scan.h"
55 #include "scop.h"
56 #include "scop_plus.h"
58 #include "config.h"
60 using namespace std;
61 using namespace clang;
63 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
64 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
66 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
67 SourceLocation(), var, false, var->getInnerLocStart(),
68 var->getType(), VK_LValue);
70 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
71 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
73 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
74 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
75 VK_LValue);
77 #else
78 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
80 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
81 var, var->getInnerLocStart(), var->getType(), VK_LValue);
83 #endif
85 /* Check if the element type corresponding to the given array type
86 * has a const qualifier.
88 static bool const_base(QualType qt)
90 const Type *type = qt.getTypePtr();
92 if (type->isPointerType())
93 return const_base(type->getPointeeType());
94 if (type->isArrayType()) {
95 const ArrayType *atype;
96 type = type->getCanonicalTypeInternal().getTypePtr();
97 atype = cast<ArrayType>(type);
98 return const_base(atype->getElementType());
101 return qt.isConstQualified();
104 /* Mark "decl" as having an unknown value in "assigned_value".
106 * If no (known or unknown) value was assigned to "decl" before,
107 * then it may have been treated as a parameter before and may
108 * therefore appear in a value assigned to another variable.
109 * If so, this assignment needs to be turned into an unknown value too.
111 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
112 ValueDecl *decl)
114 map<ValueDecl *, isl_pw_aff *>::iterator it;
116 it = assigned_value.find(decl);
118 assigned_value[decl] = NULL;
120 if (it != assigned_value.end())
121 return;
123 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
124 isl_pw_aff *pa = it->second;
125 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
127 for (int i = 0; i < nparam; ++i) {
128 isl_id *id;
130 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
131 continue;
132 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
133 if (isl_id_get_user(id) == decl)
134 it->second = NULL;
135 isl_id_free(id);
140 /* Look for any assignments to scalar variables in part of the parse
141 * tree and set assigned_value to NULL for each of them.
142 * Also reset assigned_value if the address of a scalar variable
143 * is being taken. As an exception, if the address is passed to a function
144 * that is declared to receive a const pointer, then assigned_value is
145 * not reset.
147 * This ensures that we won't use any previously stored value
148 * in the current subtree and its parents.
150 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
151 map<ValueDecl *, isl_pw_aff *> &assigned_value;
152 set<UnaryOperator *> skip;
154 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
155 assigned_value(assigned_value) {}
157 /* Check for "address of" operators whose value is passed
158 * to a const pointer argument and add them to "skip", so that
159 * we can skip them in VisitUnaryOperator.
161 bool VisitCallExpr(CallExpr *expr) {
162 FunctionDecl *fd;
163 fd = expr->getDirectCallee();
164 if (!fd)
165 return true;
166 for (int i = 0; i < expr->getNumArgs(); ++i) {
167 Expr *arg = expr->getArg(i);
168 UnaryOperator *op;
169 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
170 ImplicitCastExpr *ice;
171 ice = cast<ImplicitCastExpr>(arg);
172 arg = ice->getSubExpr();
174 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
175 continue;
176 op = cast<UnaryOperator>(arg);
177 if (op->getOpcode() != UO_AddrOf)
178 continue;
179 if (const_base(fd->getParamDecl(i)->getType()))
180 skip.insert(op);
182 return true;
185 bool VisitUnaryOperator(UnaryOperator *expr) {
186 Expr *arg;
187 DeclRefExpr *ref;
188 ValueDecl *decl;
190 switch (expr->getOpcode()) {
191 case UO_AddrOf:
192 case UO_PostInc:
193 case UO_PostDec:
194 case UO_PreInc:
195 case UO_PreDec:
196 break;
197 default:
198 return true;
200 if (skip.find(expr) != skip.end())
201 return true;
203 arg = expr->getSubExpr();
204 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
205 return true;
206 ref = cast<DeclRefExpr>(arg);
207 decl = ref->getDecl();
208 clear_assignment(assigned_value, decl);
209 return true;
212 bool VisitBinaryOperator(BinaryOperator *expr) {
213 Expr *lhs;
214 DeclRefExpr *ref;
215 ValueDecl *decl;
217 if (!expr->isAssignmentOp())
218 return true;
219 lhs = expr->getLHS();
220 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
221 return true;
222 ref = cast<DeclRefExpr>(lhs);
223 decl = ref->getDecl();
224 clear_assignment(assigned_value, decl);
225 return true;
229 /* Keep a copy of the currently assigned values.
231 * Any variable that is assigned a value inside the current scope
232 * is removed again when we leave the scope (either because it wasn't
233 * stored in the cache or because it has a different value in the cache).
235 struct assigned_value_cache {
236 map<ValueDecl *, isl_pw_aff *> &assigned_value;
237 map<ValueDecl *, isl_pw_aff *> cache;
239 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
240 assigned_value(assigned_value), cache(assigned_value) {}
241 ~assigned_value_cache() {
242 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
243 for (it = assigned_value.begin(); it != assigned_value.end();
244 ++it) {
245 if (!it->second ||
246 (cache.find(it->first) != cache.end() &&
247 cache[it->first] != it->second))
248 cache[it->first] = NULL;
250 assigned_value = cache;
254 /* Insert an expression into the collection of expressions,
255 * provided it is not already in there.
256 * The isl_pw_affs are freed in the destructor.
258 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
260 std::set<isl_pw_aff *>::iterator it;
262 if (expressions.find(expr) == expressions.end())
263 expressions.insert(expr);
264 else
265 isl_pw_aff_free(expr);
268 PetScan::~PetScan()
270 std::set<isl_pw_aff *>::iterator it;
272 for (it = expressions.begin(); it != expressions.end(); ++it)
273 isl_pw_aff_free(*it);
275 isl_union_map_free(value_bounds);
278 /* Report a diagnostic, unless autodetect is set.
280 void PetScan::report(Stmt *stmt, unsigned id)
282 if (options->autodetect)
283 return;
285 SourceLocation loc = stmt->getLocStart();
286 DiagnosticsEngine &diag = PP.getDiagnostics();
287 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
290 /* Called if we found something we (currently) cannot handle.
291 * We'll provide more informative warnings later.
293 * We only actually complain if autodetect is false.
295 void PetScan::unsupported(Stmt *stmt)
297 DiagnosticsEngine &diag = PP.getDiagnostics();
298 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
299 "unsupported");
300 report(stmt, id);
303 /* Report a missing prototype, unless autodetect is set.
305 void PetScan::report_prototype_required(Stmt *stmt)
307 DiagnosticsEngine &diag = PP.getDiagnostics();
308 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
309 "prototype required");
310 report(stmt, id);
313 /* Report a missing increment, unless autodetect is set.
315 void PetScan::report_missing_increment(Stmt *stmt)
317 DiagnosticsEngine &diag = PP.getDiagnostics();
318 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
319 "missing increment");
320 report(stmt, id);
323 /* Extract an integer from "expr".
325 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
327 const Type *type = expr->getType().getTypePtr();
328 int is_signed = type->hasSignedIntegerRepresentation();
329 llvm::APInt val = expr->getValue();
330 int is_negative = is_signed && val.isNegative();
331 isl_val *v;
333 if (is_negative)
334 val = -val;
336 v = extract_unsigned(ctx, val);
338 if (is_negative)
339 v = isl_val_neg(v);
340 return v;
343 /* Extract an integer from "val", which is assumed to be non-negative.
345 __isl_give isl_val *PetScan::extract_unsigned(isl_ctx *ctx,
346 const llvm::APInt &val)
348 unsigned n;
349 const uint64_t *data;
351 data = val.getRawData();
352 n = val.getNumWords();
353 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
356 /* Extract an integer from "expr".
357 * Return NULL if "expr" does not (obviously) represent an integer.
359 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
361 return extract_int(expr->getSubExpr());
364 /* Extract an integer from "expr".
365 * Return NULL if "expr" does not (obviously) represent an integer.
367 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
369 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
370 return extract_int(ctx, cast<IntegerLiteral>(expr));
371 if (expr->getStmtClass() == Stmt::ParenExprClass)
372 return extract_int(cast<ParenExpr>(expr));
374 unsupported(expr);
375 return NULL;
378 /* Extract an affine expression from the IntegerLiteral "expr".
380 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
382 isl_space *dim = isl_space_params_alloc(ctx, 0);
383 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
384 isl_aff *aff = isl_aff_zero_on_domain(ls);
385 isl_set *dom = isl_set_universe(dim);
386 isl_val *v;
388 v = extract_int(expr);
389 aff = isl_aff_add_constant_val(aff, v);
391 return isl_pw_aff_alloc(dom, aff);
394 /* Extract an affine expression from the APInt "val", which is assumed
395 * to be non-negative.
397 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
399 isl_space *dim = isl_space_params_alloc(ctx, 0);
400 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
401 isl_aff *aff = isl_aff_zero_on_domain(ls);
402 isl_set *dom = isl_set_universe(dim);
403 isl_val *v;
405 v = extract_unsigned(ctx, val);
406 aff = isl_aff_add_constant_val(aff, v);
408 return isl_pw_aff_alloc(dom, aff);
411 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
413 return extract_affine(expr->getSubExpr());
416 static unsigned get_type_size(ValueDecl *decl)
418 return decl->getASTContext().getIntWidth(decl->getType());
421 /* Bound parameter "pos" of "set" to the possible values of "decl".
423 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
424 unsigned pos, ValueDecl *decl)
426 unsigned width;
427 isl_ctx *ctx;
428 isl_val *bound;
430 ctx = isl_set_get_ctx(set);
431 width = get_type_size(decl);
432 if (decl->getType()->isUnsignedIntegerType()) {
433 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
434 bound = isl_val_int_from_ui(ctx, width);
435 bound = isl_val_2exp(bound);
436 bound = isl_val_sub_ui(bound, 1);
437 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
438 } else {
439 bound = isl_val_int_from_ui(ctx, width - 1);
440 bound = isl_val_2exp(bound);
441 bound = isl_val_sub_ui(bound, 1);
442 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
443 isl_val_copy(bound));
444 bound = isl_val_neg(bound);
445 bound = isl_val_sub_ui(bound, 1);
446 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
449 return set;
452 /* Extract an affine expression from the DeclRefExpr "expr".
454 * If the variable has been assigned a value, then we check whether
455 * we know what (affine) value was assigned.
456 * If so, we return this value. Otherwise we convert "expr"
457 * to an extra parameter (provided nesting_enabled is set).
459 * Otherwise, we simply return an expression that is equal
460 * to a parameter corresponding to the referenced variable.
462 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
464 ValueDecl *decl = expr->getDecl();
465 const Type *type = decl->getType().getTypePtr();
466 isl_id *id;
467 isl_space *dim;
468 isl_aff *aff;
469 isl_set *dom;
471 if (!type->isIntegerType()) {
472 unsupported(expr);
473 return NULL;
476 if (assigned_value.find(decl) != assigned_value.end()) {
477 if (assigned_value[decl])
478 return isl_pw_aff_copy(assigned_value[decl]);
479 else
480 return nested_access(expr);
483 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
484 dim = isl_space_params_alloc(ctx, 1);
486 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
488 dom = isl_set_universe(isl_space_copy(dim));
489 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
490 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
492 return isl_pw_aff_alloc(dom, aff);
495 /* Extract an affine expression from an integer division operation.
496 * In particular, if "expr" is lhs/rhs, then return
498 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
500 * The second argument (rhs) is required to be a (positive) integer constant.
502 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
504 int is_cst;
505 isl_pw_aff *rhs, *lhs;
507 rhs = extract_affine(expr->getRHS());
508 is_cst = isl_pw_aff_is_cst(rhs);
509 if (is_cst < 0 || !is_cst) {
510 isl_pw_aff_free(rhs);
511 if (!is_cst)
512 unsupported(expr);
513 return NULL;
516 lhs = extract_affine(expr->getLHS());
518 return isl_pw_aff_tdiv_q(lhs, rhs);
521 /* Extract an affine expression from a modulo operation.
522 * In particular, if "expr" is lhs/rhs, then return
524 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
526 * The second argument (rhs) is required to be a (positive) integer constant.
528 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
530 int is_cst;
531 isl_pw_aff *rhs, *lhs;
533 rhs = extract_affine(expr->getRHS());
534 is_cst = isl_pw_aff_is_cst(rhs);
535 if (is_cst < 0 || !is_cst) {
536 isl_pw_aff_free(rhs);
537 if (!is_cst)
538 unsupported(expr);
539 return NULL;
542 lhs = extract_affine(expr->getLHS());
544 return isl_pw_aff_tdiv_r(lhs, rhs);
547 /* Extract an affine expression from a multiplication operation.
548 * This is only allowed if at least one of the two arguments
549 * is a (piecewise) constant.
551 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
553 isl_pw_aff *lhs;
554 isl_pw_aff *rhs;
556 lhs = extract_affine(expr->getLHS());
557 rhs = extract_affine(expr->getRHS());
559 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
560 isl_pw_aff_free(lhs);
561 isl_pw_aff_free(rhs);
562 unsupported(expr);
563 return NULL;
566 return isl_pw_aff_mul(lhs, rhs);
569 /* Extract an affine expression from an addition or subtraction operation.
571 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
573 isl_pw_aff *lhs;
574 isl_pw_aff *rhs;
576 lhs = extract_affine(expr->getLHS());
577 rhs = extract_affine(expr->getRHS());
579 switch (expr->getOpcode()) {
580 case BO_Add:
581 return isl_pw_aff_add(lhs, rhs);
582 case BO_Sub:
583 return isl_pw_aff_sub(lhs, rhs);
584 default:
585 isl_pw_aff_free(lhs);
586 isl_pw_aff_free(rhs);
587 return NULL;
592 /* Compute
594 * pwaff mod 2^width
596 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
597 unsigned width)
599 isl_ctx *ctx;
600 isl_val *mod;
602 ctx = isl_pw_aff_get_ctx(pwaff);
603 mod = isl_val_int_from_ui(ctx, width);
604 mod = isl_val_2exp(mod);
606 pwaff = isl_pw_aff_mod_val(pwaff, mod);
608 return pwaff;
611 /* Limit the domain of "pwaff" to those elements where the function
612 * value satisfies
614 * 2^{width-1} <= pwaff < 2^{width-1}
616 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
617 unsigned width)
619 isl_ctx *ctx;
620 isl_val *v;
621 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
622 isl_local_space *ls = isl_local_space_from_space(space);
623 isl_aff *bound;
624 isl_set *dom;
625 isl_pw_aff *b;
627 ctx = isl_pw_aff_get_ctx(pwaff);
628 v = isl_val_int_from_ui(ctx, width - 1);
629 v = isl_val_2exp(v);
631 bound = isl_aff_zero_on_domain(ls);
632 bound = isl_aff_add_constant_val(bound, v);
633 b = isl_pw_aff_from_aff(bound);
635 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
636 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
638 b = isl_pw_aff_neg(b);
639 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
640 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
642 return pwaff;
645 /* Handle potential overflows on signed computations.
647 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
648 * the we adjust the domain of "pa" to avoid overflows.
650 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
651 unsigned width)
653 if (options->signed_overflow == PET_OVERFLOW_AVOID)
654 pa = avoid_overflow(pa, width);
656 return pa;
659 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
661 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
662 __isl_take isl_set *dom)
664 isl_pw_aff *pa;
665 pa = isl_set_indicator_function(set);
666 pa = isl_pw_aff_intersect_domain(pa, isl_set_coalesce(dom));
667 return pa;
670 /* Extract an affine expression from some binary operations.
671 * If the result of the expression is unsigned, then we wrap it
672 * based on the size of the type. Otherwise, we ensure that
673 * no overflow occurs.
675 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
677 isl_pw_aff *res;
678 unsigned width;
680 switch (expr->getOpcode()) {
681 case BO_Add:
682 case BO_Sub:
683 res = extract_affine_add(expr);
684 break;
685 case BO_Div:
686 res = extract_affine_div(expr);
687 break;
688 case BO_Rem:
689 res = extract_affine_mod(expr);
690 break;
691 case BO_Mul:
692 res = extract_affine_mul(expr);
693 break;
694 case BO_LT:
695 case BO_LE:
696 case BO_GT:
697 case BO_GE:
698 case BO_EQ:
699 case BO_NE:
700 case BO_LAnd:
701 case BO_LOr:
702 return extract_condition(expr);
703 default:
704 unsupported(expr);
705 return NULL;
708 width = ast_context.getIntWidth(expr->getType());
709 if (expr->getType()->isUnsignedIntegerType())
710 res = wrap(res, width);
711 else
712 res = signed_overflow(res, width);
714 return res;
717 /* Extract an affine expression from a negation operation.
719 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
721 if (expr->getOpcode() == UO_Minus)
722 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
723 if (expr->getOpcode() == UO_LNot)
724 return extract_condition(expr);
726 unsupported(expr);
727 return NULL;
730 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
732 return extract_affine(expr->getSubExpr());
735 /* Extract an affine expression from some special function calls.
736 * In particular, we handle "min", "max", "ceild", "floord",
737 * "intMod", "intFloor" and "intCeil".
738 * In case of the latter five, the second argument needs to be
739 * a (positive) integer constant.
741 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
743 FunctionDecl *fd;
744 string name;
745 isl_pw_aff *aff1, *aff2;
747 fd = expr->getDirectCallee();
748 if (!fd) {
749 unsupported(expr);
750 return NULL;
753 name = fd->getDeclName().getAsString();
754 if (!(expr->getNumArgs() == 2 && name == "min") &&
755 !(expr->getNumArgs() == 2 && name == "max") &&
756 !(expr->getNumArgs() == 2 && name == "intMod") &&
757 !(expr->getNumArgs() == 2 && name == "intFloor") &&
758 !(expr->getNumArgs() == 2 && name == "intCeil") &&
759 !(expr->getNumArgs() == 2 && name == "floord") &&
760 !(expr->getNumArgs() == 2 && name == "ceild")) {
761 unsupported(expr);
762 return NULL;
765 if (name == "min" || name == "max") {
766 aff1 = extract_affine(expr->getArg(0));
767 aff2 = extract_affine(expr->getArg(1));
769 if (name == "min")
770 aff1 = isl_pw_aff_min(aff1, aff2);
771 else
772 aff1 = isl_pw_aff_max(aff1, aff2);
773 } else if (name == "intMod") {
774 isl_val *v;
775 Expr *arg2 = expr->getArg(1);
777 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
778 unsupported(expr);
779 return NULL;
781 aff1 = extract_affine(expr->getArg(0));
782 v = extract_int(cast<IntegerLiteral>(arg2));
783 aff1 = isl_pw_aff_mod_val(aff1, v);
784 } else if (name == "floord" || name == "ceild" ||
785 name == "intFloor" || name == "intCeil") {
786 isl_val *v;
787 Expr *arg2 = expr->getArg(1);
789 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
790 unsupported(expr);
791 return NULL;
793 aff1 = extract_affine(expr->getArg(0));
794 v = extract_int(cast<IntegerLiteral>(arg2));
795 aff1 = isl_pw_aff_scale_down_val(aff1, v);
796 if (name == "floord" || name == "intFloor")
797 aff1 = isl_pw_aff_floor(aff1);
798 else
799 aff1 = isl_pw_aff_ceil(aff1);
800 } else {
801 unsupported(expr);
802 return NULL;
805 return aff1;
808 /* This method is called when we come across an access that is
809 * nested in what is supposed to be an affine expression.
810 * If nesting is allowed, we return a new parameter that corresponds
811 * to this nested access. Otherwise, we simply complain.
813 * Note that we currently don't allow nested accesses themselves
814 * to contain any nested accesses, so we check if we can extract
815 * the access without any nesting and complain if we can't.
817 * The new parameter is resolved in resolve_nested.
819 isl_pw_aff *PetScan::nested_access(Expr *expr)
821 isl_id *id;
822 isl_space *dim;
823 isl_aff *aff;
824 isl_set *dom;
825 isl_multi_pw_aff *index;
827 if (!nesting_enabled) {
828 unsupported(expr);
829 return NULL;
832 allow_nested = false;
833 index = extract_index(expr);
834 allow_nested = true;
835 if (!index) {
836 unsupported(expr);
837 return NULL;
839 isl_multi_pw_aff_free(index);
841 id = pet_nested_clang_expr(ctx, expr);
842 dim = isl_space_params_alloc(ctx, 1);
844 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
846 dom = isl_set_universe(isl_space_copy(dim));
847 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
848 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
850 return isl_pw_aff_alloc(dom, aff);
853 /* Affine expressions are not supposed to contain array accesses,
854 * but if nesting is allowed, we return a parameter corresponding
855 * to the array access.
857 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
859 return nested_access(expr);
862 /* Affine expressions are not supposed to contain member accesses,
863 * but if nesting is allowed, we return a parameter corresponding
864 * to the member access.
866 __isl_give isl_pw_aff *PetScan::extract_affine(MemberExpr *expr)
868 return nested_access(expr);
871 /* Extract an affine expression from a conditional operation.
873 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
875 isl_pw_aff *cond, *lhs, *rhs;
877 cond = extract_condition(expr->getCond());
878 lhs = extract_affine(expr->getTrueExpr());
879 rhs = extract_affine(expr->getFalseExpr());
881 return isl_pw_aff_cond(cond, lhs, rhs);
884 /* Extract an affine expression, if possible, from "expr".
885 * Otherwise return NULL.
887 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
889 switch (expr->getStmtClass()) {
890 case Stmt::ImplicitCastExprClass:
891 return extract_affine(cast<ImplicitCastExpr>(expr));
892 case Stmt::IntegerLiteralClass:
893 return extract_affine(cast<IntegerLiteral>(expr));
894 case Stmt::DeclRefExprClass:
895 return extract_affine(cast<DeclRefExpr>(expr));
896 case Stmt::BinaryOperatorClass:
897 return extract_affine(cast<BinaryOperator>(expr));
898 case Stmt::UnaryOperatorClass:
899 return extract_affine(cast<UnaryOperator>(expr));
900 case Stmt::ParenExprClass:
901 return extract_affine(cast<ParenExpr>(expr));
902 case Stmt::CallExprClass:
903 return extract_affine(cast<CallExpr>(expr));
904 case Stmt::ArraySubscriptExprClass:
905 return extract_affine(cast<ArraySubscriptExpr>(expr));
906 case Stmt::MemberExprClass:
907 return extract_affine(cast<MemberExpr>(expr));
908 case Stmt::ConditionalOperatorClass:
909 return extract_affine(cast<ConditionalOperator>(expr));
910 default:
911 unsupported(expr);
913 return NULL;
916 __isl_give isl_multi_pw_aff *PetScan::extract_index(ImplicitCastExpr *expr)
918 return extract_index(expr->getSubExpr());
921 /* Return the depth of an array of the given type.
923 static int array_depth(const Type *type)
925 if (type->isPointerType())
926 return 1 + array_depth(type->getPointeeType().getTypePtr());
927 if (type->isArrayType()) {
928 const ArrayType *atype;
929 type = type->getCanonicalTypeInternal().getTypePtr();
930 atype = cast<ArrayType>(type);
931 return 1 + array_depth(atype->getElementType().getTypePtr());
933 return 0;
936 /* Return the depth of the array accessed by the index expression "index".
937 * If "index" is an affine expression, i.e., if it does not access
938 * any array, then return 1.
939 * If "index" represent a member access, i.e., if its range is a wrapped
940 * relation, then return the sum of the depth of the array of structures
941 * and that of the member inside the structure.
943 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
945 isl_id *id;
946 ValueDecl *decl;
948 if (!index)
949 return -1;
951 if (isl_multi_pw_aff_range_is_wrapping(index)) {
952 int domain_depth, range_depth;
953 isl_multi_pw_aff *domain, *range;
955 domain = isl_multi_pw_aff_copy(index);
956 domain = isl_multi_pw_aff_range_factor_domain(domain);
957 domain_depth = extract_depth(domain);
958 isl_multi_pw_aff_free(domain);
959 range = isl_multi_pw_aff_copy(index);
960 range = isl_multi_pw_aff_range_factor_range(range);
961 range_depth = extract_depth(range);
962 isl_multi_pw_aff_free(range);
964 return domain_depth + range_depth;
967 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
968 return 1;
970 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
971 if (!id)
972 return -1;
973 decl = (ValueDecl *) isl_id_get_user(id);
974 isl_id_free(id);
976 return array_depth(decl->getType().getTypePtr());
979 /* Extract an index expression from a reference to a variable.
980 * If the variable has name "A", then the returned index expression
981 * is of the form
983 * { [] -> A[] }
985 __isl_give isl_multi_pw_aff *PetScan::extract_index(DeclRefExpr *expr)
987 return extract_index(expr->getDecl());
990 /* Extract an index expression from a variable.
991 * If the variable has name "A", then the returned index expression
992 * is of the form
994 * { [] -> A[] }
996 __isl_give isl_multi_pw_aff *PetScan::extract_index(ValueDecl *decl)
998 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
999 isl_space *space = isl_space_alloc(ctx, 0, 0, 0);
1001 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1003 return isl_multi_pw_aff_zero(space);
1006 /* Extract an index expression from an integer contant.
1007 * If the value of the constant is "v", then the returned access relation
1008 * is
1010 * { [] -> [v] }
1012 __isl_give isl_multi_pw_aff *PetScan::extract_index(IntegerLiteral *expr)
1014 isl_multi_pw_aff *mpa;
1016 mpa = isl_multi_pw_aff_from_pw_aff(extract_affine(expr));
1017 mpa = isl_multi_pw_aff_from_range(mpa);
1018 return mpa;
1021 /* Try and extract an index expression from the given Expr.
1022 * Return NULL if it doesn't work out.
1024 __isl_give isl_multi_pw_aff *PetScan::extract_index(Expr *expr)
1026 switch (expr->getStmtClass()) {
1027 case Stmt::ImplicitCastExprClass:
1028 return extract_index(cast<ImplicitCastExpr>(expr));
1029 case Stmt::DeclRefExprClass:
1030 return extract_index(cast<DeclRefExpr>(expr));
1031 case Stmt::ArraySubscriptExprClass:
1032 return extract_index(cast<ArraySubscriptExpr>(expr));
1033 case Stmt::IntegerLiteralClass:
1034 return extract_index(cast<IntegerLiteral>(expr));
1035 case Stmt::MemberExprClass:
1036 return extract_index(cast<MemberExpr>(expr));
1037 default:
1038 unsupported(expr);
1040 return NULL;
1043 /* Given a partial index expression "base" and an extra index "index",
1044 * append the extra index to "base" and return the result.
1045 * Additionally, add the constraints that the extra index is non-negative.
1046 * If "index" represent a member access, i.e., if its range is a wrapped
1047 * relation, then we recursively extend the range of this nested relation.
1049 static __isl_give isl_multi_pw_aff *subscript(__isl_take isl_multi_pw_aff *base,
1050 __isl_take isl_pw_aff *index)
1052 isl_id *id;
1053 isl_set *domain;
1054 isl_multi_pw_aff *access;
1055 int member_access;
1057 member_access = isl_multi_pw_aff_range_is_wrapping(base);
1058 if (member_access < 0)
1059 goto error;
1060 if (member_access) {
1061 isl_multi_pw_aff *domain, *range;
1062 isl_id *id;
1064 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_out);
1065 domain = isl_multi_pw_aff_copy(base);
1066 domain = isl_multi_pw_aff_range_factor_domain(domain);
1067 range = isl_multi_pw_aff_range_factor_range(base);
1068 range = subscript(range, index);
1069 access = isl_multi_pw_aff_range_product(domain, range);
1070 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_out, id);
1071 return access;
1074 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_set);
1075 index = isl_pw_aff_from_range(index);
1076 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
1077 index = isl_pw_aff_intersect_domain(index, domain);
1078 access = isl_multi_pw_aff_from_pw_aff(index);
1079 access = isl_multi_pw_aff_flat_range_product(base, access);
1080 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_set, id);
1082 return access;
1083 error:
1084 isl_multi_pw_aff_free(base);
1085 isl_pw_aff_free(index);
1086 return NULL;
1089 /* Extract an index expression from the given array subscript expression.
1090 * If nesting is allowed in general, then we turn it on while
1091 * examining the index expression.
1093 * We first extract an index expression from the base.
1094 * This will result in an index expression with a range that corresponds
1095 * to the earlier indices.
1096 * We then extract the current index, restrict its domain
1097 * to those values that result in a non-negative index and
1098 * append the index to the base index expression.
1100 __isl_give isl_multi_pw_aff *PetScan::extract_index(ArraySubscriptExpr *expr)
1102 Expr *base = expr->getBase();
1103 Expr *idx = expr->getIdx();
1104 isl_pw_aff *index;
1105 isl_multi_pw_aff *base_access;
1106 isl_multi_pw_aff *access;
1107 bool save_nesting = nesting_enabled;
1109 nesting_enabled = allow_nested;
1111 base_access = extract_index(base);
1112 index = extract_affine(idx);
1114 nesting_enabled = save_nesting;
1116 access = subscript(base_access, index);
1118 return access;
1121 /* Construct a name for a member access by concatenating the name
1122 * of the array of structures and the member, separated by an underscore.
1124 * The caller is responsible for freeing the result.
1126 static char *member_access_name(isl_ctx *ctx, const char *base,
1127 const char *field)
1129 int len;
1130 char *name;
1132 len = strlen(base) + 1 + strlen(field);
1133 name = isl_alloc_array(ctx, char, len + 1);
1134 if (!name)
1135 return NULL;
1136 snprintf(name, len + 1, "%s_%s", base, field);
1138 return name;
1141 /* Given an index expression "base" for an element of an array of structures
1142 * and an expression "field" for the field member being accessed, construct
1143 * an index expression for an access to that member of the given structure.
1144 * In particular, take the range product of "base" and "field" and
1145 * attach a name to the result.
1147 static __isl_give isl_multi_pw_aff *member(__isl_take isl_multi_pw_aff *base,
1148 __isl_take isl_multi_pw_aff *field)
1150 isl_ctx *ctx;
1151 isl_multi_pw_aff *access;
1152 const char *base_name, *field_name;
1153 char *name;
1155 ctx = isl_multi_pw_aff_get_ctx(base);
1157 base_name = isl_multi_pw_aff_get_tuple_name(base, isl_dim_out);
1158 field_name = isl_multi_pw_aff_get_tuple_name(field, isl_dim_out);
1159 name = member_access_name(ctx, base_name, field_name);
1161 access = isl_multi_pw_aff_range_product(base, field);
1163 access = isl_multi_pw_aff_set_tuple_name(access, isl_dim_out, name);
1164 free(name);
1166 return access;
1169 /* Extract an index expression from a member expression.
1171 * If the base access (to the structure containing the member)
1172 * is of the form
1174 * [] -> A[..]
1176 * and the member is called "f", then the member access is of
1177 * the form
1179 * [] -> A_f[A[..] -> f[]]
1181 * If the member access is to an anonymous struct, then simply return
1183 * [] -> A[..]
1185 * If the member access in the source code is of the form
1187 * A->f
1189 * then it is treated as
1191 * A[0].f
1193 __isl_give isl_multi_pw_aff *PetScan::extract_index(MemberExpr *expr)
1195 Expr *base = expr->getBase();
1196 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
1197 isl_multi_pw_aff *base_access, *field_access;
1198 isl_id *id;
1199 isl_space *space;
1201 base_access = extract_index(base);
1203 if (expr->isArrow()) {
1204 isl_space *space = isl_space_params_alloc(ctx, 0);
1205 isl_local_space *ls = isl_local_space_from_space(space);
1206 isl_aff *aff = isl_aff_zero_on_domain(ls);
1207 isl_pw_aff *index = isl_pw_aff_from_aff(aff);
1208 base_access = subscript(base_access, index);
1211 if (field->isAnonymousStructOrUnion())
1212 return base_access;
1214 id = isl_id_alloc(ctx, field->getName().str().c_str(), field);
1215 space = isl_multi_pw_aff_get_domain_space(base_access);
1216 space = isl_space_from_domain(space);
1217 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1218 field_access = isl_multi_pw_aff_zero(space);
1220 return member(base_access, field_access);
1223 /* Check if "expr" calls function "minmax" with two arguments and if so
1224 * make lhs and rhs refer to these two arguments.
1226 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1228 CallExpr *call;
1229 FunctionDecl *fd;
1230 string name;
1232 if (expr->getStmtClass() != Stmt::CallExprClass)
1233 return false;
1235 call = cast<CallExpr>(expr);
1236 fd = call->getDirectCallee();
1237 if (!fd)
1238 return false;
1240 if (call->getNumArgs() != 2)
1241 return false;
1243 name = fd->getDeclName().getAsString();
1244 if (name != minmax)
1245 return false;
1247 lhs = call->getArg(0);
1248 rhs = call->getArg(1);
1250 return true;
1253 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1254 * lhs and rhs refer to the two arguments.
1256 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1258 return is_minmax(expr, "min", lhs, rhs);
1261 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1262 * lhs and rhs refer to the two arguments.
1264 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1266 return is_minmax(expr, "max", lhs, rhs);
1269 /* Return "lhs && rhs", defined on the shared definition domain.
1271 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1272 __isl_take isl_pw_aff *rhs)
1274 isl_set *cond;
1275 isl_set *dom;
1277 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1278 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1279 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1280 isl_pw_aff_non_zero_set(rhs));
1281 return indicator_function(cond, dom);
1284 /* Return "lhs && rhs", with shortcut semantics.
1285 * That is, if lhs is false, then the result is defined even if rhs is not.
1286 * In practice, we compute lhs ? rhs : lhs.
1288 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1289 __isl_take isl_pw_aff *rhs)
1291 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1294 /* Return "lhs || rhs", with shortcut semantics.
1295 * That is, if lhs is true, then the result is defined even if rhs is not.
1296 * In practice, we compute lhs ? lhs : rhs.
1298 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1299 __isl_take isl_pw_aff *rhs)
1301 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1304 /* Extract an affine expressions representing the comparison "LHS op RHS"
1305 * "comp" is the original statement that "LHS op RHS" is derived from
1306 * and is used for diagnostics.
1308 * If the comparison is of the form
1310 * a <= min(b,c)
1312 * then the expression is constructed as the conjunction of
1313 * the comparisons
1315 * a <= b and a <= c
1317 * A similar optimization is performed for max(a,b) <= c.
1318 * We do this because that will lead to simpler representations
1319 * of the expression.
1320 * If isl is ever enhanced to explicitly deal with min and max expressions,
1321 * this optimization can be removed.
1323 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1324 Expr *LHS, Expr *RHS, Stmt *comp)
1326 isl_pw_aff *lhs;
1327 isl_pw_aff *rhs;
1328 isl_pw_aff *res;
1329 isl_set *cond;
1330 isl_set *dom;
1332 if (op == BO_GT)
1333 return extract_comparison(BO_LT, RHS, LHS, comp);
1334 if (op == BO_GE)
1335 return extract_comparison(BO_LE, RHS, LHS, comp);
1337 if (op == BO_LT || op == BO_LE) {
1338 Expr *expr1, *expr2;
1339 if (is_min(RHS, expr1, expr2)) {
1340 lhs = extract_comparison(op, LHS, expr1, comp);
1341 rhs = extract_comparison(op, LHS, expr2, comp);
1342 return pw_aff_and(lhs, rhs);
1344 if (is_max(LHS, expr1, expr2)) {
1345 lhs = extract_comparison(op, expr1, RHS, comp);
1346 rhs = extract_comparison(op, expr2, RHS, comp);
1347 return pw_aff_and(lhs, rhs);
1351 lhs = extract_affine(LHS);
1352 rhs = extract_affine(RHS);
1354 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1355 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1357 switch (op) {
1358 case BO_LT:
1359 cond = isl_pw_aff_lt_set(lhs, rhs);
1360 break;
1361 case BO_LE:
1362 cond = isl_pw_aff_le_set(lhs, rhs);
1363 break;
1364 case BO_EQ:
1365 cond = isl_pw_aff_eq_set(lhs, rhs);
1366 break;
1367 case BO_NE:
1368 cond = isl_pw_aff_ne_set(lhs, rhs);
1369 break;
1370 default:
1371 isl_pw_aff_free(lhs);
1372 isl_pw_aff_free(rhs);
1373 isl_set_free(dom);
1374 unsupported(comp);
1375 return NULL;
1378 cond = isl_set_coalesce(cond);
1379 res = indicator_function(cond, dom);
1381 return res;
1384 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1386 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1387 comp->getRHS(), comp);
1390 /* Extract an affine expression representing the negation (logical not)
1391 * of a subexpression.
1393 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1395 isl_set *set_cond, *dom;
1396 isl_pw_aff *cond, *res;
1398 cond = extract_condition(op->getSubExpr());
1400 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1402 set_cond = isl_pw_aff_zero_set(cond);
1404 res = indicator_function(set_cond, dom);
1406 return res;
1409 /* Extract an affine expression representing the disjunction (logical or)
1410 * or conjunction (logical and) of two subexpressions.
1412 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1414 isl_pw_aff *lhs, *rhs;
1416 lhs = extract_condition(comp->getLHS());
1417 rhs = extract_condition(comp->getRHS());
1419 switch (comp->getOpcode()) {
1420 case BO_LAnd:
1421 return pw_aff_and_then(lhs, rhs);
1422 case BO_LOr:
1423 return pw_aff_or_else(lhs, rhs);
1424 default:
1425 isl_pw_aff_free(lhs);
1426 isl_pw_aff_free(rhs);
1429 unsupported(comp);
1430 return NULL;
1433 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1435 switch (expr->getOpcode()) {
1436 case UO_LNot:
1437 return extract_boolean(expr);
1438 default:
1439 unsupported(expr);
1440 return NULL;
1444 /* Extract the affine expression "expr != 0 ? 1 : 0".
1446 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1448 isl_pw_aff *res;
1449 isl_set *set, *dom;
1451 res = extract_affine(expr);
1453 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1454 set = isl_pw_aff_non_zero_set(res);
1456 res = indicator_function(set, dom);
1458 return res;
1461 /* Extract an affine expression from a boolean expression.
1462 * In particular, return the expression "expr ? 1 : 0".
1464 * If the expression doesn't look like a condition, we assume it
1465 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1467 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1469 BinaryOperator *comp;
1471 if (!expr) {
1472 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1473 return indicator_function(u, isl_set_copy(u));
1476 if (expr->getStmtClass() == Stmt::ParenExprClass)
1477 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1479 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1480 return extract_condition(cast<UnaryOperator>(expr));
1482 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1483 return extract_implicit_condition(expr);
1485 comp = cast<BinaryOperator>(expr);
1486 switch (comp->getOpcode()) {
1487 case BO_LT:
1488 case BO_LE:
1489 case BO_GT:
1490 case BO_GE:
1491 case BO_EQ:
1492 case BO_NE:
1493 return extract_comparison(comp);
1494 case BO_LAnd:
1495 case BO_LOr:
1496 return extract_boolean(comp);
1497 default:
1498 return extract_implicit_condition(expr);
1502 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1504 switch (kind) {
1505 case UO_Minus:
1506 return pet_op_minus;
1507 case UO_Not:
1508 return pet_op_not;
1509 case UO_LNot:
1510 return pet_op_lnot;
1511 case UO_PostInc:
1512 return pet_op_post_inc;
1513 case UO_PostDec:
1514 return pet_op_post_dec;
1515 case UO_PreInc:
1516 return pet_op_pre_inc;
1517 case UO_PreDec:
1518 return pet_op_pre_dec;
1519 default:
1520 return pet_op_last;
1524 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1526 switch (kind) {
1527 case BO_AddAssign:
1528 return pet_op_add_assign;
1529 case BO_SubAssign:
1530 return pet_op_sub_assign;
1531 case BO_MulAssign:
1532 return pet_op_mul_assign;
1533 case BO_DivAssign:
1534 return pet_op_div_assign;
1535 case BO_Assign:
1536 return pet_op_assign;
1537 case BO_Add:
1538 return pet_op_add;
1539 case BO_Sub:
1540 return pet_op_sub;
1541 case BO_Mul:
1542 return pet_op_mul;
1543 case BO_Div:
1544 return pet_op_div;
1545 case BO_Rem:
1546 return pet_op_mod;
1547 case BO_Shl:
1548 return pet_op_shl;
1549 case BO_Shr:
1550 return pet_op_shr;
1551 case BO_EQ:
1552 return pet_op_eq;
1553 case BO_NE:
1554 return pet_op_ne;
1555 case BO_LE:
1556 return pet_op_le;
1557 case BO_GE:
1558 return pet_op_ge;
1559 case BO_LT:
1560 return pet_op_lt;
1561 case BO_GT:
1562 return pet_op_gt;
1563 case BO_And:
1564 return pet_op_and;
1565 case BO_Xor:
1566 return pet_op_xor;
1567 case BO_Or:
1568 return pet_op_or;
1569 case BO_LAnd:
1570 return pet_op_land;
1571 case BO_LOr:
1572 return pet_op_lor;
1573 default:
1574 return pet_op_last;
1578 /* Construct a pet_expr representing a unary operator expression.
1580 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1582 struct pet_expr *arg;
1583 enum pet_op_type op;
1585 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1586 if (op == pet_op_last) {
1587 unsupported(expr);
1588 return NULL;
1591 arg = extract_expr(expr->getSubExpr());
1593 if (expr->isIncrementDecrementOp() &&
1594 arg && arg->type == pet_expr_access) {
1595 mark_write(arg);
1596 arg->acc.read = 1;
1599 return pet_expr_new_unary(ctx, op, arg);
1602 /* Mark the given access pet_expr as a write.
1603 * If a scalar is being accessed, then mark its value
1604 * as unknown in assigned_value.
1606 void PetScan::mark_write(struct pet_expr *access)
1608 isl_id *id;
1609 ValueDecl *decl;
1611 if (!access)
1612 return;
1614 access->acc.write = 1;
1615 access->acc.read = 0;
1617 if (!pet_expr_is_scalar_access(access))
1618 return;
1620 id = pet_expr_access_get_id(access);
1621 decl = (ValueDecl *) isl_id_get_user(id);
1622 clear_assignment(assigned_value, decl);
1623 isl_id_free(id);
1626 /* Assign "rhs" to "lhs".
1628 * In particular, if "lhs" is a scalar variable, then mark
1629 * the variable as having been assigned. If, furthermore, "rhs"
1630 * is an affine expression, then keep track of this value in assigned_value
1631 * so that we can plug it in when we later come across the same variable.
1633 void PetScan::assign(struct pet_expr *lhs, Expr *rhs)
1635 isl_id *id;
1636 ValueDecl *decl;
1637 isl_pw_aff *pa;
1639 if (!lhs)
1640 return;
1641 if (!pet_expr_is_scalar_access(lhs))
1642 return;
1644 id = pet_expr_access_get_id(lhs);
1645 decl = (ValueDecl *) isl_id_get_user(id);
1646 isl_id_free(id);
1648 pa = try_extract_affine(rhs);
1649 clear_assignment(assigned_value, decl);
1650 if (!pa)
1651 return;
1652 assigned_value[decl] = pa;
1653 insert_expression(pa);
1656 /* Construct a pet_expr representing a binary operator expression.
1658 * If the top level operator is an assignment and the LHS is an access,
1659 * then we mark that access as a write. If the operator is a compound
1660 * assignment, the access is marked as both a read and a write.
1662 * If "expr" assigns something to a scalar variable, then we mark
1663 * the variable as having been assigned. If, furthermore, the expression
1664 * is affine, then keep track of this value in assigned_value
1665 * so that we can plug it in when we later come across the same variable.
1667 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1669 struct pet_expr *lhs, *rhs;
1670 enum pet_op_type op;
1672 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1673 if (op == pet_op_last) {
1674 unsupported(expr);
1675 return NULL;
1678 lhs = extract_expr(expr->getLHS());
1679 rhs = extract_expr(expr->getRHS());
1681 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1682 mark_write(lhs);
1683 if (expr->isCompoundAssignmentOp())
1684 lhs->acc.read = 1;
1687 if (expr->getOpcode() == BO_Assign)
1688 assign(lhs, expr->getRHS());
1690 return pet_expr_new_binary(ctx, op, lhs, rhs);
1693 /* Construct a pet_scop with a single statement killing the entire
1694 * array "array".
1696 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1698 isl_id *id;
1699 isl_space *space;
1700 isl_multi_pw_aff *index;
1701 isl_map *access;
1702 struct pet_expr *expr;
1704 if (!array)
1705 return NULL;
1706 access = isl_map_from_range(isl_set_copy(array->extent));
1707 id = isl_set_get_tuple_id(array->extent);
1708 space = isl_space_alloc(ctx, 0, 0, 0);
1709 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1710 index = isl_multi_pw_aff_zero(space);
1711 expr = pet_expr_kill_from_access_and_index(access, index);
1712 return extract(stmt, expr);
1715 /* Construct a pet_scop for a (single) variable declaration.
1717 * The scop contains the variable being declared (as an array)
1718 * and a statement killing the array.
1720 * If the variable is initialized in the AST, then the scop
1721 * also contains an assignment to the variable.
1723 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1725 Decl *decl;
1726 VarDecl *vd;
1727 struct pet_expr *lhs, *rhs, *pe;
1728 struct pet_scop *scop_decl, *scop;
1729 struct pet_array *array;
1731 if (!stmt->isSingleDecl()) {
1732 unsupported(stmt);
1733 return NULL;
1736 decl = stmt->getSingleDecl();
1737 vd = cast<VarDecl>(decl);
1739 array = extract_array(ctx, vd, NULL);
1740 if (array)
1741 array->declared = 1;
1742 scop_decl = kill(stmt, array);
1743 scop_decl = pet_scop_add_array(scop_decl, array);
1745 if (!vd->getInit())
1746 return scop_decl;
1748 lhs = extract_access_expr(vd);
1749 rhs = extract_expr(vd->getInit());
1751 mark_write(lhs);
1752 assign(lhs, vd->getInit());
1754 pe = pet_expr_new_binary(ctx, pet_op_assign, lhs, rhs);
1755 scop = extract(stmt, pe);
1757 scop_decl = pet_scop_prefix(scop_decl, 0);
1758 scop = pet_scop_prefix(scop, 1);
1760 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1762 return scop;
1765 /* Construct a pet_expr representing a conditional operation.
1767 * We first try to extract the condition as an affine expression.
1768 * If that fails, we construct a pet_expr tree representing the condition.
1770 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1772 struct pet_expr *cond, *lhs, *rhs;
1773 isl_pw_aff *pa;
1775 pa = try_extract_affine(expr->getCond());
1776 if (pa) {
1777 isl_multi_pw_aff *test = isl_multi_pw_aff_from_pw_aff(pa);
1778 test = isl_multi_pw_aff_from_range(test);
1779 cond = pet_expr_from_index(test);
1780 } else
1781 cond = extract_expr(expr->getCond());
1782 lhs = extract_expr(expr->getTrueExpr());
1783 rhs = extract_expr(expr->getFalseExpr());
1785 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1788 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1790 return extract_expr(expr->getSubExpr());
1793 /* Construct a pet_expr representing a floating point value.
1795 * If the floating point literal does not appear in a macro,
1796 * then we use the original representation in the source code
1797 * as the string representation. Otherwise, we use the pretty
1798 * printer to produce a string representation.
1800 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1802 double d;
1803 string s;
1804 const LangOptions &LO = PP.getLangOpts();
1805 SourceLocation loc = expr->getLocation();
1807 if (!loc.isMacroID()) {
1808 SourceManager &SM = PP.getSourceManager();
1809 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1810 s = string(SM.getCharacterData(loc), len);
1811 } else {
1812 llvm::raw_string_ostream S(s);
1813 expr->printPretty(S, 0, PrintingPolicy(LO));
1814 S.str();
1816 d = expr->getValueAsApproximateDouble();
1817 return pet_expr_new_double(ctx, d, s.c_str());
1820 /* Extract an index expression from "expr" and then convert it into
1821 * an access pet_expr.
1823 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1825 isl_multi_pw_aff *index;
1826 struct pet_expr *pe;
1827 int depth;
1829 index = extract_index(expr);
1830 depth = extract_depth(index);
1832 pe = pet_expr_from_index_and_depth(index, depth);
1834 return pe;
1837 /* Extract an index expression from "decl" and then convert it into
1838 * an access pet_expr.
1840 struct pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1842 isl_multi_pw_aff *index;
1843 struct pet_expr *pe;
1844 int depth;
1846 index = extract_index(decl);
1847 depth = extract_depth(index);
1849 pe = pet_expr_from_index_and_depth(index, depth);
1851 return pe;
1854 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1856 return extract_expr(expr->getSubExpr());
1859 /* Extract an assume statement from the argument "expr"
1860 * of a __pencil_assume statement.
1862 struct pet_expr *PetScan::extract_assume(Expr *expr)
1864 isl_pw_aff *cond;
1865 struct pet_expr *res;
1867 cond = try_extract_affine_condition(expr);
1868 if (!cond) {
1869 res = extract_expr(expr);
1870 } else {
1871 isl_multi_pw_aff *index;
1872 index = isl_multi_pw_aff_from_pw_aff(cond);
1873 index = isl_multi_pw_aff_from_range(index);
1874 res = pet_expr_from_index(index);
1876 return pet_expr_new_unary(ctx, pet_op_assume, res);
1879 /* Construct a pet_expr corresponding to the function call argument "expr".
1880 * The argument appears in position "pos" of a call to function "fd".
1882 * If we are passing along a pointer to an array element
1883 * or an entire row or even higher dimensional slice of an array,
1884 * then the function being called may write into the array.
1886 * We assume here that if the function is declared to take a pointer
1887 * to a const type, then the function will perform a read
1888 * and that otherwise, it will perform a write.
1890 struct pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
1891 Expr *expr)
1893 struct pet_expr *res;
1894 int is_addr = 0, is_partial = 0;
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 if (!res)
1910 return NULL;
1911 sc = expr->getStmtClass();
1912 if ((sc == Stmt::ArraySubscriptExprClass ||
1913 sc == Stmt::MemberExprClass) &&
1914 array_depth(expr->getType().getTypePtr()) > 0)
1915 is_partial = 1;
1916 if ((is_addr || is_partial) && res->type == pet_expr_access) {
1917 ParmVarDecl *parm;
1918 if (!fd->hasPrototype()) {
1919 report_prototype_required(expr);
1920 return pet_expr_free(res);
1922 parm = fd->getParamDecl(pos);
1923 if (!const_base(parm->getType()))
1924 mark_write(res);
1927 if (is_addr)
1928 res = pet_expr_new_unary(ctx, pet_op_address_of, res);
1929 return res;
1932 /* Construct a pet_expr representing a function call.
1934 * In the special case of a "call" to __pencil_assume,
1935 * construct an assume expression instead.
1937 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1939 struct pet_expr *res = NULL;
1940 FunctionDecl *fd;
1941 string name;
1942 unsigned n_arg;
1944 fd = expr->getDirectCallee();
1945 if (!fd) {
1946 unsupported(expr);
1947 return NULL;
1950 name = fd->getDeclName().getAsString();
1951 n_arg = expr->getNumArgs();
1953 if (n_arg == 1 && name == "__pencil_assume")
1954 return extract_assume(expr->getArg(0));
1956 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1957 if (!res)
1958 return NULL;
1960 for (int i = 0; i < n_arg; ++i) {
1961 Expr *arg = expr->getArg(i);
1962 res->args[i] = PetScan::extract_argument(fd, i, arg);
1963 if (!res->args[i])
1964 goto error;
1967 return res;
1968 error:
1969 pet_expr_free(res);
1970 return NULL;
1973 /* Construct a pet_expr representing a (C style) cast.
1975 struct pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1977 struct pet_expr *arg;
1978 QualType type;
1980 arg = extract_expr(expr->getSubExpr());
1981 if (!arg)
1982 return NULL;
1984 type = expr->getTypeAsWritten();
1985 return pet_expr_new_cast(ctx, type.getAsString().c_str(), arg);
1988 /* Construct a pet_expr representing an integer.
1990 struct pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1992 return pet_expr_new_int(extract_int(expr));
1995 /* Try and construct a pet_expr representing "expr".
1997 struct pet_expr *PetScan::extract_expr(Expr *expr)
1999 switch (expr->getStmtClass()) {
2000 case Stmt::UnaryOperatorClass:
2001 return extract_expr(cast<UnaryOperator>(expr));
2002 case Stmt::CompoundAssignOperatorClass:
2003 case Stmt::BinaryOperatorClass:
2004 return extract_expr(cast<BinaryOperator>(expr));
2005 case Stmt::ImplicitCastExprClass:
2006 return extract_expr(cast<ImplicitCastExpr>(expr));
2007 case Stmt::ArraySubscriptExprClass:
2008 case Stmt::DeclRefExprClass:
2009 case Stmt::MemberExprClass:
2010 return extract_access_expr(expr);
2011 case Stmt::IntegerLiteralClass:
2012 return extract_expr(cast<IntegerLiteral>(expr));
2013 case Stmt::FloatingLiteralClass:
2014 return extract_expr(cast<FloatingLiteral>(expr));
2015 case Stmt::ParenExprClass:
2016 return extract_expr(cast<ParenExpr>(expr));
2017 case Stmt::ConditionalOperatorClass:
2018 return extract_expr(cast<ConditionalOperator>(expr));
2019 case Stmt::CallExprClass:
2020 return extract_expr(cast<CallExpr>(expr));
2021 case Stmt::CStyleCastExprClass:
2022 return extract_expr(cast<CStyleCastExpr>(expr));
2023 default:
2024 unsupported(expr);
2026 return NULL;
2029 /* Check if the given initialization statement is an assignment.
2030 * If so, return that assignment. Otherwise return NULL.
2032 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
2034 BinaryOperator *ass;
2036 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
2037 return NULL;
2039 ass = cast<BinaryOperator>(init);
2040 if (ass->getOpcode() != BO_Assign)
2041 return NULL;
2043 return ass;
2046 /* Check if the given initialization statement is a declaration
2047 * of a single variable.
2048 * If so, return that declaration. Otherwise return NULL.
2050 Decl *PetScan::initialization_declaration(Stmt *init)
2052 DeclStmt *decl;
2054 if (init->getStmtClass() != Stmt::DeclStmtClass)
2055 return NULL;
2057 decl = cast<DeclStmt>(init);
2059 if (!decl->isSingleDecl())
2060 return NULL;
2062 return decl->getSingleDecl();
2065 /* Given the assignment operator in the initialization of a for loop,
2066 * extract the induction variable, i.e., the (integer)variable being
2067 * assigned.
2069 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
2071 Expr *lhs;
2072 DeclRefExpr *ref;
2073 ValueDecl *decl;
2074 const Type *type;
2076 lhs = init->getLHS();
2077 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2078 unsupported(init);
2079 return NULL;
2082 ref = cast<DeclRefExpr>(lhs);
2083 decl = ref->getDecl();
2084 type = decl->getType().getTypePtr();
2086 if (!type->isIntegerType()) {
2087 unsupported(lhs);
2088 return NULL;
2091 return decl;
2094 /* Given the initialization statement of a for loop and the single
2095 * declaration in this initialization statement,
2096 * extract the induction variable, i.e., the (integer) variable being
2097 * declared.
2099 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
2101 VarDecl *vd;
2103 vd = cast<VarDecl>(decl);
2105 const QualType type = vd->getType();
2106 if (!type->isIntegerType()) {
2107 unsupported(init);
2108 return NULL;
2111 if (!vd->getInit()) {
2112 unsupported(init);
2113 return NULL;
2116 return vd;
2119 /* Check that op is of the form iv++ or iv--.
2120 * Return an affine expression "1" or "-1" accordingly.
2122 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
2123 clang::UnaryOperator *op, clang::ValueDecl *iv)
2125 Expr *sub;
2126 DeclRefExpr *ref;
2127 isl_space *space;
2128 isl_aff *aff;
2130 if (!op->isIncrementDecrementOp()) {
2131 unsupported(op);
2132 return NULL;
2135 sub = op->getSubExpr();
2136 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
2137 unsupported(op);
2138 return NULL;
2141 ref = cast<DeclRefExpr>(sub);
2142 if (ref->getDecl() != iv) {
2143 unsupported(op);
2144 return NULL;
2147 space = isl_space_params_alloc(ctx, 0);
2148 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2150 if (op->isIncrementOp())
2151 aff = isl_aff_add_constant_si(aff, 1);
2152 else
2153 aff = isl_aff_add_constant_si(aff, -1);
2155 return isl_pw_aff_from_aff(aff);
2158 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
2159 * has a single constant expression, then put this constant in *user.
2160 * The caller is assumed to have checked that this function will
2161 * be called exactly once.
2163 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
2164 void *user)
2166 isl_val **inc = (isl_val **)user;
2167 int res = 0;
2169 if (isl_aff_is_cst(aff))
2170 *inc = isl_aff_get_constant_val(aff);
2171 else
2172 res = -1;
2174 isl_set_free(set);
2175 isl_aff_free(aff);
2177 return res;
2180 /* Check if op is of the form
2182 * iv = iv + inc
2184 * and return inc as an affine expression.
2186 * We extract an affine expression from the RHS, subtract iv and return
2187 * the result.
2189 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
2190 clang::ValueDecl *iv)
2192 Expr *lhs;
2193 DeclRefExpr *ref;
2194 isl_id *id;
2195 isl_space *dim;
2196 isl_aff *aff;
2197 isl_pw_aff *val;
2199 if (op->getOpcode() != BO_Assign) {
2200 unsupported(op);
2201 return NULL;
2204 lhs = op->getLHS();
2205 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2206 unsupported(op);
2207 return NULL;
2210 ref = cast<DeclRefExpr>(lhs);
2211 if (ref->getDecl() != iv) {
2212 unsupported(op);
2213 return NULL;
2216 val = extract_affine(op->getRHS());
2218 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2220 dim = isl_space_params_alloc(ctx, 1);
2221 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2222 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2223 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2225 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
2227 return val;
2230 /* Check that op is of the form iv += cst or iv -= cst
2231 * and return an affine expression corresponding oto cst or -cst accordingly.
2233 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
2234 CompoundAssignOperator *op, clang::ValueDecl *iv)
2236 Expr *lhs;
2237 DeclRefExpr *ref;
2238 bool neg = false;
2239 isl_pw_aff *val;
2240 BinaryOperatorKind opcode;
2242 opcode = op->getOpcode();
2243 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
2244 unsupported(op);
2245 return NULL;
2247 if (opcode == BO_SubAssign)
2248 neg = true;
2250 lhs = op->getLHS();
2251 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2252 unsupported(op);
2253 return NULL;
2256 ref = cast<DeclRefExpr>(lhs);
2257 if (ref->getDecl() != iv) {
2258 unsupported(op);
2259 return NULL;
2262 val = extract_affine(op->getRHS());
2263 if (neg)
2264 val = isl_pw_aff_neg(val);
2266 return val;
2269 /* Check that the increment of the given for loop increments
2270 * (or decrements) the induction variable "iv" and return
2271 * the increment as an affine expression if successful.
2273 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
2274 ValueDecl *iv)
2276 Stmt *inc = stmt->getInc();
2278 if (!inc) {
2279 report_missing_increment(stmt);
2280 return NULL;
2283 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
2284 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
2285 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
2286 return extract_compound_increment(
2287 cast<CompoundAssignOperator>(inc), iv);
2288 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
2289 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
2291 unsupported(inc);
2292 return NULL;
2295 /* Embed the given iteration domain in an extra outer loop
2296 * with induction variable "var".
2297 * If this variable appeared as a parameter in the constraints,
2298 * it is replaced by the new outermost dimension.
2300 static __isl_give isl_set *embed(__isl_take isl_set *set,
2301 __isl_take isl_id *var)
2303 int pos;
2305 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
2306 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
2307 if (pos >= 0) {
2308 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
2309 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2312 isl_id_free(var);
2313 return set;
2316 /* Return those elements in the space of "cond" that come after
2317 * (based on "sign") an element in "cond".
2319 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
2321 isl_map *previous_to_this;
2323 if (sign > 0)
2324 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
2325 else
2326 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
2328 cond = isl_set_apply(cond, previous_to_this);
2330 return cond;
2333 /* Create the infinite iteration domain
2335 * { [id] : id >= 0 }
2337 * If "scop" has an affine skip of type pet_skip_later,
2338 * then remove those iterations i that have an earlier iteration
2339 * where the skip condition is satisfied, meaning that iteration i
2340 * is not executed.
2341 * Since we are dealing with a loop without loop iterator,
2342 * the skip condition cannot refer to the current loop iterator and
2343 * so effectively, the returned set is of the form
2345 * { [0]; [id] : id >= 1 and not skip }
2347 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
2348 struct pet_scop *scop)
2350 isl_ctx *ctx = isl_id_get_ctx(id);
2351 isl_set *domain;
2352 isl_set *skip;
2354 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
2355 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
2357 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
2358 return domain;
2360 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2361 skip = embed(skip, isl_id_copy(id));
2362 skip = isl_set_intersect(skip , isl_set_copy(domain));
2363 domain = isl_set_subtract(domain, after(skip, 1));
2365 return domain;
2368 /* Create an identity affine expression on the space containing "domain",
2369 * which is assumed to be one-dimensional.
2371 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
2373 isl_local_space *ls;
2375 ls = isl_local_space_from_space(isl_set_get_space(domain));
2376 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
2379 /* Create an affine expression that maps elements
2380 * of a single-dimensional array "id_test" to the previous element
2381 * (according to "inc"), provided this element belongs to "domain".
2382 * That is, create the affine expression
2384 * { id[x] -> id[x - inc] : x - inc in domain }
2386 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
2387 __isl_take isl_set *domain, __isl_take isl_val *inc)
2389 isl_space *space;
2390 isl_local_space *ls;
2391 isl_aff *aff;
2392 isl_multi_pw_aff *prev;
2394 space = isl_set_get_space(domain);
2395 ls = isl_local_space_from_space(space);
2396 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2397 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
2398 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
2399 domain = isl_set_preimage_multi_pw_aff(domain,
2400 isl_multi_pw_aff_copy(prev));
2401 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
2402 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
2404 return prev;
2407 /* Add an implication to "scop" expressing that if an element of
2408 * virtual array "id_test" has value "satisfied" then all previous elements
2409 * of this array also have that value. The set of previous elements
2410 * is bounded by "domain". If "sign" is negative then the iterator
2411 * is decreasing and we express that all subsequent array elements
2412 * (but still defined previously) have the same value.
2414 static struct pet_scop *add_implication(struct pet_scop *scop,
2415 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
2416 int satisfied)
2418 isl_space *space;
2419 isl_map *map;
2421 domain = isl_set_set_tuple_id(domain, id_test);
2422 space = isl_set_get_space(domain);
2423 if (sign > 0)
2424 map = isl_map_lex_ge(space);
2425 else
2426 map = isl_map_lex_le(space);
2427 map = isl_map_intersect_range(map, domain);
2428 scop = pet_scop_add_implication(scop, map, satisfied);
2430 return scop;
2433 /* Add a filter to "scop" that imposes that it is only executed
2434 * when the variable identified by "id_test" has a zero value
2435 * for all previous iterations of "domain".
2437 * In particular, add a filter that imposes that the array
2438 * has a zero value at the previous iteration of domain and
2439 * add an implication that implies that it then has that
2440 * value for all previous iterations.
2442 static struct pet_scop *scop_add_break(struct pet_scop *scop,
2443 __isl_take isl_id *id_test, __isl_take isl_set *domain,
2444 __isl_take isl_val *inc)
2446 isl_multi_pw_aff *prev;
2447 int sign = isl_val_sgn(inc);
2449 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2450 scop = add_implication(scop, id_test, domain, sign, 0);
2451 scop = pet_scop_filter(scop, prev, 0);
2453 return scop;
2456 /* Construct a pet_scop for an infinite loop around the given body.
2458 * We extract a pet_scop for the body and then embed it in a loop with
2459 * iteration domain
2461 * { [t] : t >= 0 }
2463 * and schedule
2465 * { [t] -> [t] }
2467 * If the body contains any break, then it is taken into
2468 * account in infinite_domain (if the skip condition is affine)
2469 * or in scop_add_break (if the skip condition is not affine).
2471 * If we were only able to extract part of the body, then simply
2472 * return that part.
2474 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2476 isl_id *id, *id_test;
2477 isl_set *domain;
2478 isl_aff *ident;
2479 struct pet_scop *scop;
2480 bool has_var_break;
2482 scop = extract(body);
2483 if (!scop)
2484 return NULL;
2485 if (partial)
2486 return scop;
2488 id = isl_id_alloc(ctx, "t", NULL);
2489 domain = infinite_domain(isl_id_copy(id), scop);
2490 ident = identity_aff(domain);
2492 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2493 if (has_var_break)
2494 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
2496 scop = pet_scop_embed(scop, isl_set_copy(domain),
2497 isl_aff_copy(ident), ident, id);
2498 if (has_var_break)
2499 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
2500 else
2501 isl_set_free(domain);
2503 return scop;
2506 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2508 * for (;;)
2509 * body
2512 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2514 clear_assignments clear(assigned_value);
2515 clear.TraverseStmt(stmt->getBody());
2517 return extract_infinite_loop(stmt->getBody());
2520 /* Create an index expression for an access to a virtual array
2521 * representing the result of a condition.
2522 * Unlike other accessed data, the id of the array is NULL as
2523 * there is no ValueDecl in the program corresponding to the virtual
2524 * array.
2525 * The array starts out as a scalar, but grows along with the
2526 * statement writing to the array in pet_scop_embed.
2528 static __isl_give isl_multi_pw_aff *create_test_index(isl_ctx *ctx, int test_nr)
2530 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2531 isl_id *id;
2532 char name[50];
2534 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2535 id = isl_id_alloc(ctx, name, NULL);
2536 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2537 return isl_multi_pw_aff_zero(dim);
2540 /* Add an array with the given extent (range of "index") to the list
2541 * of arrays in "scop" and return the extended pet_scop.
2542 * The array is marked as attaining values 0 and 1 only and
2543 * as each element being assigned at most once.
2545 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2546 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
2548 isl_ctx *ctx = isl_multi_pw_aff_get_ctx(index);
2549 isl_space *dim;
2550 struct pet_array *array;
2551 isl_map *access;
2553 if (!scop)
2554 return NULL;
2555 if (!ctx)
2556 goto error;
2558 array = isl_calloc_type(ctx, struct pet_array);
2559 if (!array)
2560 goto error;
2562 access = isl_map_from_multi_pw_aff(isl_multi_pw_aff_copy(index));
2563 array->extent = isl_map_range(access);
2564 dim = isl_space_params_alloc(ctx, 0);
2565 array->context = isl_set_universe(dim);
2566 dim = isl_space_set_alloc(ctx, 0, 1);
2567 array->value_bounds = isl_set_universe(dim);
2568 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2569 isl_dim_set, 0, 0);
2570 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2571 isl_dim_set, 0, 1);
2572 array->element_type = strdup("int");
2573 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2574 array->uniquely_defined = 1;
2576 if (!array->extent || !array->context)
2577 array = pet_array_free(array);
2579 scop = pet_scop_add_array(scop, array);
2581 return scop;
2582 error:
2583 pet_scop_free(scop);
2584 return NULL;
2587 /* Construct a pet_scop for a while loop of the form
2589 * while (pa)
2590 * body
2592 * In particular, construct a scop for an infinite loop around body and
2593 * intersect the domain with the affine expression.
2594 * Note that this intersection may result in an empty loop.
2596 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2597 Stmt *body)
2599 struct pet_scop *scop;
2600 isl_set *dom;
2601 isl_set *valid;
2603 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2604 dom = isl_pw_aff_non_zero_set(pa);
2605 scop = extract_infinite_loop(body);
2606 scop = pet_scop_restrict(scop, dom);
2607 scop = pet_scop_restrict_context(scop, valid);
2609 return scop;
2612 /* Construct a scop for a while, given the scops for the condition
2613 * and the body, the filter identifier and the iteration domain of
2614 * the while loop.
2616 * In particular, the scop for the condition is filtered to depend
2617 * on "id_test" evaluating to true for all previous iterations
2618 * of the loop, while the scop for the body is filtered to depend
2619 * on "id_test" evaluating to true for all iterations up to the
2620 * current iteration.
2621 * The actual filter only imposes that this virtual array has
2622 * value one on the previous or the current iteration.
2623 * The fact that this condition also applies to the previous
2624 * iterations is enforced by an implication.
2626 * These filtered scops are then combined into a single scop.
2628 * "sign" is positive if the iterator increases and negative
2629 * if it decreases.
2631 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2632 struct pet_scop *scop_body, __isl_take isl_id *id_test,
2633 __isl_take isl_set *domain, __isl_take isl_val *inc)
2635 isl_ctx *ctx = isl_set_get_ctx(domain);
2636 isl_space *space;
2637 isl_multi_pw_aff *test_index;
2638 isl_multi_pw_aff *prev;
2639 int sign = isl_val_sgn(inc);
2640 struct pet_scop *scop;
2642 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2643 scop_cond = pet_scop_filter(scop_cond, prev, 1);
2645 space = isl_space_map_from_set(isl_set_get_space(domain));
2646 test_index = isl_multi_pw_aff_identity(space);
2647 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
2648 isl_id_copy(id_test));
2649 scop_body = pet_scop_filter(scop_body, test_index, 1);
2651 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
2652 scop = add_implication(scop, id_test, domain, sign, 1);
2654 return scop;
2657 /* Check if the while loop is of the form
2659 * while (affine expression)
2660 * body
2662 * If so, call extract_affine_while to construct a scop.
2664 * Otherwise, construct a generic while scop, with iteration domain
2665 * { [t] : t >= 0 }. The scop consists of two parts, one for
2666 * evaluating the condition and one for the body.
2667 * The schedule is adjusted to reflect that the condition is evaluated
2668 * before the body is executed and the body is filtered to depend
2669 * on the result of the condition evaluating to true on all iterations
2670 * up to the current iteration, while the evaluation of the condition itself
2671 * is filtered to depend on the result of the condition evaluating to true
2672 * on all previous iterations.
2673 * The context of the scop representing the body is dropped
2674 * because we don't know how many times the body will be executed,
2675 * if at all.
2677 * If the body contains any break, then it is taken into
2678 * account in infinite_domain (if the skip condition is affine)
2679 * or in scop_add_break (if the skip condition is not affine).
2681 * If we were only able to extract part of the body, then simply
2682 * return that part.
2684 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2686 Expr *cond;
2687 int test_nr, stmt_nr;
2688 isl_id *id, *id_test, *id_break_test;
2689 isl_multi_pw_aff *test_index;
2690 isl_set *domain;
2691 isl_aff *ident;
2692 isl_pw_aff *pa;
2693 struct pet_scop *scop, *scop_body;
2694 bool has_var_break;
2696 cond = stmt->getCond();
2697 if (!cond) {
2698 unsupported(stmt);
2699 return NULL;
2702 clear_assignments clear(assigned_value);
2703 clear.TraverseStmt(stmt->getBody());
2705 pa = try_extract_affine_condition(cond);
2706 if (pa)
2707 return extract_affine_while(pa, stmt->getBody());
2709 if (!allow_nested) {
2710 unsupported(stmt);
2711 return NULL;
2714 test_nr = n_test++;
2715 stmt_nr = n_stmt++;
2716 scop_body = extract(stmt->getBody());
2717 if (partial)
2718 return scop_body;
2720 test_index = create_test_index(ctx, test_nr);
2721 scop = extract_non_affine_condition(cond, stmt_nr,
2722 isl_multi_pw_aff_copy(test_index));
2723 scop = scop_add_array(scop, test_index, ast_context);
2724 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2725 isl_multi_pw_aff_free(test_index);
2727 id = isl_id_alloc(ctx, "t", NULL);
2728 domain = infinite_domain(isl_id_copy(id), scop_body);
2729 ident = identity_aff(domain);
2731 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2732 if (has_var_break)
2733 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2735 scop = pet_scop_prefix(scop, 0);
2736 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_aff_copy(ident),
2737 isl_aff_copy(ident), isl_id_copy(id));
2738 scop_body = pet_scop_reset_context(scop_body);
2739 scop_body = pet_scop_prefix(scop_body, 1);
2740 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2741 isl_aff_copy(ident), ident, id);
2743 if (has_var_break) {
2744 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2745 isl_set_copy(domain), isl_val_one(ctx));
2746 scop_body = scop_add_break(scop_body, id_break_test,
2747 isl_set_copy(domain), isl_val_one(ctx));
2749 scop = scop_add_while(scop, scop_body, id_test, domain,
2750 isl_val_one(ctx));
2752 return scop;
2755 /* Check whether "cond" expresses a simple loop bound
2756 * on the only set dimension.
2757 * In particular, if "up" is set then "cond" should contain only
2758 * upper bounds on the set dimension.
2759 * Otherwise, it should contain only lower bounds.
2761 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2763 if (isl_val_is_pos(inc))
2764 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2765 else
2766 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2769 /* Extend a condition on a given iteration of a loop to one that
2770 * imposes the same condition on all previous iterations.
2771 * "domain" expresses the lower [upper] bound on the iterations
2772 * when inc is positive [negative].
2774 * In particular, we construct the condition (when inc is positive)
2776 * forall i' : (domain(i') and i' <= i) => cond(i')
2778 * which is equivalent to
2780 * not exists i' : domain(i') and i' <= i and not cond(i')
2782 * We construct this set by negating cond, applying a map
2784 * { [i'] -> [i] : domain(i') and i' <= i }
2786 * and then negating the result again.
2788 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2789 __isl_take isl_set *domain, __isl_take isl_val *inc)
2791 isl_map *previous_to_this;
2793 if (isl_val_is_pos(inc))
2794 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2795 else
2796 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2798 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2800 cond = isl_set_complement(cond);
2801 cond = isl_set_apply(cond, previous_to_this);
2802 cond = isl_set_complement(cond);
2804 isl_val_free(inc);
2806 return cond;
2809 /* Construct a domain of the form
2811 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2813 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2814 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2816 isl_aff *aff;
2817 isl_space *dim;
2818 isl_set *set;
2820 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2821 dim = isl_pw_aff_get_domain_space(init);
2822 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2823 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2824 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2826 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2827 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2828 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2829 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2831 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2833 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2835 return isl_set_params(set);
2838 /* Assuming "cond" represents a bound on a loop where the loop
2839 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2840 * is possible.
2842 * Under the given assumptions, wrapping is only possible if "cond" allows
2843 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2844 * increasing iterator and 0 in case of a decreasing iterator.
2846 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2847 __isl_keep isl_val *inc)
2849 bool cw;
2850 isl_ctx *ctx;
2851 isl_val *limit;
2852 isl_set *test;
2854 test = isl_set_copy(cond);
2856 ctx = isl_set_get_ctx(test);
2857 if (isl_val_is_neg(inc))
2858 limit = isl_val_zero(ctx);
2859 else {
2860 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2861 limit = isl_val_2exp(limit);
2862 limit = isl_val_sub_ui(limit, 1);
2865 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2866 cw = !isl_set_is_empty(test);
2867 isl_set_free(test);
2869 return cw;
2872 /* Given a one-dimensional space, construct the following affine expression
2873 * on this space
2875 * { [v] -> [v mod 2^width] }
2877 * where width is the number of bits used to represent the values
2878 * of the unsigned variable "iv".
2880 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2881 ValueDecl *iv)
2883 isl_ctx *ctx;
2884 isl_val *mod;
2885 isl_aff *aff;
2887 ctx = isl_space_get_ctx(dim);
2888 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2889 mod = isl_val_2exp(mod);
2891 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2892 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2893 aff = isl_aff_mod_val(aff, mod);
2895 return aff;
2898 /* Project out the parameter "id" from "set".
2900 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2901 __isl_keep isl_id *id)
2903 int pos;
2905 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2906 if (pos >= 0)
2907 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2909 return set;
2912 /* Compute the set of parameters for which "set1" is a subset of "set2".
2914 * set1 is a subset of set2 if
2916 * forall i in set1 : i in set2
2918 * or
2920 * not exists i in set1 and i not in set2
2922 * i.e.,
2924 * not exists i in set1 \ set2
2926 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2927 __isl_take isl_set *set2)
2929 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2932 /* Compute the set of parameter values for which "cond" holds
2933 * on the next iteration for each element of "dom".
2935 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2936 * and then compute the set of parameters for which the result is a subset
2937 * of "cond".
2939 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2940 __isl_take isl_set *dom, __isl_take isl_val *inc)
2942 isl_space *space;
2943 isl_aff *aff;
2944 isl_map *next;
2946 space = isl_set_get_space(dom);
2947 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2948 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2949 aff = isl_aff_add_constant_val(aff, inc);
2950 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2952 dom = isl_set_apply(dom, next);
2954 return enforce_subset(dom, cond);
2957 /* Construct a pet_scop for a for statement.
2958 * The for loop is required to be of the form
2960 * for (i = init; condition; ++i)
2962 * or
2964 * for (i = init; condition; --i)
2966 * The initialization of the for loop should either be an assignment
2967 * to an integer variable, or a declaration of such a variable with
2968 * initialization.
2970 * The condition is allowed to contain nested accesses, provided
2971 * they are not being written to inside the body of the loop.
2972 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2973 * essentially treated as a while loop, with iteration domain
2974 * { [i] : i >= init }.
2976 * We extract a pet_scop for the body and then embed it in a loop with
2977 * iteration domain and schedule
2979 * { [i] : i >= init and condition' }
2980 * { [i] -> [i] }
2982 * or
2984 * { [i] : i <= init and condition' }
2985 * { [i] -> [-i] }
2987 * Where condition' is equal to condition if the latter is
2988 * a simple upper [lower] bound and a condition that is extended
2989 * to apply to all previous iterations otherwise.
2991 * If the condition is non-affine, then we drop the condition from the
2992 * iteration domain and instead create a separate statement
2993 * for evaluating the condition. The body is then filtered to depend
2994 * on the result of the condition evaluating to true on all iterations
2995 * up to the current iteration, while the evaluation the condition itself
2996 * is filtered to depend on the result of the condition evaluating to true
2997 * on all previous iterations.
2998 * The context of the scop representing the body is dropped
2999 * because we don't know how many times the body will be executed,
3000 * if at all.
3002 * If the stride of the loop is not 1, then "i >= init" is replaced by
3004 * (exists a: i = init + stride * a and a >= 0)
3006 * If the loop iterator i is unsigned, then wrapping may occur.
3007 * We therefore use a virtual iterator instead that does not wrap.
3008 * However, the condition in the code applies
3009 * to the wrapped value, so we need to change condition(i)
3010 * into condition([i % 2^width]). Similarly, we replace all accesses
3011 * to the original iterator by the wrapping of the virtual iterator.
3012 * Note that there may be no need to perform this final wrapping
3013 * if the loop condition (after wrapping) satisfies certain conditions.
3014 * However, the is_simple_bound condition is not enough since it doesn't
3015 * check if there even is an upper bound.
3017 * Wrapping on unsigned iterators can be avoided entirely if
3018 * loop condition is simple, the loop iterator is incremented
3019 * [decremented] by one and the last value before wrapping cannot
3020 * possibly satisfy the loop condition.
3022 * Before extracting a pet_scop from the body we remove all
3023 * assignments in assigned_value to variables that are assigned
3024 * somewhere in the body of the loop.
3026 * Valid parameters for a for loop are those for which the initial
3027 * value itself, the increment on each domain iteration and
3028 * the condition on both the initial value and
3029 * the result of incrementing the iterator for each iteration of the domain
3030 * can be evaluated.
3031 * If the loop condition is non-affine, then we only consider validity
3032 * of the initial value.
3034 * If the body contains any break, then we keep track of it in "skip"
3035 * (if the skip condition is affine) or it is handled in scop_add_break
3036 * (if the skip condition is not affine).
3037 * Note that the affine break condition needs to be considered with
3038 * respect to previous iterations in the virtual domain (if any).
3040 * If we were only able to extract part of the body, then simply
3041 * return that part.
3043 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
3045 BinaryOperator *ass;
3046 Decl *decl;
3047 Stmt *init;
3048 Expr *lhs, *rhs;
3049 ValueDecl *iv;
3050 isl_local_space *ls;
3051 isl_set *domain;
3052 isl_aff *sched;
3053 isl_set *cond = NULL;
3054 isl_set *skip = NULL;
3055 isl_id *id, *id_test = NULL, *id_break_test;
3056 struct pet_scop *scop, *scop_cond = NULL;
3057 assigned_value_cache cache(assigned_value);
3058 isl_val *inc;
3059 bool was_assigned;
3060 bool is_one;
3061 bool is_unsigned;
3062 bool is_simple;
3063 bool is_virtual;
3064 bool has_affine_break;
3065 bool has_var_break;
3066 isl_aff *wrap = NULL;
3067 isl_pw_aff *pa, *pa_inc, *init_val;
3068 isl_set *valid_init;
3069 isl_set *valid_cond;
3070 isl_set *valid_cond_init;
3071 isl_set *valid_cond_next;
3072 isl_set *valid_inc;
3073 int stmt_id;
3075 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
3076 return extract_infinite_for(stmt);
3078 init = stmt->getInit();
3079 if (!init) {
3080 unsupported(stmt);
3081 return NULL;
3083 if ((ass = initialization_assignment(init)) != NULL) {
3084 iv = extract_induction_variable(ass);
3085 if (!iv)
3086 return NULL;
3087 lhs = ass->getLHS();
3088 rhs = ass->getRHS();
3089 } else if ((decl = initialization_declaration(init)) != NULL) {
3090 VarDecl *var = extract_induction_variable(init, decl);
3091 if (!var)
3092 return NULL;
3093 iv = var;
3094 rhs = var->getInit();
3095 lhs = create_DeclRefExpr(var);
3096 } else {
3097 unsupported(stmt->getInit());
3098 return NULL;
3101 assigned_value.erase(iv);
3102 clear_assignments clear(assigned_value);
3103 clear.TraverseStmt(stmt->getBody());
3105 was_assigned = assigned_value.find(iv) != assigned_value.end();
3106 clear_assignment(assigned_value, iv);
3107 init_val = extract_affine(rhs);
3108 if (!was_assigned)
3109 assigned_value.erase(iv);
3110 if (!init_val)
3111 return NULL;
3113 pa_inc = extract_increment(stmt, iv);
3114 if (!pa_inc) {
3115 isl_pw_aff_free(init_val);
3116 return NULL;
3119 inc = NULL;
3120 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
3121 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
3122 isl_pw_aff_free(init_val);
3123 isl_pw_aff_free(pa_inc);
3124 unsupported(stmt->getInc());
3125 isl_val_free(inc);
3126 return NULL;
3129 pa = try_extract_nested_condition(stmt->getCond());
3130 if (allow_nested && (!pa || pet_nested_any_in_pw_aff(pa)))
3131 stmt_id = n_stmt++;
3133 scop = extract(stmt->getBody());
3134 if (partial) {
3135 isl_pw_aff_free(init_val);
3136 isl_pw_aff_free(pa_inc);
3137 isl_pw_aff_free(pa);
3138 isl_val_free(inc);
3139 return scop;
3142 valid_inc = isl_pw_aff_domain(pa_inc);
3144 is_unsigned = iv->getType()->isUnsignedIntegerType();
3146 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
3148 has_affine_break = scop &&
3149 pet_scop_has_affine_skip(scop, pet_skip_later);
3150 if (has_affine_break)
3151 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
3152 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
3153 if (has_var_break)
3154 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
3156 if (pa && !is_nested_allowed(pa, scop)) {
3157 isl_pw_aff_free(pa);
3158 pa = NULL;
3161 if (!allow_nested && !pa)
3162 pa = try_extract_affine_condition(stmt->getCond());
3163 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3164 cond = isl_pw_aff_non_zero_set(pa);
3165 if (allow_nested && !cond) {
3166 isl_multi_pw_aff *test_index;
3167 int save_n_stmt = n_stmt;
3168 test_index = create_test_index(ctx, n_test++);
3169 n_stmt = stmt_id;
3170 scop_cond = extract_non_affine_condition(stmt->getCond(),
3171 n_stmt++, isl_multi_pw_aff_copy(test_index));
3172 n_stmt = save_n_stmt;
3173 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
3174 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
3175 isl_dim_out);
3176 isl_multi_pw_aff_free(test_index);
3177 scop_cond = pet_scop_prefix(scop_cond, 0);
3178 scop = pet_scop_reset_context(scop);
3179 scop = pet_scop_prefix(scop, 1);
3180 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
3183 cond = embed(cond, isl_id_copy(id));
3184 skip = embed(skip, isl_id_copy(id));
3185 valid_cond = isl_set_coalesce(valid_cond);
3186 valid_cond = embed(valid_cond, isl_id_copy(id));
3187 valid_inc = embed(valid_inc, isl_id_copy(id));
3188 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
3189 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
3191 valid_cond_init = enforce_subset(
3192 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
3193 isl_set_copy(valid_cond));
3194 if (is_one && !is_virtual) {
3195 isl_pw_aff_free(init_val);
3196 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
3197 lhs, rhs, init);
3198 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3199 valid_init = set_project_out_by_id(valid_init, id);
3200 domain = isl_pw_aff_non_zero_set(pa);
3201 } else {
3202 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
3203 domain = strided_domain(isl_id_copy(id), init_val,
3204 isl_val_copy(inc));
3207 domain = embed(domain, isl_id_copy(id));
3208 if (is_virtual) {
3209 isl_map *rev_wrap;
3210 wrap = compute_wrapping(isl_set_get_space(cond), iv);
3211 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
3212 rev_wrap = isl_map_reverse(rev_wrap);
3213 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
3214 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
3215 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
3216 valid_inc = isl_set_apply(valid_inc, rev_wrap);
3218 is_simple = is_simple_bound(cond, inc);
3219 if (!is_simple) {
3220 cond = isl_set_gist(cond, isl_set_copy(domain));
3221 is_simple = is_simple_bound(cond, inc);
3223 if (!is_simple)
3224 cond = valid_for_each_iteration(cond,
3225 isl_set_copy(domain), isl_val_copy(inc));
3226 domain = isl_set_intersect(domain, cond);
3227 if (has_affine_break) {
3228 skip = isl_set_intersect(skip , isl_set_copy(domain));
3229 skip = after(skip, isl_val_sgn(inc));
3230 domain = isl_set_subtract(domain, skip);
3232 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
3233 ls = isl_local_space_from_space(isl_set_get_space(domain));
3234 sched = isl_aff_var_on_domain(ls, isl_dim_set, 0);
3235 if (isl_val_is_neg(inc))
3236 sched = isl_aff_neg(sched);
3238 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
3239 isl_val_copy(inc));
3240 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
3242 if (!is_virtual)
3243 wrap = identity_aff(domain);
3245 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
3246 isl_aff_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
3247 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
3248 scop = resolve_nested(scop);
3249 if (has_var_break)
3250 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
3251 isl_val_copy(inc));
3252 if (id_test) {
3253 scop = scop_add_while(scop_cond, scop, id_test, domain,
3254 isl_val_copy(inc));
3255 isl_set_free(valid_inc);
3256 } else {
3257 scop = pet_scop_restrict_context(scop, valid_inc);
3258 scop = pet_scop_restrict_context(scop, valid_cond_next);
3259 scop = pet_scop_restrict_context(scop, valid_cond_init);
3260 isl_set_free(domain);
3262 clear_assignment(assigned_value, iv);
3264 isl_val_free(inc);
3266 scop = pet_scop_restrict_context(scop, valid_init);
3268 return scop;
3271 /* Try and construct a pet_scop corresponding to a compound statement.
3273 * "skip_declarations" is set if we should skip initial declarations
3274 * in the children of the compound statements. This then implies
3275 * that this sequence of children should not be treated as a block
3276 * since the initial statements may be skipped.
3278 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
3280 return extract(stmt->children(), !skip_declarations, skip_declarations);
3283 /* For each nested access parameter in "space",
3284 * construct a corresponding pet_expr, place it in args and
3285 * record its position in "param2pos".
3286 * "n_arg" is the number of elements that are already in args.
3287 * The position recorded in "param2pos" takes this number into account.
3288 * If the pet_expr corresponding to a parameter is identical to
3289 * the pet_expr corresponding to an earlier parameter, then these two
3290 * parameters are made to refer to the same element in args.
3292 * Return the final number of elements in args or -1 if an error has occurred.
3294 int PetScan::extract_nested(__isl_keep isl_space *space,
3295 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
3297 int nparam;
3299 nparam = isl_space_dim(space, isl_dim_param);
3300 for (int i = 0; i < nparam; ++i) {
3301 int j;
3302 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3303 Expr *nested;
3305 if (!pet_nested_in_id(id)) {
3306 isl_id_free(id);
3307 continue;
3310 nested = (Expr *) isl_id_get_user(id);
3311 args[n_arg] = extract_expr(nested);
3312 isl_id_free(id);
3313 if (!args[n_arg])
3314 return -1;
3316 for (j = 0; j < n_arg; ++j)
3317 if (pet_expr_is_equal(args[j], args[n_arg]))
3318 break;
3320 if (j < n_arg) {
3321 pet_expr_free(args[n_arg]);
3322 args[n_arg] = NULL;
3323 param2pos[i] = j;
3324 } else
3325 param2pos[i] = n_arg++;
3328 return n_arg;
3331 /* For each nested access parameter in the access relations in "expr",
3332 * construct a corresponding pet_expr, place it in expr->args and
3333 * record its position in "param2pos".
3334 * n is the number of nested access parameters.
3336 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
3337 std::map<int,int> &param2pos)
3339 isl_space *space;
3341 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
3342 expr->n_arg = n;
3343 if (!expr->args)
3344 goto error;
3346 space = pet_expr_access_get_parameter_space(expr);
3347 n = extract_nested(space, 0, expr->args, param2pos);
3348 isl_space_free(space);
3350 if (n < 0)
3351 goto error;
3353 expr->n_arg = n;
3354 return expr;
3355 error:
3356 pet_expr_free(expr);
3357 return NULL;
3360 /* Look for parameters in any access relation in "expr" that
3361 * refer to nested accesses. In particular, these are
3362 * parameters with no name.
3364 * If there are any such parameters, then the domain of the index
3365 * expression and the access relation, which is still [] at this point,
3366 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
3367 * (after identifying identical nested accesses).
3369 * This transformation is performed in several steps.
3370 * We first extract the arguments in extract_nested.
3371 * param2pos maps the original parameter position to the position
3372 * of the argument.
3373 * Then we move these parameters to input dimensions.
3374 * t2pos maps the positions of these temporary input dimensions
3375 * to the positions of the corresponding arguments.
3376 * Finally, we express these temporary dimensions in terms of the domain
3377 * [[] -> [t_1,...,t_n]] and precompose index expression and access
3378 * relations with this function.
3380 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
3382 int n;
3383 int nparam;
3384 isl_space *space;
3385 isl_local_space *ls;
3386 isl_aff *aff;
3387 isl_multi_aff *ma;
3388 std::map<int,int> param2pos;
3389 std::map<int,int> t2pos;
3391 if (!expr)
3392 return expr;
3394 for (int i = 0; i < expr->n_arg; ++i) {
3395 expr->args[i] = resolve_nested(expr->args[i]);
3396 if (!expr->args[i]) {
3397 pet_expr_free(expr);
3398 return NULL;
3402 if (expr->type != pet_expr_access)
3403 return expr;
3405 space = pet_expr_access_get_parameter_space(expr);
3406 n = pet_nested_n_in_space(space);
3407 isl_space_free(space);
3408 if (n == 0)
3409 return expr;
3411 expr = extract_nested(expr, n, param2pos);
3412 if (!expr)
3413 return NULL;
3415 expr = pet_expr_access_align_params(expr);
3416 if (!expr)
3417 return NULL;
3419 n = 0;
3420 space = pet_expr_access_get_parameter_space(expr);
3421 nparam = isl_space_dim(space, isl_dim_param);
3422 for (int i = nparam - 1; i >= 0; --i) {
3423 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3424 if (!pet_nested_in_id(id)) {
3425 isl_id_free(id);
3426 continue;
3429 expr = pet_expr_access_move_dims(expr,
3430 isl_dim_in, n, isl_dim_param, i, 1);
3431 t2pos[n] = param2pos[i];
3432 n++;
3434 isl_id_free(id);
3436 isl_space_free(space);
3438 space = pet_expr_access_get_parameter_space(expr);
3439 space = isl_space_set_from_params(space);
3440 space = isl_space_add_dims(space, isl_dim_set, expr->n_arg);
3441 space = isl_space_wrap(isl_space_from_range(space));
3442 ls = isl_local_space_from_space(isl_space_copy(space));
3443 space = isl_space_from_domain(space);
3444 space = isl_space_add_dims(space, isl_dim_out, n);
3445 ma = isl_multi_aff_zero(space);
3447 for (int i = 0; i < n; ++i) {
3448 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3449 isl_dim_set, t2pos[i]);
3450 ma = isl_multi_aff_set_aff(ma, i, aff);
3452 isl_local_space_free(ls);
3454 expr = pet_expr_access_pullback_multi_aff(expr, ma);
3456 return expr;
3459 /* Return the file offset of the expansion location of "Loc".
3461 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3463 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3466 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3468 /* Return a SourceLocation for the location after the first semicolon
3469 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3470 * call it and also skip trailing spaces and newline.
3472 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3473 const LangOptions &LO)
3475 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3478 #else
3480 /* Return a SourceLocation for the location after the first semicolon
3481 * after "loc". If Lexer::findLocationAfterToken is not available,
3482 * we look in the underlying character data for the first semicolon.
3484 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3485 const LangOptions &LO)
3487 const char *semi;
3488 const char *s = SM.getCharacterData(loc);
3490 semi = strchr(s, ';');
3491 if (!semi)
3492 return SourceLocation();
3493 return loc.getFileLocWithOffset(semi + 1 - s);
3496 #endif
3498 /* If the token at "loc" is the first token on the line, then return
3499 * a location referring to the start of the line.
3500 * Otherwise, return "loc".
3502 * This function is used to extend a scop to the start of the line
3503 * if the first token of the scop is also the first token on the line.
3505 * We look for the first token on the line. If its location is equal to "loc",
3506 * then the latter is the location of the first token on the line.
3508 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3509 SourceManager &SM, const LangOptions &LO)
3511 std::pair<FileID, unsigned> file_offset_pair;
3512 llvm::StringRef file;
3513 const char *pos;
3514 Token tok;
3515 SourceLocation token_loc, line_loc;
3516 int col;
3518 loc = SM.getExpansionLoc(loc);
3519 col = SM.getExpansionColumnNumber(loc);
3520 line_loc = loc.getLocWithOffset(1 - col);
3521 file_offset_pair = SM.getDecomposedLoc(line_loc);
3522 file = SM.getBufferData(file_offset_pair.first, NULL);
3523 pos = file.data() + file_offset_pair.second;
3525 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3526 file.begin(), pos, file.end());
3527 lexer.LexFromRawLexer(tok);
3528 token_loc = tok.getLocation();
3530 if (token_loc == loc)
3531 return line_loc;
3532 else
3533 return loc;
3536 /* Update start and end of "scop" to include the region covered by "range".
3537 * If "skip_semi" is set, then we assume "range" is followed by
3538 * a semicolon and also include this semicolon.
3540 struct pet_scop *PetScan::update_scop_start_end(struct pet_scop *scop,
3541 SourceRange range, bool skip_semi)
3543 SourceLocation loc = range.getBegin();
3544 SourceManager &SM = PP.getSourceManager();
3545 const LangOptions &LO = PP.getLangOpts();
3546 unsigned start, end;
3548 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3549 start = getExpansionOffset(SM, loc);
3550 loc = range.getEnd();
3551 if (skip_semi)
3552 loc = location_after_semi(loc, SM, LO);
3553 else
3554 loc = PP.getLocForEndOfToken(loc);
3555 end = getExpansionOffset(SM, loc);
3557 scop = pet_scop_update_start_end(scop, start, end);
3558 return scop;
3561 /* Convert a top-level pet_expr to a pet_scop with one statement.
3562 * This mainly involves resolving nested expression parameters
3563 * and setting the name of the iteration space.
3564 * The name is given by "label" if it is non-NULL. Otherwise,
3565 * it is of the form S_<n_stmt>.
3566 * start and end of the pet_scop are derived from those of "stmt".
3567 * If "stmt" is an expression statement, then its range does not
3568 * include the semicolon, while it should be included in the pet_scop.
3570 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
3571 __isl_take isl_id *label)
3573 struct pet_stmt *ps;
3574 struct pet_scop *scop;
3575 SourceLocation loc = stmt->getLocStart();
3576 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3577 bool skip_semi;
3579 expr = resolve_nested(expr);
3580 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
3581 scop = pet_scop_from_pet_stmt(ctx, ps);
3583 skip_semi = isa<Expr>(stmt);
3584 scop = update_scop_start_end(scop, stmt->getSourceRange(), skip_semi);
3585 return scop;
3588 /* Check if we can extract an affine expression from "expr".
3589 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3590 * We turn on autodetection so that we won't generate any warnings
3591 * and turn off nesting, so that we won't accept any non-affine constructs.
3593 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3595 isl_pw_aff *pwaff;
3596 int save_autodetect = options->autodetect;
3597 bool save_nesting = nesting_enabled;
3599 options->autodetect = 1;
3600 nesting_enabled = false;
3602 pwaff = extract_affine(expr);
3604 options->autodetect = save_autodetect;
3605 nesting_enabled = save_nesting;
3607 return pwaff;
3610 /* Check if we can extract an affine constraint from "expr".
3611 * Return the constraint as an isl_set if we can and NULL otherwise.
3612 * We turn on autodetection so that we won't generate any warnings
3613 * and turn off nesting, so that we won't accept any non-affine constructs.
3615 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3617 isl_pw_aff *cond;
3618 int save_autodetect = options->autodetect;
3619 bool save_nesting = nesting_enabled;
3621 options->autodetect = 1;
3622 nesting_enabled = false;
3624 cond = extract_condition(expr);
3626 options->autodetect = save_autodetect;
3627 nesting_enabled = save_nesting;
3629 return cond;
3632 /* Check whether "expr" is an affine constraint.
3634 bool PetScan::is_affine_condition(Expr *expr)
3636 isl_pw_aff *cond;
3638 cond = try_extract_affine_condition(expr);
3639 isl_pw_aff_free(cond);
3641 return cond != NULL;
3644 /* Check if we can extract a condition from "expr".
3645 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3646 * If allow_nested is set, then the condition may involve parameters
3647 * corresponding to nested accesses.
3648 * We turn on autodetection so that we won't generate any warnings.
3650 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3652 isl_pw_aff *cond;
3653 int save_autodetect = options->autodetect;
3654 bool save_nesting = nesting_enabled;
3656 options->autodetect = 1;
3657 nesting_enabled = allow_nested;
3658 cond = extract_condition(expr);
3660 options->autodetect = save_autodetect;
3661 nesting_enabled = save_nesting;
3663 return cond;
3666 /* If the top-level expression of "stmt" is an assignment, then
3667 * return that assignment as a BinaryOperator.
3668 * Otherwise return NULL.
3670 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3672 BinaryOperator *ass;
3674 if (!stmt)
3675 return NULL;
3676 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3677 return NULL;
3679 ass = cast<BinaryOperator>(stmt);
3680 if(ass->getOpcode() != BO_Assign)
3681 return NULL;
3683 return ass;
3686 /* Check if the given if statement is a conditional assignement
3687 * with a non-affine condition. If so, construct a pet_scop
3688 * corresponding to this conditional assignment. Otherwise return NULL.
3690 * In particular we check if "stmt" is of the form
3692 * if (condition)
3693 * a = f(...);
3694 * else
3695 * a = g(...);
3697 * where a is some array or scalar access.
3698 * The constructed pet_scop then corresponds to the expression
3700 * a = condition ? f(...) : g(...)
3702 * All access relations in f(...) are intersected with condition
3703 * while all access relation in g(...) are intersected with the complement.
3705 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3707 BinaryOperator *ass_then, *ass_else;
3708 isl_multi_pw_aff *write_then, *write_else;
3709 isl_set *cond, *comp;
3710 isl_multi_pw_aff *index;
3711 isl_pw_aff *pa;
3712 int equal;
3713 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3714 bool save_nesting = nesting_enabled;
3716 if (!options->detect_conditional_assignment)
3717 return NULL;
3719 ass_then = top_assignment_or_null(stmt->getThen());
3720 ass_else = top_assignment_or_null(stmt->getElse());
3722 if (!ass_then || !ass_else)
3723 return NULL;
3725 if (is_affine_condition(stmt->getCond()))
3726 return NULL;
3728 write_then = extract_index(ass_then->getLHS());
3729 write_else = extract_index(ass_else->getLHS());
3731 equal = isl_multi_pw_aff_plain_is_equal(write_then, write_else);
3732 isl_multi_pw_aff_free(write_else);
3733 if (equal < 0 || !equal) {
3734 isl_multi_pw_aff_free(write_then);
3735 return NULL;
3738 nesting_enabled = allow_nested;
3739 pa = extract_condition(stmt->getCond());
3740 nesting_enabled = save_nesting;
3741 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3742 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3743 index = isl_multi_pw_aff_from_range(isl_multi_pw_aff_from_pw_aff(pa));
3745 pe_cond = pet_expr_from_index(index);
3747 pe_then = extract_expr(ass_then->getRHS());
3748 pe_then = pet_expr_restrict(pe_then, cond);
3749 pe_else = extract_expr(ass_else->getRHS());
3750 pe_else = pet_expr_restrict(pe_else, comp);
3752 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
3753 pe_write = pet_expr_from_index_and_depth(write_then,
3754 extract_depth(write_then));
3755 if (pe_write) {
3756 pe_write->acc.write = 1;
3757 pe_write->acc.read = 0;
3759 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
3760 return extract(stmt, pe);
3763 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3764 * evaluating "cond" and writing the result to a virtual scalar,
3765 * as expressed by "index".
3767 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond, int stmt_nr,
3768 __isl_take isl_multi_pw_aff *index)
3770 struct pet_expr *expr, *write;
3771 struct pet_stmt *ps;
3772 SourceLocation loc = cond->getLocStart();
3773 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3775 write = pet_expr_from_index(index);
3776 if (write) {
3777 write->acc.write = 1;
3778 write->acc.read = 0;
3780 expr = extract_expr(cond);
3781 expr = resolve_nested(expr);
3782 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
3783 ps = pet_stmt_from_pet_expr(ctx, line, NULL, stmt_nr, expr);
3784 return pet_scop_from_pet_stmt(ctx, ps);
3787 extern "C" {
3788 static struct pet_expr *embed_access(struct pet_expr *expr, void *user);
3791 /* Precompose the access relation and the index expression associated
3792 * to "expr" with the function pointed to by "user",
3793 * thereby embedding the access relation in the domain of this function.
3794 * The initial domain of the access relation and the index expression
3795 * is the zero-dimensional domain.
3797 static struct pet_expr *embed_access(struct pet_expr *expr, void *user)
3799 isl_multi_aff *ma = (isl_multi_aff *) user;
3801 return pet_expr_access_pullback_multi_aff(expr, isl_multi_aff_copy(ma));
3804 /* Precompose all access relations in "expr" with "ma", thereby
3805 * embedding them in the domain of "ma".
3807 static struct pet_expr *embed(struct pet_expr *expr,
3808 __isl_keep isl_multi_aff *ma)
3810 return pet_expr_map_access(expr, &embed_access, ma);
3813 /* For each nested access parameter in the domain of "stmt",
3814 * construct a corresponding pet_expr, place it before the original
3815 * elements in stmt->args and record its position in "param2pos".
3816 * n is the number of nested access parameters.
3818 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3819 std::map<int,int> &param2pos)
3821 int i;
3822 isl_space *space;
3823 int n_arg;
3824 struct pet_expr **args;
3826 n_arg = stmt->n_arg;
3827 args = isl_calloc_array(ctx, struct pet_expr *, n + n_arg);
3828 if (!args)
3829 goto error;
3831 space = isl_set_get_space(stmt->domain);
3832 n_arg = extract_nested(space, 0, args, param2pos);
3833 isl_space_free(space);
3835 if (n_arg < 0)
3836 goto error;
3838 for (i = 0; i < stmt->n_arg; ++i)
3839 args[n_arg + i] = stmt->args[i];
3840 free(stmt->args);
3841 stmt->args = args;
3842 stmt->n_arg += n_arg;
3844 return stmt;
3845 error:
3846 if (args) {
3847 for (i = 0; i < n; ++i)
3848 pet_expr_free(args[i]);
3849 free(args);
3851 pet_stmt_free(stmt);
3852 return NULL;
3855 /* Check whether any of the arguments i of "stmt" starting at position "n"
3856 * is equal to one of the first "n" arguments j.
3857 * If so, combine the constraints on arguments i and j and remove
3858 * argument i.
3860 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3862 int i, j;
3863 isl_map *map;
3865 if (!stmt)
3866 return NULL;
3867 if (n == 0)
3868 return stmt;
3869 if (n == stmt->n_arg)
3870 return stmt;
3872 map = isl_set_unwrap(stmt->domain);
3874 for (i = stmt->n_arg - 1; i >= n; --i) {
3875 for (j = 0; j < n; ++j)
3876 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3877 break;
3878 if (j >= n)
3879 continue;
3881 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3882 map = isl_map_project_out(map, isl_dim_out, i, 1);
3884 pet_expr_free(stmt->args[i]);
3885 for (j = i; j + 1 < stmt->n_arg; ++j)
3886 stmt->args[j] = stmt->args[j + 1];
3887 stmt->n_arg--;
3890 stmt->domain = isl_map_wrap(map);
3891 if (!stmt->domain)
3892 goto error;
3893 return stmt;
3894 error:
3895 pet_stmt_free(stmt);
3896 return NULL;
3899 /* Look for parameters in the iteration domain of "stmt" that
3900 * refer to nested accesses. In particular, these are
3901 * parameters with no name.
3903 * If there are any such parameters, then as many extra variables
3904 * (after identifying identical nested accesses) are inserted in the
3905 * range of the map wrapped inside the domain, before the original variables.
3906 * If the original domain is not a wrapped map, then a new wrapped
3907 * map is created with zero output dimensions.
3908 * The parameters are then equated to the corresponding output dimensions
3909 * and subsequently projected out, from the iteration domain,
3910 * the schedule and the access relations.
3911 * For each of the output dimensions, a corresponding argument
3912 * expression is inserted. Initially they are created with
3913 * a zero-dimensional domain, so they have to be embedded
3914 * in the current iteration domain.
3915 * param2pos maps the position of the parameter to the position
3916 * of the corresponding output dimension in the wrapped map.
3918 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3920 int n;
3921 int nparam;
3922 unsigned n_arg;
3923 isl_map *map;
3924 isl_space *space;
3925 isl_multi_aff *ma;
3926 std::map<int,int> param2pos;
3928 if (!stmt)
3929 return NULL;
3931 n = pet_nested_n_in_set(stmt->domain);
3932 if (n == 0)
3933 return stmt;
3935 n_arg = stmt->n_arg;
3936 stmt = extract_nested(stmt, n, param2pos);
3937 if (!stmt)
3938 return NULL;
3940 n = stmt->n_arg - n_arg;
3941 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3942 if (isl_set_is_wrapping(stmt->domain))
3943 map = isl_set_unwrap(stmt->domain);
3944 else
3945 map = isl_map_from_domain(stmt->domain);
3946 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3948 for (int i = nparam - 1; i >= 0; --i) {
3949 isl_id *id;
3951 if (!pet_nested_in_map(map, i))
3952 continue;
3954 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
3955 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3956 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3957 param2pos[i]);
3958 map = isl_map_project_out(map, isl_dim_param, i, 1);
3961 stmt->domain = isl_map_wrap(map);
3963 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
3964 space = isl_space_from_domain(isl_space_domain(space));
3965 ma = isl_multi_aff_zero(space);
3966 for (int pos = 0; pos < n; ++pos)
3967 stmt->args[pos] = embed(stmt->args[pos], ma);
3968 isl_multi_aff_free(ma);
3970 stmt = pet_stmt_remove_nested_parameters(stmt);
3971 stmt = remove_duplicate_arguments(stmt, n);
3973 return stmt;
3976 /* For each statement in "scop", move the parameters that correspond
3977 * to nested access into the ranges of the domains and create
3978 * corresponding argument expressions.
3980 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3982 if (!scop)
3983 return NULL;
3985 for (int i = 0; i < scop->n_stmt; ++i) {
3986 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3987 if (!scop->stmts[i])
3988 goto error;
3991 return scop;
3992 error:
3993 pet_scop_free(scop);
3994 return NULL;
3997 /* Given an access expression "expr", is the variable accessed by
3998 * "expr" assigned anywhere inside "scop"?
4000 static bool is_assigned(pet_expr *expr, pet_scop *scop)
4002 bool assigned = false;
4003 isl_id *id;
4005 id = pet_expr_access_get_id(expr);
4006 assigned = pet_scop_writes(scop, id);
4007 isl_id_free(id);
4009 return assigned;
4012 /* Are all nested access parameters in "pa" allowed given "scop".
4013 * In particular, is none of them written by anywhere inside "scop".
4015 * If "scop" has any skip conditions, then no nested access parameters
4016 * are allowed. In particular, if there is any nested access in a guard
4017 * for a piece of code containing a "continue", then we want to introduce
4018 * a separate statement for evaluating this guard so that we can express
4019 * that the result is false for all previous iterations.
4021 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
4023 int nparam;
4025 if (!scop)
4026 return true;
4028 if (!pet_nested_any_in_pw_aff(pa))
4029 return true;
4031 if (pet_scop_has_skip(scop, pet_skip_now))
4032 return false;
4034 nparam = isl_pw_aff_dim(pa, isl_dim_param);
4035 for (int i = 0; i < nparam; ++i) {
4036 Expr *nested;
4037 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
4038 pet_expr *expr;
4039 bool allowed;
4041 if (!pet_nested_in_id(id)) {
4042 isl_id_free(id);
4043 continue;
4046 nested = (Expr *) isl_id_get_user(id);
4047 expr = extract_expr(nested);
4048 allowed = expr && expr->type == pet_expr_access &&
4049 !is_assigned(expr, scop);
4051 pet_expr_free(expr);
4052 isl_id_free(id);
4054 if (!allowed)
4055 return false;
4058 return true;
4061 /* Do we need to construct a skip condition of the given type
4062 * on an if statement, given that the if condition is non-affine?
4064 * pet_scop_filter_skip can only handle the case where the if condition
4065 * holds (the then branch) and the skip condition is universal.
4066 * In any other case, we need to construct a new skip condition.
4068 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
4069 bool have_else, enum pet_skip type)
4071 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
4072 return true;
4073 if (scop_then && pet_scop_has_skip(scop_then, type) &&
4074 !pet_scop_has_universal_skip(scop_then, type))
4075 return true;
4076 return false;
4079 /* Do we need to construct a skip condition of the given type
4080 * on an if statement, given that the if condition is affine?
4082 * There is no need to construct a new skip condition if all
4083 * the skip conditions are affine.
4085 static bool need_skip_aff(struct pet_scop *scop_then,
4086 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
4088 if (scop_then && pet_scop_has_var_skip(scop_then, type))
4089 return true;
4090 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
4091 return true;
4092 return false;
4095 /* Do we need to construct a skip condition of the given type
4096 * on an if statement?
4098 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
4099 bool have_else, enum pet_skip type, bool affine)
4101 if (affine)
4102 return need_skip_aff(scop_then, scop_else, have_else, type);
4103 else
4104 return need_skip(scop_then, scop_else, have_else, type);
4107 /* Construct an affine expression pet_expr that evaluates
4108 * to the constant "val".
4110 static struct pet_expr *universally(isl_ctx *ctx, int val)
4112 isl_local_space *ls;
4113 isl_aff *aff;
4114 isl_multi_pw_aff *mpa;
4116 ls = isl_local_space_from_space(isl_space_set_alloc(ctx, 0, 0));
4117 aff = isl_aff_val_on_domain(ls, isl_val_int_from_si(ctx, val));
4118 mpa = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4120 return pet_expr_from_index(mpa);
4123 /* Construct an affine expression pet_expr that evaluates
4124 * to the constant 1.
4126 static struct pet_expr *universally_true(isl_ctx *ctx)
4128 return universally(ctx, 1);
4131 /* Construct an affine expression pet_expr that evaluates
4132 * to the constant 0.
4134 static struct pet_expr *universally_false(isl_ctx *ctx)
4136 return universally(ctx, 0);
4139 /* Given an index expression "test_index" for the if condition,
4140 * an index expression "skip_index" for the skip condition and
4141 * scops for the then and else branches, construct a scop for
4142 * computing "skip_index".
4144 * The computed scop contains a single statement that essentially does
4146 * skip_index = test_cond ? skip_cond_then : skip_cond_else
4148 * If the skip conditions of the then and/or else branch are not affine,
4149 * then they need to be filtered by test_index.
4150 * If they are missing, then this means the skip condition is false.
4152 * Since we are constructing a skip condition for the if statement,
4153 * the skip conditions on the then and else branches are removed.
4155 static struct pet_scop *extract_skip(PetScan *scan,
4156 __isl_take isl_multi_pw_aff *test_index,
4157 __isl_take isl_multi_pw_aff *skip_index,
4158 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
4159 enum pet_skip type)
4161 struct pet_expr *expr_then, *expr_else, *expr, *expr_skip;
4162 struct pet_stmt *stmt;
4163 struct pet_scop *scop;
4164 isl_ctx *ctx = scan->ctx;
4166 if (!scop_then)
4167 goto error;
4168 if (have_else && !scop_else)
4169 goto error;
4171 if (pet_scop_has_skip(scop_then, type)) {
4172 expr_then = pet_scop_get_skip_expr(scop_then, type);
4173 pet_scop_reset_skip(scop_then, type);
4174 if (!pet_expr_is_affine(expr_then))
4175 expr_then = pet_expr_filter(expr_then,
4176 isl_multi_pw_aff_copy(test_index), 1);
4177 } else
4178 expr_then = universally_false(ctx);
4180 if (have_else && pet_scop_has_skip(scop_else, type)) {
4181 expr_else = pet_scop_get_skip_expr(scop_else, type);
4182 pet_scop_reset_skip(scop_else, type);
4183 if (!pet_expr_is_affine(expr_else))
4184 expr_else = pet_expr_filter(expr_else,
4185 isl_multi_pw_aff_copy(test_index), 0);
4186 } else
4187 expr_else = universally_false(ctx);
4189 expr = pet_expr_from_index(test_index);
4190 expr = pet_expr_new_ternary(ctx, expr, expr_then, expr_else);
4191 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4192 if (expr_skip) {
4193 expr_skip->acc.write = 1;
4194 expr_skip->acc.read = 0;
4196 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4197 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, scan->n_stmt++, expr);
4199 scop = pet_scop_from_pet_stmt(ctx, stmt);
4200 scop = scop_add_array(scop, skip_index, scan->ast_context);
4201 isl_multi_pw_aff_free(skip_index);
4203 return scop;
4204 error:
4205 isl_multi_pw_aff_free(test_index);
4206 isl_multi_pw_aff_free(skip_index);
4207 return NULL;
4210 /* Is scop's skip_now condition equal to its skip_later condition?
4211 * In particular, this means that it either has no skip_now condition
4212 * or both a skip_now and a skip_later condition (that are equal to each other).
4214 static bool skip_equals_skip_later(struct pet_scop *scop)
4216 int has_skip_now, has_skip_later;
4217 int equal;
4218 isl_multi_pw_aff *skip_now, *skip_later;
4220 if (!scop)
4221 return false;
4222 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
4223 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
4224 if (has_skip_now != has_skip_later)
4225 return false;
4226 if (!has_skip_now)
4227 return true;
4229 skip_now = pet_scop_get_skip(scop, pet_skip_now);
4230 skip_later = pet_scop_get_skip(scop, pet_skip_later);
4231 equal = isl_multi_pw_aff_is_equal(skip_now, skip_later);
4232 isl_multi_pw_aff_free(skip_now);
4233 isl_multi_pw_aff_free(skip_later);
4235 return equal;
4238 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
4240 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
4242 pet_scop_reset_skip(scop1, pet_skip_later);
4243 pet_scop_reset_skip(scop2, pet_skip_later);
4246 /* Structure that handles the construction of skip conditions.
4248 * scop_then and scop_else represent the then and else branches
4249 * of the if statement
4251 * skip[type] is true if we need to construct a skip condition of that type
4252 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
4253 * are equal to each other
4254 * index[type] is an index expression from a zero-dimension domain
4255 * to the virtual array representing the skip condition
4256 * scop[type] is a scop for computing the skip condition
4258 struct pet_skip_info {
4259 isl_ctx *ctx;
4261 bool skip[2];
4262 bool equal;
4263 isl_multi_pw_aff *index[2];
4264 struct pet_scop *scop[2];
4266 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
4268 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
4271 /* Structure that handles the construction of skip conditions on if statements.
4273 * scop_then and scop_else represent the then and else branches
4274 * of the if statement
4276 struct pet_skip_info_if : public pet_skip_info {
4277 struct pet_scop *scop_then, *scop_else;
4278 bool have_else;
4280 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4281 struct pet_scop *scop_else, bool have_else, bool affine);
4282 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index,
4283 enum pet_skip type);
4284 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index);
4285 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
4286 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4287 int offset);
4288 struct pet_scop *add(struct pet_scop *scop, int offset);
4291 /* Initialize a pet_skip_info_if structure based on the then and else branches
4292 * and based on whether the if condition is affine or not.
4294 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4295 struct pet_scop *scop_else, bool have_else, bool affine) :
4296 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
4297 have_else(have_else)
4299 skip[pet_skip_now] =
4300 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
4301 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
4302 (!have_else || skip_equals_skip_later(scop_else));
4303 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4304 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
4307 /* If we need to construct a skip condition of the given type,
4308 * then do so now.
4310 * "mpa" represents the if condition.
4312 void pet_skip_info_if::extract(PetScan *scan,
4313 __isl_keep isl_multi_pw_aff *mpa, enum pet_skip type)
4315 isl_ctx *ctx;
4317 if (!skip[type])
4318 return;
4320 ctx = isl_multi_pw_aff_get_ctx(mpa);
4321 index[type] = create_test_index(ctx, scan->n_test++);
4322 scop[type] = extract_skip(scan, isl_multi_pw_aff_copy(mpa),
4323 isl_multi_pw_aff_copy(index[type]),
4324 scop_then, scop_else, have_else, type);
4327 /* Construct the required skip conditions, given the if condition "index".
4329 void pet_skip_info_if::extract(PetScan *scan,
4330 __isl_keep isl_multi_pw_aff *index)
4332 extract(scan, index, pet_skip_now);
4333 extract(scan, index, pet_skip_later);
4334 if (equal)
4335 drop_skip_later(scop_then, scop_else);
4338 /* Construct the required skip conditions, given the if condition "cond".
4340 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
4342 isl_multi_pw_aff *test;
4344 if (!skip[pet_skip_now] && !skip[pet_skip_later])
4345 return;
4347 test = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_copy(cond));
4348 test = isl_multi_pw_aff_from_range(test);
4349 extract(scan, test);
4350 isl_multi_pw_aff_free(test);
4353 /* Add the computed skip condition of the give type to "main" and
4354 * add the scop for computing the condition at the given offset.
4356 * If equal is set, then we only computed a skip condition for pet_skip_now,
4357 * but we also need to set it as main's pet_skip_later.
4359 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
4360 enum pet_skip type, int offset)
4362 if (!skip[type])
4363 return main;
4365 scop[type] = pet_scop_prefix(scop[type], offset);
4366 main = pet_scop_add_par(ctx, main, scop[type]);
4367 scop[type] = NULL;
4369 if (equal)
4370 main = pet_scop_set_skip(main, pet_skip_later,
4371 isl_multi_pw_aff_copy(index[type]));
4373 main = pet_scop_set_skip(main, type, index[type]);
4374 index[type] = NULL;
4376 return main;
4379 /* Add the computed skip conditions to "main" and
4380 * add the scops for computing the conditions at the given offset.
4382 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
4384 scop = add(scop, pet_skip_now, offset);
4385 scop = add(scop, pet_skip_later, offset);
4387 return scop;
4390 /* Construct a pet_scop for a non-affine if statement.
4392 * We create a separate statement that writes the result
4393 * of the non-affine condition to a virtual scalar.
4394 * A constraint requiring the value of this virtual scalar to be one
4395 * is added to the iteration domains of the then branch.
4396 * Similarly, a constraint requiring the value of this virtual scalar
4397 * to be zero is added to the iteration domains of the else branch, if any.
4398 * We adjust the schedules to ensure that the virtual scalar is written
4399 * before it is read.
4401 * If there are any breaks or continues in the then and/or else
4402 * branches, then we may have to compute a new skip condition.
4403 * This is handled using a pet_skip_info_if object.
4404 * On initialization, the object checks if skip conditions need
4405 * to be computed. If so, it does so in "extract" and adds them in "add".
4407 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
4408 struct pet_scop *scop_then, struct pet_scop *scop_else,
4409 bool have_else, int stmt_id)
4411 struct pet_scop *scop;
4412 isl_multi_pw_aff *test_index;
4413 int save_n_stmt = n_stmt;
4415 test_index = create_test_index(ctx, n_test++);
4416 n_stmt = stmt_id;
4417 scop = extract_non_affine_condition(cond, n_stmt++,
4418 isl_multi_pw_aff_copy(test_index));
4419 n_stmt = save_n_stmt;
4420 scop = scop_add_array(scop, test_index, ast_context);
4422 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
4423 skip.extract(this, test_index);
4425 scop = pet_scop_prefix(scop, 0);
4426 scop_then = pet_scop_prefix(scop_then, 1);
4427 scop_then = pet_scop_filter(scop_then,
4428 isl_multi_pw_aff_copy(test_index), 1);
4429 if (have_else) {
4430 scop_else = pet_scop_prefix(scop_else, 1);
4431 scop_else = pet_scop_filter(scop_else, test_index, 0);
4432 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
4433 } else
4434 isl_multi_pw_aff_free(test_index);
4436 scop = pet_scop_add_seq(ctx, scop, scop_then);
4438 scop = skip.add(scop, 2);
4440 return scop;
4443 /* Construct a pet_scop for an if statement.
4445 * If the condition fits the pattern of a conditional assignment,
4446 * then it is handled by extract_conditional_assignment.
4447 * Otherwise, we do the following.
4449 * If the condition is affine, then the condition is added
4450 * to the iteration domains of the then branch, while the
4451 * opposite of the condition in added to the iteration domains
4452 * of the else branch, if any.
4453 * We allow the condition to be dynamic, i.e., to refer to
4454 * scalars or array elements that may be written to outside
4455 * of the given if statement. These nested accesses are then represented
4456 * as output dimensions in the wrapping iteration domain.
4457 * If it is also written _inside_ the then or else branch, then
4458 * we treat the condition as non-affine.
4459 * As explained in extract_non_affine_if, this will introduce
4460 * an extra statement.
4461 * For aesthetic reasons, we want this statement to have a statement
4462 * number that is lower than those of the then and else branches.
4463 * In order to evaluate if we will need such a statement, however, we
4464 * first construct scops for the then and else branches.
4465 * We therefore reserve a statement number if we might have to
4466 * introduce such an extra statement.
4468 * If the condition is not affine, then the scop is created in
4469 * extract_non_affine_if.
4471 * If there are any breaks or continues in the then and/or else
4472 * branches, then we may have to compute a new skip condition.
4473 * This is handled using a pet_skip_info_if object.
4474 * On initialization, the object checks if skip conditions need
4475 * to be computed. If so, it does so in "extract" and adds them in "add".
4477 struct pet_scop *PetScan::extract(IfStmt *stmt)
4479 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4480 isl_pw_aff *cond;
4481 int stmt_id;
4482 isl_set *set;
4483 isl_set *valid;
4485 clear_assignments clear(assigned_value);
4486 clear.TraverseStmt(stmt->getThen());
4487 if (stmt->getElse())
4488 clear.TraverseStmt(stmt->getElse());
4490 scop = extract_conditional_assignment(stmt);
4491 if (scop)
4492 return scop;
4494 cond = try_extract_nested_condition(stmt->getCond());
4495 if (allow_nested && (!cond || pet_nested_any_in_pw_aff(cond)))
4496 stmt_id = n_stmt++;
4499 assigned_value_cache cache(assigned_value);
4500 scop_then = extract(stmt->getThen());
4503 if (stmt->getElse()) {
4504 assigned_value_cache cache(assigned_value);
4505 scop_else = extract(stmt->getElse());
4506 if (options->autodetect) {
4507 if (scop_then && !scop_else) {
4508 partial = true;
4509 isl_pw_aff_free(cond);
4510 return scop_then;
4512 if (!scop_then && scop_else) {
4513 partial = true;
4514 isl_pw_aff_free(cond);
4515 return scop_else;
4520 if (cond &&
4521 (!is_nested_allowed(cond, scop_then) ||
4522 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4523 isl_pw_aff_free(cond);
4524 cond = NULL;
4526 if (allow_nested && !cond)
4527 return extract_non_affine_if(stmt->getCond(), scop_then,
4528 scop_else, stmt->getElse(), stmt_id);
4530 if (!cond)
4531 cond = extract_condition(stmt->getCond());
4533 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4534 skip.extract(this, cond);
4536 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4537 set = isl_pw_aff_non_zero_set(cond);
4538 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4540 if (stmt->getElse()) {
4541 set = isl_set_subtract(isl_set_copy(valid), set);
4542 scop_else = pet_scop_restrict(scop_else, set);
4543 scop = pet_scop_add_par(ctx, scop, scop_else);
4544 } else
4545 isl_set_free(set);
4546 scop = resolve_nested(scop);
4547 scop = pet_scop_restrict_context(scop, valid);
4549 if (skip)
4550 scop = pet_scop_prefix(scop, 0);
4551 scop = skip.add(scop, 1);
4553 return scop;
4556 /* Try and construct a pet_scop for a label statement.
4557 * We currently only allow labels on expression statements.
4559 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4561 isl_id *label;
4562 Stmt *sub;
4564 sub = stmt->getSubStmt();
4565 if (!isa<Expr>(sub)) {
4566 unsupported(stmt);
4567 return NULL;
4570 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4572 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4575 /* Return a one-dimensional multi piecewise affine expression that is equal
4576 * to the constant 1 and is defined over a zero-dimensional domain.
4578 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
4580 isl_space *space;
4581 isl_local_space *ls;
4582 isl_aff *aff;
4584 space = isl_space_set_alloc(ctx, 0, 0);
4585 ls = isl_local_space_from_space(space);
4586 aff = isl_aff_zero_on_domain(ls);
4587 aff = isl_aff_set_constant_si(aff, 1);
4589 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4592 /* Construct a pet_scop for a continue statement.
4594 * We simply create an empty scop with a universal pet_skip_now
4595 * skip condition. This skip condition will then be taken into
4596 * account by the enclosing loop construct, possibly after
4597 * being incorporated into outer skip conditions.
4599 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4601 pet_scop *scop;
4603 scop = pet_scop_empty(ctx);
4604 if (!scop)
4605 return NULL;
4607 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
4609 return scop;
4612 /* Construct a pet_scop for a break statement.
4614 * We simply create an empty scop with both a universal pet_skip_now
4615 * skip condition and a universal pet_skip_later skip condition.
4616 * These skip conditions will then be taken into
4617 * account by the enclosing loop construct, possibly after
4618 * being incorporated into outer skip conditions.
4620 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4622 pet_scop *scop;
4623 isl_multi_pw_aff *skip;
4625 scop = pet_scop_empty(ctx);
4626 if (!scop)
4627 return NULL;
4629 skip = one_mpa(ctx);
4630 scop = pet_scop_set_skip(scop, pet_skip_now,
4631 isl_multi_pw_aff_copy(skip));
4632 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
4634 return scop;
4637 /* Try and construct a pet_scop corresponding to "stmt".
4639 * If "stmt" is a compound statement, then "skip_declarations"
4640 * indicates whether we should skip initial declarations in the
4641 * compound statement.
4643 * If the constructed pet_scop is not a (possibly) partial representation
4644 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4645 * In particular, if skip_declarations is set, then we may have skipped
4646 * declarations inside "stmt" and so the pet_scop may not represent
4647 * the entire "stmt".
4648 * Note that this function may be called with "stmt" referring to the entire
4649 * body of the function, including the outer braces. In such cases,
4650 * skip_declarations will be set and the braces will not be taken into
4651 * account in scop->start and scop->end.
4653 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
4655 struct pet_scop *scop;
4657 if (isa<Expr>(stmt))
4658 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4660 switch (stmt->getStmtClass()) {
4661 case Stmt::WhileStmtClass:
4662 scop = extract(cast<WhileStmt>(stmt));
4663 break;
4664 case Stmt::ForStmtClass:
4665 scop = extract_for(cast<ForStmt>(stmt));
4666 break;
4667 case Stmt::IfStmtClass:
4668 scop = extract(cast<IfStmt>(stmt));
4669 break;
4670 case Stmt::CompoundStmtClass:
4671 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
4672 break;
4673 case Stmt::LabelStmtClass:
4674 scop = extract(cast<LabelStmt>(stmt));
4675 break;
4676 case Stmt::ContinueStmtClass:
4677 scop = extract(cast<ContinueStmt>(stmt));
4678 break;
4679 case Stmt::BreakStmtClass:
4680 scop = extract(cast<BreakStmt>(stmt));
4681 break;
4682 case Stmt::DeclStmtClass:
4683 scop = extract(cast<DeclStmt>(stmt));
4684 break;
4685 default:
4686 unsupported(stmt);
4687 return NULL;
4690 if (partial || skip_declarations)
4691 return scop;
4693 scop = update_scop_start_end(scop, stmt->getSourceRange(), false);
4695 return scop;
4698 /* Do we need to construct a skip condition of the given type
4699 * on a sequence of statements?
4701 * There is no need to construct a new skip condition if only
4702 * only of the two statements has a skip condition or if both
4703 * of their skip conditions are affine.
4705 * In principle we also don't need a new continuation variable if
4706 * the continuation of scop2 is affine, but then we would need
4707 * to allow more complicated forms of continuations.
4709 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4710 enum pet_skip type)
4712 if (!scop1 || !pet_scop_has_skip(scop1, type))
4713 return false;
4714 if (!scop2 || !pet_scop_has_skip(scop2, type))
4715 return false;
4716 if (pet_scop_has_affine_skip(scop1, type) &&
4717 pet_scop_has_affine_skip(scop2, type))
4718 return false;
4719 return true;
4722 /* Construct a scop for computing the skip condition of the given type and
4723 * with index expression "skip_index" for a sequence of two scops "scop1"
4724 * and "scop2".
4726 * The computed scop contains a single statement that essentially does
4728 * skip_index = skip_cond_1 ? 1 : skip_cond_2
4730 * or, in other words, skip_cond1 || skip_cond2.
4731 * In this expression, skip_cond_2 is filtered to reflect that it is
4732 * only evaluated when skip_cond_1 is false.
4734 * The skip condition on scop1 is not removed because it still needs
4735 * to be applied to scop2 when these two scops are combined.
4737 static struct pet_scop *extract_skip_seq(PetScan *ps,
4738 __isl_take isl_multi_pw_aff *skip_index,
4739 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4741 struct pet_expr *expr1, *expr2, *expr, *expr_skip;
4742 struct pet_stmt *stmt;
4743 struct pet_scop *scop;
4744 isl_ctx *ctx = ps->ctx;
4746 if (!scop1 || !scop2)
4747 goto error;
4749 expr1 = pet_scop_get_skip_expr(scop1, type);
4750 expr2 = pet_scop_get_skip_expr(scop2, type);
4751 pet_scop_reset_skip(scop2, type);
4753 expr2 = pet_expr_filter(expr2,
4754 isl_multi_pw_aff_copy(expr1->acc.index), 0);
4756 expr = universally_true(ctx);
4757 expr = pet_expr_new_ternary(ctx, expr1, expr, expr2);
4758 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4759 if (expr_skip) {
4760 expr_skip->acc.write = 1;
4761 expr_skip->acc.read = 0;
4763 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4764 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, ps->n_stmt++, expr);
4766 scop = pet_scop_from_pet_stmt(ctx, stmt);
4767 scop = scop_add_array(scop, skip_index, ps->ast_context);
4768 isl_multi_pw_aff_free(skip_index);
4770 return scop;
4771 error:
4772 isl_multi_pw_aff_free(skip_index);
4773 return NULL;
4776 /* Structure that handles the construction of skip conditions
4777 * on sequences of statements.
4779 * scop1 and scop2 represent the two statements that are combined
4781 struct pet_skip_info_seq : public pet_skip_info {
4782 struct pet_scop *scop1, *scop2;
4784 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4785 struct pet_scop *scop2);
4786 void extract(PetScan *scan, enum pet_skip type);
4787 void extract(PetScan *scan);
4788 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4789 int offset);
4790 struct pet_scop *add(struct pet_scop *scop, int offset);
4793 /* Initialize a pet_skip_info_seq structure based on
4794 * on the two statements that are going to be combined.
4796 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4797 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
4799 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
4800 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
4801 skip_equals_skip_later(scop2);
4802 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4803 need_skip_seq(scop1, scop2, pet_skip_later);
4806 /* If we need to construct a skip condition of the given type,
4807 * then do so now.
4809 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
4811 if (!skip[type])
4812 return;
4814 index[type] = create_test_index(ctx, scan->n_test++);
4815 scop[type] = extract_skip_seq(scan, isl_multi_pw_aff_copy(index[type]),
4816 scop1, scop2, type);
4819 /* Construct the required skip conditions.
4821 void pet_skip_info_seq::extract(PetScan *scan)
4823 extract(scan, pet_skip_now);
4824 extract(scan, pet_skip_later);
4825 if (equal)
4826 drop_skip_later(scop1, scop2);
4829 /* Add the computed skip condition of the given type to "main" and
4830 * add the scop for computing the condition at the given offset (the statement
4831 * number). Within this offset, the condition is computed at position 1
4832 * to ensure that it is computed after the corresponding statement.
4834 * If equal is set, then we only computed a skip condition for pet_skip_now,
4835 * but we also need to set it as main's pet_skip_later.
4837 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
4838 enum pet_skip type, int offset)
4840 if (!skip[type])
4841 return main;
4843 scop[type] = pet_scop_prefix(scop[type], 1);
4844 scop[type] = pet_scop_prefix(scop[type], offset);
4845 main = pet_scop_add_par(ctx, main, scop[type]);
4846 scop[type] = NULL;
4848 if (equal)
4849 main = pet_scop_set_skip(main, pet_skip_later,
4850 isl_multi_pw_aff_copy(index[type]));
4852 main = pet_scop_set_skip(main, type, index[type]);
4853 index[type] = NULL;
4855 return main;
4858 /* Add the computed skip conditions to "main" and
4859 * add the scops for computing the conditions at the given offset.
4861 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
4863 scop = add(scop, pet_skip_now, offset);
4864 scop = add(scop, pet_skip_later, offset);
4866 return scop;
4869 /* Extract a clone of the kill statement in "scop".
4870 * "scop" is expected to have been created from a DeclStmt
4871 * and should have the kill as its first statement.
4873 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
4875 struct pet_expr *kill;
4876 struct pet_stmt *stmt;
4877 isl_multi_pw_aff *index;
4878 isl_map *access;
4880 if (!scop)
4881 return NULL;
4882 if (scop->n_stmt < 1)
4883 isl_die(ctx, isl_error_internal,
4884 "expecting at least one statement", return NULL);
4885 stmt = scop->stmts[0];
4886 if (!pet_stmt_is_kill(stmt))
4887 isl_die(ctx, isl_error_internal,
4888 "expecting kill statement", return NULL);
4890 index = isl_multi_pw_aff_copy(stmt->body->args[0]->acc.index);
4891 access = isl_map_copy(stmt->body->args[0]->acc.access);
4892 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
4893 access = isl_map_reset_tuple_id(access, isl_dim_in);
4894 kill = pet_expr_kill_from_access_and_index(access, index);
4895 return pet_stmt_from_pet_expr(ctx, stmt->line, NULL, n_stmt++, kill);
4898 /* Mark all arrays in "scop" as being exposed.
4900 static struct pet_scop *mark_exposed(struct pet_scop *scop)
4902 if (!scop)
4903 return NULL;
4904 for (int i = 0; i < scop->n_array; ++i)
4905 scop->arrays[i]->exposed = 1;
4906 return scop;
4909 /* Try and construct a pet_scop corresponding to (part of)
4910 * a sequence of statements.
4912 * "block" is set if the sequence respresents the children of
4913 * a compound statement.
4914 * "skip_declarations" is set if we should skip initial declarations
4915 * in the sequence of statements.
4917 * If there are any breaks or continues in the individual statements,
4918 * then we may have to compute a new skip condition.
4919 * This is handled using a pet_skip_info_seq object.
4920 * On initialization, the object checks if skip conditions need
4921 * to be computed. If so, it does so in "extract" and adds them in "add".
4923 * If "block" is set, then we need to insert kill statements at
4924 * the end of the block for any array that has been declared by
4925 * one of the statements in the sequence. Each of these declarations
4926 * results in the construction of a kill statement at the place
4927 * of the declaration, so we simply collect duplicates of
4928 * those kill statements and append these duplicates to the constructed scop.
4930 * If "block" is not set, then any array declared by one of the statements
4931 * in the sequence is marked as being exposed.
4933 * If autodetect is set, then we allow the extraction of only a subrange
4934 * of the sequence of statements. However, if there is at least one statement
4935 * for which we could not construct a scop and the final range contains
4936 * either no statements or at least one kill, then we discard the entire
4937 * range.
4939 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
4940 bool skip_declarations)
4942 pet_scop *scop;
4943 StmtIterator i;
4944 int j;
4945 bool partial_range = false;
4946 set<struct pet_stmt *> kills;
4947 set<struct pet_stmt *>::iterator it;
4949 scop = pet_scop_empty(ctx);
4950 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4951 Stmt *child = *i;
4952 struct pet_scop *scop_i;
4954 if (scop->n_stmt == 0 && skip_declarations &&
4955 child->getStmtClass() == Stmt::DeclStmtClass)
4956 continue;
4958 scop_i = extract(child);
4959 if (scop->n_stmt != 0 && partial) {
4960 pet_scop_free(scop_i);
4961 break;
4963 pet_skip_info_seq skip(ctx, scop, scop_i);
4964 skip.extract(this);
4965 if (skip)
4966 scop_i = pet_scop_prefix(scop_i, 0);
4967 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4968 if (block)
4969 kills.insert(extract_kill(scop_i));
4970 else
4971 scop_i = mark_exposed(scop_i);
4973 scop_i = pet_scop_prefix(scop_i, j);
4974 if (options->autodetect) {
4975 if (scop_i)
4976 scop = pet_scop_add_seq(ctx, scop, scop_i);
4977 else
4978 partial_range = true;
4979 if (scop->n_stmt != 0 && !scop_i)
4980 partial = true;
4981 } else {
4982 scop = pet_scop_add_seq(ctx, scop, scop_i);
4985 scop = skip.add(scop, j);
4987 if (partial || !scop)
4988 break;
4991 for (it = kills.begin(); it != kills.end(); ++it) {
4992 pet_scop *scop_j;
4993 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4994 scop_j = pet_scop_prefix(scop_j, j);
4995 scop = pet_scop_add_seq(ctx, scop, scop_j);
4998 if (scop && partial_range) {
4999 if (scop->n_stmt == 0 || kills.size() != 0) {
5000 pet_scop_free(scop);
5001 return NULL;
5003 partial = true;
5006 return scop;
5009 /* Check if the scop marked by the user is exactly this Stmt
5010 * or part of this Stmt.
5011 * If so, return a pet_scop corresponding to the marked region.
5012 * Otherwise, return NULL.
5014 struct pet_scop *PetScan::scan(Stmt *stmt)
5016 SourceManager &SM = PP.getSourceManager();
5017 unsigned start_off, end_off;
5019 start_off = getExpansionOffset(SM, stmt->getLocStart());
5020 end_off = getExpansionOffset(SM, stmt->getLocEnd());
5022 if (start_off > loc.end)
5023 return NULL;
5024 if (end_off < loc.start)
5025 return NULL;
5026 if (start_off >= loc.start && end_off <= loc.end) {
5027 return extract(stmt);
5030 StmtIterator start;
5031 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
5032 Stmt *child = *start;
5033 if (!child)
5034 continue;
5035 start_off = getExpansionOffset(SM, child->getLocStart());
5036 end_off = getExpansionOffset(SM, child->getLocEnd());
5037 if (start_off < loc.start && end_off >= loc.end)
5038 return scan(child);
5039 if (start_off >= loc.start)
5040 break;
5043 StmtIterator end;
5044 for (end = start; end != stmt->child_end(); ++end) {
5045 Stmt *child = *end;
5046 start_off = SM.getFileOffset(child->getLocStart());
5047 if (start_off >= loc.end)
5048 break;
5051 return extract(StmtRange(start, end), false, false);
5054 /* Set the size of index "pos" of "array" to "size".
5055 * In particular, add a constraint of the form
5057 * i_pos < size
5059 * to array->extent and a constraint of the form
5061 * size >= 0
5063 * to array->context.
5065 static struct pet_array *update_size(struct pet_array *array, int pos,
5066 __isl_take isl_pw_aff *size)
5068 isl_set *valid;
5069 isl_set *univ;
5070 isl_set *bound;
5071 isl_space *dim;
5072 isl_aff *aff;
5073 isl_pw_aff *index;
5074 isl_id *id;
5076 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
5077 array->context = isl_set_intersect(array->context, valid);
5079 dim = isl_set_get_space(array->extent);
5080 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
5081 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
5082 univ = isl_set_universe(isl_aff_get_domain_space(aff));
5083 index = isl_pw_aff_alloc(univ, aff);
5085 size = isl_pw_aff_add_dims(size, isl_dim_in,
5086 isl_set_dim(array->extent, isl_dim_set));
5087 id = isl_set_get_tuple_id(array->extent);
5088 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
5089 bound = isl_pw_aff_lt_set(index, size);
5091 array->extent = isl_set_intersect(array->extent, bound);
5093 if (!array->context || !array->extent)
5094 goto error;
5096 return array;
5097 error:
5098 pet_array_free(array);
5099 return NULL;
5102 /* Figure out the size of the array at position "pos" and all
5103 * subsequent positions from "type" and update "array" accordingly.
5105 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
5106 const Type *type, int pos)
5108 const ArrayType *atype;
5109 isl_pw_aff *size;
5111 if (!array)
5112 return NULL;
5114 if (type->isPointerType()) {
5115 type = type->getPointeeType().getTypePtr();
5116 return set_upper_bounds(array, type, pos + 1);
5118 if (!type->isArrayType())
5119 return array;
5121 type = type->getCanonicalTypeInternal().getTypePtr();
5122 atype = cast<ArrayType>(type);
5124 if (type->isConstantArrayType()) {
5125 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
5126 size = extract_affine(ca->getSize());
5127 array = update_size(array, pos, size);
5128 } else if (type->isVariableArrayType()) {
5129 const VariableArrayType *vla = cast<VariableArrayType>(atype);
5130 size = extract_affine(vla->getSizeExpr());
5131 array = update_size(array, pos, size);
5134 type = atype->getElementType().getTypePtr();
5136 return set_upper_bounds(array, type, pos + 1);
5139 /* Is "T" the type of a variable length array with static size?
5141 static bool is_vla_with_static_size(QualType T)
5143 const VariableArrayType *vlatype;
5145 if (!T->isVariableArrayType())
5146 return false;
5147 vlatype = cast<VariableArrayType>(T);
5148 return vlatype->getSizeModifier() == VariableArrayType::Static;
5151 /* Return the type of "decl" as an array.
5153 * In particular, if "decl" is a parameter declaration that
5154 * is a variable length array with a static size, then
5155 * return the original type (i.e., the variable length array).
5156 * Otherwise, return the type of decl.
5158 static QualType get_array_type(ValueDecl *decl)
5160 ParmVarDecl *parm;
5161 QualType T;
5163 parm = dyn_cast<ParmVarDecl>(decl);
5164 if (!parm)
5165 return decl->getType();
5167 T = parm->getOriginalType();
5168 if (!is_vla_with_static_size(T))
5169 return decl->getType();
5170 return T;
5173 /* Does "decl" have definition that we can keep track of in a pet_type?
5175 static bool has_printable_definition(RecordDecl *decl)
5177 if (!decl->getDeclName())
5178 return false;
5179 return decl->getLexicalDeclContext() == decl->getDeclContext();
5182 /* Construct and return a pet_array corresponding to the variable "decl".
5183 * In particular, initialize array->extent to
5185 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
5187 * and then call set_upper_bounds to set the upper bounds on the indices
5188 * based on the type of the variable.
5190 * If the base type is that of a record with a top-level definition and
5191 * if "types" is not null, then the RecordDecl corresponding to the type
5192 * is added to "types".
5194 * If the base type is that of a record with no top-level definition,
5195 * then we replace it by "<subfield>".
5197 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
5198 lex_recorddecl_set *types)
5200 struct pet_array *array;
5201 QualType qt = get_array_type(decl);
5202 const Type *type = qt.getTypePtr();
5203 int depth = array_depth(type);
5204 QualType base = pet_clang_base_type(qt);
5205 string name;
5206 isl_id *id;
5207 isl_space *dim;
5209 array = isl_calloc_type(ctx, struct pet_array);
5210 if (!array)
5211 return NULL;
5213 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
5214 dim = isl_space_set_alloc(ctx, 0, depth);
5215 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
5217 array->extent = isl_set_nat_universe(dim);
5219 dim = isl_space_params_alloc(ctx, 0);
5220 array->context = isl_set_universe(dim);
5222 array = set_upper_bounds(array, type, 0);
5223 if (!array)
5224 return NULL;
5226 name = base.getAsString();
5228 if (types && base->isRecordType()) {
5229 RecordDecl *decl = pet_clang_record_decl(base);
5230 if (has_printable_definition(decl))
5231 types->insert(decl);
5232 else
5233 name = "<subfield>";
5236 array->element_type = strdup(name.c_str());
5237 array->element_is_record = base->isRecordType();
5238 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
5240 return array;
5243 /* Construct and return a pet_array corresponding to the sequence
5244 * of declarations "decls".
5245 * If the sequence contains a single declaration, then it corresponds
5246 * to a simple array access. Otherwise, it corresponds to a member access,
5247 * with the declaration for the substructure following that of the containing
5248 * structure in the sequence of declarations.
5249 * We start with the outermost substructure and then combine it with
5250 * information from the inner structures.
5252 * Additionally, keep track of all required types in "types".
5254 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
5255 vector<ValueDecl *> decls, lex_recorddecl_set *types)
5257 struct pet_array *array;
5258 vector<ValueDecl *>::iterator it;
5260 it = decls.begin();
5262 array = extract_array(ctx, *it, types);
5264 for (++it; it != decls.end(); ++it) {
5265 struct pet_array *parent;
5266 const char *base_name, *field_name;
5267 char *product_name;
5269 parent = array;
5270 array = extract_array(ctx, *it, types);
5271 if (!array)
5272 return pet_array_free(parent);
5274 base_name = isl_set_get_tuple_name(parent->extent);
5275 field_name = isl_set_get_tuple_name(array->extent);
5276 product_name = member_access_name(ctx, base_name, field_name);
5278 array->extent = isl_set_product(isl_set_copy(parent->extent),
5279 array->extent);
5280 if (product_name)
5281 array->extent = isl_set_set_tuple_name(array->extent,
5282 product_name);
5283 array->context = isl_set_intersect(array->context,
5284 isl_set_copy(parent->context));
5286 pet_array_free(parent);
5287 free(product_name);
5289 if (!array->extent || !array->context || !product_name)
5290 return pet_array_free(array);
5293 return array;
5296 /* Add a pet_type corresponding to "decl" to "scop, provided
5297 * it is a member of "types" and it has not been added before
5298 * (i.e., it is not a member of "types_done".
5300 * Since we want the user to be able to print the types
5301 * in the order in which they appear in the scop, we need to
5302 * make sure that types of fields in a structure appear before
5303 * that structure. We therefore call ourselves recursively
5304 * on the types of all record subfields.
5306 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
5307 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
5308 lex_recorddecl_set &types_done)
5310 string s;
5311 llvm::raw_string_ostream S(s);
5312 RecordDecl::field_iterator it;
5314 if (types.find(decl) == types.end())
5315 return scop;
5316 if (types_done.find(decl) != types_done.end())
5317 return scop;
5319 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
5320 RecordDecl *record;
5321 QualType type = it->getType();
5323 if (!type->isRecordType())
5324 continue;
5325 record = pet_clang_record_decl(type);
5326 scop = add_type(ctx, scop, record, PP, types, types_done);
5329 if (strlen(decl->getName().str().c_str()) == 0)
5330 return scop;
5332 decl->print(S, PrintingPolicy(PP.getLangOpts()));
5333 S.str();
5335 scop->types[scop->n_type] = pet_type_alloc(ctx,
5336 decl->getName().str().c_str(), s.c_str());
5337 if (!scop->types[scop->n_type])
5338 return pet_scop_free(scop);
5340 types_done.insert(decl);
5342 scop->n_type++;
5344 return scop;
5347 /* Construct a list of pet_arrays, one for each array (or scalar)
5348 * accessed inside "scop", add this list to "scop" and return the result.
5350 * The context of "scop" is updated with the intersection of
5351 * the contexts of all arrays, i.e., constraints on the parameters
5352 * that ensure that the arrays have a valid (non-negative) size.
5354 * If the any of the extracted arrays refers to a member access,
5355 * then also add the required types to "scop".
5357 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
5359 int i;
5360 set<vector<ValueDecl *> > arrays;
5361 set<vector<ValueDecl *> >::iterator it;
5362 lex_recorddecl_set types;
5363 lex_recorddecl_set types_done;
5364 lex_recorddecl_set::iterator types_it;
5365 int n_array;
5366 struct pet_array **scop_arrays;
5368 if (!scop)
5369 return NULL;
5371 pet_scop_collect_arrays(scop, arrays);
5372 if (arrays.size() == 0)
5373 return scop;
5375 n_array = scop->n_array;
5377 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
5378 n_array + arrays.size());
5379 if (!scop_arrays)
5380 goto error;
5381 scop->arrays = scop_arrays;
5383 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
5384 struct pet_array *array;
5385 array = extract_array(ctx, *it, &types);
5386 scop->arrays[n_array + i] = array;
5387 if (!scop->arrays[n_array + i])
5388 goto error;
5389 scop->n_array++;
5390 scop->context = isl_set_intersect(scop->context,
5391 isl_set_copy(array->context));
5392 if (!scop->context)
5393 goto error;
5396 if (types.size() == 0)
5397 return scop;
5399 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
5400 if (!scop->types)
5401 goto error;
5403 for (types_it = types.begin(); types_it != types.end(); ++types_it)
5404 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
5406 return scop;
5407 error:
5408 pet_scop_free(scop);
5409 return NULL;
5412 /* Bound all parameters in scop->context to the possible values
5413 * of the corresponding C variable.
5415 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
5417 int n;
5419 if (!scop)
5420 return NULL;
5422 n = isl_set_dim(scop->context, isl_dim_param);
5423 for (int i = 0; i < n; ++i) {
5424 isl_id *id;
5425 ValueDecl *decl;
5427 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
5428 if (pet_nested_in_id(id)) {
5429 isl_id_free(id);
5430 isl_die(isl_set_get_ctx(scop->context),
5431 isl_error_internal,
5432 "unresolved nested parameter", goto error);
5434 decl = (ValueDecl *) isl_id_get_user(id);
5435 isl_id_free(id);
5437 scop->context = set_parameter_bounds(scop->context, i, decl);
5439 if (!scop->context)
5440 goto error;
5443 return scop;
5444 error:
5445 pet_scop_free(scop);
5446 return NULL;
5449 /* Construct a pet_scop from the given function.
5451 * If the scop was delimited by scop and endscop pragmas, then we override
5452 * the file offsets by those derived from the pragmas.
5454 struct pet_scop *PetScan::scan(FunctionDecl *fd)
5456 pet_scop *scop;
5457 Stmt *stmt;
5459 stmt = fd->getBody();
5461 if (options->autodetect)
5462 scop = extract(stmt, true);
5463 else {
5464 scop = scan(stmt);
5465 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
5467 scop = pet_scop_detect_parameter_accesses(scop);
5468 scop = scan_arrays(scop);
5469 scop = add_parameter_bounds(scop);
5470 scop = pet_scop_gist(scop, value_bounds);
5472 return scop;