remove "const" qualifier from the type of a scalar
[pet.git] / scan.cc
blob2ebf6a89ef54dd9ee681265f5dcc7dca8a3201bc
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_union_map_free(value_bounds);
222 /* Report a diagnostic on the range "range", unless autodetect is set.
224 void PetScan::report(SourceRange range, unsigned id)
226 if (options->autodetect)
227 return;
229 SourceLocation loc = range.getBegin();
230 DiagnosticsEngine &diag = PP.getDiagnostics();
231 DiagnosticBuilder B = diag.Report(loc, id) << range;
234 /* Report a diagnostic on "stmt", unless autodetect is set.
236 void PetScan::report(Stmt *stmt, unsigned id)
238 report(stmt->getSourceRange(), id);
241 /* Report a diagnostic on "decl", unless autodetect is set.
243 void PetScan::report(Decl *decl, unsigned id)
245 report(decl->getSourceRange(), id);
248 /* Called if we found something we (currently) cannot handle.
249 * We'll provide more informative warnings later.
251 * We only actually complain if autodetect is false.
253 void PetScan::unsupported(Stmt *stmt)
255 DiagnosticsEngine &diag = PP.getDiagnostics();
256 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
257 "unsupported");
258 report(stmt, id);
261 /* Report an unsupported unary operator, unless autodetect is set.
263 void PetScan::report_unsupported_unary_operator(Stmt *stmt)
265 DiagnosticsEngine &diag = PP.getDiagnostics();
266 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
267 "this type of unary operator is not supported");
268 report(stmt, id);
271 /* Report an unsupported statement type, unless autodetect is set.
273 void PetScan::report_unsupported_statement_type(Stmt *stmt)
275 DiagnosticsEngine &diag = PP.getDiagnostics();
276 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
277 "this type of statement is not supported");
278 report(stmt, id);
281 /* Report a missing prototype, unless autodetect is set.
283 void PetScan::report_prototype_required(Stmt *stmt)
285 DiagnosticsEngine &diag = PP.getDiagnostics();
286 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
287 "prototype required");
288 report(stmt, id);
291 /* Report a missing increment, unless autodetect is set.
293 void PetScan::report_missing_increment(Stmt *stmt)
295 DiagnosticsEngine &diag = PP.getDiagnostics();
296 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
297 "missing increment");
298 report(stmt, id);
301 /* Report a missing summary function, unless autodetect is set.
303 void PetScan::report_missing_summary_function(Stmt *stmt)
305 DiagnosticsEngine &diag = PP.getDiagnostics();
306 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
307 "missing summary function");
308 report(stmt, id);
311 /* Report a missing summary function body, unless autodetect is set.
313 void PetScan::report_missing_summary_function_body(Stmt *stmt)
315 DiagnosticsEngine &diag = PP.getDiagnostics();
316 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
317 "missing summary function body");
318 report(stmt, id);
321 /* Report an unsupported argument in a call to an inlined function,
322 * unless autodetect is set.
324 void PetScan::report_unsupported_inline_function_argument(Stmt *stmt)
326 DiagnosticsEngine &diag = PP.getDiagnostics();
327 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
328 "unsupported inline function call argument");
329 report(stmt, id);
332 /* Report an unsupported type of declaration, unless autodetect is set.
334 void PetScan::report_unsupported_declaration(Decl *decl)
336 DiagnosticsEngine &diag = PP.getDiagnostics();
337 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
338 "unsupported declaration");
339 report(decl, id);
342 /* Extract an integer from "val", which is assumed to be non-negative.
344 static __isl_give isl_val *extract_unsigned(isl_ctx *ctx,
345 const llvm::APInt &val)
347 unsigned n;
348 const uint64_t *data;
350 data = val.getRawData();
351 n = val.getNumWords();
352 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
355 /* Extract an integer from "val". If "is_signed" is set, then "val"
356 * is signed. Otherwise it it unsigned.
358 static __isl_give isl_val *extract_int(isl_ctx *ctx, bool is_signed,
359 llvm::APInt val)
361 int is_negative = is_signed && val.isNegative();
362 isl_val *v;
364 if (is_negative)
365 val = -val;
367 v = extract_unsigned(ctx, val);
369 if (is_negative)
370 v = isl_val_neg(v);
371 return v;
374 /* Extract an integer from "expr".
376 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
378 const Type *type = expr->getType().getTypePtr();
379 bool is_signed = type->hasSignedIntegerRepresentation();
381 return ::extract_int(ctx, is_signed, expr->getValue());
384 /* Extract an integer from "expr".
385 * Return NULL if "expr" does not (obviously) represent an integer.
387 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
389 return extract_int(expr->getSubExpr());
392 /* Extract an integer from "expr".
393 * Return NULL if "expr" does not (obviously) represent an integer.
395 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
397 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
398 return extract_int(ctx, cast<IntegerLiteral>(expr));
399 if (expr->getStmtClass() == Stmt::ParenExprClass)
400 return extract_int(cast<ParenExpr>(expr));
402 unsupported(expr);
403 return NULL;
406 /* Extract a pet_expr from the APInt "val", which is assumed
407 * to be non-negative.
409 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
411 return pet_expr_new_int(extract_unsigned(ctx, val));
414 /* Return the number of bits needed to represent the type of "decl",
415 * if it is an integer type. Otherwise return 0.
416 * If qt is signed then return the opposite of the number of bits.
418 static int get_type_size(ValueDecl *decl)
420 return pet_clang_get_type_size(decl->getType(), decl->getASTContext());
423 /* Bound parameter "pos" of "set" to the possible values of "decl".
425 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
426 unsigned pos, ValueDecl *decl)
428 int type_size;
429 isl_ctx *ctx;
430 isl_val *bound;
432 ctx = isl_set_get_ctx(set);
433 type_size = get_type_size(decl);
434 if (type_size == 0)
435 isl_die(ctx, isl_error_invalid, "not an integer type",
436 return isl_set_free(set));
437 if (type_size > 0) {
438 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
439 bound = isl_val_int_from_ui(ctx, type_size);
440 bound = isl_val_2exp(bound);
441 bound = isl_val_sub_ui(bound, 1);
442 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
443 } else {
444 bound = isl_val_int_from_ui(ctx, -type_size - 1);
445 bound = isl_val_2exp(bound);
446 bound = isl_val_sub_ui(bound, 1);
447 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
448 isl_val_copy(bound));
449 bound = isl_val_neg(bound);
450 bound = isl_val_sub_ui(bound, 1);
451 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
454 return set;
457 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
459 return extract_index_expr(expr->getSubExpr());
462 /* Return the depth of the array accessed by the index expression "index".
463 * If "index" is an affine expression, i.e., if it does not access
464 * any array, then return 1.
465 * If "index" represent a member access, i.e., if its range is a wrapped
466 * relation, then return the sum of the depth of the array of structures
467 * and that of the member inside the structure.
469 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
471 isl_id *id;
472 ValueDecl *decl;
474 if (!index)
475 return -1;
477 if (isl_multi_pw_aff_range_is_wrapping(index)) {
478 int domain_depth, range_depth;
479 isl_multi_pw_aff *domain, *range;
481 domain = isl_multi_pw_aff_copy(index);
482 domain = isl_multi_pw_aff_range_factor_domain(domain);
483 domain_depth = extract_depth(domain);
484 isl_multi_pw_aff_free(domain);
485 range = isl_multi_pw_aff_copy(index);
486 range = isl_multi_pw_aff_range_factor_range(range);
487 range_depth = extract_depth(range);
488 isl_multi_pw_aff_free(range);
490 return domain_depth + range_depth;
493 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
494 return 1;
496 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
497 if (!id)
498 return -1;
499 decl = pet_id_get_decl(id);
500 isl_id_free(id);
502 return pet_clang_array_depth(decl->getType());
505 /* Return the depth of the array accessed by the access expression "expr".
507 static int extract_depth(__isl_keep pet_expr *expr)
509 isl_multi_pw_aff *index;
510 int depth;
512 index = pet_expr_access_get_index(expr);
513 depth = extract_depth(index);
514 isl_multi_pw_aff_free(index);
516 return depth;
519 /* Construct a pet_expr representing an index expression for an access
520 * to the variable referenced by "expr".
522 * If "expr" references an enum constant, then return an integer expression
523 * instead, representing the value of the enum constant.
525 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
527 return extract_index_expr(expr->getDecl());
530 /* Construct a pet_expr representing an index expression for an access
531 * to the variable "decl".
533 * If "decl" is an enum constant, then we return an integer expression
534 * instead, representing the value of the enum constant.
536 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
538 isl_id *id;
540 if (isa<EnumConstantDecl>(decl))
541 return extract_expr(cast<EnumConstantDecl>(decl));
543 id = pet_id_from_decl(ctx, decl);
544 return pet_id_create_index_expr(id);
547 /* Construct a pet_expr representing the index expression "expr"
548 * Return NULL on error.
550 * If "expr" is a reference to an enum constant, then return
551 * an integer expression instead, representing the value of the enum constant.
553 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
555 switch (expr->getStmtClass()) {
556 case Stmt::ImplicitCastExprClass:
557 return extract_index_expr(cast<ImplicitCastExpr>(expr));
558 case Stmt::DeclRefExprClass:
559 return extract_index_expr(cast<DeclRefExpr>(expr));
560 case Stmt::ArraySubscriptExprClass:
561 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
562 case Stmt::IntegerLiteralClass:
563 return extract_expr(cast<IntegerLiteral>(expr));
564 case Stmt::MemberExprClass:
565 return extract_index_expr(cast<MemberExpr>(expr));
566 default:
567 unsupported(expr);
569 return NULL;
572 /* Extract an index expression from the given array subscript expression.
574 * We first extract an index expression from the base.
575 * This will result in an index expression with a range that corresponds
576 * to the earlier indices.
577 * We then extract the current index and let
578 * pet_expr_access_subscript combine the two.
580 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
582 Expr *base = expr->getBase();
583 Expr *idx = expr->getIdx();
584 pet_expr *index;
585 pet_expr *base_expr;
587 base_expr = extract_index_expr(base);
588 index = extract_expr(idx);
590 base_expr = pet_expr_access_subscript(base_expr, index);
592 return base_expr;
595 /* Extract an index expression from a member expression.
597 * If the base access (to the structure containing the member)
598 * is of the form
600 * A[..]
602 * and the member is called "f", then the member access is of
603 * the form
605 * A_f[A[..] -> f[]]
607 * If the member access is to an anonymous struct, then simply return
609 * A[..]
611 * If the member access in the source code is of the form
613 * A->f
615 * then it is treated as
617 * A[0].f
619 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
621 Expr *base = expr->getBase();
622 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
623 pet_expr *base_index;
624 isl_id *id;
626 base_index = extract_index_expr(base);
628 if (expr->isArrow()) {
629 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
630 base_index = pet_expr_access_subscript(base_index, index);
633 if (field->isAnonymousStructOrUnion())
634 return base_index;
636 id = pet_id_from_decl(ctx, field);
638 return pet_expr_access_member(base_index, id);
641 /* Mark the given access pet_expr as a write.
643 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
645 access = pet_expr_access_set_write(access, 1);
646 access = pet_expr_access_set_read(access, 0);
648 return access;
651 /* Mark the given (read) access pet_expr as also possibly being written.
652 * That is, initialize the may write access relation from the may read relation
653 * and initialize the must write access relation to the empty relation.
655 static __isl_give pet_expr *mark_may_write(__isl_take pet_expr *expr)
657 isl_union_map *access;
658 isl_union_map *empty;
660 access = pet_expr_access_get_dependent_access(expr,
661 pet_expr_access_may_read);
662 empty = isl_union_map_empty(isl_union_map_get_space(access));
663 expr = pet_expr_access_set_access(expr, pet_expr_access_may_write,
664 access);
665 expr = pet_expr_access_set_access(expr, pet_expr_access_must_write,
666 empty);
668 return expr;
671 /* Construct a pet_expr representing a unary operator expression.
673 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
675 int type_size;
676 pet_expr *arg;
677 enum pet_op_type op;
679 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
680 if (op == pet_op_last) {
681 report_unsupported_unary_operator(expr);
682 return NULL;
685 arg = extract_expr(expr->getSubExpr());
687 if (expr->isIncrementDecrementOp() &&
688 pet_expr_get_type(arg) == pet_expr_access) {
689 arg = mark_write(arg);
690 arg = pet_expr_access_set_read(arg, 1);
693 type_size = pet_clang_get_type_size(expr->getType(), ast_context);
694 return pet_expr_new_unary(type_size, op, arg);
697 /* Construct a pet_expr representing a binary operator expression.
699 * If the top level operator is an assignment and the LHS is an access,
700 * then we mark that access as a write. If the operator is a compound
701 * assignment, the access is marked as both a read and a write.
703 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
705 int type_size;
706 pet_expr *lhs, *rhs;
707 enum pet_op_type op;
709 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
710 if (op == pet_op_last) {
711 unsupported(expr);
712 return NULL;
715 lhs = extract_expr(expr->getLHS());
716 rhs = extract_expr(expr->getRHS());
718 if (expr->isAssignmentOp() &&
719 pet_expr_get_type(lhs) == pet_expr_access) {
720 lhs = mark_write(lhs);
721 if (expr->isCompoundAssignmentOp())
722 lhs = pet_expr_access_set_read(lhs, 1);
725 type_size = pet_clang_get_type_size(expr->getType(), ast_context);
726 return pet_expr_new_binary(type_size, op, lhs, rhs);
729 /* Construct a pet_tree for a variable declaration and
730 * add the declaration to the list of declarations
731 * inside the current compound statement.
733 __isl_give pet_tree *PetScan::extract(Decl *decl)
735 VarDecl *vd;
736 pet_expr *lhs, *rhs;
737 pet_tree *tree;
739 if (!isa<VarDecl>(decl)) {
740 report_unsupported_declaration(decl);
741 return NULL;
744 vd = cast<VarDecl>(decl);
745 declarations.push_back(vd);
747 lhs = extract_access_expr(vd);
748 lhs = mark_write(lhs);
749 if (!vd->getInit())
750 tree = pet_tree_new_decl(lhs);
751 else {
752 rhs = extract_expr(vd->getInit());
753 tree = pet_tree_new_decl_init(lhs, rhs);
756 return tree;
759 /* Construct a pet_tree for a variable declaration statement.
760 * If the declaration statement declares multiple variables,
761 * then return a group of pet_trees, one for each declared variable.
763 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
765 pet_tree *tree;
766 unsigned n;
768 if (!stmt->isSingleDecl()) {
769 const DeclGroup &group = stmt->getDeclGroup().getDeclGroup();
770 n = group.size();
771 tree = pet_tree_new_block(ctx, 0, n);
773 for (unsigned i = 0; i < n; ++i) {
774 pet_tree *tree_i;
775 pet_loc *loc;
777 tree_i = extract(group[i]);
778 loc = construct_pet_loc(group[i]->getSourceRange(),
779 false);
780 tree_i = pet_tree_set_loc(tree_i, loc);
781 tree = pet_tree_block_add_child(tree, tree_i);
784 return tree;
787 return extract(stmt->getSingleDecl());
790 /* Construct a pet_expr representing a conditional operation.
792 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
794 pet_expr *cond, *lhs, *rhs;
796 cond = extract_expr(expr->getCond());
797 lhs = extract_expr(expr->getTrueExpr());
798 rhs = extract_expr(expr->getFalseExpr());
800 return pet_expr_new_ternary(cond, lhs, rhs);
803 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
805 return extract_expr(expr->getSubExpr());
808 /* Construct a pet_expr representing a floating point value.
810 * If the floating point literal does not appear in a macro,
811 * then we use the original representation in the source code
812 * as the string representation. Otherwise, we use the pretty
813 * printer to produce a string representation.
815 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
817 double d;
818 string s;
819 const LangOptions &LO = PP.getLangOpts();
820 SourceLocation loc = expr->getLocation();
822 if (!loc.isMacroID()) {
823 SourceManager &SM = PP.getSourceManager();
824 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
825 s = string(SM.getCharacterData(loc), len);
826 } else {
827 llvm::raw_string_ostream S(s);
828 expr->printPretty(S, 0, PrintingPolicy(LO));
829 S.str();
831 d = expr->getValueAsApproximateDouble();
832 return pet_expr_new_double(ctx, d, s.c_str());
835 /* Convert the index expression "index" into an access pet_expr of type "qt".
837 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
838 __isl_take pet_expr *index)
840 int depth;
841 int type_size;
843 depth = extract_depth(index);
844 type_size = pet_clang_get_type_size(qt, ast_context);
846 index = pet_expr_set_type_size(index, type_size);
847 index = pet_expr_access_set_depth(index, depth);
849 return index;
852 /* Extract an index expression from "expr" and then convert it into
853 * an access pet_expr.
855 * If "expr" is a reference to an enum constant, then return
856 * an integer expression instead, representing the value of the enum constant.
858 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
860 pet_expr *index;
862 index = extract_index_expr(expr);
864 if (pet_expr_get_type(index) == pet_expr_int)
865 return index;
867 return extract_access_expr(expr->getType(), index);
870 /* Extract an index expression from "decl" and then convert it into
871 * an access pet_expr.
873 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
875 return extract_access_expr(decl->getType(), extract_index_expr(decl));
878 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
880 return extract_expr(expr->getSubExpr());
883 /* Extract an assume statement from the argument "expr"
884 * of a __pencil_assume statement.
886 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
888 return pet_expr_new_unary(0, pet_op_assume, extract_expr(expr));
891 /* If "expr" is an address-of operator, then return its argument.
892 * Otherwise, return NULL.
894 static Expr *extract_addr_of_arg(Expr *expr)
896 UnaryOperator *op;
898 if (expr->getStmtClass() != Stmt::UnaryOperatorClass)
899 return NULL;
900 op = cast<UnaryOperator>(expr);
901 if (op->getOpcode() != UO_AddrOf)
902 return NULL;
903 return op->getSubExpr();
906 /* Construct a pet_expr corresponding to the function call argument "expr".
907 * The argument appears in position "pos" of a call to function "fd".
909 * If we are passing along a pointer to an array element
910 * or an entire row or even higher dimensional slice of an array,
911 * then the function being called may write into the array.
913 * We assume here that if the function is declared to take a pointer
914 * to a const type, then the function may only perform a read
915 * and that otherwise, it may either perform a read or a write (or both).
916 * We only perform this check if "detect_writes" is set.
918 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
919 Expr *expr, bool detect_writes)
921 Expr *arg;
922 pet_expr *res;
923 int is_addr = 0, is_partial = 0;
925 expr = pet_clang_strip_casts(expr);
926 arg = extract_addr_of_arg(expr);
927 if (arg) {
928 is_addr = 1;
929 expr = arg;
931 res = extract_expr(expr);
932 if (!res)
933 return NULL;
934 if (pet_clang_array_depth(expr->getType()) > 0)
935 is_partial = 1;
936 if (detect_writes && (is_addr || is_partial) &&
937 pet_expr_get_type(res) == pet_expr_access) {
938 ParmVarDecl *parm;
939 if (!fd->hasPrototype()) {
940 report_prototype_required(expr);
941 return pet_expr_free(res);
943 parm = fd->getParamDecl(pos);
944 if (!const_base(parm->getType()))
945 res = mark_may_write(res);
948 if (is_addr)
949 res = pet_expr_new_unary(0, pet_op_address_of, res);
950 return res;
953 /* Find the first FunctionDecl with the given name.
954 * "call" is the corresponding call expression and is only used
955 * for reporting errors.
957 * Return NULL on error.
959 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
961 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
962 DeclContext::decl_iterator begin = tu->decls_begin();
963 DeclContext::decl_iterator end = tu->decls_end();
964 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
965 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
966 if (!fd)
967 continue;
968 if (fd->getName().str().compare(name) != 0)
969 continue;
970 if (fd->hasBody())
971 return fd;
972 report_missing_summary_function_body(call);
973 return NULL;
975 report_missing_summary_function(call);
976 return NULL;
979 /* Return the FunctionDecl for the summary function associated to the
980 * function called by "call".
982 * In particular, if the pencil option is set, then
983 * search for an annotate attribute formatted as
984 * "pencil_access(name)", where "name" is the name of the summary function.
986 * If no summary function was specified, then return the FunctionDecl
987 * that is actually being called.
989 * Return NULL on error.
991 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
993 FunctionDecl *decl = call->getDirectCallee();
994 if (!decl)
995 return NULL;
997 if (!options->pencil)
998 return decl;
1000 specific_attr_iterator<AnnotateAttr> begin, end, i;
1001 begin = decl->specific_attr_begin<AnnotateAttr>();
1002 end = decl->specific_attr_end<AnnotateAttr>();
1003 for (i = begin; i != end; ++i) {
1004 string attr = (*i)->getAnnotation().str();
1006 const char prefix[] = "pencil_access(";
1007 size_t start = attr.find(prefix);
1008 if (start == string::npos)
1009 continue;
1010 start += strlen(prefix);
1011 string name = attr.substr(start, attr.find(')') - start);
1013 return find_decl_from_name(call, name);
1016 return decl;
1019 /* Construct a pet_expr representing a function call.
1021 * In the special case of a "call" to __pencil_assume,
1022 * construct an assume expression instead.
1024 * In the case of a "call" to __pencil_kill, the arguments
1025 * are neither read nor written (only killed), so there
1026 * is no need to check for writes to these arguments.
1028 * __pencil_assume and __pencil_kill are only recognized
1029 * when the pencil option is set.
1031 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1033 pet_expr *res = NULL;
1034 FunctionDecl *fd;
1035 string name;
1036 unsigned n_arg;
1037 bool is_kill;
1039 fd = expr->getDirectCallee();
1040 if (!fd) {
1041 unsupported(expr);
1042 return NULL;
1045 name = fd->getDeclName().getAsString();
1046 n_arg = expr->getNumArgs();
1048 if (options->pencil && n_arg == 1 && name == "__pencil_assume")
1049 return extract_assume(expr->getArg(0));
1050 is_kill = options->pencil && name == "__pencil_kill";
1052 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1053 if (!res)
1054 return NULL;
1056 for (unsigned i = 0; i < n_arg; ++i) {
1057 Expr *arg = expr->getArg(i);
1058 res = pet_expr_set_arg(res, i,
1059 PetScan::extract_argument(fd, i, arg, !is_kill));
1062 fd = get_summary_function(expr);
1063 if (!fd)
1064 return pet_expr_free(res);
1066 res = set_summary(res, fd);
1068 return res;
1071 /* Construct a pet_expr representing a (C style) cast.
1073 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1075 pet_expr *arg;
1076 QualType type;
1078 arg = extract_expr(expr->getSubExpr());
1079 if (!arg)
1080 return NULL;
1082 type = expr->getTypeAsWritten();
1083 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1086 /* Construct a pet_expr representing an integer.
1088 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1090 return pet_expr_new_int(extract_int(expr));
1093 /* Construct a pet_expr representing the integer enum constant "ecd".
1095 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
1097 isl_val *v;
1098 const llvm::APSInt &init = ecd->getInitVal();
1099 v = ::extract_int(ctx, init.isSigned(), init);
1100 return pet_expr_new_int(v);
1103 /* Try and construct a pet_expr representing "expr".
1105 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1107 switch (expr->getStmtClass()) {
1108 case Stmt::UnaryOperatorClass:
1109 return extract_expr(cast<UnaryOperator>(expr));
1110 case Stmt::CompoundAssignOperatorClass:
1111 case Stmt::BinaryOperatorClass:
1112 return extract_expr(cast<BinaryOperator>(expr));
1113 case Stmt::ImplicitCastExprClass:
1114 return extract_expr(cast<ImplicitCastExpr>(expr));
1115 case Stmt::ArraySubscriptExprClass:
1116 case Stmt::DeclRefExprClass:
1117 case Stmt::MemberExprClass:
1118 return extract_access_expr(expr);
1119 case Stmt::IntegerLiteralClass:
1120 return extract_expr(cast<IntegerLiteral>(expr));
1121 case Stmt::FloatingLiteralClass:
1122 return extract_expr(cast<FloatingLiteral>(expr));
1123 case Stmt::ParenExprClass:
1124 return extract_expr(cast<ParenExpr>(expr));
1125 case Stmt::ConditionalOperatorClass:
1126 return extract_expr(cast<ConditionalOperator>(expr));
1127 case Stmt::CallExprClass:
1128 return extract_expr(cast<CallExpr>(expr));
1129 case Stmt::CStyleCastExprClass:
1130 return extract_expr(cast<CStyleCastExpr>(expr));
1131 default:
1132 unsupported(expr);
1134 return NULL;
1137 /* Check if the given initialization statement is an assignment.
1138 * If so, return that assignment. Otherwise return NULL.
1140 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1142 BinaryOperator *ass;
1144 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1145 return NULL;
1147 ass = cast<BinaryOperator>(init);
1148 if (ass->getOpcode() != BO_Assign)
1149 return NULL;
1151 return ass;
1154 /* Check if the given initialization statement is a declaration
1155 * of a single variable.
1156 * If so, return that declaration. Otherwise return NULL.
1158 Decl *PetScan::initialization_declaration(Stmt *init)
1160 DeclStmt *decl;
1162 if (init->getStmtClass() != Stmt::DeclStmtClass)
1163 return NULL;
1165 decl = cast<DeclStmt>(init);
1167 if (!decl->isSingleDecl())
1168 return NULL;
1170 return decl->getSingleDecl();
1173 /* Given the assignment operator in the initialization of a for loop,
1174 * extract the induction variable, i.e., the (integer)variable being
1175 * assigned.
1177 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1179 Expr *lhs;
1180 DeclRefExpr *ref;
1181 ValueDecl *decl;
1182 const Type *type;
1184 lhs = init->getLHS();
1185 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1186 unsupported(init);
1187 return NULL;
1190 ref = cast<DeclRefExpr>(lhs);
1191 decl = ref->getDecl();
1192 type = decl->getType().getTypePtr();
1194 if (!type->isIntegerType()) {
1195 unsupported(lhs);
1196 return NULL;
1199 return decl;
1202 /* Given the initialization statement of a for loop and the single
1203 * declaration in this initialization statement,
1204 * extract the induction variable, i.e., the (integer) variable being
1205 * declared.
1207 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1209 VarDecl *vd;
1211 vd = cast<VarDecl>(decl);
1213 const QualType type = vd->getType();
1214 if (!type->isIntegerType()) {
1215 unsupported(init);
1216 return NULL;
1219 if (!vd->getInit()) {
1220 unsupported(init);
1221 return NULL;
1224 return vd;
1227 /* Check that op is of the form iv++ or iv--.
1228 * Return a pet_expr representing "1" or "-1" accordingly.
1230 __isl_give pet_expr *PetScan::extract_unary_increment(
1231 clang::UnaryOperator *op, clang::ValueDecl *iv)
1233 Expr *sub;
1234 DeclRefExpr *ref;
1235 isl_val *v;
1237 if (!op->isIncrementDecrementOp()) {
1238 unsupported(op);
1239 return NULL;
1242 sub = op->getSubExpr();
1243 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1244 unsupported(op);
1245 return NULL;
1248 ref = cast<DeclRefExpr>(sub);
1249 if (ref->getDecl() != iv) {
1250 unsupported(op);
1251 return NULL;
1254 if (op->isIncrementOp())
1255 v = isl_val_one(ctx);
1256 else
1257 v = isl_val_negone(ctx);
1259 return pet_expr_new_int(v);
1262 /* Check if op is of the form
1264 * iv = expr
1266 * and return the increment "expr - iv" as a pet_expr.
1268 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1269 clang::ValueDecl *iv)
1271 int type_size;
1272 Expr *lhs;
1273 DeclRefExpr *ref;
1274 pet_expr *expr, *expr_iv;
1276 if (op->getOpcode() != BO_Assign) {
1277 unsupported(op);
1278 return NULL;
1281 lhs = op->getLHS();
1282 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1283 unsupported(op);
1284 return NULL;
1287 ref = cast<DeclRefExpr>(lhs);
1288 if (ref->getDecl() != iv) {
1289 unsupported(op);
1290 return NULL;
1293 expr = extract_expr(op->getRHS());
1294 expr_iv = extract_expr(lhs);
1296 type_size = pet_clang_get_type_size(iv->getType(), ast_context);
1297 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1300 /* Check that op is of the form iv += cst or iv -= cst
1301 * and return a pet_expr corresponding to cst or -cst accordingly.
1303 __isl_give pet_expr *PetScan::extract_compound_increment(
1304 CompoundAssignOperator *op, clang::ValueDecl *iv)
1306 Expr *lhs;
1307 DeclRefExpr *ref;
1308 bool neg = false;
1309 pet_expr *expr;
1310 BinaryOperatorKind opcode;
1312 opcode = op->getOpcode();
1313 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1314 unsupported(op);
1315 return NULL;
1317 if (opcode == BO_SubAssign)
1318 neg = true;
1320 lhs = op->getLHS();
1321 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1322 unsupported(op);
1323 return NULL;
1326 ref = cast<DeclRefExpr>(lhs);
1327 if (ref->getDecl() != iv) {
1328 unsupported(op);
1329 return NULL;
1332 expr = extract_expr(op->getRHS());
1333 if (neg) {
1334 int type_size;
1335 type_size = pet_clang_get_type_size(op->getType(), ast_context);
1336 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1339 return expr;
1342 /* Check that the increment of the given for loop increments
1343 * (or decrements) the induction variable "iv" and return
1344 * the increment as a pet_expr if successful.
1346 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1347 ValueDecl *iv)
1349 Stmt *inc = stmt->getInc();
1351 if (!inc) {
1352 report_missing_increment(stmt);
1353 return NULL;
1356 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1357 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1358 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1359 return extract_compound_increment(
1360 cast<CompoundAssignOperator>(inc), iv);
1361 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1362 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1364 unsupported(inc);
1365 return NULL;
1368 /* Construct a pet_tree for a while loop.
1370 * If we were only able to extract part of the body, then simply
1371 * return that part.
1373 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1375 pet_expr *pe_cond;
1376 pet_tree *tree;
1378 tree = extract(stmt->getBody());
1379 if (partial)
1380 return tree;
1381 pe_cond = extract_expr(stmt->getCond());
1382 tree = pet_tree_new_while(pe_cond, tree);
1384 return tree;
1387 /* Construct a pet_tree for a for statement.
1388 * The for loop is required to be of one of the following forms
1390 * for (i = init; condition; ++i)
1391 * for (i = init; condition; --i)
1392 * for (i = init; condition; i += constant)
1393 * for (i = init; condition; i -= constant)
1395 * We extract a pet_tree for the body and then include it in a pet_tree
1396 * of type pet_tree_for.
1398 * As a special case, we also allow a for loop of the form
1400 * for (;;)
1402 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1404 * If we were only able to extract part of the body, then simply
1405 * return that part.
1407 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1409 BinaryOperator *ass;
1410 Decl *decl;
1411 Stmt *init;
1412 Expr *lhs, *rhs;
1413 ValueDecl *iv;
1414 pet_tree *tree;
1415 int independent;
1416 int declared;
1417 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1419 independent = is_current_stmt_marked_independent();
1421 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1422 tree = extract(stmt->getBody());
1423 if (partial)
1424 return tree;
1425 tree = pet_tree_new_infinite_loop(tree);
1426 return tree;
1429 init = stmt->getInit();
1430 if (!init) {
1431 unsupported(stmt);
1432 return NULL;
1434 if ((ass = initialization_assignment(init)) != NULL) {
1435 iv = extract_induction_variable(ass);
1436 if (!iv)
1437 return NULL;
1438 lhs = ass->getLHS();
1439 rhs = ass->getRHS();
1440 } else if ((decl = initialization_declaration(init)) != NULL) {
1441 VarDecl *var = extract_induction_variable(init, decl);
1442 if (!var)
1443 return NULL;
1444 iv = var;
1445 rhs = var->getInit();
1446 lhs = create_DeclRefExpr(var);
1447 } else {
1448 unsupported(stmt->getInit());
1449 return NULL;
1452 declared = !initialization_assignment(stmt->getInit());
1453 tree = extract(stmt->getBody());
1454 if (partial)
1455 return tree;
1456 pe_iv = extract_access_expr(iv);
1457 pe_iv = mark_write(pe_iv);
1458 pe_init = extract_expr(rhs);
1459 if (!stmt->getCond())
1460 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1461 else
1462 pe_cond = extract_expr(stmt->getCond());
1463 pe_inc = extract_increment(stmt, iv);
1464 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1465 pe_inc, tree);
1466 return tree;
1469 /* Store the names of the variables declared in decl_context
1470 * in the set declared_names. Make sure to only do this once by
1471 * setting declared_names_collected.
1473 void PetScan::collect_declared_names()
1475 DeclContext *DC = decl_context;
1476 DeclContext::decl_iterator it;
1478 if (declared_names_collected)
1479 return;
1481 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1482 Decl *D = *it;
1483 NamedDecl *named;
1485 if (!isa<NamedDecl>(D))
1486 continue;
1487 named = cast<NamedDecl>(D);
1488 declared_names.insert(named->getName().str());
1491 declared_names_collected = true;
1494 /* Add the names in "names" that are not also in this->declared_names
1495 * to this->used_names.
1496 * It is up to the caller to make sure that declared_names has been
1497 * populated, if needed.
1499 void PetScan::add_new_used_names(const std::set<std::string> &names)
1501 std::set<std::string>::const_iterator it;
1503 for (it = names.begin(); it != names.end(); ++it) {
1504 if (declared_names.find(*it) != declared_names.end())
1505 continue;
1506 used_names.insert(*it);
1510 /* Is the name "name" used in any declaration other than "decl"?
1512 * If the name was found to be in use before, the consider it to be in use.
1513 * Otherwise, check the DeclContext of the function containing the scop
1514 * as well as all ancestors of this DeclContext for declarations
1515 * other than "decl" that declare something called "name".
1517 bool PetScan::name_in_use(const string &name, Decl *decl)
1519 DeclContext *DC;
1520 DeclContext::decl_iterator it;
1522 if (used_names.find(name) != used_names.end())
1523 return true;
1525 for (DC = decl_context; DC; DC = DC->getParent()) {
1526 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1527 Decl *D = *it;
1528 NamedDecl *named;
1530 if (D == decl)
1531 continue;
1532 if (!isa<NamedDecl>(D))
1533 continue;
1534 named = cast<NamedDecl>(D);
1535 if (named->getName().str() == name)
1536 return true;
1540 return false;
1543 /* Generate a new name based on "name" that is not in use.
1544 * Do so by adding a suffix _i, with i an integer.
1546 string PetScan::generate_new_name(const string &name)
1548 string new_name;
1550 do {
1551 std::ostringstream oss;
1552 oss << name << "_" << n_rename++;
1553 new_name = oss.str();
1554 } while (name_in_use(new_name, NULL));
1556 return new_name;
1559 /* Try and construct a pet_tree corresponding to a compound statement.
1561 * "skip_declarations" is set if we should skip initial declarations
1562 * in the children of the compound statements.
1564 * Collect a new set of declarations for the current compound statement.
1565 * If any of the names in these declarations is also used by another
1566 * declaration reachable from the current function, then rename it
1567 * to a name that is not already in use.
1568 * In particular, keep track of the old and new names in a pet_substituter
1569 * and apply the substitutions to the pet_tree corresponding to the
1570 * compound statement.
1572 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1573 bool skip_declarations)
1575 pet_tree *tree;
1576 std::vector<VarDecl *> saved_declarations;
1577 std::vector<VarDecl *>::iterator it;
1578 pet_substituter substituter;
1580 saved_declarations = declarations;
1581 declarations.clear();
1582 tree = extract(stmt->children(), true, skip_declarations, stmt);
1583 for (it = declarations.begin(); it != declarations.end(); ++it) {
1584 isl_id *id;
1585 pet_expr *expr;
1586 VarDecl *decl = *it;
1587 string name = decl->getName().str();
1588 bool in_use = name_in_use(name, decl);
1590 used_names.insert(name);
1591 if (!in_use)
1592 continue;
1594 name = generate_new_name(name);
1595 id = pet_id_from_name_and_decl(ctx, name.c_str(), decl);
1596 expr = pet_id_create_index_expr(id);
1597 expr = extract_access_expr(decl->getType(), expr);
1598 id = pet_id_from_decl(ctx, decl);
1599 substituter.add_sub(id, expr);
1600 used_names.insert(name);
1602 tree = substituter.substitute(tree);
1603 declarations = saved_declarations;
1605 return tree;
1608 /* Return the file offset of the expansion location of "Loc".
1610 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1612 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1615 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1617 /* Return a SourceLocation for the location after the first semicolon
1618 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1619 * call it and also skip trailing spaces and newline.
1621 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1622 const LangOptions &LO)
1624 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1627 #else
1629 /* Return a SourceLocation for the location after the first semicolon
1630 * after "loc". If Lexer::findLocationAfterToken is not available,
1631 * we look in the underlying character data for the first semicolon.
1633 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1634 const LangOptions &LO)
1636 const char *semi;
1637 const char *s = SM.getCharacterData(loc);
1639 semi = strchr(s, ';');
1640 if (!semi)
1641 return SourceLocation();
1642 return loc.getFileLocWithOffset(semi + 1 - s);
1645 #endif
1647 /* If the token at "loc" is the first token on the line, then return
1648 * a location referring to the start of the line and set *indent
1649 * to the indentation of "loc"
1650 * Otherwise, return "loc" and set *indent to "".
1652 * This function is used to extend a scop to the start of the line
1653 * if the first token of the scop is also the first token on the line.
1655 * We look for the first token on the line. If its location is equal to "loc",
1656 * then the latter is the location of the first token on the line.
1658 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1659 SourceManager &SM, const LangOptions &LO, char **indent)
1661 std::pair<FileID, unsigned> file_offset_pair;
1662 llvm::StringRef file;
1663 const char *pos;
1664 Token tok;
1665 SourceLocation token_loc, line_loc;
1666 int col;
1667 const char *s;
1669 loc = SM.getExpansionLoc(loc);
1670 col = SM.getExpansionColumnNumber(loc);
1671 line_loc = loc.getLocWithOffset(1 - col);
1672 file_offset_pair = SM.getDecomposedLoc(line_loc);
1673 file = SM.getBufferData(file_offset_pair.first, NULL);
1674 pos = file.data() + file_offset_pair.second;
1676 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1677 file.begin(), pos, file.end());
1678 lexer.LexFromRawLexer(tok);
1679 token_loc = tok.getLocation();
1681 s = SM.getCharacterData(line_loc);
1682 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1684 if (token_loc == loc)
1685 return line_loc;
1686 else
1687 return loc;
1690 /* Construct a pet_loc corresponding to the region covered by "range".
1691 * If "skip_semi" is set, then we assume "range" is followed by
1692 * a semicolon and also include this semicolon.
1694 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1695 bool skip_semi)
1697 SourceLocation loc = range.getBegin();
1698 SourceManager &SM = PP.getSourceManager();
1699 const LangOptions &LO = PP.getLangOpts();
1700 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1701 unsigned start, end;
1702 char *indent;
1704 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1705 start = getExpansionOffset(SM, loc);
1706 loc = range.getEnd();
1707 if (skip_semi)
1708 loc = location_after_semi(loc, SM, LO);
1709 else
1710 loc = PP.getLocForEndOfToken(loc);
1711 end = getExpansionOffset(SM, loc);
1713 return pet_loc_alloc(ctx, start, end, line, indent);
1716 /* Convert a top-level pet_expr to an expression pet_tree.
1718 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1719 SourceRange range, bool skip_semi)
1721 pet_loc *loc;
1722 pet_tree *tree;
1724 tree = pet_tree_new_expr(expr);
1725 loc = construct_pet_loc(range, skip_semi);
1726 tree = pet_tree_set_loc(tree, loc);
1728 return tree;
1731 /* Construct a pet_tree for an if statement.
1733 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1735 pet_expr *pe_cond;
1736 pet_tree *tree, *tree_else;
1738 pe_cond = extract_expr(stmt->getCond());
1739 tree = extract(stmt->getThen());
1740 if (stmt->getElse()) {
1741 tree_else = extract(stmt->getElse());
1742 if (options->autodetect) {
1743 if (tree && !tree_else) {
1744 partial = true;
1745 pet_expr_free(pe_cond);
1746 return tree;
1748 if (!tree && tree_else) {
1749 partial = true;
1750 pet_expr_free(pe_cond);
1751 return tree_else;
1754 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1755 } else
1756 tree = pet_tree_new_if(pe_cond, tree);
1757 return tree;
1760 /* Try and construct a pet_tree for a label statement.
1762 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1764 isl_id *label;
1765 pet_tree *tree;
1767 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1769 tree = extract(stmt->getSubStmt());
1770 tree = pet_tree_set_label(tree, label);
1771 return tree;
1774 /* Update the location of "tree" to include the source range of "stmt".
1776 * Actually, we create a new location based on the source range of "stmt" and
1777 * then extend this new location to include the region of the original location.
1778 * This ensures that the line number of the final location refers to "stmt".
1780 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1782 pet_loc *loc, *tree_loc;
1784 tree_loc = pet_tree_get_loc(tree);
1785 loc = construct_pet_loc(stmt->getSourceRange(), false);
1786 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1787 pet_loc_free(tree_loc);
1789 tree = pet_tree_set_loc(tree, loc);
1790 return tree;
1793 /* Is "expr" of a type that can be converted to an access expression?
1795 static bool is_access_expr_type(Expr *expr)
1797 switch (expr->getStmtClass()) {
1798 case Stmt::ArraySubscriptExprClass:
1799 case Stmt::DeclRefExprClass:
1800 case Stmt::MemberExprClass:
1801 return true;
1802 default:
1803 return false;
1807 /* Tell the pet_inliner "inliner" about the formal arguments
1808 * in "fd" and the corresponding actual arguments in "call".
1809 * Return 0 if this was successful and -1 otherwise.
1811 * Any pointer argument is treated as an array.
1812 * The other arguments are treated as scalars.
1814 * In case of scalars, there is no restriction on the actual argument.
1815 * This actual argument is assigned to a variable with a name
1816 * that is derived from the name of the corresponding formal argument,
1817 * but made not to conflict with any variable names that are
1818 * already in use.
1820 * In case of arrays, the actual argument needs to be an expression
1821 * of a type that can be converted to an access expression or the address
1822 * of such an expression, ignoring implicit and redundant casts.
1824 int PetScan::set_inliner_arguments(pet_inliner &inliner, CallExpr *call,
1825 FunctionDecl *fd)
1827 unsigned n;
1829 n = fd->getNumParams();
1830 for (unsigned i = 0; i < n; ++i) {
1831 ParmVarDecl *parm = fd->getParamDecl(i);
1832 QualType type = parm->getType();
1833 Expr *arg, *sub;
1834 pet_expr *expr;
1835 int is_addr = 0;
1837 arg = call->getArg(i);
1838 if (pet_clang_array_depth(type) == 0) {
1839 string name = parm->getName().str();
1840 if (name_in_use(name, NULL))
1841 name = generate_new_name(name);
1842 used_names.insert(name);
1843 inliner.add_scalar_arg(parm, name, extract_expr(arg));
1844 continue;
1846 arg = pet_clang_strip_casts(arg);
1847 sub = extract_addr_of_arg(arg);
1848 if (sub) {
1849 is_addr = 1;
1850 arg = pet_clang_strip_casts(sub);
1852 if (!is_access_expr_type(arg)) {
1853 report_unsupported_inline_function_argument(arg);
1854 return -1;
1856 expr = extract_access_expr(arg);
1857 if (!expr)
1858 return -1;
1859 inliner.add_array_arg(parm, expr, is_addr);
1862 return 0;
1865 /* Try and construct a pet_tree from the body of "fd" using the actual
1866 * arguments in "call" in place of the formal arguments.
1867 * "fd" is assumed to point to the declaration with a function body.
1868 * In particular, construct a block that consists of assignments
1869 * of (parts of) the actual arguments to temporary variables
1870 * followed by the inlined function body with the formal arguments
1871 * replaced by (expressions containing) these temporary variables.
1873 * The actual inlining is taken care of by the pet_inliner function.
1874 * This function merely calls set_inliner_arguments to tell
1875 * the pet_inliner about the actual arguments, extracts a pet_tree
1876 * from the body of the called function and then passes this pet_tree
1877 * to the pet_inliner.
1879 * During the extraction of the function body, all variables names
1880 * that are declared in the calling function as well all variable
1881 * names that are known to be in use are considered to be in use
1882 * in the called function to ensure that there is no naming conflict.
1883 * Similarly, the additional names that are in use in the called function
1884 * are considered to be in use in the calling function as well.
1886 * The location of the pet_tree is reset to the call site to ensure
1887 * that the extent of the scop does not include the body of the called
1888 * function.
1890 __isl_give pet_tree *PetScan::extract_inlined_call(CallExpr *call,
1891 FunctionDecl *fd)
1893 int save_autodetect;
1894 pet_tree *tree;
1895 pet_loc *tree_loc;
1896 pet_inliner inliner(ctx, n_arg, ast_context);
1898 if (set_inliner_arguments(inliner, call, fd) < 0)
1899 return NULL;
1901 save_autodetect = options->autodetect;
1902 options->autodetect = 0;
1903 PetScan body_scan(PP, ast_context, fd, loc, options,
1904 isl_union_map_copy(value_bounds), independent);
1905 collect_declared_names();
1906 body_scan.add_new_used_names(declared_names);
1907 body_scan.add_new_used_names(used_names);
1908 tree = body_scan.extract(fd->getBody(), false);
1909 add_new_used_names(body_scan.used_names);
1910 options->autodetect = save_autodetect;
1912 tree_loc = construct_pet_loc(call->getSourceRange(), true);
1913 tree = pet_tree_set_loc(tree, tree_loc);
1915 return inliner.inline_tree(tree);
1918 /* Try and construct a pet_tree corresponding
1919 * to the expression statement "stmt".
1921 * If the outer expression is a function call and if the corresponding
1922 * function body is marked "inline", then return a pet_tree
1923 * corresponding to the inlined function.
1925 __isl_give pet_tree *PetScan::extract_expr_stmt(Stmt *stmt)
1927 pet_expr *expr;
1929 if (stmt->getStmtClass() == Stmt::CallExprClass) {
1930 CallExpr *call = cast<CallExpr>(stmt);
1931 FunctionDecl *fd = call->getDirectCallee();
1932 fd = pet_clang_find_function_decl_with_body(fd);
1933 if (fd && fd->isInlineSpecified())
1934 return extract_inlined_call(call, fd);
1937 expr = extract_expr(cast<Expr>(stmt));
1938 return extract(expr, stmt->getSourceRange(), true);
1941 /* Try and construct a pet_tree corresponding to "stmt".
1943 * If "stmt" is a compound statement, then "skip_declarations"
1944 * indicates whether we should skip initial declarations in the
1945 * compound statement.
1947 * If the constructed pet_tree is not a (possibly) partial representation
1948 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1949 * In particular, if skip_declarations is set, then we may have skipped
1950 * declarations inside "stmt" and so the pet_scop may not represent
1951 * the entire "stmt".
1952 * Note that this function may be called with "stmt" referring to the entire
1953 * body of the function, including the outer braces. In such cases,
1954 * skip_declarations will be set and the braces will not be taken into
1955 * account in tree->loc.
1957 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
1959 pet_tree *tree;
1961 set_current_stmt(stmt);
1963 if (isa<Expr>(stmt))
1964 return extract_expr_stmt(cast<Expr>(stmt));
1966 switch (stmt->getStmtClass()) {
1967 case Stmt::WhileStmtClass:
1968 tree = extract(cast<WhileStmt>(stmt));
1969 break;
1970 case Stmt::ForStmtClass:
1971 tree = extract_for(cast<ForStmt>(stmt));
1972 break;
1973 case Stmt::IfStmtClass:
1974 tree = extract(cast<IfStmt>(stmt));
1975 break;
1976 case Stmt::CompoundStmtClass:
1977 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
1978 break;
1979 case Stmt::LabelStmtClass:
1980 tree = extract(cast<LabelStmt>(stmt));
1981 break;
1982 case Stmt::ContinueStmtClass:
1983 tree = pet_tree_new_continue(ctx);
1984 break;
1985 case Stmt::BreakStmtClass:
1986 tree = pet_tree_new_break(ctx);
1987 break;
1988 case Stmt::DeclStmtClass:
1989 tree = extract(cast<DeclStmt>(stmt));
1990 break;
1991 case Stmt::NullStmtClass:
1992 tree = pet_tree_new_block(ctx, 0, 0);
1993 break;
1994 default:
1995 report_unsupported_statement_type(stmt);
1996 return NULL;
1999 if (partial || skip_declarations)
2000 return tree;
2002 return update_loc(tree, stmt);
2005 /* Given a sequence of statements "stmt_range" of which the first "n_decl"
2006 * are declarations and of which the remaining statements are represented
2007 * by "tree", try and extend "tree" to include the last sequence of
2008 * the initial declarations that can be completely extracted.
2010 * We start collecting the initial declarations and start over
2011 * whenever we come across a declaration that we cannot extract.
2012 * If we have been able to extract any declarations, then we
2013 * copy over the contents of "tree" at the end of the declarations.
2014 * Otherwise, we simply return the original "tree".
2016 __isl_give pet_tree *PetScan::insert_initial_declarations(
2017 __isl_take pet_tree *tree, int n_decl, StmtRange stmt_range)
2019 StmtIterator i;
2020 pet_tree *res;
2021 int n_stmt;
2022 int is_block;
2023 int j;
2025 n_stmt = pet_tree_block_n_child(tree);
2026 is_block = pet_tree_block_get_block(tree);
2027 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2029 for (i = stmt_range.first; n_decl; ++i, --n_decl) {
2030 Stmt *child = *i;
2031 pet_tree *tree_i;
2033 tree_i = extract(child);
2034 if (tree_i && !partial) {
2035 res = pet_tree_block_add_child(res, tree_i);
2036 continue;
2038 pet_tree_free(tree_i);
2039 partial = false;
2040 if (pet_tree_block_n_child(res) == 0)
2041 continue;
2042 pet_tree_free(res);
2043 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2046 if (pet_tree_block_n_child(res) == 0) {
2047 pet_tree_free(res);
2048 return tree;
2051 for (j = 0; j < n_stmt; ++j) {
2052 pet_tree *tree_i;
2054 tree_i = pet_tree_block_get_child(tree, j);
2055 res = pet_tree_block_add_child(res, tree_i);
2057 pet_tree_free(tree);
2059 return res;
2062 /* Try and construct a pet_tree corresponding to (part of)
2063 * a sequence of statements.
2065 * "block" is set if the sequence represents the children of
2066 * a compound statement.
2067 * "skip_declarations" is set if we should skip initial declarations
2068 * in the sequence of statements.
2069 * "parent" is the statement that has stmt_range as (some of) its children.
2071 * If autodetect is set, then we allow the extraction of only a subrange
2072 * of the sequence of statements. However, if there is at least one
2073 * kill and there is some subsequent statement for which we could not
2074 * construct a tree, then turn off the "block" property of the tree
2075 * such that no extra kill will be introduced at the end of the (partial)
2076 * block. If, on the other hand, the final range contains
2077 * no statements, then we discard the entire range.
2078 * If only a subrange of the sequence was extracted, but each statement
2079 * in the sequence was extracted completely, and if there are some
2080 * variable declarations in the sequence before or inside
2081 * the extracted subrange, then check if any of these variables are
2082 * not used after the extracted subrange. If so, add kills to these
2083 * variables.
2085 * If the entire range was extracted, apart from some initial declarations,
2086 * then we try and extend the range with the latest of those initial
2087 * declarations.
2089 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
2090 bool skip_declarations, Stmt *parent)
2092 StmtIterator i;
2093 int j, skip;
2094 bool has_kills = false;
2095 bool partial_range = false;
2096 bool outer_partial = false;
2097 pet_tree *tree;
2098 SourceManager &SM = PP.getSourceManager();
2099 pet_killed_locals kl(SM);
2100 unsigned range_start, range_end;
2102 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
2105 tree = pet_tree_new_block(ctx, block, j);
2107 skip = 0;
2108 i = stmt_range.first;
2109 if (skip_declarations)
2110 for (; i != stmt_range.second; ++i) {
2111 if ((*i)->getStmtClass() != Stmt::DeclStmtClass)
2112 break;
2113 if (options->autodetect)
2114 kl.add_locals(cast<DeclStmt>(*i));
2115 ++skip;
2118 for (; i != stmt_range.second; ++i) {
2119 Stmt *child = *i;
2120 pet_tree *tree_i;
2122 tree_i = extract(child);
2123 if (pet_tree_block_n_child(tree) != 0 && partial) {
2124 pet_tree_free(tree_i);
2125 break;
2127 if (child->getStmtClass() == Stmt::DeclStmtClass) {
2128 if (options->autodetect)
2129 kl.add_locals(cast<DeclStmt>(child));
2130 if (tree_i && block)
2131 has_kills = true;
2133 if (options->autodetect) {
2134 if (tree_i) {
2135 range_end = getExpansionOffset(SM,
2136 child->getLocEnd());
2137 if (pet_tree_block_n_child(tree) == 0)
2138 range_start = getExpansionOffset(SM,
2139 child->getLocStart());
2140 tree = pet_tree_block_add_child(tree, tree_i);
2141 } else {
2142 partial_range = true;
2144 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
2145 outer_partial = partial = true;
2146 } else {
2147 tree = pet_tree_block_add_child(tree, tree_i);
2150 if (partial || !tree)
2151 break;
2154 if (!tree)
2155 return NULL;
2157 if (partial) {
2158 if (has_kills)
2159 tree = pet_tree_block_set_block(tree, 0);
2160 if (outer_partial) {
2161 kl.remove_accessed_after(parent,
2162 range_start, range_end);
2163 tree = add_kills(tree, kl.locals);
2165 } else if (partial_range) {
2166 if (pet_tree_block_n_child(tree) == 0) {
2167 pet_tree_free(tree);
2168 return NULL;
2170 partial = true;
2171 } else if (skip > 0)
2172 tree = insert_initial_declarations(tree, skip, stmt_range);
2174 return tree;
2177 extern "C" {
2178 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2179 void *user);
2180 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2181 __isl_keep pet_context *pc, void *user);
2184 /* Construct a pet_expr that holds the sizes of the array accessed
2185 * by "access".
2186 * This function is used as a callback to pet_context_add_parameters,
2187 * which is also passed a pointer to the PetScan object.
2189 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2190 void *user)
2192 PetScan *ps = (PetScan *) user;
2193 isl_id *id;
2194 QualType qt;
2196 id = pet_expr_access_get_id(access);
2197 qt = pet_id_get_array_type(id);
2198 isl_id_free(id);
2199 return ps->get_array_size(qt);
2202 /* Construct and return a pet_array corresponding to the variable
2203 * accessed by "access".
2204 * This function is used as a callback to pet_scop_from_pet_tree,
2205 * which is also passed a pointer to the PetScan object.
2207 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2208 __isl_keep pet_context *pc, void *user)
2210 PetScan *ps = (PetScan *) user;
2211 isl_ctx *ctx;
2212 isl_id *id;
2213 pet_array *array;
2215 ctx = pet_expr_get_ctx(access);
2216 id = pet_expr_access_get_id(access);
2217 array = ps->extract_array(id, NULL, pc);
2218 isl_id_free(id);
2220 return array;
2223 /* Extract a function summary from the body of "fd".
2225 * We extract a scop from the function body in a context with as
2226 * parameters the integer arguments of the function.
2227 * We turn off autodetection (in case it was set) to ensure that
2228 * the entire function body is considered.
2229 * We then collect the accessed array elements and attach them
2230 * to the corresponding array arguments, taking into account
2231 * that the function body may access members of array elements.
2233 * The reason for representing the integer arguments as parameters in
2234 * the context is that if we were to instead start with a context
2235 * with the function arguments as initial dimensions, then we would not
2236 * be able to refer to them from the array extents, without turning
2237 * array extents into maps.
2239 * The result is stored in the summary_cache cache so that we can reuse
2240 * it if this method gets called on the same function again later on.
2242 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
2244 isl_space *space;
2245 isl_set *domain;
2246 pet_context *pc;
2247 pet_tree *tree;
2248 pet_function_summary *summary;
2249 unsigned n;
2250 ScopLoc loc;
2251 int save_autodetect;
2252 struct pet_scop *scop;
2253 int int_size;
2254 isl_union_set *may_read, *may_write, *must_write;
2255 isl_union_map *to_inner;
2257 if (summary_cache.find(fd) != summary_cache.end())
2258 return pet_function_summary_copy(summary_cache[fd]);
2260 space = isl_space_set_alloc(ctx, 0, 0);
2262 n = fd->getNumParams();
2263 summary = pet_function_summary_alloc(ctx, n);
2264 for (unsigned i = 0; i < n; ++i) {
2265 ParmVarDecl *parm = fd->getParamDecl(i);
2266 QualType type = parm->getType();
2267 isl_id *id;
2269 if (!type->isIntegerType())
2270 continue;
2271 id = pet_id_from_decl(ctx, parm);
2272 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
2273 space = isl_space_set_dim_id(space, isl_dim_param, 0,
2274 isl_id_copy(id));
2275 summary = pet_function_summary_set_int(summary, i, id);
2278 save_autodetect = options->autodetect;
2279 options->autodetect = 0;
2280 PetScan body_scan(PP, ast_context, fd, loc, options,
2281 isl_union_map_copy(value_bounds), independent);
2283 tree = body_scan.extract(fd->getBody(), false);
2285 domain = isl_set_universe(space);
2286 pc = pet_context_alloc(domain);
2287 pc = pet_context_add_parameters(pc, tree,
2288 &::get_array_size, &body_scan);
2289 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2290 scop = pet_scop_from_pet_tree(tree, int_size,
2291 &::extract_array, &body_scan, pc);
2292 scop = scan_arrays(scop, pc);
2293 may_read = isl_union_map_range(pet_scop_get_may_reads(scop));
2294 may_write = isl_union_map_range(pet_scop_get_may_writes(scop));
2295 must_write = isl_union_map_range(pet_scop_get_must_writes(scop));
2296 to_inner = pet_scop_compute_outer_to_inner(scop);
2297 pet_scop_free(scop);
2299 for (unsigned i = 0; i < n; ++i) {
2300 ParmVarDecl *parm = fd->getParamDecl(i);
2301 QualType type = parm->getType();
2302 struct pet_array *array;
2303 isl_space *space;
2304 isl_union_set *data_set;
2305 isl_union_set *may_read_i, *may_write_i, *must_write_i;
2307 if (pet_clang_array_depth(type) == 0)
2308 continue;
2310 array = body_scan.extract_array(parm, NULL, pc);
2311 space = array ? isl_set_get_space(array->extent) : NULL;
2312 pet_array_free(array);
2313 data_set = isl_union_set_from_set(isl_set_universe(space));
2314 data_set = isl_union_set_apply(data_set,
2315 isl_union_map_copy(to_inner));
2316 may_read_i = isl_union_set_intersect(
2317 isl_union_set_copy(may_read),
2318 isl_union_set_copy(data_set));
2319 may_write_i = isl_union_set_intersect(
2320 isl_union_set_copy(may_write),
2321 isl_union_set_copy(data_set));
2322 must_write_i = isl_union_set_intersect(
2323 isl_union_set_copy(must_write), data_set);
2324 summary = pet_function_summary_set_array(summary, i,
2325 may_read_i, may_write_i, must_write_i);
2328 isl_union_set_free(may_read);
2329 isl_union_set_free(may_write);
2330 isl_union_set_free(must_write);
2331 isl_union_map_free(to_inner);
2333 options->autodetect = save_autodetect;
2334 pet_context_free(pc);
2336 summary_cache[fd] = pet_function_summary_copy(summary);
2338 return summary;
2341 /* If "fd" has a function body, then extract a function summary from
2342 * this body and attach it to the call expression "expr".
2344 * Even if a function body is available, "fd" itself may point
2345 * to a declaration without function body. We therefore first
2346 * replace it by the declaration that comes with a body (if any).
2348 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
2349 FunctionDecl *fd)
2351 pet_function_summary *summary;
2353 if (!expr)
2354 return NULL;
2355 fd = pet_clang_find_function_decl_with_body(fd);
2356 if (!fd)
2357 return expr;
2359 summary = get_summary(fd);
2361 expr = pet_expr_call_set_summary(expr, summary);
2363 return expr;
2366 /* Extract a pet_scop from "tree".
2368 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
2369 * then add pet_arrays for all accessed arrays.
2370 * We populate the pet_context with assignments for all parameters used
2371 * inside "tree" or any of the size expressions for the arrays accessed
2372 * by "tree" so that they can be used in affine expressions.
2374 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
2376 int int_size;
2377 isl_set *domain;
2378 pet_context *pc;
2379 pet_scop *scop;
2381 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2383 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2384 pc = pet_context_alloc(domain);
2385 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
2386 scop = pet_scop_from_pet_tree(tree, int_size,
2387 &::extract_array, this, pc);
2388 scop = scan_arrays(scop, pc);
2389 pet_context_free(pc);
2391 return scop;
2394 /* Add a call to __pencil_kill to the end of "tree" that kills
2395 * all the variables in "locals" and return the result.
2397 * No location is added to the kill because the most natural
2398 * location would lie outside the scop. Attaching such a location
2399 * to this tree would extend the scope of the final result
2400 * to include the location.
2402 __isl_give pet_tree *PetScan::add_kills(__isl_take pet_tree *tree,
2403 set<ValueDecl *> locals)
2405 int i;
2406 pet_expr *expr;
2407 pet_tree *kill, *block;
2408 set<ValueDecl *>::iterator it;
2410 if (locals.size() == 0)
2411 return tree;
2412 expr = pet_expr_new_call(ctx, "__pencil_kill", locals.size());
2413 i = 0;
2414 for (it = locals.begin(); it != locals.end(); ++it) {
2415 pet_expr *arg;
2416 arg = extract_access_expr(*it);
2417 expr = pet_expr_set_arg(expr, i++, arg);
2419 kill = pet_tree_new_expr(expr);
2420 block = pet_tree_new_block(ctx, 0, 2);
2421 block = pet_tree_block_add_child(block, tree);
2422 block = pet_tree_block_add_child(block, kill);
2424 return block;
2427 /* Check if the scop marked by the user is exactly this Stmt
2428 * or part of this Stmt.
2429 * If so, return a pet_scop corresponding to the marked region.
2430 * Otherwise, return NULL.
2432 * If the scop is not further nested inside a child of "stmt",
2433 * then check if there are any variable declarations before the scop
2434 * inside "stmt". If so, and if these variables are not used
2435 * after the scop, then add kills to the variables.
2437 struct pet_scop *PetScan::scan(Stmt *stmt)
2439 SourceManager &SM = PP.getSourceManager();
2440 unsigned start_off, end_off;
2441 pet_tree *tree;
2443 start_off = getExpansionOffset(SM, stmt->getLocStart());
2444 end_off = getExpansionOffset(SM, stmt->getLocEnd());
2446 if (start_off > loc.end)
2447 return NULL;
2448 if (end_off < loc.start)
2449 return NULL;
2451 if (start_off >= loc.start && end_off <= loc.end)
2452 return extract_scop(extract(stmt));
2454 pet_killed_locals kl(SM);
2455 StmtIterator start;
2456 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
2457 Stmt *child = *start;
2458 if (!child)
2459 continue;
2460 start_off = getExpansionOffset(SM, child->getLocStart());
2461 end_off = getExpansionOffset(SM, child->getLocEnd());
2462 if (start_off < loc.start && end_off >= loc.end)
2463 return scan(child);
2464 if (start_off >= loc.start)
2465 break;
2466 if (isa<DeclStmt>(child))
2467 kl.add_locals(cast<DeclStmt>(child));
2470 StmtIterator end;
2471 for (end = start; end != stmt->child_end(); ++end) {
2472 Stmt *child = *end;
2473 start_off = SM.getFileOffset(child->getLocStart());
2474 if (start_off >= loc.end)
2475 break;
2478 kl.remove_accessed_after(stmt, loc.start, loc.end);
2480 tree = extract(StmtRange(start, end), false, false, stmt);
2481 tree = add_kills(tree, kl.locals);
2482 return extract_scop(tree);
2485 /* Set the size of index "pos" of "array" to "size".
2486 * In particular, add a constraint of the form
2488 * i_pos < size
2490 * to array->extent and a constraint of the form
2492 * size >= 0
2494 * to array->context.
2496 * The domain of "size" is assumed to be zero-dimensional.
2498 static struct pet_array *update_size(struct pet_array *array, int pos,
2499 __isl_take isl_pw_aff *size)
2501 isl_set *valid;
2502 isl_set *univ;
2503 isl_set *bound;
2504 isl_space *dim;
2505 isl_aff *aff;
2506 isl_pw_aff *index;
2507 isl_id *id;
2509 if (!array)
2510 goto error;
2512 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2513 array->context = isl_set_intersect(array->context, valid);
2515 dim = isl_set_get_space(array->extent);
2516 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2517 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2518 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2519 index = isl_pw_aff_alloc(univ, aff);
2521 size = isl_pw_aff_add_dims(size, isl_dim_in,
2522 isl_set_dim(array->extent, isl_dim_set));
2523 id = isl_set_get_tuple_id(array->extent);
2524 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2525 bound = isl_pw_aff_lt_set(index, size);
2527 array->extent = isl_set_intersect(array->extent, bound);
2529 if (!array->context || !array->extent)
2530 return pet_array_free(array);
2532 return array;
2533 error:
2534 isl_pw_aff_free(size);
2535 return NULL;
2538 #ifdef HAVE_DECAYEDTYPE
2540 /* If "qt" is a decayed type, then set *decayed to true and
2541 * return the original type.
2543 static QualType undecay(QualType qt, bool *decayed)
2545 const Type *type = qt.getTypePtr();
2547 *decayed = isa<DecayedType>(type);
2548 if (*decayed)
2549 qt = cast<DecayedType>(type)->getOriginalType();
2550 return qt;
2553 #else
2555 /* If "qt" is a decayed type, then set *decayed to true and
2556 * return the original type.
2557 * Since this version of clang does not define a DecayedType,
2558 * we cannot obtain the original type even if it had been decayed and
2559 * we set *decayed to false.
2561 static QualType undecay(QualType qt, bool *decayed)
2563 *decayed = false;
2564 return qt;
2567 #endif
2569 /* Figure out the size of the array at position "pos" and all
2570 * subsequent positions from "qt" and update the corresponding
2571 * argument of "expr" accordingly.
2573 * The initial type (when pos is zero) may be a pointer type decayed
2574 * from an array type, if this initial type is the type of a function
2575 * argument. This only happens if the original array type has
2576 * a constant size in the outer dimension as otherwise we get
2577 * a VariableArrayType. Try and obtain this original type (if available) and
2578 * take the outer array size into account if it was marked static.
2580 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2581 QualType qt, int pos)
2583 const ArrayType *atype;
2584 pet_expr *size;
2585 bool decayed = false;
2587 if (!expr)
2588 return NULL;
2590 if (pos == 0)
2591 qt = undecay(qt, &decayed);
2593 if (qt->isPointerType()) {
2594 qt = qt->getPointeeType();
2595 return set_upper_bounds(expr, qt, pos + 1);
2597 if (!qt->isArrayType())
2598 return expr;
2600 qt = qt->getCanonicalTypeInternal();
2601 atype = cast<ArrayType>(qt.getTypePtr());
2603 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2604 qt = atype->getElementType();
2605 return set_upper_bounds(expr, qt, pos + 1);
2608 if (qt->isConstantArrayType()) {
2609 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2610 size = extract_expr(ca->getSize());
2611 expr = pet_expr_set_arg(expr, pos, size);
2612 } else if (qt->isVariableArrayType()) {
2613 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2614 size = extract_expr(vla->getSizeExpr());
2615 expr = pet_expr_set_arg(expr, pos, size);
2618 qt = atype->getElementType();
2620 return set_upper_bounds(expr, qt, pos + 1);
2623 /* Construct a pet_expr that holds the sizes of an array of the given type.
2624 * The returned expression is a call expression with as arguments
2625 * the sizes in each dimension. If we are unable to derive the size
2626 * in a given dimension, then the corresponding argument is set to infinity.
2627 * In fact, we initialize all arguments to infinity and then update
2628 * them if we are able to figure out the size.
2630 * The result is stored in the type_size cache so that we can reuse
2631 * it if this method gets called on the same type again later on.
2633 __isl_give pet_expr *PetScan::get_array_size(QualType qt)
2635 int depth;
2636 pet_expr *expr, *inf;
2637 const Type *type = qt.getTypePtr();
2639 if (type_size.find(type) != type_size.end())
2640 return pet_expr_copy(type_size[type]);
2642 depth = pet_clang_array_depth(qt);
2643 inf = pet_expr_new_int(isl_val_infty(ctx));
2644 expr = pet_expr_new_call(ctx, "bounds", depth);
2645 for (int i = 0; i < depth; ++i)
2646 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2647 pet_expr_free(inf);
2649 expr = set_upper_bounds(expr, qt, 0);
2650 type_size[type] = pet_expr_copy(expr);
2652 return expr;
2655 /* Does "expr" represent the "integer" infinity?
2657 static int is_infty(__isl_keep pet_expr *expr)
2659 isl_val *v;
2660 int res;
2662 if (pet_expr_get_type(expr) != pet_expr_int)
2663 return 0;
2664 v = pet_expr_int_get_val(expr);
2665 res = isl_val_is_infty(v);
2666 isl_val_free(v);
2668 return res;
2671 /* Figure out the dimensions of an array "array" based on its type
2672 * "qt" and update "array" accordingly.
2674 * We first construct a pet_expr that holds the sizes of the array
2675 * in each dimension. The resulting expression may containing
2676 * infinity values for dimension where we are unable to derive
2677 * a size expression.
2679 * The arguments of the size expression that have a value different from
2680 * infinity are then converted to an affine expression
2681 * within the context "pc" and incorporated into the size of "array".
2682 * If we are unable to convert a size expression to an affine expression or
2683 * if the size is not a (symbolic) constant,
2684 * then we leave the corresponding size of "array" untouched.
2686 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2687 QualType qt, __isl_keep pet_context *pc)
2689 int n;
2690 pet_expr *expr;
2692 if (!array)
2693 return NULL;
2695 expr = get_array_size(qt);
2697 n = pet_expr_get_n_arg(expr);
2698 for (int i = 0; i < n; ++i) {
2699 pet_expr *arg;
2700 isl_pw_aff *size;
2702 arg = pet_expr_get_arg(expr, i);
2703 if (!is_infty(arg)) {
2704 int dim;
2706 size = pet_expr_extract_affine(arg, pc);
2707 dim = isl_pw_aff_dim(size, isl_dim_in);
2708 if (!size)
2709 array = pet_array_free(array);
2710 else if (isl_pw_aff_involves_nan(size) ||
2711 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2712 isl_pw_aff_free(size);
2713 else {
2714 size = isl_pw_aff_drop_dims(size,
2715 isl_dim_in, 0, dim);
2716 array = update_size(array, i, size);
2719 pet_expr_free(arg);
2721 pet_expr_free(expr);
2723 return array;
2726 /* Does "decl" have a definition that we can keep track of in a pet_type?
2728 static bool has_printable_definition(RecordDecl *decl)
2730 if (!decl->getDeclName())
2731 return false;
2732 return decl->getLexicalDeclContext() == decl->getDeclContext();
2735 /* Add all TypedefType objects that appear when dereferencing "type"
2736 * to "types".
2738 static void insert_intermediate_typedefs(PetTypes *types, QualType type)
2740 type = pet_clang_base_or_typedef_type(type);
2741 while (isa<TypedefType>(type)) {
2742 const TypedefType *tt;
2744 tt = cast<TypedefType>(type);
2745 types->insert(tt->getDecl());
2746 type = tt->desugar();
2747 type = pet_clang_base_or_typedef_type(type);
2751 /* Construct and return a pet_array corresponding to the variable
2752 * represented by "id".
2753 * In particular, initialize array->extent to
2755 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2757 * and then call set_upper_bounds to set the upper bounds on the indices
2758 * based on the type of the variable. The upper bounds are converted
2759 * to affine expressions within the context "pc".
2761 * If the base type is that of a record with a top-level definition or
2762 * of a typedef and if "types" is not null, then the RecordDecl or
2763 * TypedefType corresponding to the type, as well as any intermediate
2764 * TypedefType, is added to "types".
2766 * If the base type is that of a record with no top-level definition,
2767 * then we replace it by "<subfield>".
2769 * If the variable is a scalar, i.e., a zero-dimensional array,
2770 * then the "const" qualifier, if any, is removed from the base type.
2771 * This makes it easier for users of pet to turn initializations
2772 * into assignments.
2774 struct pet_array *PetScan::extract_array(__isl_keep isl_id *id,
2775 PetTypes *types, __isl_keep pet_context *pc)
2777 struct pet_array *array;
2778 QualType qt = pet_id_get_array_type(id);
2779 int depth = pet_clang_array_depth(qt);
2780 QualType base = pet_clang_base_type(qt);
2781 string name;
2782 isl_space *space;
2784 array = isl_calloc_type(ctx, struct pet_array);
2785 if (!array)
2786 return NULL;
2788 space = isl_space_set_alloc(ctx, 0, depth);
2789 space = isl_space_set_tuple_id(space, isl_dim_set, isl_id_copy(id));
2791 array->extent = isl_set_nat_universe(space);
2793 space = isl_space_params_alloc(ctx, 0);
2794 array->context = isl_set_universe(space);
2796 array = set_upper_bounds(array, qt, pc);
2797 if (!array)
2798 return NULL;
2800 if (depth == 0)
2801 base.removeLocalConst();
2802 name = base.getAsString();
2804 if (types) {
2805 insert_intermediate_typedefs(types, qt);
2806 if (isa<TypedefType>(base)) {
2807 types->insert(cast<TypedefType>(base)->getDecl());
2808 } else if (base->isRecordType()) {
2809 RecordDecl *decl = pet_clang_record_decl(base);
2810 TypedefNameDecl *typedecl;
2811 typedecl = decl->getTypedefNameForAnonDecl();
2812 if (typedecl)
2813 types->insert(typedecl);
2814 else if (has_printable_definition(decl))
2815 types->insert(decl);
2816 else
2817 name = "<subfield>";
2821 array->element_type = strdup(name.c_str());
2822 array->element_is_record = base->isRecordType();
2823 array->element_size = size_in_bytes(ast_context, base);
2825 return array;
2828 /* Construct and return a pet_array corresponding to the variable "decl".
2830 struct pet_array *PetScan::extract_array(ValueDecl *decl,
2831 PetTypes *types, __isl_keep pet_context *pc)
2833 isl_id *id;
2834 pet_array *array;
2836 id = pet_id_from_decl(ctx, decl);
2837 array = extract_array(id, types, pc);
2838 isl_id_free(id);
2840 return array;
2843 /* Construct and return a pet_array corresponding to the sequence
2844 * of declarations represented by "decls".
2845 * The upper bounds of the array are converted to affine expressions
2846 * within the context "pc".
2847 * If the sequence contains a single declaration, then it corresponds
2848 * to a simple array access. Otherwise, it corresponds to a member access,
2849 * with the declaration for the substructure following that of the containing
2850 * structure in the sequence of declarations.
2851 * We start with the outermost substructure and then combine it with
2852 * information from the inner structures.
2854 * Additionally, keep track of all required types in "types".
2856 struct pet_array *PetScan::extract_array(__isl_keep isl_id_list *decls,
2857 PetTypes *types, __isl_keep pet_context *pc)
2859 int i, n;
2860 isl_id *id;
2861 struct pet_array *array;
2863 id = isl_id_list_get_id(decls, 0);
2864 array = extract_array(id, types, pc);
2865 isl_id_free(id);
2867 n = isl_id_list_n_id(decls);
2868 for (i = 1; i < n; ++i) {
2869 struct pet_array *parent;
2870 const char *base_name, *field_name;
2871 char *product_name;
2873 parent = array;
2874 id = isl_id_list_get_id(decls, i);
2875 array = extract_array(id, types, pc);
2876 isl_id_free(id);
2877 if (!array)
2878 return pet_array_free(parent);
2880 base_name = isl_set_get_tuple_name(parent->extent);
2881 field_name = isl_set_get_tuple_name(array->extent);
2882 product_name = pet_array_member_access_name(ctx,
2883 base_name, field_name);
2885 array->extent = isl_set_product(isl_set_copy(parent->extent),
2886 array->extent);
2887 if (product_name)
2888 array->extent = isl_set_set_tuple_name(array->extent,
2889 product_name);
2890 array->context = isl_set_intersect(array->context,
2891 isl_set_copy(parent->context));
2893 pet_array_free(parent);
2894 free(product_name);
2896 if (!array->extent || !array->context || !product_name)
2897 return pet_array_free(array);
2900 return array;
2903 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2904 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2905 std::set<TypeDecl *> &types_done);
2906 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2907 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2908 std::set<TypeDecl *> &types_done);
2910 /* For each of the fields of "decl" that is itself a record type
2911 * or a typedef, or an array of such type, add a corresponding pet_type
2912 * to "scop".
2914 static struct pet_scop *add_field_types(isl_ctx *ctx, struct pet_scop *scop,
2915 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2916 std::set<TypeDecl *> &types_done)
2918 RecordDecl::field_iterator it;
2920 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
2921 QualType type = it->getType();
2923 type = pet_clang_base_or_typedef_type(type);
2924 if (isa<TypedefType>(type)) {
2925 TypedefNameDecl *typedefdecl;
2927 typedefdecl = cast<TypedefType>(type)->getDecl();
2928 scop = add_type(ctx, scop, typedefdecl,
2929 PP, types, types_done);
2930 } else if (type->isRecordType()) {
2931 RecordDecl *record;
2933 record = pet_clang_record_decl(type);
2934 scop = add_type(ctx, scop, record,
2935 PP, types, types_done);
2939 return scop;
2942 /* Add a pet_type corresponding to "decl" to "scop", provided
2943 * it is a member of types.records and it has not been added before
2944 * (i.e., it is not a member of "types_done").
2946 * Since we want the user to be able to print the types
2947 * in the order in which they appear in the scop, we need to
2948 * make sure that types of fields in a structure appear before
2949 * that structure. We therefore call ourselves recursively
2950 * through add_field_types on the types of all record subfields.
2952 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2953 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2954 std::set<TypeDecl *> &types_done)
2956 string s;
2957 llvm::raw_string_ostream S(s);
2959 if (types.records.find(decl) == types.records.end())
2960 return scop;
2961 if (types_done.find(decl) != types_done.end())
2962 return scop;
2964 add_field_types(ctx, scop, decl, PP, types, types_done);
2966 if (strlen(decl->getName().str().c_str()) == 0)
2967 return scop;
2969 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2970 S.str();
2972 scop->types[scop->n_type] = pet_type_alloc(ctx,
2973 decl->getName().str().c_str(), s.c_str());
2974 if (!scop->types[scop->n_type])
2975 return pet_scop_free(scop);
2977 types_done.insert(decl);
2979 scop->n_type++;
2981 return scop;
2984 /* Add a pet_type corresponding to "decl" to "scop", provided
2985 * it is a member of types.typedefs and it has not been added before
2986 * (i.e., it is not a member of "types_done").
2988 * If the underlying type is a structure, then we print the typedef
2989 * ourselves since clang does not print the definition of the structure
2990 * in the typedef. We also make sure in this case that the types of
2991 * the fields in the structure are added first.
2992 * Since the definition of the structure also gets printed this way,
2993 * add it to types_done such that it will not be printed again,
2994 * not even without the typedef.
2996 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2997 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2998 std::set<TypeDecl *> &types_done)
3000 string s;
3001 llvm::raw_string_ostream S(s);
3002 QualType qt = decl->getUnderlyingType();
3004 if (types.typedefs.find(decl) == types.typedefs.end())
3005 return scop;
3006 if (types_done.find(decl) != types_done.end())
3007 return scop;
3009 if (qt->isRecordType()) {
3010 RecordDecl *rec = pet_clang_record_decl(qt);
3012 add_field_types(ctx, scop, rec, PP, types, types_done);
3013 S << "typedef ";
3014 rec->print(S, PrintingPolicy(PP.getLangOpts()));
3015 S << " ";
3016 S << decl->getName();
3017 types_done.insert(rec);
3018 } else {
3019 decl->print(S, PrintingPolicy(PP.getLangOpts()));
3021 S.str();
3023 scop->types[scop->n_type] = pet_type_alloc(ctx,
3024 decl->getName().str().c_str(), s.c_str());
3025 if (!scop->types[scop->n_type])
3026 return pet_scop_free(scop);
3028 types_done.insert(decl);
3030 scop->n_type++;
3032 return scop;
3035 /* Construct a list of pet_arrays, one for each array (or scalar)
3036 * accessed inside "scop", add this list to "scop" and return the result.
3037 * The upper bounds of the arrays are converted to affine expressions
3038 * within the context "pc".
3040 * The context of "scop" is updated with the intersection of
3041 * the contexts of all arrays, i.e., constraints on the parameters
3042 * that ensure that the arrays have a valid (non-negative) size.
3044 * If any of the extracted arrays refers to a member access or
3045 * has a typedef'd type as base type,
3046 * then also add the required types to "scop".
3047 * The typedef types are printed first because their definitions
3048 * may include the definition of a struct and these struct definitions
3049 * should not be printed separately. While the typedef definition
3050 * is being printed, the struct is marked as having been printed as well,
3051 * such that the later printing of the struct by itself can be prevented.
3053 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
3054 __isl_keep pet_context *pc)
3056 int i, n;
3057 array_desc_set arrays;
3058 array_desc_set::iterator it;
3059 PetTypes types;
3060 std::set<TypeDecl *> types_done;
3061 std::set<clang::RecordDecl *, less_name>::iterator records_it;
3062 std::set<clang::TypedefNameDecl *, less_name>::iterator typedefs_it;
3063 int n_array;
3064 struct pet_array **scop_arrays;
3066 if (!scop)
3067 return NULL;
3069 pet_scop_collect_arrays(scop, arrays);
3070 if (arrays.size() == 0)
3071 return scop;
3073 n_array = scop->n_array;
3075 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3076 n_array + arrays.size());
3077 if (!scop_arrays)
3078 goto error;
3079 scop->arrays = scop_arrays;
3081 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3082 struct pet_array *array;
3083 array = extract_array(*it, &types, pc);
3084 scop->arrays[n_array + i] = array;
3085 if (!scop->arrays[n_array + i])
3086 goto error;
3087 scop->n_array++;
3088 scop->context = isl_set_intersect(scop->context,
3089 isl_set_copy(array->context));
3090 if (!scop->context)
3091 goto error;
3094 n = types.records.size() + types.typedefs.size();
3095 if (n == 0)
3096 return scop;
3098 scop->types = isl_alloc_array(ctx, struct pet_type *, n);
3099 if (!scop->types)
3100 goto error;
3102 for (typedefs_it = types.typedefs.begin();
3103 typedefs_it != types.typedefs.end(); ++typedefs_it)
3104 scop = add_type(ctx, scop, *typedefs_it, PP, types, types_done);
3106 for (records_it = types.records.begin();
3107 records_it != types.records.end(); ++records_it)
3108 scop = add_type(ctx, scop, *records_it, PP, types, types_done);
3110 return scop;
3111 error:
3112 pet_scop_free(scop);
3113 return NULL;
3116 /* Bound all parameters in scop->context to the possible values
3117 * of the corresponding C variable.
3119 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
3121 int n;
3123 if (!scop)
3124 return NULL;
3126 n = isl_set_dim(scop->context, isl_dim_param);
3127 for (int i = 0; i < n; ++i) {
3128 isl_id *id;
3129 ValueDecl *decl;
3131 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
3132 if (pet_nested_in_id(id)) {
3133 isl_id_free(id);
3134 isl_die(isl_set_get_ctx(scop->context),
3135 isl_error_internal,
3136 "unresolved nested parameter", goto error);
3138 decl = pet_id_get_decl(id);
3139 isl_id_free(id);
3141 scop->context = set_parameter_bounds(scop->context, i, decl);
3143 if (!scop->context)
3144 goto error;
3147 return scop;
3148 error:
3149 pet_scop_free(scop);
3150 return NULL;
3153 /* Construct a pet_scop from the given function.
3155 * If the scop was delimited by scop and endscop pragmas, then we override
3156 * the file offsets by those derived from the pragmas.
3158 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3160 pet_scop *scop;
3161 Stmt *stmt;
3163 stmt = fd->getBody();
3165 if (options->autodetect) {
3166 set_current_stmt(stmt);
3167 scop = extract_scop(extract(stmt, true));
3168 } else {
3169 current_line = loc.start_line;
3170 scop = scan(stmt);
3171 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
3173 scop = add_parameter_bounds(scop);
3174 scop = pet_scop_gist(scop, value_bounds);
3176 return scop;
3179 /* Update this->last_line and this->current_line based on the fact
3180 * that we are about to consider "stmt".
3182 void PetScan::set_current_stmt(Stmt *stmt)
3184 SourceLocation loc = stmt->getLocStart();
3185 SourceManager &SM = PP.getSourceManager();
3187 last_line = current_line;
3188 current_line = SM.getExpansionLineNumber(loc);
3191 /* Is the current statement marked by an independent pragma?
3192 * That is, is there an independent pragma on a line between
3193 * the line of the current statement and the line of the previous statement.
3194 * The search is not implemented very efficiently. We currently
3195 * assume that there are only a few independent pragmas, if any.
3197 bool PetScan::is_current_stmt_marked_independent()
3199 for (unsigned i = 0; i < independent.size(); ++i) {
3200 unsigned line = independent[i].line;
3202 if (last_line < line && line < current_line)
3203 return true;
3206 return false;