scan.cc: extract_array: drop redundant local variable
[pet.git] / scan.cc
blobfd6cee4f65f6756bbcded58dbe47edecadfb0807
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2015 Ecole Normale Superieure. All rights reserved.
4 * Copyright 2015-2016 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 "killed_locals.h"
64 #include "nest.h"
65 #include "options.h"
66 #include "scan.h"
67 #include "scop.h"
68 #include "scop_plus.h"
69 #include "substituter.h"
70 #include "tree.h"
71 #include "tree2scop.h"
73 using namespace std;
74 using namespace clang;
76 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
78 switch (kind) {
79 case UO_Minus:
80 return pet_op_minus;
81 case UO_Not:
82 return pet_op_not;
83 case UO_LNot:
84 return pet_op_lnot;
85 case UO_PostInc:
86 return pet_op_post_inc;
87 case UO_PostDec:
88 return pet_op_post_dec;
89 case UO_PreInc:
90 return pet_op_pre_inc;
91 case UO_PreDec:
92 return pet_op_pre_dec;
93 default:
94 return pet_op_last;
98 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
100 switch (kind) {
101 case BO_AddAssign:
102 return pet_op_add_assign;
103 case BO_SubAssign:
104 return pet_op_sub_assign;
105 case BO_MulAssign:
106 return pet_op_mul_assign;
107 case BO_DivAssign:
108 return pet_op_div_assign;
109 case BO_Assign:
110 return pet_op_assign;
111 case BO_Add:
112 return pet_op_add;
113 case BO_Sub:
114 return pet_op_sub;
115 case BO_Mul:
116 return pet_op_mul;
117 case BO_Div:
118 return pet_op_div;
119 case BO_Rem:
120 return pet_op_mod;
121 case BO_Shl:
122 return pet_op_shl;
123 case BO_Shr:
124 return pet_op_shr;
125 case BO_EQ:
126 return pet_op_eq;
127 case BO_NE:
128 return pet_op_ne;
129 case BO_LE:
130 return pet_op_le;
131 case BO_GE:
132 return pet_op_ge;
133 case BO_LT:
134 return pet_op_lt;
135 case BO_GT:
136 return pet_op_gt;
137 case BO_And:
138 return pet_op_and;
139 case BO_Xor:
140 return pet_op_xor;
141 case BO_Or:
142 return pet_op_or;
143 case BO_LAnd:
144 return pet_op_land;
145 case BO_LOr:
146 return pet_op_lor;
147 default:
148 return pet_op_last;
152 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
153 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
155 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
156 SourceLocation(), var, false, var->getInnerLocStart(),
157 var->getType(), VK_LValue);
159 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
160 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
162 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
163 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
164 VK_LValue);
166 #else
167 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
169 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
170 var, var->getInnerLocStart(), var->getType(), VK_LValue);
172 #endif
174 #ifdef GETTYPEINFORETURNSTYPEINFO
176 static int size_in_bytes(ASTContext &context, QualType type)
178 return context.getTypeInfo(type).Width / 8;
181 #else
183 static int size_in_bytes(ASTContext &context, QualType type)
185 return context.getTypeInfo(type).first / 8;
188 #endif
190 /* Check if the element type corresponding to the given array type
191 * has a const qualifier.
193 static bool const_base(QualType qt)
195 const Type *type = qt.getTypePtr();
197 if (type->isPointerType())
198 return const_base(type->getPointeeType());
199 if (type->isArrayType()) {
200 const ArrayType *atype;
201 type = type->getCanonicalTypeInternal().getTypePtr();
202 atype = cast<ArrayType>(type);
203 return const_base(atype->getElementType());
206 return qt.isConstQualified();
209 PetScan::~PetScan()
211 std::map<const Type *, pet_expr *>::iterator it;
212 std::map<FunctionDecl *, pet_function_summary *>::iterator it_s;
214 for (it = type_size.begin(); it != type_size.end(); ++it)
215 pet_expr_free(it->second);
216 for (it_s = summary_cache.begin(); it_s != summary_cache.end(); ++it_s)
217 pet_function_summary_free(it_s->second);
219 isl_id_to_pet_expr_free(id_size);
220 isl_union_map_free(value_bounds);
223 /* Report a diagnostic on the range "range", unless autodetect is set.
225 void PetScan::report(SourceRange range, unsigned id)
227 if (options->autodetect)
228 return;
230 SourceLocation loc = range.getBegin();
231 DiagnosticsEngine &diag = PP.getDiagnostics();
232 DiagnosticBuilder B = diag.Report(loc, id) << range;
235 /* Report a diagnostic on "stmt", unless autodetect is set.
237 void PetScan::report(Stmt *stmt, unsigned id)
239 report(stmt->getSourceRange(), id);
242 /* Report a diagnostic on "decl", unless autodetect is set.
244 void PetScan::report(Decl *decl, unsigned id)
246 report(decl->getSourceRange(), id);
249 /* Called if we found something we (currently) cannot handle.
250 * We'll provide more informative warnings later.
252 * We only actually complain if autodetect is false.
254 void PetScan::unsupported(Stmt *stmt)
256 DiagnosticsEngine &diag = PP.getDiagnostics();
257 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
258 "unsupported");
259 report(stmt, id);
262 /* Report an unsupported unary operator, unless autodetect is set.
264 void PetScan::report_unsupported_unary_operator(Stmt *stmt)
266 DiagnosticsEngine &diag = PP.getDiagnostics();
267 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
268 "this type of unary operator is not supported");
269 report(stmt, id);
272 /* Report an unsupported statement type, unless autodetect is set.
274 void PetScan::report_unsupported_statement_type(Stmt *stmt)
276 DiagnosticsEngine &diag = PP.getDiagnostics();
277 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
278 "this type of statement is not supported");
279 report(stmt, id);
282 /* Report a missing prototype, unless autodetect is set.
284 void PetScan::report_prototype_required(Stmt *stmt)
286 DiagnosticsEngine &diag = PP.getDiagnostics();
287 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
288 "prototype required");
289 report(stmt, id);
292 /* Report a missing increment, unless autodetect is set.
294 void PetScan::report_missing_increment(Stmt *stmt)
296 DiagnosticsEngine &diag = PP.getDiagnostics();
297 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
298 "missing increment");
299 report(stmt, id);
302 /* Report a missing summary function, unless autodetect is set.
304 void PetScan::report_missing_summary_function(Stmt *stmt)
306 DiagnosticsEngine &diag = PP.getDiagnostics();
307 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
308 "missing summary function");
309 report(stmt, id);
312 /* Report a missing summary function body, unless autodetect is set.
314 void PetScan::report_missing_summary_function_body(Stmt *stmt)
316 DiagnosticsEngine &diag = PP.getDiagnostics();
317 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
318 "missing summary function body");
319 report(stmt, id);
322 /* Report an unsupported argument in a call to an inlined function,
323 * unless autodetect is set.
325 void PetScan::report_unsupported_inline_function_argument(Stmt *stmt)
327 DiagnosticsEngine &diag = PP.getDiagnostics();
328 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
329 "unsupported inline function call argument");
330 report(stmt, id);
333 /* Report an unsupported type of declaration, unless autodetect is set.
335 void PetScan::report_unsupported_declaration(Decl *decl)
337 DiagnosticsEngine &diag = PP.getDiagnostics();
338 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
339 "unsupported declaration");
340 report(decl, id);
343 /* Extract an integer from "val", which is assumed to be non-negative.
345 static __isl_give isl_val *extract_unsigned(isl_ctx *ctx,
346 const llvm::APInt &val)
348 unsigned n;
349 const uint64_t *data;
351 data = val.getRawData();
352 n = val.getNumWords();
353 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
356 /* Extract an integer from "val". If "is_signed" is set, then "val"
357 * is signed. Otherwise it it unsigned.
359 static __isl_give isl_val *extract_int(isl_ctx *ctx, bool is_signed,
360 llvm::APInt val)
362 int is_negative = is_signed && val.isNegative();
363 isl_val *v;
365 if (is_negative)
366 val = -val;
368 v = extract_unsigned(ctx, val);
370 if (is_negative)
371 v = isl_val_neg(v);
372 return v;
375 /* Extract an integer from "expr".
377 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
379 const Type *type = expr->getType().getTypePtr();
380 bool is_signed = type->hasSignedIntegerRepresentation();
382 return ::extract_int(ctx, is_signed, expr->getValue());
385 /* Extract an integer from "expr".
386 * Return NULL if "expr" does not (obviously) represent an integer.
388 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
390 return extract_int(expr->getSubExpr());
393 /* Extract an integer from "expr".
394 * Return NULL if "expr" does not (obviously) represent an integer.
396 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
398 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
399 return extract_int(ctx, cast<IntegerLiteral>(expr));
400 if (expr->getStmtClass() == Stmt::ParenExprClass)
401 return extract_int(cast<ParenExpr>(expr));
403 unsupported(expr);
404 return NULL;
407 /* Extract a pet_expr from the APInt "val", which is assumed
408 * to be non-negative.
410 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
412 return pet_expr_new_int(extract_unsigned(ctx, val));
415 /* Return the number of bits needed to represent the type of "decl",
416 * if it is an integer type. Otherwise return 0.
417 * If qt is signed then return the opposite of the number of bits.
419 static int get_type_size(ValueDecl *decl)
421 return pet_clang_get_type_size(decl->getType(), decl->getASTContext());
424 /* Bound parameter "pos" of "set" to the possible values of "decl".
426 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
427 unsigned pos, ValueDecl *decl)
429 int type_size;
430 isl_ctx *ctx;
431 isl_val *bound;
433 ctx = isl_set_get_ctx(set);
434 type_size = get_type_size(decl);
435 if (type_size == 0)
436 isl_die(ctx, isl_error_invalid, "not an integer type",
437 return isl_set_free(set));
438 if (type_size > 0) {
439 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
440 bound = isl_val_int_from_ui(ctx, type_size);
441 bound = isl_val_2exp(bound);
442 bound = isl_val_sub_ui(bound, 1);
443 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
444 } else {
445 bound = isl_val_int_from_ui(ctx, -type_size - 1);
446 bound = isl_val_2exp(bound);
447 bound = isl_val_sub_ui(bound, 1);
448 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
449 isl_val_copy(bound));
450 bound = isl_val_neg(bound);
451 bound = isl_val_sub_ui(bound, 1);
452 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
455 return set;
458 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
460 return extract_index_expr(expr->getSubExpr());
463 /* Return the depth of the array accessed by the index expression "index".
464 * If "index" is an affine expression, i.e., if it does not access
465 * any array, then return 1.
466 * If "index" represent a member access, i.e., if its range is a wrapped
467 * relation, then return the sum of the depth of the array of structures
468 * and that of the member inside the structure.
470 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
472 isl_id *id;
473 ValueDecl *decl;
475 if (!index)
476 return -1;
478 if (isl_multi_pw_aff_range_is_wrapping(index)) {
479 int domain_depth, range_depth;
480 isl_multi_pw_aff *domain, *range;
482 domain = isl_multi_pw_aff_copy(index);
483 domain = isl_multi_pw_aff_range_factor_domain(domain);
484 domain_depth = extract_depth(domain);
485 isl_multi_pw_aff_free(domain);
486 range = isl_multi_pw_aff_copy(index);
487 range = isl_multi_pw_aff_range_factor_range(range);
488 range_depth = extract_depth(range);
489 isl_multi_pw_aff_free(range);
491 return domain_depth + range_depth;
494 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
495 return 1;
497 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
498 if (!id)
499 return -1;
500 decl = pet_id_get_decl(id);
501 isl_id_free(id);
503 return pet_clang_array_depth(decl->getType());
506 /* Return the depth of the array accessed by the access expression "expr".
508 static int extract_depth(__isl_keep pet_expr *expr)
510 isl_multi_pw_aff *index;
511 int depth;
513 index = pet_expr_access_get_index(expr);
514 depth = extract_depth(index);
515 isl_multi_pw_aff_free(index);
517 return depth;
520 /* Construct a pet_expr representing an index expression for an access
521 * to the variable referenced by "expr".
523 * If "expr" references an enum constant, then return an integer expression
524 * instead, representing the value of the enum constant.
526 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
528 return extract_index_expr(expr->getDecl());
531 /* Construct a pet_expr representing an index expression for an access
532 * to the variable "decl".
534 * If "decl" is an enum constant, then we return an integer expression
535 * instead, representing the value of the enum constant.
537 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
539 isl_id *id;
541 if (isa<EnumConstantDecl>(decl))
542 return extract_expr(cast<EnumConstantDecl>(decl));
544 id = pet_id_from_decl(ctx, decl);
545 return pet_id_create_index_expr(id);
548 /* Construct a pet_expr representing the index expression "expr"
549 * Return NULL on error.
551 * If "expr" is a reference to an enum constant, then return
552 * an integer expression instead, representing the value of the enum constant.
554 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
556 switch (expr->getStmtClass()) {
557 case Stmt::ImplicitCastExprClass:
558 return extract_index_expr(cast<ImplicitCastExpr>(expr));
559 case Stmt::DeclRefExprClass:
560 return extract_index_expr(cast<DeclRefExpr>(expr));
561 case Stmt::ArraySubscriptExprClass:
562 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
563 case Stmt::IntegerLiteralClass:
564 return extract_expr(cast<IntegerLiteral>(expr));
565 case Stmt::MemberExprClass:
566 return extract_index_expr(cast<MemberExpr>(expr));
567 default:
568 unsupported(expr);
570 return NULL;
573 /* Extract an index expression from the given array subscript expression.
575 * We first extract an index expression from the base.
576 * This will result in an index expression with a range that corresponds
577 * to the earlier indices.
578 * We then extract the current index and let
579 * pet_expr_access_subscript combine the two.
581 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
583 Expr *base = expr->getBase();
584 Expr *idx = expr->getIdx();
585 pet_expr *index;
586 pet_expr *base_expr;
588 base_expr = extract_index_expr(base);
589 index = extract_expr(idx);
591 base_expr = pet_expr_access_subscript(base_expr, index);
593 return base_expr;
596 /* Extract an index expression from a member expression.
598 * If the base access (to the structure containing the member)
599 * is of the form
601 * A[..]
603 * and the member is called "f", then the member access is of
604 * the form
606 * A_f[A[..] -> f[]]
608 * If the member access is to an anonymous struct, then simply return
610 * A[..]
612 * If the member access in the source code is of the form
614 * A->f
616 * then it is treated as
618 * A[0].f
620 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
622 Expr *base = expr->getBase();
623 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
624 pet_expr *base_index;
625 isl_id *id;
627 base_index = extract_index_expr(base);
629 if (expr->isArrow()) {
630 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
631 base_index = pet_expr_access_subscript(base_index, index);
634 if (field->isAnonymousStructOrUnion())
635 return base_index;
637 id = pet_id_from_decl(ctx, field);
639 return pet_expr_access_member(base_index, id);
642 /* Mark the given access pet_expr as a write.
644 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
646 access = pet_expr_access_set_write(access, 1);
647 access = pet_expr_access_set_read(access, 0);
649 return access;
652 /* Mark the given (read) access pet_expr as also possibly being written.
653 * That is, initialize the may write access relation from the may read relation
654 * and initialize the must write access relation to the empty relation.
656 static __isl_give pet_expr *mark_may_write(__isl_take pet_expr *expr)
658 isl_union_map *access;
659 isl_union_map *empty;
661 access = pet_expr_access_get_dependent_access(expr,
662 pet_expr_access_may_read);
663 empty = isl_union_map_empty(isl_union_map_get_space(access));
664 expr = pet_expr_access_set_access(expr, pet_expr_access_may_write,
665 access);
666 expr = pet_expr_access_set_access(expr, pet_expr_access_must_write,
667 empty);
669 return expr;
672 /* Construct a pet_expr representing a unary operator expression.
674 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
676 int type_size;
677 pet_expr *arg;
678 enum pet_op_type op;
680 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
681 if (op == pet_op_last) {
682 report_unsupported_unary_operator(expr);
683 return NULL;
686 arg = extract_expr(expr->getSubExpr());
688 if (expr->isIncrementDecrementOp() &&
689 pet_expr_get_type(arg) == pet_expr_access) {
690 arg = mark_write(arg);
691 arg = pet_expr_access_set_read(arg, 1);
694 type_size = pet_clang_get_type_size(expr->getType(), ast_context);
695 return pet_expr_new_unary(type_size, op, arg);
698 /* Construct a pet_expr representing a binary operator expression.
700 * If the top level operator is an assignment and the LHS is an access,
701 * then we mark that access as a write. If the operator is a compound
702 * assignment, the access is marked as both a read and a write.
704 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
706 int type_size;
707 pet_expr *lhs, *rhs;
708 enum pet_op_type op;
710 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
711 if (op == pet_op_last) {
712 unsupported(expr);
713 return NULL;
716 lhs = extract_expr(expr->getLHS());
717 rhs = extract_expr(expr->getRHS());
719 if (expr->isAssignmentOp() &&
720 pet_expr_get_type(lhs) == pet_expr_access) {
721 lhs = mark_write(lhs);
722 if (expr->isCompoundAssignmentOp())
723 lhs = pet_expr_access_set_read(lhs, 1);
726 type_size = pet_clang_get_type_size(expr->getType(), ast_context);
727 return pet_expr_new_binary(type_size, op, lhs, rhs);
730 /* Construct a pet_tree for a variable declaration and
731 * add the declaration to the list of declarations
732 * inside the current compound statement.
734 __isl_give pet_tree *PetScan::extract(Decl *decl)
736 VarDecl *vd;
737 pet_expr *lhs, *rhs;
738 pet_tree *tree;
740 if (!isa<VarDecl>(decl)) {
741 report_unsupported_declaration(decl);
742 return NULL;
745 vd = cast<VarDecl>(decl);
746 declarations.push_back(vd);
748 lhs = extract_access_expr(vd);
749 lhs = mark_write(lhs);
750 if (!vd->getInit())
751 tree = pet_tree_new_decl(lhs);
752 else {
753 rhs = extract_expr(vd->getInit());
754 tree = pet_tree_new_decl_init(lhs, rhs);
757 return tree;
760 /* Construct a pet_tree for a variable declaration statement.
761 * If the declaration statement declares multiple variables,
762 * then return a group of pet_trees, one for each declared variable.
764 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
766 pet_tree *tree;
767 unsigned n;
769 if (!stmt->isSingleDecl()) {
770 const DeclGroup &group = stmt->getDeclGroup().getDeclGroup();
771 n = group.size();
772 tree = pet_tree_new_block(ctx, 0, n);
774 for (unsigned i = 0; i < n; ++i) {
775 pet_tree *tree_i;
776 pet_loc *loc;
778 tree_i = extract(group[i]);
779 loc = construct_pet_loc(group[i]->getSourceRange(),
780 false);
781 tree_i = pet_tree_set_loc(tree_i, loc);
782 tree = pet_tree_block_add_child(tree, tree_i);
785 return tree;
788 return extract(stmt->getSingleDecl());
791 /* Construct a pet_expr representing a conditional operation.
793 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
795 pet_expr *cond, *lhs, *rhs;
797 cond = extract_expr(expr->getCond());
798 lhs = extract_expr(expr->getTrueExpr());
799 rhs = extract_expr(expr->getFalseExpr());
801 return pet_expr_new_ternary(cond, lhs, rhs);
804 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
806 return extract_expr(expr->getSubExpr());
809 /* Construct a pet_expr representing a floating point value.
811 * If the floating point literal does not appear in a macro,
812 * then we use the original representation in the source code
813 * as the string representation. Otherwise, we use the pretty
814 * printer to produce a string representation.
816 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
818 double d;
819 string s;
820 const LangOptions &LO = PP.getLangOpts();
821 SourceLocation loc = expr->getLocation();
823 if (!loc.isMacroID()) {
824 SourceManager &SM = PP.getSourceManager();
825 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
826 s = string(SM.getCharacterData(loc), len);
827 } else {
828 llvm::raw_string_ostream S(s);
829 expr->printPretty(S, 0, PrintingPolicy(LO));
830 S.str();
832 d = expr->getValueAsApproximateDouble();
833 return pet_expr_new_double(ctx, d, s.c_str());
836 /* Convert the index expression "index" into an access pet_expr of type "qt".
838 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
839 __isl_take pet_expr *index)
841 int depth;
842 int type_size;
844 depth = extract_depth(index);
845 type_size = pet_clang_get_type_size(qt, ast_context);
847 index = pet_expr_set_type_size(index, type_size);
848 index = pet_expr_access_set_depth(index, depth);
850 return index;
853 /* Extract an index expression from "expr" and then convert it into
854 * an access pet_expr.
856 * If "expr" is a reference to an enum constant, then return
857 * an integer expression instead, representing the value of the enum constant.
859 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
861 pet_expr *index;
863 index = extract_index_expr(expr);
865 if (pet_expr_get_type(index) == pet_expr_int)
866 return index;
868 return extract_access_expr(expr->getType(), index);
871 /* Extract an index expression from "decl" and then convert it into
872 * an access pet_expr.
874 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
876 return extract_access_expr(decl->getType(), extract_index_expr(decl));
879 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
881 return extract_expr(expr->getSubExpr());
884 /* Extract an assume statement from the argument "expr"
885 * of a __builtin_assume or __pencil_assume statement.
887 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
889 return pet_expr_new_unary(0, pet_op_assume, extract_expr(expr));
892 /* If "expr" is an address-of operator, then return its argument.
893 * Otherwise, return NULL.
895 static Expr *extract_addr_of_arg(Expr *expr)
897 UnaryOperator *op;
899 if (expr->getStmtClass() != Stmt::UnaryOperatorClass)
900 return NULL;
901 op = cast<UnaryOperator>(expr);
902 if (op->getOpcode() != UO_AddrOf)
903 return NULL;
904 return op->getSubExpr();
907 /* Construct a pet_expr corresponding to the function call argument "expr".
908 * The argument appears in position "pos" of a call to function "fd".
910 * If we are passing along a pointer to an array element
911 * or an entire row or even higher dimensional slice of an array,
912 * then the function being called may write into the array.
914 * We assume here that if the function is declared to take a pointer
915 * to a const type, then the function may only perform a read
916 * and that otherwise, it may either perform a read or a write (or both).
917 * We only perform this check if "detect_writes" is set.
919 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
920 Expr *expr, bool detect_writes)
922 Expr *arg;
923 pet_expr *res;
924 int is_addr = 0, is_partial = 0;
926 expr = pet_clang_strip_casts(expr);
927 arg = extract_addr_of_arg(expr);
928 if (arg) {
929 is_addr = 1;
930 expr = arg;
932 res = extract_expr(expr);
933 if (!res)
934 return NULL;
935 if (pet_clang_array_depth(expr->getType()) > 0)
936 is_partial = 1;
937 if (detect_writes && (is_addr || is_partial) &&
938 pet_expr_get_type(res) == pet_expr_access) {
939 ParmVarDecl *parm;
940 if (!fd->hasPrototype()) {
941 report_prototype_required(expr);
942 return pet_expr_free(res);
944 parm = fd->getParamDecl(pos);
945 if (!const_base(parm->getType()))
946 res = mark_may_write(res);
949 if (is_addr)
950 res = pet_expr_new_unary(0, pet_op_address_of, res);
951 return res;
954 /* Find the first FunctionDecl with the given name.
955 * "call" is the corresponding call expression and is only used
956 * for reporting errors.
958 * Return NULL on error.
960 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
962 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
963 DeclContext::decl_iterator begin = tu->decls_begin();
964 DeclContext::decl_iterator end = tu->decls_end();
965 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
966 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
967 if (!fd)
968 continue;
969 if (fd->getName().str().compare(name) != 0)
970 continue;
971 if (fd->hasBody())
972 return fd;
973 report_missing_summary_function_body(call);
974 return NULL;
976 report_missing_summary_function(call);
977 return NULL;
980 /* Return the FunctionDecl for the summary function associated to the
981 * function called by "call".
983 * In particular, if the pencil option is set, then
984 * search for an annotate attribute formatted as
985 * "pencil_access(name)", where "name" is the name of the summary function.
987 * If no summary function was specified, then return the FunctionDecl
988 * that is actually being called.
990 * Return NULL on error.
992 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
994 FunctionDecl *decl = call->getDirectCallee();
995 if (!decl)
996 return NULL;
998 if (!options->pencil)
999 return decl;
1001 specific_attr_iterator<AnnotateAttr> begin, end, i;
1002 begin = decl->specific_attr_begin<AnnotateAttr>();
1003 end = decl->specific_attr_end<AnnotateAttr>();
1004 for (i = begin; i != end; ++i) {
1005 string attr = (*i)->getAnnotation().str();
1007 const char prefix[] = "pencil_access(";
1008 size_t start = attr.find(prefix);
1009 if (start == string::npos)
1010 continue;
1011 start += strlen(prefix);
1012 string name = attr.substr(start, attr.find(')') - start);
1014 return find_decl_from_name(call, name);
1017 return decl;
1020 /* Is "name" the name of an assume statement?
1021 * "pencil" indicates whether pencil builtins and pragmas should be supported.
1022 * "__builtin_assume" is always accepted.
1023 * If "pencil" is set, then "__pencil_assume" is also accepted.
1025 static bool is_assume(int pencil, const string &name)
1027 if (name == "__builtin_assume")
1028 return true;
1029 return pencil && name == "__pencil_assume";
1032 /* Construct a pet_expr representing a function call.
1034 * In the special case of a "call" to __builtin_assume or __pencil_assume,
1035 * construct an assume expression instead.
1037 * In the case of a "call" to __pencil_kill, the arguments
1038 * are neither read nor written (only killed), so there
1039 * is no need to check for writes to these arguments.
1041 * __pencil_assume and __pencil_kill are only recognized
1042 * when the pencil option is set.
1044 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1046 pet_expr *res = NULL;
1047 FunctionDecl *fd;
1048 string name;
1049 unsigned n_arg;
1050 bool is_kill;
1052 fd = expr->getDirectCallee();
1053 if (!fd) {
1054 unsupported(expr);
1055 return NULL;
1058 name = fd->getDeclName().getAsString();
1059 n_arg = expr->getNumArgs();
1061 if (n_arg == 1 && is_assume(options->pencil, name))
1062 return extract_assume(expr->getArg(0));
1063 is_kill = options->pencil && name == "__pencil_kill";
1065 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1066 if (!res)
1067 return NULL;
1069 for (unsigned i = 0; i < n_arg; ++i) {
1070 Expr *arg = expr->getArg(i);
1071 res = pet_expr_set_arg(res, i,
1072 PetScan::extract_argument(fd, i, arg, !is_kill));
1075 fd = get_summary_function(expr);
1076 if (!fd)
1077 return pet_expr_free(res);
1079 res = set_summary(res, fd);
1081 return res;
1084 /* Construct a pet_expr representing a (C style) cast.
1086 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1088 pet_expr *arg;
1089 QualType type;
1091 arg = extract_expr(expr->getSubExpr());
1092 if (!arg)
1093 return NULL;
1095 type = expr->getTypeAsWritten();
1096 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1099 /* Construct a pet_expr representing an integer.
1101 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1103 return pet_expr_new_int(extract_int(expr));
1106 /* Construct a pet_expr representing the integer enum constant "ecd".
1108 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
1110 isl_val *v;
1111 const llvm::APSInt &init = ecd->getInitVal();
1112 v = ::extract_int(ctx, init.isSigned(), init);
1113 return pet_expr_new_int(v);
1116 /* Try and construct a pet_expr representing "expr".
1118 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1120 switch (expr->getStmtClass()) {
1121 case Stmt::UnaryOperatorClass:
1122 return extract_expr(cast<UnaryOperator>(expr));
1123 case Stmt::CompoundAssignOperatorClass:
1124 case Stmt::BinaryOperatorClass:
1125 return extract_expr(cast<BinaryOperator>(expr));
1126 case Stmt::ImplicitCastExprClass:
1127 return extract_expr(cast<ImplicitCastExpr>(expr));
1128 case Stmt::ArraySubscriptExprClass:
1129 case Stmt::DeclRefExprClass:
1130 case Stmt::MemberExprClass:
1131 return extract_access_expr(expr);
1132 case Stmt::IntegerLiteralClass:
1133 return extract_expr(cast<IntegerLiteral>(expr));
1134 case Stmt::FloatingLiteralClass:
1135 return extract_expr(cast<FloatingLiteral>(expr));
1136 case Stmt::ParenExprClass:
1137 return extract_expr(cast<ParenExpr>(expr));
1138 case Stmt::ConditionalOperatorClass:
1139 return extract_expr(cast<ConditionalOperator>(expr));
1140 case Stmt::CallExprClass:
1141 return extract_expr(cast<CallExpr>(expr));
1142 case Stmt::CStyleCastExprClass:
1143 return extract_expr(cast<CStyleCastExpr>(expr));
1144 default:
1145 unsupported(expr);
1147 return NULL;
1150 /* Check if the given initialization statement is an assignment.
1151 * If so, return that assignment. Otherwise return NULL.
1153 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1155 BinaryOperator *ass;
1157 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1158 return NULL;
1160 ass = cast<BinaryOperator>(init);
1161 if (ass->getOpcode() != BO_Assign)
1162 return NULL;
1164 return ass;
1167 /* Check if the given initialization statement is a declaration
1168 * of a single variable.
1169 * If so, return that declaration. Otherwise return NULL.
1171 Decl *PetScan::initialization_declaration(Stmt *init)
1173 DeclStmt *decl;
1175 if (init->getStmtClass() != Stmt::DeclStmtClass)
1176 return NULL;
1178 decl = cast<DeclStmt>(init);
1180 if (!decl->isSingleDecl())
1181 return NULL;
1183 return decl->getSingleDecl();
1186 /* Given the assignment operator in the initialization of a for loop,
1187 * extract the induction variable, i.e., the (integer)variable being
1188 * assigned.
1190 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1192 Expr *lhs;
1193 DeclRefExpr *ref;
1194 ValueDecl *decl;
1195 const Type *type;
1197 lhs = init->getLHS();
1198 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1199 unsupported(init);
1200 return NULL;
1203 ref = cast<DeclRefExpr>(lhs);
1204 decl = ref->getDecl();
1205 type = decl->getType().getTypePtr();
1207 if (!type->isIntegerType()) {
1208 unsupported(lhs);
1209 return NULL;
1212 return decl;
1215 /* Given the initialization statement of a for loop and the single
1216 * declaration in this initialization statement,
1217 * extract the induction variable, i.e., the (integer) variable being
1218 * declared.
1220 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1222 VarDecl *vd;
1224 vd = cast<VarDecl>(decl);
1226 const QualType type = vd->getType();
1227 if (!type->isIntegerType()) {
1228 unsupported(init);
1229 return NULL;
1232 if (!vd->getInit()) {
1233 unsupported(init);
1234 return NULL;
1237 return vd;
1240 /* Check that op is of the form iv++ or iv--.
1241 * Return a pet_expr representing "1" or "-1" accordingly.
1243 __isl_give pet_expr *PetScan::extract_unary_increment(
1244 clang::UnaryOperator *op, clang::ValueDecl *iv)
1246 Expr *sub;
1247 DeclRefExpr *ref;
1248 isl_val *v;
1250 if (!op->isIncrementDecrementOp()) {
1251 unsupported(op);
1252 return NULL;
1255 sub = op->getSubExpr();
1256 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1257 unsupported(op);
1258 return NULL;
1261 ref = cast<DeclRefExpr>(sub);
1262 if (ref->getDecl() != iv) {
1263 unsupported(op);
1264 return NULL;
1267 if (op->isIncrementOp())
1268 v = isl_val_one(ctx);
1269 else
1270 v = isl_val_negone(ctx);
1272 return pet_expr_new_int(v);
1275 /* Check if op is of the form
1277 * iv = expr
1279 * and return the increment "expr - iv" as a pet_expr.
1281 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1282 clang::ValueDecl *iv)
1284 int type_size;
1285 Expr *lhs;
1286 DeclRefExpr *ref;
1287 pet_expr *expr, *expr_iv;
1289 if (op->getOpcode() != BO_Assign) {
1290 unsupported(op);
1291 return NULL;
1294 lhs = op->getLHS();
1295 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1296 unsupported(op);
1297 return NULL;
1300 ref = cast<DeclRefExpr>(lhs);
1301 if (ref->getDecl() != iv) {
1302 unsupported(op);
1303 return NULL;
1306 expr = extract_expr(op->getRHS());
1307 expr_iv = extract_expr(lhs);
1309 type_size = pet_clang_get_type_size(iv->getType(), ast_context);
1310 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1313 /* Check that op is of the form iv += cst or iv -= cst
1314 * and return a pet_expr corresponding to cst or -cst accordingly.
1316 __isl_give pet_expr *PetScan::extract_compound_increment(
1317 CompoundAssignOperator *op, clang::ValueDecl *iv)
1319 Expr *lhs;
1320 DeclRefExpr *ref;
1321 bool neg = false;
1322 pet_expr *expr;
1323 BinaryOperatorKind opcode;
1325 opcode = op->getOpcode();
1326 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1327 unsupported(op);
1328 return NULL;
1330 if (opcode == BO_SubAssign)
1331 neg = true;
1333 lhs = op->getLHS();
1334 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1335 unsupported(op);
1336 return NULL;
1339 ref = cast<DeclRefExpr>(lhs);
1340 if (ref->getDecl() != iv) {
1341 unsupported(op);
1342 return NULL;
1345 expr = extract_expr(op->getRHS());
1346 if (neg) {
1347 int type_size;
1348 type_size = pet_clang_get_type_size(op->getType(), ast_context);
1349 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1352 return expr;
1355 /* Check that the increment of the given for loop increments
1356 * (or decrements) the induction variable "iv" and return
1357 * the increment as a pet_expr if successful.
1359 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1360 ValueDecl *iv)
1362 Stmt *inc = stmt->getInc();
1364 if (!inc) {
1365 report_missing_increment(stmt);
1366 return NULL;
1369 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1370 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1371 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1372 return extract_compound_increment(
1373 cast<CompoundAssignOperator>(inc), iv);
1374 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1375 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1377 unsupported(inc);
1378 return NULL;
1381 /* Construct a pet_tree for a while loop.
1383 * If we were only able to extract part of the body, then simply
1384 * return that part.
1386 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1388 pet_expr *pe_cond;
1389 pet_tree *tree;
1391 tree = extract(stmt->getBody());
1392 if (partial)
1393 return tree;
1394 pe_cond = extract_expr(stmt->getCond());
1395 tree = pet_tree_new_while(pe_cond, tree);
1397 return tree;
1400 /* Construct a pet_tree for a for statement.
1401 * The for loop is required to be of one of the following forms
1403 * for (i = init; condition; ++i)
1404 * for (i = init; condition; --i)
1405 * for (i = init; condition; i += constant)
1406 * for (i = init; condition; i -= constant)
1408 * We extract a pet_tree for the body and then include it in a pet_tree
1409 * of type pet_tree_for.
1411 * As a special case, we also allow a for loop of the form
1413 * for (;;)
1415 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1417 * If we were only able to extract part of the body, then simply
1418 * return that part.
1420 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1422 BinaryOperator *ass;
1423 Decl *decl;
1424 Stmt *init;
1425 Expr *lhs, *rhs;
1426 ValueDecl *iv;
1427 pet_tree *tree;
1428 int independent;
1429 int declared;
1430 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1432 independent = is_current_stmt_marked_independent();
1434 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1435 tree = extract(stmt->getBody());
1436 if (partial)
1437 return tree;
1438 tree = pet_tree_new_infinite_loop(tree);
1439 return tree;
1442 init = stmt->getInit();
1443 if (!init) {
1444 unsupported(stmt);
1445 return NULL;
1447 if ((ass = initialization_assignment(init)) != NULL) {
1448 iv = extract_induction_variable(ass);
1449 if (!iv)
1450 return NULL;
1451 lhs = ass->getLHS();
1452 rhs = ass->getRHS();
1453 } else if ((decl = initialization_declaration(init)) != NULL) {
1454 VarDecl *var = extract_induction_variable(init, decl);
1455 if (!var)
1456 return NULL;
1457 iv = var;
1458 rhs = var->getInit();
1459 lhs = create_DeclRefExpr(var);
1460 } else {
1461 unsupported(stmt->getInit());
1462 return NULL;
1465 declared = !initialization_assignment(stmt->getInit());
1466 tree = extract(stmt->getBody());
1467 if (partial)
1468 return tree;
1469 pe_iv = extract_access_expr(iv);
1470 pe_iv = mark_write(pe_iv);
1471 pe_init = extract_expr(rhs);
1472 if (!stmt->getCond())
1473 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1474 else
1475 pe_cond = extract_expr(stmt->getCond());
1476 pe_inc = extract_increment(stmt, iv);
1477 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1478 pe_inc, tree);
1479 return tree;
1482 /* Store the names of the variables declared in decl_context
1483 * in the set declared_names. Make sure to only do this once by
1484 * setting declared_names_collected.
1486 void PetScan::collect_declared_names()
1488 DeclContext *DC = decl_context;
1489 DeclContext::decl_iterator it;
1491 if (declared_names_collected)
1492 return;
1494 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1495 Decl *D = *it;
1496 NamedDecl *named;
1498 if (!isa<NamedDecl>(D))
1499 continue;
1500 named = cast<NamedDecl>(D);
1501 declared_names.insert(named->getName().str());
1504 declared_names_collected = true;
1507 /* Add the names in "names" that are not also in this->declared_names
1508 * to this->used_names.
1509 * It is up to the caller to make sure that declared_names has been
1510 * populated, if needed.
1512 void PetScan::add_new_used_names(const std::set<std::string> &names)
1514 std::set<std::string>::const_iterator it;
1516 for (it = names.begin(); it != names.end(); ++it) {
1517 if (declared_names.find(*it) != declared_names.end())
1518 continue;
1519 used_names.insert(*it);
1523 /* Is the name "name" used in any declaration other than "decl"?
1525 * If the name was found to be in use before, the consider it to be in use.
1526 * Otherwise, check the DeclContext of the function containing the scop
1527 * as well as all ancestors of this DeclContext for declarations
1528 * other than "decl" that declare something called "name".
1530 bool PetScan::name_in_use(const string &name, Decl *decl)
1532 DeclContext *DC;
1533 DeclContext::decl_iterator it;
1535 if (used_names.find(name) != used_names.end())
1536 return true;
1538 for (DC = decl_context; DC; DC = DC->getParent()) {
1539 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1540 Decl *D = *it;
1541 NamedDecl *named;
1543 if (D == decl)
1544 continue;
1545 if (!isa<NamedDecl>(D))
1546 continue;
1547 named = cast<NamedDecl>(D);
1548 if (named->getName().str() == name)
1549 return true;
1553 return false;
1556 /* Generate a new name based on "name" that is not in use.
1557 * Do so by adding a suffix _i, with i an integer.
1559 string PetScan::generate_new_name(const string &name)
1561 string new_name;
1563 do {
1564 std::ostringstream oss;
1565 oss << name << "_" << n_rename++;
1566 new_name = oss.str();
1567 } while (name_in_use(new_name, NULL));
1569 return new_name;
1572 /* Try and construct a pet_tree corresponding to a compound statement.
1574 * "skip_declarations" is set if we should skip initial declarations
1575 * in the children of the compound statements.
1577 * Collect a new set of declarations for the current compound statement.
1578 * If any of the names in these declarations is also used by another
1579 * declaration reachable from the current function, then rename it
1580 * to a name that is not already in use.
1581 * In particular, keep track of the old and new names in a pet_substituter
1582 * and apply the substitutions to the pet_tree corresponding to the
1583 * compound statement.
1585 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1586 bool skip_declarations)
1588 pet_tree *tree;
1589 std::vector<VarDecl *> saved_declarations;
1590 std::vector<VarDecl *>::iterator it;
1591 pet_substituter substituter;
1593 saved_declarations = declarations;
1594 declarations.clear();
1595 tree = extract(stmt->children(), true, skip_declarations, stmt);
1596 for (it = declarations.begin(); it != declarations.end(); ++it) {
1597 isl_id *id;
1598 pet_expr *expr;
1599 VarDecl *decl = *it;
1600 string name = decl->getName().str();
1601 bool in_use = name_in_use(name, decl);
1603 used_names.insert(name);
1604 if (!in_use)
1605 continue;
1607 name = generate_new_name(name);
1608 id = pet_id_from_name_and_decl(ctx, name.c_str(), decl);
1609 expr = pet_id_create_index_expr(id);
1610 expr = extract_access_expr(decl->getType(), expr);
1611 id = pet_id_from_decl(ctx, decl);
1612 substituter.add_sub(id, expr);
1613 used_names.insert(name);
1615 tree = substituter.substitute(tree);
1616 declarations = saved_declarations;
1618 return tree;
1621 /* Return the file offset of the expansion location of "Loc".
1623 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1625 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1628 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1630 /* Return a SourceLocation for the location after the first semicolon
1631 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1632 * call it and also skip trailing spaces and newline.
1634 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1635 const LangOptions &LO)
1637 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1640 #else
1642 /* Return a SourceLocation for the location after the first semicolon
1643 * after "loc". If Lexer::findLocationAfterToken is not available,
1644 * we look in the underlying character data for the first semicolon.
1646 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1647 const LangOptions &LO)
1649 const char *semi;
1650 const char *s = SM.getCharacterData(loc);
1652 semi = strchr(s, ';');
1653 if (!semi)
1654 return SourceLocation();
1655 return loc.getFileLocWithOffset(semi + 1 - s);
1658 #endif
1660 /* If the token at "loc" is the first token on the line, then return
1661 * a location referring to the start of the line and set *indent
1662 * to the indentation of "loc"
1663 * Otherwise, return "loc" and set *indent to "".
1665 * This function is used to extend a scop to the start of the line
1666 * if the first token of the scop is also the first token on the line.
1668 * We look for the first token on the line. If its location is equal to "loc",
1669 * then the latter is the location of the first token on the line.
1671 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1672 SourceManager &SM, const LangOptions &LO, char **indent)
1674 std::pair<FileID, unsigned> file_offset_pair;
1675 llvm::StringRef file;
1676 const char *pos;
1677 Token tok;
1678 SourceLocation token_loc, line_loc;
1679 int col;
1680 const char *s;
1682 loc = SM.getExpansionLoc(loc);
1683 col = SM.getExpansionColumnNumber(loc);
1684 line_loc = loc.getLocWithOffset(1 - col);
1685 file_offset_pair = SM.getDecomposedLoc(line_loc);
1686 file = SM.getBufferData(file_offset_pair.first, NULL);
1687 pos = file.data() + file_offset_pair.second;
1689 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1690 file.begin(), pos, file.end());
1691 lexer.LexFromRawLexer(tok);
1692 token_loc = tok.getLocation();
1694 s = SM.getCharacterData(line_loc);
1695 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1697 if (token_loc == loc)
1698 return line_loc;
1699 else
1700 return loc;
1703 /* Construct a pet_loc corresponding to the region covered by "range".
1704 * If "skip_semi" is set, then we assume "range" is followed by
1705 * a semicolon and also include this semicolon.
1707 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1708 bool skip_semi)
1710 SourceLocation loc = range.getBegin();
1711 SourceManager &SM = PP.getSourceManager();
1712 const LangOptions &LO = PP.getLangOpts();
1713 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1714 unsigned start, end;
1715 char *indent;
1717 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1718 start = getExpansionOffset(SM, loc);
1719 loc = range.getEnd();
1720 if (skip_semi)
1721 loc = location_after_semi(loc, SM, LO);
1722 else
1723 loc = PP.getLocForEndOfToken(loc);
1724 end = getExpansionOffset(SM, loc);
1726 return pet_loc_alloc(ctx, start, end, line, indent);
1729 /* Convert a top-level pet_expr to an expression pet_tree.
1731 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1732 SourceRange range, bool skip_semi)
1734 pet_loc *loc;
1735 pet_tree *tree;
1737 tree = pet_tree_new_expr(expr);
1738 loc = construct_pet_loc(range, skip_semi);
1739 tree = pet_tree_set_loc(tree, loc);
1741 return tree;
1744 /* Construct a pet_tree for an if statement.
1746 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1748 pet_expr *pe_cond;
1749 pet_tree *tree, *tree_else;
1751 pe_cond = extract_expr(stmt->getCond());
1752 tree = extract(stmt->getThen());
1753 if (stmt->getElse()) {
1754 tree_else = extract(stmt->getElse());
1755 if (options->autodetect) {
1756 if (tree && !tree_else) {
1757 partial = true;
1758 pet_expr_free(pe_cond);
1759 return tree;
1761 if (!tree && tree_else) {
1762 partial = true;
1763 pet_expr_free(pe_cond);
1764 return tree_else;
1767 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1768 } else
1769 tree = pet_tree_new_if(pe_cond, tree);
1770 return tree;
1773 /* Try and construct a pet_tree for a label statement.
1775 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1777 isl_id *label;
1778 pet_tree *tree;
1780 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1782 tree = extract(stmt->getSubStmt());
1783 tree = pet_tree_set_label(tree, label);
1784 return tree;
1787 /* Update the location of "tree" to include the source range of "stmt".
1789 * Actually, we create a new location based on the source range of "stmt" and
1790 * then extend this new location to include the region of the original location.
1791 * This ensures that the line number of the final location refers to "stmt".
1793 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1795 pet_loc *loc, *tree_loc;
1797 tree_loc = pet_tree_get_loc(tree);
1798 loc = construct_pet_loc(stmt->getSourceRange(), false);
1799 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1800 pet_loc_free(tree_loc);
1802 tree = pet_tree_set_loc(tree, loc);
1803 return tree;
1806 /* Is "expr" of a type that can be converted to an access expression?
1808 static bool is_access_expr_type(Expr *expr)
1810 switch (expr->getStmtClass()) {
1811 case Stmt::ArraySubscriptExprClass:
1812 case Stmt::DeclRefExprClass:
1813 case Stmt::MemberExprClass:
1814 return true;
1815 default:
1816 return false;
1820 /* Tell the pet_inliner "inliner" about the formal arguments
1821 * in "fd" and the corresponding actual arguments in "call".
1822 * Return 0 if this was successful and -1 otherwise.
1824 * Any pointer argument is treated as an array.
1825 * The other arguments are treated as scalars.
1827 * In case of scalars, there is no restriction on the actual argument.
1828 * This actual argument is assigned to a variable with a name
1829 * that is derived from the name of the corresponding formal argument,
1830 * but made not to conflict with any variable names that are
1831 * already in use.
1833 * In case of arrays, the actual argument needs to be an expression
1834 * of a type that can be converted to an access expression or the address
1835 * of such an expression, ignoring implicit and redundant casts.
1837 int PetScan::set_inliner_arguments(pet_inliner &inliner, CallExpr *call,
1838 FunctionDecl *fd)
1840 unsigned n;
1842 n = fd->getNumParams();
1843 for (unsigned i = 0; i < n; ++i) {
1844 ParmVarDecl *parm = fd->getParamDecl(i);
1845 QualType type = parm->getType();
1846 Expr *arg, *sub;
1847 pet_expr *expr;
1848 int is_addr = 0;
1850 arg = call->getArg(i);
1851 if (pet_clang_array_depth(type) == 0) {
1852 string name = parm->getName().str();
1853 if (name_in_use(name, NULL))
1854 name = generate_new_name(name);
1855 used_names.insert(name);
1856 inliner.add_scalar_arg(parm, name, extract_expr(arg));
1857 continue;
1859 arg = pet_clang_strip_casts(arg);
1860 sub = extract_addr_of_arg(arg);
1861 if (sub) {
1862 is_addr = 1;
1863 arg = pet_clang_strip_casts(sub);
1865 if (!is_access_expr_type(arg)) {
1866 report_unsupported_inline_function_argument(arg);
1867 return -1;
1869 expr = extract_access_expr(arg);
1870 if (!expr)
1871 return -1;
1872 inliner.add_array_arg(parm, expr, is_addr);
1875 return 0;
1878 /* Internal data structure for PetScan::substitute_array_sizes.
1879 * ps is the PetScan on which the method was called.
1880 * substituter is the substituter that is used to substitute variables
1881 * in the size expressions.
1883 struct pet_substitute_array_sizes_data {
1884 PetScan *ps;
1885 pet_substituter *substituter;
1888 extern "C" {
1889 static int substitute_array_size(__isl_keep pet_tree *tree, void *user);
1892 /* If "tree" is a declaration, then perform the substitutions
1893 * in data->substituter on its size expression and store the result
1894 * in the size expression cache of data->ps such that the modified expression
1895 * will be used in subsequent calls to get_array_size.
1897 static int substitute_array_size(__isl_keep pet_tree *tree, void *user)
1899 struct pet_substitute_array_sizes_data *data;
1900 isl_id *id;
1901 pet_expr *var, *size;
1903 if (!pet_tree_is_decl(tree))
1904 return 0;
1906 data = (struct pet_substitute_array_sizes_data *) user;
1907 var = pet_tree_decl_get_var(tree);
1908 id = pet_expr_access_get_id(var);
1909 pet_expr_free(var);
1911 size = data->ps->get_array_size(id);
1912 size = data->substituter->substitute(size);
1913 data->ps->set_array_size(id, size);
1915 return 0;
1918 /* Perform the substitutions in "substituter" on all the arrays declared
1919 * inside "tree" and store the results in the size expression cache
1920 * such that the modified expressions will be used in subsequent calls
1921 * to get_array_size.
1923 int PetScan::substitute_array_sizes(__isl_keep pet_tree *tree,
1924 pet_substituter *substituter)
1926 struct pet_substitute_array_sizes_data data = { this, substituter };
1928 return pet_tree_foreach_sub_tree(tree, &substitute_array_size, &data);
1931 /* Try and construct a pet_tree from the body of "fd" using the actual
1932 * arguments in "call" in place of the formal arguments.
1933 * "fd" is assumed to point to the declaration with a function body.
1934 * In particular, construct a block that consists of assignments
1935 * of (parts of) the actual arguments to temporary variables
1936 * followed by the inlined function body with the formal arguments
1937 * replaced by (expressions containing) these temporary variables.
1939 * The actual inlining is taken care of by the pet_inliner object.
1940 * This function merely calls set_inliner_arguments to tell
1941 * the pet_inliner about the actual arguments, extracts a pet_tree
1942 * from the body of the called function and then passes this pet_tree
1943 * to the pet_inliner.
1944 * The substitutions performed by the inliner are also applied
1945 * to the size expressions of the arrays declared in the inlined
1946 * function. These size expressions are not stored in the tree
1947 * itself, but rather in the size expression cache.
1949 * During the extraction of the function body, all variables names
1950 * that are declared in the calling function as well all variable
1951 * names that are known to be in use are considered to be in use
1952 * in the called function to ensure that there is no naming conflict.
1953 * Similarly, the additional names that are in use in the called function
1954 * are considered to be in use in the calling function as well.
1956 * The location of the pet_tree is reset to the call site to ensure
1957 * that the extent of the scop does not include the body of the called
1958 * function.
1960 __isl_give pet_tree *PetScan::extract_inlined_call(CallExpr *call,
1961 FunctionDecl *fd)
1963 int save_autodetect;
1964 pet_tree *tree;
1965 pet_loc *tree_loc;
1966 pet_inliner inliner(ctx, n_arg, ast_context);
1968 if (set_inliner_arguments(inliner, call, fd) < 0)
1969 return NULL;
1971 save_autodetect = options->autodetect;
1972 options->autodetect = 0;
1973 PetScan body_scan(PP, ast_context, fd, loc, options,
1974 isl_union_map_copy(value_bounds), independent);
1975 collect_declared_names();
1976 body_scan.add_new_used_names(declared_names);
1977 body_scan.add_new_used_names(used_names);
1978 tree = body_scan.extract(fd->getBody(), false);
1979 add_new_used_names(body_scan.used_names);
1980 options->autodetect = save_autodetect;
1982 tree_loc = construct_pet_loc(call->getSourceRange(), true);
1983 tree = pet_tree_set_loc(tree, tree_loc);
1985 substitute_array_sizes(tree, &inliner);
1987 return inliner.inline_tree(tree);
1990 /* Try and construct a pet_tree corresponding
1991 * to the expression statement "stmt".
1993 * If the outer expression is a function call and if the corresponding
1994 * function body is marked "inline", then return a pet_tree
1995 * corresponding to the inlined function.
1997 __isl_give pet_tree *PetScan::extract_expr_stmt(Stmt *stmt)
1999 pet_expr *expr;
2001 if (stmt->getStmtClass() == Stmt::CallExprClass) {
2002 CallExpr *call = cast<CallExpr>(stmt);
2003 FunctionDecl *fd = call->getDirectCallee();
2004 fd = pet_clang_find_function_decl_with_body(fd);
2005 if (fd && fd->isInlineSpecified())
2006 return extract_inlined_call(call, fd);
2009 expr = extract_expr(cast<Expr>(stmt));
2010 return extract(expr, stmt->getSourceRange(), true);
2013 /* Try and construct a pet_tree corresponding to "stmt".
2015 * If "stmt" is a compound statement, then "skip_declarations"
2016 * indicates whether we should skip initial declarations in the
2017 * compound statement.
2019 * If the constructed pet_tree is not a (possibly) partial representation
2020 * of "stmt", we update start and end of the pet_scop to those of "stmt".
2021 * In particular, if skip_declarations is set, then we may have skipped
2022 * declarations inside "stmt" and so the pet_scop may not represent
2023 * the entire "stmt".
2024 * Note that this function may be called with "stmt" referring to the entire
2025 * body of the function, including the outer braces. In such cases,
2026 * skip_declarations will be set and the braces will not be taken into
2027 * account in tree->loc.
2029 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
2031 pet_tree *tree;
2033 set_current_stmt(stmt);
2035 if (isa<Expr>(stmt))
2036 return extract_expr_stmt(cast<Expr>(stmt));
2038 switch (stmt->getStmtClass()) {
2039 case Stmt::WhileStmtClass:
2040 tree = extract(cast<WhileStmt>(stmt));
2041 break;
2042 case Stmt::ForStmtClass:
2043 tree = extract_for(cast<ForStmt>(stmt));
2044 break;
2045 case Stmt::IfStmtClass:
2046 tree = extract(cast<IfStmt>(stmt));
2047 break;
2048 case Stmt::CompoundStmtClass:
2049 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
2050 break;
2051 case Stmt::LabelStmtClass:
2052 tree = extract(cast<LabelStmt>(stmt));
2053 break;
2054 case Stmt::ContinueStmtClass:
2055 tree = pet_tree_new_continue(ctx);
2056 break;
2057 case Stmt::BreakStmtClass:
2058 tree = pet_tree_new_break(ctx);
2059 break;
2060 case Stmt::DeclStmtClass:
2061 tree = extract(cast<DeclStmt>(stmt));
2062 break;
2063 case Stmt::NullStmtClass:
2064 tree = pet_tree_new_block(ctx, 0, 0);
2065 break;
2066 default:
2067 report_unsupported_statement_type(stmt);
2068 return NULL;
2071 if (partial || skip_declarations)
2072 return tree;
2074 return update_loc(tree, stmt);
2077 /* Given a sequence of statements "stmt_range" of which the first "n_decl"
2078 * are declarations and of which the remaining statements are represented
2079 * by "tree", try and extend "tree" to include the last sequence of
2080 * the initial declarations that can be completely extracted.
2082 * We start collecting the initial declarations and start over
2083 * whenever we come across a declaration that we cannot extract.
2084 * If we have been able to extract any declarations, then we
2085 * copy over the contents of "tree" at the end of the declarations.
2086 * Otherwise, we simply return the original "tree".
2088 __isl_give pet_tree *PetScan::insert_initial_declarations(
2089 __isl_take pet_tree *tree, int n_decl, StmtRange stmt_range)
2091 StmtIterator i;
2092 pet_tree *res;
2093 int n_stmt;
2094 int is_block;
2095 int j;
2097 n_stmt = pet_tree_block_n_child(tree);
2098 is_block = pet_tree_block_get_block(tree);
2099 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2101 for (i = stmt_range.first; n_decl; ++i, --n_decl) {
2102 Stmt *child = *i;
2103 pet_tree *tree_i;
2105 tree_i = extract(child);
2106 if (tree_i && !partial) {
2107 res = pet_tree_block_add_child(res, tree_i);
2108 continue;
2110 pet_tree_free(tree_i);
2111 partial = false;
2112 if (pet_tree_block_n_child(res) == 0)
2113 continue;
2114 pet_tree_free(res);
2115 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2118 if (pet_tree_block_n_child(res) == 0) {
2119 pet_tree_free(res);
2120 return tree;
2123 for (j = 0; j < n_stmt; ++j) {
2124 pet_tree *tree_i;
2126 tree_i = pet_tree_block_get_child(tree, j);
2127 res = pet_tree_block_add_child(res, tree_i);
2129 pet_tree_free(tree);
2131 return res;
2134 /* Try and construct a pet_tree corresponding to (part of)
2135 * a sequence of statements.
2137 * "block" is set if the sequence represents the children of
2138 * a compound statement.
2139 * "skip_declarations" is set if we should skip initial declarations
2140 * in the sequence of statements.
2141 * "parent" is the statement that has stmt_range as (some of) its children.
2143 * If autodetect is set, then we allow the extraction of only a subrange
2144 * of the sequence of statements. However, if there is at least one
2145 * kill and there is some subsequent statement for which we could not
2146 * construct a tree, then turn off the "block" property of the tree
2147 * such that no extra kill will be introduced at the end of the (partial)
2148 * block. If, on the other hand, the final range contains
2149 * no statements, then we discard the entire range.
2150 * If only a subrange of the sequence was extracted, but each statement
2151 * in the sequence was extracted completely, and if there are some
2152 * variable declarations in the sequence before or inside
2153 * the extracted subrange, then check if any of these variables are
2154 * not used after the extracted subrange. If so, add kills to these
2155 * variables.
2157 * If the entire range was extracted, apart from some initial declarations,
2158 * then we try and extend the range with the latest of those initial
2159 * declarations.
2161 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
2162 bool skip_declarations, Stmt *parent)
2164 StmtIterator i;
2165 int j, skip;
2166 bool has_kills = false;
2167 bool partial_range = false;
2168 bool outer_partial = false;
2169 pet_tree *tree;
2170 SourceManager &SM = PP.getSourceManager();
2171 pet_killed_locals kl(SM);
2172 unsigned range_start, range_end;
2174 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
2177 tree = pet_tree_new_block(ctx, block, j);
2179 skip = 0;
2180 i = stmt_range.first;
2181 if (skip_declarations)
2182 for (; i != stmt_range.second; ++i) {
2183 if ((*i)->getStmtClass() != Stmt::DeclStmtClass)
2184 break;
2185 if (options->autodetect)
2186 kl.add_locals(cast<DeclStmt>(*i));
2187 ++skip;
2190 for (; i != stmt_range.second; ++i) {
2191 Stmt *child = *i;
2192 pet_tree *tree_i;
2194 tree_i = extract(child);
2195 if (pet_tree_block_n_child(tree) != 0 && partial) {
2196 pet_tree_free(tree_i);
2197 break;
2199 if (child->getStmtClass() == Stmt::DeclStmtClass) {
2200 if (options->autodetect)
2201 kl.add_locals(cast<DeclStmt>(child));
2202 if (tree_i && block)
2203 has_kills = true;
2205 if (options->autodetect) {
2206 if (tree_i) {
2207 range_end = getExpansionOffset(SM,
2208 child->getLocEnd());
2209 if (pet_tree_block_n_child(tree) == 0)
2210 range_start = getExpansionOffset(SM,
2211 child->getLocStart());
2212 tree = pet_tree_block_add_child(tree, tree_i);
2213 } else {
2214 partial_range = true;
2216 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
2217 outer_partial = partial = true;
2218 } else {
2219 tree = pet_tree_block_add_child(tree, tree_i);
2222 if (partial || !tree)
2223 break;
2226 if (!tree)
2227 return NULL;
2229 if (partial) {
2230 if (has_kills)
2231 tree = pet_tree_block_set_block(tree, 0);
2232 if (outer_partial) {
2233 kl.remove_accessed_after(parent,
2234 range_start, range_end);
2235 tree = add_kills(tree, kl.locals);
2237 } else if (partial_range) {
2238 if (pet_tree_block_n_child(tree) == 0) {
2239 pet_tree_free(tree);
2240 return NULL;
2242 partial = true;
2243 } else if (skip > 0)
2244 tree = insert_initial_declarations(tree, skip, stmt_range);
2246 return tree;
2249 extern "C" {
2250 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2251 void *user);
2252 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2253 __isl_keep pet_context *pc, void *user);
2256 /* Construct a pet_expr that holds the sizes of the array accessed
2257 * by "access".
2258 * This function is used as a callback to pet_context_add_parameters,
2259 * which is also passed a pointer to the PetScan object.
2261 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2262 void *user)
2264 PetScan *ps = (PetScan *) user;
2265 isl_id *id;
2266 pet_expr *size;
2268 id = pet_expr_access_get_id(access);
2269 size = ps->get_array_size(id);
2270 isl_id_free(id);
2272 return size;
2275 /* Construct and return a pet_array corresponding to the variable
2276 * accessed by "access".
2277 * This function is used as a callback to pet_scop_from_pet_tree,
2278 * which is also passed a pointer to the PetScan object.
2280 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2281 __isl_keep pet_context *pc, void *user)
2283 PetScan *ps = (PetScan *) user;
2284 isl_id *id;
2285 pet_array *array;
2287 id = pet_expr_access_get_id(access);
2288 array = ps->extract_array(id, NULL, pc);
2289 isl_id_free(id);
2291 return array;
2294 /* Extract a function summary from the body of "fd".
2296 * We extract a scop from the function body in a context with as
2297 * parameters the integer arguments of the function.
2298 * We turn off autodetection (in case it was set) to ensure that
2299 * the entire function body is considered.
2300 * We then collect the accessed array elements and attach them
2301 * to the corresponding array arguments, taking into account
2302 * that the function body may access members of array elements.
2304 * The reason for representing the integer arguments as parameters in
2305 * the context is that if we were to instead start with a context
2306 * with the function arguments as initial dimensions, then we would not
2307 * be able to refer to them from the array extents, without turning
2308 * array extents into maps.
2310 * The result is stored in the summary_cache cache so that we can reuse
2311 * it if this method gets called on the same function again later on.
2313 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
2315 isl_space *space;
2316 isl_set *domain;
2317 pet_context *pc;
2318 pet_tree *tree;
2319 pet_function_summary *summary;
2320 unsigned n;
2321 ScopLoc loc;
2322 int save_autodetect;
2323 struct pet_scop *scop;
2324 int int_size;
2325 isl_union_set *may_read, *may_write, *must_write;
2326 isl_union_map *to_inner;
2328 if (summary_cache.find(fd) != summary_cache.end())
2329 return pet_function_summary_copy(summary_cache[fd]);
2331 space = isl_space_set_alloc(ctx, 0, 0);
2333 n = fd->getNumParams();
2334 summary = pet_function_summary_alloc(ctx, n);
2335 for (unsigned i = 0; i < n; ++i) {
2336 ParmVarDecl *parm = fd->getParamDecl(i);
2337 QualType type = parm->getType();
2338 isl_id *id;
2340 if (!type->isIntegerType())
2341 continue;
2342 id = pet_id_from_decl(ctx, parm);
2343 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
2344 space = isl_space_set_dim_id(space, isl_dim_param, 0,
2345 isl_id_copy(id));
2346 summary = pet_function_summary_set_int(summary, i, id);
2349 save_autodetect = options->autodetect;
2350 options->autodetect = 0;
2351 PetScan body_scan(PP, ast_context, fd, loc, options,
2352 isl_union_map_copy(value_bounds), independent);
2354 tree = body_scan.extract(fd->getBody(), false);
2356 domain = isl_set_universe(space);
2357 pc = pet_context_alloc(domain);
2358 pc = pet_context_add_parameters(pc, tree,
2359 &::get_array_size, &body_scan);
2360 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2361 scop = pet_scop_from_pet_tree(tree, int_size,
2362 &::extract_array, &body_scan, pc);
2363 scop = scan_arrays(scop, pc);
2364 may_read = isl_union_map_range(pet_scop_get_may_reads(scop));
2365 may_write = isl_union_map_range(pet_scop_get_may_writes(scop));
2366 must_write = isl_union_map_range(pet_scop_get_must_writes(scop));
2367 to_inner = pet_scop_compute_outer_to_inner(scop);
2368 pet_scop_free(scop);
2370 for (unsigned i = 0; i < n; ++i) {
2371 ParmVarDecl *parm = fd->getParamDecl(i);
2372 QualType type = parm->getType();
2373 struct pet_array *array;
2374 isl_space *space;
2375 isl_union_set *data_set;
2376 isl_union_set *may_read_i, *may_write_i, *must_write_i;
2378 if (pet_clang_array_depth(type) == 0)
2379 continue;
2381 array = body_scan.extract_array(parm, NULL, pc);
2382 space = array ? isl_set_get_space(array->extent) : NULL;
2383 pet_array_free(array);
2384 data_set = isl_union_set_from_set(isl_set_universe(space));
2385 data_set = isl_union_set_apply(data_set,
2386 isl_union_map_copy(to_inner));
2387 may_read_i = isl_union_set_intersect(
2388 isl_union_set_copy(may_read),
2389 isl_union_set_copy(data_set));
2390 may_write_i = isl_union_set_intersect(
2391 isl_union_set_copy(may_write),
2392 isl_union_set_copy(data_set));
2393 must_write_i = isl_union_set_intersect(
2394 isl_union_set_copy(must_write), data_set);
2395 summary = pet_function_summary_set_array(summary, i,
2396 may_read_i, may_write_i, must_write_i);
2399 isl_union_set_free(may_read);
2400 isl_union_set_free(may_write);
2401 isl_union_set_free(must_write);
2402 isl_union_map_free(to_inner);
2404 options->autodetect = save_autodetect;
2405 pet_context_free(pc);
2407 summary_cache[fd] = pet_function_summary_copy(summary);
2409 return summary;
2412 /* If "fd" has a function body, then extract a function summary from
2413 * this body and attach it to the call expression "expr".
2415 * Even if a function body is available, "fd" itself may point
2416 * to a declaration without function body. We therefore first
2417 * replace it by the declaration that comes with a body (if any).
2419 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
2420 FunctionDecl *fd)
2422 pet_function_summary *summary;
2424 if (!expr)
2425 return NULL;
2426 fd = pet_clang_find_function_decl_with_body(fd);
2427 if (!fd)
2428 return expr;
2430 summary = get_summary(fd);
2432 expr = pet_expr_call_set_summary(expr, summary);
2434 return expr;
2437 /* Extract a pet_scop from "tree".
2439 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
2440 * then add pet_arrays for all accessed arrays.
2441 * We populate the pet_context with assignments for all parameters used
2442 * inside "tree" or any of the size expressions for the arrays accessed
2443 * by "tree" so that they can be used in affine expressions.
2445 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
2447 int int_size;
2448 isl_set *domain;
2449 pet_context *pc;
2450 pet_scop *scop;
2452 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2454 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2455 pc = pet_context_alloc(domain);
2456 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
2457 scop = pet_scop_from_pet_tree(tree, int_size,
2458 &::extract_array, this, pc);
2459 scop = scan_arrays(scop, pc);
2460 pet_context_free(pc);
2462 return scop;
2465 /* Add a call to __pencil_kill to the end of "tree" that kills
2466 * all the variables in "locals" and return the result.
2468 * No location is added to the kill because the most natural
2469 * location would lie outside the scop. Attaching such a location
2470 * to this tree would extend the scope of the final result
2471 * to include the location.
2473 __isl_give pet_tree *PetScan::add_kills(__isl_take pet_tree *tree,
2474 set<ValueDecl *> locals)
2476 int i;
2477 pet_expr *expr;
2478 pet_tree *kill, *block;
2479 set<ValueDecl *>::iterator it;
2481 if (locals.size() == 0)
2482 return tree;
2483 expr = pet_expr_new_call(ctx, "__pencil_kill", locals.size());
2484 i = 0;
2485 for (it = locals.begin(); it != locals.end(); ++it) {
2486 pet_expr *arg;
2487 arg = extract_access_expr(*it);
2488 expr = pet_expr_set_arg(expr, i++, arg);
2490 kill = pet_tree_new_expr(expr);
2491 block = pet_tree_new_block(ctx, 0, 2);
2492 block = pet_tree_block_add_child(block, tree);
2493 block = pet_tree_block_add_child(block, kill);
2495 return block;
2498 /* Check if the scop marked by the user is exactly this Stmt
2499 * or part of this Stmt.
2500 * If so, return a pet_scop corresponding to the marked region.
2501 * Otherwise, return NULL.
2503 * If the scop is not further nested inside a child of "stmt",
2504 * then check if there are any variable declarations before the scop
2505 * inside "stmt". If so, and if these variables are not used
2506 * after the scop, then add kills to the variables.
2508 struct pet_scop *PetScan::scan(Stmt *stmt)
2510 SourceManager &SM = PP.getSourceManager();
2511 unsigned start_off, end_off;
2512 pet_tree *tree;
2514 start_off = getExpansionOffset(SM, stmt->getLocStart());
2515 end_off = getExpansionOffset(SM, stmt->getLocEnd());
2517 if (start_off > loc.end)
2518 return NULL;
2519 if (end_off < loc.start)
2520 return NULL;
2522 if (start_off >= loc.start && end_off <= loc.end)
2523 return extract_scop(extract(stmt));
2525 pet_killed_locals kl(SM);
2526 StmtIterator start;
2527 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
2528 Stmt *child = *start;
2529 if (!child)
2530 continue;
2531 start_off = getExpansionOffset(SM, child->getLocStart());
2532 end_off = getExpansionOffset(SM, child->getLocEnd());
2533 if (start_off < loc.start && end_off >= loc.end)
2534 return scan(child);
2535 if (start_off >= loc.start)
2536 break;
2537 if (isa<DeclStmt>(child))
2538 kl.add_locals(cast<DeclStmt>(child));
2541 StmtIterator end;
2542 for (end = start; end != stmt->child_end(); ++end) {
2543 Stmt *child = *end;
2544 start_off = SM.getFileOffset(child->getLocStart());
2545 if (start_off >= loc.end)
2546 break;
2549 kl.remove_accessed_after(stmt, loc.start, loc.end);
2551 tree = extract(StmtRange(start, end), false, false, stmt);
2552 tree = add_kills(tree, kl.locals);
2553 return extract_scop(tree);
2556 /* Set the size of index "pos" of "array" to "size".
2557 * In particular, add a constraint of the form
2559 * i_pos < size
2561 * to array->extent and a constraint of the form
2563 * size >= 0
2565 * to array->context.
2567 * The domain of "size" is assumed to be zero-dimensional.
2569 static struct pet_array *update_size(struct pet_array *array, int pos,
2570 __isl_take isl_pw_aff *size)
2572 isl_set *valid;
2573 isl_set *univ;
2574 isl_set *bound;
2575 isl_space *dim;
2576 isl_aff *aff;
2577 isl_pw_aff *index;
2578 isl_id *id;
2580 if (!array)
2581 goto error;
2583 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2584 array->context = isl_set_intersect(array->context, valid);
2586 dim = isl_set_get_space(array->extent);
2587 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2588 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2589 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2590 index = isl_pw_aff_alloc(univ, aff);
2592 size = isl_pw_aff_add_dims(size, isl_dim_in,
2593 isl_set_dim(array->extent, isl_dim_set));
2594 id = isl_set_get_tuple_id(array->extent);
2595 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2596 bound = isl_pw_aff_lt_set(index, size);
2598 array->extent = isl_set_intersect(array->extent, bound);
2600 if (!array->context || !array->extent)
2601 return pet_array_free(array);
2603 return array;
2604 error:
2605 isl_pw_aff_free(size);
2606 return NULL;
2609 #ifdef HAVE_DECAYEDTYPE
2611 /* If "qt" is a decayed type, then set *decayed to true and
2612 * return the original type.
2614 static QualType undecay(QualType qt, bool *decayed)
2616 const Type *type = qt.getTypePtr();
2618 *decayed = isa<DecayedType>(type);
2619 if (*decayed)
2620 qt = cast<DecayedType>(type)->getOriginalType();
2621 return qt;
2624 #else
2626 /* If "qt" is a decayed type, then set *decayed to true and
2627 * return the original type.
2628 * Since this version of clang does not define a DecayedType,
2629 * we cannot obtain the original type even if it had been decayed and
2630 * we set *decayed to false.
2632 static QualType undecay(QualType qt, bool *decayed)
2634 *decayed = false;
2635 return qt;
2638 #endif
2640 /* Figure out the size of the array at position "pos" and all
2641 * subsequent positions from "qt" and update the corresponding
2642 * argument of "expr" accordingly.
2644 * The initial type (when pos is zero) may be a pointer type decayed
2645 * from an array type, if this initial type is the type of a function
2646 * argument. This only happens if the original array type has
2647 * a constant size in the outer dimension as otherwise we get
2648 * a VariableArrayType. Try and obtain this original type (if available) and
2649 * take the outer array size into account if it was marked static.
2651 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2652 QualType qt, int pos)
2654 const ArrayType *atype;
2655 pet_expr *size;
2656 bool decayed = false;
2658 if (!expr)
2659 return NULL;
2661 if (pos == 0)
2662 qt = undecay(qt, &decayed);
2664 if (qt->isPointerType()) {
2665 qt = qt->getPointeeType();
2666 return set_upper_bounds(expr, qt, pos + 1);
2668 if (!qt->isArrayType())
2669 return expr;
2671 qt = qt->getCanonicalTypeInternal();
2672 atype = cast<ArrayType>(qt.getTypePtr());
2674 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2675 qt = atype->getElementType();
2676 return set_upper_bounds(expr, qt, pos + 1);
2679 if (qt->isConstantArrayType()) {
2680 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2681 size = extract_expr(ca->getSize());
2682 expr = pet_expr_set_arg(expr, pos, size);
2683 } else if (qt->isVariableArrayType()) {
2684 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2685 size = extract_expr(vla->getSizeExpr());
2686 expr = pet_expr_set_arg(expr, pos, size);
2689 qt = atype->getElementType();
2691 return set_upper_bounds(expr, qt, pos + 1);
2694 /* Construct a pet_expr that holds the sizes of the array represented by "id".
2695 * The returned expression is a call expression with as arguments
2696 * the sizes in each dimension. If we are unable to derive the size
2697 * in a given dimension, then the corresponding argument is set to infinity.
2698 * In fact, we initialize all arguments to infinity and then update
2699 * them if we are able to figure out the size.
2701 * The result is stored in the id_size cache so that it can be reused
2702 * if this method is called on the same array identifier later.
2703 * The result is also stored in the type_size cache in case
2704 * it gets called on a different array identifier with the same type.
2706 __isl_give pet_expr *PetScan::get_array_size(__isl_keep isl_id *id)
2708 QualType qt = pet_id_get_array_type(id);
2709 int depth;
2710 pet_expr *expr, *inf;
2711 const Type *type = qt.getTypePtr();
2712 isl_maybe_pet_expr m;
2714 m = isl_id_to_pet_expr_try_get(id_size, id);
2715 if (m.valid < 0 || m.valid)
2716 return m.value;
2717 if (type_size.find(type) != type_size.end())
2718 return pet_expr_copy(type_size[type]);
2720 depth = pet_clang_array_depth(qt);
2721 inf = pet_expr_new_int(isl_val_infty(ctx));
2722 expr = pet_expr_new_call(ctx, "bounds", depth);
2723 for (int i = 0; i < depth; ++i)
2724 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2725 pet_expr_free(inf);
2727 expr = set_upper_bounds(expr, qt, 0);
2728 type_size[type] = pet_expr_copy(expr);
2729 id_size = isl_id_to_pet_expr_set(id_size, isl_id_copy(id),
2730 pet_expr_copy(expr));
2732 return expr;
2735 /* Set the array size of the array identified by "id" to "size",
2736 * replacing any previously stored value.
2738 void PetScan::set_array_size(__isl_take isl_id *id, __isl_take pet_expr *size)
2740 id_size = isl_id_to_pet_expr_set(id_size, id, size);
2743 /* Does "expr" represent the "integer" infinity?
2745 static int is_infty(__isl_keep pet_expr *expr)
2747 isl_val *v;
2748 int res;
2750 if (pet_expr_get_type(expr) != pet_expr_int)
2751 return 0;
2752 v = pet_expr_int_get_val(expr);
2753 res = isl_val_is_infty(v);
2754 isl_val_free(v);
2756 return res;
2759 /* Figure out the dimensions of an array "array" and
2760 * update "array" accordingly.
2762 * We first construct a pet_expr that holds the sizes of the array
2763 * in each dimension. The resulting expression may containing
2764 * infinity values for dimension where we are unable to derive
2765 * a size expression.
2767 * The arguments of the size expression that have a value different from
2768 * infinity are then converted to an affine expression
2769 * within the context "pc" and incorporated into the size of "array".
2770 * If we are unable to convert a size expression to an affine expression or
2771 * if the size is not a (symbolic) constant,
2772 * then we leave the corresponding size of "array" untouched.
2774 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2775 __isl_keep pet_context *pc)
2777 int n;
2778 isl_id *id;
2779 pet_expr *expr;
2781 if (!array)
2782 return NULL;
2784 id = isl_set_get_tuple_id(array->extent);
2785 expr = get_array_size(id);
2786 isl_id_free(id);
2788 n = pet_expr_get_n_arg(expr);
2789 for (int i = 0; i < n; ++i) {
2790 pet_expr *arg;
2791 isl_pw_aff *size;
2793 arg = pet_expr_get_arg(expr, i);
2794 if (!is_infty(arg)) {
2795 int dim;
2797 size = pet_expr_extract_affine(arg, pc);
2798 dim = isl_pw_aff_dim(size, isl_dim_in);
2799 if (!size)
2800 array = pet_array_free(array);
2801 else if (isl_pw_aff_involves_nan(size) ||
2802 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2803 isl_pw_aff_free(size);
2804 else {
2805 size = isl_pw_aff_drop_dims(size,
2806 isl_dim_in, 0, dim);
2807 array = update_size(array, i, size);
2810 pet_expr_free(arg);
2812 pet_expr_free(expr);
2814 return array;
2817 /* Does "decl" have a definition that we can keep track of in a pet_type?
2819 static bool has_printable_definition(RecordDecl *decl)
2821 if (!decl->getDeclName())
2822 return false;
2823 return decl->getLexicalDeclContext() == decl->getDeclContext();
2826 /* Add all TypedefType objects that appear when dereferencing "type"
2827 * to "types".
2829 static void insert_intermediate_typedefs(PetTypes *types, QualType type)
2831 type = pet_clang_base_or_typedef_type(type);
2832 while (isa<TypedefType>(type)) {
2833 const TypedefType *tt;
2835 tt = cast<TypedefType>(type);
2836 types->insert(tt->getDecl());
2837 type = tt->desugar();
2838 type = pet_clang_base_or_typedef_type(type);
2842 /* Construct and return a pet_array corresponding to the variable
2843 * represented by "id".
2844 * In particular, initialize array->extent to
2846 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2848 * and then call set_upper_bounds to set the upper bounds on the indices
2849 * based on the type of the variable. The upper bounds are converted
2850 * to affine expressions within the context "pc".
2852 * If the base type is that of a record with a top-level definition or
2853 * of a typedef and if "types" is not null, then the RecordDecl or
2854 * TypedefType corresponding to the type, as well as any intermediate
2855 * TypedefType, is added to "types".
2857 * If the base type is that of a record with no top-level definition,
2858 * then we replace it by "<subfield>".
2860 * If the variable is a scalar, i.e., a zero-dimensional array,
2861 * then the "const" qualifier, if any, is removed from the base type.
2862 * This makes it easier for users of pet to turn initializations
2863 * into assignments.
2865 struct pet_array *PetScan::extract_array(__isl_keep isl_id *id,
2866 PetTypes *types, __isl_keep pet_context *pc)
2868 struct pet_array *array;
2869 QualType qt = pet_id_get_array_type(id);
2870 int depth = pet_clang_array_depth(qt);
2871 QualType base = pet_clang_base_type(qt);
2872 string name;
2873 isl_space *space;
2875 array = isl_calloc_type(ctx, struct pet_array);
2876 if (!array)
2877 return NULL;
2879 space = isl_space_set_alloc(ctx, 0, depth);
2880 space = isl_space_set_tuple_id(space, isl_dim_set, isl_id_copy(id));
2882 array->extent = isl_set_nat_universe(space);
2884 space = isl_space_params_alloc(ctx, 0);
2885 array->context = isl_set_universe(space);
2887 array = set_upper_bounds(array, pc);
2888 if (!array)
2889 return NULL;
2891 if (depth == 0)
2892 base.removeLocalConst();
2893 name = base.getAsString();
2895 if (types) {
2896 insert_intermediate_typedefs(types, qt);
2897 if (isa<TypedefType>(base)) {
2898 types->insert(cast<TypedefType>(base)->getDecl());
2899 } else if (base->isRecordType()) {
2900 RecordDecl *decl = pet_clang_record_decl(base);
2901 TypedefNameDecl *typedecl;
2902 typedecl = decl->getTypedefNameForAnonDecl();
2903 if (typedecl)
2904 types->insert(typedecl);
2905 else if (has_printable_definition(decl))
2906 types->insert(decl);
2907 else
2908 name = "<subfield>";
2912 array->element_type = strdup(name.c_str());
2913 array->element_is_record = base->isRecordType();
2914 array->element_size = size_in_bytes(ast_context, base);
2916 return array;
2919 /* Construct and return a pet_array corresponding to the variable "decl".
2921 struct pet_array *PetScan::extract_array(ValueDecl *decl,
2922 PetTypes *types, __isl_keep pet_context *pc)
2924 isl_id *id;
2925 pet_array *array;
2927 id = pet_id_from_decl(ctx, decl);
2928 array = extract_array(id, types, pc);
2929 isl_id_free(id);
2931 return array;
2934 /* Construct and return a pet_array corresponding to the sequence
2935 * of declarations represented by "decls".
2936 * The upper bounds of the array are converted to affine expressions
2937 * within the context "pc".
2938 * If the sequence contains a single declaration, then it corresponds
2939 * to a simple array access. Otherwise, it corresponds to a member access,
2940 * with the declaration for the substructure following that of the containing
2941 * structure in the sequence of declarations.
2942 * We start with the outermost substructure and then combine it with
2943 * information from the inner structures.
2945 * Additionally, keep track of all required types in "types".
2947 struct pet_array *PetScan::extract_array(__isl_keep isl_id_list *decls,
2948 PetTypes *types, __isl_keep pet_context *pc)
2950 int i, n;
2951 isl_id *id;
2952 struct pet_array *array;
2954 id = isl_id_list_get_id(decls, 0);
2955 array = extract_array(id, types, pc);
2956 isl_id_free(id);
2958 n = isl_id_list_n_id(decls);
2959 for (i = 1; i < n; ++i) {
2960 struct pet_array *parent;
2961 const char *base_name, *field_name;
2962 char *product_name;
2964 parent = array;
2965 id = isl_id_list_get_id(decls, i);
2966 array = extract_array(id, types, pc);
2967 isl_id_free(id);
2968 if (!array)
2969 return pet_array_free(parent);
2971 base_name = isl_set_get_tuple_name(parent->extent);
2972 field_name = isl_set_get_tuple_name(array->extent);
2973 product_name = pet_array_member_access_name(ctx,
2974 base_name, field_name);
2976 array->extent = isl_set_product(isl_set_copy(parent->extent),
2977 array->extent);
2978 if (product_name)
2979 array->extent = isl_set_set_tuple_name(array->extent,
2980 product_name);
2981 array->context = isl_set_intersect(array->context,
2982 isl_set_copy(parent->context));
2984 pet_array_free(parent);
2985 free(product_name);
2987 if (!array->extent || !array->context || !product_name)
2988 return pet_array_free(array);
2991 return array;
2994 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2995 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2996 std::set<TypeDecl *> &types_done);
2997 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2998 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2999 std::set<TypeDecl *> &types_done);
3001 /* For each of the fields of "decl" that is itself a record type
3002 * or a typedef, or an array of such type, add a corresponding pet_type
3003 * to "scop".
3005 static struct pet_scop *add_field_types(isl_ctx *ctx, struct pet_scop *scop,
3006 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
3007 std::set<TypeDecl *> &types_done)
3009 RecordDecl::field_iterator it;
3011 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
3012 QualType type = it->getType();
3014 type = pet_clang_base_or_typedef_type(type);
3015 if (isa<TypedefType>(type)) {
3016 TypedefNameDecl *typedefdecl;
3018 typedefdecl = cast<TypedefType>(type)->getDecl();
3019 scop = add_type(ctx, scop, typedefdecl,
3020 PP, types, types_done);
3021 } else if (type->isRecordType()) {
3022 RecordDecl *record;
3024 record = pet_clang_record_decl(type);
3025 scop = add_type(ctx, scop, record,
3026 PP, types, types_done);
3030 return scop;
3033 /* Add a pet_type corresponding to "decl" to "scop", provided
3034 * it is a member of types.records and it has not been added before
3035 * (i.e., it is not a member of "types_done").
3037 * Since we want the user to be able to print the types
3038 * in the order in which they appear in the scop, we need to
3039 * make sure that types of fields in a structure appear before
3040 * that structure. We therefore call ourselves recursively
3041 * through add_field_types on the types of all record subfields.
3043 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3044 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
3045 std::set<TypeDecl *> &types_done)
3047 string s;
3048 llvm::raw_string_ostream S(s);
3050 if (types.records.find(decl) == types.records.end())
3051 return scop;
3052 if (types_done.find(decl) != types_done.end())
3053 return scop;
3055 add_field_types(ctx, scop, decl, PP, types, types_done);
3057 if (strlen(decl->getName().str().c_str()) == 0)
3058 return scop;
3060 decl->print(S, PrintingPolicy(PP.getLangOpts()));
3061 S.str();
3063 scop->types[scop->n_type] = pet_type_alloc(ctx,
3064 decl->getName().str().c_str(), s.c_str());
3065 if (!scop->types[scop->n_type])
3066 return pet_scop_free(scop);
3068 types_done.insert(decl);
3070 scop->n_type++;
3072 return scop;
3075 /* Add a pet_type corresponding to "decl" to "scop", provided
3076 * it is a member of types.typedefs and it has not been added before
3077 * (i.e., it is not a member of "types_done").
3079 * If the underlying type is a structure, then we print the typedef
3080 * ourselves since clang does not print the definition of the structure
3081 * in the typedef. We also make sure in this case that the types of
3082 * the fields in the structure are added first.
3083 * Since the definition of the structure also gets printed this way,
3084 * add it to types_done such that it will not be printed again,
3085 * not even without the typedef.
3087 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3088 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
3089 std::set<TypeDecl *> &types_done)
3091 string s;
3092 llvm::raw_string_ostream S(s);
3093 QualType qt = decl->getUnderlyingType();
3095 if (types.typedefs.find(decl) == types.typedefs.end())
3096 return scop;
3097 if (types_done.find(decl) != types_done.end())
3098 return scop;
3100 if (qt->isRecordType()) {
3101 RecordDecl *rec = pet_clang_record_decl(qt);
3103 add_field_types(ctx, scop, rec, PP, types, types_done);
3104 S << "typedef ";
3105 rec->print(S, PrintingPolicy(PP.getLangOpts()));
3106 S << " ";
3107 S << decl->getName();
3108 types_done.insert(rec);
3109 } else {
3110 decl->print(S, PrintingPolicy(PP.getLangOpts()));
3112 S.str();
3114 scop->types[scop->n_type] = pet_type_alloc(ctx,
3115 decl->getName().str().c_str(), s.c_str());
3116 if (!scop->types[scop->n_type])
3117 return pet_scop_free(scop);
3119 types_done.insert(decl);
3121 scop->n_type++;
3123 return scop;
3126 /* Construct a list of pet_arrays, one for each array (or scalar)
3127 * accessed inside "scop", add this list to "scop" and return the result.
3128 * The upper bounds of the arrays are converted to affine expressions
3129 * within the context "pc".
3131 * The context of "scop" is updated with the intersection of
3132 * the contexts of all arrays, i.e., constraints on the parameters
3133 * that ensure that the arrays have a valid (non-negative) size.
3135 * If any of the extracted arrays refers to a member access or
3136 * has a typedef'd type as base type,
3137 * then also add the required types to "scop".
3138 * The typedef types are printed first because their definitions
3139 * may include the definition of a struct and these struct definitions
3140 * should not be printed separately. While the typedef definition
3141 * is being printed, the struct is marked as having been printed as well,
3142 * such that the later printing of the struct by itself can be prevented.
3144 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
3145 __isl_keep pet_context *pc)
3147 int i, n;
3148 array_desc_set arrays;
3149 array_desc_set::iterator it;
3150 PetTypes types;
3151 std::set<TypeDecl *> types_done;
3152 std::set<clang::RecordDecl *, less_name>::iterator records_it;
3153 std::set<clang::TypedefNameDecl *, less_name>::iterator typedefs_it;
3154 int n_array;
3155 struct pet_array **scop_arrays;
3157 if (!scop)
3158 return NULL;
3160 pet_scop_collect_arrays(scop, arrays);
3161 if (arrays.size() == 0)
3162 return scop;
3164 n_array = scop->n_array;
3166 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3167 n_array + arrays.size());
3168 if (!scop_arrays)
3169 goto error;
3170 scop->arrays = scop_arrays;
3172 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3173 struct pet_array *array;
3174 array = extract_array(*it, &types, pc);
3175 scop->arrays[n_array + i] = array;
3176 if (!scop->arrays[n_array + i])
3177 goto error;
3178 scop->n_array++;
3179 scop->context = isl_set_intersect(scop->context,
3180 isl_set_copy(array->context));
3181 if (!scop->context)
3182 goto error;
3185 n = types.records.size() + types.typedefs.size();
3186 if (n == 0)
3187 return scop;
3189 scop->types = isl_alloc_array(ctx, struct pet_type *, n);
3190 if (!scop->types)
3191 goto error;
3193 for (typedefs_it = types.typedefs.begin();
3194 typedefs_it != types.typedefs.end(); ++typedefs_it)
3195 scop = add_type(ctx, scop, *typedefs_it, PP, types, types_done);
3197 for (records_it = types.records.begin();
3198 records_it != types.records.end(); ++records_it)
3199 scop = add_type(ctx, scop, *records_it, PP, types, types_done);
3201 return scop;
3202 error:
3203 pet_scop_free(scop);
3204 return NULL;
3207 /* Bound all parameters in scop->context to the possible values
3208 * of the corresponding C variable.
3210 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
3212 int n;
3214 if (!scop)
3215 return NULL;
3217 n = isl_set_dim(scop->context, isl_dim_param);
3218 for (int i = 0; i < n; ++i) {
3219 isl_id *id;
3220 ValueDecl *decl;
3222 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
3223 if (pet_nested_in_id(id)) {
3224 isl_id_free(id);
3225 isl_die(isl_set_get_ctx(scop->context),
3226 isl_error_internal,
3227 "unresolved nested parameter", goto error);
3229 decl = pet_id_get_decl(id);
3230 isl_id_free(id);
3232 scop->context = set_parameter_bounds(scop->context, i, decl);
3234 if (!scop->context)
3235 goto error;
3238 return scop;
3239 error:
3240 pet_scop_free(scop);
3241 return NULL;
3244 /* Construct a pet_scop from the given function.
3246 * If the scop was delimited by scop and endscop pragmas, then we override
3247 * the file offsets by those derived from the pragmas.
3249 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3251 pet_scop *scop;
3252 Stmt *stmt;
3254 stmt = fd->getBody();
3256 if (options->autodetect) {
3257 set_current_stmt(stmt);
3258 scop = extract_scop(extract(stmt, true));
3259 } else {
3260 current_line = loc.start_line;
3261 scop = scan(stmt);
3262 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
3264 scop = add_parameter_bounds(scop);
3265 scop = pet_scop_gist(scop, value_bounds);
3267 return scop;
3270 /* Update this->last_line and this->current_line based on the fact
3271 * that we are about to consider "stmt".
3273 void PetScan::set_current_stmt(Stmt *stmt)
3275 SourceLocation loc = stmt->getLocStart();
3276 SourceManager &SM = PP.getSourceManager();
3278 last_line = current_line;
3279 current_line = SM.getExpansionLineNumber(loc);
3282 /* Is the current statement marked by an independent pragma?
3283 * That is, is there an independent pragma on a line between
3284 * the line of the current statement and the line of the previous statement.
3285 * The search is not implemented very efficiently. We currently
3286 * assume that there are only a few independent pragmas, if any.
3288 bool PetScan::is_current_stmt_marked_independent()
3290 for (unsigned i = 0; i < independent.size(); ++i) {
3291 unsigned line = independent[i].line;
3293 if (last_line < line && line < current_line)
3294 return true;
3297 return false;