update for change in TargetOptions refcounting
[pet.git] / scan.cc
blob83bc0cbdde794a5cdfb2507bce9a756ad15c8870
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 int type_size;
622 pet_expr *arg;
623 enum pet_op_type op;
625 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
626 if (op == pet_op_last) {
627 unsupported(expr);
628 return NULL;
631 arg = extract_expr(expr->getSubExpr());
633 if (expr->isIncrementDecrementOp() &&
634 pet_expr_get_type(arg) == pet_expr_access) {
635 arg = mark_write(arg);
636 arg = pet_expr_access_set_read(arg, 1);
639 type_size = get_type_size(expr->getType(), ast_context);
640 return pet_expr_new_unary(type_size, op, arg);
643 /* Construct a pet_expr representing a binary operator expression.
645 * If the top level operator is an assignment and the LHS is an access,
646 * then we mark that access as a write. If the operator is a compound
647 * assignment, the access is marked as both a read and a write.
649 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
651 int type_size;
652 pet_expr *lhs, *rhs;
653 enum pet_op_type op;
655 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
656 if (op == pet_op_last) {
657 unsupported(expr);
658 return NULL;
661 lhs = extract_expr(expr->getLHS());
662 rhs = extract_expr(expr->getRHS());
664 if (expr->isAssignmentOp() &&
665 pet_expr_get_type(lhs) == pet_expr_access) {
666 lhs = mark_write(lhs);
667 if (expr->isCompoundAssignmentOp())
668 lhs = pet_expr_access_set_read(lhs, 1);
671 type_size = get_type_size(expr->getType(), ast_context);
672 return pet_expr_new_binary(type_size, op, lhs, rhs);
675 /* Construct a pet_tree for a (single) variable declaration.
677 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
679 Decl *decl;
680 VarDecl *vd;
681 pet_expr *lhs, *rhs;
682 pet_tree *tree;
684 if (!stmt->isSingleDecl()) {
685 unsupported(stmt);
686 return NULL;
689 decl = stmt->getSingleDecl();
690 vd = cast<VarDecl>(decl);
692 lhs = extract_access_expr(vd);
693 lhs = mark_write(lhs);
694 if (!vd->getInit())
695 tree = pet_tree_new_decl(lhs);
696 else {
697 rhs = extract_expr(vd->getInit());
698 tree = pet_tree_new_decl_init(lhs, rhs);
701 return tree;
704 /* Construct a pet_expr representing a conditional operation.
706 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
708 pet_expr *cond, *lhs, *rhs;
709 isl_pw_aff *pa;
711 cond = extract_expr(expr->getCond());
712 lhs = extract_expr(expr->getTrueExpr());
713 rhs = extract_expr(expr->getFalseExpr());
715 return pet_expr_new_ternary(cond, lhs, rhs);
718 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
720 return extract_expr(expr->getSubExpr());
723 /* Construct a pet_expr representing a floating point value.
725 * If the floating point literal does not appear in a macro,
726 * then we use the original representation in the source code
727 * as the string representation. Otherwise, we use the pretty
728 * printer to produce a string representation.
730 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
732 double d;
733 string s;
734 const LangOptions &LO = PP.getLangOpts();
735 SourceLocation loc = expr->getLocation();
737 if (!loc.isMacroID()) {
738 SourceManager &SM = PP.getSourceManager();
739 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
740 s = string(SM.getCharacterData(loc), len);
741 } else {
742 llvm::raw_string_ostream S(s);
743 expr->printPretty(S, 0, PrintingPolicy(LO));
744 S.str();
746 d = expr->getValueAsApproximateDouble();
747 return pet_expr_new_double(ctx, d, s.c_str());
750 /* Convert the index expression "index" into an access pet_expr of type "qt".
752 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
753 __isl_take pet_expr *index)
755 int depth;
756 int type_size;
758 depth = extract_depth(index);
759 type_size = get_type_size(qt, ast_context);
761 index = pet_expr_set_type_size(index, type_size);
762 index = pet_expr_access_set_depth(index, depth);
764 return index;
767 /* Extract an index expression from "expr" and then convert it into
768 * an access pet_expr.
770 * If "expr" is a reference to an enum constant, then return
771 * an integer expression instead, representing the value of the enum constant.
773 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
775 pet_expr *index;
777 index = extract_index_expr(expr);
779 if (pet_expr_get_type(index) == pet_expr_int)
780 return index;
782 return extract_access_expr(expr->getType(), index);
785 /* Extract an index expression from "decl" and then convert it into
786 * an access pet_expr.
788 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
790 return extract_access_expr(decl->getType(), extract_index_expr(decl));
793 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
795 return extract_expr(expr->getSubExpr());
798 /* Extract an assume statement from the argument "expr"
799 * of a __pencil_assume statement.
801 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
803 return pet_expr_new_unary(0, pet_op_assume, extract_expr(expr));
806 /* Construct a pet_expr corresponding to the function call argument "expr".
807 * The argument appears in position "pos" of a call to function "fd".
809 * If we are passing along a pointer to an array element
810 * or an entire row or even higher dimensional slice of an array,
811 * then the function being called may write into the array.
813 * We assume here that if the function is declared to take a pointer
814 * to a const type, then the function will perform a read
815 * and that otherwise, it will perform a write.
817 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
818 Expr *expr)
820 pet_expr *res;
821 int is_addr = 0, is_partial = 0;
822 Stmt::StmtClass sc;
824 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
825 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
826 expr = ice->getSubExpr();
828 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
829 UnaryOperator *op = cast<UnaryOperator>(expr);
830 if (op->getOpcode() == UO_AddrOf) {
831 is_addr = 1;
832 expr = op->getSubExpr();
835 res = extract_expr(expr);
836 if (!res)
837 return NULL;
838 sc = expr->getStmtClass();
839 if ((sc == Stmt::ArraySubscriptExprClass ||
840 sc == Stmt::DeclRefExprClass ||
841 sc == Stmt::MemberExprClass) &&
842 array_depth(expr->getType().getTypePtr()) > 0)
843 is_partial = 1;
844 if ((is_addr || is_partial) &&
845 pet_expr_get_type(res) == pet_expr_access) {
846 ParmVarDecl *parm;
847 if (!fd->hasPrototype()) {
848 report_prototype_required(expr);
849 return pet_expr_free(res);
851 parm = fd->getParamDecl(pos);
852 if (!const_base(parm->getType()))
853 res = mark_write(res);
856 if (is_addr)
857 res = pet_expr_new_unary(0, pet_op_address_of, res);
858 return res;
861 /* Find the first FunctionDecl with the given name.
862 * "call" is the corresponding call expression and is only used
863 * for reporting errors.
865 * Return NULL on error.
867 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
869 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
870 DeclContext::decl_iterator begin = tu->decls_begin();
871 DeclContext::decl_iterator end = tu->decls_end();
872 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
873 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
874 if (!fd)
875 continue;
876 if (fd->getName().str().compare(name) != 0)
877 continue;
878 if (fd->hasBody())
879 return fd;
880 report_missing_summary_function_body(call);
881 return NULL;
883 report_missing_summary_function(call);
884 return NULL;
887 /* Return the FunctionDecl for the summary function associated to the
888 * function called by "call".
890 * In particular, search for an annotate attribute formatted as
891 * "pencil_access(name)", where "name" is the name of the summary function.
893 * If no summary function was specified, then return the FunctionDecl
894 * that is actually being called.
896 * Return NULL on error.
898 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
900 FunctionDecl *decl = call->getDirectCallee();
901 if (!decl)
902 return NULL;
904 specific_attr_iterator<AnnotateAttr> begin, end, i;
905 begin = decl->specific_attr_begin<AnnotateAttr>();
906 end = decl->specific_attr_end<AnnotateAttr>();
907 for (i = begin; i != end; ++i) {
908 string attr = (*i)->getAnnotation().str();
910 const char prefix[] = "pencil_access(";
911 size_t start = attr.find(prefix);
912 if (start == string::npos)
913 continue;
914 start += strlen(prefix);
915 string name = attr.substr(start, attr.find(')') - start);
917 return find_decl_from_name(call, name);
920 return decl;
923 /* Construct a pet_expr representing a function call.
925 * In the special case of a "call" to __pencil_assume,
926 * construct an assume expression instead.
928 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
930 pet_expr *res = NULL;
931 FunctionDecl *fd;
932 string name;
933 unsigned n_arg;
935 fd = expr->getDirectCallee();
936 if (!fd) {
937 unsupported(expr);
938 return NULL;
941 name = fd->getDeclName().getAsString();
942 n_arg = expr->getNumArgs();
944 if (n_arg == 1 && name == "__pencil_assume")
945 return extract_assume(expr->getArg(0));
947 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
948 if (!res)
949 return NULL;
951 for (int i = 0; i < n_arg; ++i) {
952 Expr *arg = expr->getArg(i);
953 res = pet_expr_set_arg(res, i,
954 PetScan::extract_argument(fd, i, arg));
957 fd = get_summary_function(expr);
958 if (!fd)
959 return pet_expr_free(res);
961 res = set_summary(res, fd);
963 return res;
966 /* Construct a pet_expr representing a (C style) cast.
968 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
970 pet_expr *arg;
971 QualType type;
973 arg = extract_expr(expr->getSubExpr());
974 if (!arg)
975 return NULL;
977 type = expr->getTypeAsWritten();
978 return pet_expr_new_cast(type.getAsString().c_str(), arg);
981 /* Construct a pet_expr representing an integer.
983 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
985 return pet_expr_new_int(extract_int(expr));
988 /* Construct a pet_expr representing the integer enum constant "ecd".
990 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
992 isl_val *v;
993 const llvm::APSInt &init = ecd->getInitVal();
994 v = ::extract_int(ctx, init.isSigned(), init);
995 return pet_expr_new_int(v);
998 /* Try and construct a pet_expr representing "expr".
1000 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1002 switch (expr->getStmtClass()) {
1003 case Stmt::UnaryOperatorClass:
1004 return extract_expr(cast<UnaryOperator>(expr));
1005 case Stmt::CompoundAssignOperatorClass:
1006 case Stmt::BinaryOperatorClass:
1007 return extract_expr(cast<BinaryOperator>(expr));
1008 case Stmt::ImplicitCastExprClass:
1009 return extract_expr(cast<ImplicitCastExpr>(expr));
1010 case Stmt::ArraySubscriptExprClass:
1011 case Stmt::DeclRefExprClass:
1012 case Stmt::MemberExprClass:
1013 return extract_access_expr(expr);
1014 case Stmt::IntegerLiteralClass:
1015 return extract_expr(cast<IntegerLiteral>(expr));
1016 case Stmt::FloatingLiteralClass:
1017 return extract_expr(cast<FloatingLiteral>(expr));
1018 case Stmt::ParenExprClass:
1019 return extract_expr(cast<ParenExpr>(expr));
1020 case Stmt::ConditionalOperatorClass:
1021 return extract_expr(cast<ConditionalOperator>(expr));
1022 case Stmt::CallExprClass:
1023 return extract_expr(cast<CallExpr>(expr));
1024 case Stmt::CStyleCastExprClass:
1025 return extract_expr(cast<CStyleCastExpr>(expr));
1026 default:
1027 unsupported(expr);
1029 return NULL;
1032 /* Check if the given initialization statement is an assignment.
1033 * If so, return that assignment. Otherwise return NULL.
1035 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1037 BinaryOperator *ass;
1039 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1040 return NULL;
1042 ass = cast<BinaryOperator>(init);
1043 if (ass->getOpcode() != BO_Assign)
1044 return NULL;
1046 return ass;
1049 /* Check if the given initialization statement is a declaration
1050 * of a single variable.
1051 * If so, return that declaration. Otherwise return NULL.
1053 Decl *PetScan::initialization_declaration(Stmt *init)
1055 DeclStmt *decl;
1057 if (init->getStmtClass() != Stmt::DeclStmtClass)
1058 return NULL;
1060 decl = cast<DeclStmt>(init);
1062 if (!decl->isSingleDecl())
1063 return NULL;
1065 return decl->getSingleDecl();
1068 /* Given the assignment operator in the initialization of a for loop,
1069 * extract the induction variable, i.e., the (integer)variable being
1070 * assigned.
1072 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1074 Expr *lhs;
1075 DeclRefExpr *ref;
1076 ValueDecl *decl;
1077 const Type *type;
1079 lhs = init->getLHS();
1080 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1081 unsupported(init);
1082 return NULL;
1085 ref = cast<DeclRefExpr>(lhs);
1086 decl = ref->getDecl();
1087 type = decl->getType().getTypePtr();
1089 if (!type->isIntegerType()) {
1090 unsupported(lhs);
1091 return NULL;
1094 return decl;
1097 /* Given the initialization statement of a for loop and the single
1098 * declaration in this initialization statement,
1099 * extract the induction variable, i.e., the (integer) variable being
1100 * declared.
1102 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1104 VarDecl *vd;
1106 vd = cast<VarDecl>(decl);
1108 const QualType type = vd->getType();
1109 if (!type->isIntegerType()) {
1110 unsupported(init);
1111 return NULL;
1114 if (!vd->getInit()) {
1115 unsupported(init);
1116 return NULL;
1119 return vd;
1122 /* Check that op is of the form iv++ or iv--.
1123 * Return a pet_expr representing "1" or "-1" accordingly.
1125 __isl_give pet_expr *PetScan::extract_unary_increment(
1126 clang::UnaryOperator *op, clang::ValueDecl *iv)
1128 Expr *sub;
1129 DeclRefExpr *ref;
1130 isl_val *v;
1132 if (!op->isIncrementDecrementOp()) {
1133 unsupported(op);
1134 return NULL;
1137 sub = op->getSubExpr();
1138 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1139 unsupported(op);
1140 return NULL;
1143 ref = cast<DeclRefExpr>(sub);
1144 if (ref->getDecl() != iv) {
1145 unsupported(op);
1146 return NULL;
1149 if (op->isIncrementOp())
1150 v = isl_val_one(ctx);
1151 else
1152 v = isl_val_negone(ctx);
1154 return pet_expr_new_int(v);
1157 /* Check if op is of the form
1159 * iv = expr
1161 * and return the increment "expr - iv" as a pet_expr.
1163 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1164 clang::ValueDecl *iv)
1166 int type_size;
1167 Expr *lhs;
1168 DeclRefExpr *ref;
1169 pet_expr *expr, *expr_iv;
1171 if (op->getOpcode() != BO_Assign) {
1172 unsupported(op);
1173 return NULL;
1176 lhs = op->getLHS();
1177 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1178 unsupported(op);
1179 return NULL;
1182 ref = cast<DeclRefExpr>(lhs);
1183 if (ref->getDecl() != iv) {
1184 unsupported(op);
1185 return NULL;
1188 expr = extract_expr(op->getRHS());
1189 expr_iv = extract_expr(lhs);
1191 type_size = get_type_size(iv->getType(), ast_context);
1192 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1195 /* Check that op is of the form iv += cst or iv -= cst
1196 * and return a pet_expr corresponding to cst or -cst accordingly.
1198 __isl_give pet_expr *PetScan::extract_compound_increment(
1199 CompoundAssignOperator *op, clang::ValueDecl *iv)
1201 Expr *lhs;
1202 DeclRefExpr *ref;
1203 bool neg = false;
1204 pet_expr *expr;
1205 BinaryOperatorKind opcode;
1207 opcode = op->getOpcode();
1208 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1209 unsupported(op);
1210 return NULL;
1212 if (opcode == BO_SubAssign)
1213 neg = true;
1215 lhs = op->getLHS();
1216 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1217 unsupported(op);
1218 return NULL;
1221 ref = cast<DeclRefExpr>(lhs);
1222 if (ref->getDecl() != iv) {
1223 unsupported(op);
1224 return NULL;
1227 expr = extract_expr(op->getRHS());
1228 if (neg) {
1229 int type_size;
1230 type_size = get_type_size(op->getType(), ast_context);
1231 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1234 return expr;
1237 /* Check that the increment of the given for loop increments
1238 * (or decrements) the induction variable "iv" and return
1239 * the increment as a pet_expr if successful.
1241 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1242 ValueDecl *iv)
1244 Stmt *inc = stmt->getInc();
1246 if (!inc) {
1247 report_missing_increment(stmt);
1248 return NULL;
1251 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1252 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1253 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1254 return extract_compound_increment(
1255 cast<CompoundAssignOperator>(inc), iv);
1256 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1257 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1259 unsupported(inc);
1260 return NULL;
1263 /* Construct a pet_tree for a while loop.
1265 * If we were only able to extract part of the body, then simply
1266 * return that part.
1268 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1270 pet_expr *pe_cond;
1271 pet_tree *tree;
1273 tree = extract(stmt->getBody());
1274 if (partial)
1275 return tree;
1276 pe_cond = extract_expr(stmt->getCond());
1277 tree = pet_tree_new_while(pe_cond, tree);
1279 return tree;
1282 /* Construct a pet_tree for a for statement.
1283 * The for loop is required to be of one of the following forms
1285 * for (i = init; condition; ++i)
1286 * for (i = init; condition; --i)
1287 * for (i = init; condition; i += constant)
1288 * for (i = init; condition; i -= constant)
1290 * We extract a pet_tree for the body and then include it in a pet_tree
1291 * of type pet_tree_for.
1293 * As a special case, we also allow a for loop of the form
1295 * for (;;)
1297 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1299 * If we were only able to extract part of the body, then simply
1300 * return that part.
1302 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1304 BinaryOperator *ass;
1305 Decl *decl;
1306 Stmt *init;
1307 Expr *lhs, *rhs;
1308 ValueDecl *iv;
1309 pet_tree *tree;
1310 struct pet_scop *scop;
1311 int independent;
1312 int declared;
1313 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1315 independent = is_current_stmt_marked_independent();
1317 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1318 tree = extract(stmt->getBody());
1319 if (partial)
1320 return tree;
1321 tree = pet_tree_new_infinite_loop(tree);
1322 return tree;
1325 init = stmt->getInit();
1326 if (!init) {
1327 unsupported(stmt);
1328 return NULL;
1330 if ((ass = initialization_assignment(init)) != NULL) {
1331 iv = extract_induction_variable(ass);
1332 if (!iv)
1333 return NULL;
1334 lhs = ass->getLHS();
1335 rhs = ass->getRHS();
1336 } else if ((decl = initialization_declaration(init)) != NULL) {
1337 VarDecl *var = extract_induction_variable(init, decl);
1338 if (!var)
1339 return NULL;
1340 iv = var;
1341 rhs = var->getInit();
1342 lhs = create_DeclRefExpr(var);
1343 } else {
1344 unsupported(stmt->getInit());
1345 return NULL;
1348 declared = !initialization_assignment(stmt->getInit());
1349 tree = extract(stmt->getBody());
1350 if (partial)
1351 return tree;
1352 pe_iv = extract_access_expr(iv);
1353 pe_iv = mark_write(pe_iv);
1354 pe_init = extract_expr(rhs);
1355 if (!stmt->getCond())
1356 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1357 else
1358 pe_cond = extract_expr(stmt->getCond());
1359 pe_inc = extract_increment(stmt, iv);
1360 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1361 pe_inc, tree);
1362 return tree;
1365 /* Try and construct a pet_tree corresponding to a compound statement.
1367 * "skip_declarations" is set if we should skip initial declarations
1368 * in the children of the compound statements. This then implies
1369 * that this sequence of children should not be treated as a block
1370 * since the initial statements may be skipped.
1372 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1373 bool skip_declarations)
1375 return extract(stmt->children(), !skip_declarations, skip_declarations);
1378 /* Return the file offset of the expansion location of "Loc".
1380 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1382 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1385 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1387 /* Return a SourceLocation for the location after the first semicolon
1388 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1389 * call it and also skip trailing spaces and newline.
1391 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1392 const LangOptions &LO)
1394 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1397 #else
1399 /* Return a SourceLocation for the location after the first semicolon
1400 * after "loc". If Lexer::findLocationAfterToken is not available,
1401 * we look in the underlying character data for the first semicolon.
1403 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1404 const LangOptions &LO)
1406 const char *semi;
1407 const char *s = SM.getCharacterData(loc);
1409 semi = strchr(s, ';');
1410 if (!semi)
1411 return SourceLocation();
1412 return loc.getFileLocWithOffset(semi + 1 - s);
1415 #endif
1417 /* If the token at "loc" is the first token on the line, then return
1418 * a location referring to the start of the line and set *indent
1419 * to the indentation of "loc"
1420 * Otherwise, return "loc" and set *indent to "".
1422 * This function is used to extend a scop to the start of the line
1423 * if the first token of the scop is also the first token on the line.
1425 * We look for the first token on the line. If its location is equal to "loc",
1426 * then the latter is the location of the first token on the line.
1428 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1429 SourceManager &SM, const LangOptions &LO, char **indent)
1431 std::pair<FileID, unsigned> file_offset_pair;
1432 llvm::StringRef file;
1433 const char *pos;
1434 Token tok;
1435 SourceLocation token_loc, line_loc;
1436 int col;
1437 const char *s;
1439 loc = SM.getExpansionLoc(loc);
1440 col = SM.getExpansionColumnNumber(loc);
1441 line_loc = loc.getLocWithOffset(1 - col);
1442 file_offset_pair = SM.getDecomposedLoc(line_loc);
1443 file = SM.getBufferData(file_offset_pair.first, NULL);
1444 pos = file.data() + file_offset_pair.second;
1446 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1447 file.begin(), pos, file.end());
1448 lexer.LexFromRawLexer(tok);
1449 token_loc = tok.getLocation();
1451 s = SM.getCharacterData(line_loc);
1452 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1454 if (token_loc == loc)
1455 return line_loc;
1456 else
1457 return loc;
1460 /* Construct a pet_loc corresponding to the region covered by "range".
1461 * If "skip_semi" is set, then we assume "range" is followed by
1462 * a semicolon and also include this semicolon.
1464 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1465 bool skip_semi)
1467 SourceLocation loc = range.getBegin();
1468 SourceManager &SM = PP.getSourceManager();
1469 const LangOptions &LO = PP.getLangOpts();
1470 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1471 unsigned start, end;
1472 char *indent;
1474 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1475 start = getExpansionOffset(SM, loc);
1476 loc = range.getEnd();
1477 if (skip_semi)
1478 loc = location_after_semi(loc, SM, LO);
1479 else
1480 loc = PP.getLocForEndOfToken(loc);
1481 end = getExpansionOffset(SM, loc);
1483 return pet_loc_alloc(ctx, start, end, line, indent);
1486 /* Convert a top-level pet_expr to an expression pet_tree.
1488 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1489 SourceRange range, bool skip_semi)
1491 pet_loc *loc;
1492 pet_tree *tree;
1494 tree = pet_tree_new_expr(expr);
1495 loc = construct_pet_loc(range, skip_semi);
1496 tree = pet_tree_set_loc(tree, loc);
1498 return tree;
1501 /* Construct a pet_tree for an if statement.
1503 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1505 pet_expr *pe_cond;
1506 pet_tree *tree, *tree_else;
1507 struct pet_scop *scop;
1508 int int_size;
1510 pe_cond = extract_expr(stmt->getCond());
1511 tree = extract(stmt->getThen());
1512 if (stmt->getElse()) {
1513 tree_else = extract(stmt->getElse());
1514 if (options->autodetect) {
1515 if (tree && !tree_else) {
1516 partial = true;
1517 pet_expr_free(pe_cond);
1518 return tree;
1520 if (!tree && tree_else) {
1521 partial = true;
1522 pet_expr_free(pe_cond);
1523 return tree_else;
1526 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1527 } else
1528 tree = pet_tree_new_if(pe_cond, tree);
1529 return tree;
1532 /* Try and construct a pet_tree for a label statement.
1533 * We currently only allow labels on expression statements.
1535 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1537 isl_id *label;
1538 pet_tree *tree;
1539 Stmt *sub;
1541 sub = stmt->getSubStmt();
1542 if (!isa<Expr>(sub)) {
1543 unsupported(stmt);
1544 return NULL;
1547 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1549 tree = extract(extract_expr(cast<Expr>(sub)), stmt->getSourceRange(),
1550 true);
1551 tree = pet_tree_set_label(tree, label);
1552 return tree;
1555 /* Update the location of "tree" to include the source range of "stmt".
1557 * Actually, we create a new location based on the source range of "stmt" and
1558 * then extend this new location to include the region of the original location.
1559 * This ensures that the line number of the final location refers to "stmt".
1561 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1563 pet_loc *loc, *tree_loc;
1565 tree_loc = pet_tree_get_loc(tree);
1566 loc = construct_pet_loc(stmt->getSourceRange(), false);
1567 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1568 pet_loc_free(tree_loc);
1570 tree = pet_tree_set_loc(tree, loc);
1571 return tree;
1574 /* Try and construct a pet_tree corresponding to "stmt".
1576 * If "stmt" is a compound statement, then "skip_declarations"
1577 * indicates whether we should skip initial declarations in the
1578 * compound statement.
1580 * If the constructed pet_tree is not a (possibly) partial representation
1581 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1582 * In particular, if skip_declarations is set, then we may have skipped
1583 * declarations inside "stmt" and so the pet_scop may not represent
1584 * the entire "stmt".
1585 * Note that this function may be called with "stmt" referring to the entire
1586 * body of the function, including the outer braces. In such cases,
1587 * skip_declarations will be set and the braces will not be taken into
1588 * account in tree->loc.
1590 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
1592 pet_tree *tree;
1594 set_current_stmt(stmt);
1596 if (isa<Expr>(stmt))
1597 return extract(extract_expr(cast<Expr>(stmt)),
1598 stmt->getSourceRange(), true);
1600 switch (stmt->getStmtClass()) {
1601 case Stmt::WhileStmtClass:
1602 tree = extract(cast<WhileStmt>(stmt));
1603 break;
1604 case Stmt::ForStmtClass:
1605 tree = extract_for(cast<ForStmt>(stmt));
1606 break;
1607 case Stmt::IfStmtClass:
1608 tree = extract(cast<IfStmt>(stmt));
1609 break;
1610 case Stmt::CompoundStmtClass:
1611 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
1612 break;
1613 case Stmt::LabelStmtClass:
1614 tree = extract(cast<LabelStmt>(stmt));
1615 break;
1616 case Stmt::ContinueStmtClass:
1617 tree = pet_tree_new_continue(ctx);
1618 break;
1619 case Stmt::BreakStmtClass:
1620 tree = pet_tree_new_break(ctx);
1621 break;
1622 case Stmt::DeclStmtClass:
1623 tree = extract(cast<DeclStmt>(stmt));
1624 break;
1625 default:
1626 unsupported(stmt);
1627 return NULL;
1630 if (partial || skip_declarations)
1631 return tree;
1633 return update_loc(tree, stmt);
1636 /* Try and construct a pet_tree corresponding to (part of)
1637 * a sequence of statements.
1639 * "block" is set if the sequence represents the children of
1640 * a compound statement.
1641 * "skip_declarations" is set if we should skip initial declarations
1642 * in the sequence of statements.
1644 * If autodetect is set, then we allow the extraction of only a subrange
1645 * of the sequence of statements. However, if there is at least one statement
1646 * for which we could not construct a scop and the final range contains
1647 * either no statements or at least one kill, then we discard the entire
1648 * range.
1650 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
1651 bool skip_declarations)
1653 StmtIterator i;
1654 int j;
1655 bool has_kills = false;
1656 bool partial_range = false;
1657 pet_tree *tree;
1658 set<struct pet_stmt *> kills;
1659 set<struct pet_stmt *>::iterator it;
1661 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
1664 tree = pet_tree_new_block(ctx, block, j);
1666 for (i = stmt_range.first; i != stmt_range.second; ++i) {
1667 Stmt *child = *i;
1668 pet_tree *tree_i;
1670 if (pet_tree_block_n_child(tree) == 0 && skip_declarations &&
1671 child->getStmtClass() == Stmt::DeclStmtClass)
1672 continue;
1674 tree_i = extract(child);
1675 if (pet_tree_block_n_child(tree) != 0 && partial) {
1676 pet_tree_free(tree_i);
1677 break;
1679 if (tree_i && child->getStmtClass() == Stmt::DeclStmtClass &&
1680 block)
1681 has_kills = true;
1682 if (options->autodetect) {
1683 if (tree_i)
1684 tree = pet_tree_block_add_child(tree, tree_i);
1685 else
1686 partial_range = true;
1687 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
1688 partial = true;
1689 } else {
1690 tree = pet_tree_block_add_child(tree, tree_i);
1693 if (partial || !tree)
1694 break;
1697 if (tree && partial_range) {
1698 if (pet_tree_block_n_child(tree) == 0 || has_kills) {
1699 pet_tree_free(tree);
1700 return NULL;
1702 partial = true;
1705 return tree;
1708 /* Is "T" the type of a variable length array with static size?
1710 static bool is_vla_with_static_size(QualType T)
1712 const VariableArrayType *vlatype;
1714 if (!T->isVariableArrayType())
1715 return false;
1716 vlatype = cast<VariableArrayType>(T);
1717 return vlatype->getSizeModifier() == VariableArrayType::Static;
1720 /* Return the type of "decl" as an array.
1722 * In particular, if "decl" is a parameter declaration that
1723 * is a variable length array with a static size, then
1724 * return the original type (i.e., the variable length array).
1725 * Otherwise, return the type of decl.
1727 static QualType get_array_type(ValueDecl *decl)
1729 ParmVarDecl *parm;
1730 QualType T;
1732 parm = dyn_cast<ParmVarDecl>(decl);
1733 if (!parm)
1734 return decl->getType();
1736 T = parm->getOriginalType();
1737 if (!is_vla_with_static_size(T))
1738 return decl->getType();
1739 return T;
1742 extern "C" {
1743 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1744 void *user);
1745 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1746 __isl_keep pet_context *pc, void *user);
1749 /* Construct a pet_expr that holds the sizes of the array accessed
1750 * by "access".
1751 * This function is used as a callback to pet_context_add_parameters,
1752 * which is also passed a pointer to the PetScan object.
1754 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1755 void *user)
1757 PetScan *ps = (PetScan *) user;
1758 isl_id *id;
1759 ValueDecl *decl;
1760 const Type *type;
1762 id = pet_expr_access_get_id(access);
1763 decl = (ValueDecl *) isl_id_get_user(id);
1764 isl_id_free(id);
1765 type = get_array_type(decl).getTypePtr();
1766 return ps->get_array_size(type);
1769 /* Construct and return a pet_array corresponding to the variable
1770 * accessed by "access".
1771 * This function is used as a callback to pet_scop_from_pet_tree,
1772 * which is also passed a pointer to the PetScan object.
1774 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1775 __isl_keep pet_context *pc, void *user)
1777 PetScan *ps = (PetScan *) user;
1778 isl_ctx *ctx;
1779 isl_id *id;
1780 ValueDecl *iv;
1782 ctx = pet_expr_get_ctx(access);
1783 id = pet_expr_access_get_id(access);
1784 iv = (ValueDecl *) isl_id_get_user(id);
1785 isl_id_free(id);
1786 return ps->extract_array(ctx, iv, NULL, pc);
1789 /* Extract a function summary from the body of "fd".
1791 * We extract a scop from the function body in a context with as
1792 * parameters the integer arguments of the function.
1793 * We turn off autodetection (in case it was set) to ensure that
1794 * the entire function body is considered.
1795 * We then collect the accessed array elements and attach them
1796 * to the corresponding array arguments, taking into account
1797 * that the function body may access members of array elements.
1799 * The reason for representing the integer arguments as parameters in
1800 * the context is that if we were to instead start with a context
1801 * with the function arguments as initial dimensions, then we would not
1802 * be able to refer to them from the array extents, without turning
1803 * array extents into maps.
1805 * The result is stored in the summary_cache cache so that we can reuse
1806 * it if this method gets called on the same function again later on.
1808 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
1810 isl_space *space;
1811 isl_set *domain;
1812 pet_context *pc;
1813 pet_tree *tree;
1814 pet_function_summary *summary;
1815 unsigned n;
1816 ScopLoc loc;
1817 int save_autodetect;
1818 struct pet_scop *scop;
1819 int int_size;
1820 isl_union_set *may_read, *may_write, *must_write;
1821 isl_union_map *to_inner;
1823 if (summary_cache.find(fd) != summary_cache.end())
1824 return pet_function_summary_copy(summary_cache[fd]);
1826 space = isl_space_set_alloc(ctx, 0, 0);
1828 n = fd->getNumParams();
1829 summary = pet_function_summary_alloc(ctx, n);
1830 for (int i = 0; i < n; ++i) {
1831 ParmVarDecl *parm = fd->getParamDecl(i);
1832 QualType type = parm->getType();
1833 isl_id *id;
1835 if (!type->isIntegerType())
1836 continue;
1837 id = create_decl_id(ctx, parm);
1838 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
1839 space = isl_space_set_dim_id(space, isl_dim_param, 0,
1840 isl_id_copy(id));
1841 summary = pet_function_summary_set_int(summary, i, id);
1844 save_autodetect = options->autodetect;
1845 options->autodetect = 0;
1846 PetScan body_scan(PP, ast_context, loc, options,
1847 isl_union_map_copy(value_bounds), independent);
1849 tree = body_scan.extract(fd->getBody(), false);
1851 domain = isl_set_universe(space);
1852 pc = pet_context_alloc(domain);
1853 pc = pet_context_add_parameters(pc, tree,
1854 &::get_array_size, &body_scan);
1855 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
1856 scop = pet_scop_from_pet_tree(tree, int_size,
1857 &::extract_array, &body_scan, pc);
1858 scop = scan_arrays(scop, pc);
1859 may_read = isl_union_map_range(pet_scop_collect_may_reads(scop));
1860 may_write = isl_union_map_range(pet_scop_collect_may_writes(scop));
1861 must_write = isl_union_map_range(pet_scop_collect_must_writes(scop));
1862 to_inner = pet_scop_compute_outer_to_inner(scop);
1863 pet_scop_free(scop);
1865 for (int i = 0; i < n; ++i) {
1866 ParmVarDecl *parm = fd->getParamDecl(i);
1867 QualType type = parm->getType();
1868 struct pet_array *array;
1869 isl_space *space;
1870 isl_union_set *data_set;
1871 isl_union_set *may_read_i, *may_write_i, *must_write_i;
1873 if (array_depth(type.getTypePtr()) == 0)
1874 continue;
1876 array = body_scan.extract_array(ctx, parm, NULL, pc);
1877 space = array ? isl_set_get_space(array->extent) : NULL;
1878 pet_array_free(array);
1879 data_set = isl_union_set_from_set(isl_set_universe(space));
1880 data_set = isl_union_set_apply(data_set,
1881 isl_union_map_copy(to_inner));
1882 may_read_i = isl_union_set_intersect(
1883 isl_union_set_copy(may_read),
1884 isl_union_set_copy(data_set));
1885 may_write_i = isl_union_set_intersect(
1886 isl_union_set_copy(may_write),
1887 isl_union_set_copy(data_set));
1888 must_write_i = isl_union_set_intersect(
1889 isl_union_set_copy(must_write), data_set);
1890 summary = pet_function_summary_set_array(summary, i,
1891 may_read_i, may_write_i, must_write_i);
1894 isl_union_set_free(may_read);
1895 isl_union_set_free(may_write);
1896 isl_union_set_free(must_write);
1897 isl_union_map_free(to_inner);
1899 options->autodetect = save_autodetect;
1900 pet_context_free(pc);
1902 summary_cache[fd] = pet_function_summary_copy(summary);
1904 return summary;
1907 /* If "fd" has a function body, then extract a function summary from
1908 * this body and attach it to the call expression "expr".
1910 * Even if a function body is available, "fd" itself may point
1911 * to a declaration without function body. We therefore first
1912 * replace it by the declaration that comes with a body (if any).
1914 * It is not clear why hasBody takes a reference to a const FunctionDecl *.
1915 * It seems that it is possible to directly use the iterators to obtain
1916 * a non-const pointer.
1917 * Since we are not going to use the pointer to modify anything anyway,
1918 * it seems safe to drop the constness. The alternative would be to
1919 * modify a lot of other functions to include const qualifiers.
1921 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
1922 FunctionDecl *fd)
1924 pet_function_summary *summary;
1925 const FunctionDecl *def;
1927 if (!expr)
1928 return NULL;
1929 if (!fd->hasBody(def))
1930 return expr;
1932 fd = const_cast<FunctionDecl *>(def);
1934 summary = get_summary(fd);
1936 expr = pet_expr_call_set_summary(expr, summary);
1938 return expr;
1941 /* Extract a pet_scop from "tree".
1943 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
1944 * then add pet_arrays for all accessed arrays.
1945 * We populate the pet_context with assignments for all parameters used
1946 * inside "tree" or any of the size expressions for the arrays accessed
1947 * by "tree" so that they can be used in affine expressions.
1949 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
1951 int int_size;
1952 isl_set *domain;
1953 pet_context *pc;
1954 pet_scop *scop;
1956 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
1958 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
1959 pc = pet_context_alloc(domain);
1960 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
1961 scop = pet_scop_from_pet_tree(tree, int_size,
1962 &::extract_array, this, pc);
1963 scop = scan_arrays(scop, pc);
1964 pet_context_free(pc);
1966 return scop;
1969 /* Check if the scop marked by the user is exactly this Stmt
1970 * or part of this Stmt.
1971 * If so, return a pet_scop corresponding to the marked region.
1972 * Otherwise, return NULL.
1974 struct pet_scop *PetScan::scan(Stmt *stmt)
1976 SourceManager &SM = PP.getSourceManager();
1977 unsigned start_off, end_off;
1979 start_off = getExpansionOffset(SM, stmt->getLocStart());
1980 end_off = getExpansionOffset(SM, stmt->getLocEnd());
1982 if (start_off > loc.end)
1983 return NULL;
1984 if (end_off < loc.start)
1985 return NULL;
1987 if (start_off >= loc.start && end_off <= loc.end)
1988 return extract_scop(extract(stmt));
1990 StmtIterator start;
1991 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
1992 Stmt *child = *start;
1993 if (!child)
1994 continue;
1995 start_off = getExpansionOffset(SM, child->getLocStart());
1996 end_off = getExpansionOffset(SM, child->getLocEnd());
1997 if (start_off < loc.start && end_off >= loc.end)
1998 return scan(child);
1999 if (start_off >= loc.start)
2000 break;
2003 StmtIterator end;
2004 for (end = start; end != stmt->child_end(); ++end) {
2005 Stmt *child = *end;
2006 start_off = SM.getFileOffset(child->getLocStart());
2007 if (start_off >= loc.end)
2008 break;
2011 return extract_scop(extract(StmtRange(start, end), false, false));
2014 /* Set the size of index "pos" of "array" to "size".
2015 * In particular, add a constraint of the form
2017 * i_pos < size
2019 * to array->extent and a constraint of the form
2021 * size >= 0
2023 * to array->context.
2025 * The domain of "size" is assumed to be zero-dimensional.
2027 static struct pet_array *update_size(struct pet_array *array, int pos,
2028 __isl_take isl_pw_aff *size)
2030 isl_set *valid;
2031 isl_set *univ;
2032 isl_set *bound;
2033 isl_space *dim;
2034 isl_aff *aff;
2035 isl_pw_aff *index;
2036 isl_id *id;
2038 if (!array)
2039 goto error;
2041 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2042 array->context = isl_set_intersect(array->context, valid);
2044 dim = isl_set_get_space(array->extent);
2045 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2046 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2047 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2048 index = isl_pw_aff_alloc(univ, aff);
2050 size = isl_pw_aff_add_dims(size, isl_dim_in,
2051 isl_set_dim(array->extent, isl_dim_set));
2052 id = isl_set_get_tuple_id(array->extent);
2053 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2054 bound = isl_pw_aff_lt_set(index, size);
2056 array->extent = isl_set_intersect(array->extent, bound);
2058 if (!array->context || !array->extent)
2059 return pet_array_free(array);
2061 return array;
2062 error:
2063 isl_pw_aff_free(size);
2064 return NULL;
2067 #ifdef HAVE_DECAYEDTYPE
2069 /* If "type" is a decayed type, then set *decayed to true and
2070 * return the original type.
2072 static const Type *undecay(const Type *type, bool *decayed)
2074 *decayed = isa<DecayedType>(type);
2075 if (*decayed)
2076 type = cast<DecayedType>(type)->getOriginalType().getTypePtr();
2077 return type;
2080 #else
2082 /* If "type" is a decayed type, then set *decayed to true and
2083 * return the original type.
2084 * Since this version of clang does not define a DecayedType,
2085 * we cannot obtain the original type even if it had been decayed and
2086 * we set *decayed to false.
2088 static const Type *undecay(const Type *type, bool *decayed)
2090 *decayed = false;
2091 return type;
2094 #endif
2096 /* Figure out the size of the array at position "pos" and all
2097 * subsequent positions from "type" and update the corresponding
2098 * argument of "expr" accordingly.
2100 * The initial type (when pos is zero) may be a pointer type decayed
2101 * from an array type, if this initial type is the type of a function
2102 * argument. This only happens if the original array type has
2103 * a constant size in the outer dimension as otherwise we get
2104 * a VariableArrayType. Try and obtain this original type (if available) and
2105 * take the outer array size into account if it was marked static.
2107 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2108 const Type *type, int pos)
2110 const ArrayType *atype;
2111 pet_expr *size;
2112 bool decayed = false;
2114 if (!expr)
2115 return NULL;
2117 if (pos == 0)
2118 type = undecay(type, &decayed);
2120 if (type->isPointerType()) {
2121 type = type->getPointeeType().getTypePtr();
2122 return set_upper_bounds(expr, type, pos + 1);
2124 if (!type->isArrayType())
2125 return expr;
2127 type = type->getCanonicalTypeInternal().getTypePtr();
2128 atype = cast<ArrayType>(type);
2130 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2131 type = atype->getElementType().getTypePtr();
2132 return set_upper_bounds(expr, type, pos + 1);
2135 if (type->isConstantArrayType()) {
2136 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2137 size = extract_expr(ca->getSize());
2138 expr = pet_expr_set_arg(expr, pos, size);
2139 } else if (type->isVariableArrayType()) {
2140 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2141 size = extract_expr(vla->getSizeExpr());
2142 expr = pet_expr_set_arg(expr, pos, size);
2145 type = atype->getElementType().getTypePtr();
2147 return set_upper_bounds(expr, type, pos + 1);
2150 /* Construct a pet_expr that holds the sizes of an array of the given type.
2151 * The returned expression is a call expression with as arguments
2152 * the sizes in each dimension. If we are unable to derive the size
2153 * in a given dimension, then the corresponding argument is set to infinity.
2154 * In fact, we initialize all arguments to infinity and then update
2155 * them if we are able to figure out the size.
2157 * The result is stored in the type_size cache so that we can reuse
2158 * it if this method gets called on the same type again later on.
2160 __isl_give pet_expr *PetScan::get_array_size(const Type *type)
2162 int depth;
2163 pet_expr *expr, *inf;
2165 if (type_size.find(type) != type_size.end())
2166 return pet_expr_copy(type_size[type]);
2168 depth = array_depth(type);
2169 inf = pet_expr_new_int(isl_val_infty(ctx));
2170 expr = pet_expr_new_call(ctx, "bounds", depth);
2171 for (int i = 0; i < depth; ++i)
2172 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2173 pet_expr_free(inf);
2175 expr = set_upper_bounds(expr, type, 0);
2176 type_size[type] = pet_expr_copy(expr);
2178 return expr;
2181 /* Does "expr" represent the "integer" infinity?
2183 static int is_infty(__isl_keep pet_expr *expr)
2185 isl_val *v;
2186 int res;
2188 if (pet_expr_get_type(expr) != pet_expr_int)
2189 return 0;
2190 v = pet_expr_int_get_val(expr);
2191 res = isl_val_is_infty(v);
2192 isl_val_free(v);
2194 return res;
2197 /* Figure out the dimensions of an array "array" based on its type
2198 * "type" and update "array" accordingly.
2200 * We first construct a pet_expr that holds the sizes of the array
2201 * in each dimension. The resulting expression may containing
2202 * infinity values for dimension where we are unable to derive
2203 * a size expression.
2205 * The arguments of the size expression that have a value different from
2206 * infinity are then converted to an affine expression
2207 * within the context "pc" and incorporated into the size of "array".
2208 * If we are unable to convert a size expression to an affine expression or
2209 * if the size is not a (symbolic) constant,
2210 * then we leave the corresponding size of "array" untouched.
2212 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2213 const Type *type, __isl_keep pet_context *pc)
2215 int n;
2216 pet_expr *expr;
2218 if (!array)
2219 return NULL;
2221 expr = get_array_size(type);
2223 n = pet_expr_get_n_arg(expr);
2224 for (int i = 0; i < n; ++i) {
2225 pet_expr *arg;
2226 isl_pw_aff *size;
2228 arg = pet_expr_get_arg(expr, i);
2229 if (!is_infty(arg)) {
2230 int dim;
2232 size = pet_expr_extract_affine(arg, pc);
2233 dim = isl_pw_aff_dim(size, isl_dim_in);
2234 if (!size)
2235 array = pet_array_free(array);
2236 else if (isl_pw_aff_involves_nan(size) ||
2237 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2238 isl_pw_aff_free(size);
2239 else {
2240 size = isl_pw_aff_drop_dims(size,
2241 isl_dim_in, i, dim);
2242 array = update_size(array, i, size);
2245 pet_expr_free(arg);
2247 pet_expr_free(expr);
2249 return array;
2252 /* Does "decl" have definition that we can keep track of in a pet_type?
2254 static bool has_printable_definition(RecordDecl *decl)
2256 if (!decl->getDeclName())
2257 return false;
2258 return decl->getLexicalDeclContext() == decl->getDeclContext();
2261 /* Construct and return a pet_array corresponding to the variable "decl".
2262 * In particular, initialize array->extent to
2264 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2266 * and then call set_upper_bounds to set the upper bounds on the indices
2267 * based on the type of the variable. The upper bounds are converted
2268 * to affine expressions within the context "pc".
2270 * If the base type is that of a record with a top-level definition and
2271 * if "types" is not null, then the RecordDecl corresponding to the type
2272 * is added to "types".
2274 * If the base type is that of a record with no top-level definition,
2275 * then we replace it by "<subfield>".
2277 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
2278 lex_recorddecl_set *types, __isl_keep pet_context *pc)
2280 struct pet_array *array;
2281 QualType qt = get_array_type(decl);
2282 const Type *type = qt.getTypePtr();
2283 int depth = array_depth(type);
2284 QualType base = pet_clang_base_type(qt);
2285 string name;
2286 isl_id *id;
2287 isl_space *dim;
2289 array = isl_calloc_type(ctx, struct pet_array);
2290 if (!array)
2291 return NULL;
2293 id = create_decl_id(ctx, decl);
2294 dim = isl_space_set_alloc(ctx, 0, depth);
2295 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
2297 array->extent = isl_set_nat_universe(dim);
2299 dim = isl_space_params_alloc(ctx, 0);
2300 array->context = isl_set_universe(dim);
2302 array = set_upper_bounds(array, type, pc);
2303 if (!array)
2304 return NULL;
2306 name = base.getAsString();
2308 if (types && base->isRecordType()) {
2309 RecordDecl *decl = pet_clang_record_decl(base);
2310 if (has_printable_definition(decl))
2311 types->insert(decl);
2312 else
2313 name = "<subfield>";
2316 array->element_type = strdup(name.c_str());
2317 array->element_is_record = base->isRecordType();
2318 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
2320 return array;
2323 /* Construct and return a pet_array corresponding to the sequence
2324 * of declarations "decls".
2325 * The upper bounds of the array are converted to affine expressions
2326 * within the context "pc".
2327 * If the sequence contains a single declaration, then it corresponds
2328 * to a simple array access. Otherwise, it corresponds to a member access,
2329 * with the declaration for the substructure following that of the containing
2330 * structure in the sequence of declarations.
2331 * We start with the outermost substructure and then combine it with
2332 * information from the inner structures.
2334 * Additionally, keep track of all required types in "types".
2336 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
2337 vector<ValueDecl *> decls, lex_recorddecl_set *types,
2338 __isl_keep pet_context *pc)
2340 struct pet_array *array;
2341 vector<ValueDecl *>::iterator it;
2343 it = decls.begin();
2345 array = extract_array(ctx, *it, types, pc);
2347 for (++it; it != decls.end(); ++it) {
2348 struct pet_array *parent;
2349 const char *base_name, *field_name;
2350 char *product_name;
2352 parent = array;
2353 array = extract_array(ctx, *it, types, pc);
2354 if (!array)
2355 return pet_array_free(parent);
2357 base_name = isl_set_get_tuple_name(parent->extent);
2358 field_name = isl_set_get_tuple_name(array->extent);
2359 product_name = pet_array_member_access_name(ctx,
2360 base_name, field_name);
2362 array->extent = isl_set_product(isl_set_copy(parent->extent),
2363 array->extent);
2364 if (product_name)
2365 array->extent = isl_set_set_tuple_name(array->extent,
2366 product_name);
2367 array->context = isl_set_intersect(array->context,
2368 isl_set_copy(parent->context));
2370 pet_array_free(parent);
2371 free(product_name);
2373 if (!array->extent || !array->context || !product_name)
2374 return pet_array_free(array);
2377 return array;
2380 /* Add a pet_type corresponding to "decl" to "scop, provided
2381 * it is a member of "types" and it has not been added before
2382 * (i.e., it is not a member of "types_done".
2384 * Since we want the user to be able to print the types
2385 * in the order in which they appear in the scop, we need to
2386 * make sure that types of fields in a structure appear before
2387 * that structure. We therefore call ourselves recursively
2388 * on the types of all record subfields.
2390 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2391 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
2392 lex_recorddecl_set &types_done)
2394 string s;
2395 llvm::raw_string_ostream S(s);
2396 RecordDecl::field_iterator it;
2398 if (types.find(decl) == types.end())
2399 return scop;
2400 if (types_done.find(decl) != types_done.end())
2401 return scop;
2403 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
2404 RecordDecl *record;
2405 QualType type = it->getType();
2407 if (!type->isRecordType())
2408 continue;
2409 record = pet_clang_record_decl(type);
2410 scop = add_type(ctx, scop, record, PP, types, types_done);
2413 if (strlen(decl->getName().str().c_str()) == 0)
2414 return scop;
2416 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2417 S.str();
2419 scop->types[scop->n_type] = pet_type_alloc(ctx,
2420 decl->getName().str().c_str(), s.c_str());
2421 if (!scop->types[scop->n_type])
2422 return pet_scop_free(scop);
2424 types_done.insert(decl);
2426 scop->n_type++;
2428 return scop;
2431 /* Construct a list of pet_arrays, one for each array (or scalar)
2432 * accessed inside "scop", add this list to "scop" and return the result.
2433 * The upper bounds of the arrays are converted to affine expressions
2434 * within the context "pc".
2436 * The context of "scop" is updated with the intersection of
2437 * the contexts of all arrays, i.e., constraints on the parameters
2438 * that ensure that the arrays have a valid (non-negative) size.
2440 * If the any of the extracted arrays refers to a member access,
2441 * then also add the required types to "scop".
2443 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
2444 __isl_keep pet_context *pc)
2446 int i;
2447 array_desc_set arrays;
2448 array_desc_set::iterator it;
2449 lex_recorddecl_set types;
2450 lex_recorddecl_set types_done;
2451 lex_recorddecl_set::iterator types_it;
2452 int n_array;
2453 struct pet_array **scop_arrays;
2455 if (!scop)
2456 return NULL;
2458 pet_scop_collect_arrays(scop, arrays);
2459 if (arrays.size() == 0)
2460 return scop;
2462 n_array = scop->n_array;
2464 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2465 n_array + arrays.size());
2466 if (!scop_arrays)
2467 goto error;
2468 scop->arrays = scop_arrays;
2470 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
2471 struct pet_array *array;
2472 array = extract_array(ctx, *it, &types, pc);
2473 scop->arrays[n_array + i] = array;
2474 if (!scop->arrays[n_array + i])
2475 goto error;
2476 scop->n_array++;
2477 scop->context = isl_set_intersect(scop->context,
2478 isl_set_copy(array->context));
2479 if (!scop->context)
2480 goto error;
2483 if (types.size() == 0)
2484 return scop;
2486 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
2487 if (!scop->types)
2488 goto error;
2490 for (types_it = types.begin(); types_it != types.end(); ++types_it)
2491 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
2493 return scop;
2494 error:
2495 pet_scop_free(scop);
2496 return NULL;
2499 /* Bound all parameters in scop->context to the possible values
2500 * of the corresponding C variable.
2502 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
2504 int n;
2506 if (!scop)
2507 return NULL;
2509 n = isl_set_dim(scop->context, isl_dim_param);
2510 for (int i = 0; i < n; ++i) {
2511 isl_id *id;
2512 ValueDecl *decl;
2514 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
2515 if (pet_nested_in_id(id)) {
2516 isl_id_free(id);
2517 isl_die(isl_set_get_ctx(scop->context),
2518 isl_error_internal,
2519 "unresolved nested parameter", goto error);
2521 decl = (ValueDecl *) isl_id_get_user(id);
2522 isl_id_free(id);
2524 scop->context = set_parameter_bounds(scop->context, i, decl);
2526 if (!scop->context)
2527 goto error;
2530 return scop;
2531 error:
2532 pet_scop_free(scop);
2533 return NULL;
2536 /* Construct a pet_scop from the given function.
2538 * If the scop was delimited by scop and endscop pragmas, then we override
2539 * the file offsets by those derived from the pragmas.
2541 struct pet_scop *PetScan::scan(FunctionDecl *fd)
2543 pet_scop *scop;
2544 Stmt *stmt;
2546 stmt = fd->getBody();
2548 if (options->autodetect) {
2549 set_current_stmt(stmt);
2550 scop = extract_scop(extract(stmt, true));
2551 } else {
2552 current_line = loc.start_line;
2553 scop = scan(stmt);
2554 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
2556 scop = add_parameter_bounds(scop);
2557 scop = pet_scop_gist(scop, value_bounds);
2559 return scop;
2562 /* Update this->last_line and this->current_line based on the fact
2563 * that we are about to consider "stmt".
2565 void PetScan::set_current_stmt(Stmt *stmt)
2567 SourceLocation loc = stmt->getLocStart();
2568 SourceManager &SM = PP.getSourceManager();
2570 last_line = current_line;
2571 current_line = SM.getExpansionLineNumber(loc);
2574 /* Is the current statement marked by an independent pragma?
2575 * That is, is there an independent pragma on a line between
2576 * the line of the current statement and the line of the previous statement.
2577 * The search is not implemented very efficiently. We currently
2578 * assume that there are only a few independent pragmas, if any.
2580 bool PetScan::is_current_stmt_marked_independent()
2582 for (int i = 0; i < independent.size(); ++i) {
2583 unsigned line = independent[i].line;
2585 if (last_line < line && line < current_line)
2586 return true;
2589 return false;