pet_stmt_print_body: do not print anything for kill statements
[pet.git] / scan.cc
blobccd9e497a8f0493da5b6a11711826ce7bf1b1c59
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2014 Ecole Normale Superieure. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
32 * Leiden University.
33 */
35 #include <string.h>
36 #include <set>
37 #include <map>
38 #include <iostream>
39 #include <llvm/Support/raw_ostream.h>
40 #include <clang/AST/ASTContext.h>
41 #include <clang/AST/ASTDiagnostic.h>
42 #include <clang/AST/Attr.h>
43 #include <clang/AST/Expr.h>
44 #include <clang/AST/RecursiveASTVisitor.h>
46 #include <isl/id.h>
47 #include <isl/space.h>
48 #include <isl/aff.h>
49 #include <isl/set.h>
51 #include "aff.h"
52 #include "array.h"
53 #include "clang.h"
54 #include "context.h"
55 #include "expr.h"
56 #include "nest.h"
57 #include "options.h"
58 #include "scan.h"
59 #include "scop.h"
60 #include "scop_plus.h"
61 #include "tree.h"
62 #include "tree2scop.h"
64 #include "config.h"
66 using namespace std;
67 using namespace clang;
69 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
71 switch (kind) {
72 case UO_Minus:
73 return pet_op_minus;
74 case UO_Not:
75 return pet_op_not;
76 case UO_LNot:
77 return pet_op_lnot;
78 case UO_PostInc:
79 return pet_op_post_inc;
80 case UO_PostDec:
81 return pet_op_post_dec;
82 case UO_PreInc:
83 return pet_op_pre_inc;
84 case UO_PreDec:
85 return pet_op_pre_dec;
86 default:
87 return pet_op_last;
91 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
93 switch (kind) {
94 case BO_AddAssign:
95 return pet_op_add_assign;
96 case BO_SubAssign:
97 return pet_op_sub_assign;
98 case BO_MulAssign:
99 return pet_op_mul_assign;
100 case BO_DivAssign:
101 return pet_op_div_assign;
102 case BO_Assign:
103 return pet_op_assign;
104 case BO_Add:
105 return pet_op_add;
106 case BO_Sub:
107 return pet_op_sub;
108 case BO_Mul:
109 return pet_op_mul;
110 case BO_Div:
111 return pet_op_div;
112 case BO_Rem:
113 return pet_op_mod;
114 case BO_Shl:
115 return pet_op_shl;
116 case BO_Shr:
117 return pet_op_shr;
118 case BO_EQ:
119 return pet_op_eq;
120 case BO_NE:
121 return pet_op_ne;
122 case BO_LE:
123 return pet_op_le;
124 case BO_GE:
125 return pet_op_ge;
126 case BO_LT:
127 return pet_op_lt;
128 case BO_GT:
129 return pet_op_gt;
130 case BO_And:
131 return pet_op_and;
132 case BO_Xor:
133 return pet_op_xor;
134 case BO_Or:
135 return pet_op_or;
136 case BO_LAnd:
137 return pet_op_land;
138 case BO_LOr:
139 return pet_op_lor;
140 default:
141 return pet_op_last;
145 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
146 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
148 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
149 SourceLocation(), var, false, var->getInnerLocStart(),
150 var->getType(), VK_LValue);
152 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
153 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
155 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
156 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
157 VK_LValue);
159 #else
160 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
162 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
163 var, var->getInnerLocStart(), var->getType(), VK_LValue);
165 #endif
167 /* Check if the element type corresponding to the given array type
168 * has a const qualifier.
170 static bool const_base(QualType qt)
172 const Type *type = qt.getTypePtr();
174 if (type->isPointerType())
175 return const_base(type->getPointeeType());
176 if (type->isArrayType()) {
177 const ArrayType *atype;
178 type = type->getCanonicalTypeInternal().getTypePtr();
179 atype = cast<ArrayType>(type);
180 return const_base(atype->getElementType());
183 return qt.isConstQualified();
186 /* Create an isl_id that refers to the named declarator "decl".
188 static __isl_give isl_id *create_decl_id(isl_ctx *ctx, NamedDecl *decl)
190 return isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
193 PetScan::~PetScan()
195 std::map<const Type *, pet_expr *>::iterator it;
196 std::map<FunctionDecl *, pet_function_summary *>::iterator it_s;
198 for (it = type_size.begin(); it != type_size.end(); ++it)
199 pet_expr_free(it->second);
200 for (it_s = summary_cache.begin(); it_s != summary_cache.end(); ++it_s)
201 pet_function_summary_free(it_s->second);
203 isl_union_map_free(value_bounds);
206 /* Report a diagnostic, unless autodetect is set.
208 void PetScan::report(Stmt *stmt, unsigned id)
210 if (options->autodetect)
211 return;
213 SourceLocation loc = stmt->getLocStart();
214 DiagnosticsEngine &diag = PP.getDiagnostics();
215 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
218 /* Called if we found something we (currently) cannot handle.
219 * We'll provide more informative warnings later.
221 * We only actually complain if autodetect is false.
223 void PetScan::unsupported(Stmt *stmt)
225 DiagnosticsEngine &diag = PP.getDiagnostics();
226 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
227 "unsupported");
228 report(stmt, id);
231 /* Report a missing prototype, unless autodetect is set.
233 void PetScan::report_prototype_required(Stmt *stmt)
235 DiagnosticsEngine &diag = PP.getDiagnostics();
236 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
237 "prototype required");
238 report(stmt, id);
241 /* Report a missing increment, unless autodetect is set.
243 void PetScan::report_missing_increment(Stmt *stmt)
245 DiagnosticsEngine &diag = PP.getDiagnostics();
246 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
247 "missing increment");
248 report(stmt, id);
251 /* Report a missing summary function, unless autodetect is set.
253 void PetScan::report_missing_summary_function(Stmt *stmt)
255 DiagnosticsEngine &diag = PP.getDiagnostics();
256 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
257 "missing summary function");
258 report(stmt, id);
261 /* Report a missing summary function body, unless autodetect is set.
263 void PetScan::report_missing_summary_function_body(Stmt *stmt)
265 DiagnosticsEngine &diag = PP.getDiagnostics();
266 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
267 "missing summary function body");
268 report(stmt, id);
271 /* Extract an integer from "val", which is assumed to be non-negative.
273 static __isl_give isl_val *extract_unsigned(isl_ctx *ctx,
274 const llvm::APInt &val)
276 unsigned n;
277 const uint64_t *data;
279 data = val.getRawData();
280 n = val.getNumWords();
281 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
284 /* Extract an integer from "val". If "is_signed" is set, then "val"
285 * is signed. Otherwise it it unsigned.
287 static __isl_give isl_val *extract_int(isl_ctx *ctx, bool is_signed,
288 llvm::APInt val)
290 int is_negative = is_signed && val.isNegative();
291 isl_val *v;
293 if (is_negative)
294 val = -val;
296 v = extract_unsigned(ctx, val);
298 if (is_negative)
299 v = isl_val_neg(v);
300 return v;
303 /* Extract an integer from "expr".
305 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
307 const Type *type = expr->getType().getTypePtr();
308 bool is_signed = type->hasSignedIntegerRepresentation();
310 return ::extract_int(ctx, is_signed, expr->getValue());
313 /* Extract an integer from "expr".
314 * Return NULL if "expr" does not (obviously) represent an integer.
316 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
318 return extract_int(expr->getSubExpr());
321 /* Extract an integer from "expr".
322 * Return NULL if "expr" does not (obviously) represent an integer.
324 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
326 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
327 return extract_int(ctx, cast<IntegerLiteral>(expr));
328 if (expr->getStmtClass() == Stmt::ParenExprClass)
329 return extract_int(cast<ParenExpr>(expr));
331 unsupported(expr);
332 return NULL;
335 /* Extract a pet_expr from the APInt "val", which is assumed
336 * to be non-negative.
338 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
340 return pet_expr_new_int(extract_unsigned(ctx, val));
343 /* Return the number of bits needed to represent the type "qt",
344 * if it is an integer type. Otherwise return 0.
345 * If qt is signed then return the opposite of the number of bits.
347 static int get_type_size(QualType qt, ASTContext &ast_context)
349 int size;
351 if (!qt->isIntegerType())
352 return 0;
354 size = ast_context.getIntWidth(qt);
355 if (!qt->isUnsignedIntegerType())
356 size = -size;
358 return size;
361 /* Return the number of bits needed to represent the type of "decl",
362 * if it is an integer type. Otherwise return 0.
363 * If qt is signed then return the opposite of the number of bits.
365 static int get_type_size(ValueDecl *decl)
367 return get_type_size(decl->getType(), decl->getASTContext());
370 /* Bound parameter "pos" of "set" to the possible values of "decl".
372 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
373 unsigned pos, ValueDecl *decl)
375 int type_size;
376 isl_ctx *ctx;
377 isl_val *bound;
379 ctx = isl_set_get_ctx(set);
380 type_size = get_type_size(decl);
381 if (type_size == 0)
382 isl_die(ctx, isl_error_invalid, "not an integer type",
383 return isl_set_free(set));
384 if (type_size > 0) {
385 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
386 bound = isl_val_int_from_ui(ctx, type_size);
387 bound = isl_val_2exp(bound);
388 bound = isl_val_sub_ui(bound, 1);
389 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
390 } else {
391 bound = isl_val_int_from_ui(ctx, -type_size - 1);
392 bound = isl_val_2exp(bound);
393 bound = isl_val_sub_ui(bound, 1);
394 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
395 isl_val_copy(bound));
396 bound = isl_val_neg(bound);
397 bound = isl_val_sub_ui(bound, 1);
398 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
401 return set;
404 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
406 return extract_index_expr(expr->getSubExpr());
409 /* Return the depth of an array of the given type.
411 static int array_depth(const Type *type)
413 if (type->isPointerType())
414 return 1 + array_depth(type->getPointeeType().getTypePtr());
415 if (type->isArrayType()) {
416 const ArrayType *atype;
417 type = type->getCanonicalTypeInternal().getTypePtr();
418 atype = cast<ArrayType>(type);
419 return 1 + array_depth(atype->getElementType().getTypePtr());
421 return 0;
424 /* Return the depth of the array accessed by the index expression "index".
425 * If "index" is an affine expression, i.e., if it does not access
426 * any array, then return 1.
427 * If "index" represent a member access, i.e., if its range is a wrapped
428 * relation, then return the sum of the depth of the array of structures
429 * and that of the member inside the structure.
431 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
433 isl_id *id;
434 ValueDecl *decl;
436 if (!index)
437 return -1;
439 if (isl_multi_pw_aff_range_is_wrapping(index)) {
440 int domain_depth, range_depth;
441 isl_multi_pw_aff *domain, *range;
443 domain = isl_multi_pw_aff_copy(index);
444 domain = isl_multi_pw_aff_range_factor_domain(domain);
445 domain_depth = extract_depth(domain);
446 isl_multi_pw_aff_free(domain);
447 range = isl_multi_pw_aff_copy(index);
448 range = isl_multi_pw_aff_range_factor_range(range);
449 range_depth = extract_depth(range);
450 isl_multi_pw_aff_free(range);
452 return domain_depth + range_depth;
455 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
456 return 1;
458 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
459 if (!id)
460 return -1;
461 decl = (ValueDecl *) isl_id_get_user(id);
462 isl_id_free(id);
464 return array_depth(decl->getType().getTypePtr());
467 /* Return the depth of the array accessed by the access expression "expr".
469 static int extract_depth(__isl_keep pet_expr *expr)
471 isl_multi_pw_aff *index;
472 int depth;
474 index = pet_expr_access_get_index(expr);
475 depth = extract_depth(index);
476 isl_multi_pw_aff_free(index);
478 return depth;
481 /* Construct a pet_expr representing an index expression for an access
482 * to the variable referenced by "expr".
484 * If "expr" references an enum constant, then return an integer expression
485 * instead, representing the value of the enum constant.
487 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
489 return extract_index_expr(expr->getDecl());
492 /* Construct a pet_expr representing an index expression for an access
493 * to the variable "decl".
495 * If "decl" is an enum constant, then we return an integer expression
496 * instead, representing the value of the enum constant.
498 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
500 isl_id *id;
501 isl_space *space;
503 if (isa<EnumConstantDecl>(decl))
504 return extract_expr(cast<EnumConstantDecl>(decl));
506 id = create_decl_id(ctx, decl);
507 space = isl_space_alloc(ctx, 0, 0, 0);
508 space = isl_space_set_tuple_id(space, isl_dim_out, id);
510 return pet_expr_from_index(isl_multi_pw_aff_zero(space));
513 /* Construct a pet_expr representing the index expression "expr"
514 * Return NULL on error.
516 * If "expr" is a reference to an enum constant, then return
517 * an integer expression instead, representing the value of the enum constant.
519 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
521 switch (expr->getStmtClass()) {
522 case Stmt::ImplicitCastExprClass:
523 return extract_index_expr(cast<ImplicitCastExpr>(expr));
524 case Stmt::DeclRefExprClass:
525 return extract_index_expr(cast<DeclRefExpr>(expr));
526 case Stmt::ArraySubscriptExprClass:
527 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
528 case Stmt::IntegerLiteralClass:
529 return extract_expr(cast<IntegerLiteral>(expr));
530 case Stmt::MemberExprClass:
531 return extract_index_expr(cast<MemberExpr>(expr));
532 default:
533 unsupported(expr);
535 return NULL;
538 /* Extract an index expression from the given array subscript expression.
540 * We first extract an index expression from the base.
541 * This will result in an index expression with a range that corresponds
542 * to the earlier indices.
543 * We then extract the current index and let
544 * pet_expr_access_subscript combine the two.
546 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
548 Expr *base = expr->getBase();
549 Expr *idx = expr->getIdx();
550 pet_expr *index;
551 pet_expr *base_expr;
553 base_expr = extract_index_expr(base);
554 index = extract_expr(idx);
556 base_expr = pet_expr_access_subscript(base_expr, index);
558 return base_expr;
561 /* Extract an index expression from a member expression.
563 * If the base access (to the structure containing the member)
564 * is of the form
566 * A[..]
568 * and the member is called "f", then the member access is of
569 * the form
571 * A_f[A[..] -> f[]]
573 * If the member access is to an anonymous struct, then simply return
575 * A[..]
577 * If the member access in the source code is of the form
579 * A->f
581 * then it is treated as
583 * A[0].f
585 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
587 Expr *base = expr->getBase();
588 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
589 pet_expr *base_index;
590 isl_id *id;
592 base_index = extract_index_expr(base);
594 if (expr->isArrow()) {
595 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
596 base_index = pet_expr_access_subscript(base_index, index);
599 if (field->isAnonymousStructOrUnion())
600 return base_index;
602 id = create_decl_id(ctx, field);
604 return pet_expr_access_member(base_index, id);
607 /* Mark the given access pet_expr as a write.
609 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
611 access = pet_expr_access_set_write(access, 1);
612 access = pet_expr_access_set_read(access, 0);
614 return access;
617 /* Construct a pet_expr representing a unary operator expression.
619 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
621 pet_expr *arg;
622 enum pet_op_type op;
624 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
625 if (op == pet_op_last) {
626 unsupported(expr);
627 return NULL;
630 arg = extract_expr(expr->getSubExpr());
632 if (expr->isIncrementDecrementOp() &&
633 pet_expr_get_type(arg) == pet_expr_access) {
634 arg = mark_write(arg);
635 arg = pet_expr_access_set_read(arg, 1);
638 return pet_expr_new_unary(op, arg);
641 /* Construct a pet_expr representing a binary operator expression.
643 * If the top level operator is an assignment and the LHS is an access,
644 * then we mark that access as a write. If the operator is a compound
645 * assignment, the access is marked as both a read and a write.
647 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
649 int type_size;
650 pet_expr *lhs, *rhs;
651 enum pet_op_type op;
653 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
654 if (op == pet_op_last) {
655 unsupported(expr);
656 return NULL;
659 lhs = extract_expr(expr->getLHS());
660 rhs = extract_expr(expr->getRHS());
662 if (expr->isAssignmentOp() &&
663 pet_expr_get_type(lhs) == pet_expr_access) {
664 lhs = mark_write(lhs);
665 if (expr->isCompoundAssignmentOp())
666 lhs = pet_expr_access_set_read(lhs, 1);
669 type_size = get_type_size(expr->getType(), ast_context);
670 return pet_expr_new_binary(type_size, op, lhs, rhs);
673 /* Construct a pet_tree for a (single) variable declaration.
675 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
677 Decl *decl;
678 VarDecl *vd;
679 pet_expr *lhs, *rhs;
680 pet_tree *tree;
682 if (!stmt->isSingleDecl()) {
683 unsupported(stmt);
684 return NULL;
687 decl = stmt->getSingleDecl();
688 vd = cast<VarDecl>(decl);
690 lhs = extract_access_expr(vd);
691 lhs = mark_write(lhs);
692 if (!vd->getInit())
693 tree = pet_tree_new_decl(lhs);
694 else {
695 rhs = extract_expr(vd->getInit());
696 tree = pet_tree_new_decl_init(lhs, rhs);
699 return tree;
702 /* Construct a pet_expr representing a conditional operation.
704 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
706 pet_expr *cond, *lhs, *rhs;
707 isl_pw_aff *pa;
709 cond = extract_expr(expr->getCond());
710 lhs = extract_expr(expr->getTrueExpr());
711 rhs = extract_expr(expr->getFalseExpr());
713 return pet_expr_new_ternary(cond, lhs, rhs);
716 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
718 return extract_expr(expr->getSubExpr());
721 /* Construct a pet_expr representing a floating point value.
723 * If the floating point literal does not appear in a macro,
724 * then we use the original representation in the source code
725 * as the string representation. Otherwise, we use the pretty
726 * printer to produce a string representation.
728 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
730 double d;
731 string s;
732 const LangOptions &LO = PP.getLangOpts();
733 SourceLocation loc = expr->getLocation();
735 if (!loc.isMacroID()) {
736 SourceManager &SM = PP.getSourceManager();
737 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
738 s = string(SM.getCharacterData(loc), len);
739 } else {
740 llvm::raw_string_ostream S(s);
741 expr->printPretty(S, 0, PrintingPolicy(LO));
742 S.str();
744 d = expr->getValueAsApproximateDouble();
745 return pet_expr_new_double(ctx, d, s.c_str());
748 /* Convert the index expression "index" into an access pet_expr of type "qt".
750 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
751 __isl_take pet_expr *index)
753 int depth;
754 int type_size;
756 depth = extract_depth(index);
757 type_size = get_type_size(qt, ast_context);
759 index = pet_expr_set_type_size(index, type_size);
760 index = pet_expr_access_set_depth(index, depth);
762 return index;
765 /* Extract an index expression from "expr" and then convert it into
766 * an access pet_expr.
768 * If "expr" is a reference to an enum constant, then return
769 * an integer expression instead, representing the value of the enum constant.
771 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
773 pet_expr *index;
775 index = extract_index_expr(expr);
777 if (pet_expr_get_type(index) == pet_expr_int)
778 return index;
780 return extract_access_expr(expr->getType(), index);
783 /* Extract an index expression from "decl" and then convert it into
784 * an access pet_expr.
786 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
788 return extract_access_expr(decl->getType(), extract_index_expr(decl));
791 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
793 return extract_expr(expr->getSubExpr());
796 /* Extract an assume statement from the argument "expr"
797 * of a __pencil_assume statement.
799 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
801 return pet_expr_new_unary(pet_op_assume, extract_expr(expr));
804 /* Construct a pet_expr corresponding to the function call argument "expr".
805 * The argument appears in position "pos" of a call to function "fd".
807 * If we are passing along a pointer to an array element
808 * or an entire row or even higher dimensional slice of an array,
809 * then the function being called may write into the array.
811 * We assume here that if the function is declared to take a pointer
812 * to a const type, then the function will perform a read
813 * and that otherwise, it will perform a write.
815 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
816 Expr *expr)
818 pet_expr *res;
819 int is_addr = 0, is_partial = 0;
820 Stmt::StmtClass sc;
822 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
823 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
824 expr = ice->getSubExpr();
826 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
827 UnaryOperator *op = cast<UnaryOperator>(expr);
828 if (op->getOpcode() == UO_AddrOf) {
829 is_addr = 1;
830 expr = op->getSubExpr();
833 res = extract_expr(expr);
834 if (!res)
835 return NULL;
836 sc = expr->getStmtClass();
837 if ((sc == Stmt::ArraySubscriptExprClass ||
838 sc == Stmt::DeclRefExprClass ||
839 sc == Stmt::MemberExprClass) &&
840 array_depth(expr->getType().getTypePtr()) > 0)
841 is_partial = 1;
842 if ((is_addr || is_partial) &&
843 pet_expr_get_type(res) == pet_expr_access) {
844 ParmVarDecl *parm;
845 if (!fd->hasPrototype()) {
846 report_prototype_required(expr);
847 return pet_expr_free(res);
849 parm = fd->getParamDecl(pos);
850 if (!const_base(parm->getType()))
851 res = mark_write(res);
854 if (is_addr)
855 res = pet_expr_new_unary(pet_op_address_of, res);
856 return res;
859 /* Find the first FunctionDecl with the given name.
860 * "call" is the corresponding call expression and is only used
861 * for reporting errors.
863 * Return NULL on error.
865 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
867 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
868 DeclContext::decl_iterator begin = tu->decls_begin();
869 DeclContext::decl_iterator end = tu->decls_end();
870 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
871 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
872 if (!fd)
873 continue;
874 if (fd->getName().str().compare(name) != 0)
875 continue;
876 if (fd->hasBody())
877 return fd;
878 report_missing_summary_function_body(call);
879 return NULL;
881 report_missing_summary_function(call);
882 return NULL;
885 /* Return the FunctionDecl for the summary function associated to the
886 * function called by "call".
888 * In particular, search for an annotate attribute formatted as
889 * "pencil_access(name)", where "name" is the name of the summary function.
891 * If no summary function was specified, then return the FunctionDecl
892 * that is actually being called.
894 * Return NULL on error.
896 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
898 FunctionDecl *decl = call->getDirectCallee();
899 if (!decl)
900 return NULL;
902 specific_attr_iterator<AnnotateAttr> begin, end, i;
903 begin = decl->specific_attr_begin<AnnotateAttr>();
904 end = decl->specific_attr_end<AnnotateAttr>();
905 for (i = begin; i != end; ++i) {
906 string attr = (*i)->getAnnotation().str();
908 const char prefix[] = "pencil_access(";
909 size_t start = attr.find(prefix);
910 if (start == string::npos)
911 continue;
912 start += strlen(prefix);
913 string name = attr.substr(start, attr.find(')') - start);
915 return find_decl_from_name(call, name);
918 return decl;
921 /* Construct a pet_expr representing a function call.
923 * In the special case of a "call" to __pencil_assume,
924 * construct an assume expression instead.
926 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
928 pet_expr *res = NULL;
929 FunctionDecl *fd;
930 string name;
931 unsigned n_arg;
933 fd = expr->getDirectCallee();
934 if (!fd) {
935 unsupported(expr);
936 return NULL;
939 name = fd->getDeclName().getAsString();
940 n_arg = expr->getNumArgs();
942 if (n_arg == 1 && name == "__pencil_assume")
943 return extract_assume(expr->getArg(0));
945 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
946 if (!res)
947 return NULL;
949 for (int i = 0; i < n_arg; ++i) {
950 Expr *arg = expr->getArg(i);
951 res = pet_expr_set_arg(res, i,
952 PetScan::extract_argument(fd, i, arg));
955 fd = get_summary_function(expr);
956 if (!fd)
957 return pet_expr_free(res);
959 res = set_summary(res, fd);
961 return res;
964 /* Construct a pet_expr representing a (C style) cast.
966 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
968 pet_expr *arg;
969 QualType type;
971 arg = extract_expr(expr->getSubExpr());
972 if (!arg)
973 return NULL;
975 type = expr->getTypeAsWritten();
976 return pet_expr_new_cast(type.getAsString().c_str(), arg);
979 /* Construct a pet_expr representing an integer.
981 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
983 return pet_expr_new_int(extract_int(expr));
986 /* Construct a pet_expr representing the integer enum constant "ecd".
988 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
990 isl_val *v;
991 const llvm::APSInt &init = ecd->getInitVal();
992 v = ::extract_int(ctx, init.isSigned(), init);
993 return pet_expr_new_int(v);
996 /* Try and construct a pet_expr representing "expr".
998 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1000 switch (expr->getStmtClass()) {
1001 case Stmt::UnaryOperatorClass:
1002 return extract_expr(cast<UnaryOperator>(expr));
1003 case Stmt::CompoundAssignOperatorClass:
1004 case Stmt::BinaryOperatorClass:
1005 return extract_expr(cast<BinaryOperator>(expr));
1006 case Stmt::ImplicitCastExprClass:
1007 return extract_expr(cast<ImplicitCastExpr>(expr));
1008 case Stmt::ArraySubscriptExprClass:
1009 case Stmt::DeclRefExprClass:
1010 case Stmt::MemberExprClass:
1011 return extract_access_expr(expr);
1012 case Stmt::IntegerLiteralClass:
1013 return extract_expr(cast<IntegerLiteral>(expr));
1014 case Stmt::FloatingLiteralClass:
1015 return extract_expr(cast<FloatingLiteral>(expr));
1016 case Stmt::ParenExprClass:
1017 return extract_expr(cast<ParenExpr>(expr));
1018 case Stmt::ConditionalOperatorClass:
1019 return extract_expr(cast<ConditionalOperator>(expr));
1020 case Stmt::CallExprClass:
1021 return extract_expr(cast<CallExpr>(expr));
1022 case Stmt::CStyleCastExprClass:
1023 return extract_expr(cast<CStyleCastExpr>(expr));
1024 default:
1025 unsupported(expr);
1027 return NULL;
1030 /* Check if the given initialization statement is an assignment.
1031 * If so, return that assignment. Otherwise return NULL.
1033 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1035 BinaryOperator *ass;
1037 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1038 return NULL;
1040 ass = cast<BinaryOperator>(init);
1041 if (ass->getOpcode() != BO_Assign)
1042 return NULL;
1044 return ass;
1047 /* Check if the given initialization statement is a declaration
1048 * of a single variable.
1049 * If so, return that declaration. Otherwise return NULL.
1051 Decl *PetScan::initialization_declaration(Stmt *init)
1053 DeclStmt *decl;
1055 if (init->getStmtClass() != Stmt::DeclStmtClass)
1056 return NULL;
1058 decl = cast<DeclStmt>(init);
1060 if (!decl->isSingleDecl())
1061 return NULL;
1063 return decl->getSingleDecl();
1066 /* Given the assignment operator in the initialization of a for loop,
1067 * extract the induction variable, i.e., the (integer)variable being
1068 * assigned.
1070 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1072 Expr *lhs;
1073 DeclRefExpr *ref;
1074 ValueDecl *decl;
1075 const Type *type;
1077 lhs = init->getLHS();
1078 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1079 unsupported(init);
1080 return NULL;
1083 ref = cast<DeclRefExpr>(lhs);
1084 decl = ref->getDecl();
1085 type = decl->getType().getTypePtr();
1087 if (!type->isIntegerType()) {
1088 unsupported(lhs);
1089 return NULL;
1092 return decl;
1095 /* Given the initialization statement of a for loop and the single
1096 * declaration in this initialization statement,
1097 * extract the induction variable, i.e., the (integer) variable being
1098 * declared.
1100 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1102 VarDecl *vd;
1104 vd = cast<VarDecl>(decl);
1106 const QualType type = vd->getType();
1107 if (!type->isIntegerType()) {
1108 unsupported(init);
1109 return NULL;
1112 if (!vd->getInit()) {
1113 unsupported(init);
1114 return NULL;
1117 return vd;
1120 /* Check that op is of the form iv++ or iv--.
1121 * Return a pet_expr representing "1" or "-1" accordingly.
1123 __isl_give pet_expr *PetScan::extract_unary_increment(
1124 clang::UnaryOperator *op, clang::ValueDecl *iv)
1126 Expr *sub;
1127 DeclRefExpr *ref;
1128 isl_val *v;
1130 if (!op->isIncrementDecrementOp()) {
1131 unsupported(op);
1132 return NULL;
1135 sub = op->getSubExpr();
1136 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1137 unsupported(op);
1138 return NULL;
1141 ref = cast<DeclRefExpr>(sub);
1142 if (ref->getDecl() != iv) {
1143 unsupported(op);
1144 return NULL;
1147 if (op->isIncrementOp())
1148 v = isl_val_one(ctx);
1149 else
1150 v = isl_val_negone(ctx);
1152 return pet_expr_new_int(v);
1155 /* Check if op is of the form
1157 * iv = expr
1159 * and return the increment "expr - iv" as a pet_expr.
1161 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1162 clang::ValueDecl *iv)
1164 int type_size;
1165 Expr *lhs;
1166 DeclRefExpr *ref;
1167 pet_expr *expr, *expr_iv;
1169 if (op->getOpcode() != BO_Assign) {
1170 unsupported(op);
1171 return NULL;
1174 lhs = op->getLHS();
1175 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1176 unsupported(op);
1177 return NULL;
1180 ref = cast<DeclRefExpr>(lhs);
1181 if (ref->getDecl() != iv) {
1182 unsupported(op);
1183 return NULL;
1186 expr = extract_expr(op->getRHS());
1187 expr_iv = extract_expr(lhs);
1189 type_size = get_type_size(iv->getType(), ast_context);
1190 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1193 /* Check that op is of the form iv += cst or iv -= cst
1194 * and return a pet_expr corresponding to cst or -cst accordingly.
1196 __isl_give pet_expr *PetScan::extract_compound_increment(
1197 CompoundAssignOperator *op, clang::ValueDecl *iv)
1199 Expr *lhs;
1200 DeclRefExpr *ref;
1201 bool neg = false;
1202 pet_expr *expr;
1203 BinaryOperatorKind opcode;
1205 opcode = op->getOpcode();
1206 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1207 unsupported(op);
1208 return NULL;
1210 if (opcode == BO_SubAssign)
1211 neg = true;
1213 lhs = op->getLHS();
1214 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1215 unsupported(op);
1216 return NULL;
1219 ref = cast<DeclRefExpr>(lhs);
1220 if (ref->getDecl() != iv) {
1221 unsupported(op);
1222 return NULL;
1225 expr = extract_expr(op->getRHS());
1226 if (neg)
1227 expr = pet_expr_new_unary(pet_op_minus, expr);
1229 return expr;
1232 /* Check that the increment of the given for loop increments
1233 * (or decrements) the induction variable "iv" and return
1234 * the increment as a pet_expr if successful.
1236 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1237 ValueDecl *iv)
1239 Stmt *inc = stmt->getInc();
1241 if (!inc) {
1242 report_missing_increment(stmt);
1243 return NULL;
1246 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1247 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1248 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1249 return extract_compound_increment(
1250 cast<CompoundAssignOperator>(inc), iv);
1251 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1252 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1254 unsupported(inc);
1255 return NULL;
1258 /* Construct a pet_tree for a while loop.
1260 * If we were only able to extract part of the body, then simply
1261 * return that part.
1263 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1265 pet_expr *pe_cond;
1266 pet_tree *tree;
1268 tree = extract(stmt->getBody());
1269 if (partial)
1270 return tree;
1271 pe_cond = extract_expr(stmt->getCond());
1272 tree = pet_tree_new_while(pe_cond, tree);
1274 return tree;
1277 /* Construct a pet_tree for a for statement.
1278 * The for loop is required to be of one of the following forms
1280 * for (i = init; condition; ++i)
1281 * for (i = init; condition; --i)
1282 * for (i = init; condition; i += constant)
1283 * for (i = init; condition; i -= constant)
1285 * We extract a pet_tree for the body and then include it in a pet_tree
1286 * of type pet_tree_for.
1288 * As a special case, we also allow a for loop of the form
1290 * for (;;)
1292 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1294 * If we were only able to extract part of the body, then simply
1295 * return that part.
1297 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1299 BinaryOperator *ass;
1300 Decl *decl;
1301 Stmt *init;
1302 Expr *lhs, *rhs;
1303 ValueDecl *iv;
1304 pet_tree *tree;
1305 struct pet_scop *scop;
1306 int independent;
1307 int declared;
1308 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1310 independent = is_current_stmt_marked_independent();
1312 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1313 tree = extract(stmt->getBody());
1314 if (partial)
1315 return tree;
1316 tree = pet_tree_new_infinite_loop(tree);
1317 return tree;
1320 init = stmt->getInit();
1321 if (!init) {
1322 unsupported(stmt);
1323 return NULL;
1325 if ((ass = initialization_assignment(init)) != NULL) {
1326 iv = extract_induction_variable(ass);
1327 if (!iv)
1328 return NULL;
1329 lhs = ass->getLHS();
1330 rhs = ass->getRHS();
1331 } else if ((decl = initialization_declaration(init)) != NULL) {
1332 VarDecl *var = extract_induction_variable(init, decl);
1333 if (!var)
1334 return NULL;
1335 iv = var;
1336 rhs = var->getInit();
1337 lhs = create_DeclRefExpr(var);
1338 } else {
1339 unsupported(stmt->getInit());
1340 return NULL;
1343 declared = !initialization_assignment(stmt->getInit());
1344 tree = extract(stmt->getBody());
1345 if (partial)
1346 return tree;
1347 pe_iv = extract_access_expr(iv);
1348 pe_iv = mark_write(pe_iv);
1349 pe_init = extract_expr(rhs);
1350 if (!stmt->getCond())
1351 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1352 else
1353 pe_cond = extract_expr(stmt->getCond());
1354 pe_inc = extract_increment(stmt, iv);
1355 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1356 pe_inc, tree);
1357 return tree;
1360 /* Try and construct a pet_tree corresponding to a compound statement.
1362 * "skip_declarations" is set if we should skip initial declarations
1363 * in the children of the compound statements. This then implies
1364 * that this sequence of children should not be treated as a block
1365 * since the initial statements may be skipped.
1367 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1368 bool skip_declarations)
1370 return extract(stmt->children(), !skip_declarations, skip_declarations);
1373 /* Return the file offset of the expansion location of "Loc".
1375 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1377 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1380 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1382 /* Return a SourceLocation for the location after the first semicolon
1383 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1384 * call it and also skip trailing spaces and newline.
1386 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1387 const LangOptions &LO)
1389 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1392 #else
1394 /* Return a SourceLocation for the location after the first semicolon
1395 * after "loc". If Lexer::findLocationAfterToken is not available,
1396 * we look in the underlying character data for the first semicolon.
1398 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1399 const LangOptions &LO)
1401 const char *semi;
1402 const char *s = SM.getCharacterData(loc);
1404 semi = strchr(s, ';');
1405 if (!semi)
1406 return SourceLocation();
1407 return loc.getFileLocWithOffset(semi + 1 - s);
1410 #endif
1412 /* If the token at "loc" is the first token on the line, then return
1413 * a location referring to the start of the line and set *indent
1414 * to the indentation of "loc"
1415 * Otherwise, return "loc" and set *indent to "".
1417 * This function is used to extend a scop to the start of the line
1418 * if the first token of the scop is also the first token on the line.
1420 * We look for the first token on the line. If its location is equal to "loc",
1421 * then the latter is the location of the first token on the line.
1423 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1424 SourceManager &SM, const LangOptions &LO, char **indent)
1426 std::pair<FileID, unsigned> file_offset_pair;
1427 llvm::StringRef file;
1428 const char *pos;
1429 Token tok;
1430 SourceLocation token_loc, line_loc;
1431 int col;
1432 const char *s;
1434 loc = SM.getExpansionLoc(loc);
1435 col = SM.getExpansionColumnNumber(loc);
1436 line_loc = loc.getLocWithOffset(1 - col);
1437 file_offset_pair = SM.getDecomposedLoc(line_loc);
1438 file = SM.getBufferData(file_offset_pair.first, NULL);
1439 pos = file.data() + file_offset_pair.second;
1441 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1442 file.begin(), pos, file.end());
1443 lexer.LexFromRawLexer(tok);
1444 token_loc = tok.getLocation();
1446 s = SM.getCharacterData(line_loc);
1447 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1449 if (token_loc == loc)
1450 return line_loc;
1451 else
1452 return loc;
1455 /* Construct a pet_loc corresponding to the region covered by "range".
1456 * If "skip_semi" is set, then we assume "range" is followed by
1457 * a semicolon and also include this semicolon.
1459 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1460 bool skip_semi)
1462 SourceLocation loc = range.getBegin();
1463 SourceManager &SM = PP.getSourceManager();
1464 const LangOptions &LO = PP.getLangOpts();
1465 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1466 unsigned start, end;
1467 char *indent;
1469 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1470 start = getExpansionOffset(SM, loc);
1471 loc = range.getEnd();
1472 if (skip_semi)
1473 loc = location_after_semi(loc, SM, LO);
1474 else
1475 loc = PP.getLocForEndOfToken(loc);
1476 end = getExpansionOffset(SM, loc);
1478 return pet_loc_alloc(ctx, start, end, line, indent);
1481 /* Convert a top-level pet_expr to an expression pet_tree.
1483 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1484 SourceRange range, bool skip_semi)
1486 pet_loc *loc;
1487 pet_tree *tree;
1489 tree = pet_tree_new_expr(expr);
1490 loc = construct_pet_loc(range, skip_semi);
1491 tree = pet_tree_set_loc(tree, loc);
1493 return tree;
1496 /* Construct a pet_tree for an if statement.
1498 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1500 pet_expr *pe_cond;
1501 pet_tree *tree, *tree_else;
1502 struct pet_scop *scop;
1503 int int_size;
1505 pe_cond = extract_expr(stmt->getCond());
1506 tree = extract(stmt->getThen());
1507 if (stmt->getElse()) {
1508 tree_else = extract(stmt->getElse());
1509 if (options->autodetect) {
1510 if (tree && !tree_else) {
1511 partial = true;
1512 pet_expr_free(pe_cond);
1513 return tree;
1515 if (!tree && tree_else) {
1516 partial = true;
1517 pet_expr_free(pe_cond);
1518 return tree_else;
1521 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1522 } else
1523 tree = pet_tree_new_if(pe_cond, tree);
1524 return tree;
1527 /* Try and construct a pet_tree for a label statement.
1528 * We currently only allow labels on expression statements.
1530 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1532 isl_id *label;
1533 pet_tree *tree;
1534 Stmt *sub;
1536 sub = stmt->getSubStmt();
1537 if (!isa<Expr>(sub)) {
1538 unsupported(stmt);
1539 return NULL;
1542 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1544 tree = extract(extract_expr(cast<Expr>(sub)), stmt->getSourceRange(),
1545 true);
1546 tree = pet_tree_set_label(tree, label);
1547 return tree;
1550 /* Update the location of "tree" to include the source range of "stmt".
1552 * Actually, we create a new location based on the source range of "stmt" and
1553 * then extend this new location to include the region of the original location.
1554 * This ensures that the line number of the final location refers to "stmt".
1556 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1558 pet_loc *loc, *tree_loc;
1560 tree_loc = pet_tree_get_loc(tree);
1561 loc = construct_pet_loc(stmt->getSourceRange(), false);
1562 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1563 pet_loc_free(tree_loc);
1565 tree = pet_tree_set_loc(tree, loc);
1566 return tree;
1569 /* Try and construct a pet_tree corresponding to "stmt".
1571 * If "stmt" is a compound statement, then "skip_declarations"
1572 * indicates whether we should skip initial declarations in the
1573 * compound statement.
1575 * If the constructed pet_tree is not a (possibly) partial representation
1576 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1577 * In particular, if skip_declarations is set, then we may have skipped
1578 * declarations inside "stmt" and so the pet_scop may not represent
1579 * the entire "stmt".
1580 * Note that this function may be called with "stmt" referring to the entire
1581 * body of the function, including the outer braces. In such cases,
1582 * skip_declarations will be set and the braces will not be taken into
1583 * account in tree->loc.
1585 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
1587 pet_tree *tree;
1589 set_current_stmt(stmt);
1591 if (isa<Expr>(stmt))
1592 return extract(extract_expr(cast<Expr>(stmt)),
1593 stmt->getSourceRange(), true);
1595 switch (stmt->getStmtClass()) {
1596 case Stmt::WhileStmtClass:
1597 tree = extract(cast<WhileStmt>(stmt));
1598 break;
1599 case Stmt::ForStmtClass:
1600 tree = extract_for(cast<ForStmt>(stmt));
1601 break;
1602 case Stmt::IfStmtClass:
1603 tree = extract(cast<IfStmt>(stmt));
1604 break;
1605 case Stmt::CompoundStmtClass:
1606 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
1607 break;
1608 case Stmt::LabelStmtClass:
1609 tree = extract(cast<LabelStmt>(stmt));
1610 break;
1611 case Stmt::ContinueStmtClass:
1612 tree = pet_tree_new_continue(ctx);
1613 break;
1614 case Stmt::BreakStmtClass:
1615 tree = pet_tree_new_break(ctx);
1616 break;
1617 case Stmt::DeclStmtClass:
1618 tree = extract(cast<DeclStmt>(stmt));
1619 break;
1620 default:
1621 unsupported(stmt);
1622 return NULL;
1625 if (partial || skip_declarations)
1626 return tree;
1628 return update_loc(tree, stmt);
1631 /* Try and construct a pet_tree corresponding to (part of)
1632 * a sequence of statements.
1634 * "block" is set if the sequence represents the children of
1635 * a compound statement.
1636 * "skip_declarations" is set if we should skip initial declarations
1637 * in the sequence of statements.
1639 * If autodetect is set, then we allow the extraction of only a subrange
1640 * of the sequence of statements. However, if there is at least one statement
1641 * for which we could not construct a scop and the final range contains
1642 * either no statements or at least one kill, then we discard the entire
1643 * range.
1645 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
1646 bool skip_declarations)
1648 StmtIterator i;
1649 int j;
1650 bool has_kills = false;
1651 bool partial_range = false;
1652 pet_tree *tree;
1653 set<struct pet_stmt *> kills;
1654 set<struct pet_stmt *>::iterator it;
1656 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
1659 tree = pet_tree_new_block(ctx, block, j);
1661 for (i = stmt_range.first; i != stmt_range.second; ++i) {
1662 Stmt *child = *i;
1663 pet_tree *tree_i;
1665 if (pet_tree_block_n_child(tree) == 0 && skip_declarations &&
1666 child->getStmtClass() == Stmt::DeclStmtClass)
1667 continue;
1669 tree_i = extract(child);
1670 if (pet_tree_block_n_child(tree) != 0 && partial) {
1671 pet_tree_free(tree_i);
1672 break;
1674 if (tree_i && child->getStmtClass() == Stmt::DeclStmtClass &&
1675 block)
1676 has_kills = true;
1677 if (options->autodetect) {
1678 if (tree_i)
1679 tree = pet_tree_block_add_child(tree, tree_i);
1680 else
1681 partial_range = true;
1682 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
1683 partial = true;
1684 } else {
1685 tree = pet_tree_block_add_child(tree, tree_i);
1688 if (partial || !tree)
1689 break;
1692 if (tree && partial_range) {
1693 if (pet_tree_block_n_child(tree) == 0 || has_kills) {
1694 pet_tree_free(tree);
1695 return NULL;
1697 partial = true;
1700 return tree;
1703 /* Is "T" the type of a variable length array with static size?
1705 static bool is_vla_with_static_size(QualType T)
1707 const VariableArrayType *vlatype;
1709 if (!T->isVariableArrayType())
1710 return false;
1711 vlatype = cast<VariableArrayType>(T);
1712 return vlatype->getSizeModifier() == VariableArrayType::Static;
1715 /* Return the type of "decl" as an array.
1717 * In particular, if "decl" is a parameter declaration that
1718 * is a variable length array with a static size, then
1719 * return the original type (i.e., the variable length array).
1720 * Otherwise, return the type of decl.
1722 static QualType get_array_type(ValueDecl *decl)
1724 ParmVarDecl *parm;
1725 QualType T;
1727 parm = dyn_cast<ParmVarDecl>(decl);
1728 if (!parm)
1729 return decl->getType();
1731 T = parm->getOriginalType();
1732 if (!is_vla_with_static_size(T))
1733 return decl->getType();
1734 return T;
1737 extern "C" {
1738 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1739 void *user);
1740 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1741 __isl_keep pet_context *pc, void *user);
1744 /* Construct a pet_expr that holds the sizes of the array accessed
1745 * by "access".
1746 * This function is used as a callback to pet_context_add_parameters,
1747 * which is also passed a pointer to the PetScan object.
1749 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1750 void *user)
1752 PetScan *ps = (PetScan *) user;
1753 isl_id *id;
1754 ValueDecl *decl;
1755 const Type *type;
1757 id = pet_expr_access_get_id(access);
1758 decl = (ValueDecl *) isl_id_get_user(id);
1759 isl_id_free(id);
1760 type = get_array_type(decl).getTypePtr();
1761 return ps->get_array_size(type);
1764 /* Construct and return a pet_array corresponding to the variable
1765 * accessed by "access".
1766 * This function is used as a callback to pet_scop_from_pet_tree,
1767 * which is also passed a pointer to the PetScan object.
1769 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1770 __isl_keep pet_context *pc, void *user)
1772 PetScan *ps = (PetScan *) user;
1773 isl_ctx *ctx;
1774 isl_id *id;
1775 ValueDecl *iv;
1777 ctx = pet_expr_get_ctx(access);
1778 id = pet_expr_access_get_id(access);
1779 iv = (ValueDecl *) isl_id_get_user(id);
1780 isl_id_free(id);
1781 return ps->extract_array(ctx, iv, NULL, pc);
1784 /* Extract a function summary from the body of "fd".
1786 * We extract a scop from the function body in a context with as
1787 * parameters the integer arguments of the function.
1788 * We turn off autodetection (in case it was set) to ensure that
1789 * the entire function body is considered.
1790 * We then collect the accessed array elements and attach them
1791 * to the corresponding array arguments, taking into account
1792 * that the function body may access members of array elements.
1794 * The reason for representing the integer arguments as parameters in
1795 * the context is that if we were to instead start with a context
1796 * with the function arguments as initial dimensions, then we would not
1797 * be able to refer to them from the array extents, without turning
1798 * array extents into maps.
1800 * The result is stored in the summary_cache cache so that we can reuse
1801 * it if this method gets called on the same function again later on.
1803 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
1805 isl_space *space;
1806 isl_set *domain;
1807 pet_context *pc;
1808 pet_tree *tree;
1809 pet_function_summary *summary;
1810 unsigned n;
1811 ScopLoc loc;
1812 int save_autodetect;
1813 struct pet_scop *scop;
1814 int int_size;
1815 isl_union_set *may_read, *may_write, *must_write;
1816 isl_union_map *to_inner;
1818 if (summary_cache.find(fd) != summary_cache.end())
1819 return pet_function_summary_copy(summary_cache[fd]);
1821 space = isl_space_set_alloc(ctx, 0, 0);
1823 n = fd->getNumParams();
1824 summary = pet_function_summary_alloc(ctx, n);
1825 for (int i = 0; i < n; ++i) {
1826 ParmVarDecl *parm = fd->getParamDecl(i);
1827 QualType type = parm->getType();
1828 isl_id *id;
1830 if (!type->isIntegerType())
1831 continue;
1832 id = create_decl_id(ctx, parm);
1833 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
1834 space = isl_space_set_dim_id(space, isl_dim_param, 0,
1835 isl_id_copy(id));
1836 summary = pet_function_summary_set_int(summary, i, id);
1839 save_autodetect = options->autodetect;
1840 options->autodetect = 0;
1841 PetScan body_scan(PP, ast_context, loc, options,
1842 isl_union_map_copy(value_bounds), independent);
1844 tree = body_scan.extract(fd->getBody(), false);
1846 domain = isl_set_universe(space);
1847 pc = pet_context_alloc(domain);
1848 pc = pet_context_add_parameters(pc, tree,
1849 &::get_array_size, &body_scan);
1850 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
1851 scop = pet_scop_from_pet_tree(tree, int_size,
1852 &::extract_array, &body_scan, pc);
1853 scop = scan_arrays(scop, pc);
1854 may_read = isl_union_map_range(pet_scop_collect_may_reads(scop));
1855 may_write = isl_union_map_range(pet_scop_collect_may_writes(scop));
1856 must_write = isl_union_map_range(pet_scop_collect_must_writes(scop));
1857 to_inner = pet_scop_compute_outer_to_inner(scop);
1858 pet_scop_free(scop);
1860 for (int i = 0; i < n; ++i) {
1861 ParmVarDecl *parm = fd->getParamDecl(i);
1862 QualType type = parm->getType();
1863 struct pet_array *array;
1864 isl_space *space;
1865 isl_union_set *data_set;
1866 isl_union_set *may_read_i, *may_write_i, *must_write_i;
1868 if (array_depth(type.getTypePtr()) == 0)
1869 continue;
1871 array = body_scan.extract_array(ctx, parm, NULL, pc);
1872 space = array ? isl_set_get_space(array->extent) : NULL;
1873 pet_array_free(array);
1874 data_set = isl_union_set_from_set(isl_set_universe(space));
1875 data_set = isl_union_set_apply(data_set,
1876 isl_union_map_copy(to_inner));
1877 may_read_i = isl_union_set_intersect(
1878 isl_union_set_copy(may_read),
1879 isl_union_set_copy(data_set));
1880 may_write_i = isl_union_set_intersect(
1881 isl_union_set_copy(may_write),
1882 isl_union_set_copy(data_set));
1883 must_write_i = isl_union_set_intersect(
1884 isl_union_set_copy(must_write), data_set);
1885 summary = pet_function_summary_set_array(summary, i,
1886 may_read_i, may_write_i, must_write_i);
1889 isl_union_set_free(may_read);
1890 isl_union_set_free(may_write);
1891 isl_union_set_free(must_write);
1892 isl_union_map_free(to_inner);
1894 options->autodetect = save_autodetect;
1895 pet_context_free(pc);
1897 summary_cache[fd] = pet_function_summary_copy(summary);
1899 return summary;
1902 /* If "fd" has a function body, then extract a function summary from
1903 * this body and attach it to the call expression "expr".
1905 * Even if a function body is available, "fd" itself may point
1906 * to a declaration without function body. We therefore first
1907 * replace it by the declaration that comes with a body (if any).
1909 * It is not clear why hasBody takes a reference to a const FunctionDecl *.
1910 * It seems that it is possible to directly use the iterators to obtain
1911 * a non-const pointer.
1912 * Since we are not going to use the pointer to modify anything anyway,
1913 * it seems safe to drop the constness. The alternative would be to
1914 * modify a lot of other functions to include const qualifiers.
1916 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
1917 FunctionDecl *fd)
1919 pet_function_summary *summary;
1920 const FunctionDecl *def;
1922 if (!expr)
1923 return NULL;
1924 if (!fd->hasBody(def))
1925 return expr;
1927 fd = const_cast<FunctionDecl *>(def);
1929 summary = get_summary(fd);
1931 expr = pet_expr_call_set_summary(expr, summary);
1933 return expr;
1936 /* Extract a pet_scop from "tree".
1938 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
1939 * then add pet_arrays for all accessed arrays.
1940 * We populate the pet_context with assignments for all parameters used
1941 * inside "tree" or any of the size expressions for the arrays accessed
1942 * by "tree" so that they can be used in affine expressions.
1944 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
1946 int int_size;
1947 isl_set *domain;
1948 pet_context *pc;
1949 pet_scop *scop;
1951 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
1953 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
1954 pc = pet_context_alloc(domain);
1955 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
1956 scop = pet_scop_from_pet_tree(tree, int_size,
1957 &::extract_array, this, pc);
1958 scop = scan_arrays(scop, pc);
1959 pet_context_free(pc);
1961 return scop;
1964 /* Check if the scop marked by the user is exactly this Stmt
1965 * or part of this Stmt.
1966 * If so, return a pet_scop corresponding to the marked region.
1967 * Otherwise, return NULL.
1969 struct pet_scop *PetScan::scan(Stmt *stmt)
1971 SourceManager &SM = PP.getSourceManager();
1972 unsigned start_off, end_off;
1974 start_off = getExpansionOffset(SM, stmt->getLocStart());
1975 end_off = getExpansionOffset(SM, stmt->getLocEnd());
1977 if (start_off > loc.end)
1978 return NULL;
1979 if (end_off < loc.start)
1980 return NULL;
1982 if (start_off >= loc.start && end_off <= loc.end)
1983 return extract_scop(extract(stmt));
1985 StmtIterator start;
1986 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
1987 Stmt *child = *start;
1988 if (!child)
1989 continue;
1990 start_off = getExpansionOffset(SM, child->getLocStart());
1991 end_off = getExpansionOffset(SM, child->getLocEnd());
1992 if (start_off < loc.start && end_off >= loc.end)
1993 return scan(child);
1994 if (start_off >= loc.start)
1995 break;
1998 StmtIterator end;
1999 for (end = start; end != stmt->child_end(); ++end) {
2000 Stmt *child = *end;
2001 start_off = SM.getFileOffset(child->getLocStart());
2002 if (start_off >= loc.end)
2003 break;
2006 return extract_scop(extract(StmtRange(start, end), false, false));
2009 /* Set the size of index "pos" of "array" to "size".
2010 * In particular, add a constraint of the form
2012 * i_pos < size
2014 * to array->extent and a constraint of the form
2016 * size >= 0
2018 * to array->context.
2020 * The domain of "size" is assumed to be zero-dimensional.
2022 static struct pet_array *update_size(struct pet_array *array, int pos,
2023 __isl_take isl_pw_aff *size)
2025 isl_set *valid;
2026 isl_set *univ;
2027 isl_set *bound;
2028 isl_space *dim;
2029 isl_aff *aff;
2030 isl_pw_aff *index;
2031 isl_id *id;
2033 if (!array)
2034 goto error;
2036 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2037 array->context = isl_set_intersect(array->context, valid);
2039 dim = isl_set_get_space(array->extent);
2040 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2041 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2042 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2043 index = isl_pw_aff_alloc(univ, aff);
2045 size = isl_pw_aff_add_dims(size, isl_dim_in,
2046 isl_set_dim(array->extent, isl_dim_set));
2047 id = isl_set_get_tuple_id(array->extent);
2048 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2049 bound = isl_pw_aff_lt_set(index, size);
2051 array->extent = isl_set_intersect(array->extent, bound);
2053 if (!array->context || !array->extent)
2054 return pet_array_free(array);
2056 return array;
2057 error:
2058 isl_pw_aff_free(size);
2059 return NULL;
2062 #ifdef HAVE_DECAYEDTYPE
2064 /* If "type" is a decayed type, then set *decayed to true and
2065 * return the original type.
2067 static const Type *undecay(const Type *type, bool *decayed)
2069 *decayed = isa<DecayedType>(type);
2070 if (*decayed)
2071 type = cast<DecayedType>(type)->getOriginalType().getTypePtr();
2072 return type;
2075 #else
2077 /* If "type" is a decayed type, then set *decayed to true and
2078 * return the original type.
2079 * Since this version of clang does not define a DecayedType,
2080 * we cannot obtain the original type even if it had been decayed and
2081 * we set *decayed to false.
2083 static const Type *undecay(const Type *type, bool *decayed)
2085 *decayed = false;
2086 return type;
2089 #endif
2091 /* Figure out the size of the array at position "pos" and all
2092 * subsequent positions from "type" and update the corresponding
2093 * argument of "expr" accordingly.
2095 * The initial type (when pos is zero) may be a pointer type decayed
2096 * from an array type, if this initial type is the type of a function
2097 * argument. This only happens if the original array type has
2098 * a constant size in the outer dimension as otherwise we get
2099 * a VariableArrayType. Try and obtain this original type (if available) and
2100 * take the outer array size into account if it was marked static.
2102 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2103 const Type *type, int pos)
2105 const ArrayType *atype;
2106 pet_expr *size;
2107 bool decayed = false;
2109 if (!expr)
2110 return NULL;
2112 if (pos == 0)
2113 type = undecay(type, &decayed);
2115 if (type->isPointerType()) {
2116 type = type->getPointeeType().getTypePtr();
2117 return set_upper_bounds(expr, type, pos + 1);
2119 if (!type->isArrayType())
2120 return expr;
2122 type = type->getCanonicalTypeInternal().getTypePtr();
2123 atype = cast<ArrayType>(type);
2125 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2126 type = atype->getElementType().getTypePtr();
2127 return set_upper_bounds(expr, type, pos + 1);
2130 if (type->isConstantArrayType()) {
2131 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2132 size = extract_expr(ca->getSize());
2133 expr = pet_expr_set_arg(expr, pos, size);
2134 } else if (type->isVariableArrayType()) {
2135 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2136 size = extract_expr(vla->getSizeExpr());
2137 expr = pet_expr_set_arg(expr, pos, size);
2140 type = atype->getElementType().getTypePtr();
2142 return set_upper_bounds(expr, type, pos + 1);
2145 /* Construct a pet_expr that holds the sizes of an array of the given type.
2146 * The returned expression is a call expression with as arguments
2147 * the sizes in each dimension. If we are unable to derive the size
2148 * in a given dimension, then the corresponding argument is set to infinity.
2149 * In fact, we initialize all arguments to infinity and then update
2150 * them if we are able to figure out the size.
2152 * The result is stored in the type_size cache so that we can reuse
2153 * it if this method gets called on the same type again later on.
2155 __isl_give pet_expr *PetScan::get_array_size(const Type *type)
2157 int depth;
2158 pet_expr *expr, *inf;
2160 if (type_size.find(type) != type_size.end())
2161 return pet_expr_copy(type_size[type]);
2163 depth = array_depth(type);
2164 inf = pet_expr_new_int(isl_val_infty(ctx));
2165 expr = pet_expr_new_call(ctx, "bounds", depth);
2166 for (int i = 0; i < depth; ++i)
2167 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2168 pet_expr_free(inf);
2170 expr = set_upper_bounds(expr, type, 0);
2171 type_size[type] = pet_expr_copy(expr);
2173 return expr;
2176 /* Does "expr" represent the "integer" infinity?
2178 static int is_infty(__isl_keep pet_expr *expr)
2180 isl_val *v;
2181 int res;
2183 if (pet_expr_get_type(expr) != pet_expr_int)
2184 return 0;
2185 v = pet_expr_int_get_val(expr);
2186 res = isl_val_is_infty(v);
2187 isl_val_free(v);
2189 return res;
2192 /* Figure out the dimensions of an array "array" based on its type
2193 * "type" and update "array" accordingly.
2195 * We first construct a pet_expr that holds the sizes of the array
2196 * in each dimension. The resulting expression may containing
2197 * infinity values for dimension where we are unable to derive
2198 * a size expression.
2200 * The arguments of the size expression that have a value different from
2201 * infinity are then converted to an affine expression
2202 * within the context "pc" and incorporated into the size of "array".
2203 * If we are unable to convert a size expression to an affine expression or
2204 * if the size is not a (symbolic) constant,
2205 * then we leave the corresponding size of "array" untouched.
2207 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2208 const Type *type, __isl_keep pet_context *pc)
2210 int n;
2211 pet_expr *expr;
2213 if (!array)
2214 return NULL;
2216 expr = get_array_size(type);
2218 n = pet_expr_get_n_arg(expr);
2219 for (int i = 0; i < n; ++i) {
2220 pet_expr *arg;
2221 isl_pw_aff *size;
2223 arg = pet_expr_get_arg(expr, i);
2224 if (!is_infty(arg)) {
2225 int dim;
2227 size = pet_expr_extract_affine(arg, pc);
2228 dim = isl_pw_aff_dim(size, isl_dim_in);
2229 if (!size)
2230 array = pet_array_free(array);
2231 else if (isl_pw_aff_involves_nan(size) ||
2232 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2233 isl_pw_aff_free(size);
2234 else {
2235 size = isl_pw_aff_drop_dims(size,
2236 isl_dim_in, i, dim);
2237 array = update_size(array, i, size);
2240 pet_expr_free(arg);
2242 pet_expr_free(expr);
2244 return array;
2247 /* Does "decl" have definition that we can keep track of in a pet_type?
2249 static bool has_printable_definition(RecordDecl *decl)
2251 if (!decl->getDeclName())
2252 return false;
2253 return decl->getLexicalDeclContext() == decl->getDeclContext();
2256 /* Construct and return a pet_array corresponding to the variable "decl".
2257 * In particular, initialize array->extent to
2259 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2261 * and then call set_upper_bounds to set the upper bounds on the indices
2262 * based on the type of the variable. The upper bounds are converted
2263 * to affine expressions within the context "pc".
2265 * If the base type is that of a record with a top-level definition and
2266 * if "types" is not null, then the RecordDecl corresponding to the type
2267 * is added to "types".
2269 * If the base type is that of a record with no top-level definition,
2270 * then we replace it by "<subfield>".
2272 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
2273 lex_recorddecl_set *types, __isl_keep pet_context *pc)
2275 struct pet_array *array;
2276 QualType qt = get_array_type(decl);
2277 const Type *type = qt.getTypePtr();
2278 int depth = array_depth(type);
2279 QualType base = pet_clang_base_type(qt);
2280 string name;
2281 isl_id *id;
2282 isl_space *dim;
2284 array = isl_calloc_type(ctx, struct pet_array);
2285 if (!array)
2286 return NULL;
2288 id = create_decl_id(ctx, decl);
2289 dim = isl_space_set_alloc(ctx, 0, depth);
2290 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
2292 array->extent = isl_set_nat_universe(dim);
2294 dim = isl_space_params_alloc(ctx, 0);
2295 array->context = isl_set_universe(dim);
2297 array = set_upper_bounds(array, type, pc);
2298 if (!array)
2299 return NULL;
2301 name = base.getAsString();
2303 if (types && base->isRecordType()) {
2304 RecordDecl *decl = pet_clang_record_decl(base);
2305 if (has_printable_definition(decl))
2306 types->insert(decl);
2307 else
2308 name = "<subfield>";
2311 array->element_type = strdup(name.c_str());
2312 array->element_is_record = base->isRecordType();
2313 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
2315 return array;
2318 /* Construct and return a pet_array corresponding to the sequence
2319 * of declarations "decls".
2320 * The upper bounds of the array are converted to affine expressions
2321 * within the context "pc".
2322 * If the sequence contains a single declaration, then it corresponds
2323 * to a simple array access. Otherwise, it corresponds to a member access,
2324 * with the declaration for the substructure following that of the containing
2325 * structure in the sequence of declarations.
2326 * We start with the outermost substructure and then combine it with
2327 * information from the inner structures.
2329 * Additionally, keep track of all required types in "types".
2331 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
2332 vector<ValueDecl *> decls, lex_recorddecl_set *types,
2333 __isl_keep pet_context *pc)
2335 struct pet_array *array;
2336 vector<ValueDecl *>::iterator it;
2338 it = decls.begin();
2340 array = extract_array(ctx, *it, types, pc);
2342 for (++it; it != decls.end(); ++it) {
2343 struct pet_array *parent;
2344 const char *base_name, *field_name;
2345 char *product_name;
2347 parent = array;
2348 array = extract_array(ctx, *it, types, pc);
2349 if (!array)
2350 return pet_array_free(parent);
2352 base_name = isl_set_get_tuple_name(parent->extent);
2353 field_name = isl_set_get_tuple_name(array->extent);
2354 product_name = pet_array_member_access_name(ctx,
2355 base_name, field_name);
2357 array->extent = isl_set_product(isl_set_copy(parent->extent),
2358 array->extent);
2359 if (product_name)
2360 array->extent = isl_set_set_tuple_name(array->extent,
2361 product_name);
2362 array->context = isl_set_intersect(array->context,
2363 isl_set_copy(parent->context));
2365 pet_array_free(parent);
2366 free(product_name);
2368 if (!array->extent || !array->context || !product_name)
2369 return pet_array_free(array);
2372 return array;
2375 /* Add a pet_type corresponding to "decl" to "scop, provided
2376 * it is a member of "types" and it has not been added before
2377 * (i.e., it is not a member of "types_done".
2379 * Since we want the user to be able to print the types
2380 * in the order in which they appear in the scop, we need to
2381 * make sure that types of fields in a structure appear before
2382 * that structure. We therefore call ourselves recursively
2383 * on the types of all record subfields.
2385 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2386 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
2387 lex_recorddecl_set &types_done)
2389 string s;
2390 llvm::raw_string_ostream S(s);
2391 RecordDecl::field_iterator it;
2393 if (types.find(decl) == types.end())
2394 return scop;
2395 if (types_done.find(decl) != types_done.end())
2396 return scop;
2398 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
2399 RecordDecl *record;
2400 QualType type = it->getType();
2402 if (!type->isRecordType())
2403 continue;
2404 record = pet_clang_record_decl(type);
2405 scop = add_type(ctx, scop, record, PP, types, types_done);
2408 if (strlen(decl->getName().str().c_str()) == 0)
2409 return scop;
2411 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2412 S.str();
2414 scop->types[scop->n_type] = pet_type_alloc(ctx,
2415 decl->getName().str().c_str(), s.c_str());
2416 if (!scop->types[scop->n_type])
2417 return pet_scop_free(scop);
2419 types_done.insert(decl);
2421 scop->n_type++;
2423 return scop;
2426 /* Construct a list of pet_arrays, one for each array (or scalar)
2427 * accessed inside "scop", add this list to "scop" and return the result.
2428 * The upper bounds of the arrays are converted to affine expressions
2429 * within the context "pc".
2431 * The context of "scop" is updated with the intersection of
2432 * the contexts of all arrays, i.e., constraints on the parameters
2433 * that ensure that the arrays have a valid (non-negative) size.
2435 * If the any of the extracted arrays refers to a member access,
2436 * then also add the required types to "scop".
2438 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
2439 __isl_keep pet_context *pc)
2441 int i;
2442 array_desc_set arrays;
2443 array_desc_set::iterator it;
2444 lex_recorddecl_set types;
2445 lex_recorddecl_set types_done;
2446 lex_recorddecl_set::iterator types_it;
2447 int n_array;
2448 struct pet_array **scop_arrays;
2450 if (!scop)
2451 return NULL;
2453 pet_scop_collect_arrays(scop, arrays);
2454 if (arrays.size() == 0)
2455 return scop;
2457 n_array = scop->n_array;
2459 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2460 n_array + arrays.size());
2461 if (!scop_arrays)
2462 goto error;
2463 scop->arrays = scop_arrays;
2465 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
2466 struct pet_array *array;
2467 array = extract_array(ctx, *it, &types, pc);
2468 scop->arrays[n_array + i] = array;
2469 if (!scop->arrays[n_array + i])
2470 goto error;
2471 scop->n_array++;
2472 scop->context = isl_set_intersect(scop->context,
2473 isl_set_copy(array->context));
2474 if (!scop->context)
2475 goto error;
2478 if (types.size() == 0)
2479 return scop;
2481 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
2482 if (!scop->types)
2483 goto error;
2485 for (types_it = types.begin(); types_it != types.end(); ++types_it)
2486 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
2488 return scop;
2489 error:
2490 pet_scop_free(scop);
2491 return NULL;
2494 /* Bound all parameters in scop->context to the possible values
2495 * of the corresponding C variable.
2497 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
2499 int n;
2501 if (!scop)
2502 return NULL;
2504 n = isl_set_dim(scop->context, isl_dim_param);
2505 for (int i = 0; i < n; ++i) {
2506 isl_id *id;
2507 ValueDecl *decl;
2509 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
2510 if (pet_nested_in_id(id)) {
2511 isl_id_free(id);
2512 isl_die(isl_set_get_ctx(scop->context),
2513 isl_error_internal,
2514 "unresolved nested parameter", goto error);
2516 decl = (ValueDecl *) isl_id_get_user(id);
2517 isl_id_free(id);
2519 scop->context = set_parameter_bounds(scop->context, i, decl);
2521 if (!scop->context)
2522 goto error;
2525 return scop;
2526 error:
2527 pet_scop_free(scop);
2528 return NULL;
2531 /* Construct a pet_scop from the given function.
2533 * If the scop was delimited by scop and endscop pragmas, then we override
2534 * the file offsets by those derived from the pragmas.
2536 struct pet_scop *PetScan::scan(FunctionDecl *fd)
2538 pet_scop *scop;
2539 Stmt *stmt;
2541 stmt = fd->getBody();
2543 if (options->autodetect) {
2544 set_current_stmt(stmt);
2545 scop = extract_scop(extract(stmt, true));
2546 } else {
2547 current_line = loc.start_line;
2548 scop = scan(stmt);
2549 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
2551 scop = add_parameter_bounds(scop);
2552 scop = pet_scop_gist(scop, value_bounds);
2554 return scop;
2557 /* Update this->last_line and this->current_line based on the fact
2558 * that we are about to consider "stmt".
2560 void PetScan::set_current_stmt(Stmt *stmt)
2562 SourceLocation loc = stmt->getLocStart();
2563 SourceManager &SM = PP.getSourceManager();
2565 last_line = current_line;
2566 current_line = SM.getExpansionLineNumber(loc);
2569 /* Is the current statement marked by an independent pragma?
2570 * That is, is there an independent pragma on a line between
2571 * the line of the current statement and the line of the previous statement.
2572 * The search is not implemented very efficiently. We currently
2573 * assume that there are only a few independent pragmas, if any.
2575 bool PetScan::is_current_stmt_marked_independent()
2577 for (int i = 0; i < independent.size(); ++i) {
2578 unsigned line = independent[i].line;
2580 if (last_line < line && line < current_line)
2581 return true;
2584 return false;