pet.cc: update to CompilerInvocation::setLangDefaults taking 5 arguments
[pet.git] / scan.cc
blobb2a3af9304af99adc3d08199c76df2ec04065bc8
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 #ifdef GETTYPEINFORETURNSTYPEINFO
154 static int size_in_bytes(ASTContext &context, QualType type)
156 return context.getTypeInfo(type).Width / 8;
159 #else
161 static int size_in_bytes(ASTContext &context, QualType type)
163 return context.getTypeInfo(type).first / 8;
166 #endif
168 /* Check if the element type corresponding to the given array type
169 * has a const qualifier.
171 static bool const_base(QualType qt)
173 const Type *type = qt.getTypePtr();
175 if (type->isPointerType())
176 return const_base(type->getPointeeType());
177 if (type->isArrayType()) {
178 const ArrayType *atype;
179 type = type->getCanonicalTypeInternal().getTypePtr();
180 atype = cast<ArrayType>(type);
181 return const_base(atype->getElementType());
184 return qt.isConstQualified();
187 PetScan::~PetScan()
189 std::map<const Type *, pet_expr *>::iterator it;
190 std::map<FunctionDecl *, pet_function_summary *>::iterator it_s;
192 for (it = type_size.begin(); it != type_size.end(); ++it)
193 pet_expr_free(it->second);
194 for (it_s = summary_cache.begin(); it_s != summary_cache.end(); ++it_s)
195 pet_function_summary_free(it_s->second);
197 isl_id_to_pet_expr_free(id_size);
198 isl_union_map_free(value_bounds);
201 /* Report a diagnostic on the range "range", unless autodetect is set.
203 void PetScan::report(SourceRange range, unsigned id)
205 if (options->autodetect)
206 return;
208 SourceLocation loc = range.getBegin();
209 DiagnosticsEngine &diag = PP.getDiagnostics();
210 DiagnosticBuilder B = diag.Report(loc, id) << range;
213 /* Report a diagnostic on "stmt", unless autodetect is set.
215 void PetScan::report(Stmt *stmt, unsigned id)
217 report(stmt->getSourceRange(), id);
220 /* Report a diagnostic on "decl", unless autodetect is set.
222 void PetScan::report(Decl *decl, unsigned id)
224 report(decl->getSourceRange(), id);
227 /* Called if we found something we (currently) cannot handle.
228 * We'll provide more informative warnings later.
230 * We only actually complain if autodetect is false.
232 void PetScan::unsupported(Stmt *stmt)
234 DiagnosticsEngine &diag = PP.getDiagnostics();
235 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
236 "unsupported");
237 report(stmt, id);
240 /* Report an unsupported unary operator, unless autodetect is set.
242 void PetScan::report_unsupported_unary_operator(Stmt *stmt)
244 DiagnosticsEngine &diag = PP.getDiagnostics();
245 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
246 "this type of unary operator is not supported");
247 report(stmt, id);
250 /* Report an unsupported statement type, unless autodetect is set.
252 void PetScan::report_unsupported_statement_type(Stmt *stmt)
254 DiagnosticsEngine &diag = PP.getDiagnostics();
255 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
256 "this type of statement is not supported");
257 report(stmt, id);
260 /* Report a missing prototype, unless autodetect is set.
262 void PetScan::report_prototype_required(Stmt *stmt)
264 DiagnosticsEngine &diag = PP.getDiagnostics();
265 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
266 "prototype required");
267 report(stmt, id);
270 /* Report a missing increment, unless autodetect is set.
272 void PetScan::report_missing_increment(Stmt *stmt)
274 DiagnosticsEngine &diag = PP.getDiagnostics();
275 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
276 "missing increment");
277 report(stmt, id);
280 /* Report a missing summary function, unless autodetect is set.
282 void PetScan::report_missing_summary_function(Stmt *stmt)
284 DiagnosticsEngine &diag = PP.getDiagnostics();
285 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
286 "missing summary function");
287 report(stmt, id);
290 /* Report a missing summary function body, unless autodetect is set.
292 void PetScan::report_missing_summary_function_body(Stmt *stmt)
294 DiagnosticsEngine &diag = PP.getDiagnostics();
295 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
296 "missing summary function body");
297 report(stmt, id);
300 /* Report an unsupported argument in a call to an inlined function,
301 * unless autodetect is set.
303 void PetScan::report_unsupported_inline_function_argument(Stmt *stmt)
305 DiagnosticsEngine &diag = PP.getDiagnostics();
306 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
307 "unsupported inline function call argument");
308 report(stmt, id);
311 /* Report an unsupported type of declaration, unless autodetect is set.
313 void PetScan::report_unsupported_declaration(Decl *decl)
315 DiagnosticsEngine &diag = PP.getDiagnostics();
316 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
317 "unsupported declaration");
318 report(decl, id);
321 /* Extract an integer from "val", which is assumed to be non-negative.
323 static __isl_give isl_val *extract_unsigned(isl_ctx *ctx,
324 const llvm::APInt &val)
326 unsigned n;
327 const uint64_t *data;
329 data = val.getRawData();
330 n = val.getNumWords();
331 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
334 /* Extract an integer from "val". If "is_signed" is set, then "val"
335 * is signed. Otherwise it it unsigned.
337 static __isl_give isl_val *extract_int(isl_ctx *ctx, bool is_signed,
338 llvm::APInt val)
340 int is_negative = is_signed && val.isNegative();
341 isl_val *v;
343 if (is_negative)
344 val = -val;
346 v = extract_unsigned(ctx, val);
348 if (is_negative)
349 v = isl_val_neg(v);
350 return v;
353 /* Extract an integer from "expr".
355 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
357 const Type *type = expr->getType().getTypePtr();
358 bool is_signed = type->hasSignedIntegerRepresentation();
360 return ::extract_int(ctx, is_signed, expr->getValue());
363 /* Extract an integer from "expr".
364 * Return NULL if "expr" does not (obviously) represent an integer.
366 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
368 return extract_int(expr->getSubExpr());
371 /* Extract an integer from "expr".
372 * Return NULL if "expr" does not (obviously) represent an integer.
374 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
376 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
377 return extract_int(ctx, cast<IntegerLiteral>(expr));
378 if (expr->getStmtClass() == Stmt::ParenExprClass)
379 return extract_int(cast<ParenExpr>(expr));
381 unsupported(expr);
382 return NULL;
385 /* Extract a pet_expr from the APInt "val", which is assumed
386 * to be non-negative.
388 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
390 return pet_expr_new_int(extract_unsigned(ctx, val));
393 /* Return the number of bits needed to represent the type of "decl",
394 * if it is an integer type. Otherwise return 0.
395 * If qt is signed then return the opposite of the number of bits.
397 static int get_type_size(ValueDecl *decl)
399 return pet_clang_get_type_size(decl->getType(), decl->getASTContext());
402 /* Bound parameter "pos" of "set" to the possible values of "decl".
404 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
405 unsigned pos, ValueDecl *decl)
407 int type_size;
408 isl_ctx *ctx;
409 isl_val *bound;
411 ctx = isl_set_get_ctx(set);
412 type_size = get_type_size(decl);
413 if (type_size == 0)
414 isl_die(ctx, isl_error_invalid, "not an integer type",
415 return isl_set_free(set));
416 if (type_size > 0) {
417 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
418 bound = isl_val_int_from_ui(ctx, type_size);
419 bound = isl_val_2exp(bound);
420 bound = isl_val_sub_ui(bound, 1);
421 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
422 } else {
423 bound = isl_val_int_from_ui(ctx, -type_size - 1);
424 bound = isl_val_2exp(bound);
425 bound = isl_val_sub_ui(bound, 1);
426 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
427 isl_val_copy(bound));
428 bound = isl_val_neg(bound);
429 bound = isl_val_sub_ui(bound, 1);
430 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
433 return set;
436 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
438 return extract_index_expr(expr->getSubExpr());
441 /* Return the depth of the array accessed by the index expression "index".
442 * If "index" is an affine expression, i.e., if it does not access
443 * any array, then return 1.
444 * If "index" represent a member access, i.e., if its range is a wrapped
445 * relation, then return the sum of the depth of the array of structures
446 * and that of the member inside the structure.
448 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
450 isl_id *id;
451 ValueDecl *decl;
453 if (!index)
454 return -1;
456 if (isl_multi_pw_aff_range_is_wrapping(index)) {
457 int domain_depth, range_depth;
458 isl_multi_pw_aff *domain, *range;
460 domain = isl_multi_pw_aff_copy(index);
461 domain = isl_multi_pw_aff_range_factor_domain(domain);
462 domain_depth = extract_depth(domain);
463 isl_multi_pw_aff_free(domain);
464 range = isl_multi_pw_aff_copy(index);
465 range = isl_multi_pw_aff_range_factor_range(range);
466 range_depth = extract_depth(range);
467 isl_multi_pw_aff_free(range);
469 return domain_depth + range_depth;
472 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
473 return 1;
475 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
476 if (!id)
477 return -1;
478 decl = pet_id_get_decl(id);
479 isl_id_free(id);
481 return pet_clang_array_depth(decl->getType());
484 /* Return the depth of the array accessed by the access expression "expr".
486 static int extract_depth(__isl_keep pet_expr *expr)
488 isl_multi_pw_aff *index;
489 int depth;
491 index = pet_expr_access_get_index(expr);
492 depth = extract_depth(index);
493 isl_multi_pw_aff_free(index);
495 return depth;
498 /* Construct a pet_expr representing an index expression for an access
499 * to the variable referenced by "expr".
501 * If "expr" references an enum constant, then return an integer expression
502 * instead, representing the value of the enum constant.
504 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
506 return extract_index_expr(expr->getDecl());
509 /* Construct a pet_expr representing an index expression for an access
510 * to the variable "decl".
512 * If "decl" is an enum constant, then we return an integer expression
513 * instead, representing the value of the enum constant.
515 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
517 isl_id *id;
519 if (isa<EnumConstantDecl>(decl))
520 return extract_expr(cast<EnumConstantDecl>(decl));
522 id = pet_id_from_decl(ctx, decl);
523 return pet_id_create_index_expr(id);
526 /* Construct a pet_expr representing the index expression "expr"
527 * Return NULL on error.
529 * If "expr" is a reference to an enum constant, then return
530 * an integer expression instead, representing the value of the enum constant.
532 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
534 switch (expr->getStmtClass()) {
535 case Stmt::ImplicitCastExprClass:
536 return extract_index_expr(cast<ImplicitCastExpr>(expr));
537 case Stmt::DeclRefExprClass:
538 return extract_index_expr(cast<DeclRefExpr>(expr));
539 case Stmt::ArraySubscriptExprClass:
540 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
541 case Stmt::IntegerLiteralClass:
542 return extract_expr(cast<IntegerLiteral>(expr));
543 case Stmt::MemberExprClass:
544 return extract_index_expr(cast<MemberExpr>(expr));
545 default:
546 unsupported(expr);
548 return NULL;
551 /* Extract an index expression from the given array subscript expression.
553 * We first extract an index expression from the base.
554 * This will result in an index expression with a range that corresponds
555 * to the earlier indices.
556 * We then extract the current index and let
557 * pet_expr_access_subscript combine the two.
559 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
561 Expr *base = expr->getBase();
562 Expr *idx = expr->getIdx();
563 pet_expr *index;
564 pet_expr *base_expr;
566 base_expr = extract_index_expr(base);
567 index = extract_expr(idx);
569 base_expr = pet_expr_access_subscript(base_expr, index);
571 return base_expr;
574 /* Extract an index expression from a member expression.
576 * If the base access (to the structure containing the member)
577 * is of the form
579 * A[..]
581 * and the member is called "f", then the member access is of
582 * the form
584 * A_f[A[..] -> f[]]
586 * If the member access is to an anonymous struct, then simply return
588 * A[..]
590 * If the member access in the source code is of the form
592 * A->f
594 * then it is treated as
596 * A[0].f
598 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
600 Expr *base = expr->getBase();
601 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
602 pet_expr *base_index;
603 isl_id *id;
605 base_index = extract_index_expr(base);
607 if (expr->isArrow()) {
608 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
609 base_index = pet_expr_access_subscript(base_index, index);
612 if (field->isAnonymousStructOrUnion())
613 return base_index;
615 id = pet_id_from_decl(ctx, field);
617 return pet_expr_access_member(base_index, id);
620 /* Mark the given access pet_expr as a write.
622 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
624 access = pet_expr_access_set_write(access, 1);
625 access = pet_expr_access_set_read(access, 0);
627 return access;
630 /* Mark the given (read) access pet_expr as also possibly being written.
631 * That is, initialize the may write access relation from the may read relation
632 * and initialize the must write access relation to the empty relation.
634 static __isl_give pet_expr *mark_may_write(__isl_take pet_expr *expr)
636 isl_union_map *access;
637 isl_union_map *empty;
639 access = pet_expr_access_get_dependent_access(expr,
640 pet_expr_access_may_read);
641 empty = isl_union_map_empty(isl_union_map_get_space(access));
642 expr = pet_expr_access_set_access(expr, pet_expr_access_may_write,
643 access);
644 expr = pet_expr_access_set_access(expr, pet_expr_access_must_write,
645 empty);
647 return expr;
650 /* Construct a pet_expr representing a unary operator expression.
652 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
654 int type_size;
655 pet_expr *arg;
656 enum pet_op_type op;
658 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
659 if (op == pet_op_last) {
660 report_unsupported_unary_operator(expr);
661 return NULL;
664 arg = extract_expr(expr->getSubExpr());
666 if (expr->isIncrementDecrementOp() &&
667 pet_expr_get_type(arg) == pet_expr_access) {
668 arg = mark_write(arg);
669 arg = pet_expr_access_set_read(arg, 1);
672 type_size = pet_clang_get_type_size(expr->getType(), ast_context);
673 return pet_expr_new_unary(type_size, op, arg);
676 /* Construct a pet_expr representing a binary operator expression.
678 * If the top level operator is an assignment and the LHS is an access,
679 * then we mark that access as a write. If the operator is a compound
680 * assignment, the access is marked as both a read and a write.
682 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
684 int type_size;
685 pet_expr *lhs, *rhs;
686 enum pet_op_type op;
688 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
689 if (op == pet_op_last) {
690 unsupported(expr);
691 return NULL;
694 lhs = extract_expr(expr->getLHS());
695 rhs = extract_expr(expr->getRHS());
697 if (expr->isAssignmentOp() &&
698 pet_expr_get_type(lhs) == pet_expr_access) {
699 lhs = mark_write(lhs);
700 if (expr->isCompoundAssignmentOp())
701 lhs = pet_expr_access_set_read(lhs, 1);
704 type_size = pet_clang_get_type_size(expr->getType(), ast_context);
705 return pet_expr_new_binary(type_size, op, lhs, rhs);
708 /* Construct a pet_tree for a variable declaration and
709 * add the declaration to the list of declarations
710 * inside the current compound statement.
712 __isl_give pet_tree *PetScan::extract(Decl *decl)
714 VarDecl *vd;
715 pet_expr *lhs, *rhs;
716 pet_tree *tree;
718 if (!isa<VarDecl>(decl)) {
719 report_unsupported_declaration(decl);
720 return NULL;
723 vd = cast<VarDecl>(decl);
724 declarations.push_back(vd);
726 lhs = extract_access_expr(vd);
727 lhs = mark_write(lhs);
728 if (!vd->getInit())
729 tree = pet_tree_new_decl(lhs);
730 else {
731 rhs = extract_expr(vd->getInit());
732 tree = pet_tree_new_decl_init(lhs, rhs);
735 return tree;
738 /* Construct a pet_tree for a variable declaration statement.
739 * If the declaration statement declares multiple variables,
740 * then return a group of pet_trees, one for each declared variable.
742 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
744 pet_tree *tree;
745 unsigned n;
747 if (!stmt->isSingleDecl()) {
748 const DeclGroup &group = stmt->getDeclGroup().getDeclGroup();
749 n = group.size();
750 tree = pet_tree_new_block(ctx, 0, n);
752 for (unsigned i = 0; i < n; ++i) {
753 pet_tree *tree_i;
754 pet_loc *loc;
756 tree_i = extract(group[i]);
757 loc = construct_pet_loc(group[i]->getSourceRange(),
758 false);
759 tree_i = pet_tree_set_loc(tree_i, loc);
760 tree = pet_tree_block_add_child(tree, tree_i);
763 return tree;
766 return extract(stmt->getSingleDecl());
769 /* Construct a pet_expr representing a conditional operation.
771 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
773 pet_expr *cond, *lhs, *rhs;
775 cond = extract_expr(expr->getCond());
776 lhs = extract_expr(expr->getTrueExpr());
777 rhs = extract_expr(expr->getFalseExpr());
779 return pet_expr_new_ternary(cond, lhs, rhs);
782 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
784 return extract_expr(expr->getSubExpr());
787 /* Construct a pet_expr representing a floating point value.
789 * If the floating point literal does not appear in a macro,
790 * then we use the original representation in the source code
791 * as the string representation. Otherwise, we use the pretty
792 * printer to produce a string representation.
794 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
796 double d;
797 string s;
798 const LangOptions &LO = PP.getLangOpts();
799 SourceLocation loc = expr->getLocation();
801 if (!loc.isMacroID()) {
802 SourceManager &SM = PP.getSourceManager();
803 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
804 s = string(SM.getCharacterData(loc), len);
805 } else {
806 llvm::raw_string_ostream S(s);
807 expr->printPretty(S, 0, PrintingPolicy(LO));
808 S.str();
810 d = expr->getValueAsApproximateDouble();
811 return pet_expr_new_double(ctx, d, s.c_str());
814 /* Convert the index expression "index" into an access pet_expr of type "qt".
816 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
817 __isl_take pet_expr *index)
819 int depth;
820 int type_size;
822 depth = extract_depth(index);
823 type_size = pet_clang_get_type_size(qt, ast_context);
825 index = pet_expr_set_type_size(index, type_size);
826 index = pet_expr_access_set_depth(index, depth);
828 return index;
831 /* Extract an index expression from "expr" and then convert it into
832 * an access pet_expr.
834 * If "expr" is a reference to an enum constant, then return
835 * an integer expression instead, representing the value of the enum constant.
837 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
839 pet_expr *index;
841 index = extract_index_expr(expr);
843 if (pet_expr_get_type(index) == pet_expr_int)
844 return index;
846 return extract_access_expr(expr->getType(), index);
849 /* Extract an index expression from "decl" and then convert it into
850 * an access pet_expr.
852 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
854 return extract_access_expr(decl->getType(), extract_index_expr(decl));
857 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
859 return extract_expr(expr->getSubExpr());
862 /* Extract an assume statement from the argument "expr"
863 * of a __builtin_assume or __pencil_assume statement.
865 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
867 return pet_expr_new_unary(0, pet_op_assume, extract_expr(expr));
870 /* If "expr" is an address-of operator, then return its argument.
871 * Otherwise, return NULL.
873 static Expr *extract_addr_of_arg(Expr *expr)
875 UnaryOperator *op;
877 if (expr->getStmtClass() != Stmt::UnaryOperatorClass)
878 return NULL;
879 op = cast<UnaryOperator>(expr);
880 if (op->getOpcode() != UO_AddrOf)
881 return NULL;
882 return op->getSubExpr();
885 /* Construct a pet_expr corresponding to the function call argument "expr".
886 * The argument appears in position "pos" of a call to function "fd".
888 * If we are passing along a pointer to an array element
889 * or an entire row or even higher dimensional slice of an array,
890 * then the function being called may write into the array.
892 * We assume here that if the function is declared to take a pointer
893 * to a const type, then the function may only perform a read
894 * and that otherwise, it may either perform a read or a write (or both).
895 * We only perform this check if "detect_writes" is set.
897 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
898 Expr *expr, bool detect_writes)
900 Expr *arg;
901 pet_expr *res;
902 int is_addr = 0, is_partial = 0;
904 expr = pet_clang_strip_casts(expr);
905 arg = extract_addr_of_arg(expr);
906 if (arg) {
907 is_addr = 1;
908 expr = arg;
910 res = extract_expr(expr);
911 if (!res)
912 return NULL;
913 if (pet_clang_array_depth(expr->getType()) > 0)
914 is_partial = 1;
915 if (detect_writes && (is_addr || is_partial) &&
916 pet_expr_get_type(res) == pet_expr_access) {
917 ParmVarDecl *parm;
918 if (!fd->hasPrototype()) {
919 report_prototype_required(expr);
920 return pet_expr_free(res);
922 parm = fd->getParamDecl(pos);
923 if (!const_base(parm->getType()))
924 res = mark_may_write(res);
927 if (is_addr)
928 res = pet_expr_new_unary(0, pet_op_address_of, res);
929 return res;
932 /* Find the first FunctionDecl with the given name.
933 * "call" is the corresponding call expression and is only used
934 * for reporting errors.
936 * Return NULL on error.
938 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
940 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
941 DeclContext::decl_iterator begin = tu->decls_begin();
942 DeclContext::decl_iterator end = tu->decls_end();
943 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
944 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
945 if (!fd)
946 continue;
947 if (fd->getName().str().compare(name) != 0)
948 continue;
949 if (fd->hasBody())
950 return fd;
951 report_missing_summary_function_body(call);
952 return NULL;
954 report_missing_summary_function(call);
955 return NULL;
958 /* Return the FunctionDecl for the summary function associated to the
959 * function called by "call".
961 * In particular, if the pencil option is set, then
962 * search for an annotate attribute formatted as
963 * "pencil_access(name)", where "name" is the name of the summary function.
965 * If no summary function was specified, then return the FunctionDecl
966 * that is actually being called.
968 * Return NULL on error.
970 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
972 FunctionDecl *decl = call->getDirectCallee();
973 if (!decl)
974 return NULL;
976 if (!options->pencil)
977 return decl;
979 specific_attr_iterator<AnnotateAttr> begin, end, i;
980 begin = decl->specific_attr_begin<AnnotateAttr>();
981 end = decl->specific_attr_end<AnnotateAttr>();
982 for (i = begin; i != end; ++i) {
983 string attr = (*i)->getAnnotation().str();
985 const char prefix[] = "pencil_access(";
986 size_t start = attr.find(prefix);
987 if (start == string::npos)
988 continue;
989 start += strlen(prefix);
990 string name = attr.substr(start, attr.find(')') - start);
992 return find_decl_from_name(call, name);
995 return decl;
998 /* Is "name" the name of an assume statement?
999 * "pencil" indicates whether pencil builtins and pragmas should be supported.
1000 * "__builtin_assume" is always accepted.
1001 * If "pencil" is set, then "__pencil_assume" is also accepted.
1003 static bool is_assume(int pencil, const string &name)
1005 if (name == "__builtin_assume")
1006 return true;
1007 return pencil && name == "__pencil_assume";
1010 /* Construct a pet_expr representing a function call.
1012 * In the special case of a "call" to __builtin_assume or __pencil_assume,
1013 * construct an assume expression instead.
1015 * In the case of a "call" to __pencil_kill, the arguments
1016 * are neither read nor written (only killed), so there
1017 * is no need to check for writes to these arguments.
1019 * __pencil_assume and __pencil_kill are only recognized
1020 * when the pencil option is set.
1022 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1024 pet_expr *res = NULL;
1025 FunctionDecl *fd;
1026 string name;
1027 unsigned n_arg;
1028 bool is_kill;
1030 fd = expr->getDirectCallee();
1031 if (!fd) {
1032 unsupported(expr);
1033 return NULL;
1036 name = fd->getDeclName().getAsString();
1037 n_arg = expr->getNumArgs();
1039 if (n_arg == 1 && is_assume(options->pencil, name))
1040 return extract_assume(expr->getArg(0));
1041 is_kill = options->pencil && name == "__pencil_kill";
1043 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1044 if (!res)
1045 return NULL;
1047 for (unsigned i = 0; i < n_arg; ++i) {
1048 Expr *arg = expr->getArg(i);
1049 res = pet_expr_set_arg(res, i,
1050 PetScan::extract_argument(fd, i, arg, !is_kill));
1053 fd = get_summary_function(expr);
1054 if (!fd)
1055 return pet_expr_free(res);
1057 res = set_summary(res, fd);
1059 return res;
1062 /* Construct a pet_expr representing a (C style) cast.
1064 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1066 pet_expr *arg;
1067 QualType type;
1069 arg = extract_expr(expr->getSubExpr());
1070 if (!arg)
1071 return NULL;
1073 type = expr->getTypeAsWritten();
1074 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1077 /* Construct a pet_expr representing an integer.
1079 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1081 return pet_expr_new_int(extract_int(expr));
1084 /* Construct a pet_expr representing the integer enum constant "ecd".
1086 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
1088 isl_val *v;
1089 const llvm::APSInt &init = ecd->getInitVal();
1090 v = ::extract_int(ctx, init.isSigned(), init);
1091 return pet_expr_new_int(v);
1094 /* Try and construct a pet_expr representing "expr".
1096 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1098 switch (expr->getStmtClass()) {
1099 case Stmt::UnaryOperatorClass:
1100 return extract_expr(cast<UnaryOperator>(expr));
1101 case Stmt::CompoundAssignOperatorClass:
1102 case Stmt::BinaryOperatorClass:
1103 return extract_expr(cast<BinaryOperator>(expr));
1104 case Stmt::ImplicitCastExprClass:
1105 return extract_expr(cast<ImplicitCastExpr>(expr));
1106 case Stmt::ArraySubscriptExprClass:
1107 case Stmt::DeclRefExprClass:
1108 case Stmt::MemberExprClass:
1109 return extract_access_expr(expr);
1110 case Stmt::IntegerLiteralClass:
1111 return extract_expr(cast<IntegerLiteral>(expr));
1112 case Stmt::FloatingLiteralClass:
1113 return extract_expr(cast<FloatingLiteral>(expr));
1114 case Stmt::ParenExprClass:
1115 return extract_expr(cast<ParenExpr>(expr));
1116 case Stmt::ConditionalOperatorClass:
1117 return extract_expr(cast<ConditionalOperator>(expr));
1118 case Stmt::CallExprClass:
1119 return extract_expr(cast<CallExpr>(expr));
1120 case Stmt::CStyleCastExprClass:
1121 return extract_expr(cast<CStyleCastExpr>(expr));
1122 default:
1123 unsupported(expr);
1125 return NULL;
1128 /* Check if the given initialization statement is an assignment.
1129 * If so, return that assignment. Otherwise return NULL.
1131 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1133 BinaryOperator *ass;
1135 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1136 return NULL;
1138 ass = cast<BinaryOperator>(init);
1139 if (ass->getOpcode() != BO_Assign)
1140 return NULL;
1142 return ass;
1145 /* Check if the given initialization statement is a declaration
1146 * of a single variable.
1147 * If so, return that declaration. Otherwise return NULL.
1149 Decl *PetScan::initialization_declaration(Stmt *init)
1151 DeclStmt *decl;
1153 if (init->getStmtClass() != Stmt::DeclStmtClass)
1154 return NULL;
1156 decl = cast<DeclStmt>(init);
1158 if (!decl->isSingleDecl())
1159 return NULL;
1161 return decl->getSingleDecl();
1164 /* Given the assignment operator in the initialization of a for loop,
1165 * extract the induction variable, i.e., the (integer)variable being
1166 * assigned.
1168 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1170 Expr *lhs;
1171 DeclRefExpr *ref;
1172 ValueDecl *decl;
1173 const Type *type;
1175 lhs = init->getLHS();
1176 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1177 unsupported(init);
1178 return NULL;
1181 ref = cast<DeclRefExpr>(lhs);
1182 decl = ref->getDecl();
1183 type = decl->getType().getTypePtr();
1185 if (!type->isIntegerType()) {
1186 unsupported(lhs);
1187 return NULL;
1190 return decl;
1193 /* Given the initialization statement of a for loop and the single
1194 * declaration in this initialization statement,
1195 * extract the induction variable, i.e., the (integer) variable being
1196 * declared.
1198 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1200 VarDecl *vd;
1202 vd = cast<VarDecl>(decl);
1204 const QualType type = vd->getType();
1205 if (!type->isIntegerType()) {
1206 unsupported(init);
1207 return NULL;
1210 if (!vd->getInit()) {
1211 unsupported(init);
1212 return NULL;
1215 return vd;
1218 /* Check that op is of the form iv++ or iv--.
1219 * Return a pet_expr representing "1" or "-1" accordingly.
1221 __isl_give pet_expr *PetScan::extract_unary_increment(
1222 clang::UnaryOperator *op, clang::ValueDecl *iv)
1224 Expr *sub;
1225 DeclRefExpr *ref;
1226 isl_val *v;
1228 if (!op->isIncrementDecrementOp()) {
1229 unsupported(op);
1230 return NULL;
1233 sub = op->getSubExpr();
1234 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1235 unsupported(op);
1236 return NULL;
1239 ref = cast<DeclRefExpr>(sub);
1240 if (ref->getDecl() != iv) {
1241 unsupported(op);
1242 return NULL;
1245 if (op->isIncrementOp())
1246 v = isl_val_one(ctx);
1247 else
1248 v = isl_val_negone(ctx);
1250 return pet_expr_new_int(v);
1253 /* Check if op is of the form
1255 * iv = expr
1257 * and return the increment "expr - iv" as a pet_expr.
1259 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1260 clang::ValueDecl *iv)
1262 int type_size;
1263 Expr *lhs;
1264 DeclRefExpr *ref;
1265 pet_expr *expr, *expr_iv;
1267 if (op->getOpcode() != BO_Assign) {
1268 unsupported(op);
1269 return NULL;
1272 lhs = op->getLHS();
1273 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1274 unsupported(op);
1275 return NULL;
1278 ref = cast<DeclRefExpr>(lhs);
1279 if (ref->getDecl() != iv) {
1280 unsupported(op);
1281 return NULL;
1284 expr = extract_expr(op->getRHS());
1285 expr_iv = extract_expr(lhs);
1287 type_size = pet_clang_get_type_size(iv->getType(), ast_context);
1288 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1291 /* Check that op is of the form iv += cst or iv -= cst
1292 * and return a pet_expr corresponding to cst or -cst accordingly.
1294 __isl_give pet_expr *PetScan::extract_compound_increment(
1295 CompoundAssignOperator *op, clang::ValueDecl *iv)
1297 Expr *lhs;
1298 DeclRefExpr *ref;
1299 bool neg = false;
1300 pet_expr *expr;
1301 BinaryOperatorKind opcode;
1303 opcode = op->getOpcode();
1304 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1305 unsupported(op);
1306 return NULL;
1308 if (opcode == BO_SubAssign)
1309 neg = true;
1311 lhs = op->getLHS();
1312 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1313 unsupported(op);
1314 return NULL;
1317 ref = cast<DeclRefExpr>(lhs);
1318 if (ref->getDecl() != iv) {
1319 unsupported(op);
1320 return NULL;
1323 expr = extract_expr(op->getRHS());
1324 if (neg) {
1325 int type_size;
1326 type_size = pet_clang_get_type_size(op->getType(), ast_context);
1327 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1330 return expr;
1333 /* Check that the increment of the given for loop increments
1334 * (or decrements) the induction variable "iv" and return
1335 * the increment as a pet_expr if successful.
1337 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1338 ValueDecl *iv)
1340 Stmt *inc = stmt->getInc();
1342 if (!inc) {
1343 report_missing_increment(stmt);
1344 return NULL;
1347 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1348 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1349 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1350 return extract_compound_increment(
1351 cast<CompoundAssignOperator>(inc), iv);
1352 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1353 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1355 unsupported(inc);
1356 return NULL;
1359 /* Construct a pet_tree for a while loop.
1361 * If we were only able to extract part of the body, then simply
1362 * return that part.
1364 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1366 pet_expr *pe_cond;
1367 pet_tree *tree;
1369 tree = extract(stmt->getBody());
1370 if (partial)
1371 return tree;
1372 pe_cond = extract_expr(stmt->getCond());
1373 tree = pet_tree_new_while(pe_cond, tree);
1375 return tree;
1378 /* Construct a pet_tree for a for statement.
1379 * The for loop is required to be of one of the following forms
1381 * for (i = init; condition; ++i)
1382 * for (i = init; condition; --i)
1383 * for (i = init; condition; i += constant)
1384 * for (i = init; condition; i -= constant)
1386 * We extract a pet_tree for the body and then include it in a pet_tree
1387 * of type pet_tree_for.
1389 * As a special case, we also allow a for loop of the form
1391 * for (;;)
1393 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1395 * If we were only able to extract part of the body, then simply
1396 * return that part.
1398 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1400 BinaryOperator *ass;
1401 Decl *decl;
1402 Stmt *init;
1403 Expr *rhs;
1404 ValueDecl *iv;
1405 pet_tree *tree;
1406 int independent;
1407 int declared;
1408 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1410 independent = is_current_stmt_marked_independent();
1412 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1413 tree = extract(stmt->getBody());
1414 if (partial)
1415 return tree;
1416 tree = pet_tree_new_infinite_loop(tree);
1417 return tree;
1420 init = stmt->getInit();
1421 if (!init) {
1422 unsupported(stmt);
1423 return NULL;
1425 if ((ass = initialization_assignment(init)) != NULL) {
1426 iv = extract_induction_variable(ass);
1427 if (!iv)
1428 return NULL;
1429 rhs = ass->getRHS();
1430 } else if ((decl = initialization_declaration(init)) != NULL) {
1431 VarDecl *var = extract_induction_variable(init, decl);
1432 if (!var)
1433 return NULL;
1434 iv = var;
1435 rhs = var->getInit();
1436 } else {
1437 unsupported(stmt->getInit());
1438 return NULL;
1441 declared = !initialization_assignment(stmt->getInit());
1442 tree = extract(stmt->getBody());
1443 if (partial)
1444 return tree;
1445 pe_iv = extract_access_expr(iv);
1446 pe_iv = mark_write(pe_iv);
1447 pe_init = extract_expr(rhs);
1448 if (!stmt->getCond())
1449 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1450 else
1451 pe_cond = extract_expr(stmt->getCond());
1452 pe_inc = extract_increment(stmt, iv);
1453 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1454 pe_inc, tree);
1455 return tree;
1458 /* Store the names of the variables declared in decl_context
1459 * in the set declared_names. Make sure to only do this once by
1460 * setting declared_names_collected.
1462 void PetScan::collect_declared_names()
1464 DeclContext *DC = decl_context;
1465 DeclContext::decl_iterator it;
1467 if (declared_names_collected)
1468 return;
1470 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1471 Decl *D = *it;
1472 NamedDecl *named;
1474 if (!isa<NamedDecl>(D))
1475 continue;
1476 named = cast<NamedDecl>(D);
1477 declared_names.insert(named->getName().str());
1480 declared_names_collected = true;
1483 /* Add the names in "names" that are not also in this->declared_names
1484 * to this->used_names.
1485 * It is up to the caller to make sure that declared_names has been
1486 * populated, if needed.
1488 void PetScan::add_new_used_names(const std::set<std::string> &names)
1490 std::set<std::string>::const_iterator it;
1492 for (it = names.begin(); it != names.end(); ++it) {
1493 if (declared_names.find(*it) != declared_names.end())
1494 continue;
1495 used_names.insert(*it);
1499 /* Is the name "name" used in any declaration other than "decl"?
1501 * If the name was found to be in use before, the consider it to be in use.
1502 * Otherwise, check the DeclContext of the function containing the scop
1503 * as well as all ancestors of this DeclContext for declarations
1504 * other than "decl" that declare something called "name".
1506 bool PetScan::name_in_use(const string &name, Decl *decl)
1508 DeclContext *DC;
1509 DeclContext::decl_iterator it;
1511 if (used_names.find(name) != used_names.end())
1512 return true;
1514 for (DC = decl_context; DC; DC = DC->getParent()) {
1515 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1516 Decl *D = *it;
1517 NamedDecl *named;
1519 if (D == decl)
1520 continue;
1521 if (!isa<NamedDecl>(D))
1522 continue;
1523 named = cast<NamedDecl>(D);
1524 if (named->getName().str() == name)
1525 return true;
1529 return false;
1532 /* Generate a new name based on "name" that is not in use.
1533 * Do so by adding a suffix _i, with i an integer.
1535 string PetScan::generate_new_name(const string &name)
1537 string new_name;
1539 do {
1540 std::ostringstream oss;
1541 oss << name << "_" << n_rename++;
1542 new_name = oss.str();
1543 } while (name_in_use(new_name, NULL));
1545 return new_name;
1548 /* Try and construct a pet_tree corresponding to a compound statement.
1550 * "skip_declarations" is set if we should skip initial declarations
1551 * in the children of the compound statements.
1553 * Collect a new set of declarations for the current compound statement.
1554 * If any of the names in these declarations is also used by another
1555 * declaration reachable from the current function, then rename it
1556 * to a name that is not already in use.
1557 * In particular, keep track of the old and new names in a pet_substituter
1558 * and apply the substitutions to the pet_tree corresponding to the
1559 * compound statement.
1561 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1562 bool skip_declarations)
1564 pet_tree *tree;
1565 std::vector<VarDecl *> saved_declarations;
1566 std::vector<VarDecl *>::iterator it;
1567 pet_substituter substituter;
1569 saved_declarations = declarations;
1570 declarations.clear();
1571 tree = extract(stmt->children(), true, skip_declarations, stmt);
1572 for (it = declarations.begin(); it != declarations.end(); ++it) {
1573 isl_id *id;
1574 pet_expr *expr;
1575 VarDecl *decl = *it;
1576 string name = decl->getName().str();
1577 bool in_use = name_in_use(name, decl);
1579 used_names.insert(name);
1580 if (!in_use)
1581 continue;
1583 name = generate_new_name(name);
1584 id = pet_id_from_name_and_decl(ctx, name.c_str(), decl);
1585 expr = pet_id_create_index_expr(id);
1586 expr = extract_access_expr(decl->getType(), expr);
1587 id = pet_id_from_decl(ctx, decl);
1588 substituter.add_sub(id, expr);
1589 used_names.insert(name);
1591 tree = substituter.substitute(tree);
1592 declarations = saved_declarations;
1594 return tree;
1597 /* Return the file offset of the expansion location of "Loc".
1599 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1601 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1604 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1606 /* Return a SourceLocation for the location after the first semicolon
1607 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1608 * call it and also skip trailing spaces and newline.
1610 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1611 const LangOptions &LO)
1613 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1616 #else
1618 /* Return a SourceLocation for the location after the first semicolon
1619 * after "loc". If Lexer::findLocationAfterToken is not available,
1620 * we look in the underlying character data for the first semicolon.
1622 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1623 const LangOptions &LO)
1625 const char *semi;
1626 const char *s = SM.getCharacterData(loc);
1628 semi = strchr(s, ';');
1629 if (!semi)
1630 return SourceLocation();
1631 return loc.getFileLocWithOffset(semi + 1 - s);
1634 #endif
1636 /* If the token at "loc" is the first token on the line, then return
1637 * a location referring to the start of the line and set *indent
1638 * to the indentation of "loc"
1639 * Otherwise, return "loc" and set *indent to "".
1641 * This function is used to extend a scop to the start of the line
1642 * if the first token of the scop is also the first token on the line.
1644 * We look for the first token on the line. If its location is equal to "loc",
1645 * then the latter is the location of the first token on the line.
1647 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1648 SourceManager &SM, const LangOptions &LO, char **indent)
1650 std::pair<FileID, unsigned> file_offset_pair;
1651 llvm::StringRef file;
1652 const char *pos;
1653 Token tok;
1654 SourceLocation token_loc, line_loc;
1655 int col;
1656 const char *s;
1658 loc = SM.getExpansionLoc(loc);
1659 col = SM.getExpansionColumnNumber(loc);
1660 line_loc = loc.getLocWithOffset(1 - col);
1661 file_offset_pair = SM.getDecomposedLoc(line_loc);
1662 file = SM.getBufferData(file_offset_pair.first, NULL);
1663 pos = file.data() + file_offset_pair.second;
1665 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1666 file.begin(), pos, file.end());
1667 lexer.LexFromRawLexer(tok);
1668 token_loc = tok.getLocation();
1670 s = SM.getCharacterData(line_loc);
1671 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1673 if (token_loc == loc)
1674 return line_loc;
1675 else
1676 return loc;
1679 /* Construct a pet_loc corresponding to the region covered by "range".
1680 * If "skip_semi" is set, then we assume "range" is followed by
1681 * a semicolon and also include this semicolon.
1683 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1684 bool skip_semi)
1686 SourceLocation loc = range.getBegin();
1687 SourceManager &SM = PP.getSourceManager();
1688 const LangOptions &LO = PP.getLangOpts();
1689 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1690 unsigned start, end;
1691 char *indent;
1693 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1694 start = getExpansionOffset(SM, loc);
1695 loc = range.getEnd();
1696 if (skip_semi)
1697 loc = location_after_semi(loc, SM, LO);
1698 else
1699 loc = PP.getLocForEndOfToken(loc);
1700 end = getExpansionOffset(SM, loc);
1702 return pet_loc_alloc(ctx, start, end, line, indent);
1705 /* Convert a top-level pet_expr to an expression pet_tree.
1707 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1708 SourceRange range, bool skip_semi)
1710 pet_loc *loc;
1711 pet_tree *tree;
1713 tree = pet_tree_new_expr(expr);
1714 loc = construct_pet_loc(range, skip_semi);
1715 tree = pet_tree_set_loc(tree, loc);
1717 return tree;
1720 /* Construct a pet_tree for an if statement.
1722 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1724 pet_expr *pe_cond;
1725 pet_tree *tree, *tree_else;
1727 pe_cond = extract_expr(stmt->getCond());
1728 tree = extract(stmt->getThen());
1729 if (stmt->getElse()) {
1730 tree_else = extract(stmt->getElse());
1731 if (options->autodetect) {
1732 if (tree && !tree_else) {
1733 partial = true;
1734 pet_expr_free(pe_cond);
1735 return tree;
1737 if (!tree && tree_else) {
1738 partial = true;
1739 pet_expr_free(pe_cond);
1740 return tree_else;
1743 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1744 } else
1745 tree = pet_tree_new_if(pe_cond, tree);
1746 return tree;
1749 /* Try and construct a pet_tree for a label statement.
1751 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1753 isl_id *label;
1754 pet_tree *tree;
1756 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1758 tree = extract(stmt->getSubStmt());
1759 tree = pet_tree_set_label(tree, label);
1760 return tree;
1763 /* Update the location of "tree" to include the source range of "stmt".
1765 * Actually, we create a new location based on the source range of "stmt" and
1766 * then extend this new location to include the region of the original location.
1767 * This ensures that the line number of the final location refers to "stmt".
1769 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1771 pet_loc *loc, *tree_loc;
1773 tree_loc = pet_tree_get_loc(tree);
1774 loc = construct_pet_loc(stmt->getSourceRange(), false);
1775 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1776 pet_loc_free(tree_loc);
1778 tree = pet_tree_set_loc(tree, loc);
1779 return tree;
1782 /* Is "expr" of a type that can be converted to an access expression?
1784 static bool is_access_expr_type(Expr *expr)
1786 switch (expr->getStmtClass()) {
1787 case Stmt::ArraySubscriptExprClass:
1788 case Stmt::DeclRefExprClass:
1789 case Stmt::MemberExprClass:
1790 return true;
1791 default:
1792 return false;
1796 /* Tell the pet_inliner "inliner" about the formal arguments
1797 * in "fd" and the corresponding actual arguments in "call".
1798 * Return 0 if this was successful and -1 otherwise.
1800 * Any pointer argument is treated as an array.
1801 * The other arguments are treated as scalars.
1803 * In case of scalars, there is no restriction on the actual argument.
1804 * This actual argument is assigned to a variable with a name
1805 * that is derived from the name of the corresponding formal argument,
1806 * but made not to conflict with any variable names that are
1807 * already in use.
1809 * In case of arrays, the actual argument needs to be an expression
1810 * of a type that can be converted to an access expression or the address
1811 * of such an expression, ignoring implicit and redundant casts.
1813 int PetScan::set_inliner_arguments(pet_inliner &inliner, CallExpr *call,
1814 FunctionDecl *fd)
1816 unsigned n;
1818 n = fd->getNumParams();
1819 for (unsigned i = 0; i < n; ++i) {
1820 ParmVarDecl *parm = fd->getParamDecl(i);
1821 QualType type = parm->getType();
1822 Expr *arg, *sub;
1823 pet_expr *expr;
1824 int is_addr = 0;
1826 arg = call->getArg(i);
1827 if (pet_clang_array_depth(type) == 0) {
1828 string name = parm->getName().str();
1829 if (name_in_use(name, NULL))
1830 name = generate_new_name(name);
1831 used_names.insert(name);
1832 inliner.add_scalar_arg(parm, name, extract_expr(arg));
1833 continue;
1835 arg = pet_clang_strip_casts(arg);
1836 sub = extract_addr_of_arg(arg);
1837 if (sub) {
1838 is_addr = 1;
1839 arg = pet_clang_strip_casts(sub);
1841 if (!is_access_expr_type(arg)) {
1842 report_unsupported_inline_function_argument(arg);
1843 return -1;
1845 expr = extract_access_expr(arg);
1846 if (!expr)
1847 return -1;
1848 inliner.add_array_arg(parm, expr, is_addr);
1851 return 0;
1854 /* Internal data structure for PetScan::substitute_array_sizes.
1855 * ps is the PetScan on which the method was called.
1856 * substituter is the substituter that is used to substitute variables
1857 * in the size expressions.
1859 struct pet_substitute_array_sizes_data {
1860 PetScan *ps;
1861 pet_substituter *substituter;
1864 extern "C" {
1865 static int substitute_array_size(__isl_keep pet_tree *tree, void *user);
1868 /* If "tree" is a declaration, then perform the substitutions
1869 * in data->substituter on its size expression and store the result
1870 * in the size expression cache of data->ps such that the modified expression
1871 * will be used in subsequent calls to get_array_size.
1873 static int substitute_array_size(__isl_keep pet_tree *tree, void *user)
1875 struct pet_substitute_array_sizes_data *data;
1876 isl_id *id;
1877 pet_expr *var, *size;
1879 if (!pet_tree_is_decl(tree))
1880 return 0;
1882 data = (struct pet_substitute_array_sizes_data *) user;
1883 var = pet_tree_decl_get_var(tree);
1884 id = pet_expr_access_get_id(var);
1885 pet_expr_free(var);
1887 size = data->ps->get_array_size(id);
1888 size = data->substituter->substitute(size);
1889 data->ps->set_array_size(id, size);
1891 return 0;
1894 /* Perform the substitutions in "substituter" on all the arrays declared
1895 * inside "tree" and store the results in the size expression cache
1896 * such that the modified expressions will be used in subsequent calls
1897 * to get_array_size.
1899 int PetScan::substitute_array_sizes(__isl_keep pet_tree *tree,
1900 pet_substituter *substituter)
1902 struct pet_substitute_array_sizes_data data = { this, substituter };
1904 return pet_tree_foreach_sub_tree(tree, &substitute_array_size, &data);
1907 /* Try and construct a pet_tree from the body of "fd" using the actual
1908 * arguments in "call" in place of the formal arguments.
1909 * "fd" is assumed to point to the declaration with a function body.
1910 * In particular, construct a block that consists of assignments
1911 * of (parts of) the actual arguments to temporary variables
1912 * followed by the inlined function body with the formal arguments
1913 * replaced by (expressions containing) these temporary variables.
1915 * The actual inlining is taken care of by the pet_inliner object.
1916 * This function merely calls set_inliner_arguments to tell
1917 * the pet_inliner about the actual arguments, extracts a pet_tree
1918 * from the body of the called function and then passes this pet_tree
1919 * to the pet_inliner.
1920 * The substitutions performed by the inliner are also applied
1921 * to the size expressions of the arrays declared in the inlined
1922 * function. These size expressions are not stored in the tree
1923 * itself, but rather in the size expression cache.
1925 * During the extraction of the function body, all variables names
1926 * that are declared in the calling function as well all variable
1927 * names that are known to be in use are considered to be in use
1928 * in the called function to ensure that there is no naming conflict.
1929 * Similarly, the additional names that are in use in the called function
1930 * are considered to be in use in the calling function as well.
1932 * The location of the pet_tree is reset to the call site to ensure
1933 * that the extent of the scop does not include the body of the called
1934 * function.
1936 __isl_give pet_tree *PetScan::extract_inlined_call(CallExpr *call,
1937 FunctionDecl *fd)
1939 int save_autodetect;
1940 pet_tree *tree;
1941 pet_loc *tree_loc;
1942 pet_inliner inliner(ctx, n_arg, ast_context);
1944 if (set_inliner_arguments(inliner, call, fd) < 0)
1945 return NULL;
1947 save_autodetect = options->autodetect;
1948 options->autodetect = 0;
1949 PetScan body_scan(PP, ast_context, fd, loc, options,
1950 isl_union_map_copy(value_bounds), independent);
1951 collect_declared_names();
1952 body_scan.add_new_used_names(declared_names);
1953 body_scan.add_new_used_names(used_names);
1954 tree = body_scan.extract(fd->getBody(), false);
1955 add_new_used_names(body_scan.used_names);
1956 options->autodetect = save_autodetect;
1958 tree_loc = construct_pet_loc(call->getSourceRange(), true);
1959 tree = pet_tree_set_loc(tree, tree_loc);
1961 substitute_array_sizes(tree, &inliner);
1963 return inliner.inline_tree(tree);
1966 /* Try and construct a pet_tree corresponding
1967 * to the expression statement "stmt".
1969 * If the outer expression is a function call and if the corresponding
1970 * function body is marked "inline", then return a pet_tree
1971 * corresponding to the inlined function.
1973 __isl_give pet_tree *PetScan::extract_expr_stmt(Stmt *stmt)
1975 pet_expr *expr;
1977 if (stmt->getStmtClass() == Stmt::CallExprClass) {
1978 CallExpr *call = cast<CallExpr>(stmt);
1979 FunctionDecl *fd = call->getDirectCallee();
1980 fd = pet_clang_find_function_decl_with_body(fd);
1981 if (fd && fd->isInlineSpecified())
1982 return extract_inlined_call(call, fd);
1985 expr = extract_expr(cast<Expr>(stmt));
1986 return extract(expr, stmt->getSourceRange(), true);
1989 /* Try and construct a pet_tree corresponding to "stmt".
1991 * If "stmt" is a compound statement, then "skip_declarations"
1992 * indicates whether we should skip initial declarations in the
1993 * compound statement.
1995 * If the constructed pet_tree is not a (possibly) partial representation
1996 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1997 * In particular, if skip_declarations is set, then we may have skipped
1998 * declarations inside "stmt" and so the pet_scop may not represent
1999 * the entire "stmt".
2000 * Note that this function may be called with "stmt" referring to the entire
2001 * body of the function, including the outer braces. In such cases,
2002 * skip_declarations will be set and the braces will not be taken into
2003 * account in tree->loc.
2005 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
2007 pet_tree *tree;
2009 set_current_stmt(stmt);
2011 if (isa<Expr>(stmt))
2012 return extract_expr_stmt(cast<Expr>(stmt));
2014 switch (stmt->getStmtClass()) {
2015 case Stmt::WhileStmtClass:
2016 tree = extract(cast<WhileStmt>(stmt));
2017 break;
2018 case Stmt::ForStmtClass:
2019 tree = extract_for(cast<ForStmt>(stmt));
2020 break;
2021 case Stmt::IfStmtClass:
2022 tree = extract(cast<IfStmt>(stmt));
2023 break;
2024 case Stmt::CompoundStmtClass:
2025 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
2026 break;
2027 case Stmt::LabelStmtClass:
2028 tree = extract(cast<LabelStmt>(stmt));
2029 break;
2030 case Stmt::ContinueStmtClass:
2031 tree = pet_tree_new_continue(ctx);
2032 break;
2033 case Stmt::BreakStmtClass:
2034 tree = pet_tree_new_break(ctx);
2035 break;
2036 case Stmt::DeclStmtClass:
2037 tree = extract(cast<DeclStmt>(stmt));
2038 break;
2039 case Stmt::NullStmtClass:
2040 tree = pet_tree_new_block(ctx, 0, 0);
2041 break;
2042 default:
2043 report_unsupported_statement_type(stmt);
2044 return NULL;
2047 if (partial || skip_declarations)
2048 return tree;
2050 return update_loc(tree, stmt);
2053 /* Given a sequence of statements "stmt_range" of which the first "n_decl"
2054 * are declarations and of which the remaining statements are represented
2055 * by "tree", try and extend "tree" to include the last sequence of
2056 * the initial declarations that can be completely extracted.
2058 * We start collecting the initial declarations and start over
2059 * whenever we come across a declaration that we cannot extract.
2060 * If we have been able to extract any declarations, then we
2061 * copy over the contents of "tree" at the end of the declarations.
2062 * Otherwise, we simply return the original "tree".
2064 __isl_give pet_tree *PetScan::insert_initial_declarations(
2065 __isl_take pet_tree *tree, int n_decl, StmtRange stmt_range)
2067 StmtIterator i;
2068 pet_tree *res;
2069 int n_stmt;
2070 int is_block;
2071 int j;
2073 n_stmt = pet_tree_block_n_child(tree);
2074 is_block = pet_tree_block_get_block(tree);
2075 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2077 for (i = stmt_range.first; n_decl; ++i, --n_decl) {
2078 Stmt *child = *i;
2079 pet_tree *tree_i;
2081 tree_i = extract(child);
2082 if (tree_i && !partial) {
2083 res = pet_tree_block_add_child(res, tree_i);
2084 continue;
2086 pet_tree_free(tree_i);
2087 partial = false;
2088 if (pet_tree_block_n_child(res) == 0)
2089 continue;
2090 pet_tree_free(res);
2091 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2094 if (pet_tree_block_n_child(res) == 0) {
2095 pet_tree_free(res);
2096 return tree;
2099 for (j = 0; j < n_stmt; ++j) {
2100 pet_tree *tree_i;
2102 tree_i = pet_tree_block_get_child(tree, j);
2103 res = pet_tree_block_add_child(res, tree_i);
2105 pet_tree_free(tree);
2107 return res;
2110 /* Try and construct a pet_tree corresponding to (part of)
2111 * a sequence of statements.
2113 * "block" is set if the sequence represents the children of
2114 * a compound statement.
2115 * "skip_declarations" is set if we should skip initial declarations
2116 * in the sequence of statements.
2117 * "parent" is the statement that has stmt_range as (some of) its children.
2119 * If autodetect is set, then we allow the extraction of only a subrange
2120 * of the sequence of statements. However, if there is at least one
2121 * kill and there is some subsequent statement for which we could not
2122 * construct a tree, then turn off the "block" property of the tree
2123 * such that no extra kill will be introduced at the end of the (partial)
2124 * block. If, on the other hand, the final range contains
2125 * no statements, then we discard the entire range.
2126 * If only a subrange of the sequence was extracted, but each statement
2127 * in the sequence was extracted completely, and if there are some
2128 * variable declarations in the sequence before or inside
2129 * the extracted subrange, then check if any of these variables are
2130 * not used after the extracted subrange. If so, add kills to these
2131 * variables.
2133 * If the entire range was extracted, apart from some initial declarations,
2134 * then we try and extend the range with the latest of those initial
2135 * declarations.
2137 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
2138 bool skip_declarations, Stmt *parent)
2140 StmtIterator i;
2141 int j, skip;
2142 bool has_kills = false;
2143 bool partial_range = false;
2144 bool outer_partial = false;
2145 pet_tree *tree;
2146 SourceManager &SM = PP.getSourceManager();
2147 pet_killed_locals kl(SM);
2148 unsigned range_start, range_end;
2150 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
2153 tree = pet_tree_new_block(ctx, block, j);
2155 skip = 0;
2156 i = stmt_range.first;
2157 if (skip_declarations)
2158 for (; i != stmt_range.second; ++i) {
2159 if ((*i)->getStmtClass() != Stmt::DeclStmtClass)
2160 break;
2161 if (options->autodetect)
2162 kl.add_locals(cast<DeclStmt>(*i));
2163 ++skip;
2166 for (; i != stmt_range.second; ++i) {
2167 Stmt *child = *i;
2168 pet_tree *tree_i;
2170 tree_i = extract(child);
2171 if (pet_tree_block_n_child(tree) != 0 && partial) {
2172 pet_tree_free(tree_i);
2173 break;
2175 if (child->getStmtClass() == Stmt::DeclStmtClass) {
2176 if (options->autodetect)
2177 kl.add_locals(cast<DeclStmt>(child));
2178 if (tree_i && block)
2179 has_kills = true;
2181 if (options->autodetect) {
2182 if (tree_i) {
2183 range_end = getExpansionOffset(SM,
2184 child->getLocEnd());
2185 if (pet_tree_block_n_child(tree) == 0)
2186 range_start = getExpansionOffset(SM,
2187 child->getLocStart());
2188 tree = pet_tree_block_add_child(tree, tree_i);
2189 } else {
2190 partial_range = true;
2192 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
2193 outer_partial = partial = true;
2194 } else {
2195 tree = pet_tree_block_add_child(tree, tree_i);
2198 if (partial || !tree)
2199 break;
2202 if (!tree)
2203 return NULL;
2205 if (partial) {
2206 if (has_kills)
2207 tree = pet_tree_block_set_block(tree, 0);
2208 if (outer_partial) {
2209 kl.remove_accessed_after(parent,
2210 range_start, range_end);
2211 tree = add_kills(tree, kl.locals);
2213 } else if (partial_range) {
2214 if (pet_tree_block_n_child(tree) == 0) {
2215 pet_tree_free(tree);
2216 return NULL;
2218 partial = true;
2219 } else if (skip > 0)
2220 tree = insert_initial_declarations(tree, skip, stmt_range);
2222 return tree;
2225 extern "C" {
2226 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2227 void *user);
2228 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2229 __isl_keep pet_context *pc, void *user);
2232 /* Construct a pet_expr that holds the sizes of the array accessed
2233 * by "access".
2234 * This function is used as a callback to pet_context_add_parameters,
2235 * which is also passed a pointer to the PetScan object.
2237 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2238 void *user)
2240 PetScan *ps = (PetScan *) user;
2241 isl_id *id;
2242 pet_expr *size;
2244 id = pet_expr_access_get_id(access);
2245 size = ps->get_array_size(id);
2246 isl_id_free(id);
2248 return size;
2251 /* Construct and return a pet_array corresponding to the variable
2252 * accessed by "access".
2253 * This function is used as a callback to pet_scop_from_pet_tree,
2254 * which is also passed a pointer to the PetScan object.
2256 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2257 __isl_keep pet_context *pc, void *user)
2259 PetScan *ps = (PetScan *) user;
2260 isl_id *id;
2261 pet_array *array;
2263 id = pet_expr_access_get_id(access);
2264 array = ps->extract_array(id, NULL, pc);
2265 isl_id_free(id);
2267 return array;
2270 /* Extract a function summary from the body of "fd".
2272 * We extract a scop from the function body in a context with as
2273 * parameters the integer arguments of the function.
2274 * We turn off autodetection (in case it was set) to ensure that
2275 * the entire function body is considered.
2276 * We then collect the accessed array elements and attach them
2277 * to the corresponding array arguments, taking into account
2278 * that the function body may access members of array elements.
2280 * The reason for representing the integer arguments as parameters in
2281 * the context is that if we were to instead start with a context
2282 * with the function arguments as initial dimensions, then we would not
2283 * be able to refer to them from the array extents, without turning
2284 * array extents into maps.
2286 * The result is stored in the summary_cache cache so that we can reuse
2287 * it if this method gets called on the same function again later on.
2289 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
2291 isl_space *space;
2292 isl_set *domain;
2293 pet_context *pc;
2294 pet_tree *tree;
2295 pet_function_summary *summary;
2296 unsigned n;
2297 ScopLoc loc;
2298 int save_autodetect;
2299 struct pet_scop *scop;
2300 int int_size;
2301 isl_union_set *may_read, *may_write, *must_write;
2302 isl_union_map *to_inner;
2304 if (summary_cache.find(fd) != summary_cache.end())
2305 return pet_function_summary_copy(summary_cache[fd]);
2307 space = isl_space_set_alloc(ctx, 0, 0);
2309 n = fd->getNumParams();
2310 summary = pet_function_summary_alloc(ctx, n);
2311 for (unsigned i = 0; i < n; ++i) {
2312 ParmVarDecl *parm = fd->getParamDecl(i);
2313 QualType type = parm->getType();
2314 isl_id *id;
2316 if (!type->isIntegerType())
2317 continue;
2318 id = pet_id_from_decl(ctx, parm);
2319 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
2320 space = isl_space_set_dim_id(space, isl_dim_param, 0,
2321 isl_id_copy(id));
2322 summary = pet_function_summary_set_int(summary, i, id);
2325 save_autodetect = options->autodetect;
2326 options->autodetect = 0;
2327 PetScan body_scan(PP, ast_context, fd, loc, options,
2328 isl_union_map_copy(value_bounds), independent);
2330 tree = body_scan.extract(fd->getBody(), false);
2332 domain = isl_set_universe(space);
2333 pc = pet_context_alloc(domain);
2334 pc = pet_context_add_parameters(pc, tree,
2335 &::get_array_size, &body_scan);
2336 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2337 scop = pet_scop_from_pet_tree(tree, int_size,
2338 &::extract_array, &body_scan, pc);
2339 scop = scan_arrays(scop, pc);
2340 may_read = isl_union_map_range(pet_scop_get_may_reads(scop));
2341 may_write = isl_union_map_range(pet_scop_get_may_writes(scop));
2342 must_write = isl_union_map_range(pet_scop_get_must_writes(scop));
2343 to_inner = pet_scop_compute_outer_to_inner(scop);
2344 pet_scop_free(scop);
2346 for (unsigned i = 0; i < n; ++i) {
2347 ParmVarDecl *parm = fd->getParamDecl(i);
2348 QualType type = parm->getType();
2349 struct pet_array *array;
2350 isl_space *space;
2351 isl_union_set *data_set;
2352 isl_union_set *may_read_i, *may_write_i, *must_write_i;
2354 if (pet_clang_array_depth(type) == 0)
2355 continue;
2357 array = body_scan.extract_array(parm, NULL, pc);
2358 space = array ? isl_set_get_space(array->extent) : NULL;
2359 pet_array_free(array);
2360 data_set = isl_union_set_from_set(isl_set_universe(space));
2361 data_set = isl_union_set_apply(data_set,
2362 isl_union_map_copy(to_inner));
2363 may_read_i = isl_union_set_intersect(
2364 isl_union_set_copy(may_read),
2365 isl_union_set_copy(data_set));
2366 may_write_i = isl_union_set_intersect(
2367 isl_union_set_copy(may_write),
2368 isl_union_set_copy(data_set));
2369 must_write_i = isl_union_set_intersect(
2370 isl_union_set_copy(must_write), data_set);
2371 summary = pet_function_summary_set_array(summary, i,
2372 may_read_i, may_write_i, must_write_i);
2375 isl_union_set_free(may_read);
2376 isl_union_set_free(may_write);
2377 isl_union_set_free(must_write);
2378 isl_union_map_free(to_inner);
2380 options->autodetect = save_autodetect;
2381 pet_context_free(pc);
2383 summary_cache[fd] = pet_function_summary_copy(summary);
2385 return summary;
2388 /* If "fd" has a function body, then extract a function summary from
2389 * this body and attach it to the call expression "expr".
2391 * Even if a function body is available, "fd" itself may point
2392 * to a declaration without function body. We therefore first
2393 * replace it by the declaration that comes with a body (if any).
2395 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
2396 FunctionDecl *fd)
2398 pet_function_summary *summary;
2400 if (!expr)
2401 return NULL;
2402 fd = pet_clang_find_function_decl_with_body(fd);
2403 if (!fd)
2404 return expr;
2406 summary = get_summary(fd);
2408 expr = pet_expr_call_set_summary(expr, summary);
2410 return expr;
2413 /* Extract a pet_scop from "tree".
2415 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
2416 * then add pet_arrays for all accessed arrays.
2417 * We populate the pet_context with assignments for all parameters used
2418 * inside "tree" or any of the size expressions for the arrays accessed
2419 * by "tree" so that they can be used in affine expressions.
2421 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
2423 int int_size;
2424 isl_set *domain;
2425 pet_context *pc;
2426 pet_scop *scop;
2428 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2430 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2431 pc = pet_context_alloc(domain);
2432 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
2433 scop = pet_scop_from_pet_tree(tree, int_size,
2434 &::extract_array, this, pc);
2435 scop = scan_arrays(scop, pc);
2436 pet_context_free(pc);
2438 return scop;
2441 /* Add a call to __pencil_kill to the end of "tree" that kills
2442 * all the variables in "locals" and return the result.
2444 * No location is added to the kill because the most natural
2445 * location would lie outside the scop. Attaching such a location
2446 * to this tree would extend the scope of the final result
2447 * to include the location.
2449 __isl_give pet_tree *PetScan::add_kills(__isl_take pet_tree *tree,
2450 set<ValueDecl *> locals)
2452 int i;
2453 pet_expr *expr;
2454 pet_tree *kill, *block;
2455 set<ValueDecl *>::iterator it;
2457 if (locals.size() == 0)
2458 return tree;
2459 expr = pet_expr_new_call(ctx, "__pencil_kill", locals.size());
2460 i = 0;
2461 for (it = locals.begin(); it != locals.end(); ++it) {
2462 pet_expr *arg;
2463 arg = extract_access_expr(*it);
2464 expr = pet_expr_set_arg(expr, i++, arg);
2466 kill = pet_tree_new_expr(expr);
2467 block = pet_tree_new_block(ctx, 0, 2);
2468 block = pet_tree_block_add_child(block, tree);
2469 block = pet_tree_block_add_child(block, kill);
2471 return block;
2474 /* Check if the scop marked by the user is exactly this Stmt
2475 * or part of this Stmt.
2476 * If so, return a pet_scop corresponding to the marked region.
2477 * Otherwise, return NULL.
2479 * If the scop is not further nested inside a child of "stmt",
2480 * then check if there are any variable declarations before the scop
2481 * inside "stmt". If so, and if these variables are not used
2482 * after the scop, then add kills to the variables.
2484 struct pet_scop *PetScan::scan(Stmt *stmt)
2486 SourceManager &SM = PP.getSourceManager();
2487 unsigned start_off, end_off;
2488 pet_tree *tree;
2490 start_off = getExpansionOffset(SM, stmt->getLocStart());
2491 end_off = getExpansionOffset(SM, stmt->getLocEnd());
2493 if (start_off > loc.end)
2494 return NULL;
2495 if (end_off < loc.start)
2496 return NULL;
2498 if (start_off >= loc.start && end_off <= loc.end)
2499 return extract_scop(extract(stmt));
2501 pet_killed_locals kl(SM);
2502 StmtIterator start;
2503 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
2504 Stmt *child = *start;
2505 if (!child)
2506 continue;
2507 start_off = getExpansionOffset(SM, child->getLocStart());
2508 end_off = getExpansionOffset(SM, child->getLocEnd());
2509 if (start_off < loc.start && end_off >= loc.end)
2510 return scan(child);
2511 if (start_off >= loc.start)
2512 break;
2513 if (isa<DeclStmt>(child))
2514 kl.add_locals(cast<DeclStmt>(child));
2517 StmtIterator end;
2518 for (end = start; end != stmt->child_end(); ++end) {
2519 Stmt *child = *end;
2520 start_off = SM.getFileOffset(child->getLocStart());
2521 if (start_off >= loc.end)
2522 break;
2525 kl.remove_accessed_after(stmt, loc.start, loc.end);
2527 tree = extract(StmtRange(start, end), false, false, stmt);
2528 tree = add_kills(tree, kl.locals);
2529 return extract_scop(tree);
2532 /* Set the size of index "pos" of "array" to "size".
2533 * In particular, add a constraint of the form
2535 * i_pos < size
2537 * to array->extent and a constraint of the form
2539 * size >= 0
2541 * to array->context.
2543 * The domain of "size" is assumed to be zero-dimensional.
2545 static struct pet_array *update_size(struct pet_array *array, int pos,
2546 __isl_take isl_pw_aff *size)
2548 isl_set *valid;
2549 isl_set *univ;
2550 isl_set *bound;
2551 isl_space *dim;
2552 isl_aff *aff;
2553 isl_pw_aff *index;
2554 isl_id *id;
2556 if (!array)
2557 goto error;
2559 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2560 array->context = isl_set_intersect(array->context, valid);
2562 dim = isl_set_get_space(array->extent);
2563 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2564 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2565 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2566 index = isl_pw_aff_alloc(univ, aff);
2568 size = isl_pw_aff_add_dims(size, isl_dim_in,
2569 isl_set_dim(array->extent, isl_dim_set));
2570 id = isl_set_get_tuple_id(array->extent);
2571 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2572 bound = isl_pw_aff_lt_set(index, size);
2574 array->extent = isl_set_intersect(array->extent, bound);
2576 if (!array->context || !array->extent)
2577 return pet_array_free(array);
2579 return array;
2580 error:
2581 isl_pw_aff_free(size);
2582 return NULL;
2585 #ifdef HAVE_DECAYEDTYPE
2587 /* If "qt" is a decayed type, then set *decayed to true and
2588 * return the original type.
2590 static QualType undecay(QualType qt, bool *decayed)
2592 const Type *type = qt.getTypePtr();
2594 *decayed = isa<DecayedType>(type);
2595 if (*decayed)
2596 qt = cast<DecayedType>(type)->getOriginalType();
2597 return qt;
2600 #else
2602 /* If "qt" is a decayed type, then set *decayed to true and
2603 * return the original type.
2604 * Since this version of clang does not define a DecayedType,
2605 * we cannot obtain the original type even if it had been decayed and
2606 * we set *decayed to false.
2608 static QualType undecay(QualType qt, bool *decayed)
2610 *decayed = false;
2611 return qt;
2614 #endif
2616 /* Figure out the size of the array at position "pos" and all
2617 * subsequent positions from "qt" and update the corresponding
2618 * argument of "expr" accordingly.
2620 * The initial type (when pos is zero) may be a pointer type decayed
2621 * from an array type, if this initial type is the type of a function
2622 * argument. This only happens if the original array type has
2623 * a constant size in the outer dimension as otherwise we get
2624 * a VariableArrayType. Try and obtain this original type (if available) and
2625 * take the outer array size into account if it was marked static.
2627 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2628 QualType qt, int pos)
2630 const ArrayType *atype;
2631 pet_expr *size;
2632 bool decayed = false;
2634 if (!expr)
2635 return NULL;
2637 if (pos == 0)
2638 qt = undecay(qt, &decayed);
2640 if (qt->isPointerType()) {
2641 qt = qt->getPointeeType();
2642 return set_upper_bounds(expr, qt, pos + 1);
2644 if (!qt->isArrayType())
2645 return expr;
2647 qt = qt->getCanonicalTypeInternal();
2648 atype = cast<ArrayType>(qt.getTypePtr());
2650 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2651 qt = atype->getElementType();
2652 return set_upper_bounds(expr, qt, pos + 1);
2655 if (qt->isConstantArrayType()) {
2656 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2657 size = extract_expr(ca->getSize());
2658 expr = pet_expr_set_arg(expr, pos, size);
2659 } else if (qt->isVariableArrayType()) {
2660 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2661 size = extract_expr(vla->getSizeExpr());
2662 expr = pet_expr_set_arg(expr, pos, size);
2665 qt = atype->getElementType();
2667 return set_upper_bounds(expr, qt, pos + 1);
2670 /* Construct a pet_expr that holds the sizes of the array represented by "id".
2671 * The returned expression is a call expression with as arguments
2672 * the sizes in each dimension. If we are unable to derive the size
2673 * in a given dimension, then the corresponding argument is set to infinity.
2674 * In fact, we initialize all arguments to infinity and then update
2675 * them if we are able to figure out the size.
2677 * The result is stored in the id_size cache so that it can be reused
2678 * if this method is called on the same array identifier later.
2679 * The result is also stored in the type_size cache in case
2680 * it gets called on a different array identifier with the same type.
2682 __isl_give pet_expr *PetScan::get_array_size(__isl_keep isl_id *id)
2684 QualType qt = pet_id_get_array_type(id);
2685 int depth;
2686 pet_expr *expr, *inf;
2687 const Type *type = qt.getTypePtr();
2688 isl_maybe_pet_expr m;
2690 m = isl_id_to_pet_expr_try_get(id_size, id);
2691 if (m.valid < 0 || m.valid)
2692 return m.value;
2693 if (type_size.find(type) != type_size.end())
2694 return pet_expr_copy(type_size[type]);
2696 depth = pet_clang_array_depth(qt);
2697 inf = pet_expr_new_int(isl_val_infty(ctx));
2698 expr = pet_expr_new_call(ctx, "bounds", depth);
2699 for (int i = 0; i < depth; ++i)
2700 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2701 pet_expr_free(inf);
2703 expr = set_upper_bounds(expr, qt, 0);
2704 type_size[type] = pet_expr_copy(expr);
2705 id_size = isl_id_to_pet_expr_set(id_size, isl_id_copy(id),
2706 pet_expr_copy(expr));
2708 return expr;
2711 /* Set the array size of the array identified by "id" to "size",
2712 * replacing any previously stored value.
2714 void PetScan::set_array_size(__isl_take isl_id *id, __isl_take pet_expr *size)
2716 id_size = isl_id_to_pet_expr_set(id_size, id, size);
2719 /* Does "expr" represent the "integer" infinity?
2721 static int is_infty(__isl_keep pet_expr *expr)
2723 isl_val *v;
2724 int res;
2726 if (pet_expr_get_type(expr) != pet_expr_int)
2727 return 0;
2728 v = pet_expr_int_get_val(expr);
2729 res = isl_val_is_infty(v);
2730 isl_val_free(v);
2732 return res;
2735 /* Figure out the dimensions of an array "array" and
2736 * update "array" accordingly.
2738 * We first construct a pet_expr that holds the sizes of the array
2739 * in each dimension. The resulting expression may containing
2740 * infinity values for dimension where we are unable to derive
2741 * a size expression.
2743 * The arguments of the size expression that have a value different from
2744 * infinity are then converted to an affine expression
2745 * within the context "pc" and incorporated into the size of "array".
2746 * If we are unable to convert a size expression to an affine expression or
2747 * if the size is not a (symbolic) constant,
2748 * then we leave the corresponding size of "array" untouched.
2750 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2751 __isl_keep pet_context *pc)
2753 int n;
2754 isl_id *id;
2755 pet_expr *expr;
2757 if (!array)
2758 return NULL;
2760 id = isl_set_get_tuple_id(array->extent);
2761 expr = get_array_size(id);
2762 isl_id_free(id);
2764 n = pet_expr_get_n_arg(expr);
2765 for (int i = 0; i < n; ++i) {
2766 pet_expr *arg;
2767 isl_pw_aff *size;
2769 arg = pet_expr_get_arg(expr, i);
2770 if (!is_infty(arg)) {
2771 int dim;
2773 size = pet_expr_extract_affine(arg, pc);
2774 dim = isl_pw_aff_dim(size, isl_dim_in);
2775 if (!size)
2776 array = pet_array_free(array);
2777 else if (isl_pw_aff_involves_nan(size) ||
2778 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2779 isl_pw_aff_free(size);
2780 else {
2781 size = isl_pw_aff_drop_dims(size,
2782 isl_dim_in, 0, dim);
2783 array = update_size(array, i, size);
2786 pet_expr_free(arg);
2788 pet_expr_free(expr);
2790 return array;
2793 /* Does "decl" have a definition that we can keep track of in a pet_type?
2795 static bool has_printable_definition(RecordDecl *decl)
2797 if (!decl->getDeclName())
2798 return false;
2799 return decl->getLexicalDeclContext() == decl->getDeclContext();
2802 /* Add all TypedefType objects that appear when dereferencing "type"
2803 * to "types".
2805 static void insert_intermediate_typedefs(PetTypes *types, QualType type)
2807 type = pet_clang_base_or_typedef_type(type);
2808 while (isa<TypedefType>(type)) {
2809 const TypedefType *tt;
2811 tt = cast<TypedefType>(type);
2812 types->insert(tt->getDecl());
2813 type = tt->desugar();
2814 type = pet_clang_base_or_typedef_type(type);
2818 /* Construct and return a pet_array corresponding to the variable
2819 * represented by "id".
2820 * In particular, initialize array->extent to
2822 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2824 * and then call set_upper_bounds to set the upper bounds on the indices
2825 * based on the type of the variable. The upper bounds are converted
2826 * to affine expressions within the context "pc".
2828 * If the base type is that of a record with a top-level definition or
2829 * of a typedef and if "types" is not null, then the RecordDecl or
2830 * TypedefType corresponding to the type, as well as any intermediate
2831 * TypedefType, is added to "types".
2833 * If the base type is that of a record with no top-level definition,
2834 * then we replace it by "<subfield>".
2836 * If the variable is a scalar, i.e., a zero-dimensional array,
2837 * then the "const" qualifier, if any, is removed from the base type.
2838 * This makes it easier for users of pet to turn initializations
2839 * into assignments.
2841 struct pet_array *PetScan::extract_array(__isl_keep isl_id *id,
2842 PetTypes *types, __isl_keep pet_context *pc)
2844 struct pet_array *array;
2845 QualType qt = pet_id_get_array_type(id);
2846 int depth = pet_clang_array_depth(qt);
2847 QualType base = pet_clang_base_type(qt);
2848 string name;
2849 isl_space *space;
2851 array = isl_calloc_type(ctx, struct pet_array);
2852 if (!array)
2853 return NULL;
2855 space = isl_space_set_alloc(ctx, 0, depth);
2856 space = isl_space_set_tuple_id(space, isl_dim_set, isl_id_copy(id));
2858 array->extent = isl_set_nat_universe(space);
2860 space = isl_space_params_alloc(ctx, 0);
2861 array->context = isl_set_universe(space);
2863 array = set_upper_bounds(array, pc);
2864 if (!array)
2865 return NULL;
2867 if (depth == 0)
2868 base.removeLocalConst();
2869 name = base.getAsString();
2871 if (types) {
2872 insert_intermediate_typedefs(types, qt);
2873 if (isa<TypedefType>(base)) {
2874 types->insert(cast<TypedefType>(base)->getDecl());
2875 } else if (base->isRecordType()) {
2876 RecordDecl *decl = pet_clang_record_decl(base);
2877 TypedefNameDecl *typedecl;
2878 typedecl = decl->getTypedefNameForAnonDecl();
2879 if (typedecl)
2880 types->insert(typedecl);
2881 else if (has_printable_definition(decl))
2882 types->insert(decl);
2883 else
2884 name = "<subfield>";
2888 array->element_type = strdup(name.c_str());
2889 array->element_is_record = base->isRecordType();
2890 array->element_size = size_in_bytes(ast_context, base);
2892 return array;
2895 /* Construct and return a pet_array corresponding to the variable "decl".
2897 struct pet_array *PetScan::extract_array(ValueDecl *decl,
2898 PetTypes *types, __isl_keep pet_context *pc)
2900 isl_id *id;
2901 pet_array *array;
2903 id = pet_id_from_decl(ctx, decl);
2904 array = extract_array(id, types, pc);
2905 isl_id_free(id);
2907 return array;
2910 /* Construct and return a pet_array corresponding to the sequence
2911 * of declarations represented by "decls".
2912 * The upper bounds of the array are converted to affine expressions
2913 * within the context "pc".
2914 * If the sequence contains a single declaration, then it corresponds
2915 * to a simple array access. Otherwise, it corresponds to a member access,
2916 * with the declaration for the substructure following that of the containing
2917 * structure in the sequence of declarations.
2918 * We start with the outermost substructure and then combine it with
2919 * information from the inner structures.
2921 * Additionally, keep track of all required types in "types".
2923 struct pet_array *PetScan::extract_array(__isl_keep isl_id_list *decls,
2924 PetTypes *types, __isl_keep pet_context *pc)
2926 int i, n;
2927 isl_id *id;
2928 struct pet_array *array;
2930 id = isl_id_list_get_id(decls, 0);
2931 array = extract_array(id, types, pc);
2932 isl_id_free(id);
2934 n = isl_id_list_n_id(decls);
2935 for (i = 1; i < n; ++i) {
2936 struct pet_array *parent;
2937 const char *base_name, *field_name;
2938 char *product_name;
2940 parent = array;
2941 id = isl_id_list_get_id(decls, i);
2942 array = extract_array(id, types, pc);
2943 isl_id_free(id);
2944 if (!array)
2945 return pet_array_free(parent);
2947 base_name = isl_set_get_tuple_name(parent->extent);
2948 field_name = isl_set_get_tuple_name(array->extent);
2949 product_name = pet_array_member_access_name(ctx,
2950 base_name, field_name);
2952 array->extent = isl_set_product(isl_set_copy(parent->extent),
2953 array->extent);
2954 if (product_name)
2955 array->extent = isl_set_set_tuple_name(array->extent,
2956 product_name);
2957 array->context = isl_set_intersect(array->context,
2958 isl_set_copy(parent->context));
2960 pet_array_free(parent);
2961 free(product_name);
2963 if (!array->extent || !array->context || !product_name)
2964 return pet_array_free(array);
2967 return array;
2970 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2971 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2972 std::set<TypeDecl *> &types_done);
2973 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2974 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2975 std::set<TypeDecl *> &types_done);
2977 /* For each of the fields of "decl" that is itself a record type
2978 * or a typedef, or an array of such type, add a corresponding pet_type
2979 * to "scop".
2981 static struct pet_scop *add_field_types(isl_ctx *ctx, struct pet_scop *scop,
2982 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2983 std::set<TypeDecl *> &types_done)
2985 RecordDecl::field_iterator it;
2987 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
2988 QualType type = it->getType();
2990 type = pet_clang_base_or_typedef_type(type);
2991 if (isa<TypedefType>(type)) {
2992 TypedefNameDecl *typedefdecl;
2994 typedefdecl = cast<TypedefType>(type)->getDecl();
2995 scop = add_type(ctx, scop, typedefdecl,
2996 PP, types, types_done);
2997 } else if (type->isRecordType()) {
2998 RecordDecl *record;
3000 record = pet_clang_record_decl(type);
3001 scop = add_type(ctx, scop, record,
3002 PP, types, types_done);
3006 return scop;
3009 /* Add a pet_type corresponding to "decl" to "scop", provided
3010 * it is a member of types.records and it has not been added before
3011 * (i.e., it is not a member of "types_done").
3013 * Since we want the user to be able to print the types
3014 * in the order in which they appear in the scop, we need to
3015 * make sure that types of fields in a structure appear before
3016 * that structure. We therefore call ourselves recursively
3017 * through add_field_types on the types of all record subfields.
3019 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3020 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
3021 std::set<TypeDecl *> &types_done)
3023 string s;
3024 llvm::raw_string_ostream S(s);
3026 if (types.records.find(decl) == types.records.end())
3027 return scop;
3028 if (types_done.find(decl) != types_done.end())
3029 return scop;
3031 add_field_types(ctx, scop, decl, PP, types, types_done);
3033 if (strlen(decl->getName().str().c_str()) == 0)
3034 return scop;
3036 decl->print(S, PrintingPolicy(PP.getLangOpts()));
3037 S.str();
3039 scop->types[scop->n_type] = pet_type_alloc(ctx,
3040 decl->getName().str().c_str(), s.c_str());
3041 if (!scop->types[scop->n_type])
3042 return pet_scop_free(scop);
3044 types_done.insert(decl);
3046 scop->n_type++;
3048 return scop;
3051 /* Add a pet_type corresponding to "decl" to "scop", provided
3052 * it is a member of types.typedefs and it has not been added before
3053 * (i.e., it is not a member of "types_done").
3055 * If the underlying type is a structure, then we print the typedef
3056 * ourselves since clang does not print the definition of the structure
3057 * in the typedef. We also make sure in this case that the types of
3058 * the fields in the structure are added first.
3059 * Since the definition of the structure also gets printed this way,
3060 * add it to types_done such that it will not be printed again,
3061 * not even without the typedef.
3063 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3064 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
3065 std::set<TypeDecl *> &types_done)
3067 string s;
3068 llvm::raw_string_ostream S(s);
3069 QualType qt = decl->getUnderlyingType();
3071 if (types.typedefs.find(decl) == types.typedefs.end())
3072 return scop;
3073 if (types_done.find(decl) != types_done.end())
3074 return scop;
3076 if (qt->isRecordType()) {
3077 RecordDecl *rec = pet_clang_record_decl(qt);
3079 add_field_types(ctx, scop, rec, PP, types, types_done);
3080 S << "typedef ";
3081 rec->print(S, PrintingPolicy(PP.getLangOpts()));
3082 S << " ";
3083 S << decl->getName();
3084 types_done.insert(rec);
3085 } else {
3086 decl->print(S, PrintingPolicy(PP.getLangOpts()));
3088 S.str();
3090 scop->types[scop->n_type] = pet_type_alloc(ctx,
3091 decl->getName().str().c_str(), s.c_str());
3092 if (!scop->types[scop->n_type])
3093 return pet_scop_free(scop);
3095 types_done.insert(decl);
3097 scop->n_type++;
3099 return scop;
3102 /* Construct a list of pet_arrays, one for each array (or scalar)
3103 * accessed inside "scop", add this list to "scop" and return the result.
3104 * The upper bounds of the arrays are converted to affine expressions
3105 * within the context "pc".
3107 * The context of "scop" is updated with the intersection of
3108 * the contexts of all arrays, i.e., constraints on the parameters
3109 * that ensure that the arrays have a valid (non-negative) size.
3111 * If any of the extracted arrays refers to a member access or
3112 * has a typedef'd type as base type,
3113 * then also add the required types to "scop".
3114 * The typedef types are printed first because their definitions
3115 * may include the definition of a struct and these struct definitions
3116 * should not be printed separately. While the typedef definition
3117 * is being printed, the struct is marked as having been printed as well,
3118 * such that the later printing of the struct by itself can be prevented.
3120 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
3121 __isl_keep pet_context *pc)
3123 int i, n;
3124 array_desc_set arrays;
3125 array_desc_set::iterator it;
3126 PetTypes types;
3127 std::set<TypeDecl *> types_done;
3128 std::set<clang::RecordDecl *, less_name>::iterator records_it;
3129 std::set<clang::TypedefNameDecl *, less_name>::iterator typedefs_it;
3130 int n_array;
3131 struct pet_array **scop_arrays;
3133 if (!scop)
3134 return NULL;
3136 pet_scop_collect_arrays(scop, arrays);
3137 if (arrays.size() == 0)
3138 return scop;
3140 n_array = scop->n_array;
3142 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3143 n_array + arrays.size());
3144 if (!scop_arrays)
3145 goto error;
3146 scop->arrays = scop_arrays;
3148 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3149 struct pet_array *array;
3150 array = extract_array(*it, &types, pc);
3151 scop->arrays[n_array + i] = array;
3152 if (!scop->arrays[n_array + i])
3153 goto error;
3154 scop->n_array++;
3155 scop->context = isl_set_intersect(scop->context,
3156 isl_set_copy(array->context));
3157 if (!scop->context)
3158 goto error;
3161 n = types.records.size() + types.typedefs.size();
3162 if (n == 0)
3163 return scop;
3165 scop->types = isl_alloc_array(ctx, struct pet_type *, n);
3166 if (!scop->types)
3167 goto error;
3169 for (typedefs_it = types.typedefs.begin();
3170 typedefs_it != types.typedefs.end(); ++typedefs_it)
3171 scop = add_type(ctx, scop, *typedefs_it, PP, types, types_done);
3173 for (records_it = types.records.begin();
3174 records_it != types.records.end(); ++records_it)
3175 scop = add_type(ctx, scop, *records_it, PP, types, types_done);
3177 return scop;
3178 error:
3179 pet_scop_free(scop);
3180 return NULL;
3183 /* Bound all parameters in scop->context to the possible values
3184 * of the corresponding C variable.
3186 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
3188 int n;
3190 if (!scop)
3191 return NULL;
3193 n = isl_set_dim(scop->context, isl_dim_param);
3194 for (int i = 0; i < n; ++i) {
3195 isl_id *id;
3196 ValueDecl *decl;
3198 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
3199 if (pet_nested_in_id(id)) {
3200 isl_id_free(id);
3201 isl_die(isl_set_get_ctx(scop->context),
3202 isl_error_internal,
3203 "unresolved nested parameter", goto error);
3205 decl = pet_id_get_decl(id);
3206 isl_id_free(id);
3208 scop->context = set_parameter_bounds(scop->context, i, decl);
3210 if (!scop->context)
3211 goto error;
3214 return scop;
3215 error:
3216 pet_scop_free(scop);
3217 return NULL;
3220 /* Construct a pet_scop from the given function.
3222 * If the scop was delimited by scop and endscop pragmas, then we override
3223 * the file offsets by those derived from the pragmas.
3225 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3227 pet_scop *scop;
3228 Stmt *stmt;
3230 stmt = fd->getBody();
3232 if (options->autodetect) {
3233 set_current_stmt(stmt);
3234 scop = extract_scop(extract(stmt, true));
3235 } else {
3236 current_line = loc.start_line;
3237 scop = scan(stmt);
3238 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
3240 scop = add_parameter_bounds(scop);
3241 scop = pet_scop_gist(scop, value_bounds);
3243 return scop;
3246 /* Update this->last_line and this->current_line based on the fact
3247 * that we are about to consider "stmt".
3249 void PetScan::set_current_stmt(Stmt *stmt)
3251 SourceLocation loc = stmt->getLocStart();
3252 SourceManager &SM = PP.getSourceManager();
3254 last_line = current_line;
3255 current_line = SM.getExpansionLineNumber(loc);
3258 /* Is the current statement marked by an independent pragma?
3259 * That is, is there an independent pragma on a line between
3260 * the line of the current statement and the line of the previous statement.
3261 * The search is not implemented very efficiently. We currently
3262 * assume that there are only a few independent pragmas, if any.
3264 bool PetScan::is_current_stmt_marked_independent()
3266 for (unsigned i = 0; i < independent.size(); ++i) {
3267 unsigned line = independent[i].line;
3269 if (last_line < line && line < current_line)
3270 return true;
3273 return false;