PetScan::extract_expr: remove unused variable
[pet.git] / scan.cc
blob1917e908820b6ba1e7327556eabb0c1efe09de28
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2015 Ecole Normale Superieure. All rights reserved.
4 * Copyright 2015 Sven Verdoolaege. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
19 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
22 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
25 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 * The views and conclusions contained in the software and documentation
31 * are those of the authors and should not be interpreted as
32 * representing official policies, either expressed or implied, of
33 * Leiden University.
34 */
36 #include "config.h"
38 #include <string.h>
39 #include <set>
40 #include <map>
41 #include <iostream>
42 #include <sstream>
43 #include <llvm/Support/raw_ostream.h>
44 #include <clang/AST/ASTContext.h>
45 #include <clang/AST/ASTDiagnostic.h>
46 #include <clang/AST/Attr.h>
47 #include <clang/AST/Expr.h>
48 #include <clang/AST/RecursiveASTVisitor.h>
50 #include <isl/id.h>
51 #include <isl/space.h>
52 #include <isl/aff.h>
53 #include <isl/set.h>
54 #include <isl/union_set.h>
56 #include "aff.h"
57 #include "array.h"
58 #include "clang.h"
59 #include "context.h"
60 #include "expr.h"
61 #include "id.h"
62 #include "inliner.h"
63 #include "nest.h"
64 #include "options.h"
65 #include "scan.h"
66 #include "scop.h"
67 #include "scop_plus.h"
68 #include "substituter.h"
69 #include "tree.h"
70 #include "tree2scop.h"
72 using namespace std;
73 using namespace clang;
75 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
77 switch (kind) {
78 case UO_Minus:
79 return pet_op_minus;
80 case UO_Not:
81 return pet_op_not;
82 case UO_LNot:
83 return pet_op_lnot;
84 case UO_PostInc:
85 return pet_op_post_inc;
86 case UO_PostDec:
87 return pet_op_post_dec;
88 case UO_PreInc:
89 return pet_op_pre_inc;
90 case UO_PreDec:
91 return pet_op_pre_dec;
92 default:
93 return pet_op_last;
97 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
99 switch (kind) {
100 case BO_AddAssign:
101 return pet_op_add_assign;
102 case BO_SubAssign:
103 return pet_op_sub_assign;
104 case BO_MulAssign:
105 return pet_op_mul_assign;
106 case BO_DivAssign:
107 return pet_op_div_assign;
108 case BO_Assign:
109 return pet_op_assign;
110 case BO_Add:
111 return pet_op_add;
112 case BO_Sub:
113 return pet_op_sub;
114 case BO_Mul:
115 return pet_op_mul;
116 case BO_Div:
117 return pet_op_div;
118 case BO_Rem:
119 return pet_op_mod;
120 case BO_Shl:
121 return pet_op_shl;
122 case BO_Shr:
123 return pet_op_shr;
124 case BO_EQ:
125 return pet_op_eq;
126 case BO_NE:
127 return pet_op_ne;
128 case BO_LE:
129 return pet_op_le;
130 case BO_GE:
131 return pet_op_ge;
132 case BO_LT:
133 return pet_op_lt;
134 case BO_GT:
135 return pet_op_gt;
136 case BO_And:
137 return pet_op_and;
138 case BO_Xor:
139 return pet_op_xor;
140 case BO_Or:
141 return pet_op_or;
142 case BO_LAnd:
143 return pet_op_land;
144 case BO_LOr:
145 return pet_op_lor;
146 default:
147 return pet_op_last;
151 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
152 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
154 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
155 SourceLocation(), var, false, var->getInnerLocStart(),
156 var->getType(), VK_LValue);
158 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
159 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
161 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
162 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
163 VK_LValue);
165 #else
166 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
168 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
169 var, var->getInnerLocStart(), var->getType(), VK_LValue);
171 #endif
173 #ifdef GETTYPEINFORETURNSTYPEINFO
175 static int size_in_bytes(ASTContext &context, QualType type)
177 return context.getTypeInfo(type).Width / 8;
180 #else
182 static int size_in_bytes(ASTContext &context, QualType type)
184 return context.getTypeInfo(type).first / 8;
187 #endif
189 /* Check if the element type corresponding to the given array type
190 * has a const qualifier.
192 static bool const_base(QualType qt)
194 const Type *type = qt.getTypePtr();
196 if (type->isPointerType())
197 return const_base(type->getPointeeType());
198 if (type->isArrayType()) {
199 const ArrayType *atype;
200 type = type->getCanonicalTypeInternal().getTypePtr();
201 atype = cast<ArrayType>(type);
202 return const_base(atype->getElementType());
205 return qt.isConstQualified();
208 PetScan::~PetScan()
210 std::map<const Type *, pet_expr *>::iterator it;
211 std::map<FunctionDecl *, pet_function_summary *>::iterator it_s;
213 for (it = type_size.begin(); it != type_size.end(); ++it)
214 pet_expr_free(it->second);
215 for (it_s = summary_cache.begin(); it_s != summary_cache.end(); ++it_s)
216 pet_function_summary_free(it_s->second);
218 isl_union_map_free(value_bounds);
221 /* Report a diagnostic on the range "range", unless autodetect is set.
223 void PetScan::report(SourceRange range, unsigned id)
225 if (options->autodetect)
226 return;
228 SourceLocation loc = range.getBegin();
229 DiagnosticsEngine &diag = PP.getDiagnostics();
230 DiagnosticBuilder B = diag.Report(loc, id) << range;
233 /* Report a diagnostic on "stmt", unless autodetect is set.
235 void PetScan::report(Stmt *stmt, unsigned id)
237 report(stmt->getSourceRange(), id);
240 /* Report a diagnostic on "decl", unless autodetect is set.
242 void PetScan::report(Decl *decl, unsigned id)
244 report(decl->getSourceRange(), id);
247 /* Called if we found something we (currently) cannot handle.
248 * We'll provide more informative warnings later.
250 * We only actually complain if autodetect is false.
252 void PetScan::unsupported(Stmt *stmt)
254 DiagnosticsEngine &diag = PP.getDiagnostics();
255 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
256 "unsupported");
257 report(stmt, id);
260 /* Report an unsupported unary operator, unless autodetect is set.
262 void PetScan::report_unsupported_unary_operator(Stmt *stmt)
264 DiagnosticsEngine &diag = PP.getDiagnostics();
265 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
266 "this type of unary operator is not supported");
267 report(stmt, id);
270 /* Report an unsupported statement type, unless autodetect is set.
272 void PetScan::report_unsupported_statement_type(Stmt *stmt)
274 DiagnosticsEngine &diag = PP.getDiagnostics();
275 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
276 "this type of statement is not supported");
277 report(stmt, id);
280 /* Report a missing prototype, unless autodetect is set.
282 void PetScan::report_prototype_required(Stmt *stmt)
284 DiagnosticsEngine &diag = PP.getDiagnostics();
285 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
286 "prototype required");
287 report(stmt, id);
290 /* Report a missing increment, unless autodetect is set.
292 void PetScan::report_missing_increment(Stmt *stmt)
294 DiagnosticsEngine &diag = PP.getDiagnostics();
295 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
296 "missing increment");
297 report(stmt, id);
300 /* Report a missing summary function, unless autodetect is set.
302 void PetScan::report_missing_summary_function(Stmt *stmt)
304 DiagnosticsEngine &diag = PP.getDiagnostics();
305 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
306 "missing summary function");
307 report(stmt, id);
310 /* Report a missing summary function body, unless autodetect is set.
312 void PetScan::report_missing_summary_function_body(Stmt *stmt)
314 DiagnosticsEngine &diag = PP.getDiagnostics();
315 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
316 "missing summary function body");
317 report(stmt, id);
320 /* Report an unsupported argument in a call to an inlined function,
321 * unless autodetect is set.
323 void PetScan::report_unsupported_inline_function_argument(Stmt *stmt)
325 DiagnosticsEngine &diag = PP.getDiagnostics();
326 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
327 "unsupported inline function call argument");
328 report(stmt, id);
331 /* Report an unsupported type of declaration, unless autodetect is set.
333 void PetScan::report_unsupported_declaration(Decl *decl)
335 DiagnosticsEngine &diag = PP.getDiagnostics();
336 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
337 "unsupported declaration");
338 report(decl, id);
341 /* Extract an integer from "val", which is assumed to be non-negative.
343 static __isl_give isl_val *extract_unsigned(isl_ctx *ctx,
344 const llvm::APInt &val)
346 unsigned n;
347 const uint64_t *data;
349 data = val.getRawData();
350 n = val.getNumWords();
351 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
354 /* Extract an integer from "val". If "is_signed" is set, then "val"
355 * is signed. Otherwise it it unsigned.
357 static __isl_give isl_val *extract_int(isl_ctx *ctx, bool is_signed,
358 llvm::APInt val)
360 int is_negative = is_signed && val.isNegative();
361 isl_val *v;
363 if (is_negative)
364 val = -val;
366 v = extract_unsigned(ctx, val);
368 if (is_negative)
369 v = isl_val_neg(v);
370 return v;
373 /* Extract an integer from "expr".
375 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
377 const Type *type = expr->getType().getTypePtr();
378 bool is_signed = type->hasSignedIntegerRepresentation();
380 return ::extract_int(ctx, is_signed, expr->getValue());
383 /* Extract an integer from "expr".
384 * Return NULL if "expr" does not (obviously) represent an integer.
386 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
388 return extract_int(expr->getSubExpr());
391 /* Extract an integer from "expr".
392 * Return NULL if "expr" does not (obviously) represent an integer.
394 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
396 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
397 return extract_int(ctx, cast<IntegerLiteral>(expr));
398 if (expr->getStmtClass() == Stmt::ParenExprClass)
399 return extract_int(cast<ParenExpr>(expr));
401 unsupported(expr);
402 return NULL;
405 /* Extract a pet_expr from the APInt "val", which is assumed
406 * to be non-negative.
408 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
410 return pet_expr_new_int(extract_unsigned(ctx, val));
413 /* Return the number of bits needed to represent the type of "decl",
414 * if it is an integer type. Otherwise return 0.
415 * If qt is signed then return the opposite of the number of bits.
417 static int get_type_size(ValueDecl *decl)
419 return pet_clang_get_type_size(decl->getType(), decl->getASTContext());
422 /* Bound parameter "pos" of "set" to the possible values of "decl".
424 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
425 unsigned pos, ValueDecl *decl)
427 int type_size;
428 isl_ctx *ctx;
429 isl_val *bound;
431 ctx = isl_set_get_ctx(set);
432 type_size = get_type_size(decl);
433 if (type_size == 0)
434 isl_die(ctx, isl_error_invalid, "not an integer type",
435 return isl_set_free(set));
436 if (type_size > 0) {
437 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
438 bound = isl_val_int_from_ui(ctx, type_size);
439 bound = isl_val_2exp(bound);
440 bound = isl_val_sub_ui(bound, 1);
441 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
442 } else {
443 bound = isl_val_int_from_ui(ctx, -type_size - 1);
444 bound = isl_val_2exp(bound);
445 bound = isl_val_sub_ui(bound, 1);
446 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
447 isl_val_copy(bound));
448 bound = isl_val_neg(bound);
449 bound = isl_val_sub_ui(bound, 1);
450 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
453 return set;
456 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
458 return extract_index_expr(expr->getSubExpr());
461 /* Return the depth of an array of the given type.
463 static int array_depth(const Type *type)
465 if (type->isPointerType())
466 return 1 + array_depth(type->getPointeeType().getTypePtr());
467 if (type->isArrayType()) {
468 const ArrayType *atype;
469 type = type->getCanonicalTypeInternal().getTypePtr();
470 atype = cast<ArrayType>(type);
471 return 1 + array_depth(atype->getElementType().getTypePtr());
473 return 0;
476 /* Return the depth of the array accessed by the index expression "index".
477 * If "index" is an affine expression, i.e., if it does not access
478 * any array, then return 1.
479 * If "index" represent a member access, i.e., if its range is a wrapped
480 * relation, then return the sum of the depth of the array of structures
481 * and that of the member inside the structure.
483 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
485 isl_id *id;
486 ValueDecl *decl;
488 if (!index)
489 return -1;
491 if (isl_multi_pw_aff_range_is_wrapping(index)) {
492 int domain_depth, range_depth;
493 isl_multi_pw_aff *domain, *range;
495 domain = isl_multi_pw_aff_copy(index);
496 domain = isl_multi_pw_aff_range_factor_domain(domain);
497 domain_depth = extract_depth(domain);
498 isl_multi_pw_aff_free(domain);
499 range = isl_multi_pw_aff_copy(index);
500 range = isl_multi_pw_aff_range_factor_range(range);
501 range_depth = extract_depth(range);
502 isl_multi_pw_aff_free(range);
504 return domain_depth + range_depth;
507 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
508 return 1;
510 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
511 if (!id)
512 return -1;
513 decl = pet_id_get_decl(id);
514 isl_id_free(id);
516 return array_depth(decl->getType().getTypePtr());
519 /* Return the depth of the array accessed by the access expression "expr".
521 static int extract_depth(__isl_keep pet_expr *expr)
523 isl_multi_pw_aff *index;
524 int depth;
526 index = pet_expr_access_get_index(expr);
527 depth = extract_depth(index);
528 isl_multi_pw_aff_free(index);
530 return depth;
533 /* Construct a pet_expr representing an index expression for an access
534 * to the variable referenced by "expr".
536 * If "expr" references an enum constant, then return an integer expression
537 * instead, representing the value of the enum constant.
539 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
541 return extract_index_expr(expr->getDecl());
544 /* Construct a pet_expr representing an index expression for an access
545 * to the variable "decl".
547 * If "decl" is an enum constant, then we return an integer expression
548 * instead, representing the value of the enum constant.
550 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
552 isl_id *id;
554 if (isa<EnumConstantDecl>(decl))
555 return extract_expr(cast<EnumConstantDecl>(decl));
557 id = pet_id_from_decl(ctx, decl);
558 return pet_id_create_index_expr(id);
561 /* Construct a pet_expr representing the index expression "expr"
562 * Return NULL on error.
564 * If "expr" is a reference to an enum constant, then return
565 * an integer expression instead, representing the value of the enum constant.
567 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
569 switch (expr->getStmtClass()) {
570 case Stmt::ImplicitCastExprClass:
571 return extract_index_expr(cast<ImplicitCastExpr>(expr));
572 case Stmt::DeclRefExprClass:
573 return extract_index_expr(cast<DeclRefExpr>(expr));
574 case Stmt::ArraySubscriptExprClass:
575 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
576 case Stmt::IntegerLiteralClass:
577 return extract_expr(cast<IntegerLiteral>(expr));
578 case Stmt::MemberExprClass:
579 return extract_index_expr(cast<MemberExpr>(expr));
580 default:
581 unsupported(expr);
583 return NULL;
586 /* Extract an index expression from the given array subscript expression.
588 * We first extract an index expression from the base.
589 * This will result in an index expression with a range that corresponds
590 * to the earlier indices.
591 * We then extract the current index and let
592 * pet_expr_access_subscript combine the two.
594 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
596 Expr *base = expr->getBase();
597 Expr *idx = expr->getIdx();
598 pet_expr *index;
599 pet_expr *base_expr;
601 base_expr = extract_index_expr(base);
602 index = extract_expr(idx);
604 base_expr = pet_expr_access_subscript(base_expr, index);
606 return base_expr;
609 /* Extract an index expression from a member expression.
611 * If the base access (to the structure containing the member)
612 * is of the form
614 * A[..]
616 * and the member is called "f", then the member access is of
617 * the form
619 * A_f[A[..] -> f[]]
621 * If the member access is to an anonymous struct, then simply return
623 * A[..]
625 * If the member access in the source code is of the form
627 * A->f
629 * then it is treated as
631 * A[0].f
633 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
635 Expr *base = expr->getBase();
636 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
637 pet_expr *base_index;
638 isl_id *id;
640 base_index = extract_index_expr(base);
642 if (expr->isArrow()) {
643 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
644 base_index = pet_expr_access_subscript(base_index, index);
647 if (field->isAnonymousStructOrUnion())
648 return base_index;
650 id = pet_id_from_decl(ctx, field);
652 return pet_expr_access_member(base_index, id);
655 /* Mark the given access pet_expr as a write.
657 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
659 access = pet_expr_access_set_write(access, 1);
660 access = pet_expr_access_set_read(access, 0);
662 return access;
665 /* Mark the given (read) access pet_expr as also possibly being written.
666 * That is, initialize the may write access relation from the may read relation
667 * and initialize the must write access relation to the empty relation.
669 static __isl_give pet_expr *mark_may_write(__isl_take pet_expr *expr)
671 isl_union_map *access;
672 isl_union_map *empty;
674 access = pet_expr_access_get_dependent_access(expr,
675 pet_expr_access_may_read);
676 empty = isl_union_map_empty(isl_union_map_get_space(access));
677 expr = pet_expr_access_set_access(expr, pet_expr_access_may_write,
678 access);
679 expr = pet_expr_access_set_access(expr, pet_expr_access_must_write,
680 empty);
682 return expr;
685 /* Construct a pet_expr representing a unary operator expression.
687 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
689 int type_size;
690 pet_expr *arg;
691 enum pet_op_type op;
693 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
694 if (op == pet_op_last) {
695 report_unsupported_unary_operator(expr);
696 return NULL;
699 arg = extract_expr(expr->getSubExpr());
701 if (expr->isIncrementDecrementOp() &&
702 pet_expr_get_type(arg) == pet_expr_access) {
703 arg = mark_write(arg);
704 arg = pet_expr_access_set_read(arg, 1);
707 type_size = pet_clang_get_type_size(expr->getType(), ast_context);
708 return pet_expr_new_unary(type_size, op, arg);
711 /* Construct a pet_expr representing a binary operator expression.
713 * If the top level operator is an assignment and the LHS is an access,
714 * then we mark that access as a write. If the operator is a compound
715 * assignment, the access is marked as both a read and a write.
717 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
719 int type_size;
720 pet_expr *lhs, *rhs;
721 enum pet_op_type op;
723 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
724 if (op == pet_op_last) {
725 unsupported(expr);
726 return NULL;
729 lhs = extract_expr(expr->getLHS());
730 rhs = extract_expr(expr->getRHS());
732 if (expr->isAssignmentOp() &&
733 pet_expr_get_type(lhs) == pet_expr_access) {
734 lhs = mark_write(lhs);
735 if (expr->isCompoundAssignmentOp())
736 lhs = pet_expr_access_set_read(lhs, 1);
739 type_size = pet_clang_get_type_size(expr->getType(), ast_context);
740 return pet_expr_new_binary(type_size, op, lhs, rhs);
743 /* Construct a pet_tree for a variable declaration and
744 * add the declaration to the list of declarations
745 * inside the current compound statement.
747 __isl_give pet_tree *PetScan::extract(Decl *decl)
749 VarDecl *vd;
750 pet_expr *lhs, *rhs;
751 pet_tree *tree;
753 if (!isa<VarDecl>(decl)) {
754 report_unsupported_declaration(decl);
755 return NULL;
758 vd = cast<VarDecl>(decl);
759 declarations.push_back(vd);
761 lhs = extract_access_expr(vd);
762 lhs = mark_write(lhs);
763 if (!vd->getInit())
764 tree = pet_tree_new_decl(lhs);
765 else {
766 rhs = extract_expr(vd->getInit());
767 tree = pet_tree_new_decl_init(lhs, rhs);
770 return tree;
773 /* Construct a pet_tree for a variable declaration statement.
774 * If the declaration statement declares multiple variables,
775 * then return a group of pet_trees, one for each declared variable.
777 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
779 pet_tree *tree;
780 unsigned n;
782 if (!stmt->isSingleDecl()) {
783 const DeclGroup &group = stmt->getDeclGroup().getDeclGroup();
784 n = group.size();
785 tree = pet_tree_new_block(ctx, 0, n);
787 for (int i = 0; i < n; ++i) {
788 pet_tree *tree_i;
789 pet_loc *loc;
791 tree_i = extract(group[i]);
792 loc = construct_pet_loc(group[i]->getSourceRange(),
793 false);
794 tree_i = pet_tree_set_loc(tree_i, loc);
795 tree = pet_tree_block_add_child(tree, tree_i);
798 return tree;
801 return extract(stmt->getSingleDecl());
804 /* Construct a pet_expr representing a conditional operation.
806 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
808 pet_expr *cond, *lhs, *rhs;
810 cond = extract_expr(expr->getCond());
811 lhs = extract_expr(expr->getTrueExpr());
812 rhs = extract_expr(expr->getFalseExpr());
814 return pet_expr_new_ternary(cond, lhs, rhs);
817 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
819 return extract_expr(expr->getSubExpr());
822 /* Construct a pet_expr representing a floating point value.
824 * If the floating point literal does not appear in a macro,
825 * then we use the original representation in the source code
826 * as the string representation. Otherwise, we use the pretty
827 * printer to produce a string representation.
829 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
831 double d;
832 string s;
833 const LangOptions &LO = PP.getLangOpts();
834 SourceLocation loc = expr->getLocation();
836 if (!loc.isMacroID()) {
837 SourceManager &SM = PP.getSourceManager();
838 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
839 s = string(SM.getCharacterData(loc), len);
840 } else {
841 llvm::raw_string_ostream S(s);
842 expr->printPretty(S, 0, PrintingPolicy(LO));
843 S.str();
845 d = expr->getValueAsApproximateDouble();
846 return pet_expr_new_double(ctx, d, s.c_str());
849 /* Convert the index expression "index" into an access pet_expr of type "qt".
851 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
852 __isl_take pet_expr *index)
854 int depth;
855 int type_size;
857 depth = extract_depth(index);
858 type_size = pet_clang_get_type_size(qt, ast_context);
860 index = pet_expr_set_type_size(index, type_size);
861 index = pet_expr_access_set_depth(index, depth);
863 return index;
866 /* Extract an index expression from "expr" and then convert it into
867 * an access pet_expr.
869 * If "expr" is a reference to an enum constant, then return
870 * an integer expression instead, representing the value of the enum constant.
872 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
874 pet_expr *index;
876 index = extract_index_expr(expr);
878 if (pet_expr_get_type(index) == pet_expr_int)
879 return index;
881 return extract_access_expr(expr->getType(), index);
884 /* Extract an index expression from "decl" and then convert it into
885 * an access pet_expr.
887 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
889 return extract_access_expr(decl->getType(), extract_index_expr(decl));
892 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
894 return extract_expr(expr->getSubExpr());
897 /* Extract an assume statement from the argument "expr"
898 * of a __pencil_assume statement.
900 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
902 return pet_expr_new_unary(0, pet_op_assume, extract_expr(expr));
905 /* If "expr" is an address-of operator, then return its argument.
906 * Otherwise, return NULL.
908 static Expr *extract_addr_of_arg(Expr *expr)
910 UnaryOperator *op;
912 if (expr->getStmtClass() != Stmt::UnaryOperatorClass)
913 return NULL;
914 op = cast<UnaryOperator>(expr);
915 if (op->getOpcode() != UO_AddrOf)
916 return NULL;
917 return op->getSubExpr();
920 /* Construct a pet_expr corresponding to the function call argument "expr".
921 * The argument appears in position "pos" of a call to function "fd".
923 * If we are passing along a pointer to an array element
924 * or an entire row or even higher dimensional slice of an array,
925 * then the function being called may write into the array.
927 * We assume here that if the function is declared to take a pointer
928 * to a const type, then the function may only perform a read
929 * and that otherwise, it may either perform a read or a write (or both).
930 * We only perform this check if "detect_writes" is set.
932 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
933 Expr *expr, bool detect_writes)
935 Expr *arg;
936 pet_expr *res;
937 int is_addr = 0, is_partial = 0;
939 expr = pet_clang_strip_casts(expr);
940 arg = extract_addr_of_arg(expr);
941 if (arg) {
942 is_addr = 1;
943 expr = arg;
945 res = extract_expr(expr);
946 if (!res)
947 return NULL;
948 if (array_depth(expr->getType().getTypePtr()) > 0)
949 is_partial = 1;
950 if (detect_writes && (is_addr || is_partial) &&
951 pet_expr_get_type(res) == pet_expr_access) {
952 ParmVarDecl *parm;
953 if (!fd->hasPrototype()) {
954 report_prototype_required(expr);
955 return pet_expr_free(res);
957 parm = fd->getParamDecl(pos);
958 if (!const_base(parm->getType()))
959 res = mark_may_write(res);
962 if (is_addr)
963 res = pet_expr_new_unary(0, pet_op_address_of, res);
964 return res;
967 /* Find the first FunctionDecl with the given name.
968 * "call" is the corresponding call expression and is only used
969 * for reporting errors.
971 * Return NULL on error.
973 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
975 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
976 DeclContext::decl_iterator begin = tu->decls_begin();
977 DeclContext::decl_iterator end = tu->decls_end();
978 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
979 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
980 if (!fd)
981 continue;
982 if (fd->getName().str().compare(name) != 0)
983 continue;
984 if (fd->hasBody())
985 return fd;
986 report_missing_summary_function_body(call);
987 return NULL;
989 report_missing_summary_function(call);
990 return NULL;
993 /* Return the FunctionDecl for the summary function associated to the
994 * function called by "call".
996 * In particular, if the pencil option is set, then
997 * search for an annotate attribute formatted as
998 * "pencil_access(name)", where "name" is the name of the summary function.
1000 * If no summary function was specified, then return the FunctionDecl
1001 * that is actually being called.
1003 * Return NULL on error.
1005 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
1007 FunctionDecl *decl = call->getDirectCallee();
1008 if (!decl)
1009 return NULL;
1011 if (!options->pencil)
1012 return decl;
1014 specific_attr_iterator<AnnotateAttr> begin, end, i;
1015 begin = decl->specific_attr_begin<AnnotateAttr>();
1016 end = decl->specific_attr_end<AnnotateAttr>();
1017 for (i = begin; i != end; ++i) {
1018 string attr = (*i)->getAnnotation().str();
1020 const char prefix[] = "pencil_access(";
1021 size_t start = attr.find(prefix);
1022 if (start == string::npos)
1023 continue;
1024 start += strlen(prefix);
1025 string name = attr.substr(start, attr.find(')') - start);
1027 return find_decl_from_name(call, name);
1030 return decl;
1033 /* Construct a pet_expr representing a function call.
1035 * In the special case of a "call" to __pencil_assume,
1036 * construct an assume expression instead.
1038 * In the case of a "call" to __pencil_kill, the arguments
1039 * are neither read nor written (only killed), so there
1040 * is no need to check for writes to these arguments.
1042 * __pencil_assume and __pencil_kill are only recognized
1043 * when the pencil option is set.
1045 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1047 pet_expr *res = NULL;
1048 FunctionDecl *fd;
1049 string name;
1050 unsigned n_arg;
1051 bool is_kill;
1053 fd = expr->getDirectCallee();
1054 if (!fd) {
1055 unsupported(expr);
1056 return NULL;
1059 name = fd->getDeclName().getAsString();
1060 n_arg = expr->getNumArgs();
1062 if (options->pencil && n_arg == 1 && name == "__pencil_assume")
1063 return extract_assume(expr->getArg(0));
1064 is_kill = options->pencil && name == "__pencil_kill";
1066 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1067 if (!res)
1068 return NULL;
1070 for (int i = 0; i < n_arg; ++i) {
1071 Expr *arg = expr->getArg(i);
1072 res = pet_expr_set_arg(res, i,
1073 PetScan::extract_argument(fd, i, arg, !is_kill));
1076 fd = get_summary_function(expr);
1077 if (!fd)
1078 return pet_expr_free(res);
1080 res = set_summary(res, fd);
1082 return res;
1085 /* Construct a pet_expr representing a (C style) cast.
1087 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1089 pet_expr *arg;
1090 QualType type;
1092 arg = extract_expr(expr->getSubExpr());
1093 if (!arg)
1094 return NULL;
1096 type = expr->getTypeAsWritten();
1097 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1100 /* Construct a pet_expr representing an integer.
1102 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1104 return pet_expr_new_int(extract_int(expr));
1107 /* Construct a pet_expr representing the integer enum constant "ecd".
1109 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
1111 isl_val *v;
1112 const llvm::APSInt &init = ecd->getInitVal();
1113 v = ::extract_int(ctx, init.isSigned(), init);
1114 return pet_expr_new_int(v);
1117 /* Try and construct a pet_expr representing "expr".
1119 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1121 switch (expr->getStmtClass()) {
1122 case Stmt::UnaryOperatorClass:
1123 return extract_expr(cast<UnaryOperator>(expr));
1124 case Stmt::CompoundAssignOperatorClass:
1125 case Stmt::BinaryOperatorClass:
1126 return extract_expr(cast<BinaryOperator>(expr));
1127 case Stmt::ImplicitCastExprClass:
1128 return extract_expr(cast<ImplicitCastExpr>(expr));
1129 case Stmt::ArraySubscriptExprClass:
1130 case Stmt::DeclRefExprClass:
1131 case Stmt::MemberExprClass:
1132 return extract_access_expr(expr);
1133 case Stmt::IntegerLiteralClass:
1134 return extract_expr(cast<IntegerLiteral>(expr));
1135 case Stmt::FloatingLiteralClass:
1136 return extract_expr(cast<FloatingLiteral>(expr));
1137 case Stmt::ParenExprClass:
1138 return extract_expr(cast<ParenExpr>(expr));
1139 case Stmt::ConditionalOperatorClass:
1140 return extract_expr(cast<ConditionalOperator>(expr));
1141 case Stmt::CallExprClass:
1142 return extract_expr(cast<CallExpr>(expr));
1143 case Stmt::CStyleCastExprClass:
1144 return extract_expr(cast<CStyleCastExpr>(expr));
1145 default:
1146 unsupported(expr);
1148 return NULL;
1151 /* Check if the given initialization statement is an assignment.
1152 * If so, return that assignment. Otherwise return NULL.
1154 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1156 BinaryOperator *ass;
1158 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1159 return NULL;
1161 ass = cast<BinaryOperator>(init);
1162 if (ass->getOpcode() != BO_Assign)
1163 return NULL;
1165 return ass;
1168 /* Check if the given initialization statement is a declaration
1169 * of a single variable.
1170 * If so, return that declaration. Otherwise return NULL.
1172 Decl *PetScan::initialization_declaration(Stmt *init)
1174 DeclStmt *decl;
1176 if (init->getStmtClass() != Stmt::DeclStmtClass)
1177 return NULL;
1179 decl = cast<DeclStmt>(init);
1181 if (!decl->isSingleDecl())
1182 return NULL;
1184 return decl->getSingleDecl();
1187 /* Given the assignment operator in the initialization of a for loop,
1188 * extract the induction variable, i.e., the (integer)variable being
1189 * assigned.
1191 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1193 Expr *lhs;
1194 DeclRefExpr *ref;
1195 ValueDecl *decl;
1196 const Type *type;
1198 lhs = init->getLHS();
1199 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1200 unsupported(init);
1201 return NULL;
1204 ref = cast<DeclRefExpr>(lhs);
1205 decl = ref->getDecl();
1206 type = decl->getType().getTypePtr();
1208 if (!type->isIntegerType()) {
1209 unsupported(lhs);
1210 return NULL;
1213 return decl;
1216 /* Given the initialization statement of a for loop and the single
1217 * declaration in this initialization statement,
1218 * extract the induction variable, i.e., the (integer) variable being
1219 * declared.
1221 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1223 VarDecl *vd;
1225 vd = cast<VarDecl>(decl);
1227 const QualType type = vd->getType();
1228 if (!type->isIntegerType()) {
1229 unsupported(init);
1230 return NULL;
1233 if (!vd->getInit()) {
1234 unsupported(init);
1235 return NULL;
1238 return vd;
1241 /* Check that op is of the form iv++ or iv--.
1242 * Return a pet_expr representing "1" or "-1" accordingly.
1244 __isl_give pet_expr *PetScan::extract_unary_increment(
1245 clang::UnaryOperator *op, clang::ValueDecl *iv)
1247 Expr *sub;
1248 DeclRefExpr *ref;
1249 isl_val *v;
1251 if (!op->isIncrementDecrementOp()) {
1252 unsupported(op);
1253 return NULL;
1256 sub = op->getSubExpr();
1257 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1258 unsupported(op);
1259 return NULL;
1262 ref = cast<DeclRefExpr>(sub);
1263 if (ref->getDecl() != iv) {
1264 unsupported(op);
1265 return NULL;
1268 if (op->isIncrementOp())
1269 v = isl_val_one(ctx);
1270 else
1271 v = isl_val_negone(ctx);
1273 return pet_expr_new_int(v);
1276 /* Check if op is of the form
1278 * iv = expr
1280 * and return the increment "expr - iv" as a pet_expr.
1282 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1283 clang::ValueDecl *iv)
1285 int type_size;
1286 Expr *lhs;
1287 DeclRefExpr *ref;
1288 pet_expr *expr, *expr_iv;
1290 if (op->getOpcode() != BO_Assign) {
1291 unsupported(op);
1292 return NULL;
1295 lhs = op->getLHS();
1296 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1297 unsupported(op);
1298 return NULL;
1301 ref = cast<DeclRefExpr>(lhs);
1302 if (ref->getDecl() != iv) {
1303 unsupported(op);
1304 return NULL;
1307 expr = extract_expr(op->getRHS());
1308 expr_iv = extract_expr(lhs);
1310 type_size = pet_clang_get_type_size(iv->getType(), ast_context);
1311 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1314 /* Check that op is of the form iv += cst or iv -= cst
1315 * and return a pet_expr corresponding to cst or -cst accordingly.
1317 __isl_give pet_expr *PetScan::extract_compound_increment(
1318 CompoundAssignOperator *op, clang::ValueDecl *iv)
1320 Expr *lhs;
1321 DeclRefExpr *ref;
1322 bool neg = false;
1323 pet_expr *expr;
1324 BinaryOperatorKind opcode;
1326 opcode = op->getOpcode();
1327 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1328 unsupported(op);
1329 return NULL;
1331 if (opcode == BO_SubAssign)
1332 neg = true;
1334 lhs = op->getLHS();
1335 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1336 unsupported(op);
1337 return NULL;
1340 ref = cast<DeclRefExpr>(lhs);
1341 if (ref->getDecl() != iv) {
1342 unsupported(op);
1343 return NULL;
1346 expr = extract_expr(op->getRHS());
1347 if (neg) {
1348 int type_size;
1349 type_size = pet_clang_get_type_size(op->getType(), ast_context);
1350 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1353 return expr;
1356 /* Check that the increment of the given for loop increments
1357 * (or decrements) the induction variable "iv" and return
1358 * the increment as a pet_expr if successful.
1360 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1361 ValueDecl *iv)
1363 Stmt *inc = stmt->getInc();
1365 if (!inc) {
1366 report_missing_increment(stmt);
1367 return NULL;
1370 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1371 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1372 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1373 return extract_compound_increment(
1374 cast<CompoundAssignOperator>(inc), iv);
1375 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1376 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1378 unsupported(inc);
1379 return NULL;
1382 /* Construct a pet_tree for a while loop.
1384 * If we were only able to extract part of the body, then simply
1385 * return that part.
1387 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1389 pet_expr *pe_cond;
1390 pet_tree *tree;
1392 tree = extract(stmt->getBody());
1393 if (partial)
1394 return tree;
1395 pe_cond = extract_expr(stmt->getCond());
1396 tree = pet_tree_new_while(pe_cond, tree);
1398 return tree;
1401 /* Construct a pet_tree for a for statement.
1402 * The for loop is required to be of one of the following forms
1404 * for (i = init; condition; ++i)
1405 * for (i = init; condition; --i)
1406 * for (i = init; condition; i += constant)
1407 * for (i = init; condition; i -= constant)
1409 * We extract a pet_tree for the body and then include it in a pet_tree
1410 * of type pet_tree_for.
1412 * As a special case, we also allow a for loop of the form
1414 * for (;;)
1416 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1418 * If we were only able to extract part of the body, then simply
1419 * return that part.
1421 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1423 BinaryOperator *ass;
1424 Decl *decl;
1425 Stmt *init;
1426 Expr *lhs, *rhs;
1427 ValueDecl *iv;
1428 pet_tree *tree;
1429 struct pet_scop *scop;
1430 int independent;
1431 int declared;
1432 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1434 independent = is_current_stmt_marked_independent();
1436 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1437 tree = extract(stmt->getBody());
1438 if (partial)
1439 return tree;
1440 tree = pet_tree_new_infinite_loop(tree);
1441 return tree;
1444 init = stmt->getInit();
1445 if (!init) {
1446 unsupported(stmt);
1447 return NULL;
1449 if ((ass = initialization_assignment(init)) != NULL) {
1450 iv = extract_induction_variable(ass);
1451 if (!iv)
1452 return NULL;
1453 lhs = ass->getLHS();
1454 rhs = ass->getRHS();
1455 } else if ((decl = initialization_declaration(init)) != NULL) {
1456 VarDecl *var = extract_induction_variable(init, decl);
1457 if (!var)
1458 return NULL;
1459 iv = var;
1460 rhs = var->getInit();
1461 lhs = create_DeclRefExpr(var);
1462 } else {
1463 unsupported(stmt->getInit());
1464 return NULL;
1467 declared = !initialization_assignment(stmt->getInit());
1468 tree = extract(stmt->getBody());
1469 if (partial)
1470 return tree;
1471 pe_iv = extract_access_expr(iv);
1472 pe_iv = mark_write(pe_iv);
1473 pe_init = extract_expr(rhs);
1474 if (!stmt->getCond())
1475 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1476 else
1477 pe_cond = extract_expr(stmt->getCond());
1478 pe_inc = extract_increment(stmt, iv);
1479 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1480 pe_inc, tree);
1481 return tree;
1484 /* Store the names of the variables declared in decl_context
1485 * in the set declared_names. Make sure to only do this once by
1486 * setting declared_names_collected.
1488 void PetScan::collect_declared_names()
1490 DeclContext *DC = decl_context;
1491 DeclContext::decl_iterator it;
1493 if (declared_names_collected)
1494 return;
1496 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1497 Decl *D = *it;
1498 NamedDecl *named;
1500 if (!isa<NamedDecl>(D))
1501 continue;
1502 named = cast<NamedDecl>(D);
1503 declared_names.insert(named->getName().str());
1506 declared_names_collected = true;
1509 /* Add the names in "names" that are not also in this->declared_names
1510 * to this->used_names.
1511 * It is up to the caller to make sure that declared_names has been
1512 * populated, if needed.
1514 void PetScan::add_new_used_names(const std::set<std::string> &names)
1516 std::set<std::string>::const_iterator it;
1518 for (it = names.begin(); it != names.end(); ++it) {
1519 if (declared_names.find(*it) != declared_names.end())
1520 continue;
1521 used_names.insert(*it);
1525 /* Is the name "name" used in any declaration other than "decl"?
1527 * If the name was found to be in use before, the consider it to be in use.
1528 * Otherwise, check the DeclContext of the function containing the scop
1529 * as well as all ancestors of this DeclContext for declarations
1530 * other than "decl" that declare something called "name".
1532 bool PetScan::name_in_use(const string &name, Decl *decl)
1534 DeclContext *DC;
1535 DeclContext::decl_iterator it;
1537 if (used_names.find(name) != used_names.end())
1538 return true;
1540 for (DC = decl_context; DC; DC = DC->getParent()) {
1541 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1542 Decl *D = *it;
1543 NamedDecl *named;
1545 if (D == decl)
1546 continue;
1547 if (!isa<NamedDecl>(D))
1548 continue;
1549 named = cast<NamedDecl>(D);
1550 if (named->getName().str() == name)
1551 return true;
1555 return false;
1558 /* Generate a new name based on "name" that is not in use.
1559 * Do so by adding a suffix _i, with i an integer.
1561 string PetScan::generate_new_name(const string &name)
1563 string new_name;
1565 do {
1566 std::ostringstream oss;
1567 oss << name << "_" << n_rename++;
1568 new_name = oss.str();
1569 } while (name_in_use(new_name, NULL));
1571 return new_name;
1574 /* Try and construct a pet_tree corresponding to a compound statement.
1576 * "skip_declarations" is set if we should skip initial declarations
1577 * in the children of the compound statements.
1579 * Collect a new set of declarations for the current compound statement.
1580 * If any of the names in these declarations is also used by another
1581 * declaration reachable from the current function, then rename it
1582 * to a name that is not already in use.
1583 * In particular, keep track of the old and new names in a pet_substituter
1584 * and apply the substitutions to the pet_tree corresponding to the
1585 * compound statement.
1587 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1588 bool skip_declarations)
1590 pet_tree *tree;
1591 std::vector<VarDecl *> saved_declarations;
1592 std::vector<VarDecl *>::iterator it;
1593 pet_substituter substituter;
1595 saved_declarations = declarations;
1596 declarations.clear();
1597 tree = extract(stmt->children(), true, skip_declarations);
1598 for (it = declarations.begin(); it != declarations.end(); ++it) {
1599 isl_id *id;
1600 pet_expr *expr;
1601 VarDecl *decl = *it;
1602 string name = decl->getName().str();
1603 bool in_use = name_in_use(name, decl);
1605 used_names.insert(name);
1606 if (!in_use)
1607 continue;
1609 name = generate_new_name(name);
1610 id = pet_id_from_name_and_decl(ctx, name.c_str(), decl);
1611 expr = pet_id_create_index_expr(id);
1612 expr = extract_access_expr(decl->getType(), expr);
1613 id = pet_id_from_decl(ctx, decl);
1614 substituter.add_sub(id, expr);
1615 used_names.insert(name);
1617 tree = substituter.substitute(tree);
1618 declarations = saved_declarations;
1620 return tree;
1623 /* Return the file offset of the expansion location of "Loc".
1625 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1627 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1630 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1632 /* Return a SourceLocation for the location after the first semicolon
1633 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1634 * call it and also skip trailing spaces and newline.
1636 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1637 const LangOptions &LO)
1639 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1642 #else
1644 /* Return a SourceLocation for the location after the first semicolon
1645 * after "loc". If Lexer::findLocationAfterToken is not available,
1646 * we look in the underlying character data for the first semicolon.
1648 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1649 const LangOptions &LO)
1651 const char *semi;
1652 const char *s = SM.getCharacterData(loc);
1654 semi = strchr(s, ';');
1655 if (!semi)
1656 return SourceLocation();
1657 return loc.getFileLocWithOffset(semi + 1 - s);
1660 #endif
1662 /* If the token at "loc" is the first token on the line, then return
1663 * a location referring to the start of the line and set *indent
1664 * to the indentation of "loc"
1665 * Otherwise, return "loc" and set *indent to "".
1667 * This function is used to extend a scop to the start of the line
1668 * if the first token of the scop is also the first token on the line.
1670 * We look for the first token on the line. If its location is equal to "loc",
1671 * then the latter is the location of the first token on the line.
1673 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1674 SourceManager &SM, const LangOptions &LO, char **indent)
1676 std::pair<FileID, unsigned> file_offset_pair;
1677 llvm::StringRef file;
1678 const char *pos;
1679 Token tok;
1680 SourceLocation token_loc, line_loc;
1681 int col;
1682 const char *s;
1684 loc = SM.getExpansionLoc(loc);
1685 col = SM.getExpansionColumnNumber(loc);
1686 line_loc = loc.getLocWithOffset(1 - col);
1687 file_offset_pair = SM.getDecomposedLoc(line_loc);
1688 file = SM.getBufferData(file_offset_pair.first, NULL);
1689 pos = file.data() + file_offset_pair.second;
1691 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1692 file.begin(), pos, file.end());
1693 lexer.LexFromRawLexer(tok);
1694 token_loc = tok.getLocation();
1696 s = SM.getCharacterData(line_loc);
1697 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1699 if (token_loc == loc)
1700 return line_loc;
1701 else
1702 return loc;
1705 /* Construct a pet_loc corresponding to the region covered by "range".
1706 * If "skip_semi" is set, then we assume "range" is followed by
1707 * a semicolon and also include this semicolon.
1709 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1710 bool skip_semi)
1712 SourceLocation loc = range.getBegin();
1713 SourceManager &SM = PP.getSourceManager();
1714 const LangOptions &LO = PP.getLangOpts();
1715 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1716 unsigned start, end;
1717 char *indent;
1719 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1720 start = getExpansionOffset(SM, loc);
1721 loc = range.getEnd();
1722 if (skip_semi)
1723 loc = location_after_semi(loc, SM, LO);
1724 else
1725 loc = PP.getLocForEndOfToken(loc);
1726 end = getExpansionOffset(SM, loc);
1728 return pet_loc_alloc(ctx, start, end, line, indent);
1731 /* Convert a top-level pet_expr to an expression pet_tree.
1733 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1734 SourceRange range, bool skip_semi)
1736 pet_loc *loc;
1737 pet_tree *tree;
1739 tree = pet_tree_new_expr(expr);
1740 loc = construct_pet_loc(range, skip_semi);
1741 tree = pet_tree_set_loc(tree, loc);
1743 return tree;
1746 /* Construct a pet_tree for an if statement.
1748 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1750 pet_expr *pe_cond;
1751 pet_tree *tree, *tree_else;
1752 struct pet_scop *scop;
1753 int int_size;
1755 pe_cond = extract_expr(stmt->getCond());
1756 tree = extract(stmt->getThen());
1757 if (stmt->getElse()) {
1758 tree_else = extract(stmt->getElse());
1759 if (options->autodetect) {
1760 if (tree && !tree_else) {
1761 partial = true;
1762 pet_expr_free(pe_cond);
1763 return tree;
1765 if (!tree && tree_else) {
1766 partial = true;
1767 pet_expr_free(pe_cond);
1768 return tree_else;
1771 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1772 } else
1773 tree = pet_tree_new_if(pe_cond, tree);
1774 return tree;
1777 /* Try and construct a pet_tree for a label statement.
1779 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1781 isl_id *label;
1782 pet_tree *tree;
1784 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1786 tree = extract(stmt->getSubStmt());
1787 tree = pet_tree_set_label(tree, label);
1788 return tree;
1791 /* Update the location of "tree" to include the source range of "stmt".
1793 * Actually, we create a new location based on the source range of "stmt" and
1794 * then extend this new location to include the region of the original location.
1795 * This ensures that the line number of the final location refers to "stmt".
1797 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1799 pet_loc *loc, *tree_loc;
1801 tree_loc = pet_tree_get_loc(tree);
1802 loc = construct_pet_loc(stmt->getSourceRange(), false);
1803 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1804 pet_loc_free(tree_loc);
1806 tree = pet_tree_set_loc(tree, loc);
1807 return tree;
1810 /* Is "expr" of a type that can be converted to an access expression?
1812 static bool is_access_expr_type(Expr *expr)
1814 switch (expr->getStmtClass()) {
1815 case Stmt::ArraySubscriptExprClass:
1816 case Stmt::DeclRefExprClass:
1817 case Stmt::MemberExprClass:
1818 return true;
1819 default:
1820 return false;
1824 /* Tell the pet_inliner "inliner" about the formal arguments
1825 * in "fd" and the corresponding actual arguments in "call".
1826 * Return 0 if this was successful and -1 otherwise.
1828 * Any pointer argument is treated as an array.
1829 * The other arguments are treated as scalars.
1831 * In case of scalars, there is no restriction on the actual argument.
1832 * This actual argument is assigned to a variable with a name
1833 * that is derived from the name of the corresponding formal argument,
1834 * but made not to conflict with any variable names that are
1835 * already in use.
1837 * In case of arrays, the actual argument needs to be an expression
1838 * of a type that can be converted to an access expression or the address
1839 * of such an expression, ignoring implicit and redundant casts.
1841 int PetScan::set_inliner_arguments(pet_inliner &inliner, CallExpr *call,
1842 FunctionDecl *fd)
1844 unsigned n;
1846 n = fd->getNumParams();
1847 for (int i = 0; i < n; ++i) {
1848 ParmVarDecl *parm = fd->getParamDecl(i);
1849 QualType type = parm->getType();
1850 Expr *arg, *sub;
1851 pet_expr *expr;
1852 int is_addr = 0;
1854 arg = call->getArg(i);
1855 if (array_depth(type.getTypePtr()) == 0) {
1856 string name = parm->getName().str();
1857 if (name_in_use(name, NULL))
1858 name = generate_new_name(name);
1859 inliner.add_scalar_arg(parm, name, extract_expr(arg));
1860 continue;
1862 arg = pet_clang_strip_casts(arg);
1863 sub = extract_addr_of_arg(arg);
1864 if (sub) {
1865 is_addr = 1;
1866 arg = pet_clang_strip_casts(sub);
1868 if (!is_access_expr_type(arg)) {
1869 report_unsupported_inline_function_argument(arg);
1870 return -1;
1872 expr = extract_access_expr(arg);
1873 if (!expr)
1874 return -1;
1875 inliner.add_array_arg(parm, expr, is_addr);
1878 return 0;
1881 /* Try and construct a pet_tree from the body of "fd" using the actual
1882 * arguments in "call" in place of the formal arguments.
1883 * "fd" is assumed to point to the declaration with a function body.
1884 * In particular, construct a block that consists of assignments
1885 * of (parts of) the actual arguments to temporary variables
1886 * followed by the inlined function body with the formal arguments
1887 * replaced by (expressions containing) these temporary variables.
1889 * The actual inlining is taken care of by the pet_inliner function.
1890 * This function merely calls set_inliner_arguments to tell
1891 * the pet_inliner about the actual arguments, extracts a pet_tree
1892 * from the body of the called function and then passes this pet_tree
1893 * to the pet_inliner.
1895 * During the extraction of the function body, all variables names
1896 * that are declared in the calling function as well all variable
1897 * names that are known to be in use are considered to be in use
1898 * in the called function to ensure that there is no naming conflict.
1899 * Similarly, the additional names that are in use in the called function
1900 * are considered to be in use in the calling function as well.
1902 * The location of the pet_tree is reset to the call site to ensure
1903 * that the extent of the scop does not include the body of the called
1904 * function.
1906 __isl_give pet_tree *PetScan::extract_inlined_call(CallExpr *call,
1907 FunctionDecl *fd)
1909 int save_autodetect;
1910 pet_tree *tree;
1911 pet_loc *tree_loc;
1912 pet_inliner inliner(ctx, n_arg, ast_context);
1914 if (set_inliner_arguments(inliner, call, fd) < 0)
1915 return NULL;
1917 save_autodetect = options->autodetect;
1918 options->autodetect = 0;
1919 PetScan body_scan(PP, ast_context, fd, loc, options,
1920 isl_union_map_copy(value_bounds), independent);
1921 collect_declared_names();
1922 body_scan.add_new_used_names(declared_names);
1923 body_scan.add_new_used_names(used_names);
1924 tree = body_scan.extract(fd->getBody(), false);
1925 add_new_used_names(body_scan.used_names);
1926 options->autodetect = save_autodetect;
1928 tree_loc = construct_pet_loc(call->getSourceRange(), true);
1929 tree = pet_tree_set_loc(tree, tree_loc);
1931 return inliner.inline_tree(tree);
1934 /* Try and construct a pet_tree corresponding
1935 * to the expression statement "stmt".
1937 * If the outer expression is a function call and if the corresponding
1938 * function body is marked "inline", then return a pet_tree
1939 * corresponding to the inlined function.
1941 __isl_give pet_tree *PetScan::extract_expr_stmt(Stmt *stmt)
1943 pet_expr *expr;
1945 if (stmt->getStmtClass() == Stmt::CallExprClass) {
1946 CallExpr *call = cast<CallExpr>(stmt);
1947 FunctionDecl *fd = call->getDirectCallee();
1948 fd = pet_clang_find_function_decl_with_body(fd);
1949 if (fd && fd->isInlineSpecified())
1950 return extract_inlined_call(call, fd);
1953 expr = extract_expr(cast<Expr>(stmt));
1954 return extract(expr, stmt->getSourceRange(), true);
1957 /* Try and construct a pet_tree corresponding to "stmt".
1959 * If "stmt" is a compound statement, then "skip_declarations"
1960 * indicates whether we should skip initial declarations in the
1961 * compound statement.
1963 * If the constructed pet_tree is not a (possibly) partial representation
1964 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1965 * In particular, if skip_declarations is set, then we may have skipped
1966 * declarations inside "stmt" and so the pet_scop may not represent
1967 * the entire "stmt".
1968 * Note that this function may be called with "stmt" referring to the entire
1969 * body of the function, including the outer braces. In such cases,
1970 * skip_declarations will be set and the braces will not be taken into
1971 * account in tree->loc.
1973 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
1975 pet_tree *tree;
1977 set_current_stmt(stmt);
1979 if (isa<Expr>(stmt))
1980 return extract_expr_stmt(cast<Expr>(stmt));
1982 switch (stmt->getStmtClass()) {
1983 case Stmt::WhileStmtClass:
1984 tree = extract(cast<WhileStmt>(stmt));
1985 break;
1986 case Stmt::ForStmtClass:
1987 tree = extract_for(cast<ForStmt>(stmt));
1988 break;
1989 case Stmt::IfStmtClass:
1990 tree = extract(cast<IfStmt>(stmt));
1991 break;
1992 case Stmt::CompoundStmtClass:
1993 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
1994 break;
1995 case Stmt::LabelStmtClass:
1996 tree = extract(cast<LabelStmt>(stmt));
1997 break;
1998 case Stmt::ContinueStmtClass:
1999 tree = pet_tree_new_continue(ctx);
2000 break;
2001 case Stmt::BreakStmtClass:
2002 tree = pet_tree_new_break(ctx);
2003 break;
2004 case Stmt::DeclStmtClass:
2005 tree = extract(cast<DeclStmt>(stmt));
2006 break;
2007 default:
2008 report_unsupported_statement_type(stmt);
2009 return NULL;
2012 if (partial || skip_declarations)
2013 return tree;
2015 return update_loc(tree, stmt);
2018 /* Given a sequence of statements "stmt_range" of which the first "n_decl"
2019 * are declarations and of which the remaining statements are represented
2020 * by "tree", try and extend "tree" to include the last sequence of
2021 * the initial declarations that can be completely extracted.
2023 * We start collecting the initial declarations and start over
2024 * whenever we come across a declaration that we cannot extract.
2025 * If we have been able to extract any declarations, then we
2026 * copy over the contents of "tree" at the end of the declarations.
2027 * Otherwise, we simply return the original "tree".
2029 __isl_give pet_tree *PetScan::insert_initial_declarations(
2030 __isl_take pet_tree *tree, int n_decl, StmtRange stmt_range)
2032 StmtIterator i;
2033 pet_tree *res;
2034 int n_stmt;
2035 int is_block;
2036 int j;
2038 n_stmt = pet_tree_block_n_child(tree);
2039 is_block = pet_tree_block_get_block(tree);
2040 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2042 for (i = stmt_range.first; n_decl; ++i, --n_decl) {
2043 Stmt *child = *i;
2044 pet_tree *tree_i;
2046 tree_i = extract(child);
2047 if (tree_i && !partial) {
2048 res = pet_tree_block_add_child(res, tree_i);
2049 continue;
2051 pet_tree_free(tree_i);
2052 partial = false;
2053 if (pet_tree_block_n_child(res) == 0)
2054 continue;
2055 pet_tree_free(res);
2056 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2059 if (pet_tree_block_n_child(res) == 0) {
2060 pet_tree_free(res);
2061 return tree;
2064 for (j = 0; j < n_stmt; ++j) {
2065 pet_tree *tree_i;
2067 tree_i = pet_tree_block_get_child(tree, j);
2068 res = pet_tree_block_add_child(res, tree_i);
2070 pet_tree_free(tree);
2072 return res;
2075 /* Try and construct a pet_tree corresponding to (part of)
2076 * a sequence of statements.
2078 * "block" is set if the sequence represents the children of
2079 * a compound statement.
2080 * "skip_declarations" is set if we should skip initial declarations
2081 * in the sequence of statements.
2083 * If autodetect is set, then we allow the extraction of only a subrange
2084 * of the sequence of statements. However, if there is at least one
2085 * kill and there is some subsequent statement for which we could not
2086 * construct a tree, then turn off the "block" property of the tree
2087 * such that no extra kill will be introduced at the end of the (partial)
2088 * block. If, on the other hand, the final range contains
2089 * no statements, then we discard the entire range.
2091 * If the entire range was extracted, apart from some initial declarations,
2092 * then we try and extend the range with the latest of those initial
2093 * declarations.
2095 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
2096 bool skip_declarations)
2098 StmtIterator i;
2099 int j, skip;
2100 bool has_kills = false;
2101 bool partial_range = false;
2102 pet_tree *tree;
2104 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
2107 tree = pet_tree_new_block(ctx, block, j);
2109 skip = 0;
2110 i = stmt_range.first;
2111 if (skip_declarations)
2112 for (; i != stmt_range.second; ++i) {
2113 if ((*i)->getStmtClass() != Stmt::DeclStmtClass)
2114 break;
2115 ++skip;
2118 for (; i != stmt_range.second; ++i) {
2119 Stmt *child = *i;
2120 pet_tree *tree_i;
2122 tree_i = extract(child);
2123 if (pet_tree_block_n_child(tree) != 0 && partial) {
2124 pet_tree_free(tree_i);
2125 break;
2127 if (tree_i && child->getStmtClass() == Stmt::DeclStmtClass &&
2128 block)
2129 has_kills = true;
2130 if (options->autodetect) {
2131 if (tree_i)
2132 tree = pet_tree_block_add_child(tree, tree_i);
2133 else
2134 partial_range = true;
2135 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
2136 partial = true;
2137 } else {
2138 tree = pet_tree_block_add_child(tree, tree_i);
2141 if (partial || !tree)
2142 break;
2145 if (!tree)
2146 return NULL;
2148 if (partial) {
2149 if (has_kills)
2150 tree = pet_tree_block_set_block(tree, 0);
2151 } else if (partial_range) {
2152 if (pet_tree_block_n_child(tree) == 0) {
2153 pet_tree_free(tree);
2154 return NULL;
2156 partial = true;
2157 } else if (skip > 0)
2158 tree = insert_initial_declarations(tree, skip, stmt_range);
2160 return tree;
2163 extern "C" {
2164 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2165 void *user);
2166 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2167 __isl_keep pet_context *pc, void *user);
2170 /* Construct a pet_expr that holds the sizes of the array accessed
2171 * by "access".
2172 * This function is used as a callback to pet_context_add_parameters,
2173 * which is also passed a pointer to the PetScan object.
2175 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2176 void *user)
2178 PetScan *ps = (PetScan *) user;
2179 isl_id *id;
2180 const Type *type;
2182 id = pet_expr_access_get_id(access);
2183 type = pet_id_get_array_type(id).getTypePtr();
2184 isl_id_free(id);
2185 return ps->get_array_size(type);
2188 /* Construct and return a pet_array corresponding to the variable
2189 * accessed by "access".
2190 * This function is used as a callback to pet_scop_from_pet_tree,
2191 * which is also passed a pointer to the PetScan object.
2193 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2194 __isl_keep pet_context *pc, void *user)
2196 PetScan *ps = (PetScan *) user;
2197 isl_ctx *ctx;
2198 isl_id *id;
2199 pet_array *array;
2201 ctx = pet_expr_get_ctx(access);
2202 id = pet_expr_access_get_id(access);
2203 array = ps->extract_array(id, NULL, pc);
2204 isl_id_free(id);
2206 return array;
2209 /* Extract a function summary from the body of "fd".
2211 * We extract a scop from the function body in a context with as
2212 * parameters the integer arguments of the function.
2213 * We turn off autodetection (in case it was set) to ensure that
2214 * the entire function body is considered.
2215 * We then collect the accessed array elements and attach them
2216 * to the corresponding array arguments, taking into account
2217 * that the function body may access members of array elements.
2219 * The reason for representing the integer arguments as parameters in
2220 * the context is that if we were to instead start with a context
2221 * with the function arguments as initial dimensions, then we would not
2222 * be able to refer to them from the array extents, without turning
2223 * array extents into maps.
2225 * The result is stored in the summary_cache cache so that we can reuse
2226 * it if this method gets called on the same function again later on.
2228 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
2230 isl_space *space;
2231 isl_set *domain;
2232 pet_context *pc;
2233 pet_tree *tree;
2234 pet_function_summary *summary;
2235 unsigned n;
2236 ScopLoc loc;
2237 int save_autodetect;
2238 struct pet_scop *scop;
2239 int int_size;
2240 isl_union_set *may_read, *may_write, *must_write;
2241 isl_union_map *to_inner;
2243 if (summary_cache.find(fd) != summary_cache.end())
2244 return pet_function_summary_copy(summary_cache[fd]);
2246 space = isl_space_set_alloc(ctx, 0, 0);
2248 n = fd->getNumParams();
2249 summary = pet_function_summary_alloc(ctx, n);
2250 for (int i = 0; i < n; ++i) {
2251 ParmVarDecl *parm = fd->getParamDecl(i);
2252 QualType type = parm->getType();
2253 isl_id *id;
2255 if (!type->isIntegerType())
2256 continue;
2257 id = pet_id_from_decl(ctx, parm);
2258 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
2259 space = isl_space_set_dim_id(space, isl_dim_param, 0,
2260 isl_id_copy(id));
2261 summary = pet_function_summary_set_int(summary, i, id);
2264 save_autodetect = options->autodetect;
2265 options->autodetect = 0;
2266 PetScan body_scan(PP, ast_context, fd, loc, options,
2267 isl_union_map_copy(value_bounds), independent);
2269 tree = body_scan.extract(fd->getBody(), false);
2271 domain = isl_set_universe(space);
2272 pc = pet_context_alloc(domain);
2273 pc = pet_context_add_parameters(pc, tree,
2274 &::get_array_size, &body_scan);
2275 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2276 scop = pet_scop_from_pet_tree(tree, int_size,
2277 &::extract_array, &body_scan, pc);
2278 scop = scan_arrays(scop, pc);
2279 may_read = isl_union_map_range(pet_scop_get_may_reads(scop));
2280 may_write = isl_union_map_range(pet_scop_get_may_writes(scop));
2281 must_write = isl_union_map_range(pet_scop_get_must_writes(scop));
2282 to_inner = pet_scop_compute_outer_to_inner(scop);
2283 pet_scop_free(scop);
2285 for (int i = 0; i < n; ++i) {
2286 ParmVarDecl *parm = fd->getParamDecl(i);
2287 QualType type = parm->getType();
2288 struct pet_array *array;
2289 isl_space *space;
2290 isl_union_set *data_set;
2291 isl_union_set *may_read_i, *may_write_i, *must_write_i;
2293 if (array_depth(type.getTypePtr()) == 0)
2294 continue;
2296 array = body_scan.extract_array(parm, NULL, pc);
2297 space = array ? isl_set_get_space(array->extent) : NULL;
2298 pet_array_free(array);
2299 data_set = isl_union_set_from_set(isl_set_universe(space));
2300 data_set = isl_union_set_apply(data_set,
2301 isl_union_map_copy(to_inner));
2302 may_read_i = isl_union_set_intersect(
2303 isl_union_set_copy(may_read),
2304 isl_union_set_copy(data_set));
2305 may_write_i = isl_union_set_intersect(
2306 isl_union_set_copy(may_write),
2307 isl_union_set_copy(data_set));
2308 must_write_i = isl_union_set_intersect(
2309 isl_union_set_copy(must_write), data_set);
2310 summary = pet_function_summary_set_array(summary, i,
2311 may_read_i, may_write_i, must_write_i);
2314 isl_union_set_free(may_read);
2315 isl_union_set_free(may_write);
2316 isl_union_set_free(must_write);
2317 isl_union_map_free(to_inner);
2319 options->autodetect = save_autodetect;
2320 pet_context_free(pc);
2322 summary_cache[fd] = pet_function_summary_copy(summary);
2324 return summary;
2327 /* If "fd" has a function body, then extract a function summary from
2328 * this body and attach it to the call expression "expr".
2330 * Even if a function body is available, "fd" itself may point
2331 * to a declaration without function body. We therefore first
2332 * replace it by the declaration that comes with a body (if any).
2334 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
2335 FunctionDecl *fd)
2337 pet_function_summary *summary;
2339 if (!expr)
2340 return NULL;
2341 fd = pet_clang_find_function_decl_with_body(fd);
2342 if (!fd)
2343 return expr;
2345 summary = get_summary(fd);
2347 expr = pet_expr_call_set_summary(expr, summary);
2349 return expr;
2352 /* Extract a pet_scop from "tree".
2354 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
2355 * then add pet_arrays for all accessed arrays.
2356 * We populate the pet_context with assignments for all parameters used
2357 * inside "tree" or any of the size expressions for the arrays accessed
2358 * by "tree" so that they can be used in affine expressions.
2360 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
2362 int int_size;
2363 isl_set *domain;
2364 pet_context *pc;
2365 pet_scop *scop;
2367 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2369 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2370 pc = pet_context_alloc(domain);
2371 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
2372 scop = pet_scop_from_pet_tree(tree, int_size,
2373 &::extract_array, this, pc);
2374 scop = scan_arrays(scop, pc);
2375 pet_context_free(pc);
2377 return scop;
2380 /* Given a DeclRefExpr or an ArraySubscriptExpr, return a pointer
2381 * to the base DeclRefExpr.
2382 * If the expression is something other than a nested ArraySubscriptExpr
2383 * with a DeclRefExpr at the base, then return NULL.
2385 static DeclRefExpr *extract_array_base(Expr *expr)
2387 while (isa<ArraySubscriptExpr>(expr)) {
2388 expr = (cast<ArraySubscriptExpr>(expr))->getBase();
2389 expr = pet_clang_strip_casts(expr);
2391 return dyn_cast<DeclRefExpr>(expr);
2394 /* Structure for keeping track of local variables that can be killed
2395 * after the scop.
2396 * In particular, variables of interest are first added to "locals"
2397 * Then the Stmt in which the variable declaration appears is scanned
2398 * for any possible leak of a pointer or any use after a specified scop.
2399 * In such cases, the variable is removed from "locals".
2400 * The scop is assumed to appear at the same level of the declaration.
2401 * In particular, it does not appear inside a nested control structure,
2402 * meaning that it is sufficient to look at uses of the variables
2403 * that textually appear after the specified scop.
2405 * locals is the set of variables of interest.
2406 * accessed keeps track of the variables that are accessed inside the scop.
2407 * scop_start is the start of the scop
2408 * scop_end is the end of the scop
2409 * addr_end is the end of the latest visited address_of expression.
2410 * expr_end is the end of the latest handled expression.
2412 struct killed_locals : RecursiveASTVisitor<killed_locals> {
2413 SourceManager &SM;
2414 set<ValueDecl *> locals;
2415 set<ValueDecl *> accessed;
2416 unsigned scop_start;
2417 unsigned scop_end;
2418 unsigned addr_end;
2419 unsigned expr_end;
2421 killed_locals(SourceManager &SM) : SM(SM) {}
2423 void add_local(Decl *decl);
2424 void add_locals(DeclStmt *stmt);
2425 void set_addr_end(UnaryOperator *expr);
2426 bool check_decl_in_expr(Expr *expr);
2427 void remove_accessed_after(Stmt *stmt, unsigned start, unsigned end);
2428 bool VisitUnaryOperator(UnaryOperator *expr) {
2429 if (expr->getOpcode() == UO_AddrOf)
2430 set_addr_end(expr);
2431 return true;
2433 bool VisitArraySubscriptExpr(ArraySubscriptExpr *expr) {
2434 return check_decl_in_expr(expr);
2436 bool VisitDeclRefExpr(DeclRefExpr *expr) {
2437 return check_decl_in_expr(expr);
2439 void dump() {
2440 set<ValueDecl *>::iterator it;
2441 cerr << "local" << endl;
2442 for (it = locals.begin(); it != locals.end(); ++it)
2443 (*it)->dump();
2444 cerr << "accessed" << endl;
2445 for (it = accessed.begin(); it != accessed.end(); ++it)
2446 (*it)->dump();
2450 /* Add "decl" to the set of local variables, provided it is a ValueDecl.
2452 void killed_locals::add_local(Decl *decl)
2454 ValueDecl *vd;
2456 vd = dyn_cast<ValueDecl>(decl);
2457 if (vd)
2458 locals.insert(vd);
2461 /* Add all variables declared by "stmt" to the set of local variables.
2463 void killed_locals::add_locals(DeclStmt *stmt)
2465 if (stmt->isSingleDecl()) {
2466 add_local(stmt->getSingleDecl());
2467 } else {
2468 const DeclGroup &group = stmt->getDeclGroup().getDeclGroup();
2469 unsigned n = group.size();
2470 for (int i = 0; i < n; ++i)
2471 add_local(group[i]);
2475 /* Set this->addr_end to the end of the address_of expression "expr".
2477 void killed_locals::set_addr_end(UnaryOperator *expr)
2479 addr_end = getExpansionOffset(SM, expr->getLocEnd());
2482 /* Given an expression of type ArraySubscriptExpr or DeclRefExpr,
2483 * check two things
2484 * - is the variable used inside the scop?
2485 * - is the variable used after the scop or can a pointer be taken?
2486 * Return true if the traversal should continue.
2488 * Reset the pointer to the end of the latest address-of expression
2489 * such that only the first array or scalar is considered to have
2490 * its address taken. In particular, accesses inside the indices
2491 * of the array should not be considered to have their address taken.
2493 * If the variable is not one of the local variables or
2494 * if the access appears inside an expression that was already handled,
2495 * then simply return.
2497 * Otherwise, the expression is handled and "expr_end" is updated
2498 * to prevent subexpressions with the same base expression
2499 * from being handled as well.
2501 * If a higher-dimensional slice of an array is accessed or
2502 * if the access appears inside an address-of expression,
2503 * then a pointer may leak, so the variable should not be killed.
2504 * Similarly, if the access appears after the end of the scop,
2505 * then the variable should not be killed.
2507 * Otherwise, if the access appears inside the scop, then
2508 * keep track of the fact that the variable was accessed at least once
2509 * inside the scop.
2511 bool killed_locals::check_decl_in_expr(Expr *expr)
2513 unsigned loc;
2514 int depth;
2515 DeclRefExpr *ref;
2516 ValueDecl *decl;
2517 unsigned old_addr_end;
2519 ref = extract_array_base(expr);
2520 if (!ref)
2521 return true;
2523 old_addr_end = addr_end;
2524 addr_end = 0;
2526 decl = ref->getDecl();
2527 if (locals.find(decl) == locals.end())
2528 return true;
2529 loc = getExpansionOffset(SM, expr->getLocStart());
2530 if (loc <= expr_end)
2531 return true;
2533 expr_end = getExpansionOffset(SM, ref->getLocEnd());
2534 depth = array_depth(expr->getType().getTypePtr());
2535 if (loc >= scop_end || loc <= old_addr_end || depth != 0)
2536 locals.erase(decl);
2537 if (loc >= scop_start && loc <= scop_end)
2538 accessed.insert(decl);
2540 return locals.size() != 0;
2543 /* Remove the local variables that may be accessed inside "stmt" after
2544 * the scop starting at "start" and ending at "end", or that
2545 * are not accessed at all inside that scop.
2547 * If there are no local variables that could potentially be killed,
2548 * then simply return.
2550 * Otherwise, scan "stmt" for any potential use of the variables
2551 * after the scop. This includes a possible pointer being taken
2552 * to (part of) the variable. If there is any such use, then
2553 * the variable is removed from the set of local variables.
2555 * At the same time, keep track of the variables that are
2556 * used anywhere inside the scop. At the end, replace the local
2557 * variables with the intersection with these accessed variables.
2559 void killed_locals::remove_accessed_after(Stmt *stmt, unsigned start,
2560 unsigned end)
2562 set<ValueDecl *> accessed_local;
2564 if (locals.size() == 0)
2565 return;
2566 scop_start = start;
2567 scop_end = end;
2568 addr_end = 0;
2569 expr_end = 0;
2570 TraverseStmt(stmt);
2571 set_intersection(locals.begin(), locals.end(),
2572 accessed.begin(), accessed.end(),
2573 inserter(accessed_local, accessed_local.begin()));
2574 locals = accessed_local;
2577 /* Add a call to __pencil_kill to the end of "tree" that kills
2578 * all the variables in "locals" and return the result.
2580 * No location is added to the kill because the most natural
2581 * location would lie outside the scop. Attaching such a location
2582 * to this tree would extend the scope of the final result
2583 * to include the location.
2585 __isl_give pet_tree *PetScan::add_kills(__isl_take pet_tree *tree,
2586 set<ValueDecl *> locals)
2588 int i;
2589 pet_expr *expr;
2590 pet_tree *kill, *block;
2591 set<ValueDecl *>::iterator it;
2593 if (locals.size() == 0)
2594 return tree;
2595 expr = pet_expr_new_call(ctx, "__pencil_kill", locals.size());
2596 i = 0;
2597 for (it = locals.begin(); it != locals.end(); ++it) {
2598 pet_expr *arg;
2599 arg = extract_access_expr(*it);
2600 expr = pet_expr_set_arg(expr, i++, arg);
2602 kill = pet_tree_new_expr(expr);
2603 block = pet_tree_new_block(ctx, 0, 2);
2604 block = pet_tree_block_add_child(block, tree);
2605 block = pet_tree_block_add_child(block, kill);
2607 return block;
2610 /* Check if the scop marked by the user is exactly this Stmt
2611 * or part of this Stmt.
2612 * If so, return a pet_scop corresponding to the marked region.
2613 * Otherwise, return NULL.
2615 * If the scop is not further nested inside a child of "stmt",
2616 * then check if there are any variable declarations before the scop
2617 * inside "stmt". If so, and if these variables are not used
2618 * after the scop, then add kills to the variables.
2620 struct pet_scop *PetScan::scan(Stmt *stmt)
2622 SourceManager &SM = PP.getSourceManager();
2623 unsigned start_off, end_off;
2624 pet_tree *tree;
2626 start_off = getExpansionOffset(SM, stmt->getLocStart());
2627 end_off = getExpansionOffset(SM, stmt->getLocEnd());
2629 if (start_off > loc.end)
2630 return NULL;
2631 if (end_off < loc.start)
2632 return NULL;
2634 if (start_off >= loc.start && end_off <= loc.end)
2635 return extract_scop(extract(stmt));
2637 killed_locals kl(SM);
2638 StmtIterator start;
2639 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
2640 Stmt *child = *start;
2641 if (!child)
2642 continue;
2643 start_off = getExpansionOffset(SM, child->getLocStart());
2644 end_off = getExpansionOffset(SM, child->getLocEnd());
2645 if (start_off < loc.start && end_off >= loc.end)
2646 return scan(child);
2647 if (start_off >= loc.start)
2648 break;
2649 if (isa<DeclStmt>(child))
2650 kl.add_locals(cast<DeclStmt>(child));
2653 StmtIterator end;
2654 for (end = start; end != stmt->child_end(); ++end) {
2655 Stmt *child = *end;
2656 start_off = SM.getFileOffset(child->getLocStart());
2657 if (start_off >= loc.end)
2658 break;
2661 kl.remove_accessed_after(stmt, loc.start, loc.end);
2663 tree = extract(StmtRange(start, end), false, false);
2664 tree = add_kills(tree, kl.locals);
2665 return extract_scop(tree);
2668 /* Set the size of index "pos" of "array" to "size".
2669 * In particular, add a constraint of the form
2671 * i_pos < size
2673 * to array->extent and a constraint of the form
2675 * size >= 0
2677 * to array->context.
2679 * The domain of "size" is assumed to be zero-dimensional.
2681 static struct pet_array *update_size(struct pet_array *array, int pos,
2682 __isl_take isl_pw_aff *size)
2684 isl_set *valid;
2685 isl_set *univ;
2686 isl_set *bound;
2687 isl_space *dim;
2688 isl_aff *aff;
2689 isl_pw_aff *index;
2690 isl_id *id;
2692 if (!array)
2693 goto error;
2695 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2696 array->context = isl_set_intersect(array->context, valid);
2698 dim = isl_set_get_space(array->extent);
2699 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2700 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2701 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2702 index = isl_pw_aff_alloc(univ, aff);
2704 size = isl_pw_aff_add_dims(size, isl_dim_in,
2705 isl_set_dim(array->extent, isl_dim_set));
2706 id = isl_set_get_tuple_id(array->extent);
2707 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2708 bound = isl_pw_aff_lt_set(index, size);
2710 array->extent = isl_set_intersect(array->extent, bound);
2712 if (!array->context || !array->extent)
2713 return pet_array_free(array);
2715 return array;
2716 error:
2717 isl_pw_aff_free(size);
2718 return NULL;
2721 #ifdef HAVE_DECAYEDTYPE
2723 /* If "type" is a decayed type, then set *decayed to true and
2724 * return the original type.
2726 static const Type *undecay(const Type *type, bool *decayed)
2728 *decayed = isa<DecayedType>(type);
2729 if (*decayed)
2730 type = cast<DecayedType>(type)->getOriginalType().getTypePtr();
2731 return type;
2734 #else
2736 /* If "type" is a decayed type, then set *decayed to true and
2737 * return the original type.
2738 * Since this version of clang does not define a DecayedType,
2739 * we cannot obtain the original type even if it had been decayed and
2740 * we set *decayed to false.
2742 static const Type *undecay(const Type *type, bool *decayed)
2744 *decayed = false;
2745 return type;
2748 #endif
2750 /* Figure out the size of the array at position "pos" and all
2751 * subsequent positions from "type" and update the corresponding
2752 * argument of "expr" accordingly.
2754 * The initial type (when pos is zero) may be a pointer type decayed
2755 * from an array type, if this initial type is the type of a function
2756 * argument. This only happens if the original array type has
2757 * a constant size in the outer dimension as otherwise we get
2758 * a VariableArrayType. Try and obtain this original type (if available) and
2759 * take the outer array size into account if it was marked static.
2761 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2762 const Type *type, int pos)
2764 const ArrayType *atype;
2765 pet_expr *size;
2766 bool decayed = false;
2768 if (!expr)
2769 return NULL;
2771 if (pos == 0)
2772 type = undecay(type, &decayed);
2774 if (type->isPointerType()) {
2775 type = type->getPointeeType().getTypePtr();
2776 return set_upper_bounds(expr, type, pos + 1);
2778 if (!type->isArrayType())
2779 return expr;
2781 type = type->getCanonicalTypeInternal().getTypePtr();
2782 atype = cast<ArrayType>(type);
2784 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2785 type = atype->getElementType().getTypePtr();
2786 return set_upper_bounds(expr, type, pos + 1);
2789 if (type->isConstantArrayType()) {
2790 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2791 size = extract_expr(ca->getSize());
2792 expr = pet_expr_set_arg(expr, pos, size);
2793 } else if (type->isVariableArrayType()) {
2794 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2795 size = extract_expr(vla->getSizeExpr());
2796 expr = pet_expr_set_arg(expr, pos, size);
2799 type = atype->getElementType().getTypePtr();
2801 return set_upper_bounds(expr, type, pos + 1);
2804 /* Construct a pet_expr that holds the sizes of an array of the given type.
2805 * The returned expression is a call expression with as arguments
2806 * the sizes in each dimension. If we are unable to derive the size
2807 * in a given dimension, then the corresponding argument is set to infinity.
2808 * In fact, we initialize all arguments to infinity and then update
2809 * them if we are able to figure out the size.
2811 * The result is stored in the type_size cache so that we can reuse
2812 * it if this method gets called on the same type again later on.
2814 __isl_give pet_expr *PetScan::get_array_size(const Type *type)
2816 int depth;
2817 pet_expr *expr, *inf;
2819 if (type_size.find(type) != type_size.end())
2820 return pet_expr_copy(type_size[type]);
2822 depth = array_depth(type);
2823 inf = pet_expr_new_int(isl_val_infty(ctx));
2824 expr = pet_expr_new_call(ctx, "bounds", depth);
2825 for (int i = 0; i < depth; ++i)
2826 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2827 pet_expr_free(inf);
2829 expr = set_upper_bounds(expr, type, 0);
2830 type_size[type] = pet_expr_copy(expr);
2832 return expr;
2835 /* Does "expr" represent the "integer" infinity?
2837 static int is_infty(__isl_keep pet_expr *expr)
2839 isl_val *v;
2840 int res;
2842 if (pet_expr_get_type(expr) != pet_expr_int)
2843 return 0;
2844 v = pet_expr_int_get_val(expr);
2845 res = isl_val_is_infty(v);
2846 isl_val_free(v);
2848 return res;
2851 /* Figure out the dimensions of an array "array" based on its type
2852 * "type" and update "array" accordingly.
2854 * We first construct a pet_expr that holds the sizes of the array
2855 * in each dimension. The resulting expression may containing
2856 * infinity values for dimension where we are unable to derive
2857 * a size expression.
2859 * The arguments of the size expression that have a value different from
2860 * infinity are then converted to an affine expression
2861 * within the context "pc" and incorporated into the size of "array".
2862 * If we are unable to convert a size expression to an affine expression or
2863 * if the size is not a (symbolic) constant,
2864 * then we leave the corresponding size of "array" untouched.
2866 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2867 const Type *type, __isl_keep pet_context *pc)
2869 int n;
2870 pet_expr *expr;
2872 if (!array)
2873 return NULL;
2875 expr = get_array_size(type);
2877 n = pet_expr_get_n_arg(expr);
2878 for (int i = 0; i < n; ++i) {
2879 pet_expr *arg;
2880 isl_pw_aff *size;
2882 arg = pet_expr_get_arg(expr, i);
2883 if (!is_infty(arg)) {
2884 int dim;
2886 size = pet_expr_extract_affine(arg, pc);
2887 dim = isl_pw_aff_dim(size, isl_dim_in);
2888 if (!size)
2889 array = pet_array_free(array);
2890 else if (isl_pw_aff_involves_nan(size) ||
2891 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2892 isl_pw_aff_free(size);
2893 else {
2894 size = isl_pw_aff_drop_dims(size,
2895 isl_dim_in, 0, dim);
2896 array = update_size(array, i, size);
2899 pet_expr_free(arg);
2901 pet_expr_free(expr);
2903 return array;
2906 /* Does "decl" have a definition that we can keep track of in a pet_type?
2908 static bool has_printable_definition(RecordDecl *decl)
2910 if (!decl->getDeclName())
2911 return false;
2912 return decl->getLexicalDeclContext() == decl->getDeclContext();
2915 /* Construct and return a pet_array corresponding to the variable
2916 * represented by "id".
2917 * In particular, initialize array->extent to
2919 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2921 * and then call set_upper_bounds to set the upper bounds on the indices
2922 * based on the type of the variable. The upper bounds are converted
2923 * to affine expressions within the context "pc".
2925 * If the base type is that of a record with a top-level definition or
2926 * of a typedef and if "types" is not null, then the RecordDecl or
2927 * TypedefType corresponding to the type
2928 * is added to "types".
2930 * If the base type is that of a record with no top-level definition,
2931 * then we replace it by "<subfield>".
2933 struct pet_array *PetScan::extract_array(__isl_keep isl_id *id,
2934 PetTypes *types, __isl_keep pet_context *pc)
2936 struct pet_array *array;
2937 QualType qt = pet_id_get_array_type(id);
2938 const Type *type = qt.getTypePtr();
2939 int depth = array_depth(type);
2940 QualType base = pet_clang_base_type(qt);
2941 string name;
2942 isl_space *space;
2944 array = isl_calloc_type(ctx, struct pet_array);
2945 if (!array)
2946 return NULL;
2948 space = isl_space_set_alloc(ctx, 0, depth);
2949 space = isl_space_set_tuple_id(space, isl_dim_set, isl_id_copy(id));
2951 array->extent = isl_set_nat_universe(space);
2953 space = isl_space_params_alloc(ctx, 0);
2954 array->context = isl_set_universe(space);
2956 array = set_upper_bounds(array, type, pc);
2957 if (!array)
2958 return NULL;
2960 name = base.getAsString();
2962 if (types) {
2963 if (isa<TypedefType>(base)) {
2964 types->insert(cast<TypedefType>(base)->getDecl());
2965 } else if (base->isRecordType()) {
2966 RecordDecl *decl = pet_clang_record_decl(base);
2967 TypedefNameDecl *typedecl;
2968 typedecl = decl->getTypedefNameForAnonDecl();
2969 if (typedecl)
2970 types->insert(typedecl);
2971 else if (has_printable_definition(decl))
2972 types->insert(decl);
2973 else
2974 name = "<subfield>";
2978 array->element_type = strdup(name.c_str());
2979 array->element_is_record = base->isRecordType();
2980 array->element_size = size_in_bytes(ast_context, base);
2982 return array;
2985 /* Construct and return a pet_array corresponding to the variable "decl".
2987 struct pet_array *PetScan::extract_array(ValueDecl *decl,
2988 PetTypes *types, __isl_keep pet_context *pc)
2990 isl_id *id;
2991 pet_array *array;
2993 id = pet_id_from_decl(ctx, decl);
2994 array = extract_array(id, types, pc);
2995 isl_id_free(id);
2997 return array;
3000 /* Construct and return a pet_array corresponding to the sequence
3001 * of declarations represented by "decls".
3002 * The upper bounds of the array are converted to affine expressions
3003 * within the context "pc".
3004 * If the sequence contains a single declaration, then it corresponds
3005 * to a simple array access. Otherwise, it corresponds to a member access,
3006 * with the declaration for the substructure following that of the containing
3007 * structure in the sequence of declarations.
3008 * We start with the outermost substructure and then combine it with
3009 * information from the inner structures.
3011 * Additionally, keep track of all required types in "types".
3013 struct pet_array *PetScan::extract_array(__isl_keep isl_id_list *decls,
3014 PetTypes *types, __isl_keep pet_context *pc)
3016 int i, n;
3017 isl_id *id;
3018 struct pet_array *array;
3020 id = isl_id_list_get_id(decls, 0);
3021 array = extract_array(id, types, pc);
3022 isl_id_free(id);
3024 n = isl_id_list_n_id(decls);
3025 for (i = 1; i < n; ++i) {
3026 struct pet_array *parent;
3027 const char *base_name, *field_name;
3028 char *product_name;
3030 parent = array;
3031 id = isl_id_list_get_id(decls, i);
3032 array = extract_array(id, types, pc);
3033 isl_id_free(id);
3034 if (!array)
3035 return pet_array_free(parent);
3037 base_name = isl_set_get_tuple_name(parent->extent);
3038 field_name = isl_set_get_tuple_name(array->extent);
3039 product_name = pet_array_member_access_name(ctx,
3040 base_name, field_name);
3042 array->extent = isl_set_product(isl_set_copy(parent->extent),
3043 array->extent);
3044 if (product_name)
3045 array->extent = isl_set_set_tuple_name(array->extent,
3046 product_name);
3047 array->context = isl_set_intersect(array->context,
3048 isl_set_copy(parent->context));
3050 pet_array_free(parent);
3051 free(product_name);
3053 if (!array->extent || !array->context || !product_name)
3054 return pet_array_free(array);
3057 return array;
3060 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3061 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
3062 std::set<TypeDecl *> &types_done);
3063 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3064 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
3065 std::set<TypeDecl *> &types_done);
3067 /* For each of the fields of "decl" that is itself a record type
3068 * or a typedef, add a corresponding pet_type to "scop".
3070 static struct pet_scop *add_field_types(isl_ctx *ctx, struct pet_scop *scop,
3071 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
3072 std::set<TypeDecl *> &types_done)
3074 RecordDecl::field_iterator it;
3076 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
3077 QualType type = it->getType();
3079 if (isa<TypedefType>(type)) {
3080 TypedefNameDecl *typedefdecl;
3082 typedefdecl = cast<TypedefType>(type)->getDecl();
3083 scop = add_type(ctx, scop, typedefdecl,
3084 PP, types, types_done);
3085 } else if (type->isRecordType()) {
3086 RecordDecl *record;
3088 record = pet_clang_record_decl(type);
3089 scop = add_type(ctx, scop, record,
3090 PP, types, types_done);
3094 return scop;
3097 /* Add a pet_type corresponding to "decl" to "scop", provided
3098 * it is a member of types.records and it has not been added before
3099 * (i.e., it is not a member of "types_done").
3101 * Since we want the user to be able to print the types
3102 * in the order in which they appear in the scop, we need to
3103 * make sure that types of fields in a structure appear before
3104 * that structure. We therefore call ourselves recursively
3105 * through add_field_types on the types of all record subfields.
3107 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3108 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
3109 std::set<TypeDecl *> &types_done)
3111 string s;
3112 llvm::raw_string_ostream S(s);
3114 if (types.records.find(decl) == types.records.end())
3115 return scop;
3116 if (types_done.find(decl) != types_done.end())
3117 return scop;
3119 add_field_types(ctx, scop, decl, PP, types, types_done);
3121 if (strlen(decl->getName().str().c_str()) == 0)
3122 return scop;
3124 decl->print(S, PrintingPolicy(PP.getLangOpts()));
3125 S.str();
3127 scop->types[scop->n_type] = pet_type_alloc(ctx,
3128 decl->getName().str().c_str(), s.c_str());
3129 if (!scop->types[scop->n_type])
3130 return pet_scop_free(scop);
3132 types_done.insert(decl);
3134 scop->n_type++;
3136 return scop;
3139 /* Add a pet_type corresponding to "decl" to "scop", provided
3140 * it is a member of types.typedefs and it has not been added before
3141 * (i.e., it is not a member of "types_done").
3143 * If the underlying type is a structure, then we print the typedef
3144 * ourselves since clang does not print the definition of the structure
3145 * in the typedef. We also make sure in this case that the types of
3146 * the fields in the structure are added first.
3148 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3149 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
3150 std::set<TypeDecl *> &types_done)
3152 string s;
3153 llvm::raw_string_ostream S(s);
3154 QualType qt = decl->getUnderlyingType();
3156 if (types.typedefs.find(decl) == types.typedefs.end())
3157 return scop;
3158 if (types_done.find(decl) != types_done.end())
3159 return scop;
3161 if (qt->isRecordType()) {
3162 RecordDecl *rec = pet_clang_record_decl(qt);
3164 add_field_types(ctx, scop, rec, PP, types, types_done);
3165 S << "typedef ";
3166 rec->print(S, PrintingPolicy(PP.getLangOpts()));
3167 S << " ";
3168 S << decl->getName();
3169 } else {
3170 decl->print(S, PrintingPolicy(PP.getLangOpts()));
3172 S.str();
3174 scop->types[scop->n_type] = pet_type_alloc(ctx,
3175 decl->getName().str().c_str(), s.c_str());
3176 if (!scop->types[scop->n_type])
3177 return pet_scop_free(scop);
3179 types_done.insert(decl);
3181 scop->n_type++;
3183 return scop;
3186 /* Construct a list of pet_arrays, one for each array (or scalar)
3187 * accessed inside "scop", add this list to "scop" and return the result.
3188 * The upper bounds of the arrays are converted to affine expressions
3189 * within the context "pc".
3191 * The context of "scop" is updated with the intersection of
3192 * the contexts of all arrays, i.e., constraints on the parameters
3193 * that ensure that the arrays have a valid (non-negative) size.
3195 * If any of the extracted arrays refers to a member access or
3196 * has a typedef'd type as base type,
3197 * then also add the required types to "scop".
3199 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
3200 __isl_keep pet_context *pc)
3202 int i, n;
3203 array_desc_set arrays;
3204 array_desc_set::iterator it;
3205 PetTypes types;
3206 std::set<TypeDecl *> types_done;
3207 std::set<clang::RecordDecl *, less_name>::iterator records_it;
3208 std::set<clang::TypedefNameDecl *, less_name>::iterator typedefs_it;
3209 int n_array;
3210 struct pet_array **scop_arrays;
3212 if (!scop)
3213 return NULL;
3215 pet_scop_collect_arrays(scop, arrays);
3216 if (arrays.size() == 0)
3217 return scop;
3219 n_array = scop->n_array;
3221 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3222 n_array + arrays.size());
3223 if (!scop_arrays)
3224 goto error;
3225 scop->arrays = scop_arrays;
3227 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3228 struct pet_array *array;
3229 array = extract_array(*it, &types, pc);
3230 scop->arrays[n_array + i] = array;
3231 if (!scop->arrays[n_array + i])
3232 goto error;
3233 scop->n_array++;
3234 scop->context = isl_set_intersect(scop->context,
3235 isl_set_copy(array->context));
3236 if (!scop->context)
3237 goto error;
3240 n = types.records.size() + types.typedefs.size();
3241 if (n == 0)
3242 return scop;
3244 scop->types = isl_alloc_array(ctx, struct pet_type *, n);
3245 if (!scop->types)
3246 goto error;
3248 for (records_it = types.records.begin();
3249 records_it != types.records.end(); ++records_it)
3250 scop = add_type(ctx, scop, *records_it, PP, types, types_done);
3252 for (typedefs_it = types.typedefs.begin();
3253 typedefs_it != types.typedefs.end(); ++typedefs_it)
3254 scop = add_type(ctx, scop, *typedefs_it, PP, types, types_done);
3256 return scop;
3257 error:
3258 pet_scop_free(scop);
3259 return NULL;
3262 /* Bound all parameters in scop->context to the possible values
3263 * of the corresponding C variable.
3265 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
3267 int n;
3269 if (!scop)
3270 return NULL;
3272 n = isl_set_dim(scop->context, isl_dim_param);
3273 for (int i = 0; i < n; ++i) {
3274 isl_id *id;
3275 ValueDecl *decl;
3277 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
3278 if (pet_nested_in_id(id)) {
3279 isl_id_free(id);
3280 isl_die(isl_set_get_ctx(scop->context),
3281 isl_error_internal,
3282 "unresolved nested parameter", goto error);
3284 decl = pet_id_get_decl(id);
3285 isl_id_free(id);
3287 scop->context = set_parameter_bounds(scop->context, i, decl);
3289 if (!scop->context)
3290 goto error;
3293 return scop;
3294 error:
3295 pet_scop_free(scop);
3296 return NULL;
3299 /* Construct a pet_scop from the given function.
3301 * If the scop was delimited by scop and endscop pragmas, then we override
3302 * the file offsets by those derived from the pragmas.
3304 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3306 pet_scop *scop;
3307 Stmt *stmt;
3309 stmt = fd->getBody();
3311 if (options->autodetect) {
3312 set_current_stmt(stmt);
3313 scop = extract_scop(extract(stmt, true));
3314 } else {
3315 current_line = loc.start_line;
3316 scop = scan(stmt);
3317 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
3319 scop = add_parameter_bounds(scop);
3320 scop = pet_scop_gist(scop, value_bounds);
3322 return scop;
3325 /* Update this->last_line and this->current_line based on the fact
3326 * that we are about to consider "stmt".
3328 void PetScan::set_current_stmt(Stmt *stmt)
3330 SourceLocation loc = stmt->getLocStart();
3331 SourceManager &SM = PP.getSourceManager();
3333 last_line = current_line;
3334 current_line = SM.getExpansionLineNumber(loc);
3337 /* Is the current statement marked by an independent pragma?
3338 * That is, is there an independent pragma on a line between
3339 * the line of the current statement and the line of the previous statement.
3340 * The search is not implemented very efficiently. We currently
3341 * assume that there are only a few independent pragmas, if any.
3343 bool PetScan::is_current_stmt_marked_independent()
3345 for (int i = 0; i < independent.size(); ++i) {
3346 unsigned line = independent[i].line;
3348 if (last_line < line && line < current_line)
3349 return true;
3352 return false;