PetScan::extract_affine(const llvm::APInt &): extract as pet_expr first
[pet.git] / scan.cc
blob840299e0aa4f89b0ea1488320581ebd05bf99968
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 a pet_expr from the APInt "val", which is assumed
495 * to be non-negative.
497 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
499 return pet_expr_new_int(extract_unsigned(ctx, val));
502 /* Extract an affine expression from the APInt "val", which is assumed
503 * to be non-negative.
504 * If the value of "val" is "v", then the returned expression
505 * is
507 * { [] -> [v] }
509 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
511 pet_context *pc;
512 pet_expr *expr;
513 isl_pw_aff *pa;
515 expr = extract_expr(val);
516 pc = pet_context_alloc(isl_space_set_alloc(ctx, 0, 0));
517 pa = pet_expr_extract_affine(expr, pc);
518 pet_context_free(pc);
519 pet_expr_free(expr);
521 return pa;
524 /* Return the number of bits needed to represent the type "qt",
525 * if it is an integer type. Otherwise return 0.
526 * If qt is signed then return the opposite of the number of bits.
528 static int get_type_size(QualType qt, ASTContext &ast_context)
530 int size;
532 if (!qt->isIntegerType())
533 return 0;
535 size = ast_context.getIntWidth(qt);
536 if (!qt->isUnsignedIntegerType())
537 size = -size;
539 return size;
542 /* Return the number of bits needed to represent the type of "decl",
543 * if it is an integer type. Otherwise return 0.
544 * If qt is signed then return the opposite of the number of bits.
546 static int get_type_size(ValueDecl *decl)
548 return get_type_size(decl->getType(), decl->getASTContext());
551 /* Bound parameter "pos" of "set" to the possible values of "decl".
553 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
554 unsigned pos, ValueDecl *decl)
556 int type_size;
557 isl_ctx *ctx;
558 isl_val *bound;
560 ctx = isl_set_get_ctx(set);
561 type_size = get_type_size(decl);
562 if (type_size == 0)
563 isl_die(ctx, isl_error_invalid, "not an integer type",
564 return isl_set_free(set));
565 if (type_size > 0) {
566 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
567 bound = isl_val_int_from_ui(ctx, type_size);
568 bound = isl_val_2exp(bound);
569 bound = isl_val_sub_ui(bound, 1);
570 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
571 } else {
572 bound = isl_val_int_from_ui(ctx, -type_size - 1);
573 bound = isl_val_2exp(bound);
574 bound = isl_val_sub_ui(bound, 1);
575 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
576 isl_val_copy(bound));
577 bound = isl_val_neg(bound);
578 bound = isl_val_sub_ui(bound, 1);
579 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
582 return set;
585 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
587 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
588 __isl_take isl_set *dom)
590 isl_pw_aff *pa;
591 pa = isl_set_indicator_function(set);
592 pa = isl_pw_aff_intersect_domain(pa, isl_set_coalesce(dom));
593 return pa;
596 /* Extract an affine expression, if possible, from "expr".
597 * Otherwise return NULL.
599 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
601 pet_expr *pe;
602 pet_context *pc;
603 isl_pw_aff *pa;
605 pe = extract_expr(expr);
606 if (!pe)
607 return NULL;
608 pc = convert_assignments(ctx, assigned_value);
609 pe = pet_expr_plug_in_args(pe, pc);
610 pa = pet_expr_extract_affine(pe, pc);
611 if (isl_pw_aff_involves_nan(pa)) {
612 unsupported(expr);
613 pa = isl_pw_aff_free(pa);
615 pet_context_free(pc);
616 pet_expr_free(pe);
618 return pa;
621 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
623 return extract_index_expr(expr->getSubExpr());
626 /* Return the depth of an array of the given type.
628 static int array_depth(const Type *type)
630 if (type->isPointerType())
631 return 1 + array_depth(type->getPointeeType().getTypePtr());
632 if (type->isArrayType()) {
633 const ArrayType *atype;
634 type = type->getCanonicalTypeInternal().getTypePtr();
635 atype = cast<ArrayType>(type);
636 return 1 + array_depth(atype->getElementType().getTypePtr());
638 return 0;
641 /* Return the depth of the array accessed by the index expression "index".
642 * If "index" is an affine expression, i.e., if it does not access
643 * any array, then return 1.
644 * If "index" represent a member access, i.e., if its range is a wrapped
645 * relation, then return the sum of the depth of the array of structures
646 * and that of the member inside the structure.
648 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
650 isl_id *id;
651 ValueDecl *decl;
653 if (!index)
654 return -1;
656 if (isl_multi_pw_aff_range_is_wrapping(index)) {
657 int domain_depth, range_depth;
658 isl_multi_pw_aff *domain, *range;
660 domain = isl_multi_pw_aff_copy(index);
661 domain = isl_multi_pw_aff_range_factor_domain(domain);
662 domain_depth = extract_depth(domain);
663 isl_multi_pw_aff_free(domain);
664 range = isl_multi_pw_aff_copy(index);
665 range = isl_multi_pw_aff_range_factor_range(range);
666 range_depth = extract_depth(range);
667 isl_multi_pw_aff_free(range);
669 return domain_depth + range_depth;
672 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
673 return 1;
675 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
676 if (!id)
677 return -1;
678 decl = (ValueDecl *) isl_id_get_user(id);
679 isl_id_free(id);
681 return array_depth(decl->getType().getTypePtr());
684 /* Return the depth of the array accessed by the access expression "expr".
686 static int extract_depth(__isl_keep pet_expr *expr)
688 isl_multi_pw_aff *index;
689 int depth;
691 index = pet_expr_access_get_index(expr);
692 depth = extract_depth(index);
693 isl_multi_pw_aff_free(index);
695 return depth;
698 /* Construct a pet_expr representing an index expression for an access
699 * to the variable referenced by "expr".
701 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
703 return extract_index_expr(expr->getDecl());
706 /* Construct a pet_expr representing an index expression for an access
707 * to the variable "decl".
709 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
711 isl_id *id = create_decl_id(ctx, decl);
712 isl_space *space = isl_space_alloc(ctx, 0, 0, 0);
714 space = isl_space_set_tuple_id(space, isl_dim_out, id);
716 return pet_expr_from_index(isl_multi_pw_aff_zero(space));
719 /* Construct a pet_expr representing the index expression "expr"
720 * Return NULL on error.
722 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
724 switch (expr->getStmtClass()) {
725 case Stmt::ImplicitCastExprClass:
726 return extract_index_expr(cast<ImplicitCastExpr>(expr));
727 case Stmt::DeclRefExprClass:
728 return extract_index_expr(cast<DeclRefExpr>(expr));
729 case Stmt::ArraySubscriptExprClass:
730 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
731 case Stmt::IntegerLiteralClass:
732 return extract_expr(cast<IntegerLiteral>(expr));
733 case Stmt::MemberExprClass:
734 return extract_index_expr(cast<MemberExpr>(expr));
735 default:
736 unsupported(expr);
738 return NULL;
741 /* Extract an index expression from the given array subscript expression.
743 * We first extract an index expression from the base.
744 * This will result in an index expression with a range that corresponds
745 * to the earlier indices.
746 * We then extract the current index and let
747 * pet_expr_access_subscript combine the two.
749 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
751 Expr *base = expr->getBase();
752 Expr *idx = expr->getIdx();
753 pet_expr *index;
754 pet_expr *base_expr;
756 base_expr = extract_index_expr(base);
757 index = extract_expr(idx);
759 base_expr = pet_expr_access_subscript(base_expr, index);
761 return base_expr;
764 /* Extract an index expression from a member expression.
766 * If the base access (to the structure containing the member)
767 * is of the form
769 * A[..]
771 * and the member is called "f", then the member access is of
772 * the form
774 * A_f[A[..] -> f[]]
776 * If the member access is to an anonymous struct, then simply return
778 * A[..]
780 * If the member access in the source code is of the form
782 * A->f
784 * then it is treated as
786 * A[0].f
788 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
790 Expr *base = expr->getBase();
791 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
792 pet_expr *base_index;
793 isl_id *id;
795 base_index = extract_index_expr(base);
797 if (expr->isArrow()) {
798 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
799 base_index = pet_expr_access_subscript(base_index, index);
802 if (field->isAnonymousStructOrUnion())
803 return base_index;
805 id = create_decl_id(ctx, field);
807 return pet_expr_access_member(base_index, id);
810 /* Check if "expr" calls function "minmax" with two arguments and if so
811 * make lhs and rhs refer to these two arguments.
813 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
815 CallExpr *call;
816 FunctionDecl *fd;
817 string name;
819 if (expr->getStmtClass() != Stmt::CallExprClass)
820 return false;
822 call = cast<CallExpr>(expr);
823 fd = call->getDirectCallee();
824 if (!fd)
825 return false;
827 if (call->getNumArgs() != 2)
828 return false;
830 name = fd->getDeclName().getAsString();
831 if (name != minmax)
832 return false;
834 lhs = call->getArg(0);
835 rhs = call->getArg(1);
837 return true;
840 /* Check if "expr" is of the form min(lhs, rhs) and if so make
841 * lhs and rhs refer to the two arguments.
843 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
845 return is_minmax(expr, "min", lhs, rhs);
848 /* Check if "expr" is of the form max(lhs, rhs) and if so make
849 * lhs and rhs refer to the two arguments.
851 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
853 return is_minmax(expr, "max", lhs, rhs);
856 /* Extract an affine expressions representing the comparison "LHS op RHS"
857 * "comp" is the original statement that "LHS op RHS" is derived from
858 * and is used for diagnostics.
860 * If the comparison is of the form
862 * a <= min(b,c)
864 * then the expression is constructed as the conjunction of
865 * the comparisons
867 * a <= b and a <= c
869 * A similar optimization is performed for max(a,b) <= c.
870 * We do this because that will lead to simpler representations
871 * of the expression.
872 * If isl is ever enhanced to explicitly deal with min and max expressions,
873 * this optimization can be removed.
875 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
876 Expr *LHS, Expr *RHS, Stmt *comp)
878 isl_pw_aff *lhs;
879 isl_pw_aff *rhs;
880 isl_pw_aff *res;
881 isl_set *cond;
882 isl_set *dom;
883 enum pet_op_type type;
885 if (op == BO_GT)
886 return extract_comparison(BO_LT, RHS, LHS, comp);
887 if (op == BO_GE)
888 return extract_comparison(BO_LE, RHS, LHS, comp);
890 if (op == BO_LT || op == BO_LE) {
891 Expr *expr1, *expr2;
892 if (is_min(RHS, expr1, expr2)) {
893 lhs = extract_comparison(op, LHS, expr1, comp);
894 rhs = extract_comparison(op, LHS, expr2, comp);
895 return pet_and(lhs, rhs);
897 if (is_max(LHS, expr1, expr2)) {
898 lhs = extract_comparison(op, expr1, RHS, comp);
899 rhs = extract_comparison(op, expr2, RHS, comp);
900 return pet_and(lhs, rhs);
904 lhs = extract_affine(LHS);
905 rhs = extract_affine(RHS);
907 type = BinaryOperatorKind2pet_op_type(op);
908 return pet_comparison(type, lhs, rhs);
911 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
913 return extract_comparison(comp->getOpcode(), comp->getLHS(),
914 comp->getRHS(), comp);
917 /* Extract an affine expression from a boolean expression.
918 * In particular, return the expression "expr ? 1 : 0".
919 * Return NULL if we are unable to extract an affine expression.
921 * We first convert the clang::Expr to a pet_expr and
922 * then extract an affine expression from that pet_expr.
924 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
926 isl_pw_aff *cond;
927 pet_expr *pe;
928 pet_context *pc;
930 if (!expr) {
931 isl_set *u = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
932 return indicator_function(u, isl_set_copy(u));
935 pe = extract_expr(expr);
936 pc = convert_assignments(ctx, assigned_value);
937 pe = pet_expr_plug_in_args(pe, pc);
938 pc = pet_context_set_allow_nested(pc, nesting_enabled);
939 cond = pet_expr_extract_affine_condition(pe, pc);
940 if (isl_pw_aff_involves_nan(cond))
941 cond = isl_pw_aff_free(cond);
942 pet_context_free(pc);
943 pet_expr_free(pe);
944 return cond;
947 /* Mark the given access pet_expr as a write.
949 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
951 access = pet_expr_access_set_write(access, 1);
952 access = pet_expr_access_set_read(access, 0);
954 return access;
957 /* Construct a pet_expr representing a unary operator expression.
959 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
961 pet_expr *arg;
962 enum pet_op_type op;
964 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
965 if (op == pet_op_last) {
966 unsupported(expr);
967 return NULL;
970 arg = extract_expr(expr->getSubExpr());
972 if (expr->isIncrementDecrementOp() &&
973 pet_expr_get_type(arg) == pet_expr_access) {
974 arg = mark_write(arg);
975 arg = pet_expr_access_set_read(arg, 1);
978 return pet_expr_new_unary(op, arg);
981 /* If the access expression "expr" writes to a (non-virtual) scalar,
982 * then mark the scalar as having an unknown value in "assigned_value".
984 static int clear_write(__isl_keep pet_expr *expr, void *user)
986 isl_id *id;
987 ValueDecl *decl;
988 PetScan *ps = (PetScan *) user;
990 if (!pet_expr_access_is_write(expr))
991 return 0;
992 if (!pet_expr_is_scalar_access(expr))
993 return 0;
995 id = pet_expr_access_get_id(expr);
996 decl = (ValueDecl *) isl_id_get_user(id);
997 isl_id_free(id);
999 if (decl)
1000 clear_assignment(ps->assigned_value, decl);
1002 return 0;
1005 /* Take into account the writes in "stmt".
1006 * That is, first mark all scalar variables that are written by "stmt"
1007 * as having an unknown value. Afterwards,
1008 * if "stmt" is a top-level (i.e., unconditional) assignment
1009 * to a scalar variable, then update "assigned_value" accordingly.
1011 * In particular, if the lhs of the assignment is a scalar variable, then mark
1012 * the variable as having been assigned. If, furthermore, the rhs
1013 * is an affine expression, then keep track of this value in assigned_value
1014 * so that we can plug it in when we later come across the same variable.
1016 * We skip assignments to virtual arrays (those with NULL user pointer).
1018 void PetScan::handle_writes(struct pet_stmt *stmt)
1020 pet_expr *body = stmt->body;
1021 pet_expr *arg;
1022 isl_id *id;
1023 ValueDecl *decl;
1024 pet_context *pc;
1025 isl_pw_aff *pa;
1027 pet_expr_foreach_access_expr(body, &clear_write, this);
1029 if (!pet_stmt_is_assign(stmt))
1030 return;
1031 if (!isl_set_plain_is_universe(stmt->domain))
1032 return;
1033 arg = pet_expr_get_arg(body, 0);
1034 if (!pet_expr_is_scalar_access(arg)) {
1035 pet_expr_free(arg);
1036 return;
1039 id = pet_expr_access_get_id(arg);
1040 decl = (ValueDecl *) isl_id_get_user(id);
1041 isl_id_free(id);
1042 pet_expr_free(arg);
1044 if (!decl)
1045 return;
1047 arg = pet_expr_get_arg(body, 1);
1048 pc = convert_assignments(ctx, assigned_value);
1049 pa = pet_expr_extract_affine(arg, pc);
1050 pet_context_free(pc);
1051 clear_assignment(assigned_value, decl);
1052 pet_expr_free(arg);
1054 if (isl_pw_aff_involves_nan(pa))
1055 pa = isl_pw_aff_free(pa);
1056 if (!pa)
1057 return;
1058 assigned_value[decl] = pa;
1059 insert_expression(pa);
1062 /* Update "assigned_value" based on the write accesses (and, in particular,
1063 * assignments) in "scop".
1065 void PetScan::handle_writes(struct pet_scop *scop)
1067 if (!scop)
1068 return;
1069 for (int i = 0; i < scop->n_stmt; ++i)
1070 handle_writes(scop->stmts[i]);
1073 /* Construct a pet_expr representing a binary operator expression.
1075 * If the top level operator is an assignment and the LHS is an access,
1076 * then we mark that access as a write. If the operator is a compound
1077 * assignment, the access is marked as both a read and a write.
1079 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1081 int type_size;
1082 pet_expr *lhs, *rhs;
1083 enum pet_op_type op;
1085 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1086 if (op == pet_op_last) {
1087 unsupported(expr);
1088 return NULL;
1091 lhs = extract_expr(expr->getLHS());
1092 rhs = extract_expr(expr->getRHS());
1094 if (expr->isAssignmentOp() &&
1095 pet_expr_get_type(lhs) == pet_expr_access) {
1096 lhs = mark_write(lhs);
1097 if (expr->isCompoundAssignmentOp())
1098 lhs = pet_expr_access_set_read(lhs, 1);
1101 type_size = get_type_size(expr->getType(), ast_context);
1102 return pet_expr_new_binary(type_size, op, lhs, rhs);
1105 /* Construct a pet_scop with a single statement killing the entire
1106 * array "array".
1108 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1110 isl_id *id;
1111 isl_space *space;
1112 isl_multi_pw_aff *index;
1113 isl_map *access;
1114 pet_expr *expr;
1116 if (!array)
1117 return NULL;
1118 access = isl_map_from_range(isl_set_copy(array->extent));
1119 id = isl_set_get_tuple_id(array->extent);
1120 space = isl_space_alloc(ctx, 0, 0, 0);
1121 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1122 index = isl_multi_pw_aff_zero(space);
1123 expr = pet_expr_kill_from_access_and_index(access, index);
1124 return extract(expr, stmt->getSourceRange(), false);
1127 /* Construct a pet_scop for a (single) variable declaration.
1129 * The scop contains the variable being declared (as an array)
1130 * and a statement killing the array.
1132 * If the variable is initialized in the AST, then the scop
1133 * also contains an assignment to the variable.
1135 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1137 int type_size;
1138 Decl *decl;
1139 VarDecl *vd;
1140 pet_expr *lhs, *rhs, *pe;
1141 struct pet_scop *scop_decl, *scop;
1142 struct pet_array *array;
1144 if (!stmt->isSingleDecl()) {
1145 unsupported(stmt);
1146 return NULL;
1149 decl = stmt->getSingleDecl();
1150 vd = cast<VarDecl>(decl);
1152 array = extract_array(ctx, vd, NULL);
1153 if (array)
1154 array->declared = 1;
1155 scop_decl = kill(stmt, array);
1156 scop_decl = pet_scop_add_array(scop_decl, array);
1158 if (!vd->getInit())
1159 return scop_decl;
1161 lhs = extract_access_expr(vd);
1162 rhs = extract_expr(vd->getInit());
1164 lhs = mark_write(lhs);
1166 type_size = get_type_size(vd->getType(), ast_context);
1167 pe = pet_expr_new_binary(type_size, pet_op_assign, lhs, rhs);
1168 scop = extract(pe, stmt->getSourceRange(), false);
1170 scop_decl = pet_scop_prefix(scop_decl, 0);
1171 scop = pet_scop_prefix(scop, 1);
1173 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1175 return scop;
1178 /* Construct a pet_expr representing a conditional operation.
1180 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1182 pet_expr *cond, *lhs, *rhs;
1183 isl_pw_aff *pa;
1185 cond = extract_expr(expr->getCond());
1186 lhs = extract_expr(expr->getTrueExpr());
1187 rhs = extract_expr(expr->getFalseExpr());
1189 return pet_expr_new_ternary(cond, lhs, rhs);
1192 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1194 return extract_expr(expr->getSubExpr());
1197 /* Construct a pet_expr representing a floating point value.
1199 * If the floating point literal does not appear in a macro,
1200 * then we use the original representation in the source code
1201 * as the string representation. Otherwise, we use the pretty
1202 * printer to produce a string representation.
1204 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1206 double d;
1207 string s;
1208 const LangOptions &LO = PP.getLangOpts();
1209 SourceLocation loc = expr->getLocation();
1211 if (!loc.isMacroID()) {
1212 SourceManager &SM = PP.getSourceManager();
1213 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1214 s = string(SM.getCharacterData(loc), len);
1215 } else {
1216 llvm::raw_string_ostream S(s);
1217 expr->printPretty(S, 0, PrintingPolicy(LO));
1218 S.str();
1220 d = expr->getValueAsApproximateDouble();
1221 return pet_expr_new_double(ctx, d, s.c_str());
1224 /* Convert the index expression "index" into an access pet_expr of type "qt".
1226 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
1227 __isl_take pet_expr *index)
1229 int depth;
1230 int type_size;
1232 depth = extract_depth(index);
1233 type_size = get_type_size(qt, ast_context);
1235 index = pet_expr_set_type_size(index, type_size);
1236 index = pet_expr_access_set_depth(index, depth);
1238 return index;
1241 /* Extract an index expression from "expr" and then convert it into
1242 * an access pet_expr.
1244 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
1246 return extract_access_expr(expr->getType(), extract_index_expr(expr));
1249 /* Extract an index expression from "decl" and then convert it into
1250 * an access pet_expr.
1252 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1254 return extract_access_expr(decl->getType(), extract_index_expr(decl));
1257 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
1259 return extract_expr(expr->getSubExpr());
1262 /* Extract an assume statement from the argument "expr"
1263 * of a __pencil_assume statement.
1265 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
1267 return pet_expr_new_unary(pet_op_assume, extract_expr(expr));
1270 /* Construct a pet_expr corresponding to the function call argument "expr".
1271 * The argument appears in position "pos" of a call to function "fd".
1273 * If we are passing along a pointer to an array element
1274 * or an entire row or even higher dimensional slice of an array,
1275 * then the function being called may write into the array.
1277 * We assume here that if the function is declared to take a pointer
1278 * to a const type, then the function will perform a read
1279 * and that otherwise, it will perform a write.
1281 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
1282 Expr *expr)
1284 pet_expr *res;
1285 int is_addr = 0, is_partial = 0;
1286 Stmt::StmtClass sc;
1288 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
1289 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
1290 expr = ice->getSubExpr();
1292 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
1293 UnaryOperator *op = cast<UnaryOperator>(expr);
1294 if (op->getOpcode() == UO_AddrOf) {
1295 is_addr = 1;
1296 expr = op->getSubExpr();
1299 res = extract_expr(expr);
1300 if (!res)
1301 return NULL;
1302 sc = expr->getStmtClass();
1303 if ((sc == Stmt::ArraySubscriptExprClass ||
1304 sc == Stmt::MemberExprClass) &&
1305 array_depth(expr->getType().getTypePtr()) > 0)
1306 is_partial = 1;
1307 if ((is_addr || is_partial) &&
1308 pet_expr_get_type(res) == pet_expr_access) {
1309 ParmVarDecl *parm;
1310 if (!fd->hasPrototype()) {
1311 report_prototype_required(expr);
1312 return pet_expr_free(res);
1314 parm = fd->getParamDecl(pos);
1315 if (!const_base(parm->getType()))
1316 res = mark_write(res);
1319 if (is_addr)
1320 res = pet_expr_new_unary(pet_op_address_of, res);
1321 return res;
1324 /* Construct a pet_expr representing a function call.
1326 * In the special case of a "call" to __pencil_assume,
1327 * construct an assume expression instead.
1329 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1331 pet_expr *res = NULL;
1332 FunctionDecl *fd;
1333 string name;
1334 unsigned n_arg;
1336 fd = expr->getDirectCallee();
1337 if (!fd) {
1338 unsupported(expr);
1339 return NULL;
1342 name = fd->getDeclName().getAsString();
1343 n_arg = expr->getNumArgs();
1345 if (n_arg == 1 && name == "__pencil_assume")
1346 return extract_assume(expr->getArg(0));
1348 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1349 if (!res)
1350 return NULL;
1352 for (int i = 0; i < n_arg; ++i) {
1353 Expr *arg = expr->getArg(i);
1354 res = pet_expr_set_arg(res, i,
1355 PetScan::extract_argument(fd, i, arg));
1358 return res;
1361 /* Construct a pet_expr representing a (C style) cast.
1363 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1365 pet_expr *arg;
1366 QualType type;
1368 arg = extract_expr(expr->getSubExpr());
1369 if (!arg)
1370 return NULL;
1372 type = expr->getTypeAsWritten();
1373 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1376 /* Construct a pet_expr representing an integer.
1378 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1380 return pet_expr_new_int(extract_int(expr));
1383 /* Try and construct a pet_expr representing "expr".
1385 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1387 switch (expr->getStmtClass()) {
1388 case Stmt::UnaryOperatorClass:
1389 return extract_expr(cast<UnaryOperator>(expr));
1390 case Stmt::CompoundAssignOperatorClass:
1391 case Stmt::BinaryOperatorClass:
1392 return extract_expr(cast<BinaryOperator>(expr));
1393 case Stmt::ImplicitCastExprClass:
1394 return extract_expr(cast<ImplicitCastExpr>(expr));
1395 case Stmt::ArraySubscriptExprClass:
1396 case Stmt::DeclRefExprClass:
1397 case Stmt::MemberExprClass:
1398 return extract_access_expr(expr);
1399 case Stmt::IntegerLiteralClass:
1400 return extract_expr(cast<IntegerLiteral>(expr));
1401 case Stmt::FloatingLiteralClass:
1402 return extract_expr(cast<FloatingLiteral>(expr));
1403 case Stmt::ParenExprClass:
1404 return extract_expr(cast<ParenExpr>(expr));
1405 case Stmt::ConditionalOperatorClass:
1406 return extract_expr(cast<ConditionalOperator>(expr));
1407 case Stmt::CallExprClass:
1408 return extract_expr(cast<CallExpr>(expr));
1409 case Stmt::CStyleCastExprClass:
1410 return extract_expr(cast<CStyleCastExpr>(expr));
1411 default:
1412 unsupported(expr);
1414 return NULL;
1417 /* Check if the given initialization statement is an assignment.
1418 * If so, return that assignment. Otherwise return NULL.
1420 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1422 BinaryOperator *ass;
1424 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1425 return NULL;
1427 ass = cast<BinaryOperator>(init);
1428 if (ass->getOpcode() != BO_Assign)
1429 return NULL;
1431 return ass;
1434 /* Check if the given initialization statement is a declaration
1435 * of a single variable.
1436 * If so, return that declaration. Otherwise return NULL.
1438 Decl *PetScan::initialization_declaration(Stmt *init)
1440 DeclStmt *decl;
1442 if (init->getStmtClass() != Stmt::DeclStmtClass)
1443 return NULL;
1445 decl = cast<DeclStmt>(init);
1447 if (!decl->isSingleDecl())
1448 return NULL;
1450 return decl->getSingleDecl();
1453 /* Given the assignment operator in the initialization of a for loop,
1454 * extract the induction variable, i.e., the (integer)variable being
1455 * assigned.
1457 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1459 Expr *lhs;
1460 DeclRefExpr *ref;
1461 ValueDecl *decl;
1462 const Type *type;
1464 lhs = init->getLHS();
1465 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1466 unsupported(init);
1467 return NULL;
1470 ref = cast<DeclRefExpr>(lhs);
1471 decl = ref->getDecl();
1472 type = decl->getType().getTypePtr();
1474 if (!type->isIntegerType()) {
1475 unsupported(lhs);
1476 return NULL;
1479 return decl;
1482 /* Given the initialization statement of a for loop and the single
1483 * declaration in this initialization statement,
1484 * extract the induction variable, i.e., the (integer) variable being
1485 * declared.
1487 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1489 VarDecl *vd;
1491 vd = cast<VarDecl>(decl);
1493 const QualType type = vd->getType();
1494 if (!type->isIntegerType()) {
1495 unsupported(init);
1496 return NULL;
1499 if (!vd->getInit()) {
1500 unsupported(init);
1501 return NULL;
1504 return vd;
1507 /* Check that op is of the form iv++ or iv--.
1508 * Return a pet_expr representing "1" or "-1" accordingly.
1510 __isl_give pet_expr *PetScan::extract_unary_increment(
1511 clang::UnaryOperator *op, clang::ValueDecl *iv)
1513 Expr *sub;
1514 DeclRefExpr *ref;
1515 isl_val *v;
1517 if (!op->isIncrementDecrementOp()) {
1518 unsupported(op);
1519 return NULL;
1522 sub = op->getSubExpr();
1523 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1524 unsupported(op);
1525 return NULL;
1528 ref = cast<DeclRefExpr>(sub);
1529 if (ref->getDecl() != iv) {
1530 unsupported(op);
1531 return NULL;
1534 if (op->isIncrementOp())
1535 v = isl_val_one(ctx);
1536 else
1537 v = isl_val_negone(ctx);
1539 return pet_expr_new_int(v);
1542 /* Check if op is of the form
1544 * iv = expr
1546 * and return the increment "expr - iv" as a pet_expr.
1548 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1549 clang::ValueDecl *iv)
1551 int type_size;
1552 Expr *lhs;
1553 DeclRefExpr *ref;
1554 pet_expr *expr, *expr_iv;
1556 if (op->getOpcode() != BO_Assign) {
1557 unsupported(op);
1558 return NULL;
1561 lhs = op->getLHS();
1562 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1563 unsupported(op);
1564 return NULL;
1567 ref = cast<DeclRefExpr>(lhs);
1568 if (ref->getDecl() != iv) {
1569 unsupported(op);
1570 return NULL;
1573 expr = extract_expr(op->getRHS());
1574 expr_iv = extract_expr(lhs);
1576 type_size = get_type_size(iv->getType(), ast_context);
1577 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1580 /* Check that op is of the form iv += cst or iv -= cst
1581 * and return a pet_expr corresponding to cst or -cst accordingly.
1583 __isl_give pet_expr *PetScan::extract_compound_increment(
1584 CompoundAssignOperator *op, clang::ValueDecl *iv)
1586 Expr *lhs;
1587 DeclRefExpr *ref;
1588 bool neg = false;
1589 pet_expr *expr;
1590 BinaryOperatorKind opcode;
1592 opcode = op->getOpcode();
1593 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1594 unsupported(op);
1595 return NULL;
1597 if (opcode == BO_SubAssign)
1598 neg = true;
1600 lhs = op->getLHS();
1601 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1602 unsupported(op);
1603 return NULL;
1606 ref = cast<DeclRefExpr>(lhs);
1607 if (ref->getDecl() != iv) {
1608 unsupported(op);
1609 return NULL;
1612 expr = extract_expr(op->getRHS());
1613 if (neg)
1614 expr = pet_expr_new_unary(pet_op_minus, expr);
1616 return expr;
1619 /* Check that the increment of the given for loop increments
1620 * (or decrements) the induction variable "iv" and return
1621 * the increment as a pet_expr if successful.
1623 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1624 ValueDecl *iv)
1626 Stmt *inc = stmt->getInc();
1628 if (!inc) {
1629 report_missing_increment(stmt);
1630 return NULL;
1633 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1634 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1635 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1636 return extract_compound_increment(
1637 cast<CompoundAssignOperator>(inc), iv);
1638 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1639 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1641 unsupported(inc);
1642 return NULL;
1645 /* Embed the given iteration domain in an extra outer loop
1646 * with induction variable "var".
1647 * If this variable appeared as a parameter in the constraints,
1648 * it is replaced by the new outermost dimension.
1650 static __isl_give isl_set *embed(__isl_take isl_set *set,
1651 __isl_take isl_id *var)
1653 int pos;
1655 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1656 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1657 if (pos >= 0) {
1658 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1659 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1662 isl_id_free(var);
1663 return set;
1666 /* Return those elements in the space of "cond" that come after
1667 * (based on "sign") an element in "cond".
1669 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
1671 isl_map *previous_to_this;
1673 if (sign > 0)
1674 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
1675 else
1676 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
1678 cond = isl_set_apply(cond, previous_to_this);
1680 return cond;
1683 /* Create the infinite iteration domain
1685 * { [id] : id >= 0 }
1687 * If "scop" has an affine skip of type pet_skip_later,
1688 * then remove those iterations i that have an earlier iteration
1689 * where the skip condition is satisfied, meaning that iteration i
1690 * is not executed.
1691 * Since we are dealing with a loop without loop iterator,
1692 * the skip condition cannot refer to the current loop iterator and
1693 * so effectively, the returned set is of the form
1695 * { [0]; [id] : id >= 1 and not skip }
1697 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
1698 struct pet_scop *scop)
1700 isl_ctx *ctx = isl_id_get_ctx(id);
1701 isl_set *domain;
1702 isl_set *skip;
1704 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1705 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
1707 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
1708 return domain;
1710 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
1711 skip = embed(skip, isl_id_copy(id));
1712 skip = isl_set_intersect(skip , isl_set_copy(domain));
1713 domain = isl_set_subtract(domain, after(skip, 1));
1715 return domain;
1718 /* Create an identity affine expression on the space containing "domain",
1719 * which is assumed to be one-dimensional.
1721 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
1723 isl_local_space *ls;
1725 ls = isl_local_space_from_space(isl_set_get_space(domain));
1726 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
1729 /* Create an affine expression that maps elements
1730 * of a single-dimensional array "id_test" to the previous element
1731 * (according to "inc"), provided this element belongs to "domain".
1732 * That is, create the affine expression
1734 * { id[x] -> id[x - inc] : x - inc in domain }
1736 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
1737 __isl_take isl_set *domain, __isl_take isl_val *inc)
1739 isl_space *space;
1740 isl_local_space *ls;
1741 isl_aff *aff;
1742 isl_multi_pw_aff *prev;
1744 space = isl_set_get_space(domain);
1745 ls = isl_local_space_from_space(space);
1746 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
1747 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
1748 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
1749 domain = isl_set_preimage_multi_pw_aff(domain,
1750 isl_multi_pw_aff_copy(prev));
1751 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
1752 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
1754 return prev;
1757 /* Add an implication to "scop" expressing that if an element of
1758 * virtual array "id_test" has value "satisfied" then all previous elements
1759 * of this array also have that value. The set of previous elements
1760 * is bounded by "domain". If "sign" is negative then the iterator
1761 * is decreasing and we express that all subsequent array elements
1762 * (but still defined previously) have the same value.
1764 static struct pet_scop *add_implication(struct pet_scop *scop,
1765 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
1766 int satisfied)
1768 isl_space *space;
1769 isl_map *map;
1771 domain = isl_set_set_tuple_id(domain, id_test);
1772 space = isl_set_get_space(domain);
1773 if (sign > 0)
1774 map = isl_map_lex_ge(space);
1775 else
1776 map = isl_map_lex_le(space);
1777 map = isl_map_intersect_range(map, domain);
1778 scop = pet_scop_add_implication(scop, map, satisfied);
1780 return scop;
1783 /* Add a filter to "scop" that imposes that it is only executed
1784 * when the variable identified by "id_test" has a zero value
1785 * for all previous iterations of "domain".
1787 * In particular, add a filter that imposes that the array
1788 * has a zero value at the previous iteration of domain and
1789 * add an implication that implies that it then has that
1790 * value for all previous iterations.
1792 static struct pet_scop *scop_add_break(struct pet_scop *scop,
1793 __isl_take isl_id *id_test, __isl_take isl_set *domain,
1794 __isl_take isl_val *inc)
1796 isl_multi_pw_aff *prev;
1797 int sign = isl_val_sgn(inc);
1799 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
1800 scop = add_implication(scop, id_test, domain, sign, 0);
1801 scop = pet_scop_filter(scop, prev, 0);
1803 return scop;
1806 /* Construct a pet_scop for an infinite loop around the given body.
1808 * We extract a pet_scop for the body and then embed it in a loop with
1809 * iteration domain
1811 * { [t] : t >= 0 }
1813 * and schedule
1815 * { [t] -> [t] }
1817 * If the body contains any break, then it is taken into
1818 * account in infinite_domain (if the skip condition is affine)
1819 * or in scop_add_break (if the skip condition is not affine).
1821 * If we were only able to extract part of the body, then simply
1822 * return that part.
1824 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1826 isl_id *id, *id_test;
1827 isl_set *domain;
1828 isl_aff *ident;
1829 struct pet_scop *scop;
1830 bool has_var_break;
1832 scop = extract(body);
1833 if (!scop)
1834 return NULL;
1835 if (partial)
1836 return scop;
1838 id = isl_id_alloc(ctx, "t", NULL);
1839 domain = infinite_domain(isl_id_copy(id), scop);
1840 ident = identity_aff(domain);
1842 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
1843 if (has_var_break)
1844 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
1846 scop = pet_scop_embed(scop, isl_set_copy(domain),
1847 isl_aff_copy(ident), ident, id);
1848 if (has_var_break)
1849 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
1850 else
1851 isl_set_free(domain);
1853 return scop;
1856 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1858 * for (;;)
1859 * body
1862 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1864 clear_assignments clear(assigned_value);
1865 clear.TraverseStmt(stmt->getBody());
1867 return extract_infinite_loop(stmt->getBody());
1870 /* Add an array with the given extent (range of "index") to the list
1871 * of arrays in "scop" and return the extended pet_scop.
1872 * The array is marked as attaining values 0 and 1 only and
1873 * as each element being assigned at most once.
1875 static struct pet_scop *scop_add_array(struct pet_scop *scop,
1876 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
1878 int int_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
1880 return pet_scop_add_boolean_array(scop, isl_multi_pw_aff_copy(index),
1881 int_size);
1884 /* Construct a pet_scop for a while loop of the form
1886 * while (pa)
1887 * body
1889 * In particular, construct a scop for an infinite loop around body and
1890 * intersect the domain with the affine expression.
1891 * Note that this intersection may result in an empty loop.
1893 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
1894 Stmt *body)
1896 struct pet_scop *scop;
1897 isl_set *dom;
1898 isl_set *valid;
1900 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
1901 dom = isl_pw_aff_non_zero_set(pa);
1902 scop = extract_infinite_loop(body);
1903 scop = pet_scop_restrict(scop, isl_set_params(dom));
1904 scop = pet_scop_restrict_context(scop, isl_set_params(valid));
1906 return scop;
1909 /* Construct a scop for a while, given the scops for the condition
1910 * and the body, the filter identifier and the iteration domain of
1911 * the while loop.
1913 * In particular, the scop for the condition is filtered to depend
1914 * on "id_test" evaluating to true for all previous iterations
1915 * of the loop, while the scop for the body is filtered to depend
1916 * on "id_test" evaluating to true for all iterations up to the
1917 * current iteration.
1918 * The actual filter only imposes that this virtual array has
1919 * value one on the previous or the current iteration.
1920 * The fact that this condition also applies to the previous
1921 * iterations is enforced by an implication.
1923 * These filtered scops are then combined into a single scop.
1925 * "sign" is positive if the iterator increases and negative
1926 * if it decreases.
1928 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
1929 struct pet_scop *scop_body, __isl_take isl_id *id_test,
1930 __isl_take isl_set *domain, __isl_take isl_val *inc)
1932 isl_ctx *ctx = isl_set_get_ctx(domain);
1933 isl_space *space;
1934 isl_multi_pw_aff *test_index;
1935 isl_multi_pw_aff *prev;
1936 int sign = isl_val_sgn(inc);
1937 struct pet_scop *scop;
1939 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
1940 scop_cond = pet_scop_filter(scop_cond, prev, 1);
1942 space = isl_space_map_from_set(isl_set_get_space(domain));
1943 test_index = isl_multi_pw_aff_identity(space);
1944 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
1945 isl_id_copy(id_test));
1946 scop_body = pet_scop_filter(scop_body, test_index, 1);
1948 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
1949 scop = add_implication(scop, id_test, domain, sign, 1);
1951 return scop;
1954 /* Check if the while loop is of the form
1956 * while (affine expression)
1957 * body
1959 * If so, call extract_affine_while to construct a scop.
1961 * Otherwise, extract the body and pass control to extract_while
1962 * to extend the iteration domain with an infinite loop.
1963 * If we were only able to extract part of the body, then simply
1964 * return that part.
1966 struct pet_scop *PetScan::extract(WhileStmt *stmt)
1968 Expr *cond;
1969 int test_nr, stmt_nr;
1970 isl_pw_aff *pa;
1971 struct pet_scop *scop_body;
1973 cond = stmt->getCond();
1974 if (!cond) {
1975 unsupported(stmt);
1976 return NULL;
1979 clear_assignments clear(assigned_value);
1980 clear.TraverseStmt(stmt->getBody());
1982 pa = try_extract_affine_condition(cond);
1983 if (pa)
1984 return extract_affine_while(pa, stmt->getBody());
1986 if (!allow_nested) {
1987 unsupported(stmt);
1988 return NULL;
1991 test_nr = n_test++;
1992 stmt_nr = n_stmt++;
1993 scop_body = extract(stmt->getBody());
1994 if (partial)
1995 return scop_body;
1997 return extract_while(cond, test_nr, stmt_nr, scop_body, NULL);
2000 /* Construct a generic while scop, with iteration domain
2001 * { [t] : t >= 0 } around "scop_body". The scop consists of two parts,
2002 * one for evaluating the condition "cond" and one for the body.
2003 * "test_nr" is the sequence number of the virtual test variable that contains
2004 * the result of the condition and "stmt_nr" is the sequence number
2005 * of the statement that evaluates the condition.
2006 * If "scop_inc" is not NULL, then it is added at the end of the body,
2007 * after replacing any skip conditions resulting from continue statements
2008 * by the skip conditions resulting from break statements (if any).
2010 * The schedule is adjusted to reflect that the condition is evaluated
2011 * before the body is executed and the body is filtered to depend
2012 * on the result of the condition evaluating to true on all iterations
2013 * up to the current iteration, while the evaluation of the condition itself
2014 * is filtered to depend on the result of the condition evaluating to true
2015 * on all previous iterations.
2016 * The context of the scop representing the body is dropped
2017 * because we don't know how many times the body will be executed,
2018 * if at all.
2020 * If the body contains any break, then it is taken into
2021 * account in infinite_domain (if the skip condition is affine)
2022 * or in scop_add_break (if the skip condition is not affine).
2024 struct pet_scop *PetScan::extract_while(Expr *cond, int test_nr, int stmt_nr,
2025 struct pet_scop *scop_body, struct pet_scop *scop_inc)
2027 isl_id *id, *id_test, *id_break_test;
2028 isl_set *domain;
2029 isl_aff *ident;
2030 isl_multi_pw_aff *test_index;
2031 struct pet_scop *scop;
2032 bool has_var_break;
2034 test_index = pet_create_test_index(ctx, test_nr);
2035 scop = extract_non_affine_condition(cond, stmt_nr,
2036 isl_multi_pw_aff_copy(test_index));
2037 scop = scop_add_array(scop, test_index, ast_context);
2038 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2039 isl_multi_pw_aff_free(test_index);
2041 id = isl_id_alloc(ctx, "t", NULL);
2042 domain = infinite_domain(isl_id_copy(id), scop_body);
2043 ident = identity_aff(domain);
2045 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2046 if (has_var_break)
2047 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2049 scop = pet_scop_prefix(scop, 0);
2050 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_aff_copy(ident),
2051 isl_aff_copy(ident), isl_id_copy(id));
2052 scop_body = pet_scop_reset_context(scop_body);
2053 scop_body = pet_scop_prefix(scop_body, 1);
2054 if (scop_inc) {
2055 scop_inc = pet_scop_prefix(scop_inc, 2);
2056 if (pet_scop_has_skip(scop_body, pet_skip_later)) {
2057 isl_multi_pw_aff *skip;
2058 skip = pet_scop_get_skip(scop_body, pet_skip_later);
2059 scop_body = pet_scop_set_skip(scop_body,
2060 pet_skip_now, skip);
2061 } else
2062 pet_scop_reset_skip(scop_body, pet_skip_now);
2063 scop_body = pet_scop_add_seq(ctx, scop_body, scop_inc);
2065 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2066 isl_aff_copy(ident), ident, id);
2068 if (has_var_break) {
2069 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2070 isl_set_copy(domain), isl_val_one(ctx));
2071 scop_body = scop_add_break(scop_body, id_break_test,
2072 isl_set_copy(domain), isl_val_one(ctx));
2074 scop = scop_add_while(scop, scop_body, id_test, domain,
2075 isl_val_one(ctx));
2077 return scop;
2080 /* Check whether "cond" expresses a simple loop bound
2081 * on the only set dimension.
2082 * In particular, if "up" is set then "cond" should contain only
2083 * upper bounds on the set dimension.
2084 * Otherwise, it should contain only lower bounds.
2086 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2088 if (isl_val_is_pos(inc))
2089 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2090 else
2091 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2094 /* Extend a condition on a given iteration of a loop to one that
2095 * imposes the same condition on all previous iterations.
2096 * "domain" expresses the lower [upper] bound on the iterations
2097 * when inc is positive [negative].
2099 * In particular, we construct the condition (when inc is positive)
2101 * forall i' : (domain(i') and i' <= i) => cond(i')
2103 * which is equivalent to
2105 * not exists i' : domain(i') and i' <= i and not cond(i')
2107 * We construct this set by negating cond, applying a map
2109 * { [i'] -> [i] : domain(i') and i' <= i }
2111 * and then negating the result again.
2113 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2114 __isl_take isl_set *domain, __isl_take isl_val *inc)
2116 isl_map *previous_to_this;
2118 if (isl_val_is_pos(inc))
2119 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2120 else
2121 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2123 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2125 cond = isl_set_complement(cond);
2126 cond = isl_set_apply(cond, previous_to_this);
2127 cond = isl_set_complement(cond);
2129 isl_val_free(inc);
2131 return cond;
2134 /* Construct a domain of the form
2136 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2138 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2139 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2141 isl_aff *aff;
2142 isl_space *dim;
2143 isl_set *set;
2145 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2146 dim = isl_pw_aff_get_domain_space(init);
2147 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2148 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2149 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2151 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2152 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2153 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2154 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2156 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2158 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2160 return isl_set_params(set);
2163 /* Assuming "cond" represents a bound on a loop where the loop
2164 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2165 * is possible.
2167 * Under the given assumptions, wrapping is only possible if "cond" allows
2168 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2169 * increasing iterator and 0 in case of a decreasing iterator.
2171 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2172 __isl_keep isl_val *inc)
2174 bool cw;
2175 isl_ctx *ctx;
2176 isl_val *limit;
2177 isl_set *test;
2179 test = isl_set_copy(cond);
2181 ctx = isl_set_get_ctx(test);
2182 if (isl_val_is_neg(inc))
2183 limit = isl_val_zero(ctx);
2184 else {
2185 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2186 limit = isl_val_2exp(limit);
2187 limit = isl_val_sub_ui(limit, 1);
2190 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2191 cw = !isl_set_is_empty(test);
2192 isl_set_free(test);
2194 return cw;
2197 /* Given a one-dimensional space, construct the following affine expression
2198 * on this space
2200 * { [v] -> [v mod 2^width] }
2202 * where width is the number of bits used to represent the values
2203 * of the unsigned variable "iv".
2205 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2206 ValueDecl *iv)
2208 isl_ctx *ctx;
2209 isl_val *mod;
2210 isl_aff *aff;
2212 ctx = isl_space_get_ctx(dim);
2213 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2214 mod = isl_val_2exp(mod);
2216 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2217 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2218 aff = isl_aff_mod_val(aff, mod);
2220 return aff;
2223 /* Project out the parameter "id" from "set".
2225 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2226 __isl_keep isl_id *id)
2228 int pos;
2230 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2231 if (pos >= 0)
2232 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2234 return set;
2237 /* Compute the set of parameters for which "set1" is a subset of "set2".
2239 * set1 is a subset of set2 if
2241 * forall i in set1 : i in set2
2243 * or
2245 * not exists i in set1 and i not in set2
2247 * i.e.,
2249 * not exists i in set1 \ set2
2251 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2252 __isl_take isl_set *set2)
2254 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2257 /* Compute the set of parameter values for which "cond" holds
2258 * on the next iteration for each element of "dom".
2260 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2261 * and then compute the set of parameters for which the result is a subset
2262 * of "cond".
2264 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2265 __isl_take isl_set *dom, __isl_take isl_val *inc)
2267 isl_space *space;
2268 isl_aff *aff;
2269 isl_map *next;
2271 space = isl_set_get_space(dom);
2272 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2273 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2274 aff = isl_aff_add_constant_val(aff, inc);
2275 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2277 dom = isl_set_apply(dom, next);
2279 return enforce_subset(dom, cond);
2282 /* Extract the for loop "stmt" as a while loop.
2283 * "iv" is the loop iterator. "init" is the initialization.
2284 * "inc" is the increment.
2286 * That is, the for loop has the form
2288 * for (iv = init; cond; iv += inc)
2289 * body;
2291 * and is treated as
2293 * iv = init;
2294 * while (cond) {
2295 * body;
2296 * iv += inc;
2299 * except that the skips resulting from any continue statements
2300 * in body do not apply to the increment, but are replaced by the skips
2301 * resulting from break statements.
2303 * If "iv" is declared in the for loop, then it is killed before
2304 * and after the loop.
2306 struct pet_scop *PetScan::extract_non_affine_for(ForStmt *stmt, ValueDecl *iv,
2307 __isl_take pet_expr *init, __isl_take pet_expr *inc)
2309 int declared;
2310 int test_nr, stmt_nr;
2311 pet_expr *expr_iv;
2312 struct pet_scop *scop_init, *scop_inc, *scop, *scop_body;
2313 int type_size;
2314 struct pet_array *array;
2315 struct pet_scop *scop_kill;
2317 if (!allow_nested) {
2318 unsupported(stmt);
2319 return NULL;
2322 clear_assignment(assigned_value, iv);
2324 declared = !initialization_assignment(stmt->getInit());
2326 expr_iv = extract_access_expr(iv);
2327 expr_iv = mark_write(expr_iv);
2328 type_size = pet_expr_get_type_size(expr_iv);
2329 init = pet_expr_new_binary(type_size, pet_op_assign, expr_iv, init);
2330 scop_init = extract(init, stmt->getInit()->getSourceRange(), false);
2331 scop_init = pet_scop_prefix(scop_init, declared);
2333 test_nr = n_test++;
2334 stmt_nr = n_stmt++;
2335 scop_body = extract(stmt->getBody());
2336 if (partial) {
2337 pet_scop_free(scop_init);
2338 return scop_body;
2341 expr_iv = extract_access_expr(iv);
2342 expr_iv = mark_write(expr_iv);
2343 type_size = pet_expr_get_type_size(expr_iv);
2344 inc = pet_expr_new_binary(type_size, pet_op_add_assign, expr_iv, inc);
2345 scop_inc = extract(inc, stmt->getInc()->getSourceRange(), false);
2346 if (!scop_inc) {
2347 pet_scop_free(scop_init);
2348 pet_scop_free(scop_body);
2349 return NULL;
2352 scop = extract_while(stmt->getCond(), test_nr, stmt_nr, scop_body,
2353 scop_inc);
2355 scop = pet_scop_prefix(scop, declared + 1);
2356 scop = pet_scop_add_seq(ctx, scop_init, scop);
2358 if (!declared)
2359 return scop;
2361 array = extract_array(ctx, iv, NULL);
2362 if (array)
2363 array->declared = 1;
2364 scop_kill = kill(stmt, array);
2365 scop_kill = pet_scop_prefix(scop_kill, 0);
2366 scop = pet_scop_add_seq(ctx, scop_kill, scop);
2367 scop_kill = kill(stmt, array);
2368 scop_kill = pet_scop_add_array(scop_kill, array);
2369 scop_kill = pet_scop_prefix(scop_kill, 3);
2370 scop = pet_scop_add_seq(ctx, scop, scop_kill);
2372 return scop;
2375 /* Construct a pet_scop for a for statement.
2376 * The for loop is required to be of one of the following forms
2378 * for (i = init; condition; ++i)
2379 * for (i = init; condition; --i)
2380 * for (i = init; condition; i += constant)
2381 * for (i = init; condition; i -= constant)
2383 * The initialization of the for loop should either be an assignment
2384 * of a static affine value to an integer variable, or a declaration
2385 * of such a variable with initialization.
2387 * If the initialization or the increment do not satisfy the above
2388 * conditions, i.e., if the initialization is not static affine
2389 * or the increment is not constant, then the for loop is extracted
2390 * as a while loop instead.
2392 * The condition is allowed to contain nested accesses, provided
2393 * they are not being written to inside the body of the loop.
2394 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2395 * essentially treated as a while loop, with iteration domain
2396 * { [i] : i >= init }.
2398 * We extract a pet_scop for the body and then embed it in a loop with
2399 * iteration domain and schedule
2401 * { [i] : i >= init and condition' }
2402 * { [i] -> [i] }
2404 * or
2406 * { [i] : i <= init and condition' }
2407 * { [i] -> [-i] }
2409 * Where condition' is equal to condition if the latter is
2410 * a simple upper [lower] bound and a condition that is extended
2411 * to apply to all previous iterations otherwise.
2413 * If the condition is non-affine, then we drop the condition from the
2414 * iteration domain and instead create a separate statement
2415 * for evaluating the condition. The body is then filtered to depend
2416 * on the result of the condition evaluating to true on all iterations
2417 * up to the current iteration, while the evaluation the condition itself
2418 * is filtered to depend on the result of the condition evaluating to true
2419 * on all previous iterations.
2420 * The context of the scop representing the body is dropped
2421 * because we don't know how many times the body will be executed,
2422 * if at all.
2424 * If the stride of the loop is not 1, then "i >= init" is replaced by
2426 * (exists a: i = init + stride * a and a >= 0)
2428 * If the loop iterator i is unsigned, then wrapping may occur.
2429 * We therefore use a virtual iterator instead that does not wrap.
2430 * However, the condition in the code applies
2431 * to the wrapped value, so we need to change condition(i)
2432 * into condition([i % 2^width]). Similarly, we replace all accesses
2433 * to the original iterator by the wrapping of the virtual iterator.
2434 * Note that there may be no need to perform this final wrapping
2435 * if the loop condition (after wrapping) satisfies certain conditions.
2436 * However, the is_simple_bound condition is not enough since it doesn't
2437 * check if there even is an upper bound.
2439 * Wrapping on unsigned iterators can be avoided entirely if
2440 * loop condition is simple, the loop iterator is incremented
2441 * [decremented] by one and the last value before wrapping cannot
2442 * possibly satisfy the loop condition.
2444 * Before extracting a pet_scop from the body we remove all
2445 * assignments in assigned_value to variables that are assigned
2446 * somewhere in the body of the loop.
2448 * Valid parameters for a for loop are those for which the initial
2449 * value itself, the increment on each domain iteration and
2450 * the condition on both the initial value and
2451 * the result of incrementing the iterator for each iteration of the domain
2452 * can be evaluated.
2453 * If the loop condition is non-affine, then we only consider validity
2454 * of the initial value.
2456 * If the body contains any break, then we keep track of it in "skip"
2457 * (if the skip condition is affine) or it is handled in scop_add_break
2458 * (if the skip condition is not affine).
2459 * Note that the affine break condition needs to be considered with
2460 * respect to previous iterations in the virtual domain (if any).
2462 * If we were only able to extract part of the body, then simply
2463 * return that part.
2465 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2467 BinaryOperator *ass;
2468 Decl *decl;
2469 Stmt *init;
2470 Expr *lhs, *rhs;
2471 ValueDecl *iv;
2472 isl_local_space *ls;
2473 isl_set *domain;
2474 isl_aff *sched;
2475 isl_set *cond = NULL;
2476 isl_set *skip = NULL;
2477 isl_id *id, *id_test = NULL, *id_break_test;
2478 struct pet_scop *scop, *scop_cond = NULL;
2479 assigned_value_cache cache(assigned_value);
2480 isl_val *inc;
2481 bool is_one;
2482 bool is_unsigned;
2483 bool is_simple;
2484 bool is_virtual;
2485 bool has_affine_break;
2486 bool has_var_break;
2487 isl_aff *wrap = NULL;
2488 isl_pw_aff *pa, *pa_inc, *init_val;
2489 isl_set *valid_init;
2490 isl_set *valid_cond;
2491 isl_set *valid_cond_init;
2492 isl_set *valid_cond_next;
2493 isl_set *valid_inc;
2494 int stmt_id;
2495 pet_expr *pe_init, *pe_inc;
2496 pet_context *pc, *pc_init_val;
2498 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2499 return extract_infinite_for(stmt);
2501 init = stmt->getInit();
2502 if (!init) {
2503 unsupported(stmt);
2504 return NULL;
2506 if ((ass = initialization_assignment(init)) != NULL) {
2507 iv = extract_induction_variable(ass);
2508 if (!iv)
2509 return NULL;
2510 lhs = ass->getLHS();
2511 rhs = ass->getRHS();
2512 } else if ((decl = initialization_declaration(init)) != NULL) {
2513 VarDecl *var = extract_induction_variable(init, decl);
2514 if (!var)
2515 return NULL;
2516 iv = var;
2517 rhs = var->getInit();
2518 lhs = create_DeclRefExpr(var);
2519 } else {
2520 unsupported(stmt->getInit());
2521 return NULL;
2524 id = create_decl_id(ctx, iv);
2526 assigned_value.erase(iv);
2527 clear_assignments clear(assigned_value);
2528 clear.TraverseStmt(stmt->getBody());
2530 pe_init = extract_expr(rhs);
2531 pe_inc = extract_increment(stmt, iv);
2532 pc = convert_assignments(ctx, assigned_value);
2533 pc_init_val = pet_context_copy(pc);
2534 pc_init_val = pet_context_mark_unknown(pc_init_val, isl_id_copy(id));
2535 init_val = pet_expr_extract_affine(pe_init, pc_init_val);
2536 pet_context_free(pc_init_val);
2537 pa_inc = pet_expr_extract_affine(pe_inc, pc);
2538 pet_context_free(pc);
2539 inc = pet_extract_cst(pa_inc);
2540 if (!pe_init || !pe_inc || !inc || isl_val_is_nan(inc) ||
2541 isl_pw_aff_involves_nan(pa_inc) ||
2542 isl_pw_aff_involves_nan(init_val)) {
2543 isl_id_free(id);
2544 isl_val_free(inc);
2545 isl_pw_aff_free(pa_inc);
2546 isl_pw_aff_free(init_val);
2547 if (pe_init && pe_inc && !(pa_inc && !inc))
2548 return extract_non_affine_for(stmt, iv,
2549 pe_init, pe_inc);
2550 pet_expr_free(pe_init);
2551 pet_expr_free(pe_inc);
2552 return NULL;
2554 pet_expr_free(pe_init);
2555 pet_expr_free(pe_inc);
2557 pa = try_extract_nested_condition(stmt->getCond());
2558 if (allow_nested && (!pa || pet_nested_any_in_pw_aff(pa)))
2559 stmt_id = n_stmt++;
2561 scop = extract(stmt->getBody());
2562 if (partial) {
2563 isl_id_free(id);
2564 isl_pw_aff_free(init_val);
2565 isl_pw_aff_free(pa_inc);
2566 isl_pw_aff_free(pa);
2567 isl_val_free(inc);
2568 return scop;
2571 valid_inc = isl_pw_aff_domain(pa_inc);
2573 is_unsigned = iv->getType()->isUnsignedIntegerType();
2575 has_affine_break = scop &&
2576 pet_scop_has_affine_skip(scop, pet_skip_later);
2577 if (has_affine_break)
2578 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2579 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
2580 if (has_var_break)
2581 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
2583 if (pa && !is_nested_allowed(pa, scop)) {
2584 isl_pw_aff_free(pa);
2585 pa = NULL;
2588 if (!allow_nested && !pa)
2589 pa = try_extract_affine_condition(stmt->getCond());
2590 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2591 cond = isl_pw_aff_non_zero_set(pa);
2592 if (allow_nested && !cond) {
2593 isl_multi_pw_aff *test_index;
2594 int save_n_stmt = n_stmt;
2595 test_index = pet_create_test_index(ctx, n_test++);
2596 n_stmt = stmt_id;
2597 scop_cond = extract_non_affine_condition(stmt->getCond(),
2598 n_stmt++, isl_multi_pw_aff_copy(test_index));
2599 n_stmt = save_n_stmt;
2600 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
2601 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
2602 isl_dim_out);
2603 isl_multi_pw_aff_free(test_index);
2604 scop_cond = pet_scop_prefix(scop_cond, 0);
2605 scop = pet_scop_reset_context(scop);
2606 scop = pet_scop_prefix(scop, 1);
2607 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2610 cond = embed(cond, isl_id_copy(id));
2611 skip = embed(skip, isl_id_copy(id));
2612 valid_cond = isl_set_coalesce(valid_cond);
2613 valid_cond = embed(valid_cond, isl_id_copy(id));
2614 valid_inc = embed(valid_inc, isl_id_copy(id));
2615 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
2616 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2618 valid_cond_init = enforce_subset(
2619 isl_map_range(isl_map_from_pw_aff(isl_pw_aff_copy(init_val))),
2620 isl_set_copy(valid_cond));
2621 if (is_one && !is_virtual) {
2622 isl_pw_aff_free(init_val);
2623 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
2624 lhs, rhs, init);
2625 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2626 valid_init = set_project_out_by_id(valid_init, id);
2627 domain = isl_pw_aff_non_zero_set(pa);
2628 } else {
2629 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2630 domain = strided_domain(isl_id_copy(id), init_val,
2631 isl_val_copy(inc));
2634 domain = embed(domain, isl_id_copy(id));
2635 if (is_virtual) {
2636 isl_map *rev_wrap;
2637 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2638 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
2639 rev_wrap = isl_map_reverse(rev_wrap);
2640 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2641 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
2642 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2643 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2645 is_simple = is_simple_bound(cond, inc);
2646 if (!is_simple) {
2647 cond = isl_set_gist(cond, isl_set_copy(domain));
2648 is_simple = is_simple_bound(cond, inc);
2650 if (!is_simple)
2651 cond = valid_for_each_iteration(cond,
2652 isl_set_copy(domain), isl_val_copy(inc));
2653 domain = isl_set_intersect(domain, cond);
2654 if (has_affine_break) {
2655 skip = isl_set_intersect(skip , isl_set_copy(domain));
2656 skip = after(skip, isl_val_sgn(inc));
2657 domain = isl_set_subtract(domain, skip);
2659 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2660 ls = isl_local_space_from_space(isl_set_get_space(domain));
2661 sched = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2662 if (isl_val_is_neg(inc))
2663 sched = isl_aff_neg(sched);
2665 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
2666 isl_val_copy(inc));
2667 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2669 if (!is_virtual)
2670 wrap = identity_aff(domain);
2672 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
2673 isl_aff_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
2674 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
2675 scop = resolve_nested(scop);
2676 if (has_var_break)
2677 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
2678 isl_val_copy(inc));
2679 if (id_test) {
2680 scop = scop_add_while(scop_cond, scop, id_test, domain,
2681 isl_val_copy(inc));
2682 isl_set_free(valid_inc);
2683 } else {
2684 scop = pet_scop_restrict_context(scop, valid_inc);
2685 scop = pet_scop_restrict_context(scop, valid_cond_next);
2686 scop = pet_scop_restrict_context(scop, valid_cond_init);
2687 isl_set_free(domain);
2689 clear_assignment(assigned_value, iv);
2691 isl_val_free(inc);
2693 scop = pet_scop_restrict_context(scop, isl_set_params(valid_init));
2695 return scop;
2698 /* Try and construct a pet_scop corresponding to a compound statement.
2700 * "skip_declarations" is set if we should skip initial declarations
2701 * in the children of the compound statements. This then implies
2702 * that this sequence of children should not be treated as a block
2703 * since the initial statements may be skipped.
2705 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
2707 return extract(stmt->children(), !skip_declarations, skip_declarations);
2710 /* For each nested access parameter in "space",
2711 * construct a corresponding pet_expr, place it in args and
2712 * record its position in "param2pos".
2713 * "n_arg" is the number of elements that are already in args.
2714 * The position recorded in "param2pos" takes this number into account.
2715 * If the pet_expr corresponding to a parameter is identical to
2716 * the pet_expr corresponding to an earlier parameter, then these two
2717 * parameters are made to refer to the same element in args.
2719 * Return the final number of elements in args or -1 if an error has occurred.
2721 int PetScan::extract_nested(__isl_keep isl_space *space,
2722 int n_arg, pet_expr **args, std::map<int,int> &param2pos)
2724 int nparam;
2726 nparam = isl_space_dim(space, isl_dim_param);
2727 for (int i = 0; i < nparam; ++i) {
2728 int j;
2729 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2731 if (!pet_nested_in_id(id)) {
2732 isl_id_free(id);
2733 continue;
2736 args[n_arg] = pet_nested_extract_expr(id);
2737 isl_id_free(id);
2738 if (!args[n_arg])
2739 return -1;
2741 for (j = 0; j < n_arg; ++j)
2742 if (pet_expr_is_equal(args[j], args[n_arg]))
2743 break;
2745 if (j < n_arg) {
2746 pet_expr_free(args[n_arg]);
2747 args[n_arg] = NULL;
2748 param2pos[i] = j;
2749 } else
2750 param2pos[i] = n_arg++;
2753 return n_arg;
2756 /* For each nested access parameter in the access relations in "expr",
2757 * construct a corresponding pet_expr, append it to the arguments of "expr"
2758 * and record its position in "param2pos" (relative to the initial
2759 * number of arguments).
2760 * n is the number of nested access parameters.
2762 __isl_give pet_expr *PetScan::extract_nested(__isl_take pet_expr *expr, int n,
2763 std::map<int,int> &param2pos)
2765 isl_space *space;
2766 int i, n_arg;
2767 pet_expr **args;
2769 args = isl_calloc_array(ctx, pet_expr *, n);
2770 if (!args)
2771 return pet_expr_free(expr);
2773 n_arg = pet_expr_get_n_arg(expr);
2774 space = pet_expr_access_get_parameter_space(expr);
2775 n = extract_nested(space, 0, args, param2pos);
2776 isl_space_free(space);
2778 if (n < 0)
2779 expr = pet_expr_free(expr);
2780 else
2781 expr = pet_expr_set_n_arg(expr, n_arg + n);
2783 for (i = 0; i < n; ++i)
2784 expr = pet_expr_set_arg(expr, n_arg + i, args[i]);
2785 free(args);
2787 return expr;
2790 /* Are "expr1" and "expr2" both array accesses such that
2791 * the access relation of "expr1" is a subset of that of "expr2"?
2792 * Only take into account the first "n_arg" arguments.
2794 static int is_sub_access(__isl_keep pet_expr *expr1, __isl_keep pet_expr *expr2,
2795 int n_arg)
2797 isl_id *id1, *id2;
2798 isl_map *access1, *access2;
2799 int is_subset;
2800 int i, n1, n2;
2802 if (!expr1 || !expr2)
2803 return 0;
2804 if (pet_expr_get_type(expr1) != pet_expr_access)
2805 return 0;
2806 if (pet_expr_get_type(expr2) != pet_expr_access)
2807 return 0;
2808 if (pet_expr_is_affine(expr1))
2809 return 0;
2810 if (pet_expr_is_affine(expr2))
2811 return 0;
2812 n1 = pet_expr_get_n_arg(expr1);
2813 if (n1 > n_arg)
2814 n1 = n_arg;
2815 n2 = pet_expr_get_n_arg(expr2);
2816 if (n2 > n_arg)
2817 n2 = n_arg;
2818 if (n1 != n2)
2819 return 0;
2820 for (i = 0; i < n1; ++i) {
2821 pet_expr *arg1, *arg2;
2822 int equal;
2823 arg1 = pet_expr_get_arg(expr1, i);
2824 arg2 = pet_expr_get_arg(expr2, i);
2825 equal = pet_expr_is_equal(arg1, arg2);
2826 pet_expr_free(arg1);
2827 pet_expr_free(arg2);
2828 if (equal < 0 || !equal)
2829 return equal;
2831 id1 = pet_expr_access_get_id(expr1);
2832 id2 = pet_expr_access_get_id(expr2);
2833 isl_id_free(id1);
2834 isl_id_free(id2);
2835 if (!id1 || !id2)
2836 return 0;
2837 if (id1 != id2)
2838 return 0;
2840 access1 = pet_expr_access_get_access(expr1);
2841 access2 = pet_expr_access_get_access(expr2);
2842 is_subset = isl_map_is_subset(access1, access2);
2843 isl_map_free(access1);
2844 isl_map_free(access2);
2846 return is_subset;
2849 /* Mark self dependences among the arguments of "expr" starting at "first".
2850 * These arguments have already been added to the list of arguments
2851 * but are not yet referenced directly from the index expression.
2852 * Instead, they are still referenced through parameters encoding
2853 * nested accesses.
2855 * In particular, if "expr" is a read access, then check the arguments
2856 * starting at "first" to see if "expr" accesses a subset of
2857 * the elements accessed by the argument, or under more restrictive conditions.
2858 * If so, then this nested access can be removed from the constraints
2859 * governing the outer access. There is no point in restricting
2860 * accesses to an array if in order to evaluate the restriction,
2861 * we have to access the same elements (or more).
2863 * Rather than removing the argument at this point (which would
2864 * complicate the resolution of the other nested accesses), we simply
2865 * mark it here by replacing it by a NaN pet_expr.
2866 * These NaNs are then later removed in remove_marked_self_dependences.
2868 static __isl_give pet_expr *mark_self_dependences(__isl_take pet_expr *expr,
2869 int first)
2871 int n;
2873 if (pet_expr_access_is_write(expr))
2874 return expr;
2876 n = pet_expr_get_n_arg(expr);
2877 for (int i = first; i < n; ++i) {
2878 int mark;
2879 pet_expr *arg;
2881 arg = pet_expr_get_arg(expr, i);
2882 mark = is_sub_access(expr, arg, first);
2883 pet_expr_free(arg);
2884 if (mark < 0)
2885 return pet_expr_free(expr);
2886 if (!mark)
2887 continue;
2889 arg = pet_expr_new_int(isl_val_nan(pet_expr_get_ctx(expr)));
2890 expr = pet_expr_set_arg(expr, i, arg);
2893 return expr;
2896 /* Is "expr" a NaN integer expression?
2898 static int expr_is_nan(__isl_keep pet_expr *expr)
2900 isl_val *v;
2901 int is_nan;
2903 if (pet_expr_get_type(expr) != pet_expr_int)
2904 return 0;
2906 v = pet_expr_int_get_val(expr);
2907 is_nan = isl_val_is_nan(v);
2908 isl_val_free(v);
2910 return is_nan;
2913 /* Check if we have marked any self dependences (as NaNs)
2914 * in mark_self_dependences and remove them here.
2915 * It is safe to project them out since these arguments
2916 * can at most be referenced from the condition of the access relation,
2917 * but do not appear in the index expression.
2918 * "dim" is the dimension of the iteration domain.
2920 static __isl_give pet_expr *remove_marked_self_dependences(
2921 __isl_take pet_expr *expr, int dim, int first)
2923 int n;
2925 n = pet_expr_get_n_arg(expr);
2926 for (int i = n - 1; i >= first; --i) {
2927 int is_nan;
2928 pet_expr *arg;
2930 arg = pet_expr_get_arg(expr, i);
2931 is_nan = expr_is_nan(arg);
2932 pet_expr_free(arg);
2933 if (!is_nan)
2934 continue;
2935 expr = pet_expr_access_project_out_arg(expr, dim, i);
2938 return expr;
2941 /* Look for parameters in any access relation in "expr" that
2942 * refer to nested accesses. In particular, these are
2943 * parameters with name "__pet_expr".
2945 * If there are any such parameters, then the domain of the index
2946 * expression and the access relation, which is either [] or
2947 * [[] -> [a_1,...,a_m]] at this point, is replaced by [[] -> [t_1,...,t_n]] or
2948 * [[] -> [a_1,...,a_m,t_1,...,t_n]], with m the original number of arguments
2949 * (n_arg) and n the number of these parameters
2950 * (after identifying identical nested accesses).
2952 * This transformation is performed in several steps.
2953 * We first extract the arguments in extract_nested.
2954 * param2pos maps the original parameter position to the position
2955 * of the argument beyond the initial (n_arg) number of arguments.
2956 * Then we move these parameters to input dimensions.
2957 * t2pos maps the positions of these temporary input dimensions
2958 * to the positions of the corresponding arguments.
2959 * Finally, we express these temporary dimensions in terms of the domain
2960 * [[] -> [a_1,...,a_m,t_1,...,t_n]] and precompose index expression and access
2961 * relations with this function.
2963 __isl_give pet_expr *PetScan::resolve_nested(__isl_take pet_expr *expr)
2965 int n, n_arg;
2966 int nparam;
2967 isl_space *space;
2968 isl_local_space *ls;
2969 isl_aff *aff;
2970 isl_multi_aff *ma;
2971 std::map<int,int> param2pos;
2972 std::map<int,int> t2pos;
2974 if (!expr)
2975 return expr;
2977 n_arg = pet_expr_get_n_arg(expr);
2978 for (int i = 0; i < n_arg; ++i) {
2979 pet_expr *arg;
2980 arg = pet_expr_get_arg(expr, i);
2981 arg = resolve_nested(arg);
2982 expr = pet_expr_set_arg(expr, i, arg);
2985 if (pet_expr_get_type(expr) != pet_expr_access)
2986 return expr;
2988 space = pet_expr_access_get_parameter_space(expr);
2989 n = pet_nested_n_in_space(space);
2990 isl_space_free(space);
2991 if (n == 0)
2992 return expr;
2994 expr = extract_nested(expr, n, param2pos);
2995 if (!expr)
2996 return NULL;
2998 expr = pet_expr_access_align_params(expr);
2999 expr = mark_self_dependences(expr, n_arg);
3000 if (!expr)
3001 return NULL;
3003 n = 0;
3004 space = pet_expr_access_get_parameter_space(expr);
3005 nparam = isl_space_dim(space, isl_dim_param);
3006 for (int i = nparam - 1; i >= 0; --i) {
3007 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3008 if (!pet_nested_in_id(id)) {
3009 isl_id_free(id);
3010 continue;
3013 expr = pet_expr_access_move_dims(expr,
3014 isl_dim_in, n_arg + n, isl_dim_param, i, 1);
3015 t2pos[n] = n_arg + param2pos[i];
3016 n++;
3018 isl_id_free(id);
3020 isl_space_free(space);
3022 space = pet_expr_access_get_parameter_space(expr);
3023 space = isl_space_set_from_params(space);
3024 space = isl_space_add_dims(space, isl_dim_set,
3025 pet_expr_get_n_arg(expr));
3026 space = isl_space_wrap(isl_space_from_range(space));
3027 ls = isl_local_space_from_space(isl_space_copy(space));
3028 space = isl_space_from_domain(space);
3029 space = isl_space_add_dims(space, isl_dim_out, n_arg + n);
3030 ma = isl_multi_aff_zero(space);
3032 for (int i = 0; i < n_arg; ++i) {
3033 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3034 isl_dim_set, i);
3035 ma = isl_multi_aff_set_aff(ma, i, aff);
3037 for (int i = 0; i < n; ++i) {
3038 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3039 isl_dim_set, t2pos[i]);
3040 ma = isl_multi_aff_set_aff(ma, n_arg + i, aff);
3042 isl_local_space_free(ls);
3044 expr = pet_expr_access_pullback_multi_aff(expr, ma);
3046 expr = remove_marked_self_dependences(expr, 0, n_arg);
3048 return expr;
3051 /* Return the file offset of the expansion location of "Loc".
3053 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3055 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3058 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3060 /* Return a SourceLocation for the location after the first semicolon
3061 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3062 * call it and also skip trailing spaces and newline.
3064 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3065 const LangOptions &LO)
3067 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3070 #else
3072 /* Return a SourceLocation for the location after the first semicolon
3073 * after "loc". If Lexer::findLocationAfterToken is not available,
3074 * we look in the underlying character data for the first semicolon.
3076 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3077 const LangOptions &LO)
3079 const char *semi;
3080 const char *s = SM.getCharacterData(loc);
3082 semi = strchr(s, ';');
3083 if (!semi)
3084 return SourceLocation();
3085 return loc.getFileLocWithOffset(semi + 1 - s);
3088 #endif
3090 /* If the token at "loc" is the first token on the line, then return
3091 * a location referring to the start of the line.
3092 * Otherwise, return "loc".
3094 * This function is used to extend a scop to the start of the line
3095 * if the first token of the scop is also the first token on the line.
3097 * We look for the first token on the line. If its location is equal to "loc",
3098 * then the latter is the location of the first token on the line.
3100 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3101 SourceManager &SM, const LangOptions &LO)
3103 std::pair<FileID, unsigned> file_offset_pair;
3104 llvm::StringRef file;
3105 const char *pos;
3106 Token tok;
3107 SourceLocation token_loc, line_loc;
3108 int col;
3110 loc = SM.getExpansionLoc(loc);
3111 col = SM.getExpansionColumnNumber(loc);
3112 line_loc = loc.getLocWithOffset(1 - col);
3113 file_offset_pair = SM.getDecomposedLoc(line_loc);
3114 file = SM.getBufferData(file_offset_pair.first, NULL);
3115 pos = file.data() + file_offset_pair.second;
3117 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3118 file.begin(), pos, file.end());
3119 lexer.LexFromRawLexer(tok);
3120 token_loc = tok.getLocation();
3122 if (token_loc == loc)
3123 return line_loc;
3124 else
3125 return loc;
3128 /* If "expr" is an assume expression, then try and convert
3129 * its single argument to an affine expression.
3131 __isl_give pet_expr *PetScan::resolve_assume(__isl_take pet_expr *expr)
3133 pet_context *pc;
3135 if (!expr)
3136 return NULL;
3137 if (!pet_expr_is_assume(expr))
3138 return expr;
3140 pc = convert_assignments(ctx, assigned_value);
3141 expr = pet_expr_resolve_assume(expr, pc);
3142 pet_context_free(pc);
3144 return expr;
3147 /* Update start and end of "scop" to include the region covered by "range".
3148 * If "skip_semi" is set, then we assume "range" is followed by
3149 * a semicolon and also include this semicolon.
3151 struct pet_scop *PetScan::update_scop_start_end(struct pet_scop *scop,
3152 SourceRange range, bool skip_semi)
3154 SourceLocation loc = range.getBegin();
3155 SourceManager &SM = PP.getSourceManager();
3156 const LangOptions &LO = PP.getLangOpts();
3157 unsigned start, end;
3159 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3160 start = getExpansionOffset(SM, loc);
3161 loc = range.getEnd();
3162 if (skip_semi)
3163 loc = location_after_semi(loc, SM, LO);
3164 else
3165 loc = PP.getLocForEndOfToken(loc);
3166 end = getExpansionOffset(SM, loc);
3168 scop = pet_scop_update_start_end(scop, start, end);
3169 return scop;
3172 /* Convert a top-level pet_expr to a pet_scop with one statement.
3173 * This mainly involves resolving nested expression parameters
3174 * and setting the name of the iteration space.
3175 * The name is given by "label" if it is non-NULL. Otherwise,
3176 * it is of the form S_<n_stmt>.
3177 * start and end of the pet_scop are derived from "range" and "skip_semi".
3178 * In particular, if "skip_semi" is set then the semicolon following "range"
3179 * is also included.
3181 struct pet_scop *PetScan::extract(__isl_take pet_expr *expr, SourceRange range,
3182 bool skip_semi, __isl_take isl_id *label)
3184 struct pet_stmt *ps;
3185 struct pet_scop *scop;
3186 SourceLocation loc = range.getBegin();
3187 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3188 pet_context *pc;
3190 pc = convert_assignments(ctx, assigned_value);
3191 expr = pet_expr_plug_in_args(expr, pc);
3192 pet_context_free(pc);
3194 expr = resolve_nested(expr);
3195 expr = resolve_assume(expr);
3196 ps = pet_stmt_from_pet_expr(line, label, n_stmt++, expr);
3197 scop = pet_scop_from_pet_stmt(ctx, ps);
3199 scop = update_scop_start_end(scop, range, skip_semi);
3200 return scop;
3203 /* Check if we can extract an affine constraint from "expr".
3204 * Return the constraint as an isl_set if we can and NULL otherwise.
3205 * We turn on autodetection so that we won't generate any warnings
3206 * and turn off nesting, so that we won't accept any non-affine constructs.
3208 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3210 isl_pw_aff *cond;
3211 int save_autodetect = options->autodetect;
3212 bool save_nesting = nesting_enabled;
3214 options->autodetect = 1;
3215 nesting_enabled = false;
3217 cond = extract_condition(expr);
3219 options->autodetect = save_autodetect;
3220 nesting_enabled = save_nesting;
3222 return cond;
3225 /* Check whether "expr" is an affine constraint.
3227 bool PetScan::is_affine_condition(Expr *expr)
3229 isl_pw_aff *cond;
3231 cond = try_extract_affine_condition(expr);
3232 isl_pw_aff_free(cond);
3234 return cond != NULL;
3237 /* Check if we can extract a condition from "expr".
3238 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3239 * If allow_nested is set, then the condition may involve parameters
3240 * corresponding to nested accesses.
3241 * We turn on autodetection so that we won't generate any warnings.
3243 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3245 isl_pw_aff *cond;
3246 int save_autodetect = options->autodetect;
3247 bool save_nesting = nesting_enabled;
3249 options->autodetect = 1;
3250 nesting_enabled = allow_nested;
3251 cond = extract_condition(expr);
3253 options->autodetect = save_autodetect;
3254 nesting_enabled = save_nesting;
3256 return cond;
3259 /* If the top-level expression of "stmt" is an assignment, then
3260 * return that assignment as a BinaryOperator.
3261 * Otherwise return NULL.
3263 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3265 BinaryOperator *ass;
3267 if (!stmt)
3268 return NULL;
3269 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3270 return NULL;
3272 ass = cast<BinaryOperator>(stmt);
3273 if(ass->getOpcode() != BO_Assign)
3274 return NULL;
3276 return ass;
3279 /* Check if the given if statement is a conditional assignement
3280 * with a non-affine condition. If so, construct a pet_scop
3281 * corresponding to this conditional assignment. Otherwise return NULL.
3283 * In particular we check if "stmt" is of the form
3285 * if (condition)
3286 * a = f(...);
3287 * else
3288 * a = g(...);
3290 * where a is some array or scalar access.
3291 * The constructed pet_scop then corresponds to the expression
3293 * a = condition ? f(...) : g(...)
3295 * All access relations in f(...) are intersected with condition
3296 * while all access relation in g(...) are intersected with the complement.
3298 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3300 BinaryOperator *ass_then, *ass_else;
3301 pet_expr *write_then, *write_else;
3302 isl_set *cond, *comp;
3303 isl_multi_pw_aff *index;
3304 isl_pw_aff *pa;
3305 int equal;
3306 int type_size;
3307 pet_expr *pe_cond, *pe_then, *pe_else, *pe;
3308 bool save_nesting = nesting_enabled;
3310 if (!options->detect_conditional_assignment)
3311 return NULL;
3313 ass_then = top_assignment_or_null(stmt->getThen());
3314 ass_else = top_assignment_or_null(stmt->getElse());
3316 if (!ass_then || !ass_else)
3317 return NULL;
3319 if (is_affine_condition(stmt->getCond()))
3320 return NULL;
3322 write_then = extract_access_expr(ass_then->getLHS());
3323 write_else = extract_access_expr(ass_else->getLHS());
3325 equal = pet_expr_is_equal(write_then, write_else);
3326 pet_expr_free(write_else);
3327 if (equal < 0 || !equal) {
3328 pet_expr_free(write_then);
3329 return NULL;
3332 nesting_enabled = allow_nested;
3333 pa = extract_condition(stmt->getCond());
3334 nesting_enabled = save_nesting;
3335 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3336 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3337 index = isl_multi_pw_aff_from_pw_aff(pa);
3339 pe_cond = pet_expr_from_index(index);
3341 pe_then = extract_expr(ass_then->getRHS());
3342 pe_then = pet_expr_restrict(pe_then, cond);
3343 pe_else = extract_expr(ass_else->getRHS());
3344 pe_else = pet_expr_restrict(pe_else, comp);
3346 pe = pet_expr_new_ternary(pe_cond, pe_then, pe_else);
3347 write_then = pet_expr_access_set_write(write_then, 1);
3348 write_then = pet_expr_access_set_read(write_then, 0);
3349 type_size = get_type_size(ass_then->getType(), ast_context);
3350 pe = pet_expr_new_binary(type_size, pet_op_assign, write_then, pe);
3351 return extract(pe, stmt->getSourceRange(), false);
3354 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3355 * evaluating "cond" and writing the result to a virtual scalar,
3356 * as expressed by "index".
3358 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond, int stmt_nr,
3359 __isl_take isl_multi_pw_aff *index)
3361 pet_expr *expr, *write;
3362 struct pet_stmt *ps;
3363 SourceLocation loc = cond->getLocStart();
3364 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3365 pet_context *pc;
3367 write = pet_expr_from_index(index);
3368 write = pet_expr_access_set_write(write, 1);
3369 write = pet_expr_access_set_read(write, 0);
3370 expr = extract_expr(cond);
3372 pc = convert_assignments(ctx, assigned_value);
3373 expr = pet_expr_plug_in_args(expr, pc);
3374 pet_context_free(pc);
3376 expr = resolve_nested(expr);
3377 expr = pet_expr_new_binary(1, pet_op_assign, write, expr);
3378 ps = pet_stmt_from_pet_expr(line, NULL, stmt_nr, expr);
3379 return pet_scop_from_pet_stmt(ctx, ps);
3382 extern "C" {
3383 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr,
3384 void *user);
3387 /* Precompose the access relation and the index expression associated
3388 * to "expr" with the function pointed to by "user",
3389 * thereby embedding the access relation in the domain of this function.
3390 * The initial domain of the access relation and the index expression
3391 * is the zero-dimensional domain.
3393 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr, void *user)
3395 isl_multi_aff *ma = (isl_multi_aff *) user;
3397 return pet_expr_access_pullback_multi_aff(expr, isl_multi_aff_copy(ma));
3400 /* Precompose all access relations in "expr" with "ma", thereby
3401 * embedding them in the domain of "ma".
3403 static __isl_give pet_expr *embed(__isl_take pet_expr *expr,
3404 __isl_keep isl_multi_aff *ma)
3406 return pet_expr_map_access(expr, &embed_access, ma);
3409 /* For each nested access parameter in the domain of "stmt",
3410 * construct a corresponding pet_expr, place it before the original
3411 * elements in stmt->args and record its position in "param2pos".
3412 * n is the number of nested access parameters.
3414 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3415 std::map<int,int> &param2pos)
3417 int i;
3418 isl_space *space;
3419 int n_arg;
3420 pet_expr **args;
3422 n_arg = stmt->n_arg;
3423 args = isl_calloc_array(ctx, pet_expr *, n + n_arg);
3424 if (!args)
3425 goto error;
3427 space = isl_set_get_space(stmt->domain);
3428 n_arg = extract_nested(space, 0, args, param2pos);
3429 isl_space_free(space);
3431 if (n_arg < 0)
3432 goto error;
3434 for (i = 0; i < stmt->n_arg; ++i)
3435 args[n_arg + i] = stmt->args[i];
3436 free(stmt->args);
3437 stmt->args = args;
3438 stmt->n_arg += n_arg;
3440 return stmt;
3441 error:
3442 if (args) {
3443 for (i = 0; i < n; ++i)
3444 pet_expr_free(args[i]);
3445 free(args);
3447 pet_stmt_free(stmt);
3448 return NULL;
3451 /* Check whether any of the arguments i of "stmt" starting at position "n"
3452 * is equal to one of the first "n" arguments j.
3453 * If so, combine the constraints on arguments i and j and remove
3454 * argument i.
3456 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3458 int i, j;
3459 isl_map *map;
3461 if (!stmt)
3462 return NULL;
3463 if (n == 0)
3464 return stmt;
3465 if (n == stmt->n_arg)
3466 return stmt;
3468 map = isl_set_unwrap(stmt->domain);
3470 for (i = stmt->n_arg - 1; i >= n; --i) {
3471 for (j = 0; j < n; ++j)
3472 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3473 break;
3474 if (j >= n)
3475 continue;
3477 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3478 map = isl_map_project_out(map, isl_dim_out, i, 1);
3480 pet_expr_free(stmt->args[i]);
3481 for (j = i; j + 1 < stmt->n_arg; ++j)
3482 stmt->args[j] = stmt->args[j + 1];
3483 stmt->n_arg--;
3486 stmt->domain = isl_map_wrap(map);
3487 if (!stmt->domain)
3488 goto error;
3489 return stmt;
3490 error:
3491 pet_stmt_free(stmt);
3492 return NULL;
3495 /* Look for parameters in the iteration domain of "stmt" that
3496 * refer to nested accesses. In particular, these are
3497 * parameters with name "__pet_expr".
3499 * If there are any such parameters, then as many extra variables
3500 * (after identifying identical nested accesses) are inserted in the
3501 * range of the map wrapped inside the domain, before the original variables.
3502 * If the original domain is not a wrapped map, then a new wrapped
3503 * map is created with zero output dimensions.
3504 * The parameters are then equated to the corresponding output dimensions
3505 * and subsequently projected out, from the iteration domain,
3506 * the schedule and the access relations.
3507 * For each of the output dimensions, a corresponding argument
3508 * expression is inserted. Initially they are created with
3509 * a zero-dimensional domain, so they have to be embedded
3510 * in the current iteration domain.
3511 * param2pos maps the position of the parameter to the position
3512 * of the corresponding output dimension in the wrapped map.
3514 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3516 int n;
3517 int nparam;
3518 unsigned n_arg;
3519 isl_map *map;
3520 isl_space *space;
3521 isl_multi_aff *ma;
3522 std::map<int,int> param2pos;
3524 if (!stmt)
3525 return NULL;
3527 n = pet_nested_n_in_set(stmt->domain);
3528 if (n == 0)
3529 return stmt;
3531 n_arg = stmt->n_arg;
3532 stmt = extract_nested(stmt, n, param2pos);
3533 if (!stmt)
3534 return NULL;
3536 n = stmt->n_arg - n_arg;
3537 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3538 if (isl_set_is_wrapping(stmt->domain))
3539 map = isl_set_unwrap(stmt->domain);
3540 else
3541 map = isl_map_from_domain(stmt->domain);
3542 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3544 for (int i = nparam - 1; i >= 0; --i) {
3545 isl_id *id;
3547 if (!pet_nested_in_map(map, i))
3548 continue;
3550 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
3551 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3552 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3553 param2pos[i]);
3554 map = isl_map_project_out(map, isl_dim_param, i, 1);
3557 stmt->domain = isl_map_wrap(map);
3559 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
3560 space = isl_space_from_domain(isl_space_domain(space));
3561 ma = isl_multi_aff_zero(space);
3562 for (int pos = 0; pos < n; ++pos)
3563 stmt->args[pos] = embed(stmt->args[pos], ma);
3564 isl_multi_aff_free(ma);
3566 stmt = pet_stmt_remove_nested_parameters(stmt);
3567 stmt = remove_duplicate_arguments(stmt, n);
3569 return stmt;
3572 /* For each statement in "scop", move the parameters that correspond
3573 * to nested access into the ranges of the domains and create
3574 * corresponding argument expressions.
3576 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3578 if (!scop)
3579 return NULL;
3581 for (int i = 0; i < scop->n_stmt; ++i) {
3582 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3583 if (!scop->stmts[i])
3584 goto error;
3587 return scop;
3588 error:
3589 pet_scop_free(scop);
3590 return NULL;
3593 /* Given an access expression "expr", is the variable accessed by
3594 * "expr" assigned anywhere inside "scop"?
3596 static bool is_assigned(__isl_keep pet_expr *expr, pet_scop *scop)
3598 bool assigned = false;
3599 isl_id *id;
3601 id = pet_expr_access_get_id(expr);
3602 assigned = pet_scop_writes(scop, id);
3603 isl_id_free(id);
3605 return assigned;
3608 /* Are all nested access parameters in "pa" allowed given "scop".
3609 * In particular, is none of them written by anywhere inside "scop".
3611 * If "scop" has any skip conditions, then no nested access parameters
3612 * are allowed. In particular, if there is any nested access in a guard
3613 * for a piece of code containing a "continue", then we want to introduce
3614 * a separate statement for evaluating this guard so that we can express
3615 * that the result is false for all previous iterations.
3617 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3619 int nparam;
3621 if (!scop)
3622 return true;
3624 if (!pet_nested_any_in_pw_aff(pa))
3625 return true;
3627 if (pet_scop_has_skip(scop, pet_skip_now))
3628 return false;
3630 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3631 for (int i = 0; i < nparam; ++i) {
3632 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3633 pet_expr *expr;
3634 bool allowed;
3636 if (!pet_nested_in_id(id)) {
3637 isl_id_free(id);
3638 continue;
3641 expr = pet_nested_extract_expr(id);
3642 allowed = pet_expr_get_type(expr) == pet_expr_access &&
3643 !is_assigned(expr, scop);
3645 pet_expr_free(expr);
3646 isl_id_free(id);
3648 if (!allowed)
3649 return false;
3652 return true;
3655 /* Construct a pet_scop for a non-affine if statement.
3657 * We create a separate statement that writes the result
3658 * of the non-affine condition to a virtual scalar.
3659 * A constraint requiring the value of this virtual scalar to be one
3660 * is added to the iteration domains of the then branch.
3661 * Similarly, a constraint requiring the value of this virtual scalar
3662 * to be zero is added to the iteration domains of the else branch, if any.
3663 * We adjust the schedules to ensure that the virtual scalar is written
3664 * before it is read.
3666 * If there are any breaks or continues in the then and/or else
3667 * branches, then we may have to compute a new skip condition.
3668 * This is handled using a pet_skip_info object.
3669 * On initialization, the object checks if skip conditions need
3670 * to be computed. If so, it does so in pet_skip_info_if_extract_index and
3671 * adds them in pet_skip_info_if_add.
3673 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
3674 struct pet_scop *scop_then, struct pet_scop *scop_else,
3675 bool have_else, int stmt_id)
3677 struct pet_scop *scop;
3678 isl_multi_pw_aff *test_index;
3679 int int_size;
3680 int save_n_stmt = n_stmt;
3682 test_index = pet_create_test_index(ctx, n_test++);
3683 n_stmt = stmt_id;
3684 scop = extract_non_affine_condition(cond, n_stmt++,
3685 isl_multi_pw_aff_copy(test_index));
3686 n_stmt = save_n_stmt;
3687 scop = scop_add_array(scop, test_index, ast_context);
3689 pet_skip_info skip;
3690 pet_skip_info_if_init(&skip, ctx, scop_then, scop_else, have_else, 0);
3691 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
3692 pet_skip_info_if_extract_index(&skip, test_index, int_size,
3693 &n_stmt, &n_test);
3695 scop = pet_scop_prefix(scop, 0);
3696 scop_then = pet_scop_prefix(scop_then, 1);
3697 scop_then = pet_scop_filter(scop_then,
3698 isl_multi_pw_aff_copy(test_index), 1);
3699 if (have_else) {
3700 scop_else = pet_scop_prefix(scop_else, 1);
3701 scop_else = pet_scop_filter(scop_else, test_index, 0);
3702 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
3703 } else
3704 isl_multi_pw_aff_free(test_index);
3706 scop = pet_scop_add_seq(ctx, scop, scop_then);
3708 scop = pet_skip_info_if_add(&skip, scop, 2);
3710 return scop;
3713 /* Construct a pet_scop for an if statement.
3715 * If the condition fits the pattern of a conditional assignment,
3716 * then it is handled by extract_conditional_assignment.
3717 * Otherwise, we do the following.
3719 * If the condition is affine, then the condition is added
3720 * to the iteration domains of the then branch, while the
3721 * opposite of the condition in added to the iteration domains
3722 * of the else branch, if any.
3723 * We allow the condition to be dynamic, i.e., to refer to
3724 * scalars or array elements that may be written to outside
3725 * of the given if statement. These nested accesses are then represented
3726 * as output dimensions in the wrapping iteration domain.
3727 * If it is also written _inside_ the then or else branch, then
3728 * we treat the condition as non-affine.
3729 * As explained in extract_non_affine_if, this will introduce
3730 * an extra statement.
3731 * For aesthetic reasons, we want this statement to have a statement
3732 * number that is lower than those of the then and else branches.
3733 * In order to evaluate if we will need such a statement, however, we
3734 * first construct scops for the then and else branches.
3735 * We therefore reserve a statement number if we might have to
3736 * introduce such an extra statement.
3738 * If the condition is not affine, then the scop is created in
3739 * extract_non_affine_if.
3741 * If there are any breaks or continues in the then and/or else
3742 * branches, then we may have to compute a new skip condition.
3743 * This is handled using a pet_skip_info object.
3744 * On initialization, the object checks if skip conditions need
3745 * to be computed. If so, it does so in pet_skip_info_if_extract_cond and
3746 * adds them in pet_skip_info_if_add.
3748 struct pet_scop *PetScan::extract(IfStmt *stmt)
3750 struct pet_scop *scop_then, *scop_else = NULL, *scop;
3751 isl_pw_aff *cond;
3752 int stmt_id;
3753 int int_size;
3754 isl_set *set;
3755 isl_set *valid;
3757 clear_assignments clear(assigned_value);
3758 clear.TraverseStmt(stmt->getThen());
3759 if (stmt->getElse())
3760 clear.TraverseStmt(stmt->getElse());
3762 scop = extract_conditional_assignment(stmt);
3763 if (scop)
3764 return scop;
3766 cond = try_extract_nested_condition(stmt->getCond());
3767 if (allow_nested && (!cond || pet_nested_any_in_pw_aff(cond)))
3768 stmt_id = n_stmt++;
3771 assigned_value_cache cache(assigned_value);
3772 scop_then = extract(stmt->getThen());
3775 if (stmt->getElse()) {
3776 assigned_value_cache cache(assigned_value);
3777 scop_else = extract(stmt->getElse());
3778 if (options->autodetect) {
3779 if (scop_then && !scop_else) {
3780 partial = true;
3781 isl_pw_aff_free(cond);
3782 return scop_then;
3784 if (!scop_then && scop_else) {
3785 partial = true;
3786 isl_pw_aff_free(cond);
3787 return scop_else;
3792 if (cond &&
3793 (!is_nested_allowed(cond, scop_then) ||
3794 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
3795 isl_pw_aff_free(cond);
3796 cond = NULL;
3798 if (allow_nested && !cond)
3799 return extract_non_affine_if(stmt->getCond(), scop_then,
3800 scop_else, stmt->getElse(), stmt_id);
3802 if (!cond)
3803 cond = extract_condition(stmt->getCond());
3805 pet_skip_info skip;
3806 pet_skip_info_if_init(&skip, ctx, scop_then, scop_else,
3807 stmt->getElse() != NULL, 1);
3808 pet_skip_info_if_extract_cond(&skip, cond, int_size, &n_stmt, &n_test);
3810 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
3811 set = isl_pw_aff_non_zero_set(cond);
3812 scop = pet_scop_restrict(scop_then, isl_set_params(isl_set_copy(set)));
3814 if (stmt->getElse()) {
3815 set = isl_set_subtract(isl_set_copy(valid), set);
3816 scop_else = pet_scop_restrict(scop_else, isl_set_params(set));
3817 scop = pet_scop_add_par(ctx, scop, scop_else);
3818 } else
3819 isl_set_free(set);
3820 scop = resolve_nested(scop);
3821 scop = pet_scop_restrict_context(scop, isl_set_params(valid));
3823 if (pet_skip_info_has_skip(&skip))
3824 scop = pet_scop_prefix(scop, 0);
3825 scop = pet_skip_info_if_add(&skip, scop, 1);
3827 return scop;
3830 /* Try and construct a pet_scop for a label statement.
3831 * We currently only allow labels on expression statements.
3833 struct pet_scop *PetScan::extract(LabelStmt *stmt)
3835 isl_id *label;
3836 Stmt *sub;
3838 sub = stmt->getSubStmt();
3839 if (!isa<Expr>(sub)) {
3840 unsupported(stmt);
3841 return NULL;
3844 label = isl_id_alloc(ctx, stmt->getName(), NULL);
3846 return extract(extract_expr(cast<Expr>(sub)), stmt->getSourceRange(),
3847 true, label);
3850 /* Return a one-dimensional multi piecewise affine expression that is equal
3851 * to the constant 1 and is defined over a zero-dimensional domain.
3853 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
3855 isl_space *space;
3856 isl_local_space *ls;
3857 isl_aff *aff;
3859 space = isl_space_set_alloc(ctx, 0, 0);
3860 ls = isl_local_space_from_space(space);
3861 aff = isl_aff_zero_on_domain(ls);
3862 aff = isl_aff_set_constant_si(aff, 1);
3864 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
3867 /* Construct a pet_scop for a continue statement.
3869 * We simply create an empty scop with a universal pet_skip_now
3870 * skip condition. This skip condition will then be taken into
3871 * account by the enclosing loop construct, possibly after
3872 * being incorporated into outer skip conditions.
3874 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
3876 pet_scop *scop;
3878 scop = pet_scop_empty(ctx);
3879 if (!scop)
3880 return NULL;
3882 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
3884 return scop;
3887 /* Construct a pet_scop for a break statement.
3889 * We simply create an empty scop with both a universal pet_skip_now
3890 * skip condition and a universal pet_skip_later skip condition.
3891 * These skip conditions will then be taken into
3892 * account by the enclosing loop construct, possibly after
3893 * being incorporated into outer skip conditions.
3895 struct pet_scop *PetScan::extract(BreakStmt *stmt)
3897 pet_scop *scop;
3898 isl_multi_pw_aff *skip;
3900 scop = pet_scop_empty(ctx);
3901 if (!scop)
3902 return NULL;
3904 skip = one_mpa(ctx);
3905 scop = pet_scop_set_skip(scop, pet_skip_now,
3906 isl_multi_pw_aff_copy(skip));
3907 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
3909 return scop;
3912 /* Try and construct a pet_scop corresponding to "stmt".
3914 * If "stmt" is a compound statement, then "skip_declarations"
3915 * indicates whether we should skip initial declarations in the
3916 * compound statement.
3918 * If the constructed pet_scop is not a (possibly) partial representation
3919 * of "stmt", we update start and end of the pet_scop to those of "stmt".
3920 * In particular, if skip_declarations is set, then we may have skipped
3921 * declarations inside "stmt" and so the pet_scop may not represent
3922 * the entire "stmt".
3923 * Note that this function may be called with "stmt" referring to the entire
3924 * body of the function, including the outer braces. In such cases,
3925 * skip_declarations will be set and the braces will not be taken into
3926 * account in scop->start and scop->end.
3928 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
3930 struct pet_scop *scop;
3932 if (isa<Expr>(stmt))
3933 return extract(extract_expr(cast<Expr>(stmt)),
3934 stmt->getSourceRange(), true);
3936 switch (stmt->getStmtClass()) {
3937 case Stmt::WhileStmtClass:
3938 scop = extract(cast<WhileStmt>(stmt));
3939 break;
3940 case Stmt::ForStmtClass:
3941 scop = extract_for(cast<ForStmt>(stmt));
3942 break;
3943 case Stmt::IfStmtClass:
3944 scop = extract(cast<IfStmt>(stmt));
3945 break;
3946 case Stmt::CompoundStmtClass:
3947 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
3948 break;
3949 case Stmt::LabelStmtClass:
3950 scop = extract(cast<LabelStmt>(stmt));
3951 break;
3952 case Stmt::ContinueStmtClass:
3953 scop = extract(cast<ContinueStmt>(stmt));
3954 break;
3955 case Stmt::BreakStmtClass:
3956 scop = extract(cast<BreakStmt>(stmt));
3957 break;
3958 case Stmt::DeclStmtClass:
3959 scop = extract(cast<DeclStmt>(stmt));
3960 break;
3961 default:
3962 unsupported(stmt);
3963 return NULL;
3966 if (partial || skip_declarations)
3967 return scop;
3969 scop = update_scop_start_end(scop, stmt->getSourceRange(), false);
3971 return scop;
3974 /* Extract a clone of the kill statement in "scop".
3975 * "scop" is expected to have been created from a DeclStmt
3976 * and should have the kill as its first statement.
3978 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
3980 pet_expr *kill;
3981 struct pet_stmt *stmt;
3982 isl_multi_pw_aff *index;
3983 isl_map *access;
3984 pet_expr *arg;
3986 if (!scop)
3987 return NULL;
3988 if (scop->n_stmt < 1)
3989 isl_die(ctx, isl_error_internal,
3990 "expecting at least one statement", return NULL);
3991 stmt = scop->stmts[0];
3992 if (!pet_stmt_is_kill(stmt))
3993 isl_die(ctx, isl_error_internal,
3994 "expecting kill statement", return NULL);
3996 arg = pet_expr_get_arg(stmt->body, 0);
3997 index = pet_expr_access_get_index(arg);
3998 access = pet_expr_access_get_access(arg);
3999 pet_expr_free(arg);
4000 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
4001 access = isl_map_reset_tuple_id(access, isl_dim_in);
4002 kill = pet_expr_kill_from_access_and_index(access, index);
4003 return pet_stmt_from_pet_expr(stmt->line, NULL, n_stmt++, kill);
4006 /* Mark all arrays in "scop" as being exposed.
4008 static struct pet_scop *mark_exposed(struct pet_scop *scop)
4010 if (!scop)
4011 return NULL;
4012 for (int i = 0; i < scop->n_array; ++i)
4013 scop->arrays[i]->exposed = 1;
4014 return scop;
4017 /* Try and construct a pet_scop corresponding to (part of)
4018 * a sequence of statements.
4020 * "block" is set if the sequence respresents the children of
4021 * a compound statement.
4022 * "skip_declarations" is set if we should skip initial declarations
4023 * in the sequence of statements.
4025 * After extracting a statement, we update "assigned_value"
4026 * based on the top-level assignments in the statement
4027 * so that we can exploit them in subsequent statements in the same block.
4029 * If there are any breaks or continues in the individual statements,
4030 * then we may have to compute a new skip condition.
4031 * This is handled using a pet_skip_info object.
4032 * On initialization, the object checks if skip conditions need
4033 * to be computed. If so, it does so in pet_skip_info_seq_extract and
4034 * adds them in pet_skip_info_seq_add.
4036 * If "block" is set, then we need to insert kill statements at
4037 * the end of the block for any array that has been declared by
4038 * one of the statements in the sequence. Each of these declarations
4039 * results in the construction of a kill statement at the place
4040 * of the declaration, so we simply collect duplicates of
4041 * those kill statements and append these duplicates to the constructed scop.
4043 * If "block" is not set, then any array declared by one of the statements
4044 * in the sequence is marked as being exposed.
4046 * If autodetect is set, then we allow the extraction of only a subrange
4047 * of the sequence of statements. However, if there is at least one statement
4048 * for which we could not construct a scop and the final range contains
4049 * either no statements or at least one kill, then we discard the entire
4050 * range.
4052 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
4053 bool skip_declarations)
4055 pet_scop *scop;
4056 StmtIterator i;
4057 int int_size;
4058 int j;
4059 bool partial_range = false;
4060 set<struct pet_stmt *> kills;
4061 set<struct pet_stmt *>::iterator it;
4063 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
4065 scop = pet_scop_empty(ctx);
4066 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4067 Stmt *child = *i;
4068 struct pet_scop *scop_i;
4070 if (scop->n_stmt == 0 && skip_declarations &&
4071 child->getStmtClass() == Stmt::DeclStmtClass)
4072 continue;
4074 scop_i = extract(child);
4075 if (scop->n_stmt != 0 && partial) {
4076 pet_scop_free(scop_i);
4077 break;
4079 handle_writes(scop_i);
4080 pet_skip_info skip;
4081 pet_skip_info_seq_init(&skip, ctx, scop, scop_i);
4082 pet_skip_info_seq_extract(&skip, int_size, &n_stmt, &n_test);
4083 if (pet_skip_info_has_skip(&skip))
4084 scop_i = pet_scop_prefix(scop_i, 0);
4085 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4086 if (block)
4087 kills.insert(extract_kill(scop_i));
4088 else
4089 scop_i = mark_exposed(scop_i);
4091 scop_i = pet_scop_prefix(scop_i, j);
4092 if (options->autodetect) {
4093 if (scop_i)
4094 scop = pet_scop_add_seq(ctx, scop, scop_i);
4095 else
4096 partial_range = true;
4097 if (scop->n_stmt != 0 && !scop_i)
4098 partial = true;
4099 } else {
4100 scop = pet_scop_add_seq(ctx, scop, scop_i);
4103 scop = pet_skip_info_seq_add(&skip, scop, j);
4105 if (partial || !scop)
4106 break;
4109 for (it = kills.begin(); it != kills.end(); ++it) {
4110 pet_scop *scop_j;
4111 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4112 scop_j = pet_scop_prefix(scop_j, j);
4113 scop = pet_scop_add_seq(ctx, scop, scop_j);
4116 if (scop && partial_range) {
4117 if (scop->n_stmt == 0 || kills.size() != 0) {
4118 pet_scop_free(scop);
4119 return NULL;
4121 partial = true;
4124 return scop;
4127 /* Check if the scop marked by the user is exactly this Stmt
4128 * or part of this Stmt.
4129 * If so, return a pet_scop corresponding to the marked region.
4130 * Otherwise, return NULL.
4132 struct pet_scop *PetScan::scan(Stmt *stmt)
4134 SourceManager &SM = PP.getSourceManager();
4135 unsigned start_off, end_off;
4137 start_off = getExpansionOffset(SM, stmt->getLocStart());
4138 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4140 if (start_off > loc.end)
4141 return NULL;
4142 if (end_off < loc.start)
4143 return NULL;
4144 if (start_off >= loc.start && end_off <= loc.end) {
4145 return extract(stmt);
4148 StmtIterator start;
4149 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4150 Stmt *child = *start;
4151 if (!child)
4152 continue;
4153 start_off = getExpansionOffset(SM, child->getLocStart());
4154 end_off = getExpansionOffset(SM, child->getLocEnd());
4155 if (start_off < loc.start && end_off >= loc.end)
4156 return scan(child);
4157 if (start_off >= loc.start)
4158 break;
4161 StmtIterator end;
4162 for (end = start; end != stmt->child_end(); ++end) {
4163 Stmt *child = *end;
4164 start_off = SM.getFileOffset(child->getLocStart());
4165 if (start_off >= loc.end)
4166 break;
4169 return extract(StmtRange(start, end), false, false);
4172 /* Set the size of index "pos" of "array" to "size".
4173 * In particular, add a constraint of the form
4175 * i_pos < size
4177 * to array->extent and a constraint of the form
4179 * size >= 0
4181 * to array->context.
4183 static struct pet_array *update_size(struct pet_array *array, int pos,
4184 __isl_take isl_pw_aff *size)
4186 isl_set *valid;
4187 isl_set *univ;
4188 isl_set *bound;
4189 isl_space *dim;
4190 isl_aff *aff;
4191 isl_pw_aff *index;
4192 isl_id *id;
4194 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
4195 array->context = isl_set_intersect(array->context, valid);
4197 dim = isl_set_get_space(array->extent);
4198 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
4199 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
4200 univ = isl_set_universe(isl_aff_get_domain_space(aff));
4201 index = isl_pw_aff_alloc(univ, aff);
4203 size = isl_pw_aff_add_dims(size, isl_dim_in,
4204 isl_set_dim(array->extent, isl_dim_set));
4205 id = isl_set_get_tuple_id(array->extent);
4206 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
4207 bound = isl_pw_aff_lt_set(index, size);
4209 array->extent = isl_set_intersect(array->extent, bound);
4211 if (!array->context || !array->extent)
4212 goto error;
4214 return array;
4215 error:
4216 pet_array_free(array);
4217 return NULL;
4220 /* Figure out the size of the array at position "pos" and all
4221 * subsequent positions from "type" and update "array" accordingly.
4223 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
4224 const Type *type, int pos)
4226 const ArrayType *atype;
4227 isl_pw_aff *size;
4229 if (!array)
4230 return NULL;
4232 if (type->isPointerType()) {
4233 type = type->getPointeeType().getTypePtr();
4234 return set_upper_bounds(array, type, pos + 1);
4236 if (!type->isArrayType())
4237 return array;
4239 type = type->getCanonicalTypeInternal().getTypePtr();
4240 atype = cast<ArrayType>(type);
4242 if (type->isConstantArrayType()) {
4243 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
4244 size = extract_affine(ca->getSize());
4245 array = update_size(array, pos, size);
4246 } else if (type->isVariableArrayType()) {
4247 const VariableArrayType *vla = cast<VariableArrayType>(atype);
4248 size = extract_affine(vla->getSizeExpr());
4249 array = update_size(array, pos, size);
4252 type = atype->getElementType().getTypePtr();
4254 return set_upper_bounds(array, type, pos + 1);
4257 /* Is "T" the type of a variable length array with static size?
4259 static bool is_vla_with_static_size(QualType T)
4261 const VariableArrayType *vlatype;
4263 if (!T->isVariableArrayType())
4264 return false;
4265 vlatype = cast<VariableArrayType>(T);
4266 return vlatype->getSizeModifier() == VariableArrayType::Static;
4269 /* Return the type of "decl" as an array.
4271 * In particular, if "decl" is a parameter declaration that
4272 * is a variable length array with a static size, then
4273 * return the original type (i.e., the variable length array).
4274 * Otherwise, return the type of decl.
4276 static QualType get_array_type(ValueDecl *decl)
4278 ParmVarDecl *parm;
4279 QualType T;
4281 parm = dyn_cast<ParmVarDecl>(decl);
4282 if (!parm)
4283 return decl->getType();
4285 T = parm->getOriginalType();
4286 if (!is_vla_with_static_size(T))
4287 return decl->getType();
4288 return T;
4291 /* Does "decl" have definition that we can keep track of in a pet_type?
4293 static bool has_printable_definition(RecordDecl *decl)
4295 if (!decl->getDeclName())
4296 return false;
4297 return decl->getLexicalDeclContext() == decl->getDeclContext();
4300 /* Construct and return a pet_array corresponding to the variable "decl".
4301 * In particular, initialize array->extent to
4303 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4305 * and then call set_upper_bounds to set the upper bounds on the indices
4306 * based on the type of the variable.
4308 * If the base type is that of a record with a top-level definition and
4309 * if "types" is not null, then the RecordDecl corresponding to the type
4310 * is added to "types".
4312 * If the base type is that of a record with no top-level definition,
4313 * then we replace it by "<subfield>".
4315 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
4316 lex_recorddecl_set *types)
4318 struct pet_array *array;
4319 QualType qt = get_array_type(decl);
4320 const Type *type = qt.getTypePtr();
4321 int depth = array_depth(type);
4322 QualType base = pet_clang_base_type(qt);
4323 string name;
4324 isl_id *id;
4325 isl_space *dim;
4327 array = isl_calloc_type(ctx, struct pet_array);
4328 if (!array)
4329 return NULL;
4331 id = create_decl_id(ctx, decl);
4332 dim = isl_space_set_alloc(ctx, 0, depth);
4333 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
4335 array->extent = isl_set_nat_universe(dim);
4337 dim = isl_space_params_alloc(ctx, 0);
4338 array->context = isl_set_universe(dim);
4340 array = set_upper_bounds(array, type, 0);
4341 if (!array)
4342 return NULL;
4344 name = base.getAsString();
4346 if (types && base->isRecordType()) {
4347 RecordDecl *decl = pet_clang_record_decl(base);
4348 if (has_printable_definition(decl))
4349 types->insert(decl);
4350 else
4351 name = "<subfield>";
4354 array->element_type = strdup(name.c_str());
4355 array->element_is_record = base->isRecordType();
4356 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
4358 return array;
4361 /* Construct and return a pet_array corresponding to the sequence
4362 * of declarations "decls".
4363 * If the sequence contains a single declaration, then it corresponds
4364 * to a simple array access. Otherwise, it corresponds to a member access,
4365 * with the declaration for the substructure following that of the containing
4366 * structure in the sequence of declarations.
4367 * We start with the outermost substructure and then combine it with
4368 * information from the inner structures.
4370 * Additionally, keep track of all required types in "types".
4372 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
4373 vector<ValueDecl *> decls, lex_recorddecl_set *types)
4375 struct pet_array *array;
4376 vector<ValueDecl *>::iterator it;
4378 it = decls.begin();
4380 array = extract_array(ctx, *it, types);
4382 for (++it; it != decls.end(); ++it) {
4383 struct pet_array *parent;
4384 const char *base_name, *field_name;
4385 char *product_name;
4387 parent = array;
4388 array = extract_array(ctx, *it, types);
4389 if (!array)
4390 return pet_array_free(parent);
4392 base_name = isl_set_get_tuple_name(parent->extent);
4393 field_name = isl_set_get_tuple_name(array->extent);
4394 product_name = pet_array_member_access_name(ctx,
4395 base_name, field_name);
4397 array->extent = isl_set_product(isl_set_copy(parent->extent),
4398 array->extent);
4399 if (product_name)
4400 array->extent = isl_set_set_tuple_name(array->extent,
4401 product_name);
4402 array->context = isl_set_intersect(array->context,
4403 isl_set_copy(parent->context));
4405 pet_array_free(parent);
4406 free(product_name);
4408 if (!array->extent || !array->context || !product_name)
4409 return pet_array_free(array);
4412 return array;
4415 /* Add a pet_type corresponding to "decl" to "scop, provided
4416 * it is a member of "types" and it has not been added before
4417 * (i.e., it is not a member of "types_done".
4419 * Since we want the user to be able to print the types
4420 * in the order in which they appear in the scop, we need to
4421 * make sure that types of fields in a structure appear before
4422 * that structure. We therefore call ourselves recursively
4423 * on the types of all record subfields.
4425 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
4426 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
4427 lex_recorddecl_set &types_done)
4429 string s;
4430 llvm::raw_string_ostream S(s);
4431 RecordDecl::field_iterator it;
4433 if (types.find(decl) == types.end())
4434 return scop;
4435 if (types_done.find(decl) != types_done.end())
4436 return scop;
4438 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
4439 RecordDecl *record;
4440 QualType type = it->getType();
4442 if (!type->isRecordType())
4443 continue;
4444 record = pet_clang_record_decl(type);
4445 scop = add_type(ctx, scop, record, PP, types, types_done);
4448 if (strlen(decl->getName().str().c_str()) == 0)
4449 return scop;
4451 decl->print(S, PrintingPolicy(PP.getLangOpts()));
4452 S.str();
4454 scop->types[scop->n_type] = pet_type_alloc(ctx,
4455 decl->getName().str().c_str(), s.c_str());
4456 if (!scop->types[scop->n_type])
4457 return pet_scop_free(scop);
4459 types_done.insert(decl);
4461 scop->n_type++;
4463 return scop;
4466 /* Construct a list of pet_arrays, one for each array (or scalar)
4467 * accessed inside "scop", add this list to "scop" and return the result.
4469 * The context of "scop" is updated with the intersection of
4470 * the contexts of all arrays, i.e., constraints on the parameters
4471 * that ensure that the arrays have a valid (non-negative) size.
4473 * If the any of the extracted arrays refers to a member access,
4474 * then also add the required types to "scop".
4476 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
4478 int i;
4479 array_desc_set arrays;
4480 array_desc_set::iterator it;
4481 lex_recorddecl_set types;
4482 lex_recorddecl_set types_done;
4483 lex_recorddecl_set::iterator types_it;
4484 int n_array;
4485 struct pet_array **scop_arrays;
4487 if (!scop)
4488 return NULL;
4490 pet_scop_collect_arrays(scop, arrays);
4491 if (arrays.size() == 0)
4492 return scop;
4494 n_array = scop->n_array;
4496 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
4497 n_array + arrays.size());
4498 if (!scop_arrays)
4499 goto error;
4500 scop->arrays = scop_arrays;
4502 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
4503 struct pet_array *array;
4504 array = extract_array(ctx, *it, &types);
4505 scop->arrays[n_array + i] = array;
4506 if (!scop->arrays[n_array + i])
4507 goto error;
4508 scop->n_array++;
4509 scop->context = isl_set_intersect(scop->context,
4510 isl_set_copy(array->context));
4511 if (!scop->context)
4512 goto error;
4515 if (types.size() == 0)
4516 return scop;
4518 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
4519 if (!scop->types)
4520 goto error;
4522 for (types_it = types.begin(); types_it != types.end(); ++types_it)
4523 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
4525 return scop;
4526 error:
4527 pet_scop_free(scop);
4528 return NULL;
4531 /* Bound all parameters in scop->context to the possible values
4532 * of the corresponding C variable.
4534 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
4536 int n;
4538 if (!scop)
4539 return NULL;
4541 n = isl_set_dim(scop->context, isl_dim_param);
4542 for (int i = 0; i < n; ++i) {
4543 isl_id *id;
4544 ValueDecl *decl;
4546 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
4547 if (pet_nested_in_id(id)) {
4548 isl_id_free(id);
4549 isl_die(isl_set_get_ctx(scop->context),
4550 isl_error_internal,
4551 "unresolved nested parameter", goto error);
4553 decl = (ValueDecl *) isl_id_get_user(id);
4554 isl_id_free(id);
4556 scop->context = set_parameter_bounds(scop->context, i, decl);
4558 if (!scop->context)
4559 goto error;
4562 return scop;
4563 error:
4564 pet_scop_free(scop);
4565 return NULL;
4568 /* Construct a pet_scop from the given function.
4570 * If the scop was delimited by scop and endscop pragmas, then we override
4571 * the file offsets by those derived from the pragmas.
4573 struct pet_scop *PetScan::scan(FunctionDecl *fd)
4575 pet_scop *scop;
4576 Stmt *stmt;
4578 stmt = fd->getBody();
4580 if (options->autodetect)
4581 scop = extract(stmt, true);
4582 else {
4583 scop = scan(stmt);
4584 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
4586 scop = pet_scop_detect_parameter_accesses(scop);
4587 scop = scan_arrays(scop);
4588 scop = add_parameter_bounds(scop);
4589 scop = pet_scop_gist(scop, value_bounds);
4591 return scop;