extract out pet_expr_is_assume
[pet.git] / scan.cc
blob5d0f1f8760a67714ac43538db403d2b1e2664a26
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 "aff.h"
51 #include "array.h"
52 #include "clang.h"
53 #include "context.h"
54 #include "expr.h"
55 #include "expr_arg.h"
56 #include "nest.h"
57 #include "options.h"
58 #include "scan.h"
59 #include "scop.h"
60 #include "scop_plus.h"
61 #include "skip.h"
63 #include "config.h"
65 using namespace std;
66 using namespace clang;
68 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
70 switch (kind) {
71 case UO_Minus:
72 return pet_op_minus;
73 case UO_Not:
74 return pet_op_not;
75 case UO_LNot:
76 return pet_op_lnot;
77 case UO_PostInc:
78 return pet_op_post_inc;
79 case UO_PostDec:
80 return pet_op_post_dec;
81 case UO_PreInc:
82 return pet_op_pre_inc;
83 case UO_PreDec:
84 return pet_op_pre_dec;
85 default:
86 return pet_op_last;
90 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
92 switch (kind) {
93 case BO_AddAssign:
94 return pet_op_add_assign;
95 case BO_SubAssign:
96 return pet_op_sub_assign;
97 case BO_MulAssign:
98 return pet_op_mul_assign;
99 case BO_DivAssign:
100 return pet_op_div_assign;
101 case BO_Assign:
102 return pet_op_assign;
103 case BO_Add:
104 return pet_op_add;
105 case BO_Sub:
106 return pet_op_sub;
107 case BO_Mul:
108 return pet_op_mul;
109 case BO_Div:
110 return pet_op_div;
111 case BO_Rem:
112 return pet_op_mod;
113 case BO_Shl:
114 return pet_op_shl;
115 case BO_Shr:
116 return pet_op_shr;
117 case BO_EQ:
118 return pet_op_eq;
119 case BO_NE:
120 return pet_op_ne;
121 case BO_LE:
122 return pet_op_le;
123 case BO_GE:
124 return pet_op_ge;
125 case BO_LT:
126 return pet_op_lt;
127 case BO_GT:
128 return pet_op_gt;
129 case BO_And:
130 return pet_op_and;
131 case BO_Xor:
132 return pet_op_xor;
133 case BO_Or:
134 return pet_op_or;
135 case BO_LAnd:
136 return pet_op_land;
137 case BO_LOr:
138 return pet_op_lor;
139 default:
140 return pet_op_last;
144 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
145 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
147 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
148 SourceLocation(), var, false, var->getInnerLocStart(),
149 var->getType(), VK_LValue);
151 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
152 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
154 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
155 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
156 VK_LValue);
158 #else
159 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
161 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
162 var, var->getInnerLocStart(), var->getType(), VK_LValue);
164 #endif
166 /* Check if the element type corresponding to the given array type
167 * has a const qualifier.
169 static bool const_base(QualType qt)
171 const Type *type = qt.getTypePtr();
173 if (type->isPointerType())
174 return const_base(type->getPointeeType());
175 if (type->isArrayType()) {
176 const ArrayType *atype;
177 type = type->getCanonicalTypeInternal().getTypePtr();
178 atype = cast<ArrayType>(type);
179 return const_base(atype->getElementType());
182 return qt.isConstQualified();
185 /* Create an isl_id that refers to the named declarator "decl".
187 static __isl_give isl_id *create_decl_id(isl_ctx *ctx, NamedDecl *decl)
189 return isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
192 /* Mark "decl" as having an unknown value in "assigned_value".
194 * If no (known or unknown) value was assigned to "decl" before,
195 * then it may have been treated as a parameter before and may
196 * therefore appear in a value assigned to another variable.
197 * If so, this assignment needs to be turned into an unknown value too.
199 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
200 ValueDecl *decl)
202 map<ValueDecl *, isl_pw_aff *>::iterator it;
204 it = assigned_value.find(decl);
206 assigned_value[decl] = NULL;
208 if (it != assigned_value.end())
209 return;
211 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
212 isl_pw_aff *pa = it->second;
213 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
215 for (int i = 0; i < nparam; ++i) {
216 isl_id *id;
218 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
219 continue;
220 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
221 if (isl_id_get_user(id) == decl)
222 it->second = NULL;
223 isl_id_free(id);
228 /* Look for any assignments to scalar variables in part of the parse
229 * tree and set assigned_value to NULL for each of them.
230 * Also reset assigned_value if the address of a scalar variable
231 * is being taken. As an exception, if the address is passed to a function
232 * that is declared to receive a const pointer, then assigned_value is
233 * not reset.
235 * This ensures that we won't use any previously stored value
236 * in the current subtree and its parents.
238 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
239 map<ValueDecl *, isl_pw_aff *> &assigned_value;
240 set<UnaryOperator *> skip;
242 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
243 assigned_value(assigned_value) {}
245 /* Check for "address of" operators whose value is passed
246 * to a const pointer argument and add them to "skip", so that
247 * we can skip them in VisitUnaryOperator.
249 bool VisitCallExpr(CallExpr *expr) {
250 FunctionDecl *fd;
251 fd = expr->getDirectCallee();
252 if (!fd)
253 return true;
254 for (int i = 0; i < expr->getNumArgs(); ++i) {
255 Expr *arg = expr->getArg(i);
256 UnaryOperator *op;
257 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
258 ImplicitCastExpr *ice;
259 ice = cast<ImplicitCastExpr>(arg);
260 arg = ice->getSubExpr();
262 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
263 continue;
264 op = cast<UnaryOperator>(arg);
265 if (op->getOpcode() != UO_AddrOf)
266 continue;
267 if (const_base(fd->getParamDecl(i)->getType()))
268 skip.insert(op);
270 return true;
273 bool VisitUnaryOperator(UnaryOperator *expr) {
274 Expr *arg;
275 DeclRefExpr *ref;
276 ValueDecl *decl;
278 switch (expr->getOpcode()) {
279 case UO_AddrOf:
280 case UO_PostInc:
281 case UO_PostDec:
282 case UO_PreInc:
283 case UO_PreDec:
284 break;
285 default:
286 return true;
288 if (skip.find(expr) != skip.end())
289 return true;
291 arg = expr->getSubExpr();
292 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
293 return true;
294 ref = cast<DeclRefExpr>(arg);
295 decl = ref->getDecl();
296 clear_assignment(assigned_value, decl);
297 return true;
300 bool VisitBinaryOperator(BinaryOperator *expr) {
301 Expr *lhs;
302 DeclRefExpr *ref;
303 ValueDecl *decl;
305 if (!expr->isAssignmentOp())
306 return true;
307 lhs = expr->getLHS();
308 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
309 return true;
310 ref = cast<DeclRefExpr>(lhs);
311 decl = ref->getDecl();
312 clear_assignment(assigned_value, decl);
313 return true;
317 /* Keep a copy of the currently assigned values.
319 * Any variable that is assigned a value inside the current scope
320 * is removed again when we leave the scope (either because it wasn't
321 * stored in the cache or because it has a different value in the cache).
323 struct assigned_value_cache {
324 map<ValueDecl *, isl_pw_aff *> &assigned_value;
325 map<ValueDecl *, isl_pw_aff *> cache;
327 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
328 assigned_value(assigned_value), cache(assigned_value) {}
329 ~assigned_value_cache() {
330 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
331 for (it = assigned_value.begin(); it != assigned_value.end();
332 ++it) {
333 if (!it->second ||
334 (cache.find(it->first) != cache.end() &&
335 cache[it->first] != it->second))
336 cache[it->first] = NULL;
338 assigned_value = cache;
342 /* Convert the mapping from identifiers to values in "assigned_value"
343 * to a pet_context to be used by pet_expr_extract_*.
344 * In particular, the clang identifiers are wrapped in an isl_id and
345 * a NULL value (representing an unknown value) is replaced by a NaN.
347 static __isl_give pet_context *convert_assignments(isl_ctx *ctx,
348 map<ValueDecl *, isl_pw_aff *> &assigned_value)
350 pet_context *pc;
351 map<ValueDecl *, isl_pw_aff *>::iterator it;
353 pc = pet_context_alloc(isl_space_set_alloc(ctx, 0, 0));
355 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
356 ValueDecl *decl = it->first;
357 isl_pw_aff *pa = it->second;
358 isl_id *id;
360 id = create_decl_id(ctx, decl);
361 if (pa)
362 pc = pet_context_set_value(pc, id, isl_pw_aff_copy(pa));
363 else
364 pc = pet_context_mark_unknown(pc, id);
367 return pc;
370 /* Insert an expression into the collection of expressions,
371 * provided it is not already in there.
372 * The isl_pw_affs are freed in the destructor.
374 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
376 std::set<isl_pw_aff *>::iterator it;
378 if (expressions.find(expr) == expressions.end())
379 expressions.insert(expr);
380 else
381 isl_pw_aff_free(expr);
384 PetScan::~PetScan()
386 std::set<isl_pw_aff *>::iterator it;
388 for (it = expressions.begin(); it != expressions.end(); ++it)
389 isl_pw_aff_free(*it);
391 isl_union_map_free(value_bounds);
394 /* Report a diagnostic, unless autodetect is set.
396 void PetScan::report(Stmt *stmt, unsigned id)
398 if (options->autodetect)
399 return;
401 SourceLocation loc = stmt->getLocStart();
402 DiagnosticsEngine &diag = PP.getDiagnostics();
403 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
406 /* Called if we found something we (currently) cannot handle.
407 * We'll provide more informative warnings later.
409 * We only actually complain if autodetect is false.
411 void PetScan::unsupported(Stmt *stmt)
413 DiagnosticsEngine &diag = PP.getDiagnostics();
414 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
415 "unsupported");
416 report(stmt, id);
419 /* Report a missing prototype, unless autodetect is set.
421 void PetScan::report_prototype_required(Stmt *stmt)
423 DiagnosticsEngine &diag = PP.getDiagnostics();
424 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
425 "prototype required");
426 report(stmt, id);
429 /* Report a missing increment, unless autodetect is set.
431 void PetScan::report_missing_increment(Stmt *stmt)
433 DiagnosticsEngine &diag = PP.getDiagnostics();
434 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
435 "missing increment");
436 report(stmt, id);
439 /* Extract an integer from "expr".
441 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
443 const Type *type = expr->getType().getTypePtr();
444 int is_signed = type->hasSignedIntegerRepresentation();
445 llvm::APInt val = expr->getValue();
446 int is_negative = is_signed && val.isNegative();
447 isl_val *v;
449 if (is_negative)
450 val = -val;
452 v = extract_unsigned(ctx, val);
454 if (is_negative)
455 v = isl_val_neg(v);
456 return v;
459 /* Extract an integer from "val", which is assumed to be non-negative.
461 __isl_give isl_val *PetScan::extract_unsigned(isl_ctx *ctx,
462 const llvm::APInt &val)
464 unsigned n;
465 const uint64_t *data;
467 data = val.getRawData();
468 n = val.getNumWords();
469 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
472 /* Extract an integer from "expr".
473 * Return NULL if "expr" does not (obviously) represent an integer.
475 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
477 return extract_int(expr->getSubExpr());
480 /* Extract an integer from "expr".
481 * Return NULL if "expr" does not (obviously) represent an integer.
483 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
485 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
486 return extract_int(ctx, cast<IntegerLiteral>(expr));
487 if (expr->getStmtClass() == Stmt::ParenExprClass)
488 return extract_int(cast<ParenExpr>(expr));
490 unsupported(expr);
491 return NULL;
494 /* Extract an affine expression from the APInt "val", which is assumed
495 * to be non-negative.
496 * If the value of "val" is "v", then the returned expression
497 * is
499 * { [] -> [v] }
501 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
503 isl_space *space = isl_space_set_alloc(ctx, 0, 0);
504 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(space));
505 isl_aff *aff = isl_aff_zero_on_domain(ls);
506 isl_set *dom = isl_set_universe(space);
507 isl_val *v;
509 v = extract_unsigned(ctx, val);
510 aff = isl_aff_add_constant_val(aff, v);
512 return isl_pw_aff_alloc(dom, aff);
515 /* Return the number of bits needed to represent the type "qt",
516 * if it is an integer type. Otherwise return 0.
517 * If qt is signed then return the opposite of the number of bits.
519 static int get_type_size(QualType qt, ASTContext &ast_context)
521 int size;
523 if (!qt->isIntegerType())
524 return 0;
526 size = ast_context.getIntWidth(qt);
527 if (!qt->isUnsignedIntegerType())
528 size = -size;
530 return size;
533 /* Return the number of bits needed to represent the type of "decl",
534 * if it is an integer type. Otherwise return 0.
535 * If qt is signed then return the opposite of the number of bits.
537 static int get_type_size(ValueDecl *decl)
539 return get_type_size(decl->getType(), decl->getASTContext());
542 /* Bound parameter "pos" of "set" to the possible values of "decl".
544 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
545 unsigned pos, ValueDecl *decl)
547 int type_size;
548 isl_ctx *ctx;
549 isl_val *bound;
551 ctx = isl_set_get_ctx(set);
552 type_size = get_type_size(decl);
553 if (type_size == 0)
554 isl_die(ctx, isl_error_invalid, "not an integer type",
555 return isl_set_free(set));
556 if (type_size > 0) {
557 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
558 bound = isl_val_int_from_ui(ctx, type_size);
559 bound = isl_val_2exp(bound);
560 bound = isl_val_sub_ui(bound, 1);
561 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
562 } else {
563 bound = isl_val_int_from_ui(ctx, -type_size - 1);
564 bound = isl_val_2exp(bound);
565 bound = isl_val_sub_ui(bound, 1);
566 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
567 isl_val_copy(bound));
568 bound = isl_val_neg(bound);
569 bound = isl_val_sub_ui(bound, 1);
570 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
573 return set;
576 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
578 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
579 __isl_take isl_set *dom)
581 isl_pw_aff *pa;
582 pa = isl_set_indicator_function(set);
583 pa = isl_pw_aff_intersect_domain(pa, isl_set_coalesce(dom));
584 return pa;
587 /* Extract an affine expression, if possible, from "expr".
588 * Otherwise return NULL.
590 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
592 pet_expr *pe;
593 pet_context *pc;
594 isl_pw_aff *pa;
596 pe = extract_expr(expr);
597 if (!pe)
598 return NULL;
599 pc = convert_assignments(ctx, assigned_value);
600 pe = pet_expr_plug_in_args(pe, pc);
601 pa = pet_expr_extract_affine(pe, pc);
602 if (isl_pw_aff_involves_nan(pa)) {
603 unsupported(expr);
604 pa = isl_pw_aff_free(pa);
606 pet_context_free(pc);
607 pet_expr_free(pe);
609 return pa;
612 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
614 return extract_index_expr(expr->getSubExpr());
617 /* Return the depth of an array of the given type.
619 static int array_depth(const Type *type)
621 if (type->isPointerType())
622 return 1 + array_depth(type->getPointeeType().getTypePtr());
623 if (type->isArrayType()) {
624 const ArrayType *atype;
625 type = type->getCanonicalTypeInternal().getTypePtr();
626 atype = cast<ArrayType>(type);
627 return 1 + array_depth(atype->getElementType().getTypePtr());
629 return 0;
632 /* Return the depth of the array accessed by the index expression "index".
633 * If "index" is an affine expression, i.e., if it does not access
634 * any array, then return 1.
635 * If "index" represent a member access, i.e., if its range is a wrapped
636 * relation, then return the sum of the depth of the array of structures
637 * and that of the member inside the structure.
639 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
641 isl_id *id;
642 ValueDecl *decl;
644 if (!index)
645 return -1;
647 if (isl_multi_pw_aff_range_is_wrapping(index)) {
648 int domain_depth, range_depth;
649 isl_multi_pw_aff *domain, *range;
651 domain = isl_multi_pw_aff_copy(index);
652 domain = isl_multi_pw_aff_range_factor_domain(domain);
653 domain_depth = extract_depth(domain);
654 isl_multi_pw_aff_free(domain);
655 range = isl_multi_pw_aff_copy(index);
656 range = isl_multi_pw_aff_range_factor_range(range);
657 range_depth = extract_depth(range);
658 isl_multi_pw_aff_free(range);
660 return domain_depth + range_depth;
663 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
664 return 1;
666 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
667 if (!id)
668 return -1;
669 decl = (ValueDecl *) isl_id_get_user(id);
670 isl_id_free(id);
672 return array_depth(decl->getType().getTypePtr());
675 /* Return the depth of the array accessed by the access expression "expr".
677 static int extract_depth(__isl_keep pet_expr *expr)
679 isl_multi_pw_aff *index;
680 int depth;
682 index = pet_expr_access_get_index(expr);
683 depth = extract_depth(index);
684 isl_multi_pw_aff_free(index);
686 return depth;
689 /* Construct a pet_expr representing an index expression for an access
690 * to the variable referenced by "expr".
692 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
694 return extract_index_expr(expr->getDecl());
697 /* Construct a pet_expr representing an index expression for an access
698 * to the variable "decl".
700 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
702 isl_id *id = create_decl_id(ctx, decl);
703 isl_space *space = isl_space_alloc(ctx, 0, 0, 0);
705 space = isl_space_set_tuple_id(space, isl_dim_out, id);
707 return pet_expr_from_index(isl_multi_pw_aff_zero(space));
710 /* Construct a pet_expr representing the index expression "expr"
711 * Return NULL on error.
713 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
715 switch (expr->getStmtClass()) {
716 case Stmt::ImplicitCastExprClass:
717 return extract_index_expr(cast<ImplicitCastExpr>(expr));
718 case Stmt::DeclRefExprClass:
719 return extract_index_expr(cast<DeclRefExpr>(expr));
720 case Stmt::ArraySubscriptExprClass:
721 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
722 case Stmt::IntegerLiteralClass:
723 return extract_expr(cast<IntegerLiteral>(expr));
724 case Stmt::MemberExprClass:
725 return extract_index_expr(cast<MemberExpr>(expr));
726 default:
727 unsupported(expr);
729 return NULL;
732 /* Extract an index expression from the given array subscript expression.
734 * We first extract an index expression from the base.
735 * This will result in an index expression with a range that corresponds
736 * to the earlier indices.
737 * We then extract the current index and let
738 * pet_expr_access_subscript combine the two.
740 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
742 Expr *base = expr->getBase();
743 Expr *idx = expr->getIdx();
744 pet_expr *index;
745 pet_expr *base_expr;
747 base_expr = extract_index_expr(base);
748 index = extract_expr(idx);
750 base_expr = pet_expr_access_subscript(base_expr, index);
752 return base_expr;
755 /* Extract an index expression from a member expression.
757 * If the base access (to the structure containing the member)
758 * is of the form
760 * A[..]
762 * and the member is called "f", then the member access is of
763 * the form
765 * A_f[A[..] -> f[]]
767 * If the member access is to an anonymous struct, then simply return
769 * A[..]
771 * If the member access in the source code is of the form
773 * A->f
775 * then it is treated as
777 * A[0].f
779 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
781 Expr *base = expr->getBase();
782 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
783 pet_expr *base_index;
784 isl_id *id;
786 base_index = extract_index_expr(base);
788 if (expr->isArrow()) {
789 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
790 base_index = pet_expr_access_subscript(base_index, index);
793 if (field->isAnonymousStructOrUnion())
794 return base_index;
796 id = create_decl_id(ctx, field);
798 return pet_expr_access_member(base_index, id);
801 /* Check if "expr" calls function "minmax" with two arguments and if so
802 * make lhs and rhs refer to these two arguments.
804 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
806 CallExpr *call;
807 FunctionDecl *fd;
808 string name;
810 if (expr->getStmtClass() != Stmt::CallExprClass)
811 return false;
813 call = cast<CallExpr>(expr);
814 fd = call->getDirectCallee();
815 if (!fd)
816 return false;
818 if (call->getNumArgs() != 2)
819 return false;
821 name = fd->getDeclName().getAsString();
822 if (name != minmax)
823 return false;
825 lhs = call->getArg(0);
826 rhs = call->getArg(1);
828 return true;
831 /* Check if "expr" is of the form min(lhs, rhs) and if so make
832 * lhs and rhs refer to the two arguments.
834 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
836 return is_minmax(expr, "min", lhs, rhs);
839 /* Check if "expr" is of the form max(lhs, rhs) and if so make
840 * lhs and rhs refer to the two arguments.
842 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
844 return is_minmax(expr, "max", lhs, rhs);
847 /* Extract an affine expressions representing the comparison "LHS op RHS"
848 * "comp" is the original statement that "LHS op RHS" is derived from
849 * and is used for diagnostics.
851 * If the comparison is of the form
853 * a <= min(b,c)
855 * then the expression is constructed as the conjunction of
856 * the comparisons
858 * a <= b and a <= c
860 * A similar optimization is performed for max(a,b) <= c.
861 * We do this because that will lead to simpler representations
862 * of the expression.
863 * If isl is ever enhanced to explicitly deal with min and max expressions,
864 * this optimization can be removed.
866 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
867 Expr *LHS, Expr *RHS, Stmt *comp)
869 isl_pw_aff *lhs;
870 isl_pw_aff *rhs;
871 isl_pw_aff *res;
872 isl_set *cond;
873 isl_set *dom;
874 enum pet_op_type type;
876 if (op == BO_GT)
877 return extract_comparison(BO_LT, RHS, LHS, comp);
878 if (op == BO_GE)
879 return extract_comparison(BO_LE, RHS, LHS, comp);
881 if (op == BO_LT || op == BO_LE) {
882 Expr *expr1, *expr2;
883 if (is_min(RHS, expr1, expr2)) {
884 lhs = extract_comparison(op, LHS, expr1, comp);
885 rhs = extract_comparison(op, LHS, expr2, comp);
886 return pet_and(lhs, rhs);
888 if (is_max(LHS, expr1, expr2)) {
889 lhs = extract_comparison(op, expr1, RHS, comp);
890 rhs = extract_comparison(op, expr2, RHS, comp);
891 return pet_and(lhs, rhs);
895 lhs = extract_affine(LHS);
896 rhs = extract_affine(RHS);
898 type = BinaryOperatorKind2pet_op_type(op);
899 return pet_comparison(type, lhs, rhs);
902 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
904 return extract_comparison(comp->getOpcode(), comp->getLHS(),
905 comp->getRHS(), comp);
908 /* Extract an affine expression from a boolean expression.
909 * In particular, return the expression "expr ? 1 : 0".
910 * Return NULL if we are unable to extract an affine expression.
912 * We first convert the clang::Expr to a pet_expr and
913 * then extract an affine expression from that pet_expr.
915 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
917 isl_pw_aff *cond;
918 pet_expr *pe;
919 pet_context *pc;
921 if (!expr) {
922 isl_set *u = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
923 return indicator_function(u, isl_set_copy(u));
926 pe = extract_expr(expr);
927 pc = convert_assignments(ctx, assigned_value);
928 pe = pet_expr_plug_in_args(pe, pc);
929 pc = pet_context_set_allow_nested(pc, nesting_enabled);
930 cond = pet_expr_extract_affine_condition(pe, pc);
931 if (isl_pw_aff_involves_nan(cond))
932 cond = isl_pw_aff_free(cond);
933 pet_context_free(pc);
934 pet_expr_free(pe);
935 return cond;
938 /* Mark the given access pet_expr as a write.
940 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
942 access = pet_expr_access_set_write(access, 1);
943 access = pet_expr_access_set_read(access, 0);
945 return access;
948 /* Construct a pet_expr representing a unary operator expression.
950 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
952 pet_expr *arg;
953 enum pet_op_type op;
955 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
956 if (op == pet_op_last) {
957 unsupported(expr);
958 return NULL;
961 arg = extract_expr(expr->getSubExpr());
963 if (expr->isIncrementDecrementOp() &&
964 pet_expr_get_type(arg) == pet_expr_access) {
965 arg = mark_write(arg);
966 arg = pet_expr_access_set_read(arg, 1);
969 return pet_expr_new_unary(op, arg);
972 /* If the access expression "expr" writes to a (non-virtual) scalar,
973 * then mark the scalar as having an unknown value in "assigned_value".
975 static int clear_write(__isl_keep pet_expr *expr, void *user)
977 isl_id *id;
978 ValueDecl *decl;
979 PetScan *ps = (PetScan *) user;
981 if (!pet_expr_access_is_write(expr))
982 return 0;
983 if (!pet_expr_is_scalar_access(expr))
984 return 0;
986 id = pet_expr_access_get_id(expr);
987 decl = (ValueDecl *) isl_id_get_user(id);
988 isl_id_free(id);
990 if (decl)
991 clear_assignment(ps->assigned_value, decl);
993 return 0;
996 /* Take into account the writes in "stmt".
997 * That is, first mark all scalar variables that are written by "stmt"
998 * as having an unknown value. Afterwards,
999 * if "stmt" is a top-level (i.e., unconditional) assignment
1000 * to a scalar variable, then update "assigned_value" accordingly.
1002 * In particular, if the lhs of the assignment is a scalar variable, then mark
1003 * the variable as having been assigned. If, furthermore, the rhs
1004 * is an affine expression, then keep track of this value in assigned_value
1005 * so that we can plug it in when we later come across the same variable.
1007 * We skip assignments to virtual arrays (those with NULL user pointer).
1009 void PetScan::handle_writes(struct pet_stmt *stmt)
1011 pet_expr *body = stmt->body;
1012 pet_expr *arg;
1013 isl_id *id;
1014 ValueDecl *decl;
1015 pet_context *pc;
1016 isl_pw_aff *pa;
1018 pet_expr_foreach_access_expr(body, &clear_write, this);
1020 if (!pet_stmt_is_assign(stmt))
1021 return;
1022 if (!isl_set_plain_is_universe(stmt->domain))
1023 return;
1024 arg = pet_expr_get_arg(body, 0);
1025 if (!pet_expr_is_scalar_access(arg)) {
1026 pet_expr_free(arg);
1027 return;
1030 id = pet_expr_access_get_id(arg);
1031 decl = (ValueDecl *) isl_id_get_user(id);
1032 isl_id_free(id);
1033 pet_expr_free(arg);
1035 if (!decl)
1036 return;
1038 arg = pet_expr_get_arg(body, 1);
1039 pc = convert_assignments(ctx, assigned_value);
1040 pa = pet_expr_extract_affine(arg, pc);
1041 pet_context_free(pc);
1042 clear_assignment(assigned_value, decl);
1043 pet_expr_free(arg);
1045 if (isl_pw_aff_involves_nan(pa))
1046 pa = isl_pw_aff_free(pa);
1047 if (!pa)
1048 return;
1049 assigned_value[decl] = pa;
1050 insert_expression(pa);
1053 /* Update "assigned_value" based on the write accesses (and, in particular,
1054 * assignments) in "scop".
1056 void PetScan::handle_writes(struct pet_scop *scop)
1058 if (!scop)
1059 return;
1060 for (int i = 0; i < scop->n_stmt; ++i)
1061 handle_writes(scop->stmts[i]);
1064 /* Construct a pet_expr representing a binary operator expression.
1066 * If the top level operator is an assignment and the LHS is an access,
1067 * then we mark that access as a write. If the operator is a compound
1068 * assignment, the access is marked as both a read and a write.
1070 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1072 int type_size;
1073 pet_expr *lhs, *rhs;
1074 enum pet_op_type op;
1076 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1077 if (op == pet_op_last) {
1078 unsupported(expr);
1079 return NULL;
1082 lhs = extract_expr(expr->getLHS());
1083 rhs = extract_expr(expr->getRHS());
1085 if (expr->isAssignmentOp() &&
1086 pet_expr_get_type(lhs) == pet_expr_access) {
1087 lhs = mark_write(lhs);
1088 if (expr->isCompoundAssignmentOp())
1089 lhs = pet_expr_access_set_read(lhs, 1);
1092 type_size = get_type_size(expr->getType(), ast_context);
1093 return pet_expr_new_binary(type_size, op, lhs, rhs);
1096 /* Construct a pet_scop with a single statement killing the entire
1097 * array "array".
1099 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1101 isl_id *id;
1102 isl_space *space;
1103 isl_multi_pw_aff *index;
1104 isl_map *access;
1105 pet_expr *expr;
1107 if (!array)
1108 return NULL;
1109 access = isl_map_from_range(isl_set_copy(array->extent));
1110 id = isl_set_get_tuple_id(array->extent);
1111 space = isl_space_alloc(ctx, 0, 0, 0);
1112 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1113 index = isl_multi_pw_aff_zero(space);
1114 expr = pet_expr_kill_from_access_and_index(access, index);
1115 return extract(expr, stmt->getSourceRange(), false);
1118 /* Construct a pet_scop for a (single) variable declaration.
1120 * The scop contains the variable being declared (as an array)
1121 * and a statement killing the array.
1123 * If the variable is initialized in the AST, then the scop
1124 * also contains an assignment to the variable.
1126 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1128 int type_size;
1129 Decl *decl;
1130 VarDecl *vd;
1131 pet_expr *lhs, *rhs, *pe;
1132 struct pet_scop *scop_decl, *scop;
1133 struct pet_array *array;
1135 if (!stmt->isSingleDecl()) {
1136 unsupported(stmt);
1137 return NULL;
1140 decl = stmt->getSingleDecl();
1141 vd = cast<VarDecl>(decl);
1143 array = extract_array(ctx, vd, NULL);
1144 if (array)
1145 array->declared = 1;
1146 scop_decl = kill(stmt, array);
1147 scop_decl = pet_scop_add_array(scop_decl, array);
1149 if (!vd->getInit())
1150 return scop_decl;
1152 lhs = extract_access_expr(vd);
1153 rhs = extract_expr(vd->getInit());
1155 lhs = mark_write(lhs);
1157 type_size = get_type_size(vd->getType(), ast_context);
1158 pe = pet_expr_new_binary(type_size, pet_op_assign, lhs, rhs);
1159 scop = extract(pe, stmt->getSourceRange(), false);
1161 scop_decl = pet_scop_prefix(scop_decl, 0);
1162 scop = pet_scop_prefix(scop, 1);
1164 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1166 return scop;
1169 /* Construct a pet_expr representing a conditional operation.
1171 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1173 pet_expr *cond, *lhs, *rhs;
1174 isl_pw_aff *pa;
1176 cond = extract_expr(expr->getCond());
1177 lhs = extract_expr(expr->getTrueExpr());
1178 rhs = extract_expr(expr->getFalseExpr());
1180 return pet_expr_new_ternary(cond, lhs, rhs);
1183 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1185 return extract_expr(expr->getSubExpr());
1188 /* Construct a pet_expr representing a floating point value.
1190 * If the floating point literal does not appear in a macro,
1191 * then we use the original representation in the source code
1192 * as the string representation. Otherwise, we use the pretty
1193 * printer to produce a string representation.
1195 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1197 double d;
1198 string s;
1199 const LangOptions &LO = PP.getLangOpts();
1200 SourceLocation loc = expr->getLocation();
1202 if (!loc.isMacroID()) {
1203 SourceManager &SM = PP.getSourceManager();
1204 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1205 s = string(SM.getCharacterData(loc), len);
1206 } else {
1207 llvm::raw_string_ostream S(s);
1208 expr->printPretty(S, 0, PrintingPolicy(LO));
1209 S.str();
1211 d = expr->getValueAsApproximateDouble();
1212 return pet_expr_new_double(ctx, d, s.c_str());
1215 /* Convert the index expression "index" into an access pet_expr of type "qt".
1217 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
1218 __isl_take pet_expr *index)
1220 int depth;
1221 int type_size;
1223 depth = extract_depth(index);
1224 type_size = get_type_size(qt, ast_context);
1226 index = pet_expr_set_type_size(index, type_size);
1227 index = pet_expr_access_set_depth(index, depth);
1229 return index;
1232 /* Extract an index expression from "expr" and then convert it into
1233 * an access pet_expr.
1235 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
1237 return extract_access_expr(expr->getType(), extract_index_expr(expr));
1240 /* Extract an index expression from "decl" and then convert it into
1241 * an access pet_expr.
1243 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1245 return extract_access_expr(decl->getType(), extract_index_expr(decl));
1248 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
1250 return extract_expr(expr->getSubExpr());
1253 /* Extract an assume statement from the argument "expr"
1254 * of a __pencil_assume statement.
1256 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
1258 isl_pw_aff *cond;
1259 pet_expr *res;
1261 cond = try_extract_affine_condition(expr);
1262 if (!cond) {
1263 res = extract_expr(expr);
1264 } else {
1265 isl_multi_pw_aff *index;
1266 index = isl_multi_pw_aff_from_pw_aff(cond);
1267 res = pet_expr_from_index(index);
1269 return pet_expr_new_unary(pet_op_assume, res);
1272 /* Construct a pet_expr corresponding to the function call argument "expr".
1273 * The argument appears in position "pos" of a call to function "fd".
1275 * If we are passing along a pointer to an array element
1276 * or an entire row or even higher dimensional slice of an array,
1277 * then the function being called may write into the array.
1279 * We assume here that if the function is declared to take a pointer
1280 * to a const type, then the function will perform a read
1281 * and that otherwise, it will perform a write.
1283 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
1284 Expr *expr)
1286 pet_expr *res;
1287 int is_addr = 0, is_partial = 0;
1288 Stmt::StmtClass sc;
1290 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
1291 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
1292 expr = ice->getSubExpr();
1294 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
1295 UnaryOperator *op = cast<UnaryOperator>(expr);
1296 if (op->getOpcode() == UO_AddrOf) {
1297 is_addr = 1;
1298 expr = op->getSubExpr();
1301 res = extract_expr(expr);
1302 if (!res)
1303 return NULL;
1304 sc = expr->getStmtClass();
1305 if ((sc == Stmt::ArraySubscriptExprClass ||
1306 sc == Stmt::MemberExprClass) &&
1307 array_depth(expr->getType().getTypePtr()) > 0)
1308 is_partial = 1;
1309 if ((is_addr || is_partial) &&
1310 pet_expr_get_type(res) == pet_expr_access) {
1311 ParmVarDecl *parm;
1312 if (!fd->hasPrototype()) {
1313 report_prototype_required(expr);
1314 return pet_expr_free(res);
1316 parm = fd->getParamDecl(pos);
1317 if (!const_base(parm->getType()))
1318 res = mark_write(res);
1321 if (is_addr)
1322 res = pet_expr_new_unary(pet_op_address_of, res);
1323 return res;
1326 /* Construct a pet_expr representing a function call.
1328 * In the special case of a "call" to __pencil_assume,
1329 * construct an assume expression instead.
1331 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1333 pet_expr *res = NULL;
1334 FunctionDecl *fd;
1335 string name;
1336 unsigned n_arg;
1338 fd = expr->getDirectCallee();
1339 if (!fd) {
1340 unsupported(expr);
1341 return NULL;
1344 name = fd->getDeclName().getAsString();
1345 n_arg = expr->getNumArgs();
1347 if (n_arg == 1 && name == "__pencil_assume")
1348 return extract_assume(expr->getArg(0));
1350 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1351 if (!res)
1352 return NULL;
1354 for (int i = 0; i < n_arg; ++i) {
1355 Expr *arg = expr->getArg(i);
1356 res = pet_expr_set_arg(res, i,
1357 PetScan::extract_argument(fd, i, arg));
1360 return res;
1363 /* Construct a pet_expr representing a (C style) cast.
1365 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1367 pet_expr *arg;
1368 QualType type;
1370 arg = extract_expr(expr->getSubExpr());
1371 if (!arg)
1372 return NULL;
1374 type = expr->getTypeAsWritten();
1375 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1378 /* Construct a pet_expr representing an integer.
1380 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1382 return pet_expr_new_int(extract_int(expr));
1385 /* Try and construct a pet_expr representing "expr".
1387 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1389 switch (expr->getStmtClass()) {
1390 case Stmt::UnaryOperatorClass:
1391 return extract_expr(cast<UnaryOperator>(expr));
1392 case Stmt::CompoundAssignOperatorClass:
1393 case Stmt::BinaryOperatorClass:
1394 return extract_expr(cast<BinaryOperator>(expr));
1395 case Stmt::ImplicitCastExprClass:
1396 return extract_expr(cast<ImplicitCastExpr>(expr));
1397 case Stmt::ArraySubscriptExprClass:
1398 case Stmt::DeclRefExprClass:
1399 case Stmt::MemberExprClass:
1400 return extract_access_expr(expr);
1401 case Stmt::IntegerLiteralClass:
1402 return extract_expr(cast<IntegerLiteral>(expr));
1403 case Stmt::FloatingLiteralClass:
1404 return extract_expr(cast<FloatingLiteral>(expr));
1405 case Stmt::ParenExprClass:
1406 return extract_expr(cast<ParenExpr>(expr));
1407 case Stmt::ConditionalOperatorClass:
1408 return extract_expr(cast<ConditionalOperator>(expr));
1409 case Stmt::CallExprClass:
1410 return extract_expr(cast<CallExpr>(expr));
1411 case Stmt::CStyleCastExprClass:
1412 return extract_expr(cast<CStyleCastExpr>(expr));
1413 default:
1414 unsupported(expr);
1416 return NULL;
1419 /* Check if the given initialization statement is an assignment.
1420 * If so, return that assignment. Otherwise return NULL.
1422 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1424 BinaryOperator *ass;
1426 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1427 return NULL;
1429 ass = cast<BinaryOperator>(init);
1430 if (ass->getOpcode() != BO_Assign)
1431 return NULL;
1433 return ass;
1436 /* Check if the given initialization statement is a declaration
1437 * of a single variable.
1438 * If so, return that declaration. Otherwise return NULL.
1440 Decl *PetScan::initialization_declaration(Stmt *init)
1442 DeclStmt *decl;
1444 if (init->getStmtClass() != Stmt::DeclStmtClass)
1445 return NULL;
1447 decl = cast<DeclStmt>(init);
1449 if (!decl->isSingleDecl())
1450 return NULL;
1452 return decl->getSingleDecl();
1455 /* Given the assignment operator in the initialization of a for loop,
1456 * extract the induction variable, i.e., the (integer)variable being
1457 * assigned.
1459 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1461 Expr *lhs;
1462 DeclRefExpr *ref;
1463 ValueDecl *decl;
1464 const Type *type;
1466 lhs = init->getLHS();
1467 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1468 unsupported(init);
1469 return NULL;
1472 ref = cast<DeclRefExpr>(lhs);
1473 decl = ref->getDecl();
1474 type = decl->getType().getTypePtr();
1476 if (!type->isIntegerType()) {
1477 unsupported(lhs);
1478 return NULL;
1481 return decl;
1484 /* Given the initialization statement of a for loop and the single
1485 * declaration in this initialization statement,
1486 * extract the induction variable, i.e., the (integer) variable being
1487 * declared.
1489 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1491 VarDecl *vd;
1493 vd = cast<VarDecl>(decl);
1495 const QualType type = vd->getType();
1496 if (!type->isIntegerType()) {
1497 unsupported(init);
1498 return NULL;
1501 if (!vd->getInit()) {
1502 unsupported(init);
1503 return NULL;
1506 return vd;
1509 /* Check that op is of the form iv++ or iv--.
1510 * Return a pet_expr representing "1" or "-1" accordingly.
1512 __isl_give pet_expr *PetScan::extract_unary_increment(
1513 clang::UnaryOperator *op, clang::ValueDecl *iv)
1515 Expr *sub;
1516 DeclRefExpr *ref;
1517 isl_val *v;
1519 if (!op->isIncrementDecrementOp()) {
1520 unsupported(op);
1521 return NULL;
1524 sub = op->getSubExpr();
1525 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1526 unsupported(op);
1527 return NULL;
1530 ref = cast<DeclRefExpr>(sub);
1531 if (ref->getDecl() != iv) {
1532 unsupported(op);
1533 return NULL;
1536 if (op->isIncrementOp())
1537 v = isl_val_one(ctx);
1538 else
1539 v = isl_val_negone(ctx);
1541 return pet_expr_new_int(v);
1544 /* Check if op is of the form
1546 * iv = expr
1548 * and return the increment "expr - iv" as a pet_expr.
1550 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1551 clang::ValueDecl *iv)
1553 int type_size;
1554 Expr *lhs;
1555 DeclRefExpr *ref;
1556 pet_expr *expr, *expr_iv;
1558 if (op->getOpcode() != BO_Assign) {
1559 unsupported(op);
1560 return NULL;
1563 lhs = op->getLHS();
1564 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1565 unsupported(op);
1566 return NULL;
1569 ref = cast<DeclRefExpr>(lhs);
1570 if (ref->getDecl() != iv) {
1571 unsupported(op);
1572 return NULL;
1575 expr = extract_expr(op->getRHS());
1576 expr_iv = extract_expr(lhs);
1578 type_size = get_type_size(iv->getType(), ast_context);
1579 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1582 /* Check that op is of the form iv += cst or iv -= cst
1583 * and return a pet_expr corresponding to cst or -cst accordingly.
1585 __isl_give pet_expr *PetScan::extract_compound_increment(
1586 CompoundAssignOperator *op, clang::ValueDecl *iv)
1588 Expr *lhs;
1589 DeclRefExpr *ref;
1590 bool neg = false;
1591 pet_expr *expr;
1592 BinaryOperatorKind opcode;
1594 opcode = op->getOpcode();
1595 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1596 unsupported(op);
1597 return NULL;
1599 if (opcode == BO_SubAssign)
1600 neg = true;
1602 lhs = op->getLHS();
1603 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1604 unsupported(op);
1605 return NULL;
1608 ref = cast<DeclRefExpr>(lhs);
1609 if (ref->getDecl() != iv) {
1610 unsupported(op);
1611 return NULL;
1614 expr = extract_expr(op->getRHS());
1615 if (neg)
1616 expr = pet_expr_new_unary(pet_op_minus, expr);
1618 return expr;
1621 /* Check that the increment of the given for loop increments
1622 * (or decrements) the induction variable "iv" and return
1623 * the increment as a pet_expr if successful.
1625 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1626 ValueDecl *iv)
1628 Stmt *inc = stmt->getInc();
1630 if (!inc) {
1631 report_missing_increment(stmt);
1632 return NULL;
1635 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1636 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1637 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1638 return extract_compound_increment(
1639 cast<CompoundAssignOperator>(inc), iv);
1640 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1641 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1643 unsupported(inc);
1644 return NULL;
1647 /* Embed the given iteration domain in an extra outer loop
1648 * with induction variable "var".
1649 * If this variable appeared as a parameter in the constraints,
1650 * it is replaced by the new outermost dimension.
1652 static __isl_give isl_set *embed(__isl_take isl_set *set,
1653 __isl_take isl_id *var)
1655 int pos;
1657 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1658 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1659 if (pos >= 0) {
1660 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1661 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1664 isl_id_free(var);
1665 return set;
1668 /* Return those elements in the space of "cond" that come after
1669 * (based on "sign") an element in "cond".
1671 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
1673 isl_map *previous_to_this;
1675 if (sign > 0)
1676 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
1677 else
1678 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
1680 cond = isl_set_apply(cond, previous_to_this);
1682 return cond;
1685 /* Create the infinite iteration domain
1687 * { [id] : id >= 0 }
1689 * If "scop" has an affine skip of type pet_skip_later,
1690 * then remove those iterations i that have an earlier iteration
1691 * where the skip condition is satisfied, meaning that iteration i
1692 * is not executed.
1693 * Since we are dealing with a loop without loop iterator,
1694 * the skip condition cannot refer to the current loop iterator and
1695 * so effectively, the returned set is of the form
1697 * { [0]; [id] : id >= 1 and not skip }
1699 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
1700 struct pet_scop *scop)
1702 isl_ctx *ctx = isl_id_get_ctx(id);
1703 isl_set *domain;
1704 isl_set *skip;
1706 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1707 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
1709 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
1710 return domain;
1712 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
1713 skip = embed(skip, isl_id_copy(id));
1714 skip = isl_set_intersect(skip , isl_set_copy(domain));
1715 domain = isl_set_subtract(domain, after(skip, 1));
1717 return domain;
1720 /* Create an identity affine expression on the space containing "domain",
1721 * which is assumed to be one-dimensional.
1723 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
1725 isl_local_space *ls;
1727 ls = isl_local_space_from_space(isl_set_get_space(domain));
1728 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
1731 /* Create an affine expression that maps elements
1732 * of a single-dimensional array "id_test" to the previous element
1733 * (according to "inc"), provided this element belongs to "domain".
1734 * That is, create the affine expression
1736 * { id[x] -> id[x - inc] : x - inc in domain }
1738 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
1739 __isl_take isl_set *domain, __isl_take isl_val *inc)
1741 isl_space *space;
1742 isl_local_space *ls;
1743 isl_aff *aff;
1744 isl_multi_pw_aff *prev;
1746 space = isl_set_get_space(domain);
1747 ls = isl_local_space_from_space(space);
1748 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
1749 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
1750 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
1751 domain = isl_set_preimage_multi_pw_aff(domain,
1752 isl_multi_pw_aff_copy(prev));
1753 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
1754 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
1756 return prev;
1759 /* Add an implication to "scop" expressing that if an element of
1760 * virtual array "id_test" has value "satisfied" then all previous elements
1761 * of this array also have that value. The set of previous elements
1762 * is bounded by "domain". If "sign" is negative then the iterator
1763 * is decreasing and we express that all subsequent array elements
1764 * (but still defined previously) have the same value.
1766 static struct pet_scop *add_implication(struct pet_scop *scop,
1767 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
1768 int satisfied)
1770 isl_space *space;
1771 isl_map *map;
1773 domain = isl_set_set_tuple_id(domain, id_test);
1774 space = isl_set_get_space(domain);
1775 if (sign > 0)
1776 map = isl_map_lex_ge(space);
1777 else
1778 map = isl_map_lex_le(space);
1779 map = isl_map_intersect_range(map, domain);
1780 scop = pet_scop_add_implication(scop, map, satisfied);
1782 return scop;
1785 /* Add a filter to "scop" that imposes that it is only executed
1786 * when the variable identified by "id_test" has a zero value
1787 * for all previous iterations of "domain".
1789 * In particular, add a filter that imposes that the array
1790 * has a zero value at the previous iteration of domain and
1791 * add an implication that implies that it then has that
1792 * value for all previous iterations.
1794 static struct pet_scop *scop_add_break(struct pet_scop *scop,
1795 __isl_take isl_id *id_test, __isl_take isl_set *domain,
1796 __isl_take isl_val *inc)
1798 isl_multi_pw_aff *prev;
1799 int sign = isl_val_sgn(inc);
1801 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
1802 scop = add_implication(scop, id_test, domain, sign, 0);
1803 scop = pet_scop_filter(scop, prev, 0);
1805 return scop;
1808 /* Construct a pet_scop for an infinite loop around the given body.
1810 * We extract a pet_scop for the body and then embed it in a loop with
1811 * iteration domain
1813 * { [t] : t >= 0 }
1815 * and schedule
1817 * { [t] -> [t] }
1819 * If the body contains any break, then it is taken into
1820 * account in infinite_domain (if the skip condition is affine)
1821 * or in scop_add_break (if the skip condition is not affine).
1823 * If we were only able to extract part of the body, then simply
1824 * return that part.
1826 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1828 isl_id *id, *id_test;
1829 isl_set *domain;
1830 isl_aff *ident;
1831 struct pet_scop *scop;
1832 bool has_var_break;
1834 scop = extract(body);
1835 if (!scop)
1836 return NULL;
1837 if (partial)
1838 return scop;
1840 id = isl_id_alloc(ctx, "t", NULL);
1841 domain = infinite_domain(isl_id_copy(id), scop);
1842 ident = identity_aff(domain);
1844 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
1845 if (has_var_break)
1846 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
1848 scop = pet_scop_embed(scop, isl_set_copy(domain),
1849 isl_aff_copy(ident), ident, id);
1850 if (has_var_break)
1851 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
1852 else
1853 isl_set_free(domain);
1855 return scop;
1858 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1860 * for (;;)
1861 * body
1864 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1866 clear_assignments clear(assigned_value);
1867 clear.TraverseStmt(stmt->getBody());
1869 return extract_infinite_loop(stmt->getBody());
1872 /* Add an array with the given extent (range of "index") to the list
1873 * of arrays in "scop" and return the extended pet_scop.
1874 * The array is marked as attaining values 0 and 1 only and
1875 * as each element being assigned at most once.
1877 static struct pet_scop *scop_add_array(struct pet_scop *scop,
1878 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
1880 int int_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
1882 return pet_scop_add_boolean_array(scop, isl_multi_pw_aff_copy(index),
1883 int_size);
1886 /* Construct a pet_scop for a while loop of the form
1888 * while (pa)
1889 * body
1891 * In particular, construct a scop for an infinite loop around body and
1892 * intersect the domain with the affine expression.
1893 * Note that this intersection may result in an empty loop.
1895 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
1896 Stmt *body)
1898 struct pet_scop *scop;
1899 isl_set *dom;
1900 isl_set *valid;
1902 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
1903 dom = isl_pw_aff_non_zero_set(pa);
1904 scop = extract_infinite_loop(body);
1905 scop = pet_scop_restrict(scop, isl_set_params(dom));
1906 scop = pet_scop_restrict_context(scop, isl_set_params(valid));
1908 return scop;
1911 /* Construct a scop for a while, given the scops for the condition
1912 * and the body, the filter identifier and the iteration domain of
1913 * the while loop.
1915 * In particular, the scop for the condition is filtered to depend
1916 * on "id_test" evaluating to true for all previous iterations
1917 * of the loop, while the scop for the body is filtered to depend
1918 * on "id_test" evaluating to true for all iterations up to the
1919 * current iteration.
1920 * The actual filter only imposes that this virtual array has
1921 * value one on the previous or the current iteration.
1922 * The fact that this condition also applies to the previous
1923 * iterations is enforced by an implication.
1925 * These filtered scops are then combined into a single scop.
1927 * "sign" is positive if the iterator increases and negative
1928 * if it decreases.
1930 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
1931 struct pet_scop *scop_body, __isl_take isl_id *id_test,
1932 __isl_take isl_set *domain, __isl_take isl_val *inc)
1934 isl_ctx *ctx = isl_set_get_ctx(domain);
1935 isl_space *space;
1936 isl_multi_pw_aff *test_index;
1937 isl_multi_pw_aff *prev;
1938 int sign = isl_val_sgn(inc);
1939 struct pet_scop *scop;
1941 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
1942 scop_cond = pet_scop_filter(scop_cond, prev, 1);
1944 space = isl_space_map_from_set(isl_set_get_space(domain));
1945 test_index = isl_multi_pw_aff_identity(space);
1946 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
1947 isl_id_copy(id_test));
1948 scop_body = pet_scop_filter(scop_body, test_index, 1);
1950 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
1951 scop = add_implication(scop, id_test, domain, sign, 1);
1953 return scop;
1956 /* Check if the while loop is of the form
1958 * while (affine expression)
1959 * body
1961 * If so, call extract_affine_while to construct a scop.
1963 * Otherwise, extract the body and pass control to extract_while
1964 * to extend the iteration domain with an infinite loop.
1965 * If we were only able to extract part of the body, then simply
1966 * return that part.
1968 struct pet_scop *PetScan::extract(WhileStmt *stmt)
1970 Expr *cond;
1971 int test_nr, stmt_nr;
1972 isl_pw_aff *pa;
1973 struct pet_scop *scop_body;
1975 cond = stmt->getCond();
1976 if (!cond) {
1977 unsupported(stmt);
1978 return NULL;
1981 clear_assignments clear(assigned_value);
1982 clear.TraverseStmt(stmt->getBody());
1984 pa = try_extract_affine_condition(cond);
1985 if (pa)
1986 return extract_affine_while(pa, stmt->getBody());
1988 if (!allow_nested) {
1989 unsupported(stmt);
1990 return NULL;
1993 test_nr = n_test++;
1994 stmt_nr = n_stmt++;
1995 scop_body = extract(stmt->getBody());
1996 if (partial)
1997 return scop_body;
1999 return extract_while(cond, test_nr, stmt_nr, scop_body, NULL);
2002 /* Construct a generic while scop, with iteration domain
2003 * { [t] : t >= 0 } around "scop_body". The scop consists of two parts,
2004 * one for evaluating the condition "cond" and one for the body.
2005 * "test_nr" is the sequence number of the virtual test variable that contains
2006 * the result of the condition and "stmt_nr" is the sequence number
2007 * of the statement that evaluates the condition.
2008 * If "scop_inc" is not NULL, then it is added at the end of the body,
2009 * after replacing any skip conditions resulting from continue statements
2010 * by the skip conditions resulting from break statements (if any).
2012 * The schedule is adjusted to reflect that the condition is evaluated
2013 * before the body is executed and the body is filtered to depend
2014 * on the result of the condition evaluating to true on all iterations
2015 * up to the current iteration, while the evaluation of the condition itself
2016 * is filtered to depend on the result of the condition evaluating to true
2017 * on all previous iterations.
2018 * The context of the scop representing the body is dropped
2019 * because we don't know how many times the body will be executed,
2020 * if at all.
2022 * If the body contains any break, then it is taken into
2023 * account in infinite_domain (if the skip condition is affine)
2024 * or in scop_add_break (if the skip condition is not affine).
2026 struct pet_scop *PetScan::extract_while(Expr *cond, int test_nr, int stmt_nr,
2027 struct pet_scop *scop_body, struct pet_scop *scop_inc)
2029 isl_id *id, *id_test, *id_break_test;
2030 isl_set *domain;
2031 isl_aff *ident;
2032 isl_multi_pw_aff *test_index;
2033 struct pet_scop *scop;
2034 bool has_var_break;
2036 test_index = pet_create_test_index(ctx, test_nr);
2037 scop = extract_non_affine_condition(cond, stmt_nr,
2038 isl_multi_pw_aff_copy(test_index));
2039 scop = scop_add_array(scop, test_index, ast_context);
2040 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2041 isl_multi_pw_aff_free(test_index);
2043 id = isl_id_alloc(ctx, "t", NULL);
2044 domain = infinite_domain(isl_id_copy(id), scop_body);
2045 ident = identity_aff(domain);
2047 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2048 if (has_var_break)
2049 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2051 scop = pet_scop_prefix(scop, 0);
2052 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_aff_copy(ident),
2053 isl_aff_copy(ident), isl_id_copy(id));
2054 scop_body = pet_scop_reset_context(scop_body);
2055 scop_body = pet_scop_prefix(scop_body, 1);
2056 if (scop_inc) {
2057 scop_inc = pet_scop_prefix(scop_inc, 2);
2058 if (pet_scop_has_skip(scop_body, pet_skip_later)) {
2059 isl_multi_pw_aff *skip;
2060 skip = pet_scop_get_skip(scop_body, pet_skip_later);
2061 scop_body = pet_scop_set_skip(scop_body,
2062 pet_skip_now, skip);
2063 } else
2064 pet_scop_reset_skip(scop_body, pet_skip_now);
2065 scop_body = pet_scop_add_seq(ctx, scop_body, scop_inc);
2067 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2068 isl_aff_copy(ident), ident, id);
2070 if (has_var_break) {
2071 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2072 isl_set_copy(domain), isl_val_one(ctx));
2073 scop_body = scop_add_break(scop_body, id_break_test,
2074 isl_set_copy(domain), isl_val_one(ctx));
2076 scop = scop_add_while(scop, scop_body, id_test, domain,
2077 isl_val_one(ctx));
2079 return scop;
2082 /* Check whether "cond" expresses a simple loop bound
2083 * on the only set dimension.
2084 * In particular, if "up" is set then "cond" should contain only
2085 * upper bounds on the set dimension.
2086 * Otherwise, it should contain only lower bounds.
2088 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2090 if (isl_val_is_pos(inc))
2091 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2092 else
2093 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2096 /* Extend a condition on a given iteration of a loop to one that
2097 * imposes the same condition on all previous iterations.
2098 * "domain" expresses the lower [upper] bound on the iterations
2099 * when inc is positive [negative].
2101 * In particular, we construct the condition (when inc is positive)
2103 * forall i' : (domain(i') and i' <= i) => cond(i')
2105 * which is equivalent to
2107 * not exists i' : domain(i') and i' <= i and not cond(i')
2109 * We construct this set by negating cond, applying a map
2111 * { [i'] -> [i] : domain(i') and i' <= i }
2113 * and then negating the result again.
2115 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2116 __isl_take isl_set *domain, __isl_take isl_val *inc)
2118 isl_map *previous_to_this;
2120 if (isl_val_is_pos(inc))
2121 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2122 else
2123 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2125 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2127 cond = isl_set_complement(cond);
2128 cond = isl_set_apply(cond, previous_to_this);
2129 cond = isl_set_complement(cond);
2131 isl_val_free(inc);
2133 return cond;
2136 /* Construct a domain of the form
2138 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2140 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2141 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2143 isl_aff *aff;
2144 isl_space *dim;
2145 isl_set *set;
2147 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2148 dim = isl_pw_aff_get_domain_space(init);
2149 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2150 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2151 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2153 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2154 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2155 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2156 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2158 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2160 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2162 return isl_set_params(set);
2165 /* Assuming "cond" represents a bound on a loop where the loop
2166 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2167 * is possible.
2169 * Under the given assumptions, wrapping is only possible if "cond" allows
2170 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2171 * increasing iterator and 0 in case of a decreasing iterator.
2173 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2174 __isl_keep isl_val *inc)
2176 bool cw;
2177 isl_ctx *ctx;
2178 isl_val *limit;
2179 isl_set *test;
2181 test = isl_set_copy(cond);
2183 ctx = isl_set_get_ctx(test);
2184 if (isl_val_is_neg(inc))
2185 limit = isl_val_zero(ctx);
2186 else {
2187 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2188 limit = isl_val_2exp(limit);
2189 limit = isl_val_sub_ui(limit, 1);
2192 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2193 cw = !isl_set_is_empty(test);
2194 isl_set_free(test);
2196 return cw;
2199 /* Given a one-dimensional space, construct the following affine expression
2200 * on this space
2202 * { [v] -> [v mod 2^width] }
2204 * where width is the number of bits used to represent the values
2205 * of the unsigned variable "iv".
2207 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2208 ValueDecl *iv)
2210 isl_ctx *ctx;
2211 isl_val *mod;
2212 isl_aff *aff;
2214 ctx = isl_space_get_ctx(dim);
2215 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2216 mod = isl_val_2exp(mod);
2218 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2219 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2220 aff = isl_aff_mod_val(aff, mod);
2222 return aff;
2225 /* Project out the parameter "id" from "set".
2227 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2228 __isl_keep isl_id *id)
2230 int pos;
2232 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2233 if (pos >= 0)
2234 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2236 return set;
2239 /* Compute the set of parameters for which "set1" is a subset of "set2".
2241 * set1 is a subset of set2 if
2243 * forall i in set1 : i in set2
2245 * or
2247 * not exists i in set1 and i not in set2
2249 * i.e.,
2251 * not exists i in set1 \ set2
2253 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2254 __isl_take isl_set *set2)
2256 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2259 /* Compute the set of parameter values for which "cond" holds
2260 * on the next iteration for each element of "dom".
2262 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2263 * and then compute the set of parameters for which the result is a subset
2264 * of "cond".
2266 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2267 __isl_take isl_set *dom, __isl_take isl_val *inc)
2269 isl_space *space;
2270 isl_aff *aff;
2271 isl_map *next;
2273 space = isl_set_get_space(dom);
2274 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2275 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2276 aff = isl_aff_add_constant_val(aff, inc);
2277 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2279 dom = isl_set_apply(dom, next);
2281 return enforce_subset(dom, cond);
2284 /* Extract the for loop "stmt" as a while loop.
2285 * "iv" is the loop iterator. "init" is the initialization.
2286 * "inc" is the increment.
2288 * That is, the for loop has the form
2290 * for (iv = init; cond; iv += inc)
2291 * body;
2293 * and is treated as
2295 * iv = init;
2296 * while (cond) {
2297 * body;
2298 * iv += inc;
2301 * except that the skips resulting from any continue statements
2302 * in body do not apply to the increment, but are replaced by the skips
2303 * resulting from break statements.
2305 * If "iv" is declared in the for loop, then it is killed before
2306 * and after the loop.
2308 struct pet_scop *PetScan::extract_non_affine_for(ForStmt *stmt, ValueDecl *iv,
2309 __isl_take pet_expr *init, __isl_take pet_expr *inc)
2311 int declared;
2312 int test_nr, stmt_nr;
2313 pet_expr *expr_iv;
2314 struct pet_scop *scop_init, *scop_inc, *scop, *scop_body;
2315 int type_size;
2316 struct pet_array *array;
2317 struct pet_scop *scop_kill;
2319 if (!allow_nested) {
2320 unsupported(stmt);
2321 return NULL;
2324 clear_assignment(assigned_value, iv);
2326 declared = !initialization_assignment(stmt->getInit());
2328 expr_iv = extract_access_expr(iv);
2329 expr_iv = mark_write(expr_iv);
2330 type_size = pet_expr_get_type_size(expr_iv);
2331 init = pet_expr_new_binary(type_size, pet_op_assign, expr_iv, init);
2332 scop_init = extract(init, stmt->getInit()->getSourceRange(), false);
2333 scop_init = pet_scop_prefix(scop_init, declared);
2335 test_nr = n_test++;
2336 stmt_nr = n_stmt++;
2337 scop_body = extract(stmt->getBody());
2338 if (partial) {
2339 pet_scop_free(scop_init);
2340 return scop_body;
2343 expr_iv = extract_access_expr(iv);
2344 expr_iv = mark_write(expr_iv);
2345 type_size = pet_expr_get_type_size(expr_iv);
2346 inc = pet_expr_new_binary(type_size, pet_op_add_assign, expr_iv, inc);
2347 scop_inc = extract(inc, stmt->getInc()->getSourceRange(), false);
2348 if (!scop_inc) {
2349 pet_scop_free(scop_init);
2350 pet_scop_free(scop_body);
2351 return NULL;
2354 scop = extract_while(stmt->getCond(), test_nr, stmt_nr, scop_body,
2355 scop_inc);
2357 scop = pet_scop_prefix(scop, declared + 1);
2358 scop = pet_scop_add_seq(ctx, scop_init, scop);
2360 if (!declared)
2361 return scop;
2363 array = extract_array(ctx, iv, NULL);
2364 if (array)
2365 array->declared = 1;
2366 scop_kill = kill(stmt, array);
2367 scop_kill = pet_scop_prefix(scop_kill, 0);
2368 scop = pet_scop_add_seq(ctx, scop_kill, scop);
2369 scop_kill = kill(stmt, array);
2370 scop_kill = pet_scop_add_array(scop_kill, array);
2371 scop_kill = pet_scop_prefix(scop_kill, 3);
2372 scop = pet_scop_add_seq(ctx, scop, scop_kill);
2374 return scop;
2377 /* Construct a pet_scop for a for statement.
2378 * The for loop is required to be of one of the following forms
2380 * for (i = init; condition; ++i)
2381 * for (i = init; condition; --i)
2382 * for (i = init; condition; i += constant)
2383 * for (i = init; condition; i -= constant)
2385 * The initialization of the for loop should either be an assignment
2386 * of a static affine value to an integer variable, or a declaration
2387 * of such a variable with initialization.
2389 * If the initialization or the increment do not satisfy the above
2390 * conditions, i.e., if the initialization is not static affine
2391 * or the increment is not constant, then the for loop is extracted
2392 * as a while loop instead.
2394 * The condition is allowed to contain nested accesses, provided
2395 * they are not being written to inside the body of the loop.
2396 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2397 * essentially treated as a while loop, with iteration domain
2398 * { [i] : i >= init }.
2400 * We extract a pet_scop for the body and then embed it in a loop with
2401 * iteration domain and schedule
2403 * { [i] : i >= init and condition' }
2404 * { [i] -> [i] }
2406 * or
2408 * { [i] : i <= init and condition' }
2409 * { [i] -> [-i] }
2411 * Where condition' is equal to condition if the latter is
2412 * a simple upper [lower] bound and a condition that is extended
2413 * to apply to all previous iterations otherwise.
2415 * If the condition is non-affine, then we drop the condition from the
2416 * iteration domain and instead create a separate statement
2417 * for evaluating the condition. The body is then filtered to depend
2418 * on the result of the condition evaluating to true on all iterations
2419 * up to the current iteration, while the evaluation the condition itself
2420 * is filtered to depend on the result of the condition evaluating to true
2421 * on all previous iterations.
2422 * The context of the scop representing the body is dropped
2423 * because we don't know how many times the body will be executed,
2424 * if at all.
2426 * If the stride of the loop is not 1, then "i >= init" is replaced by
2428 * (exists a: i = init + stride * a and a >= 0)
2430 * If the loop iterator i is unsigned, then wrapping may occur.
2431 * We therefore use a virtual iterator instead that does not wrap.
2432 * However, the condition in the code applies
2433 * to the wrapped value, so we need to change condition(i)
2434 * into condition([i % 2^width]). Similarly, we replace all accesses
2435 * to the original iterator by the wrapping of the virtual iterator.
2436 * Note that there may be no need to perform this final wrapping
2437 * if the loop condition (after wrapping) satisfies certain conditions.
2438 * However, the is_simple_bound condition is not enough since it doesn't
2439 * check if there even is an upper bound.
2441 * Wrapping on unsigned iterators can be avoided entirely if
2442 * loop condition is simple, the loop iterator is incremented
2443 * [decremented] by one and the last value before wrapping cannot
2444 * possibly satisfy the loop condition.
2446 * Before extracting a pet_scop from the body we remove all
2447 * assignments in assigned_value to variables that are assigned
2448 * somewhere in the body of the loop.
2450 * Valid parameters for a for loop are those for which the initial
2451 * value itself, the increment on each domain iteration and
2452 * the condition on both the initial value and
2453 * the result of incrementing the iterator for each iteration of the domain
2454 * can be evaluated.
2455 * If the loop condition is non-affine, then we only consider validity
2456 * of the initial value.
2458 * If the body contains any break, then we keep track of it in "skip"
2459 * (if the skip condition is affine) or it is handled in scop_add_break
2460 * (if the skip condition is not affine).
2461 * Note that the affine break condition needs to be considered with
2462 * respect to previous iterations in the virtual domain (if any).
2464 * If we were only able to extract part of the body, then simply
2465 * return that part.
2467 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2469 BinaryOperator *ass;
2470 Decl *decl;
2471 Stmt *init;
2472 Expr *lhs, *rhs;
2473 ValueDecl *iv;
2474 isl_local_space *ls;
2475 isl_set *domain;
2476 isl_aff *sched;
2477 isl_set *cond = NULL;
2478 isl_set *skip = NULL;
2479 isl_id *id, *id_test = NULL, *id_break_test;
2480 struct pet_scop *scop, *scop_cond = NULL;
2481 assigned_value_cache cache(assigned_value);
2482 isl_val *inc;
2483 bool is_one;
2484 bool is_unsigned;
2485 bool is_simple;
2486 bool is_virtual;
2487 bool has_affine_break;
2488 bool has_var_break;
2489 isl_aff *wrap = NULL;
2490 isl_pw_aff *pa, *pa_inc, *init_val;
2491 isl_set *valid_init;
2492 isl_set *valid_cond;
2493 isl_set *valid_cond_init;
2494 isl_set *valid_cond_next;
2495 isl_set *valid_inc;
2496 int stmt_id;
2497 pet_expr *pe_init, *pe_inc;
2498 pet_context *pc, *pc_init_val;
2500 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2501 return extract_infinite_for(stmt);
2503 init = stmt->getInit();
2504 if (!init) {
2505 unsupported(stmt);
2506 return NULL;
2508 if ((ass = initialization_assignment(init)) != NULL) {
2509 iv = extract_induction_variable(ass);
2510 if (!iv)
2511 return NULL;
2512 lhs = ass->getLHS();
2513 rhs = ass->getRHS();
2514 } else if ((decl = initialization_declaration(init)) != NULL) {
2515 VarDecl *var = extract_induction_variable(init, decl);
2516 if (!var)
2517 return NULL;
2518 iv = var;
2519 rhs = var->getInit();
2520 lhs = create_DeclRefExpr(var);
2521 } else {
2522 unsupported(stmt->getInit());
2523 return NULL;
2526 id = create_decl_id(ctx, iv);
2528 assigned_value.erase(iv);
2529 clear_assignments clear(assigned_value);
2530 clear.TraverseStmt(stmt->getBody());
2532 pe_init = extract_expr(rhs);
2533 pe_inc = extract_increment(stmt, iv);
2534 pc = convert_assignments(ctx, assigned_value);
2535 pc_init_val = pet_context_copy(pc);
2536 pc_init_val = pet_context_mark_unknown(pc_init_val, isl_id_copy(id));
2537 init_val = pet_expr_extract_affine(pe_init, pc_init_val);
2538 pet_context_free(pc_init_val);
2539 pa_inc = pet_expr_extract_affine(pe_inc, pc);
2540 pet_context_free(pc);
2541 inc = pet_extract_cst(pa_inc);
2542 if (!pe_init || !pe_inc || !inc || isl_val_is_nan(inc) ||
2543 isl_pw_aff_involves_nan(pa_inc) ||
2544 isl_pw_aff_involves_nan(init_val)) {
2545 isl_id_free(id);
2546 isl_val_free(inc);
2547 isl_pw_aff_free(pa_inc);
2548 isl_pw_aff_free(init_val);
2549 if (pe_init && pe_inc && !(pa_inc && !inc))
2550 return extract_non_affine_for(stmt, iv,
2551 pe_init, pe_inc);
2552 pet_expr_free(pe_init);
2553 pet_expr_free(pe_inc);
2554 return NULL;
2556 pet_expr_free(pe_init);
2557 pet_expr_free(pe_inc);
2559 pa = try_extract_nested_condition(stmt->getCond());
2560 if (allow_nested && (!pa || pet_nested_any_in_pw_aff(pa)))
2561 stmt_id = n_stmt++;
2563 scop = extract(stmt->getBody());
2564 if (partial) {
2565 isl_id_free(id);
2566 isl_pw_aff_free(init_val);
2567 isl_pw_aff_free(pa_inc);
2568 isl_pw_aff_free(pa);
2569 isl_val_free(inc);
2570 return scop;
2573 valid_inc = isl_pw_aff_domain(pa_inc);
2575 is_unsigned = iv->getType()->isUnsignedIntegerType();
2577 has_affine_break = scop &&
2578 pet_scop_has_affine_skip(scop, pet_skip_later);
2579 if (has_affine_break)
2580 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2581 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
2582 if (has_var_break)
2583 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
2585 if (pa && !is_nested_allowed(pa, scop)) {
2586 isl_pw_aff_free(pa);
2587 pa = NULL;
2590 if (!allow_nested && !pa)
2591 pa = try_extract_affine_condition(stmt->getCond());
2592 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2593 cond = isl_pw_aff_non_zero_set(pa);
2594 if (allow_nested && !cond) {
2595 isl_multi_pw_aff *test_index;
2596 int save_n_stmt = n_stmt;
2597 test_index = pet_create_test_index(ctx, n_test++);
2598 n_stmt = stmt_id;
2599 scop_cond = extract_non_affine_condition(stmt->getCond(),
2600 n_stmt++, isl_multi_pw_aff_copy(test_index));
2601 n_stmt = save_n_stmt;
2602 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
2603 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
2604 isl_dim_out);
2605 isl_multi_pw_aff_free(test_index);
2606 scop_cond = pet_scop_prefix(scop_cond, 0);
2607 scop = pet_scop_reset_context(scop);
2608 scop = pet_scop_prefix(scop, 1);
2609 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2612 cond = embed(cond, isl_id_copy(id));
2613 skip = embed(skip, isl_id_copy(id));
2614 valid_cond = isl_set_coalesce(valid_cond);
2615 valid_cond = embed(valid_cond, isl_id_copy(id));
2616 valid_inc = embed(valid_inc, isl_id_copy(id));
2617 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
2618 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2620 valid_cond_init = enforce_subset(
2621 isl_map_range(isl_map_from_pw_aff(isl_pw_aff_copy(init_val))),
2622 isl_set_copy(valid_cond));
2623 if (is_one && !is_virtual) {
2624 isl_pw_aff_free(init_val);
2625 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
2626 lhs, rhs, init);
2627 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2628 valid_init = set_project_out_by_id(valid_init, id);
2629 domain = isl_pw_aff_non_zero_set(pa);
2630 } else {
2631 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2632 domain = strided_domain(isl_id_copy(id), init_val,
2633 isl_val_copy(inc));
2636 domain = embed(domain, isl_id_copy(id));
2637 if (is_virtual) {
2638 isl_map *rev_wrap;
2639 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2640 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
2641 rev_wrap = isl_map_reverse(rev_wrap);
2642 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2643 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
2644 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2645 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2647 is_simple = is_simple_bound(cond, inc);
2648 if (!is_simple) {
2649 cond = isl_set_gist(cond, isl_set_copy(domain));
2650 is_simple = is_simple_bound(cond, inc);
2652 if (!is_simple)
2653 cond = valid_for_each_iteration(cond,
2654 isl_set_copy(domain), isl_val_copy(inc));
2655 domain = isl_set_intersect(domain, cond);
2656 if (has_affine_break) {
2657 skip = isl_set_intersect(skip , isl_set_copy(domain));
2658 skip = after(skip, isl_val_sgn(inc));
2659 domain = isl_set_subtract(domain, skip);
2661 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2662 ls = isl_local_space_from_space(isl_set_get_space(domain));
2663 sched = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2664 if (isl_val_is_neg(inc))
2665 sched = isl_aff_neg(sched);
2667 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
2668 isl_val_copy(inc));
2669 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2671 if (!is_virtual)
2672 wrap = identity_aff(domain);
2674 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
2675 isl_aff_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
2676 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
2677 scop = resolve_nested(scop);
2678 if (has_var_break)
2679 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
2680 isl_val_copy(inc));
2681 if (id_test) {
2682 scop = scop_add_while(scop_cond, scop, id_test, domain,
2683 isl_val_copy(inc));
2684 isl_set_free(valid_inc);
2685 } else {
2686 scop = pet_scop_restrict_context(scop, valid_inc);
2687 scop = pet_scop_restrict_context(scop, valid_cond_next);
2688 scop = pet_scop_restrict_context(scop, valid_cond_init);
2689 isl_set_free(domain);
2691 clear_assignment(assigned_value, iv);
2693 isl_val_free(inc);
2695 scop = pet_scop_restrict_context(scop, isl_set_params(valid_init));
2697 return scop;
2700 /* Try and construct a pet_scop corresponding to a compound statement.
2702 * "skip_declarations" is set if we should skip initial declarations
2703 * in the children of the compound statements. This then implies
2704 * that this sequence of children should not be treated as a block
2705 * since the initial statements may be skipped.
2707 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
2709 return extract(stmt->children(), !skip_declarations, skip_declarations);
2712 /* For each nested access parameter in "space",
2713 * construct a corresponding pet_expr, place it in args and
2714 * record its position in "param2pos".
2715 * "n_arg" is the number of elements that are already in args.
2716 * The position recorded in "param2pos" takes this number into account.
2717 * If the pet_expr corresponding to a parameter is identical to
2718 * the pet_expr corresponding to an earlier parameter, then these two
2719 * parameters are made to refer to the same element in args.
2721 * Return the final number of elements in args or -1 if an error has occurred.
2723 int PetScan::extract_nested(__isl_keep isl_space *space,
2724 int n_arg, pet_expr **args, std::map<int,int> &param2pos)
2726 int nparam;
2728 nparam = isl_space_dim(space, isl_dim_param);
2729 for (int i = 0; i < nparam; ++i) {
2730 int j;
2731 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2733 if (!pet_nested_in_id(id)) {
2734 isl_id_free(id);
2735 continue;
2738 args[n_arg] = pet_nested_extract_expr(id);
2739 isl_id_free(id);
2740 if (!args[n_arg])
2741 return -1;
2743 for (j = 0; j < n_arg; ++j)
2744 if (pet_expr_is_equal(args[j], args[n_arg]))
2745 break;
2747 if (j < n_arg) {
2748 pet_expr_free(args[n_arg]);
2749 args[n_arg] = NULL;
2750 param2pos[i] = j;
2751 } else
2752 param2pos[i] = n_arg++;
2755 return n_arg;
2758 /* For each nested access parameter in the access relations in "expr",
2759 * construct a corresponding pet_expr, append it to the arguments of "expr"
2760 * and record its position in "param2pos" (relative to the initial
2761 * number of arguments).
2762 * n is the number of nested access parameters.
2764 __isl_give pet_expr *PetScan::extract_nested(__isl_take pet_expr *expr, int n,
2765 std::map<int,int> &param2pos)
2767 isl_space *space;
2768 int i, n_arg;
2769 pet_expr **args;
2771 args = isl_calloc_array(ctx, pet_expr *, n);
2772 if (!args)
2773 return pet_expr_free(expr);
2775 n_arg = pet_expr_get_n_arg(expr);
2776 space = pet_expr_access_get_parameter_space(expr);
2777 n = extract_nested(space, 0, args, param2pos);
2778 isl_space_free(space);
2780 if (n < 0)
2781 expr = pet_expr_free(expr);
2782 else
2783 expr = pet_expr_set_n_arg(expr, n_arg + n);
2785 for (i = 0; i < n; ++i)
2786 expr = pet_expr_set_arg(expr, n_arg + i, args[i]);
2787 free(args);
2789 return expr;
2792 /* Are "expr1" and "expr2" both array accesses such that
2793 * the access relation of "expr1" is a subset of that of "expr2"?
2794 * Only take into account the first "n_arg" arguments.
2796 static int is_sub_access(__isl_keep pet_expr *expr1, __isl_keep pet_expr *expr2,
2797 int n_arg)
2799 isl_id *id1, *id2;
2800 isl_map *access1, *access2;
2801 int is_subset;
2802 int i, n1, n2;
2804 if (!expr1 || !expr2)
2805 return 0;
2806 if (pet_expr_get_type(expr1) != pet_expr_access)
2807 return 0;
2808 if (pet_expr_get_type(expr2) != pet_expr_access)
2809 return 0;
2810 if (pet_expr_is_affine(expr1))
2811 return 0;
2812 if (pet_expr_is_affine(expr2))
2813 return 0;
2814 n1 = pet_expr_get_n_arg(expr1);
2815 if (n1 > n_arg)
2816 n1 = n_arg;
2817 n2 = pet_expr_get_n_arg(expr2);
2818 if (n2 > n_arg)
2819 n2 = n_arg;
2820 if (n1 != n2)
2821 return 0;
2822 for (i = 0; i < n1; ++i) {
2823 pet_expr *arg1, *arg2;
2824 int equal;
2825 arg1 = pet_expr_get_arg(expr1, i);
2826 arg2 = pet_expr_get_arg(expr2, i);
2827 equal = pet_expr_is_equal(arg1, arg2);
2828 pet_expr_free(arg1);
2829 pet_expr_free(arg2);
2830 if (equal < 0 || !equal)
2831 return equal;
2833 id1 = pet_expr_access_get_id(expr1);
2834 id2 = pet_expr_access_get_id(expr2);
2835 isl_id_free(id1);
2836 isl_id_free(id2);
2837 if (!id1 || !id2)
2838 return 0;
2839 if (id1 != id2)
2840 return 0;
2842 access1 = pet_expr_access_get_access(expr1);
2843 access2 = pet_expr_access_get_access(expr2);
2844 is_subset = isl_map_is_subset(access1, access2);
2845 isl_map_free(access1);
2846 isl_map_free(access2);
2848 return is_subset;
2851 /* Mark self dependences among the arguments of "expr" starting at "first".
2852 * These arguments have already been added to the list of arguments
2853 * but are not yet referenced directly from the index expression.
2854 * Instead, they are still referenced through parameters encoding
2855 * nested accesses.
2857 * In particular, if "expr" is a read access, then check the arguments
2858 * starting at "first" to see if "expr" accesses a subset of
2859 * the elements accessed by the argument, or under more restrictive conditions.
2860 * If so, then this nested access can be removed from the constraints
2861 * governing the outer access. There is no point in restricting
2862 * accesses to an array if in order to evaluate the restriction,
2863 * we have to access the same elements (or more).
2865 * Rather than removing the argument at this point (which would
2866 * complicate the resolution of the other nested accesses), we simply
2867 * mark it here by replacing it by a NaN pet_expr.
2868 * These NaNs are then later removed in remove_marked_self_dependences.
2870 static __isl_give pet_expr *mark_self_dependences(__isl_take pet_expr *expr,
2871 int first)
2873 int n;
2875 if (pet_expr_access_is_write(expr))
2876 return expr;
2878 n = pet_expr_get_n_arg(expr);
2879 for (int i = first; i < n; ++i) {
2880 int mark;
2881 pet_expr *arg;
2883 arg = pet_expr_get_arg(expr, i);
2884 mark = is_sub_access(expr, arg, first);
2885 pet_expr_free(arg);
2886 if (mark < 0)
2887 return pet_expr_free(expr);
2888 if (!mark)
2889 continue;
2891 arg = pet_expr_new_int(isl_val_nan(pet_expr_get_ctx(expr)));
2892 expr = pet_expr_set_arg(expr, i, arg);
2895 return expr;
2898 /* Is "expr" a NaN integer expression?
2900 static int expr_is_nan(__isl_keep pet_expr *expr)
2902 isl_val *v;
2903 int is_nan;
2905 if (pet_expr_get_type(expr) != pet_expr_int)
2906 return 0;
2908 v = pet_expr_int_get_val(expr);
2909 is_nan = isl_val_is_nan(v);
2910 isl_val_free(v);
2912 return is_nan;
2915 /* Check if we have marked any self dependences (as NaNs)
2916 * in mark_self_dependences and remove them here.
2917 * It is safe to project them out since these arguments
2918 * can at most be referenced from the condition of the access relation,
2919 * but do not appear in the index expression.
2920 * "dim" is the dimension of the iteration domain.
2922 static __isl_give pet_expr *remove_marked_self_dependences(
2923 __isl_take pet_expr *expr, int dim, int first)
2925 int n;
2927 n = pet_expr_get_n_arg(expr);
2928 for (int i = n - 1; i >= first; --i) {
2929 int is_nan;
2930 pet_expr *arg;
2932 arg = pet_expr_get_arg(expr, i);
2933 is_nan = expr_is_nan(arg);
2934 pet_expr_free(arg);
2935 if (!is_nan)
2936 continue;
2937 expr = pet_expr_access_project_out_arg(expr, dim, i);
2940 return expr;
2943 /* Look for parameters in any access relation in "expr" that
2944 * refer to nested accesses. In particular, these are
2945 * parameters with name "__pet_expr".
2947 * If there are any such parameters, then the domain of the index
2948 * expression and the access relation, which is either [] or
2949 * [[] -> [a_1,...,a_m]] at this point, is replaced by [[] -> [t_1,...,t_n]] or
2950 * [[] -> [a_1,...,a_m,t_1,...,t_n]], with m the original number of arguments
2951 * (n_arg) and n the number of these parameters
2952 * (after identifying identical nested accesses).
2954 * This transformation is performed in several steps.
2955 * We first extract the arguments in extract_nested.
2956 * param2pos maps the original parameter position to the position
2957 * of the argument beyond the initial (n_arg) number of arguments.
2958 * Then we move these parameters to input dimensions.
2959 * t2pos maps the positions of these temporary input dimensions
2960 * to the positions of the corresponding arguments.
2961 * Finally, we express these temporary dimensions in terms of the domain
2962 * [[] -> [a_1,...,a_m,t_1,...,t_n]] and precompose index expression and access
2963 * relations with this function.
2965 __isl_give pet_expr *PetScan::resolve_nested(__isl_take pet_expr *expr)
2967 int n, n_arg;
2968 int nparam;
2969 isl_space *space;
2970 isl_local_space *ls;
2971 isl_aff *aff;
2972 isl_multi_aff *ma;
2973 std::map<int,int> param2pos;
2974 std::map<int,int> t2pos;
2976 if (!expr)
2977 return expr;
2979 n_arg = pet_expr_get_n_arg(expr);
2980 for (int i = 0; i < n_arg; ++i) {
2981 pet_expr *arg;
2982 arg = pet_expr_get_arg(expr, i);
2983 arg = resolve_nested(arg);
2984 expr = pet_expr_set_arg(expr, i, arg);
2987 if (pet_expr_get_type(expr) != pet_expr_access)
2988 return expr;
2990 space = pet_expr_access_get_parameter_space(expr);
2991 n = pet_nested_n_in_space(space);
2992 isl_space_free(space);
2993 if (n == 0)
2994 return expr;
2996 expr = extract_nested(expr, n, param2pos);
2997 if (!expr)
2998 return NULL;
3000 expr = pet_expr_access_align_params(expr);
3001 expr = mark_self_dependences(expr, n_arg);
3002 if (!expr)
3003 return NULL;
3005 n = 0;
3006 space = pet_expr_access_get_parameter_space(expr);
3007 nparam = isl_space_dim(space, isl_dim_param);
3008 for (int i = nparam - 1; i >= 0; --i) {
3009 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3010 if (!pet_nested_in_id(id)) {
3011 isl_id_free(id);
3012 continue;
3015 expr = pet_expr_access_move_dims(expr,
3016 isl_dim_in, n_arg + n, isl_dim_param, i, 1);
3017 t2pos[n] = n_arg + param2pos[i];
3018 n++;
3020 isl_id_free(id);
3022 isl_space_free(space);
3024 space = pet_expr_access_get_parameter_space(expr);
3025 space = isl_space_set_from_params(space);
3026 space = isl_space_add_dims(space, isl_dim_set,
3027 pet_expr_get_n_arg(expr));
3028 space = isl_space_wrap(isl_space_from_range(space));
3029 ls = isl_local_space_from_space(isl_space_copy(space));
3030 space = isl_space_from_domain(space);
3031 space = isl_space_add_dims(space, isl_dim_out, n_arg + n);
3032 ma = isl_multi_aff_zero(space);
3034 for (int i = 0; i < n_arg; ++i) {
3035 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3036 isl_dim_set, i);
3037 ma = isl_multi_aff_set_aff(ma, i, aff);
3039 for (int i = 0; i < n; ++i) {
3040 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3041 isl_dim_set, t2pos[i]);
3042 ma = isl_multi_aff_set_aff(ma, n_arg + i, aff);
3044 isl_local_space_free(ls);
3046 expr = pet_expr_access_pullback_multi_aff(expr, ma);
3048 expr = remove_marked_self_dependences(expr, 0, n_arg);
3050 return expr;
3053 /* Return the file offset of the expansion location of "Loc".
3055 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3057 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3060 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3062 /* Return a SourceLocation for the location after the first semicolon
3063 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3064 * call it and also skip trailing spaces and newline.
3066 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3067 const LangOptions &LO)
3069 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3072 #else
3074 /* Return a SourceLocation for the location after the first semicolon
3075 * after "loc". If Lexer::findLocationAfterToken is not available,
3076 * we look in the underlying character data for the first semicolon.
3078 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3079 const LangOptions &LO)
3081 const char *semi;
3082 const char *s = SM.getCharacterData(loc);
3084 semi = strchr(s, ';');
3085 if (!semi)
3086 return SourceLocation();
3087 return loc.getFileLocWithOffset(semi + 1 - s);
3090 #endif
3092 /* If the token at "loc" is the first token on the line, then return
3093 * a location referring to the start of the line.
3094 * Otherwise, return "loc".
3096 * This function is used to extend a scop to the start of the line
3097 * if the first token of the scop is also the first token on the line.
3099 * We look for the first token on the line. If its location is equal to "loc",
3100 * then the latter is the location of the first token on the line.
3102 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3103 SourceManager &SM, const LangOptions &LO)
3105 std::pair<FileID, unsigned> file_offset_pair;
3106 llvm::StringRef file;
3107 const char *pos;
3108 Token tok;
3109 SourceLocation token_loc, line_loc;
3110 int col;
3112 loc = SM.getExpansionLoc(loc);
3113 col = SM.getExpansionColumnNumber(loc);
3114 line_loc = loc.getLocWithOffset(1 - col);
3115 file_offset_pair = SM.getDecomposedLoc(line_loc);
3116 file = SM.getBufferData(file_offset_pair.first, NULL);
3117 pos = file.data() + file_offset_pair.second;
3119 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3120 file.begin(), pos, file.end());
3121 lexer.LexFromRawLexer(tok);
3122 token_loc = tok.getLocation();
3124 if (token_loc == loc)
3125 return line_loc;
3126 else
3127 return loc;
3130 /* Update start and end of "scop" to include the region covered by "range".
3131 * If "skip_semi" is set, then we assume "range" is followed by
3132 * a semicolon and also include this semicolon.
3134 struct pet_scop *PetScan::update_scop_start_end(struct pet_scop *scop,
3135 SourceRange range, bool skip_semi)
3137 SourceLocation loc = range.getBegin();
3138 SourceManager &SM = PP.getSourceManager();
3139 const LangOptions &LO = PP.getLangOpts();
3140 unsigned start, end;
3142 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3143 start = getExpansionOffset(SM, loc);
3144 loc = range.getEnd();
3145 if (skip_semi)
3146 loc = location_after_semi(loc, SM, LO);
3147 else
3148 loc = PP.getLocForEndOfToken(loc);
3149 end = getExpansionOffset(SM, loc);
3151 scop = pet_scop_update_start_end(scop, start, end);
3152 return scop;
3155 /* Convert a top-level pet_expr to a pet_scop with one statement.
3156 * This mainly involves resolving nested expression parameters
3157 * and setting the name of the iteration space.
3158 * The name is given by "label" if it is non-NULL. Otherwise,
3159 * it is of the form S_<n_stmt>.
3160 * start and end of the pet_scop are derived from "range" and "skip_semi".
3161 * In particular, if "skip_semi" is set then the semicolon following "range"
3162 * is also included.
3164 struct pet_scop *PetScan::extract(__isl_take pet_expr *expr, SourceRange range,
3165 bool skip_semi, __isl_take isl_id *label)
3167 struct pet_stmt *ps;
3168 struct pet_scop *scop;
3169 SourceLocation loc = range.getBegin();
3170 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3171 pet_context *pc;
3173 pc = convert_assignments(ctx, assigned_value);
3174 expr = pet_expr_plug_in_args(expr, pc);
3175 pet_context_free(pc);
3177 expr = resolve_nested(expr);
3178 ps = pet_stmt_from_pet_expr(line, label, n_stmt++, expr);
3179 scop = pet_scop_from_pet_stmt(ctx, ps);
3181 scop = update_scop_start_end(scop, range, skip_semi);
3182 return scop;
3185 /* Check if we can extract an affine constraint from "expr".
3186 * Return the constraint as an isl_set if we can and NULL otherwise.
3187 * We turn on autodetection so that we won't generate any warnings
3188 * and turn off nesting, so that we won't accept any non-affine constructs.
3190 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3192 isl_pw_aff *cond;
3193 int save_autodetect = options->autodetect;
3194 bool save_nesting = nesting_enabled;
3196 options->autodetect = 1;
3197 nesting_enabled = false;
3199 cond = extract_condition(expr);
3201 options->autodetect = save_autodetect;
3202 nesting_enabled = save_nesting;
3204 return cond;
3207 /* Check whether "expr" is an affine constraint.
3209 bool PetScan::is_affine_condition(Expr *expr)
3211 isl_pw_aff *cond;
3213 cond = try_extract_affine_condition(expr);
3214 isl_pw_aff_free(cond);
3216 return cond != NULL;
3219 /* Check if we can extract a condition from "expr".
3220 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3221 * If allow_nested is set, then the condition may involve parameters
3222 * corresponding to nested accesses.
3223 * We turn on autodetection so that we won't generate any warnings.
3225 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3227 isl_pw_aff *cond;
3228 int save_autodetect = options->autodetect;
3229 bool save_nesting = nesting_enabled;
3231 options->autodetect = 1;
3232 nesting_enabled = allow_nested;
3233 cond = extract_condition(expr);
3235 options->autodetect = save_autodetect;
3236 nesting_enabled = save_nesting;
3238 return cond;
3241 /* If the top-level expression of "stmt" is an assignment, then
3242 * return that assignment as a BinaryOperator.
3243 * Otherwise return NULL.
3245 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3247 BinaryOperator *ass;
3249 if (!stmt)
3250 return NULL;
3251 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3252 return NULL;
3254 ass = cast<BinaryOperator>(stmt);
3255 if(ass->getOpcode() != BO_Assign)
3256 return NULL;
3258 return ass;
3261 /* Check if the given if statement is a conditional assignement
3262 * with a non-affine condition. If so, construct a pet_scop
3263 * corresponding to this conditional assignment. Otherwise return NULL.
3265 * In particular we check if "stmt" is of the form
3267 * if (condition)
3268 * a = f(...);
3269 * else
3270 * a = g(...);
3272 * where a is some array or scalar access.
3273 * The constructed pet_scop then corresponds to the expression
3275 * a = condition ? f(...) : g(...)
3277 * All access relations in f(...) are intersected with condition
3278 * while all access relation in g(...) are intersected with the complement.
3280 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3282 BinaryOperator *ass_then, *ass_else;
3283 pet_expr *write_then, *write_else;
3284 isl_set *cond, *comp;
3285 isl_multi_pw_aff *index;
3286 isl_pw_aff *pa;
3287 int equal;
3288 int type_size;
3289 pet_expr *pe_cond, *pe_then, *pe_else, *pe;
3290 bool save_nesting = nesting_enabled;
3292 if (!options->detect_conditional_assignment)
3293 return NULL;
3295 ass_then = top_assignment_or_null(stmt->getThen());
3296 ass_else = top_assignment_or_null(stmt->getElse());
3298 if (!ass_then || !ass_else)
3299 return NULL;
3301 if (is_affine_condition(stmt->getCond()))
3302 return NULL;
3304 write_then = extract_access_expr(ass_then->getLHS());
3305 write_else = extract_access_expr(ass_else->getLHS());
3307 equal = pet_expr_is_equal(write_then, write_else);
3308 pet_expr_free(write_else);
3309 if (equal < 0 || !equal) {
3310 pet_expr_free(write_then);
3311 return NULL;
3314 nesting_enabled = allow_nested;
3315 pa = extract_condition(stmt->getCond());
3316 nesting_enabled = save_nesting;
3317 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3318 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3319 index = isl_multi_pw_aff_from_pw_aff(pa);
3321 pe_cond = pet_expr_from_index(index);
3323 pe_then = extract_expr(ass_then->getRHS());
3324 pe_then = pet_expr_restrict(pe_then, cond);
3325 pe_else = extract_expr(ass_else->getRHS());
3326 pe_else = pet_expr_restrict(pe_else, comp);
3328 pe = pet_expr_new_ternary(pe_cond, pe_then, pe_else);
3329 write_then = pet_expr_access_set_write(write_then, 1);
3330 write_then = pet_expr_access_set_read(write_then, 0);
3331 type_size = get_type_size(ass_then->getType(), ast_context);
3332 pe = pet_expr_new_binary(type_size, pet_op_assign, write_then, pe);
3333 return extract(pe, stmt->getSourceRange(), false);
3336 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3337 * evaluating "cond" and writing the result to a virtual scalar,
3338 * as expressed by "index".
3340 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond, int stmt_nr,
3341 __isl_take isl_multi_pw_aff *index)
3343 pet_expr *expr, *write;
3344 struct pet_stmt *ps;
3345 SourceLocation loc = cond->getLocStart();
3346 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3347 pet_context *pc;
3349 write = pet_expr_from_index(index);
3350 write = pet_expr_access_set_write(write, 1);
3351 write = pet_expr_access_set_read(write, 0);
3352 expr = extract_expr(cond);
3354 pc = convert_assignments(ctx, assigned_value);
3355 expr = pet_expr_plug_in_args(expr, pc);
3356 pet_context_free(pc);
3358 expr = resolve_nested(expr);
3359 expr = pet_expr_new_binary(1, pet_op_assign, write, expr);
3360 ps = pet_stmt_from_pet_expr(line, NULL, stmt_nr, expr);
3361 return pet_scop_from_pet_stmt(ctx, ps);
3364 extern "C" {
3365 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr,
3366 void *user);
3369 /* Precompose the access relation and the index expression associated
3370 * to "expr" with the function pointed to by "user",
3371 * thereby embedding the access relation in the domain of this function.
3372 * The initial domain of the access relation and the index expression
3373 * is the zero-dimensional domain.
3375 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr, void *user)
3377 isl_multi_aff *ma = (isl_multi_aff *) user;
3379 return pet_expr_access_pullback_multi_aff(expr, isl_multi_aff_copy(ma));
3382 /* Precompose all access relations in "expr" with "ma", thereby
3383 * embedding them in the domain of "ma".
3385 static __isl_give pet_expr *embed(__isl_take pet_expr *expr,
3386 __isl_keep isl_multi_aff *ma)
3388 return pet_expr_map_access(expr, &embed_access, ma);
3391 /* For each nested access parameter in the domain of "stmt",
3392 * construct a corresponding pet_expr, place it before the original
3393 * elements in stmt->args and record its position in "param2pos".
3394 * n is the number of nested access parameters.
3396 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3397 std::map<int,int> &param2pos)
3399 int i;
3400 isl_space *space;
3401 int n_arg;
3402 pet_expr **args;
3404 n_arg = stmt->n_arg;
3405 args = isl_calloc_array(ctx, pet_expr *, n + n_arg);
3406 if (!args)
3407 goto error;
3409 space = isl_set_get_space(stmt->domain);
3410 n_arg = extract_nested(space, 0, args, param2pos);
3411 isl_space_free(space);
3413 if (n_arg < 0)
3414 goto error;
3416 for (i = 0; i < stmt->n_arg; ++i)
3417 args[n_arg + i] = stmt->args[i];
3418 free(stmt->args);
3419 stmt->args = args;
3420 stmt->n_arg += n_arg;
3422 return stmt;
3423 error:
3424 if (args) {
3425 for (i = 0; i < n; ++i)
3426 pet_expr_free(args[i]);
3427 free(args);
3429 pet_stmt_free(stmt);
3430 return NULL;
3433 /* Check whether any of the arguments i of "stmt" starting at position "n"
3434 * is equal to one of the first "n" arguments j.
3435 * If so, combine the constraints on arguments i and j and remove
3436 * argument i.
3438 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3440 int i, j;
3441 isl_map *map;
3443 if (!stmt)
3444 return NULL;
3445 if (n == 0)
3446 return stmt;
3447 if (n == stmt->n_arg)
3448 return stmt;
3450 map = isl_set_unwrap(stmt->domain);
3452 for (i = stmt->n_arg - 1; i >= n; --i) {
3453 for (j = 0; j < n; ++j)
3454 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3455 break;
3456 if (j >= n)
3457 continue;
3459 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3460 map = isl_map_project_out(map, isl_dim_out, i, 1);
3462 pet_expr_free(stmt->args[i]);
3463 for (j = i; j + 1 < stmt->n_arg; ++j)
3464 stmt->args[j] = stmt->args[j + 1];
3465 stmt->n_arg--;
3468 stmt->domain = isl_map_wrap(map);
3469 if (!stmt->domain)
3470 goto error;
3471 return stmt;
3472 error:
3473 pet_stmt_free(stmt);
3474 return NULL;
3477 /* Look for parameters in the iteration domain of "stmt" that
3478 * refer to nested accesses. In particular, these are
3479 * parameters with name "__pet_expr".
3481 * If there are any such parameters, then as many extra variables
3482 * (after identifying identical nested accesses) are inserted in the
3483 * range of the map wrapped inside the domain, before the original variables.
3484 * If the original domain is not a wrapped map, then a new wrapped
3485 * map is created with zero output dimensions.
3486 * The parameters are then equated to the corresponding output dimensions
3487 * and subsequently projected out, from the iteration domain,
3488 * the schedule and the access relations.
3489 * For each of the output dimensions, a corresponding argument
3490 * expression is inserted. Initially they are created with
3491 * a zero-dimensional domain, so they have to be embedded
3492 * in the current iteration domain.
3493 * param2pos maps the position of the parameter to the position
3494 * of the corresponding output dimension in the wrapped map.
3496 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3498 int n;
3499 int nparam;
3500 unsigned n_arg;
3501 isl_map *map;
3502 isl_space *space;
3503 isl_multi_aff *ma;
3504 std::map<int,int> param2pos;
3506 if (!stmt)
3507 return NULL;
3509 n = pet_nested_n_in_set(stmt->domain);
3510 if (n == 0)
3511 return stmt;
3513 n_arg = stmt->n_arg;
3514 stmt = extract_nested(stmt, n, param2pos);
3515 if (!stmt)
3516 return NULL;
3518 n = stmt->n_arg - n_arg;
3519 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3520 if (isl_set_is_wrapping(stmt->domain))
3521 map = isl_set_unwrap(stmt->domain);
3522 else
3523 map = isl_map_from_domain(stmt->domain);
3524 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3526 for (int i = nparam - 1; i >= 0; --i) {
3527 isl_id *id;
3529 if (!pet_nested_in_map(map, i))
3530 continue;
3532 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
3533 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3534 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3535 param2pos[i]);
3536 map = isl_map_project_out(map, isl_dim_param, i, 1);
3539 stmt->domain = isl_map_wrap(map);
3541 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
3542 space = isl_space_from_domain(isl_space_domain(space));
3543 ma = isl_multi_aff_zero(space);
3544 for (int pos = 0; pos < n; ++pos)
3545 stmt->args[pos] = embed(stmt->args[pos], ma);
3546 isl_multi_aff_free(ma);
3548 stmt = pet_stmt_remove_nested_parameters(stmt);
3549 stmt = remove_duplicate_arguments(stmt, n);
3551 return stmt;
3554 /* For each statement in "scop", move the parameters that correspond
3555 * to nested access into the ranges of the domains and create
3556 * corresponding argument expressions.
3558 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3560 if (!scop)
3561 return NULL;
3563 for (int i = 0; i < scop->n_stmt; ++i) {
3564 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3565 if (!scop->stmts[i])
3566 goto error;
3569 return scop;
3570 error:
3571 pet_scop_free(scop);
3572 return NULL;
3575 /* Given an access expression "expr", is the variable accessed by
3576 * "expr" assigned anywhere inside "scop"?
3578 static bool is_assigned(__isl_keep pet_expr *expr, pet_scop *scop)
3580 bool assigned = false;
3581 isl_id *id;
3583 id = pet_expr_access_get_id(expr);
3584 assigned = pet_scop_writes(scop, id);
3585 isl_id_free(id);
3587 return assigned;
3590 /* Are all nested access parameters in "pa" allowed given "scop".
3591 * In particular, is none of them written by anywhere inside "scop".
3593 * If "scop" has any skip conditions, then no nested access parameters
3594 * are allowed. In particular, if there is any nested access in a guard
3595 * for a piece of code containing a "continue", then we want to introduce
3596 * a separate statement for evaluating this guard so that we can express
3597 * that the result is false for all previous iterations.
3599 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3601 int nparam;
3603 if (!scop)
3604 return true;
3606 if (!pet_nested_any_in_pw_aff(pa))
3607 return true;
3609 if (pet_scop_has_skip(scop, pet_skip_now))
3610 return false;
3612 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3613 for (int i = 0; i < nparam; ++i) {
3614 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3615 pet_expr *expr;
3616 bool allowed;
3618 if (!pet_nested_in_id(id)) {
3619 isl_id_free(id);
3620 continue;
3623 expr = pet_nested_extract_expr(id);
3624 allowed = pet_expr_get_type(expr) == pet_expr_access &&
3625 !is_assigned(expr, scop);
3627 pet_expr_free(expr);
3628 isl_id_free(id);
3630 if (!allowed)
3631 return false;
3634 return true;
3637 /* Construct a pet_scop for a non-affine if statement.
3639 * We create a separate statement that writes the result
3640 * of the non-affine condition to a virtual scalar.
3641 * A constraint requiring the value of this virtual scalar to be one
3642 * is added to the iteration domains of the then branch.
3643 * Similarly, a constraint requiring the value of this virtual scalar
3644 * to be zero is added to the iteration domains of the else branch, if any.
3645 * We adjust the schedules to ensure that the virtual scalar is written
3646 * before it is read.
3648 * If there are any breaks or continues in the then and/or else
3649 * branches, then we may have to compute a new skip condition.
3650 * This is handled using a pet_skip_info object.
3651 * On initialization, the object checks if skip conditions need
3652 * to be computed. If so, it does so in pet_skip_info_if_extract_index and
3653 * adds them in pet_skip_info_if_add.
3655 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
3656 struct pet_scop *scop_then, struct pet_scop *scop_else,
3657 bool have_else, int stmt_id)
3659 struct pet_scop *scop;
3660 isl_multi_pw_aff *test_index;
3661 int int_size;
3662 int save_n_stmt = n_stmt;
3664 test_index = pet_create_test_index(ctx, n_test++);
3665 n_stmt = stmt_id;
3666 scop = extract_non_affine_condition(cond, n_stmt++,
3667 isl_multi_pw_aff_copy(test_index));
3668 n_stmt = save_n_stmt;
3669 scop = scop_add_array(scop, test_index, ast_context);
3671 pet_skip_info skip;
3672 pet_skip_info_if_init(&skip, ctx, scop_then, scop_else, have_else, 0);
3673 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
3674 pet_skip_info_if_extract_index(&skip, test_index, int_size,
3675 &n_stmt, &n_test);
3677 scop = pet_scop_prefix(scop, 0);
3678 scop_then = pet_scop_prefix(scop_then, 1);
3679 scop_then = pet_scop_filter(scop_then,
3680 isl_multi_pw_aff_copy(test_index), 1);
3681 if (have_else) {
3682 scop_else = pet_scop_prefix(scop_else, 1);
3683 scop_else = pet_scop_filter(scop_else, test_index, 0);
3684 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
3685 } else
3686 isl_multi_pw_aff_free(test_index);
3688 scop = pet_scop_add_seq(ctx, scop, scop_then);
3690 scop = pet_skip_info_if_add(&skip, scop, 2);
3692 return scop;
3695 /* Construct a pet_scop for an if statement.
3697 * If the condition fits the pattern of a conditional assignment,
3698 * then it is handled by extract_conditional_assignment.
3699 * Otherwise, we do the following.
3701 * If the condition is affine, then the condition is added
3702 * to the iteration domains of the then branch, while the
3703 * opposite of the condition in added to the iteration domains
3704 * of the else branch, if any.
3705 * We allow the condition to be dynamic, i.e., to refer to
3706 * scalars or array elements that may be written to outside
3707 * of the given if statement. These nested accesses are then represented
3708 * as output dimensions in the wrapping iteration domain.
3709 * If it is also written _inside_ the then or else branch, then
3710 * we treat the condition as non-affine.
3711 * As explained in extract_non_affine_if, this will introduce
3712 * an extra statement.
3713 * For aesthetic reasons, we want this statement to have a statement
3714 * number that is lower than those of the then and else branches.
3715 * In order to evaluate if we will need such a statement, however, we
3716 * first construct scops for the then and else branches.
3717 * We therefore reserve a statement number if we might have to
3718 * introduce such an extra statement.
3720 * If the condition is not affine, then the scop is created in
3721 * extract_non_affine_if.
3723 * If there are any breaks or continues in the then and/or else
3724 * branches, then we may have to compute a new skip condition.
3725 * This is handled using a pet_skip_info object.
3726 * On initialization, the object checks if skip conditions need
3727 * to be computed. If so, it does so in pet_skip_info_if_extract_cond and
3728 * adds them in pet_skip_info_if_add.
3730 struct pet_scop *PetScan::extract(IfStmt *stmt)
3732 struct pet_scop *scop_then, *scop_else = NULL, *scop;
3733 isl_pw_aff *cond;
3734 int stmt_id;
3735 int int_size;
3736 isl_set *set;
3737 isl_set *valid;
3739 clear_assignments clear(assigned_value);
3740 clear.TraverseStmt(stmt->getThen());
3741 if (stmt->getElse())
3742 clear.TraverseStmt(stmt->getElse());
3744 scop = extract_conditional_assignment(stmt);
3745 if (scop)
3746 return scop;
3748 cond = try_extract_nested_condition(stmt->getCond());
3749 if (allow_nested && (!cond || pet_nested_any_in_pw_aff(cond)))
3750 stmt_id = n_stmt++;
3753 assigned_value_cache cache(assigned_value);
3754 scop_then = extract(stmt->getThen());
3757 if (stmt->getElse()) {
3758 assigned_value_cache cache(assigned_value);
3759 scop_else = extract(stmt->getElse());
3760 if (options->autodetect) {
3761 if (scop_then && !scop_else) {
3762 partial = true;
3763 isl_pw_aff_free(cond);
3764 return scop_then;
3766 if (!scop_then && scop_else) {
3767 partial = true;
3768 isl_pw_aff_free(cond);
3769 return scop_else;
3774 if (cond &&
3775 (!is_nested_allowed(cond, scop_then) ||
3776 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
3777 isl_pw_aff_free(cond);
3778 cond = NULL;
3780 if (allow_nested && !cond)
3781 return extract_non_affine_if(stmt->getCond(), scop_then,
3782 scop_else, stmt->getElse(), stmt_id);
3784 if (!cond)
3785 cond = extract_condition(stmt->getCond());
3787 pet_skip_info skip;
3788 pet_skip_info_if_init(&skip, ctx, scop_then, scop_else,
3789 stmt->getElse() != NULL, 1);
3790 pet_skip_info_if_extract_cond(&skip, cond, int_size, &n_stmt, &n_test);
3792 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
3793 set = isl_pw_aff_non_zero_set(cond);
3794 scop = pet_scop_restrict(scop_then, isl_set_params(isl_set_copy(set)));
3796 if (stmt->getElse()) {
3797 set = isl_set_subtract(isl_set_copy(valid), set);
3798 scop_else = pet_scop_restrict(scop_else, isl_set_params(set));
3799 scop = pet_scop_add_par(ctx, scop, scop_else);
3800 } else
3801 isl_set_free(set);
3802 scop = resolve_nested(scop);
3803 scop = pet_scop_restrict_context(scop, isl_set_params(valid));
3805 if (pet_skip_info_has_skip(&skip))
3806 scop = pet_scop_prefix(scop, 0);
3807 scop = pet_skip_info_if_add(&skip, scop, 1);
3809 return scop;
3812 /* Try and construct a pet_scop for a label statement.
3813 * We currently only allow labels on expression statements.
3815 struct pet_scop *PetScan::extract(LabelStmt *stmt)
3817 isl_id *label;
3818 Stmt *sub;
3820 sub = stmt->getSubStmt();
3821 if (!isa<Expr>(sub)) {
3822 unsupported(stmt);
3823 return NULL;
3826 label = isl_id_alloc(ctx, stmt->getName(), NULL);
3828 return extract(extract_expr(cast<Expr>(sub)), stmt->getSourceRange(),
3829 true, label);
3832 /* Return a one-dimensional multi piecewise affine expression that is equal
3833 * to the constant 1 and is defined over a zero-dimensional domain.
3835 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
3837 isl_space *space;
3838 isl_local_space *ls;
3839 isl_aff *aff;
3841 space = isl_space_set_alloc(ctx, 0, 0);
3842 ls = isl_local_space_from_space(space);
3843 aff = isl_aff_zero_on_domain(ls);
3844 aff = isl_aff_set_constant_si(aff, 1);
3846 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
3849 /* Construct a pet_scop for a continue statement.
3851 * We simply create an empty scop with a universal pet_skip_now
3852 * skip condition. This skip condition will then be taken into
3853 * account by the enclosing loop construct, possibly after
3854 * being incorporated into outer skip conditions.
3856 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
3858 pet_scop *scop;
3860 scop = pet_scop_empty(ctx);
3861 if (!scop)
3862 return NULL;
3864 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
3866 return scop;
3869 /* Construct a pet_scop for a break statement.
3871 * We simply create an empty scop with both a universal pet_skip_now
3872 * skip condition and a universal pet_skip_later skip condition.
3873 * These skip conditions will then be taken into
3874 * account by the enclosing loop construct, possibly after
3875 * being incorporated into outer skip conditions.
3877 struct pet_scop *PetScan::extract(BreakStmt *stmt)
3879 pet_scop *scop;
3880 isl_multi_pw_aff *skip;
3882 scop = pet_scop_empty(ctx);
3883 if (!scop)
3884 return NULL;
3886 skip = one_mpa(ctx);
3887 scop = pet_scop_set_skip(scop, pet_skip_now,
3888 isl_multi_pw_aff_copy(skip));
3889 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
3891 return scop;
3894 /* Try and construct a pet_scop corresponding to "stmt".
3896 * If "stmt" is a compound statement, then "skip_declarations"
3897 * indicates whether we should skip initial declarations in the
3898 * compound statement.
3900 * If the constructed pet_scop is not a (possibly) partial representation
3901 * of "stmt", we update start and end of the pet_scop to those of "stmt".
3902 * In particular, if skip_declarations is set, then we may have skipped
3903 * declarations inside "stmt" and so the pet_scop may not represent
3904 * the entire "stmt".
3905 * Note that this function may be called with "stmt" referring to the entire
3906 * body of the function, including the outer braces. In such cases,
3907 * skip_declarations will be set and the braces will not be taken into
3908 * account in scop->start and scop->end.
3910 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
3912 struct pet_scop *scop;
3914 if (isa<Expr>(stmt))
3915 return extract(extract_expr(cast<Expr>(stmt)),
3916 stmt->getSourceRange(), true);
3918 switch (stmt->getStmtClass()) {
3919 case Stmt::WhileStmtClass:
3920 scop = extract(cast<WhileStmt>(stmt));
3921 break;
3922 case Stmt::ForStmtClass:
3923 scop = extract_for(cast<ForStmt>(stmt));
3924 break;
3925 case Stmt::IfStmtClass:
3926 scop = extract(cast<IfStmt>(stmt));
3927 break;
3928 case Stmt::CompoundStmtClass:
3929 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
3930 break;
3931 case Stmt::LabelStmtClass:
3932 scop = extract(cast<LabelStmt>(stmt));
3933 break;
3934 case Stmt::ContinueStmtClass:
3935 scop = extract(cast<ContinueStmt>(stmt));
3936 break;
3937 case Stmt::BreakStmtClass:
3938 scop = extract(cast<BreakStmt>(stmt));
3939 break;
3940 case Stmt::DeclStmtClass:
3941 scop = extract(cast<DeclStmt>(stmt));
3942 break;
3943 default:
3944 unsupported(stmt);
3945 return NULL;
3948 if (partial || skip_declarations)
3949 return scop;
3951 scop = update_scop_start_end(scop, stmt->getSourceRange(), false);
3953 return scop;
3956 /* Extract a clone of the kill statement in "scop".
3957 * "scop" is expected to have been created from a DeclStmt
3958 * and should have the kill as its first statement.
3960 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
3962 pet_expr *kill;
3963 struct pet_stmt *stmt;
3964 isl_multi_pw_aff *index;
3965 isl_map *access;
3966 pet_expr *arg;
3968 if (!scop)
3969 return NULL;
3970 if (scop->n_stmt < 1)
3971 isl_die(ctx, isl_error_internal,
3972 "expecting at least one statement", return NULL);
3973 stmt = scop->stmts[0];
3974 if (!pet_stmt_is_kill(stmt))
3975 isl_die(ctx, isl_error_internal,
3976 "expecting kill statement", return NULL);
3978 arg = pet_expr_get_arg(stmt->body, 0);
3979 index = pet_expr_access_get_index(arg);
3980 access = pet_expr_access_get_access(arg);
3981 pet_expr_free(arg);
3982 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
3983 access = isl_map_reset_tuple_id(access, isl_dim_in);
3984 kill = pet_expr_kill_from_access_and_index(access, index);
3985 return pet_stmt_from_pet_expr(stmt->line, NULL, n_stmt++, kill);
3988 /* Mark all arrays in "scop" as being exposed.
3990 static struct pet_scop *mark_exposed(struct pet_scop *scop)
3992 if (!scop)
3993 return NULL;
3994 for (int i = 0; i < scop->n_array; ++i)
3995 scop->arrays[i]->exposed = 1;
3996 return scop;
3999 /* Try and construct a pet_scop corresponding to (part of)
4000 * a sequence of statements.
4002 * "block" is set if the sequence respresents the children of
4003 * a compound statement.
4004 * "skip_declarations" is set if we should skip initial declarations
4005 * in the sequence of statements.
4007 * After extracting a statement, we update "assigned_value"
4008 * based on the top-level assignments in the statement
4009 * so that we can exploit them in subsequent statements in the same block.
4011 * If there are any breaks or continues in the individual statements,
4012 * then we may have to compute a new skip condition.
4013 * This is handled using a pet_skip_info object.
4014 * On initialization, the object checks if skip conditions need
4015 * to be computed. If so, it does so in pet_skip_info_seq_extract and
4016 * adds them in pet_skip_info_seq_add.
4018 * If "block" is set, then we need to insert kill statements at
4019 * the end of the block for any array that has been declared by
4020 * one of the statements in the sequence. Each of these declarations
4021 * results in the construction of a kill statement at the place
4022 * of the declaration, so we simply collect duplicates of
4023 * those kill statements and append these duplicates to the constructed scop.
4025 * If "block" is not set, then any array declared by one of the statements
4026 * in the sequence is marked as being exposed.
4028 * If autodetect is set, then we allow the extraction of only a subrange
4029 * of the sequence of statements. However, if there is at least one statement
4030 * for which we could not construct a scop and the final range contains
4031 * either no statements or at least one kill, then we discard the entire
4032 * range.
4034 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
4035 bool skip_declarations)
4037 pet_scop *scop;
4038 StmtIterator i;
4039 int int_size;
4040 int j;
4041 bool partial_range = false;
4042 set<struct pet_stmt *> kills;
4043 set<struct pet_stmt *>::iterator it;
4045 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
4047 scop = pet_scop_empty(ctx);
4048 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4049 Stmt *child = *i;
4050 struct pet_scop *scop_i;
4052 if (scop->n_stmt == 0 && skip_declarations &&
4053 child->getStmtClass() == Stmt::DeclStmtClass)
4054 continue;
4056 scop_i = extract(child);
4057 if (scop->n_stmt != 0 && partial) {
4058 pet_scop_free(scop_i);
4059 break;
4061 handle_writes(scop_i);
4062 pet_skip_info skip;
4063 pet_skip_info_seq_init(&skip, ctx, scop, scop_i);
4064 pet_skip_info_seq_extract(&skip, int_size, &n_stmt, &n_test);
4065 if (pet_skip_info_has_skip(&skip))
4066 scop_i = pet_scop_prefix(scop_i, 0);
4067 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4068 if (block)
4069 kills.insert(extract_kill(scop_i));
4070 else
4071 scop_i = mark_exposed(scop_i);
4073 scop_i = pet_scop_prefix(scop_i, j);
4074 if (options->autodetect) {
4075 if (scop_i)
4076 scop = pet_scop_add_seq(ctx, scop, scop_i);
4077 else
4078 partial_range = true;
4079 if (scop->n_stmt != 0 && !scop_i)
4080 partial = true;
4081 } else {
4082 scop = pet_scop_add_seq(ctx, scop, scop_i);
4085 scop = pet_skip_info_seq_add(&skip, scop, j);
4087 if (partial || !scop)
4088 break;
4091 for (it = kills.begin(); it != kills.end(); ++it) {
4092 pet_scop *scop_j;
4093 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4094 scop_j = pet_scop_prefix(scop_j, j);
4095 scop = pet_scop_add_seq(ctx, scop, scop_j);
4098 if (scop && partial_range) {
4099 if (scop->n_stmt == 0 || kills.size() != 0) {
4100 pet_scop_free(scop);
4101 return NULL;
4103 partial = true;
4106 return scop;
4109 /* Check if the scop marked by the user is exactly this Stmt
4110 * or part of this Stmt.
4111 * If so, return a pet_scop corresponding to the marked region.
4112 * Otherwise, return NULL.
4114 struct pet_scop *PetScan::scan(Stmt *stmt)
4116 SourceManager &SM = PP.getSourceManager();
4117 unsigned start_off, end_off;
4119 start_off = getExpansionOffset(SM, stmt->getLocStart());
4120 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4122 if (start_off > loc.end)
4123 return NULL;
4124 if (end_off < loc.start)
4125 return NULL;
4126 if (start_off >= loc.start && end_off <= loc.end) {
4127 return extract(stmt);
4130 StmtIterator start;
4131 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4132 Stmt *child = *start;
4133 if (!child)
4134 continue;
4135 start_off = getExpansionOffset(SM, child->getLocStart());
4136 end_off = getExpansionOffset(SM, child->getLocEnd());
4137 if (start_off < loc.start && end_off >= loc.end)
4138 return scan(child);
4139 if (start_off >= loc.start)
4140 break;
4143 StmtIterator end;
4144 for (end = start; end != stmt->child_end(); ++end) {
4145 Stmt *child = *end;
4146 start_off = SM.getFileOffset(child->getLocStart());
4147 if (start_off >= loc.end)
4148 break;
4151 return extract(StmtRange(start, end), false, false);
4154 /* Set the size of index "pos" of "array" to "size".
4155 * In particular, add a constraint of the form
4157 * i_pos < size
4159 * to array->extent and a constraint of the form
4161 * size >= 0
4163 * to array->context.
4165 static struct pet_array *update_size(struct pet_array *array, int pos,
4166 __isl_take isl_pw_aff *size)
4168 isl_set *valid;
4169 isl_set *univ;
4170 isl_set *bound;
4171 isl_space *dim;
4172 isl_aff *aff;
4173 isl_pw_aff *index;
4174 isl_id *id;
4176 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
4177 array->context = isl_set_intersect(array->context, valid);
4179 dim = isl_set_get_space(array->extent);
4180 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
4181 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
4182 univ = isl_set_universe(isl_aff_get_domain_space(aff));
4183 index = isl_pw_aff_alloc(univ, aff);
4185 size = isl_pw_aff_add_dims(size, isl_dim_in,
4186 isl_set_dim(array->extent, isl_dim_set));
4187 id = isl_set_get_tuple_id(array->extent);
4188 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
4189 bound = isl_pw_aff_lt_set(index, size);
4191 array->extent = isl_set_intersect(array->extent, bound);
4193 if (!array->context || !array->extent)
4194 goto error;
4196 return array;
4197 error:
4198 pet_array_free(array);
4199 return NULL;
4202 /* Figure out the size of the array at position "pos" and all
4203 * subsequent positions from "type" and update "array" accordingly.
4205 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
4206 const Type *type, int pos)
4208 const ArrayType *atype;
4209 isl_pw_aff *size;
4211 if (!array)
4212 return NULL;
4214 if (type->isPointerType()) {
4215 type = type->getPointeeType().getTypePtr();
4216 return set_upper_bounds(array, type, pos + 1);
4218 if (!type->isArrayType())
4219 return array;
4221 type = type->getCanonicalTypeInternal().getTypePtr();
4222 atype = cast<ArrayType>(type);
4224 if (type->isConstantArrayType()) {
4225 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
4226 size = extract_affine(ca->getSize());
4227 array = update_size(array, pos, size);
4228 } else if (type->isVariableArrayType()) {
4229 const VariableArrayType *vla = cast<VariableArrayType>(atype);
4230 size = extract_affine(vla->getSizeExpr());
4231 array = update_size(array, pos, size);
4234 type = atype->getElementType().getTypePtr();
4236 return set_upper_bounds(array, type, pos + 1);
4239 /* Is "T" the type of a variable length array with static size?
4241 static bool is_vla_with_static_size(QualType T)
4243 const VariableArrayType *vlatype;
4245 if (!T->isVariableArrayType())
4246 return false;
4247 vlatype = cast<VariableArrayType>(T);
4248 return vlatype->getSizeModifier() == VariableArrayType::Static;
4251 /* Return the type of "decl" as an array.
4253 * In particular, if "decl" is a parameter declaration that
4254 * is a variable length array with a static size, then
4255 * return the original type (i.e., the variable length array).
4256 * Otherwise, return the type of decl.
4258 static QualType get_array_type(ValueDecl *decl)
4260 ParmVarDecl *parm;
4261 QualType T;
4263 parm = dyn_cast<ParmVarDecl>(decl);
4264 if (!parm)
4265 return decl->getType();
4267 T = parm->getOriginalType();
4268 if (!is_vla_with_static_size(T))
4269 return decl->getType();
4270 return T;
4273 /* Does "decl" have definition that we can keep track of in a pet_type?
4275 static bool has_printable_definition(RecordDecl *decl)
4277 if (!decl->getDeclName())
4278 return false;
4279 return decl->getLexicalDeclContext() == decl->getDeclContext();
4282 /* Construct and return a pet_array corresponding to the variable "decl".
4283 * In particular, initialize array->extent to
4285 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4287 * and then call set_upper_bounds to set the upper bounds on the indices
4288 * based on the type of the variable.
4290 * If the base type is that of a record with a top-level definition and
4291 * if "types" is not null, then the RecordDecl corresponding to the type
4292 * is added to "types".
4294 * If the base type is that of a record with no top-level definition,
4295 * then we replace it by "<subfield>".
4297 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
4298 lex_recorddecl_set *types)
4300 struct pet_array *array;
4301 QualType qt = get_array_type(decl);
4302 const Type *type = qt.getTypePtr();
4303 int depth = array_depth(type);
4304 QualType base = pet_clang_base_type(qt);
4305 string name;
4306 isl_id *id;
4307 isl_space *dim;
4309 array = isl_calloc_type(ctx, struct pet_array);
4310 if (!array)
4311 return NULL;
4313 id = create_decl_id(ctx, decl);
4314 dim = isl_space_set_alloc(ctx, 0, depth);
4315 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
4317 array->extent = isl_set_nat_universe(dim);
4319 dim = isl_space_params_alloc(ctx, 0);
4320 array->context = isl_set_universe(dim);
4322 array = set_upper_bounds(array, type, 0);
4323 if (!array)
4324 return NULL;
4326 name = base.getAsString();
4328 if (types && base->isRecordType()) {
4329 RecordDecl *decl = pet_clang_record_decl(base);
4330 if (has_printable_definition(decl))
4331 types->insert(decl);
4332 else
4333 name = "<subfield>";
4336 array->element_type = strdup(name.c_str());
4337 array->element_is_record = base->isRecordType();
4338 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
4340 return array;
4343 /* Construct and return a pet_array corresponding to the sequence
4344 * of declarations "decls".
4345 * If the sequence contains a single declaration, then it corresponds
4346 * to a simple array access. Otherwise, it corresponds to a member access,
4347 * with the declaration for the substructure following that of the containing
4348 * structure in the sequence of declarations.
4349 * We start with the outermost substructure and then combine it with
4350 * information from the inner structures.
4352 * Additionally, keep track of all required types in "types".
4354 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
4355 vector<ValueDecl *> decls, lex_recorddecl_set *types)
4357 struct pet_array *array;
4358 vector<ValueDecl *>::iterator it;
4360 it = decls.begin();
4362 array = extract_array(ctx, *it, types);
4364 for (++it; it != decls.end(); ++it) {
4365 struct pet_array *parent;
4366 const char *base_name, *field_name;
4367 char *product_name;
4369 parent = array;
4370 array = extract_array(ctx, *it, types);
4371 if (!array)
4372 return pet_array_free(parent);
4374 base_name = isl_set_get_tuple_name(parent->extent);
4375 field_name = isl_set_get_tuple_name(array->extent);
4376 product_name = pet_array_member_access_name(ctx,
4377 base_name, field_name);
4379 array->extent = isl_set_product(isl_set_copy(parent->extent),
4380 array->extent);
4381 if (product_name)
4382 array->extent = isl_set_set_tuple_name(array->extent,
4383 product_name);
4384 array->context = isl_set_intersect(array->context,
4385 isl_set_copy(parent->context));
4387 pet_array_free(parent);
4388 free(product_name);
4390 if (!array->extent || !array->context || !product_name)
4391 return pet_array_free(array);
4394 return array;
4397 /* Add a pet_type corresponding to "decl" to "scop, provided
4398 * it is a member of "types" and it has not been added before
4399 * (i.e., it is not a member of "types_done".
4401 * Since we want the user to be able to print the types
4402 * in the order in which they appear in the scop, we need to
4403 * make sure that types of fields in a structure appear before
4404 * that structure. We therefore call ourselves recursively
4405 * on the types of all record subfields.
4407 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
4408 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
4409 lex_recorddecl_set &types_done)
4411 string s;
4412 llvm::raw_string_ostream S(s);
4413 RecordDecl::field_iterator it;
4415 if (types.find(decl) == types.end())
4416 return scop;
4417 if (types_done.find(decl) != types_done.end())
4418 return scop;
4420 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
4421 RecordDecl *record;
4422 QualType type = it->getType();
4424 if (!type->isRecordType())
4425 continue;
4426 record = pet_clang_record_decl(type);
4427 scop = add_type(ctx, scop, record, PP, types, types_done);
4430 if (strlen(decl->getName().str().c_str()) == 0)
4431 return scop;
4433 decl->print(S, PrintingPolicy(PP.getLangOpts()));
4434 S.str();
4436 scop->types[scop->n_type] = pet_type_alloc(ctx,
4437 decl->getName().str().c_str(), s.c_str());
4438 if (!scop->types[scop->n_type])
4439 return pet_scop_free(scop);
4441 types_done.insert(decl);
4443 scop->n_type++;
4445 return scop;
4448 /* Construct a list of pet_arrays, one for each array (or scalar)
4449 * accessed inside "scop", add this list to "scop" and return the result.
4451 * The context of "scop" is updated with the intersection of
4452 * the contexts of all arrays, i.e., constraints on the parameters
4453 * that ensure that the arrays have a valid (non-negative) size.
4455 * If the any of the extracted arrays refers to a member access,
4456 * then also add the required types to "scop".
4458 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
4460 int i;
4461 array_desc_set arrays;
4462 array_desc_set::iterator it;
4463 lex_recorddecl_set types;
4464 lex_recorddecl_set types_done;
4465 lex_recorddecl_set::iterator types_it;
4466 int n_array;
4467 struct pet_array **scop_arrays;
4469 if (!scop)
4470 return NULL;
4472 pet_scop_collect_arrays(scop, arrays);
4473 if (arrays.size() == 0)
4474 return scop;
4476 n_array = scop->n_array;
4478 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
4479 n_array + arrays.size());
4480 if (!scop_arrays)
4481 goto error;
4482 scop->arrays = scop_arrays;
4484 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
4485 struct pet_array *array;
4486 array = extract_array(ctx, *it, &types);
4487 scop->arrays[n_array + i] = array;
4488 if (!scop->arrays[n_array + i])
4489 goto error;
4490 scop->n_array++;
4491 scop->context = isl_set_intersect(scop->context,
4492 isl_set_copy(array->context));
4493 if (!scop->context)
4494 goto error;
4497 if (types.size() == 0)
4498 return scop;
4500 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
4501 if (!scop->types)
4502 goto error;
4504 for (types_it = types.begin(); types_it != types.end(); ++types_it)
4505 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
4507 return scop;
4508 error:
4509 pet_scop_free(scop);
4510 return NULL;
4513 /* Bound all parameters in scop->context to the possible values
4514 * of the corresponding C variable.
4516 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
4518 int n;
4520 if (!scop)
4521 return NULL;
4523 n = isl_set_dim(scop->context, isl_dim_param);
4524 for (int i = 0; i < n; ++i) {
4525 isl_id *id;
4526 ValueDecl *decl;
4528 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
4529 if (pet_nested_in_id(id)) {
4530 isl_id_free(id);
4531 isl_die(isl_set_get_ctx(scop->context),
4532 isl_error_internal,
4533 "unresolved nested parameter", goto error);
4535 decl = (ValueDecl *) isl_id_get_user(id);
4536 isl_id_free(id);
4538 scop->context = set_parameter_bounds(scop->context, i, decl);
4540 if (!scop->context)
4541 goto error;
4544 return scop;
4545 error:
4546 pet_scop_free(scop);
4547 return NULL;
4550 /* Construct a pet_scop from the given function.
4552 * If the scop was delimited by scop and endscop pragmas, then we override
4553 * the file offsets by those derived from the pragmas.
4555 struct pet_scop *PetScan::scan(FunctionDecl *fd)
4557 pet_scop *scop;
4558 Stmt *stmt;
4560 stmt = fd->getBody();
4562 if (options->autodetect)
4563 scop = extract(stmt, true);
4564 else {
4565 scop = scan(stmt);
4566 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
4568 scop = pet_scop_detect_parameter_accesses(scop);
4569 scop = scan_arrays(scop);
4570 scop = add_parameter_bounds(scop);
4571 scop = pet_scop_gist(scop, value_bounds);
4573 return scop;