extract out pet_killed_locals
[pet.git] / scan.cc
blob400504f4ea488c3b3bdb4d65dfd4c19b05e02a40
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2015 Ecole Normale Superieure. All rights reserved.
4 * Copyright 2015 Sven Verdoolaege. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
19 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
22 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
25 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 * The views and conclusions contained in the software and documentation
31 * are those of the authors and should not be interpreted as
32 * representing official policies, either expressed or implied, of
33 * Leiden University.
34 */
36 #include "config.h"
38 #include <string.h>
39 #include <set>
40 #include <map>
41 #include <iostream>
42 #include <sstream>
43 #include <llvm/Support/raw_ostream.h>
44 #include <clang/AST/ASTContext.h>
45 #include <clang/AST/ASTDiagnostic.h>
46 #include <clang/AST/Attr.h>
47 #include <clang/AST/Expr.h>
48 #include <clang/AST/RecursiveASTVisitor.h>
50 #include <isl/id.h>
51 #include <isl/space.h>
52 #include <isl/aff.h>
53 #include <isl/set.h>
54 #include <isl/union_set.h>
56 #include "aff.h"
57 #include "array.h"
58 #include "clang.h"
59 #include "context.h"
60 #include "expr.h"
61 #include "id.h"
62 #include "inliner.h"
63 #include "killed_locals.h"
64 #include "nest.h"
65 #include "options.h"
66 #include "scan.h"
67 #include "scop.h"
68 #include "scop_plus.h"
69 #include "substituter.h"
70 #include "tree.h"
71 #include "tree2scop.h"
73 using namespace std;
74 using namespace clang;
76 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
78 switch (kind) {
79 case UO_Minus:
80 return pet_op_minus;
81 case UO_Not:
82 return pet_op_not;
83 case UO_LNot:
84 return pet_op_lnot;
85 case UO_PostInc:
86 return pet_op_post_inc;
87 case UO_PostDec:
88 return pet_op_post_dec;
89 case UO_PreInc:
90 return pet_op_pre_inc;
91 case UO_PreDec:
92 return pet_op_pre_dec;
93 default:
94 return pet_op_last;
98 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
100 switch (kind) {
101 case BO_AddAssign:
102 return pet_op_add_assign;
103 case BO_SubAssign:
104 return pet_op_sub_assign;
105 case BO_MulAssign:
106 return pet_op_mul_assign;
107 case BO_DivAssign:
108 return pet_op_div_assign;
109 case BO_Assign:
110 return pet_op_assign;
111 case BO_Add:
112 return pet_op_add;
113 case BO_Sub:
114 return pet_op_sub;
115 case BO_Mul:
116 return pet_op_mul;
117 case BO_Div:
118 return pet_op_div;
119 case BO_Rem:
120 return pet_op_mod;
121 case BO_Shl:
122 return pet_op_shl;
123 case BO_Shr:
124 return pet_op_shr;
125 case BO_EQ:
126 return pet_op_eq;
127 case BO_NE:
128 return pet_op_ne;
129 case BO_LE:
130 return pet_op_le;
131 case BO_GE:
132 return pet_op_ge;
133 case BO_LT:
134 return pet_op_lt;
135 case BO_GT:
136 return pet_op_gt;
137 case BO_And:
138 return pet_op_and;
139 case BO_Xor:
140 return pet_op_xor;
141 case BO_Or:
142 return pet_op_or;
143 case BO_LAnd:
144 return pet_op_land;
145 case BO_LOr:
146 return pet_op_lor;
147 default:
148 return pet_op_last;
152 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
153 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
155 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
156 SourceLocation(), var, false, var->getInnerLocStart(),
157 var->getType(), VK_LValue);
159 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
160 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
162 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
163 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
164 VK_LValue);
166 #else
167 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
169 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
170 var, var->getInnerLocStart(), var->getType(), VK_LValue);
172 #endif
174 #ifdef GETTYPEINFORETURNSTYPEINFO
176 static int size_in_bytes(ASTContext &context, QualType type)
178 return context.getTypeInfo(type).Width / 8;
181 #else
183 static int size_in_bytes(ASTContext &context, QualType type)
185 return context.getTypeInfo(type).first / 8;
188 #endif
190 /* Check if the element type corresponding to the given array type
191 * has a const qualifier.
193 static bool const_base(QualType qt)
195 const Type *type = qt.getTypePtr();
197 if (type->isPointerType())
198 return const_base(type->getPointeeType());
199 if (type->isArrayType()) {
200 const ArrayType *atype;
201 type = type->getCanonicalTypeInternal().getTypePtr();
202 atype = cast<ArrayType>(type);
203 return const_base(atype->getElementType());
206 return qt.isConstQualified();
209 PetScan::~PetScan()
211 std::map<const Type *, pet_expr *>::iterator it;
212 std::map<FunctionDecl *, pet_function_summary *>::iterator it_s;
214 for (it = type_size.begin(); it != type_size.end(); ++it)
215 pet_expr_free(it->second);
216 for (it_s = summary_cache.begin(); it_s != summary_cache.end(); ++it_s)
217 pet_function_summary_free(it_s->second);
219 isl_union_map_free(value_bounds);
222 /* Report a diagnostic on the range "range", unless autodetect is set.
224 void PetScan::report(SourceRange range, unsigned id)
226 if (options->autodetect)
227 return;
229 SourceLocation loc = range.getBegin();
230 DiagnosticsEngine &diag = PP.getDiagnostics();
231 DiagnosticBuilder B = diag.Report(loc, id) << range;
234 /* Report a diagnostic on "stmt", unless autodetect is set.
236 void PetScan::report(Stmt *stmt, unsigned id)
238 report(stmt->getSourceRange(), id);
241 /* Report a diagnostic on "decl", unless autodetect is set.
243 void PetScan::report(Decl *decl, unsigned id)
245 report(decl->getSourceRange(), id);
248 /* Called if we found something we (currently) cannot handle.
249 * We'll provide more informative warnings later.
251 * We only actually complain if autodetect is false.
253 void PetScan::unsupported(Stmt *stmt)
255 DiagnosticsEngine &diag = PP.getDiagnostics();
256 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
257 "unsupported");
258 report(stmt, id);
261 /* Report an unsupported unary operator, unless autodetect is set.
263 void PetScan::report_unsupported_unary_operator(Stmt *stmt)
265 DiagnosticsEngine &diag = PP.getDiagnostics();
266 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
267 "this type of unary operator is not supported");
268 report(stmt, id);
271 /* Report an unsupported statement type, unless autodetect is set.
273 void PetScan::report_unsupported_statement_type(Stmt *stmt)
275 DiagnosticsEngine &diag = PP.getDiagnostics();
276 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
277 "this type of statement is not supported");
278 report(stmt, id);
281 /* Report a missing prototype, unless autodetect is set.
283 void PetScan::report_prototype_required(Stmt *stmt)
285 DiagnosticsEngine &diag = PP.getDiagnostics();
286 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
287 "prototype required");
288 report(stmt, id);
291 /* Report a missing increment, unless autodetect is set.
293 void PetScan::report_missing_increment(Stmt *stmt)
295 DiagnosticsEngine &diag = PP.getDiagnostics();
296 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
297 "missing increment");
298 report(stmt, id);
301 /* Report a missing summary function, unless autodetect is set.
303 void PetScan::report_missing_summary_function(Stmt *stmt)
305 DiagnosticsEngine &diag = PP.getDiagnostics();
306 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
307 "missing summary function");
308 report(stmt, id);
311 /* Report a missing summary function body, unless autodetect is set.
313 void PetScan::report_missing_summary_function_body(Stmt *stmt)
315 DiagnosticsEngine &diag = PP.getDiagnostics();
316 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
317 "missing summary function body");
318 report(stmt, id);
321 /* Report an unsupported argument in a call to an inlined function,
322 * unless autodetect is set.
324 void PetScan::report_unsupported_inline_function_argument(Stmt *stmt)
326 DiagnosticsEngine &diag = PP.getDiagnostics();
327 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
328 "unsupported inline function call argument");
329 report(stmt, id);
332 /* Report an unsupported type of declaration, unless autodetect is set.
334 void PetScan::report_unsupported_declaration(Decl *decl)
336 DiagnosticsEngine &diag = PP.getDiagnostics();
337 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
338 "unsupported declaration");
339 report(decl, id);
342 /* Extract an integer from "val", which is assumed to be non-negative.
344 static __isl_give isl_val *extract_unsigned(isl_ctx *ctx,
345 const llvm::APInt &val)
347 unsigned n;
348 const uint64_t *data;
350 data = val.getRawData();
351 n = val.getNumWords();
352 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
355 /* Extract an integer from "val". If "is_signed" is set, then "val"
356 * is signed. Otherwise it it unsigned.
358 static __isl_give isl_val *extract_int(isl_ctx *ctx, bool is_signed,
359 llvm::APInt val)
361 int is_negative = is_signed && val.isNegative();
362 isl_val *v;
364 if (is_negative)
365 val = -val;
367 v = extract_unsigned(ctx, val);
369 if (is_negative)
370 v = isl_val_neg(v);
371 return v;
374 /* Extract an integer from "expr".
376 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
378 const Type *type = expr->getType().getTypePtr();
379 bool is_signed = type->hasSignedIntegerRepresentation();
381 return ::extract_int(ctx, is_signed, expr->getValue());
384 /* Extract an integer from "expr".
385 * Return NULL if "expr" does not (obviously) represent an integer.
387 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
389 return extract_int(expr->getSubExpr());
392 /* Extract an integer from "expr".
393 * Return NULL if "expr" does not (obviously) represent an integer.
395 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
397 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
398 return extract_int(ctx, cast<IntegerLiteral>(expr));
399 if (expr->getStmtClass() == Stmt::ParenExprClass)
400 return extract_int(cast<ParenExpr>(expr));
402 unsupported(expr);
403 return NULL;
406 /* Extract a pet_expr from the APInt "val", which is assumed
407 * to be non-negative.
409 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
411 return pet_expr_new_int(extract_unsigned(ctx, val));
414 /* Return the number of bits needed to represent the type of "decl",
415 * if it is an integer type. Otherwise return 0.
416 * If qt is signed then return the opposite of the number of bits.
418 static int get_type_size(ValueDecl *decl)
420 return pet_clang_get_type_size(decl->getType(), decl->getASTContext());
423 /* Bound parameter "pos" of "set" to the possible values of "decl".
425 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
426 unsigned pos, ValueDecl *decl)
428 int type_size;
429 isl_ctx *ctx;
430 isl_val *bound;
432 ctx = isl_set_get_ctx(set);
433 type_size = get_type_size(decl);
434 if (type_size == 0)
435 isl_die(ctx, isl_error_invalid, "not an integer type",
436 return isl_set_free(set));
437 if (type_size > 0) {
438 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
439 bound = isl_val_int_from_ui(ctx, type_size);
440 bound = isl_val_2exp(bound);
441 bound = isl_val_sub_ui(bound, 1);
442 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
443 } else {
444 bound = isl_val_int_from_ui(ctx, -type_size - 1);
445 bound = isl_val_2exp(bound);
446 bound = isl_val_sub_ui(bound, 1);
447 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
448 isl_val_copy(bound));
449 bound = isl_val_neg(bound);
450 bound = isl_val_sub_ui(bound, 1);
451 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
454 return set;
457 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
459 return extract_index_expr(expr->getSubExpr());
462 /* Return the depth of the array accessed by the index expression "index".
463 * If "index" is an affine expression, i.e., if it does not access
464 * any array, then return 1.
465 * If "index" represent a member access, i.e., if its range is a wrapped
466 * relation, then return the sum of the depth of the array of structures
467 * and that of the member inside the structure.
469 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
471 isl_id *id;
472 ValueDecl *decl;
474 if (!index)
475 return -1;
477 if (isl_multi_pw_aff_range_is_wrapping(index)) {
478 int domain_depth, range_depth;
479 isl_multi_pw_aff *domain, *range;
481 domain = isl_multi_pw_aff_copy(index);
482 domain = isl_multi_pw_aff_range_factor_domain(domain);
483 domain_depth = extract_depth(domain);
484 isl_multi_pw_aff_free(domain);
485 range = isl_multi_pw_aff_copy(index);
486 range = isl_multi_pw_aff_range_factor_range(range);
487 range_depth = extract_depth(range);
488 isl_multi_pw_aff_free(range);
490 return domain_depth + range_depth;
493 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
494 return 1;
496 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
497 if (!id)
498 return -1;
499 decl = pet_id_get_decl(id);
500 isl_id_free(id);
502 return pet_clang_array_depth(decl->getType());
505 /* Return the depth of the array accessed by the access expression "expr".
507 static int extract_depth(__isl_keep pet_expr *expr)
509 isl_multi_pw_aff *index;
510 int depth;
512 index = pet_expr_access_get_index(expr);
513 depth = extract_depth(index);
514 isl_multi_pw_aff_free(index);
516 return depth;
519 /* Construct a pet_expr representing an index expression for an access
520 * to the variable referenced by "expr".
522 * If "expr" references an enum constant, then return an integer expression
523 * instead, representing the value of the enum constant.
525 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
527 return extract_index_expr(expr->getDecl());
530 /* Construct a pet_expr representing an index expression for an access
531 * to the variable "decl".
533 * If "decl" is an enum constant, then we return an integer expression
534 * instead, representing the value of the enum constant.
536 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
538 isl_id *id;
540 if (isa<EnumConstantDecl>(decl))
541 return extract_expr(cast<EnumConstantDecl>(decl));
543 id = pet_id_from_decl(ctx, decl);
544 return pet_id_create_index_expr(id);
547 /* Construct a pet_expr representing the index expression "expr"
548 * Return NULL on error.
550 * If "expr" is a reference to an enum constant, then return
551 * an integer expression instead, representing the value of the enum constant.
553 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
555 switch (expr->getStmtClass()) {
556 case Stmt::ImplicitCastExprClass:
557 return extract_index_expr(cast<ImplicitCastExpr>(expr));
558 case Stmt::DeclRefExprClass:
559 return extract_index_expr(cast<DeclRefExpr>(expr));
560 case Stmt::ArraySubscriptExprClass:
561 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
562 case Stmt::IntegerLiteralClass:
563 return extract_expr(cast<IntegerLiteral>(expr));
564 case Stmt::MemberExprClass:
565 return extract_index_expr(cast<MemberExpr>(expr));
566 default:
567 unsupported(expr);
569 return NULL;
572 /* Extract an index expression from the given array subscript expression.
574 * We first extract an index expression from the base.
575 * This will result in an index expression with a range that corresponds
576 * to the earlier indices.
577 * We then extract the current index and let
578 * pet_expr_access_subscript combine the two.
580 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
582 Expr *base = expr->getBase();
583 Expr *idx = expr->getIdx();
584 pet_expr *index;
585 pet_expr *base_expr;
587 base_expr = extract_index_expr(base);
588 index = extract_expr(idx);
590 base_expr = pet_expr_access_subscript(base_expr, index);
592 return base_expr;
595 /* Extract an index expression from a member expression.
597 * If the base access (to the structure containing the member)
598 * is of the form
600 * A[..]
602 * and the member is called "f", then the member access is of
603 * the form
605 * A_f[A[..] -> f[]]
607 * If the member access is to an anonymous struct, then simply return
609 * A[..]
611 * If the member access in the source code is of the form
613 * A->f
615 * then it is treated as
617 * A[0].f
619 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
621 Expr *base = expr->getBase();
622 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
623 pet_expr *base_index;
624 isl_id *id;
626 base_index = extract_index_expr(base);
628 if (expr->isArrow()) {
629 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
630 base_index = pet_expr_access_subscript(base_index, index);
633 if (field->isAnonymousStructOrUnion())
634 return base_index;
636 id = pet_id_from_decl(ctx, field);
638 return pet_expr_access_member(base_index, id);
641 /* Mark the given access pet_expr as a write.
643 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
645 access = pet_expr_access_set_write(access, 1);
646 access = pet_expr_access_set_read(access, 0);
648 return access;
651 /* Mark the given (read) access pet_expr as also possibly being written.
652 * That is, initialize the may write access relation from the may read relation
653 * and initialize the must write access relation to the empty relation.
655 static __isl_give pet_expr *mark_may_write(__isl_take pet_expr *expr)
657 isl_union_map *access;
658 isl_union_map *empty;
660 access = pet_expr_access_get_dependent_access(expr,
661 pet_expr_access_may_read);
662 empty = isl_union_map_empty(isl_union_map_get_space(access));
663 expr = pet_expr_access_set_access(expr, pet_expr_access_may_write,
664 access);
665 expr = pet_expr_access_set_access(expr, pet_expr_access_must_write,
666 empty);
668 return expr;
671 /* Construct a pet_expr representing a unary operator expression.
673 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
675 int type_size;
676 pet_expr *arg;
677 enum pet_op_type op;
679 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
680 if (op == pet_op_last) {
681 report_unsupported_unary_operator(expr);
682 return NULL;
685 arg = extract_expr(expr->getSubExpr());
687 if (expr->isIncrementDecrementOp() &&
688 pet_expr_get_type(arg) == pet_expr_access) {
689 arg = mark_write(arg);
690 arg = pet_expr_access_set_read(arg, 1);
693 type_size = pet_clang_get_type_size(expr->getType(), ast_context);
694 return pet_expr_new_unary(type_size, op, arg);
697 /* Construct a pet_expr representing a binary operator expression.
699 * If the top level operator is an assignment and the LHS is an access,
700 * then we mark that access as a write. If the operator is a compound
701 * assignment, the access is marked as both a read and a write.
703 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
705 int type_size;
706 pet_expr *lhs, *rhs;
707 enum pet_op_type op;
709 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
710 if (op == pet_op_last) {
711 unsupported(expr);
712 return NULL;
715 lhs = extract_expr(expr->getLHS());
716 rhs = extract_expr(expr->getRHS());
718 if (expr->isAssignmentOp() &&
719 pet_expr_get_type(lhs) == pet_expr_access) {
720 lhs = mark_write(lhs);
721 if (expr->isCompoundAssignmentOp())
722 lhs = pet_expr_access_set_read(lhs, 1);
725 type_size = pet_clang_get_type_size(expr->getType(), ast_context);
726 return pet_expr_new_binary(type_size, op, lhs, rhs);
729 /* Construct a pet_tree for a variable declaration and
730 * add the declaration to the list of declarations
731 * inside the current compound statement.
733 __isl_give pet_tree *PetScan::extract(Decl *decl)
735 VarDecl *vd;
736 pet_expr *lhs, *rhs;
737 pet_tree *tree;
739 if (!isa<VarDecl>(decl)) {
740 report_unsupported_declaration(decl);
741 return NULL;
744 vd = cast<VarDecl>(decl);
745 declarations.push_back(vd);
747 lhs = extract_access_expr(vd);
748 lhs = mark_write(lhs);
749 if (!vd->getInit())
750 tree = pet_tree_new_decl(lhs);
751 else {
752 rhs = extract_expr(vd->getInit());
753 tree = pet_tree_new_decl_init(lhs, rhs);
756 return tree;
759 /* Construct a pet_tree for a variable declaration statement.
760 * If the declaration statement declares multiple variables,
761 * then return a group of pet_trees, one for each declared variable.
763 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
765 pet_tree *tree;
766 unsigned n;
768 if (!stmt->isSingleDecl()) {
769 const DeclGroup &group = stmt->getDeclGroup().getDeclGroup();
770 n = group.size();
771 tree = pet_tree_new_block(ctx, 0, n);
773 for (unsigned i = 0; i < n; ++i) {
774 pet_tree *tree_i;
775 pet_loc *loc;
777 tree_i = extract(group[i]);
778 loc = construct_pet_loc(group[i]->getSourceRange(),
779 false);
780 tree_i = pet_tree_set_loc(tree_i, loc);
781 tree = pet_tree_block_add_child(tree, tree_i);
784 return tree;
787 return extract(stmt->getSingleDecl());
790 /* Construct a pet_expr representing a conditional operation.
792 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
794 pet_expr *cond, *lhs, *rhs;
796 cond = extract_expr(expr->getCond());
797 lhs = extract_expr(expr->getTrueExpr());
798 rhs = extract_expr(expr->getFalseExpr());
800 return pet_expr_new_ternary(cond, lhs, rhs);
803 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
805 return extract_expr(expr->getSubExpr());
808 /* Construct a pet_expr representing a floating point value.
810 * If the floating point literal does not appear in a macro,
811 * then we use the original representation in the source code
812 * as the string representation. Otherwise, we use the pretty
813 * printer to produce a string representation.
815 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
817 double d;
818 string s;
819 const LangOptions &LO = PP.getLangOpts();
820 SourceLocation loc = expr->getLocation();
822 if (!loc.isMacroID()) {
823 SourceManager &SM = PP.getSourceManager();
824 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
825 s = string(SM.getCharacterData(loc), len);
826 } else {
827 llvm::raw_string_ostream S(s);
828 expr->printPretty(S, 0, PrintingPolicy(LO));
829 S.str();
831 d = expr->getValueAsApproximateDouble();
832 return pet_expr_new_double(ctx, d, s.c_str());
835 /* Convert the index expression "index" into an access pet_expr of type "qt".
837 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
838 __isl_take pet_expr *index)
840 int depth;
841 int type_size;
843 depth = extract_depth(index);
844 type_size = pet_clang_get_type_size(qt, ast_context);
846 index = pet_expr_set_type_size(index, type_size);
847 index = pet_expr_access_set_depth(index, depth);
849 return index;
852 /* Extract an index expression from "expr" and then convert it into
853 * an access pet_expr.
855 * If "expr" is a reference to an enum constant, then return
856 * an integer expression instead, representing the value of the enum constant.
858 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
860 pet_expr *index;
862 index = extract_index_expr(expr);
864 if (pet_expr_get_type(index) == pet_expr_int)
865 return index;
867 return extract_access_expr(expr->getType(), index);
870 /* Extract an index expression from "decl" and then convert it into
871 * an access pet_expr.
873 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
875 return extract_access_expr(decl->getType(), extract_index_expr(decl));
878 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
880 return extract_expr(expr->getSubExpr());
883 /* Extract an assume statement from the argument "expr"
884 * of a __pencil_assume statement.
886 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
888 return pet_expr_new_unary(0, pet_op_assume, extract_expr(expr));
891 /* If "expr" is an address-of operator, then return its argument.
892 * Otherwise, return NULL.
894 static Expr *extract_addr_of_arg(Expr *expr)
896 UnaryOperator *op;
898 if (expr->getStmtClass() != Stmt::UnaryOperatorClass)
899 return NULL;
900 op = cast<UnaryOperator>(expr);
901 if (op->getOpcode() != UO_AddrOf)
902 return NULL;
903 return op->getSubExpr();
906 /* Construct a pet_expr corresponding to the function call argument "expr".
907 * The argument appears in position "pos" of a call to function "fd".
909 * If we are passing along a pointer to an array element
910 * or an entire row or even higher dimensional slice of an array,
911 * then the function being called may write into the array.
913 * We assume here that if the function is declared to take a pointer
914 * to a const type, then the function may only perform a read
915 * and that otherwise, it may either perform a read or a write (or both).
916 * We only perform this check if "detect_writes" is set.
918 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
919 Expr *expr, bool detect_writes)
921 Expr *arg;
922 pet_expr *res;
923 int is_addr = 0, is_partial = 0;
925 expr = pet_clang_strip_casts(expr);
926 arg = extract_addr_of_arg(expr);
927 if (arg) {
928 is_addr = 1;
929 expr = arg;
931 res = extract_expr(expr);
932 if (!res)
933 return NULL;
934 if (pet_clang_array_depth(expr->getType()) > 0)
935 is_partial = 1;
936 if (detect_writes && (is_addr || is_partial) &&
937 pet_expr_get_type(res) == pet_expr_access) {
938 ParmVarDecl *parm;
939 if (!fd->hasPrototype()) {
940 report_prototype_required(expr);
941 return pet_expr_free(res);
943 parm = fd->getParamDecl(pos);
944 if (!const_base(parm->getType()))
945 res = mark_may_write(res);
948 if (is_addr)
949 res = pet_expr_new_unary(0, pet_op_address_of, res);
950 return res;
953 /* Find the first FunctionDecl with the given name.
954 * "call" is the corresponding call expression and is only used
955 * for reporting errors.
957 * Return NULL on error.
959 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
961 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
962 DeclContext::decl_iterator begin = tu->decls_begin();
963 DeclContext::decl_iterator end = tu->decls_end();
964 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
965 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
966 if (!fd)
967 continue;
968 if (fd->getName().str().compare(name) != 0)
969 continue;
970 if (fd->hasBody())
971 return fd;
972 report_missing_summary_function_body(call);
973 return NULL;
975 report_missing_summary_function(call);
976 return NULL;
979 /* Return the FunctionDecl for the summary function associated to the
980 * function called by "call".
982 * In particular, if the pencil option is set, then
983 * search for an annotate attribute formatted as
984 * "pencil_access(name)", where "name" is the name of the summary function.
986 * If no summary function was specified, then return the FunctionDecl
987 * that is actually being called.
989 * Return NULL on error.
991 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
993 FunctionDecl *decl = call->getDirectCallee();
994 if (!decl)
995 return NULL;
997 if (!options->pencil)
998 return decl;
1000 specific_attr_iterator<AnnotateAttr> begin, end, i;
1001 begin = decl->specific_attr_begin<AnnotateAttr>();
1002 end = decl->specific_attr_end<AnnotateAttr>();
1003 for (i = begin; i != end; ++i) {
1004 string attr = (*i)->getAnnotation().str();
1006 const char prefix[] = "pencil_access(";
1007 size_t start = attr.find(prefix);
1008 if (start == string::npos)
1009 continue;
1010 start += strlen(prefix);
1011 string name = attr.substr(start, attr.find(')') - start);
1013 return find_decl_from_name(call, name);
1016 return decl;
1019 /* Construct a pet_expr representing a function call.
1021 * In the special case of a "call" to __pencil_assume,
1022 * construct an assume expression instead.
1024 * In the case of a "call" to __pencil_kill, the arguments
1025 * are neither read nor written (only killed), so there
1026 * is no need to check for writes to these arguments.
1028 * __pencil_assume and __pencil_kill are only recognized
1029 * when the pencil option is set.
1031 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1033 pet_expr *res = NULL;
1034 FunctionDecl *fd;
1035 string name;
1036 unsigned n_arg;
1037 bool is_kill;
1039 fd = expr->getDirectCallee();
1040 if (!fd) {
1041 unsupported(expr);
1042 return NULL;
1045 name = fd->getDeclName().getAsString();
1046 n_arg = expr->getNumArgs();
1048 if (options->pencil && n_arg == 1 && name == "__pencil_assume")
1049 return extract_assume(expr->getArg(0));
1050 is_kill = options->pencil && name == "__pencil_kill";
1052 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1053 if (!res)
1054 return NULL;
1056 for (unsigned i = 0; i < n_arg; ++i) {
1057 Expr *arg = expr->getArg(i);
1058 res = pet_expr_set_arg(res, i,
1059 PetScan::extract_argument(fd, i, arg, !is_kill));
1062 fd = get_summary_function(expr);
1063 if (!fd)
1064 return pet_expr_free(res);
1066 res = set_summary(res, fd);
1068 return res;
1071 /* Construct a pet_expr representing a (C style) cast.
1073 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1075 pet_expr *arg;
1076 QualType type;
1078 arg = extract_expr(expr->getSubExpr());
1079 if (!arg)
1080 return NULL;
1082 type = expr->getTypeAsWritten();
1083 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1086 /* Construct a pet_expr representing an integer.
1088 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1090 return pet_expr_new_int(extract_int(expr));
1093 /* Construct a pet_expr representing the integer enum constant "ecd".
1095 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
1097 isl_val *v;
1098 const llvm::APSInt &init = ecd->getInitVal();
1099 v = ::extract_int(ctx, init.isSigned(), init);
1100 return pet_expr_new_int(v);
1103 /* Try and construct a pet_expr representing "expr".
1105 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1107 switch (expr->getStmtClass()) {
1108 case Stmt::UnaryOperatorClass:
1109 return extract_expr(cast<UnaryOperator>(expr));
1110 case Stmt::CompoundAssignOperatorClass:
1111 case Stmt::BinaryOperatorClass:
1112 return extract_expr(cast<BinaryOperator>(expr));
1113 case Stmt::ImplicitCastExprClass:
1114 return extract_expr(cast<ImplicitCastExpr>(expr));
1115 case Stmt::ArraySubscriptExprClass:
1116 case Stmt::DeclRefExprClass:
1117 case Stmt::MemberExprClass:
1118 return extract_access_expr(expr);
1119 case Stmt::IntegerLiteralClass:
1120 return extract_expr(cast<IntegerLiteral>(expr));
1121 case Stmt::FloatingLiteralClass:
1122 return extract_expr(cast<FloatingLiteral>(expr));
1123 case Stmt::ParenExprClass:
1124 return extract_expr(cast<ParenExpr>(expr));
1125 case Stmt::ConditionalOperatorClass:
1126 return extract_expr(cast<ConditionalOperator>(expr));
1127 case Stmt::CallExprClass:
1128 return extract_expr(cast<CallExpr>(expr));
1129 case Stmt::CStyleCastExprClass:
1130 return extract_expr(cast<CStyleCastExpr>(expr));
1131 default:
1132 unsupported(expr);
1134 return NULL;
1137 /* Check if the given initialization statement is an assignment.
1138 * If so, return that assignment. Otherwise return NULL.
1140 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1142 BinaryOperator *ass;
1144 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1145 return NULL;
1147 ass = cast<BinaryOperator>(init);
1148 if (ass->getOpcode() != BO_Assign)
1149 return NULL;
1151 return ass;
1154 /* Check if the given initialization statement is a declaration
1155 * of a single variable.
1156 * If so, return that declaration. Otherwise return NULL.
1158 Decl *PetScan::initialization_declaration(Stmt *init)
1160 DeclStmt *decl;
1162 if (init->getStmtClass() != Stmt::DeclStmtClass)
1163 return NULL;
1165 decl = cast<DeclStmt>(init);
1167 if (!decl->isSingleDecl())
1168 return NULL;
1170 return decl->getSingleDecl();
1173 /* Given the assignment operator in the initialization of a for loop,
1174 * extract the induction variable, i.e., the (integer)variable being
1175 * assigned.
1177 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1179 Expr *lhs;
1180 DeclRefExpr *ref;
1181 ValueDecl *decl;
1182 const Type *type;
1184 lhs = init->getLHS();
1185 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1186 unsupported(init);
1187 return NULL;
1190 ref = cast<DeclRefExpr>(lhs);
1191 decl = ref->getDecl();
1192 type = decl->getType().getTypePtr();
1194 if (!type->isIntegerType()) {
1195 unsupported(lhs);
1196 return NULL;
1199 return decl;
1202 /* Given the initialization statement of a for loop and the single
1203 * declaration in this initialization statement,
1204 * extract the induction variable, i.e., the (integer) variable being
1205 * declared.
1207 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1209 VarDecl *vd;
1211 vd = cast<VarDecl>(decl);
1213 const QualType type = vd->getType();
1214 if (!type->isIntegerType()) {
1215 unsupported(init);
1216 return NULL;
1219 if (!vd->getInit()) {
1220 unsupported(init);
1221 return NULL;
1224 return vd;
1227 /* Check that op is of the form iv++ or iv--.
1228 * Return a pet_expr representing "1" or "-1" accordingly.
1230 __isl_give pet_expr *PetScan::extract_unary_increment(
1231 clang::UnaryOperator *op, clang::ValueDecl *iv)
1233 Expr *sub;
1234 DeclRefExpr *ref;
1235 isl_val *v;
1237 if (!op->isIncrementDecrementOp()) {
1238 unsupported(op);
1239 return NULL;
1242 sub = op->getSubExpr();
1243 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1244 unsupported(op);
1245 return NULL;
1248 ref = cast<DeclRefExpr>(sub);
1249 if (ref->getDecl() != iv) {
1250 unsupported(op);
1251 return NULL;
1254 if (op->isIncrementOp())
1255 v = isl_val_one(ctx);
1256 else
1257 v = isl_val_negone(ctx);
1259 return pet_expr_new_int(v);
1262 /* Check if op is of the form
1264 * iv = expr
1266 * and return the increment "expr - iv" as a pet_expr.
1268 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1269 clang::ValueDecl *iv)
1271 int type_size;
1272 Expr *lhs;
1273 DeclRefExpr *ref;
1274 pet_expr *expr, *expr_iv;
1276 if (op->getOpcode() != BO_Assign) {
1277 unsupported(op);
1278 return NULL;
1281 lhs = op->getLHS();
1282 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1283 unsupported(op);
1284 return NULL;
1287 ref = cast<DeclRefExpr>(lhs);
1288 if (ref->getDecl() != iv) {
1289 unsupported(op);
1290 return NULL;
1293 expr = extract_expr(op->getRHS());
1294 expr_iv = extract_expr(lhs);
1296 type_size = pet_clang_get_type_size(iv->getType(), ast_context);
1297 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1300 /* Check that op is of the form iv += cst or iv -= cst
1301 * and return a pet_expr corresponding to cst or -cst accordingly.
1303 __isl_give pet_expr *PetScan::extract_compound_increment(
1304 CompoundAssignOperator *op, clang::ValueDecl *iv)
1306 Expr *lhs;
1307 DeclRefExpr *ref;
1308 bool neg = false;
1309 pet_expr *expr;
1310 BinaryOperatorKind opcode;
1312 opcode = op->getOpcode();
1313 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1314 unsupported(op);
1315 return NULL;
1317 if (opcode == BO_SubAssign)
1318 neg = true;
1320 lhs = op->getLHS();
1321 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1322 unsupported(op);
1323 return NULL;
1326 ref = cast<DeclRefExpr>(lhs);
1327 if (ref->getDecl() != iv) {
1328 unsupported(op);
1329 return NULL;
1332 expr = extract_expr(op->getRHS());
1333 if (neg) {
1334 int type_size;
1335 type_size = pet_clang_get_type_size(op->getType(), ast_context);
1336 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1339 return expr;
1342 /* Check that the increment of the given for loop increments
1343 * (or decrements) the induction variable "iv" and return
1344 * the increment as a pet_expr if successful.
1346 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1347 ValueDecl *iv)
1349 Stmt *inc = stmt->getInc();
1351 if (!inc) {
1352 report_missing_increment(stmt);
1353 return NULL;
1356 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1357 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1358 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1359 return extract_compound_increment(
1360 cast<CompoundAssignOperator>(inc), iv);
1361 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1362 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1364 unsupported(inc);
1365 return NULL;
1368 /* Construct a pet_tree for a while loop.
1370 * If we were only able to extract part of the body, then simply
1371 * return that part.
1373 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1375 pet_expr *pe_cond;
1376 pet_tree *tree;
1378 tree = extract(stmt->getBody());
1379 if (partial)
1380 return tree;
1381 pe_cond = extract_expr(stmt->getCond());
1382 tree = pet_tree_new_while(pe_cond, tree);
1384 return tree;
1387 /* Construct a pet_tree for a for statement.
1388 * The for loop is required to be of one of the following forms
1390 * for (i = init; condition; ++i)
1391 * for (i = init; condition; --i)
1392 * for (i = init; condition; i += constant)
1393 * for (i = init; condition; i -= constant)
1395 * We extract a pet_tree for the body and then include it in a pet_tree
1396 * of type pet_tree_for.
1398 * As a special case, we also allow a for loop of the form
1400 * for (;;)
1402 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1404 * If we were only able to extract part of the body, then simply
1405 * return that part.
1407 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1409 BinaryOperator *ass;
1410 Decl *decl;
1411 Stmt *init;
1412 Expr *lhs, *rhs;
1413 ValueDecl *iv;
1414 pet_tree *tree;
1415 int independent;
1416 int declared;
1417 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1419 independent = is_current_stmt_marked_independent();
1421 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1422 tree = extract(stmt->getBody());
1423 if (partial)
1424 return tree;
1425 tree = pet_tree_new_infinite_loop(tree);
1426 return tree;
1429 init = stmt->getInit();
1430 if (!init) {
1431 unsupported(stmt);
1432 return NULL;
1434 if ((ass = initialization_assignment(init)) != NULL) {
1435 iv = extract_induction_variable(ass);
1436 if (!iv)
1437 return NULL;
1438 lhs = ass->getLHS();
1439 rhs = ass->getRHS();
1440 } else if ((decl = initialization_declaration(init)) != NULL) {
1441 VarDecl *var = extract_induction_variable(init, decl);
1442 if (!var)
1443 return NULL;
1444 iv = var;
1445 rhs = var->getInit();
1446 lhs = create_DeclRefExpr(var);
1447 } else {
1448 unsupported(stmt->getInit());
1449 return NULL;
1452 declared = !initialization_assignment(stmt->getInit());
1453 tree = extract(stmt->getBody());
1454 if (partial)
1455 return tree;
1456 pe_iv = extract_access_expr(iv);
1457 pe_iv = mark_write(pe_iv);
1458 pe_init = extract_expr(rhs);
1459 if (!stmt->getCond())
1460 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1461 else
1462 pe_cond = extract_expr(stmt->getCond());
1463 pe_inc = extract_increment(stmt, iv);
1464 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1465 pe_inc, tree);
1466 return tree;
1469 /* Store the names of the variables declared in decl_context
1470 * in the set declared_names. Make sure to only do this once by
1471 * setting declared_names_collected.
1473 void PetScan::collect_declared_names()
1475 DeclContext *DC = decl_context;
1476 DeclContext::decl_iterator it;
1478 if (declared_names_collected)
1479 return;
1481 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1482 Decl *D = *it;
1483 NamedDecl *named;
1485 if (!isa<NamedDecl>(D))
1486 continue;
1487 named = cast<NamedDecl>(D);
1488 declared_names.insert(named->getName().str());
1491 declared_names_collected = true;
1494 /* Add the names in "names" that are not also in this->declared_names
1495 * to this->used_names.
1496 * It is up to the caller to make sure that declared_names has been
1497 * populated, if needed.
1499 void PetScan::add_new_used_names(const std::set<std::string> &names)
1501 std::set<std::string>::const_iterator it;
1503 for (it = names.begin(); it != names.end(); ++it) {
1504 if (declared_names.find(*it) != declared_names.end())
1505 continue;
1506 used_names.insert(*it);
1510 /* Is the name "name" used in any declaration other than "decl"?
1512 * If the name was found to be in use before, the consider it to be in use.
1513 * Otherwise, check the DeclContext of the function containing the scop
1514 * as well as all ancestors of this DeclContext for declarations
1515 * other than "decl" that declare something called "name".
1517 bool PetScan::name_in_use(const string &name, Decl *decl)
1519 DeclContext *DC;
1520 DeclContext::decl_iterator it;
1522 if (used_names.find(name) != used_names.end())
1523 return true;
1525 for (DC = decl_context; DC; DC = DC->getParent()) {
1526 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1527 Decl *D = *it;
1528 NamedDecl *named;
1530 if (D == decl)
1531 continue;
1532 if (!isa<NamedDecl>(D))
1533 continue;
1534 named = cast<NamedDecl>(D);
1535 if (named->getName().str() == name)
1536 return true;
1540 return false;
1543 /* Generate a new name based on "name" that is not in use.
1544 * Do so by adding a suffix _i, with i an integer.
1546 string PetScan::generate_new_name(const string &name)
1548 string new_name;
1550 do {
1551 std::ostringstream oss;
1552 oss << name << "_" << n_rename++;
1553 new_name = oss.str();
1554 } while (name_in_use(new_name, NULL));
1556 return new_name;
1559 /* Try and construct a pet_tree corresponding to a compound statement.
1561 * "skip_declarations" is set if we should skip initial declarations
1562 * in the children of the compound statements.
1564 * Collect a new set of declarations for the current compound statement.
1565 * If any of the names in these declarations is also used by another
1566 * declaration reachable from the current function, then rename it
1567 * to a name that is not already in use.
1568 * In particular, keep track of the old and new names in a pet_substituter
1569 * and apply the substitutions to the pet_tree corresponding to the
1570 * compound statement.
1572 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1573 bool skip_declarations)
1575 pet_tree *tree;
1576 std::vector<VarDecl *> saved_declarations;
1577 std::vector<VarDecl *>::iterator it;
1578 pet_substituter substituter;
1580 saved_declarations = declarations;
1581 declarations.clear();
1582 tree = extract(stmt->children(), true, skip_declarations);
1583 for (it = declarations.begin(); it != declarations.end(); ++it) {
1584 isl_id *id;
1585 pet_expr *expr;
1586 VarDecl *decl = *it;
1587 string name = decl->getName().str();
1588 bool in_use = name_in_use(name, decl);
1590 used_names.insert(name);
1591 if (!in_use)
1592 continue;
1594 name = generate_new_name(name);
1595 id = pet_id_from_name_and_decl(ctx, name.c_str(), decl);
1596 expr = pet_id_create_index_expr(id);
1597 expr = extract_access_expr(decl->getType(), expr);
1598 id = pet_id_from_decl(ctx, decl);
1599 substituter.add_sub(id, expr);
1600 used_names.insert(name);
1602 tree = substituter.substitute(tree);
1603 declarations = saved_declarations;
1605 return tree;
1608 /* Return the file offset of the expansion location of "Loc".
1610 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1612 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1615 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1617 /* Return a SourceLocation for the location after the first semicolon
1618 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1619 * call it and also skip trailing spaces and newline.
1621 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1622 const LangOptions &LO)
1624 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1627 #else
1629 /* Return a SourceLocation for the location after the first semicolon
1630 * after "loc". If Lexer::findLocationAfterToken is not available,
1631 * we look in the underlying character data for the first semicolon.
1633 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1634 const LangOptions &LO)
1636 const char *semi;
1637 const char *s = SM.getCharacterData(loc);
1639 semi = strchr(s, ';');
1640 if (!semi)
1641 return SourceLocation();
1642 return loc.getFileLocWithOffset(semi + 1 - s);
1645 #endif
1647 /* If the token at "loc" is the first token on the line, then return
1648 * a location referring to the start of the line and set *indent
1649 * to the indentation of "loc"
1650 * Otherwise, return "loc" and set *indent to "".
1652 * This function is used to extend a scop to the start of the line
1653 * if the first token of the scop is also the first token on the line.
1655 * We look for the first token on the line. If its location is equal to "loc",
1656 * then the latter is the location of the first token on the line.
1658 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1659 SourceManager &SM, const LangOptions &LO, char **indent)
1661 std::pair<FileID, unsigned> file_offset_pair;
1662 llvm::StringRef file;
1663 const char *pos;
1664 Token tok;
1665 SourceLocation token_loc, line_loc;
1666 int col;
1667 const char *s;
1669 loc = SM.getExpansionLoc(loc);
1670 col = SM.getExpansionColumnNumber(loc);
1671 line_loc = loc.getLocWithOffset(1 - col);
1672 file_offset_pair = SM.getDecomposedLoc(line_loc);
1673 file = SM.getBufferData(file_offset_pair.first, NULL);
1674 pos = file.data() + file_offset_pair.second;
1676 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1677 file.begin(), pos, file.end());
1678 lexer.LexFromRawLexer(tok);
1679 token_loc = tok.getLocation();
1681 s = SM.getCharacterData(line_loc);
1682 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1684 if (token_loc == loc)
1685 return line_loc;
1686 else
1687 return loc;
1690 /* Construct a pet_loc corresponding to the region covered by "range".
1691 * If "skip_semi" is set, then we assume "range" is followed by
1692 * a semicolon and also include this semicolon.
1694 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1695 bool skip_semi)
1697 SourceLocation loc = range.getBegin();
1698 SourceManager &SM = PP.getSourceManager();
1699 const LangOptions &LO = PP.getLangOpts();
1700 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1701 unsigned start, end;
1702 char *indent;
1704 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1705 start = getExpansionOffset(SM, loc);
1706 loc = range.getEnd();
1707 if (skip_semi)
1708 loc = location_after_semi(loc, SM, LO);
1709 else
1710 loc = PP.getLocForEndOfToken(loc);
1711 end = getExpansionOffset(SM, loc);
1713 return pet_loc_alloc(ctx, start, end, line, indent);
1716 /* Convert a top-level pet_expr to an expression pet_tree.
1718 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1719 SourceRange range, bool skip_semi)
1721 pet_loc *loc;
1722 pet_tree *tree;
1724 tree = pet_tree_new_expr(expr);
1725 loc = construct_pet_loc(range, skip_semi);
1726 tree = pet_tree_set_loc(tree, loc);
1728 return tree;
1731 /* Construct a pet_tree for an if statement.
1733 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1735 pet_expr *pe_cond;
1736 pet_tree *tree, *tree_else;
1738 pe_cond = extract_expr(stmt->getCond());
1739 tree = extract(stmt->getThen());
1740 if (stmt->getElse()) {
1741 tree_else = extract(stmt->getElse());
1742 if (options->autodetect) {
1743 if (tree && !tree_else) {
1744 partial = true;
1745 pet_expr_free(pe_cond);
1746 return tree;
1748 if (!tree && tree_else) {
1749 partial = true;
1750 pet_expr_free(pe_cond);
1751 return tree_else;
1754 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1755 } else
1756 tree = pet_tree_new_if(pe_cond, tree);
1757 return tree;
1760 /* Try and construct a pet_tree for a label statement.
1762 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1764 isl_id *label;
1765 pet_tree *tree;
1767 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1769 tree = extract(stmt->getSubStmt());
1770 tree = pet_tree_set_label(tree, label);
1771 return tree;
1774 /* Update the location of "tree" to include the source range of "stmt".
1776 * Actually, we create a new location based on the source range of "stmt" and
1777 * then extend this new location to include the region of the original location.
1778 * This ensures that the line number of the final location refers to "stmt".
1780 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1782 pet_loc *loc, *tree_loc;
1784 tree_loc = pet_tree_get_loc(tree);
1785 loc = construct_pet_loc(stmt->getSourceRange(), false);
1786 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1787 pet_loc_free(tree_loc);
1789 tree = pet_tree_set_loc(tree, loc);
1790 return tree;
1793 /* Is "expr" of a type that can be converted to an access expression?
1795 static bool is_access_expr_type(Expr *expr)
1797 switch (expr->getStmtClass()) {
1798 case Stmt::ArraySubscriptExprClass:
1799 case Stmt::DeclRefExprClass:
1800 case Stmt::MemberExprClass:
1801 return true;
1802 default:
1803 return false;
1807 /* Tell the pet_inliner "inliner" about the formal arguments
1808 * in "fd" and the corresponding actual arguments in "call".
1809 * Return 0 if this was successful and -1 otherwise.
1811 * Any pointer argument is treated as an array.
1812 * The other arguments are treated as scalars.
1814 * In case of scalars, there is no restriction on the actual argument.
1815 * This actual argument is assigned to a variable with a name
1816 * that is derived from the name of the corresponding formal argument,
1817 * but made not to conflict with any variable names that are
1818 * already in use.
1820 * In case of arrays, the actual argument needs to be an expression
1821 * of a type that can be converted to an access expression or the address
1822 * of such an expression, ignoring implicit and redundant casts.
1824 int PetScan::set_inliner_arguments(pet_inliner &inliner, CallExpr *call,
1825 FunctionDecl *fd)
1827 unsigned n;
1829 n = fd->getNumParams();
1830 for (unsigned i = 0; i < n; ++i) {
1831 ParmVarDecl *parm = fd->getParamDecl(i);
1832 QualType type = parm->getType();
1833 Expr *arg, *sub;
1834 pet_expr *expr;
1835 int is_addr = 0;
1837 arg = call->getArg(i);
1838 if (pet_clang_array_depth(type) == 0) {
1839 string name = parm->getName().str();
1840 if (name_in_use(name, NULL))
1841 name = generate_new_name(name);
1842 inliner.add_scalar_arg(parm, name, extract_expr(arg));
1843 continue;
1845 arg = pet_clang_strip_casts(arg);
1846 sub = extract_addr_of_arg(arg);
1847 if (sub) {
1848 is_addr = 1;
1849 arg = pet_clang_strip_casts(sub);
1851 if (!is_access_expr_type(arg)) {
1852 report_unsupported_inline_function_argument(arg);
1853 return -1;
1855 expr = extract_access_expr(arg);
1856 if (!expr)
1857 return -1;
1858 inliner.add_array_arg(parm, expr, is_addr);
1861 return 0;
1864 /* Try and construct a pet_tree from the body of "fd" using the actual
1865 * arguments in "call" in place of the formal arguments.
1866 * "fd" is assumed to point to the declaration with a function body.
1867 * In particular, construct a block that consists of assignments
1868 * of (parts of) the actual arguments to temporary variables
1869 * followed by the inlined function body with the formal arguments
1870 * replaced by (expressions containing) these temporary variables.
1872 * The actual inlining is taken care of by the pet_inliner function.
1873 * This function merely calls set_inliner_arguments to tell
1874 * the pet_inliner about the actual arguments, extracts a pet_tree
1875 * from the body of the called function and then passes this pet_tree
1876 * to the pet_inliner.
1878 * During the extraction of the function body, all variables names
1879 * that are declared in the calling function as well all variable
1880 * names that are known to be in use are considered to be in use
1881 * in the called function to ensure that there is no naming conflict.
1882 * Similarly, the additional names that are in use in the called function
1883 * are considered to be in use in the calling function as well.
1885 * The location of the pet_tree is reset to the call site to ensure
1886 * that the extent of the scop does not include the body of the called
1887 * function.
1889 __isl_give pet_tree *PetScan::extract_inlined_call(CallExpr *call,
1890 FunctionDecl *fd)
1892 int save_autodetect;
1893 pet_tree *tree;
1894 pet_loc *tree_loc;
1895 pet_inliner inliner(ctx, n_arg, ast_context);
1897 if (set_inliner_arguments(inliner, call, fd) < 0)
1898 return NULL;
1900 save_autodetect = options->autodetect;
1901 options->autodetect = 0;
1902 PetScan body_scan(PP, ast_context, fd, loc, options,
1903 isl_union_map_copy(value_bounds), independent);
1904 collect_declared_names();
1905 body_scan.add_new_used_names(declared_names);
1906 body_scan.add_new_used_names(used_names);
1907 tree = body_scan.extract(fd->getBody(), false);
1908 add_new_used_names(body_scan.used_names);
1909 options->autodetect = save_autodetect;
1911 tree_loc = construct_pet_loc(call->getSourceRange(), true);
1912 tree = pet_tree_set_loc(tree, tree_loc);
1914 return inliner.inline_tree(tree);
1917 /* Try and construct a pet_tree corresponding
1918 * to the expression statement "stmt".
1920 * If the outer expression is a function call and if the corresponding
1921 * function body is marked "inline", then return a pet_tree
1922 * corresponding to the inlined function.
1924 __isl_give pet_tree *PetScan::extract_expr_stmt(Stmt *stmt)
1926 pet_expr *expr;
1928 if (stmt->getStmtClass() == Stmt::CallExprClass) {
1929 CallExpr *call = cast<CallExpr>(stmt);
1930 FunctionDecl *fd = call->getDirectCallee();
1931 fd = pet_clang_find_function_decl_with_body(fd);
1932 if (fd && fd->isInlineSpecified())
1933 return extract_inlined_call(call, fd);
1936 expr = extract_expr(cast<Expr>(stmt));
1937 return extract(expr, stmt->getSourceRange(), true);
1940 /* Try and construct a pet_tree corresponding to "stmt".
1942 * If "stmt" is a compound statement, then "skip_declarations"
1943 * indicates whether we should skip initial declarations in the
1944 * compound statement.
1946 * If the constructed pet_tree is not a (possibly) partial representation
1947 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1948 * In particular, if skip_declarations is set, then we may have skipped
1949 * declarations inside "stmt" and so the pet_scop may not represent
1950 * the entire "stmt".
1951 * Note that this function may be called with "stmt" referring to the entire
1952 * body of the function, including the outer braces. In such cases,
1953 * skip_declarations will be set and the braces will not be taken into
1954 * account in tree->loc.
1956 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
1958 pet_tree *tree;
1960 set_current_stmt(stmt);
1962 if (isa<Expr>(stmt))
1963 return extract_expr_stmt(cast<Expr>(stmt));
1965 switch (stmt->getStmtClass()) {
1966 case Stmt::WhileStmtClass:
1967 tree = extract(cast<WhileStmt>(stmt));
1968 break;
1969 case Stmt::ForStmtClass:
1970 tree = extract_for(cast<ForStmt>(stmt));
1971 break;
1972 case Stmt::IfStmtClass:
1973 tree = extract(cast<IfStmt>(stmt));
1974 break;
1975 case Stmt::CompoundStmtClass:
1976 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
1977 break;
1978 case Stmt::LabelStmtClass:
1979 tree = extract(cast<LabelStmt>(stmt));
1980 break;
1981 case Stmt::ContinueStmtClass:
1982 tree = pet_tree_new_continue(ctx);
1983 break;
1984 case Stmt::BreakStmtClass:
1985 tree = pet_tree_new_break(ctx);
1986 break;
1987 case Stmt::DeclStmtClass:
1988 tree = extract(cast<DeclStmt>(stmt));
1989 break;
1990 default:
1991 report_unsupported_statement_type(stmt);
1992 return NULL;
1995 if (partial || skip_declarations)
1996 return tree;
1998 return update_loc(tree, stmt);
2001 /* Given a sequence of statements "stmt_range" of which the first "n_decl"
2002 * are declarations and of which the remaining statements are represented
2003 * by "tree", try and extend "tree" to include the last sequence of
2004 * the initial declarations that can be completely extracted.
2006 * We start collecting the initial declarations and start over
2007 * whenever we come across a declaration that we cannot extract.
2008 * If we have been able to extract any declarations, then we
2009 * copy over the contents of "tree" at the end of the declarations.
2010 * Otherwise, we simply return the original "tree".
2012 __isl_give pet_tree *PetScan::insert_initial_declarations(
2013 __isl_take pet_tree *tree, int n_decl, StmtRange stmt_range)
2015 StmtIterator i;
2016 pet_tree *res;
2017 int n_stmt;
2018 int is_block;
2019 int j;
2021 n_stmt = pet_tree_block_n_child(tree);
2022 is_block = pet_tree_block_get_block(tree);
2023 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2025 for (i = stmt_range.first; n_decl; ++i, --n_decl) {
2026 Stmt *child = *i;
2027 pet_tree *tree_i;
2029 tree_i = extract(child);
2030 if (tree_i && !partial) {
2031 res = pet_tree_block_add_child(res, tree_i);
2032 continue;
2034 pet_tree_free(tree_i);
2035 partial = false;
2036 if (pet_tree_block_n_child(res) == 0)
2037 continue;
2038 pet_tree_free(res);
2039 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2042 if (pet_tree_block_n_child(res) == 0) {
2043 pet_tree_free(res);
2044 return tree;
2047 for (j = 0; j < n_stmt; ++j) {
2048 pet_tree *tree_i;
2050 tree_i = pet_tree_block_get_child(tree, j);
2051 res = pet_tree_block_add_child(res, tree_i);
2053 pet_tree_free(tree);
2055 return res;
2058 /* Try and construct a pet_tree corresponding to (part of)
2059 * a sequence of statements.
2061 * "block" is set if the sequence represents the children of
2062 * a compound statement.
2063 * "skip_declarations" is set if we should skip initial declarations
2064 * in the sequence of statements.
2066 * If autodetect is set, then we allow the extraction of only a subrange
2067 * of the sequence of statements. However, if there is at least one
2068 * kill and there is some subsequent statement for which we could not
2069 * construct a tree, then turn off the "block" property of the tree
2070 * such that no extra kill will be introduced at the end of the (partial)
2071 * block. If, on the other hand, the final range contains
2072 * no statements, then we discard the entire range.
2074 * If the entire range was extracted, apart from some initial declarations,
2075 * then we try and extend the range with the latest of those initial
2076 * declarations.
2078 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
2079 bool skip_declarations)
2081 StmtIterator i;
2082 int j, skip;
2083 bool has_kills = false;
2084 bool partial_range = false;
2085 pet_tree *tree;
2087 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
2090 tree = pet_tree_new_block(ctx, block, j);
2092 skip = 0;
2093 i = stmt_range.first;
2094 if (skip_declarations)
2095 for (; i != stmt_range.second; ++i) {
2096 if ((*i)->getStmtClass() != Stmt::DeclStmtClass)
2097 break;
2098 ++skip;
2101 for (; i != stmt_range.second; ++i) {
2102 Stmt *child = *i;
2103 pet_tree *tree_i;
2105 tree_i = extract(child);
2106 if (pet_tree_block_n_child(tree) != 0 && partial) {
2107 pet_tree_free(tree_i);
2108 break;
2110 if (tree_i && child->getStmtClass() == Stmt::DeclStmtClass &&
2111 block)
2112 has_kills = true;
2113 if (options->autodetect) {
2114 if (tree_i)
2115 tree = pet_tree_block_add_child(tree, tree_i);
2116 else
2117 partial_range = true;
2118 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
2119 partial = true;
2120 } else {
2121 tree = pet_tree_block_add_child(tree, tree_i);
2124 if (partial || !tree)
2125 break;
2128 if (!tree)
2129 return NULL;
2131 if (partial) {
2132 if (has_kills)
2133 tree = pet_tree_block_set_block(tree, 0);
2134 } else if (partial_range) {
2135 if (pet_tree_block_n_child(tree) == 0) {
2136 pet_tree_free(tree);
2137 return NULL;
2139 partial = true;
2140 } else if (skip > 0)
2141 tree = insert_initial_declarations(tree, skip, stmt_range);
2143 return tree;
2146 extern "C" {
2147 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2148 void *user);
2149 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2150 __isl_keep pet_context *pc, void *user);
2153 /* Construct a pet_expr that holds the sizes of the array accessed
2154 * by "access".
2155 * This function is used as a callback to pet_context_add_parameters,
2156 * which is also passed a pointer to the PetScan object.
2158 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2159 void *user)
2161 PetScan *ps = (PetScan *) user;
2162 isl_id *id;
2163 QualType qt;
2165 id = pet_expr_access_get_id(access);
2166 qt = pet_id_get_array_type(id);
2167 isl_id_free(id);
2168 return ps->get_array_size(qt);
2171 /* Construct and return a pet_array corresponding to the variable
2172 * accessed by "access".
2173 * This function is used as a callback to pet_scop_from_pet_tree,
2174 * which is also passed a pointer to the PetScan object.
2176 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2177 __isl_keep pet_context *pc, void *user)
2179 PetScan *ps = (PetScan *) user;
2180 isl_ctx *ctx;
2181 isl_id *id;
2182 pet_array *array;
2184 ctx = pet_expr_get_ctx(access);
2185 id = pet_expr_access_get_id(access);
2186 array = ps->extract_array(id, NULL, pc);
2187 isl_id_free(id);
2189 return array;
2192 /* Extract a function summary from the body of "fd".
2194 * We extract a scop from the function body in a context with as
2195 * parameters the integer arguments of the function.
2196 * We turn off autodetection (in case it was set) to ensure that
2197 * the entire function body is considered.
2198 * We then collect the accessed array elements and attach them
2199 * to the corresponding array arguments, taking into account
2200 * that the function body may access members of array elements.
2202 * The reason for representing the integer arguments as parameters in
2203 * the context is that if we were to instead start with a context
2204 * with the function arguments as initial dimensions, then we would not
2205 * be able to refer to them from the array extents, without turning
2206 * array extents into maps.
2208 * The result is stored in the summary_cache cache so that we can reuse
2209 * it if this method gets called on the same function again later on.
2211 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
2213 isl_space *space;
2214 isl_set *domain;
2215 pet_context *pc;
2216 pet_tree *tree;
2217 pet_function_summary *summary;
2218 unsigned n;
2219 ScopLoc loc;
2220 int save_autodetect;
2221 struct pet_scop *scop;
2222 int int_size;
2223 isl_union_set *may_read, *may_write, *must_write;
2224 isl_union_map *to_inner;
2226 if (summary_cache.find(fd) != summary_cache.end())
2227 return pet_function_summary_copy(summary_cache[fd]);
2229 space = isl_space_set_alloc(ctx, 0, 0);
2231 n = fd->getNumParams();
2232 summary = pet_function_summary_alloc(ctx, n);
2233 for (unsigned i = 0; i < n; ++i) {
2234 ParmVarDecl *parm = fd->getParamDecl(i);
2235 QualType type = parm->getType();
2236 isl_id *id;
2238 if (!type->isIntegerType())
2239 continue;
2240 id = pet_id_from_decl(ctx, parm);
2241 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
2242 space = isl_space_set_dim_id(space, isl_dim_param, 0,
2243 isl_id_copy(id));
2244 summary = pet_function_summary_set_int(summary, i, id);
2247 save_autodetect = options->autodetect;
2248 options->autodetect = 0;
2249 PetScan body_scan(PP, ast_context, fd, loc, options,
2250 isl_union_map_copy(value_bounds), independent);
2252 tree = body_scan.extract(fd->getBody(), false);
2254 domain = isl_set_universe(space);
2255 pc = pet_context_alloc(domain);
2256 pc = pet_context_add_parameters(pc, tree,
2257 &::get_array_size, &body_scan);
2258 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2259 scop = pet_scop_from_pet_tree(tree, int_size,
2260 &::extract_array, &body_scan, pc);
2261 scop = scan_arrays(scop, pc);
2262 may_read = isl_union_map_range(pet_scop_get_may_reads(scop));
2263 may_write = isl_union_map_range(pet_scop_get_may_writes(scop));
2264 must_write = isl_union_map_range(pet_scop_get_must_writes(scop));
2265 to_inner = pet_scop_compute_outer_to_inner(scop);
2266 pet_scop_free(scop);
2268 for (unsigned i = 0; i < n; ++i) {
2269 ParmVarDecl *parm = fd->getParamDecl(i);
2270 QualType type = parm->getType();
2271 struct pet_array *array;
2272 isl_space *space;
2273 isl_union_set *data_set;
2274 isl_union_set *may_read_i, *may_write_i, *must_write_i;
2276 if (pet_clang_array_depth(type) == 0)
2277 continue;
2279 array = body_scan.extract_array(parm, NULL, pc);
2280 space = array ? isl_set_get_space(array->extent) : NULL;
2281 pet_array_free(array);
2282 data_set = isl_union_set_from_set(isl_set_universe(space));
2283 data_set = isl_union_set_apply(data_set,
2284 isl_union_map_copy(to_inner));
2285 may_read_i = isl_union_set_intersect(
2286 isl_union_set_copy(may_read),
2287 isl_union_set_copy(data_set));
2288 may_write_i = isl_union_set_intersect(
2289 isl_union_set_copy(may_write),
2290 isl_union_set_copy(data_set));
2291 must_write_i = isl_union_set_intersect(
2292 isl_union_set_copy(must_write), data_set);
2293 summary = pet_function_summary_set_array(summary, i,
2294 may_read_i, may_write_i, must_write_i);
2297 isl_union_set_free(may_read);
2298 isl_union_set_free(may_write);
2299 isl_union_set_free(must_write);
2300 isl_union_map_free(to_inner);
2302 options->autodetect = save_autodetect;
2303 pet_context_free(pc);
2305 summary_cache[fd] = pet_function_summary_copy(summary);
2307 return summary;
2310 /* If "fd" has a function body, then extract a function summary from
2311 * this body and attach it to the call expression "expr".
2313 * Even if a function body is available, "fd" itself may point
2314 * to a declaration without function body. We therefore first
2315 * replace it by the declaration that comes with a body (if any).
2317 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
2318 FunctionDecl *fd)
2320 pet_function_summary *summary;
2322 if (!expr)
2323 return NULL;
2324 fd = pet_clang_find_function_decl_with_body(fd);
2325 if (!fd)
2326 return expr;
2328 summary = get_summary(fd);
2330 expr = pet_expr_call_set_summary(expr, summary);
2332 return expr;
2335 /* Extract a pet_scop from "tree".
2337 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
2338 * then add pet_arrays for all accessed arrays.
2339 * We populate the pet_context with assignments for all parameters used
2340 * inside "tree" or any of the size expressions for the arrays accessed
2341 * by "tree" so that they can be used in affine expressions.
2343 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
2345 int int_size;
2346 isl_set *domain;
2347 pet_context *pc;
2348 pet_scop *scop;
2350 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2352 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2353 pc = pet_context_alloc(domain);
2354 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
2355 scop = pet_scop_from_pet_tree(tree, int_size,
2356 &::extract_array, this, pc);
2357 scop = scan_arrays(scop, pc);
2358 pet_context_free(pc);
2360 return scop;
2363 /* Add a call to __pencil_kill to the end of "tree" that kills
2364 * all the variables in "locals" and return the result.
2366 * No location is added to the kill because the most natural
2367 * location would lie outside the scop. Attaching such a location
2368 * to this tree would extend the scope of the final result
2369 * to include the location.
2371 __isl_give pet_tree *PetScan::add_kills(__isl_take pet_tree *tree,
2372 set<ValueDecl *> locals)
2374 int i;
2375 pet_expr *expr;
2376 pet_tree *kill, *block;
2377 set<ValueDecl *>::iterator it;
2379 if (locals.size() == 0)
2380 return tree;
2381 expr = pet_expr_new_call(ctx, "__pencil_kill", locals.size());
2382 i = 0;
2383 for (it = locals.begin(); it != locals.end(); ++it) {
2384 pet_expr *arg;
2385 arg = extract_access_expr(*it);
2386 expr = pet_expr_set_arg(expr, i++, arg);
2388 kill = pet_tree_new_expr(expr);
2389 block = pet_tree_new_block(ctx, 0, 2);
2390 block = pet_tree_block_add_child(block, tree);
2391 block = pet_tree_block_add_child(block, kill);
2393 return block;
2396 /* Check if the scop marked by the user is exactly this Stmt
2397 * or part of this Stmt.
2398 * If so, return a pet_scop corresponding to the marked region.
2399 * Otherwise, return NULL.
2401 * If the scop is not further nested inside a child of "stmt",
2402 * then check if there are any variable declarations before the scop
2403 * inside "stmt". If so, and if these variables are not used
2404 * after the scop, then add kills to the variables.
2406 struct pet_scop *PetScan::scan(Stmt *stmt)
2408 SourceManager &SM = PP.getSourceManager();
2409 unsigned start_off, end_off;
2410 pet_tree *tree;
2412 start_off = getExpansionOffset(SM, stmt->getLocStart());
2413 end_off = getExpansionOffset(SM, stmt->getLocEnd());
2415 if (start_off > loc.end)
2416 return NULL;
2417 if (end_off < loc.start)
2418 return NULL;
2420 if (start_off >= loc.start && end_off <= loc.end)
2421 return extract_scop(extract(stmt));
2423 pet_killed_locals kl(SM);
2424 StmtIterator start;
2425 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
2426 Stmt *child = *start;
2427 if (!child)
2428 continue;
2429 start_off = getExpansionOffset(SM, child->getLocStart());
2430 end_off = getExpansionOffset(SM, child->getLocEnd());
2431 if (start_off < loc.start && end_off >= loc.end)
2432 return scan(child);
2433 if (start_off >= loc.start)
2434 break;
2435 if (isa<DeclStmt>(child))
2436 kl.add_locals(cast<DeclStmt>(child));
2439 StmtIterator end;
2440 for (end = start; end != stmt->child_end(); ++end) {
2441 Stmt *child = *end;
2442 start_off = SM.getFileOffset(child->getLocStart());
2443 if (start_off >= loc.end)
2444 break;
2447 kl.remove_accessed_after(stmt, loc.start, loc.end);
2449 tree = extract(StmtRange(start, end), false, false);
2450 tree = add_kills(tree, kl.locals);
2451 return extract_scop(tree);
2454 /* Set the size of index "pos" of "array" to "size".
2455 * In particular, add a constraint of the form
2457 * i_pos < size
2459 * to array->extent and a constraint of the form
2461 * size >= 0
2463 * to array->context.
2465 * The domain of "size" is assumed to be zero-dimensional.
2467 static struct pet_array *update_size(struct pet_array *array, int pos,
2468 __isl_take isl_pw_aff *size)
2470 isl_set *valid;
2471 isl_set *univ;
2472 isl_set *bound;
2473 isl_space *dim;
2474 isl_aff *aff;
2475 isl_pw_aff *index;
2476 isl_id *id;
2478 if (!array)
2479 goto error;
2481 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2482 array->context = isl_set_intersect(array->context, valid);
2484 dim = isl_set_get_space(array->extent);
2485 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2486 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2487 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2488 index = isl_pw_aff_alloc(univ, aff);
2490 size = isl_pw_aff_add_dims(size, isl_dim_in,
2491 isl_set_dim(array->extent, isl_dim_set));
2492 id = isl_set_get_tuple_id(array->extent);
2493 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2494 bound = isl_pw_aff_lt_set(index, size);
2496 array->extent = isl_set_intersect(array->extent, bound);
2498 if (!array->context || !array->extent)
2499 return pet_array_free(array);
2501 return array;
2502 error:
2503 isl_pw_aff_free(size);
2504 return NULL;
2507 #ifdef HAVE_DECAYEDTYPE
2509 /* If "qt" is a decayed type, then set *decayed to true and
2510 * return the original type.
2512 static QualType undecay(QualType qt, bool *decayed)
2514 const Type *type = qt.getTypePtr();
2516 *decayed = isa<DecayedType>(type);
2517 if (*decayed)
2518 qt = cast<DecayedType>(type)->getOriginalType();
2519 return qt;
2522 #else
2524 /* If "qt" is a decayed type, then set *decayed to true and
2525 * return the original type.
2526 * Since this version of clang does not define a DecayedType,
2527 * we cannot obtain the original type even if it had been decayed and
2528 * we set *decayed to false.
2530 static QualType undecay(QualType qt, bool *decayed)
2532 *decayed = false;
2533 return qt;
2536 #endif
2538 /* Figure out the size of the array at position "pos" and all
2539 * subsequent positions from "qt" and update the corresponding
2540 * argument of "expr" accordingly.
2542 * The initial type (when pos is zero) may be a pointer type decayed
2543 * from an array type, if this initial type is the type of a function
2544 * argument. This only happens if the original array type has
2545 * a constant size in the outer dimension as otherwise we get
2546 * a VariableArrayType. Try and obtain this original type (if available) and
2547 * take the outer array size into account if it was marked static.
2549 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2550 QualType qt, int pos)
2552 const ArrayType *atype;
2553 pet_expr *size;
2554 bool decayed = false;
2556 if (!expr)
2557 return NULL;
2559 if (pos == 0)
2560 qt = undecay(qt, &decayed);
2562 if (qt->isPointerType()) {
2563 qt = qt->getPointeeType();
2564 return set_upper_bounds(expr, qt, pos + 1);
2566 if (!qt->isArrayType())
2567 return expr;
2569 qt = qt->getCanonicalTypeInternal();
2570 atype = cast<ArrayType>(qt.getTypePtr());
2572 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2573 qt = atype->getElementType();
2574 return set_upper_bounds(expr, qt, pos + 1);
2577 if (qt->isConstantArrayType()) {
2578 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2579 size = extract_expr(ca->getSize());
2580 expr = pet_expr_set_arg(expr, pos, size);
2581 } else if (qt->isVariableArrayType()) {
2582 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2583 size = extract_expr(vla->getSizeExpr());
2584 expr = pet_expr_set_arg(expr, pos, size);
2587 qt = atype->getElementType();
2589 return set_upper_bounds(expr, qt, pos + 1);
2592 /* Construct a pet_expr that holds the sizes of an array of the given type.
2593 * The returned expression is a call expression with as arguments
2594 * the sizes in each dimension. If we are unable to derive the size
2595 * in a given dimension, then the corresponding argument is set to infinity.
2596 * In fact, we initialize all arguments to infinity and then update
2597 * them if we are able to figure out the size.
2599 * The result is stored in the type_size cache so that we can reuse
2600 * it if this method gets called on the same type again later on.
2602 __isl_give pet_expr *PetScan::get_array_size(QualType qt)
2604 int depth;
2605 pet_expr *expr, *inf;
2606 const Type *type = qt.getTypePtr();
2608 if (type_size.find(type) != type_size.end())
2609 return pet_expr_copy(type_size[type]);
2611 depth = pet_clang_array_depth(qt);
2612 inf = pet_expr_new_int(isl_val_infty(ctx));
2613 expr = pet_expr_new_call(ctx, "bounds", depth);
2614 for (int i = 0; i < depth; ++i)
2615 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2616 pet_expr_free(inf);
2618 expr = set_upper_bounds(expr, qt, 0);
2619 type_size[type] = pet_expr_copy(expr);
2621 return expr;
2624 /* Does "expr" represent the "integer" infinity?
2626 static int is_infty(__isl_keep pet_expr *expr)
2628 isl_val *v;
2629 int res;
2631 if (pet_expr_get_type(expr) != pet_expr_int)
2632 return 0;
2633 v = pet_expr_int_get_val(expr);
2634 res = isl_val_is_infty(v);
2635 isl_val_free(v);
2637 return res;
2640 /* Figure out the dimensions of an array "array" based on its type
2641 * "qt" and update "array" accordingly.
2643 * We first construct a pet_expr that holds the sizes of the array
2644 * in each dimension. The resulting expression may containing
2645 * infinity values for dimension where we are unable to derive
2646 * a size expression.
2648 * The arguments of the size expression that have a value different from
2649 * infinity are then converted to an affine expression
2650 * within the context "pc" and incorporated into the size of "array".
2651 * If we are unable to convert a size expression to an affine expression or
2652 * if the size is not a (symbolic) constant,
2653 * then we leave the corresponding size of "array" untouched.
2655 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2656 QualType qt, __isl_keep pet_context *pc)
2658 int n;
2659 pet_expr *expr;
2661 if (!array)
2662 return NULL;
2664 expr = get_array_size(qt);
2666 n = pet_expr_get_n_arg(expr);
2667 for (int i = 0; i < n; ++i) {
2668 pet_expr *arg;
2669 isl_pw_aff *size;
2671 arg = pet_expr_get_arg(expr, i);
2672 if (!is_infty(arg)) {
2673 int dim;
2675 size = pet_expr_extract_affine(arg, pc);
2676 dim = isl_pw_aff_dim(size, isl_dim_in);
2677 if (!size)
2678 array = pet_array_free(array);
2679 else if (isl_pw_aff_involves_nan(size) ||
2680 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2681 isl_pw_aff_free(size);
2682 else {
2683 size = isl_pw_aff_drop_dims(size,
2684 isl_dim_in, 0, dim);
2685 array = update_size(array, i, size);
2688 pet_expr_free(arg);
2690 pet_expr_free(expr);
2692 return array;
2695 /* Does "decl" have a definition that we can keep track of in a pet_type?
2697 static bool has_printable_definition(RecordDecl *decl)
2699 if (!decl->getDeclName())
2700 return false;
2701 return decl->getLexicalDeclContext() == decl->getDeclContext();
2704 /* Construct and return a pet_array corresponding to the variable
2705 * represented by "id".
2706 * In particular, initialize array->extent to
2708 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2710 * and then call set_upper_bounds to set the upper bounds on the indices
2711 * based on the type of the variable. The upper bounds are converted
2712 * to affine expressions within the context "pc".
2714 * If the base type is that of a record with a top-level definition or
2715 * of a typedef and if "types" is not null, then the RecordDecl or
2716 * TypedefType corresponding to the type
2717 * is added to "types".
2719 * If the base type is that of a record with no top-level definition,
2720 * then we replace it by "<subfield>".
2722 struct pet_array *PetScan::extract_array(__isl_keep isl_id *id,
2723 PetTypes *types, __isl_keep pet_context *pc)
2725 struct pet_array *array;
2726 QualType qt = pet_id_get_array_type(id);
2727 int depth = pet_clang_array_depth(qt);
2728 QualType base = pet_clang_base_type(qt);
2729 string name;
2730 isl_space *space;
2732 array = isl_calloc_type(ctx, struct pet_array);
2733 if (!array)
2734 return NULL;
2736 space = isl_space_set_alloc(ctx, 0, depth);
2737 space = isl_space_set_tuple_id(space, isl_dim_set, isl_id_copy(id));
2739 array->extent = isl_set_nat_universe(space);
2741 space = isl_space_params_alloc(ctx, 0);
2742 array->context = isl_set_universe(space);
2744 array = set_upper_bounds(array, qt, pc);
2745 if (!array)
2746 return NULL;
2748 name = base.getAsString();
2750 if (types) {
2751 if (isa<TypedefType>(base)) {
2752 types->insert(cast<TypedefType>(base)->getDecl());
2753 } else if (base->isRecordType()) {
2754 RecordDecl *decl = pet_clang_record_decl(base);
2755 TypedefNameDecl *typedecl;
2756 typedecl = decl->getTypedefNameForAnonDecl();
2757 if (typedecl)
2758 types->insert(typedecl);
2759 else if (has_printable_definition(decl))
2760 types->insert(decl);
2761 else
2762 name = "<subfield>";
2766 array->element_type = strdup(name.c_str());
2767 array->element_is_record = base->isRecordType();
2768 array->element_size = size_in_bytes(ast_context, base);
2770 return array;
2773 /* Construct and return a pet_array corresponding to the variable "decl".
2775 struct pet_array *PetScan::extract_array(ValueDecl *decl,
2776 PetTypes *types, __isl_keep pet_context *pc)
2778 isl_id *id;
2779 pet_array *array;
2781 id = pet_id_from_decl(ctx, decl);
2782 array = extract_array(id, types, pc);
2783 isl_id_free(id);
2785 return array;
2788 /* Construct and return a pet_array corresponding to the sequence
2789 * of declarations represented by "decls".
2790 * The upper bounds of the array are converted to affine expressions
2791 * within the context "pc".
2792 * If the sequence contains a single declaration, then it corresponds
2793 * to a simple array access. Otherwise, it corresponds to a member access,
2794 * with the declaration for the substructure following that of the containing
2795 * structure in the sequence of declarations.
2796 * We start with the outermost substructure and then combine it with
2797 * information from the inner structures.
2799 * Additionally, keep track of all required types in "types".
2801 struct pet_array *PetScan::extract_array(__isl_keep isl_id_list *decls,
2802 PetTypes *types, __isl_keep pet_context *pc)
2804 int i, n;
2805 isl_id *id;
2806 struct pet_array *array;
2808 id = isl_id_list_get_id(decls, 0);
2809 array = extract_array(id, types, pc);
2810 isl_id_free(id);
2812 n = isl_id_list_n_id(decls);
2813 for (i = 1; i < n; ++i) {
2814 struct pet_array *parent;
2815 const char *base_name, *field_name;
2816 char *product_name;
2818 parent = array;
2819 id = isl_id_list_get_id(decls, i);
2820 array = extract_array(id, types, pc);
2821 isl_id_free(id);
2822 if (!array)
2823 return pet_array_free(parent);
2825 base_name = isl_set_get_tuple_name(parent->extent);
2826 field_name = isl_set_get_tuple_name(array->extent);
2827 product_name = pet_array_member_access_name(ctx,
2828 base_name, field_name);
2830 array->extent = isl_set_product(isl_set_copy(parent->extent),
2831 array->extent);
2832 if (product_name)
2833 array->extent = isl_set_set_tuple_name(array->extent,
2834 product_name);
2835 array->context = isl_set_intersect(array->context,
2836 isl_set_copy(parent->context));
2838 pet_array_free(parent);
2839 free(product_name);
2841 if (!array->extent || !array->context || !product_name)
2842 return pet_array_free(array);
2845 return array;
2848 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2849 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2850 std::set<TypeDecl *> &types_done);
2851 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2852 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2853 std::set<TypeDecl *> &types_done);
2855 /* For each of the fields of "decl" that is itself a record type
2856 * or a typedef, add a corresponding pet_type to "scop".
2858 static struct pet_scop *add_field_types(isl_ctx *ctx, struct pet_scop *scop,
2859 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2860 std::set<TypeDecl *> &types_done)
2862 RecordDecl::field_iterator it;
2864 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
2865 QualType type = it->getType();
2867 if (isa<TypedefType>(type)) {
2868 TypedefNameDecl *typedefdecl;
2870 typedefdecl = cast<TypedefType>(type)->getDecl();
2871 scop = add_type(ctx, scop, typedefdecl,
2872 PP, types, types_done);
2873 } else if (type->isRecordType()) {
2874 RecordDecl *record;
2876 record = pet_clang_record_decl(type);
2877 scop = add_type(ctx, scop, record,
2878 PP, types, types_done);
2882 return scop;
2885 /* Add a pet_type corresponding to "decl" to "scop", provided
2886 * it is a member of types.records and it has not been added before
2887 * (i.e., it is not a member of "types_done").
2889 * Since we want the user to be able to print the types
2890 * in the order in which they appear in the scop, we need to
2891 * make sure that types of fields in a structure appear before
2892 * that structure. We therefore call ourselves recursively
2893 * through add_field_types on the types of all record subfields.
2895 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2896 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2897 std::set<TypeDecl *> &types_done)
2899 string s;
2900 llvm::raw_string_ostream S(s);
2902 if (types.records.find(decl) == types.records.end())
2903 return scop;
2904 if (types_done.find(decl) != types_done.end())
2905 return scop;
2907 add_field_types(ctx, scop, decl, PP, types, types_done);
2909 if (strlen(decl->getName().str().c_str()) == 0)
2910 return scop;
2912 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2913 S.str();
2915 scop->types[scop->n_type] = pet_type_alloc(ctx,
2916 decl->getName().str().c_str(), s.c_str());
2917 if (!scop->types[scop->n_type])
2918 return pet_scop_free(scop);
2920 types_done.insert(decl);
2922 scop->n_type++;
2924 return scop;
2927 /* Add a pet_type corresponding to "decl" to "scop", provided
2928 * it is a member of types.typedefs and it has not been added before
2929 * (i.e., it is not a member of "types_done").
2931 * If the underlying type is a structure, then we print the typedef
2932 * ourselves since clang does not print the definition of the structure
2933 * in the typedef. We also make sure in this case that the types of
2934 * the fields in the structure are added first.
2936 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2937 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2938 std::set<TypeDecl *> &types_done)
2940 string s;
2941 llvm::raw_string_ostream S(s);
2942 QualType qt = decl->getUnderlyingType();
2944 if (types.typedefs.find(decl) == types.typedefs.end())
2945 return scop;
2946 if (types_done.find(decl) != types_done.end())
2947 return scop;
2949 if (qt->isRecordType()) {
2950 RecordDecl *rec = pet_clang_record_decl(qt);
2952 add_field_types(ctx, scop, rec, PP, types, types_done);
2953 S << "typedef ";
2954 rec->print(S, PrintingPolicy(PP.getLangOpts()));
2955 S << " ";
2956 S << decl->getName();
2957 } else {
2958 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2960 S.str();
2962 scop->types[scop->n_type] = pet_type_alloc(ctx,
2963 decl->getName().str().c_str(), s.c_str());
2964 if (!scop->types[scop->n_type])
2965 return pet_scop_free(scop);
2967 types_done.insert(decl);
2969 scop->n_type++;
2971 return scop;
2974 /* Construct a list of pet_arrays, one for each array (or scalar)
2975 * accessed inside "scop", add this list to "scop" and return the result.
2976 * The upper bounds of the arrays are converted to affine expressions
2977 * within the context "pc".
2979 * The context of "scop" is updated with the intersection of
2980 * the contexts of all arrays, i.e., constraints on the parameters
2981 * that ensure that the arrays have a valid (non-negative) size.
2983 * If any of the extracted arrays refers to a member access or
2984 * has a typedef'd type as base type,
2985 * then also add the required types to "scop".
2987 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
2988 __isl_keep pet_context *pc)
2990 int i, n;
2991 array_desc_set arrays;
2992 array_desc_set::iterator it;
2993 PetTypes types;
2994 std::set<TypeDecl *> types_done;
2995 std::set<clang::RecordDecl *, less_name>::iterator records_it;
2996 std::set<clang::TypedefNameDecl *, less_name>::iterator typedefs_it;
2997 int n_array;
2998 struct pet_array **scop_arrays;
3000 if (!scop)
3001 return NULL;
3003 pet_scop_collect_arrays(scop, arrays);
3004 if (arrays.size() == 0)
3005 return scop;
3007 n_array = scop->n_array;
3009 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3010 n_array + arrays.size());
3011 if (!scop_arrays)
3012 goto error;
3013 scop->arrays = scop_arrays;
3015 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3016 struct pet_array *array;
3017 array = extract_array(*it, &types, pc);
3018 scop->arrays[n_array + i] = array;
3019 if (!scop->arrays[n_array + i])
3020 goto error;
3021 scop->n_array++;
3022 scop->context = isl_set_intersect(scop->context,
3023 isl_set_copy(array->context));
3024 if (!scop->context)
3025 goto error;
3028 n = types.records.size() + types.typedefs.size();
3029 if (n == 0)
3030 return scop;
3032 scop->types = isl_alloc_array(ctx, struct pet_type *, n);
3033 if (!scop->types)
3034 goto error;
3036 for (records_it = types.records.begin();
3037 records_it != types.records.end(); ++records_it)
3038 scop = add_type(ctx, scop, *records_it, PP, types, types_done);
3040 for (typedefs_it = types.typedefs.begin();
3041 typedefs_it != types.typedefs.end(); ++typedefs_it)
3042 scop = add_type(ctx, scop, *typedefs_it, PP, types, types_done);
3044 return scop;
3045 error:
3046 pet_scop_free(scop);
3047 return NULL;
3050 /* Bound all parameters in scop->context to the possible values
3051 * of the corresponding C variable.
3053 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
3055 int n;
3057 if (!scop)
3058 return NULL;
3060 n = isl_set_dim(scop->context, isl_dim_param);
3061 for (int i = 0; i < n; ++i) {
3062 isl_id *id;
3063 ValueDecl *decl;
3065 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
3066 if (pet_nested_in_id(id)) {
3067 isl_id_free(id);
3068 isl_die(isl_set_get_ctx(scop->context),
3069 isl_error_internal,
3070 "unresolved nested parameter", goto error);
3072 decl = pet_id_get_decl(id);
3073 isl_id_free(id);
3075 scop->context = set_parameter_bounds(scop->context, i, decl);
3077 if (!scop->context)
3078 goto error;
3081 return scop;
3082 error:
3083 pet_scop_free(scop);
3084 return NULL;
3087 /* Construct a pet_scop from the given function.
3089 * If the scop was delimited by scop and endscop pragmas, then we override
3090 * the file offsets by those derived from the pragmas.
3092 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3094 pet_scop *scop;
3095 Stmt *stmt;
3097 stmt = fd->getBody();
3099 if (options->autodetect) {
3100 set_current_stmt(stmt);
3101 scop = extract_scop(extract(stmt, true));
3102 } else {
3103 current_line = loc.start_line;
3104 scop = scan(stmt);
3105 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
3107 scop = add_parameter_bounds(scop);
3108 scop = pet_scop_gist(scop, value_bounds);
3110 return scop;
3113 /* Update this->last_line and this->current_line based on the fact
3114 * that we are about to consider "stmt".
3116 void PetScan::set_current_stmt(Stmt *stmt)
3118 SourceLocation loc = stmt->getLocStart();
3119 SourceManager &SM = PP.getSourceManager();
3121 last_line = current_line;
3122 current_line = SM.getExpansionLineNumber(loc);
3125 /* Is the current statement marked by an independent pragma?
3126 * That is, is there an independent pragma on a line between
3127 * the line of the current statement and the line of the previous statement.
3128 * The search is not implemented very efficiently. We currently
3129 * assume that there are only a few independent pragmas, if any.
3131 bool PetScan::is_current_stmt_marked_independent()
3133 for (unsigned i = 0; i < independent.size(); ++i) {
3134 unsigned line = independent[i].line;
3136 if (last_line < line && line < current_line)
3137 return true;
3140 return false;