2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2015 Ecole Normale Superieure. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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
42 #include <llvm/Support/raw_ostream.h>
43 #include <clang/AST/ASTContext.h>
44 #include <clang/AST/ASTDiagnostic.h>
45 #include <clang/AST/Attr.h>
46 #include <clang/AST/Expr.h>
47 #include <clang/AST/RecursiveASTVisitor.h>
50 #include <isl/space.h>
53 #include <isl/union_set.h>
66 #include "scop_plus.h"
67 #include "substituter.h"
69 #include "tree2scop.h"
72 using namespace clang
;
74 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
84 return pet_op_post_inc
;
86 return pet_op_post_dec
;
88 return pet_op_pre_inc
;
90 return pet_op_pre_dec
;
96 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
100 return pet_op_add_assign
;
102 return pet_op_sub_assign
;
104 return pet_op_mul_assign
;
106 return pet_op_div_assign
;
108 return pet_op_assign
;
150 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
151 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
153 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
154 SourceLocation(), var
, false, var
->getInnerLocStart(),
155 var
->getType(), VK_LValue
);
157 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
158 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
160 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
161 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
165 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
167 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
168 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
172 #ifdef GETTYPEINFORETURNSTYPEINFO
174 static int size_in_bytes(ASTContext
&context
, QualType type
)
176 return context
.getTypeInfo(type
).Width
/ 8;
181 static int size_in_bytes(ASTContext
&context
, QualType type
)
183 return context
.getTypeInfo(type
).first
/ 8;
188 /* Check if the element type corresponding to the given array type
189 * has a const qualifier.
191 static bool const_base(QualType qt
)
193 const Type
*type
= qt
.getTypePtr();
195 if (type
->isPointerType())
196 return const_base(type
->getPointeeType());
197 if (type
->isArrayType()) {
198 const ArrayType
*atype
;
199 type
= type
->getCanonicalTypeInternal().getTypePtr();
200 atype
= cast
<ArrayType
>(type
);
201 return const_base(atype
->getElementType());
204 return qt
.isConstQualified();
209 std::map
<const Type
*, pet_expr
*>::iterator it
;
210 std::map
<FunctionDecl
*, pet_function_summary
*>::iterator it_s
;
212 for (it
= type_size
.begin(); it
!= type_size
.end(); ++it
)
213 pet_expr_free(it
->second
);
214 for (it_s
= summary_cache
.begin(); it_s
!= summary_cache
.end(); ++it_s
)
215 pet_function_summary_free(it_s
->second
);
217 isl_union_map_free(value_bounds
);
220 /* Report a diagnostic, unless autodetect is set.
222 void PetScan::report(Stmt
*stmt
, unsigned id
)
224 if (options
->autodetect
)
227 SourceLocation loc
= stmt
->getLocStart();
228 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
229 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
232 /* Called if we found something we (currently) cannot handle.
233 * We'll provide more informative warnings later.
235 * We only actually complain if autodetect is false.
237 void PetScan::unsupported(Stmt
*stmt
)
239 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
240 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
245 /* Report an unsupported unary operator, unless autodetect is set.
247 void PetScan::report_unsupported_unary_operator(Stmt
*stmt
)
249 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
250 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
251 "this type of unary operator is not supported");
255 /* Report an unsupported statement type, unless autodetect is set.
257 void PetScan::report_unsupported_statement_type(Stmt
*stmt
)
259 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
260 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
261 "this type of statement is not supported");
265 /* Report a missing prototype, unless autodetect is set.
267 void PetScan::report_prototype_required(Stmt
*stmt
)
269 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
270 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
271 "prototype required");
275 /* Report a missing increment, unless autodetect is set.
277 void PetScan::report_missing_increment(Stmt
*stmt
)
279 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
280 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
281 "missing increment");
285 /* Report a missing summary function, unless autodetect is set.
287 void PetScan::report_missing_summary_function(Stmt
*stmt
)
289 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
290 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
291 "missing summary function");
295 /* Report a missing summary function body, unless autodetect is set.
297 void PetScan::report_missing_summary_function_body(Stmt
*stmt
)
299 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
300 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
301 "missing summary function body");
305 /* Report an unsupported argument in a call to an inlined function,
306 * unless autodetect is set.
308 void PetScan::report_unsupported_inline_function_argument(Stmt
*stmt
)
310 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
311 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
312 "unsupported inline function call argument");
316 /* Extract an integer from "val", which is assumed to be non-negative.
318 static __isl_give isl_val
*extract_unsigned(isl_ctx
*ctx
,
319 const llvm::APInt
&val
)
322 const uint64_t *data
;
324 data
= val
.getRawData();
325 n
= val
.getNumWords();
326 return isl_val_int_from_chunks(ctx
, n
, sizeof(uint64_t), data
);
329 /* Extract an integer from "val". If "is_signed" is set, then "val"
330 * is signed. Otherwise it it unsigned.
332 static __isl_give isl_val
*extract_int(isl_ctx
*ctx
, bool is_signed
,
335 int is_negative
= is_signed
&& val
.isNegative();
341 v
= extract_unsigned(ctx
, val
);
348 /* Extract an integer from "expr".
350 __isl_give isl_val
*PetScan::extract_int(isl_ctx
*ctx
, IntegerLiteral
*expr
)
352 const Type
*type
= expr
->getType().getTypePtr();
353 bool is_signed
= type
->hasSignedIntegerRepresentation();
355 return ::extract_int(ctx
, is_signed
, expr
->getValue());
358 /* Extract an integer from "expr".
359 * Return NULL if "expr" does not (obviously) represent an integer.
361 __isl_give isl_val
*PetScan::extract_int(clang::ParenExpr
*expr
)
363 return extract_int(expr
->getSubExpr());
366 /* Extract an integer from "expr".
367 * Return NULL if "expr" does not (obviously) represent an integer.
369 __isl_give isl_val
*PetScan::extract_int(clang::Expr
*expr
)
371 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
372 return extract_int(ctx
, cast
<IntegerLiteral
>(expr
));
373 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
374 return extract_int(cast
<ParenExpr
>(expr
));
380 /* Extract a pet_expr from the APInt "val", which is assumed
381 * to be non-negative.
383 __isl_give pet_expr
*PetScan::extract_expr(const llvm::APInt
&val
)
385 return pet_expr_new_int(extract_unsigned(ctx
, val
));
388 /* Return the number of bits needed to represent the type of "decl",
389 * if it is an integer type. Otherwise return 0.
390 * If qt is signed then return the opposite of the number of bits.
392 static int get_type_size(ValueDecl
*decl
)
394 return pet_clang_get_type_size(decl
->getType(), decl
->getASTContext());
397 /* Bound parameter "pos" of "set" to the possible values of "decl".
399 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
400 unsigned pos
, ValueDecl
*decl
)
406 ctx
= isl_set_get_ctx(set
);
407 type_size
= get_type_size(decl
);
409 isl_die(ctx
, isl_error_invalid
, "not an integer type",
410 return isl_set_free(set
));
412 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
413 bound
= isl_val_int_from_ui(ctx
, type_size
);
414 bound
= isl_val_2exp(bound
);
415 bound
= isl_val_sub_ui(bound
, 1);
416 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
, bound
);
418 bound
= isl_val_int_from_ui(ctx
, -type_size
- 1);
419 bound
= isl_val_2exp(bound
);
420 bound
= isl_val_sub_ui(bound
, 1);
421 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
,
422 isl_val_copy(bound
));
423 bound
= isl_val_neg(bound
);
424 bound
= isl_val_sub_ui(bound
, 1);
425 set
= isl_set_lower_bound_val(set
, isl_dim_param
, pos
, bound
);
431 __isl_give pet_expr
*PetScan::extract_index_expr(ImplicitCastExpr
*expr
)
433 return extract_index_expr(expr
->getSubExpr());
436 /* Return the depth of an array of the given type.
438 static int array_depth(const Type
*type
)
440 if (type
->isPointerType())
441 return 1 + array_depth(type
->getPointeeType().getTypePtr());
442 if (type
->isArrayType()) {
443 const ArrayType
*atype
;
444 type
= type
->getCanonicalTypeInternal().getTypePtr();
445 atype
= cast
<ArrayType
>(type
);
446 return 1 + array_depth(atype
->getElementType().getTypePtr());
451 /* Return the depth of the array accessed by the index expression "index".
452 * If "index" is an affine expression, i.e., if it does not access
453 * any array, then return 1.
454 * If "index" represent a member access, i.e., if its range is a wrapped
455 * relation, then return the sum of the depth of the array of structures
456 * and that of the member inside the structure.
458 static int extract_depth(__isl_keep isl_multi_pw_aff
*index
)
466 if (isl_multi_pw_aff_range_is_wrapping(index
)) {
467 int domain_depth
, range_depth
;
468 isl_multi_pw_aff
*domain
, *range
;
470 domain
= isl_multi_pw_aff_copy(index
);
471 domain
= isl_multi_pw_aff_range_factor_domain(domain
);
472 domain_depth
= extract_depth(domain
);
473 isl_multi_pw_aff_free(domain
);
474 range
= isl_multi_pw_aff_copy(index
);
475 range
= isl_multi_pw_aff_range_factor_range(range
);
476 range_depth
= extract_depth(range
);
477 isl_multi_pw_aff_free(range
);
479 return domain_depth
+ range_depth
;
482 if (!isl_multi_pw_aff_has_tuple_id(index
, isl_dim_out
))
485 id
= isl_multi_pw_aff_get_tuple_id(index
, isl_dim_out
);
488 decl
= pet_id_get_decl(id
);
491 return array_depth(decl
->getType().getTypePtr());
494 /* Return the depth of the array accessed by the access expression "expr".
496 static int extract_depth(__isl_keep pet_expr
*expr
)
498 isl_multi_pw_aff
*index
;
501 index
= pet_expr_access_get_index(expr
);
502 depth
= extract_depth(index
);
503 isl_multi_pw_aff_free(index
);
508 /* Construct a pet_expr representing an index expression for an access
509 * to the variable referenced by "expr".
511 * If "expr" references an enum constant, then return an integer expression
512 * instead, representing the value of the enum constant.
514 __isl_give pet_expr
*PetScan::extract_index_expr(DeclRefExpr
*expr
)
516 return extract_index_expr(expr
->getDecl());
519 /* Construct a pet_expr representing an index expression for an access
520 * to the variable "decl".
522 * If "decl" is an enum constant, then we return an integer expression
523 * instead, representing the value of the enum constant.
525 __isl_give pet_expr
*PetScan::extract_index_expr(ValueDecl
*decl
)
529 if (isa
<EnumConstantDecl
>(decl
))
530 return extract_expr(cast
<EnumConstantDecl
>(decl
));
532 id
= pet_id_from_decl(ctx
, decl
);
533 return pet_id_create_index_expr(id
);
536 /* Construct a pet_expr representing the index expression "expr"
537 * Return NULL on error.
539 * If "expr" is a reference to an enum constant, then return
540 * an integer expression instead, representing the value of the enum constant.
542 __isl_give pet_expr
*PetScan::extract_index_expr(Expr
*expr
)
544 switch (expr
->getStmtClass()) {
545 case Stmt::ImplicitCastExprClass
:
546 return extract_index_expr(cast
<ImplicitCastExpr
>(expr
));
547 case Stmt::DeclRefExprClass
:
548 return extract_index_expr(cast
<DeclRefExpr
>(expr
));
549 case Stmt::ArraySubscriptExprClass
:
550 return extract_index_expr(cast
<ArraySubscriptExpr
>(expr
));
551 case Stmt::IntegerLiteralClass
:
552 return extract_expr(cast
<IntegerLiteral
>(expr
));
553 case Stmt::MemberExprClass
:
554 return extract_index_expr(cast
<MemberExpr
>(expr
));
561 /* Extract an index expression from the given array subscript expression.
563 * We first extract an index expression from the base.
564 * This will result in an index expression with a range that corresponds
565 * to the earlier indices.
566 * We then extract the current index and let
567 * pet_expr_access_subscript combine the two.
569 __isl_give pet_expr
*PetScan::extract_index_expr(ArraySubscriptExpr
*expr
)
571 Expr
*base
= expr
->getBase();
572 Expr
*idx
= expr
->getIdx();
576 base_expr
= extract_index_expr(base
);
577 index
= extract_expr(idx
);
579 base_expr
= pet_expr_access_subscript(base_expr
, index
);
584 /* Extract an index expression from a member expression.
586 * If the base access (to the structure containing the member)
591 * and the member is called "f", then the member access is of
596 * If the member access is to an anonymous struct, then simply return
600 * If the member access in the source code is of the form
604 * then it is treated as
608 __isl_give pet_expr
*PetScan::extract_index_expr(MemberExpr
*expr
)
610 Expr
*base
= expr
->getBase();
611 FieldDecl
*field
= cast
<FieldDecl
>(expr
->getMemberDecl());
612 pet_expr
*base_index
;
615 base_index
= extract_index_expr(base
);
617 if (expr
->isArrow()) {
618 pet_expr
*index
= pet_expr_new_int(isl_val_zero(ctx
));
619 base_index
= pet_expr_access_subscript(base_index
, index
);
622 if (field
->isAnonymousStructOrUnion())
625 id
= pet_id_from_decl(ctx
, field
);
627 return pet_expr_access_member(base_index
, id
);
630 /* Mark the given access pet_expr as a write.
632 static __isl_give pet_expr
*mark_write(__isl_take pet_expr
*access
)
634 access
= pet_expr_access_set_write(access
, 1);
635 access
= pet_expr_access_set_read(access
, 0);
640 /* Mark the given (read) access pet_expr as also possibly being written.
641 * That is, initialize the may write access relation from the may read relation
642 * and initialize the must write access relation to the empty relation.
644 static __isl_give pet_expr
*mark_may_write(__isl_take pet_expr
*expr
)
646 isl_union_map
*access
;
647 isl_union_map
*empty
;
649 access
= pet_expr_access_get_dependent_access(expr
,
650 pet_expr_access_may_read
);
651 empty
= isl_union_map_empty(isl_union_map_get_space(access
));
652 expr
= pet_expr_access_set_access(expr
, pet_expr_access_may_write
,
654 expr
= pet_expr_access_set_access(expr
, pet_expr_access_must_write
,
660 /* Construct a pet_expr representing a unary operator expression.
662 __isl_give pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
668 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
669 if (op
== pet_op_last
) {
670 report_unsupported_unary_operator(expr
);
674 arg
= extract_expr(expr
->getSubExpr());
676 if (expr
->isIncrementDecrementOp() &&
677 pet_expr_get_type(arg
) == pet_expr_access
) {
678 arg
= mark_write(arg
);
679 arg
= pet_expr_access_set_read(arg
, 1);
682 type_size
= pet_clang_get_type_size(expr
->getType(), ast_context
);
683 return pet_expr_new_unary(type_size
, op
, arg
);
686 /* Construct a pet_expr representing a binary operator expression.
688 * If the top level operator is an assignment and the LHS is an access,
689 * then we mark that access as a write. If the operator is a compound
690 * assignment, the access is marked as both a read and a write.
692 __isl_give pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
698 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
699 if (op
== pet_op_last
) {
704 lhs
= extract_expr(expr
->getLHS());
705 rhs
= extract_expr(expr
->getRHS());
707 if (expr
->isAssignmentOp() &&
708 pet_expr_get_type(lhs
) == pet_expr_access
) {
709 lhs
= mark_write(lhs
);
710 if (expr
->isCompoundAssignmentOp())
711 lhs
= pet_expr_access_set_read(lhs
, 1);
714 type_size
= pet_clang_get_type_size(expr
->getType(), ast_context
);
715 return pet_expr_new_binary(type_size
, op
, lhs
, rhs
);
718 /* Construct a pet_tree for a variable declaration and
719 * add the declaration to the list of declarations
720 * inside the current compound statement.
722 __isl_give pet_tree
*PetScan::extract(Decl
*decl
)
728 vd
= cast
<VarDecl
>(decl
);
729 declarations
.push_back(vd
);
731 lhs
= extract_access_expr(vd
);
732 lhs
= mark_write(lhs
);
734 tree
= pet_tree_new_decl(lhs
);
736 rhs
= extract_expr(vd
->getInit());
737 tree
= pet_tree_new_decl_init(lhs
, rhs
);
743 /* Construct a pet_tree for a variable declaration statement.
744 * If the declaration statement declares multiple variables,
745 * then return a group of pet_trees, one for each declared variable.
747 __isl_give pet_tree
*PetScan::extract(DeclStmt
*stmt
)
752 if (!stmt
->isSingleDecl()) {
753 const DeclGroup
&group
= stmt
->getDeclGroup().getDeclGroup();
755 tree
= pet_tree_new_block(ctx
, 0, n
);
757 for (int i
= 0; i
< n
; ++i
) {
761 tree_i
= extract(group
[i
]);
762 loc
= construct_pet_loc(group
[i
]->getSourceRange(),
764 tree_i
= pet_tree_set_loc(tree_i
, loc
);
765 tree
= pet_tree_block_add_child(tree
, tree_i
);
771 return extract(stmt
->getSingleDecl());
774 /* Construct a pet_expr representing a conditional operation.
776 __isl_give pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
778 pet_expr
*cond
, *lhs
, *rhs
;
781 cond
= extract_expr(expr
->getCond());
782 lhs
= extract_expr(expr
->getTrueExpr());
783 rhs
= extract_expr(expr
->getFalseExpr());
785 return pet_expr_new_ternary(cond
, lhs
, rhs
);
788 __isl_give pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
790 return extract_expr(expr
->getSubExpr());
793 /* Construct a pet_expr representing a floating point value.
795 * If the floating point literal does not appear in a macro,
796 * then we use the original representation in the source code
797 * as the string representation. Otherwise, we use the pretty
798 * printer to produce a string representation.
800 __isl_give pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
804 const LangOptions
&LO
= PP
.getLangOpts();
805 SourceLocation loc
= expr
->getLocation();
807 if (!loc
.isMacroID()) {
808 SourceManager
&SM
= PP
.getSourceManager();
809 unsigned len
= Lexer::MeasureTokenLength(loc
, SM
, LO
);
810 s
= string(SM
.getCharacterData(loc
), len
);
812 llvm::raw_string_ostream
S(s
);
813 expr
->printPretty(S
, 0, PrintingPolicy(LO
));
816 d
= expr
->getValueAsApproximateDouble();
817 return pet_expr_new_double(ctx
, d
, s
.c_str());
820 /* Convert the index expression "index" into an access pet_expr of type "qt".
822 __isl_give pet_expr
*PetScan::extract_access_expr(QualType qt
,
823 __isl_take pet_expr
*index
)
828 depth
= extract_depth(index
);
829 type_size
= pet_clang_get_type_size(qt
, ast_context
);
831 index
= pet_expr_set_type_size(index
, type_size
);
832 index
= pet_expr_access_set_depth(index
, depth
);
837 /* Extract an index expression from "expr" and then convert it into
838 * an access pet_expr.
840 * If "expr" is a reference to an enum constant, then return
841 * an integer expression instead, representing the value of the enum constant.
843 __isl_give pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
847 index
= extract_index_expr(expr
);
849 if (pet_expr_get_type(index
) == pet_expr_int
)
852 return extract_access_expr(expr
->getType(), index
);
855 /* Extract an index expression from "decl" and then convert it into
856 * an access pet_expr.
858 __isl_give pet_expr
*PetScan::extract_access_expr(ValueDecl
*decl
)
860 return extract_access_expr(decl
->getType(), extract_index_expr(decl
));
863 __isl_give pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
865 return extract_expr(expr
->getSubExpr());
868 /* Extract an assume statement from the argument "expr"
869 * of a __pencil_assume statement.
871 __isl_give pet_expr
*PetScan::extract_assume(Expr
*expr
)
873 return pet_expr_new_unary(0, pet_op_assume
, extract_expr(expr
));
876 /* If "expr" is an address-of operator, then return its argument.
877 * Otherwise, return NULL.
879 static Expr
*extract_addr_of_arg(Expr
*expr
)
883 if (expr
->getStmtClass() != Stmt::UnaryOperatorClass
)
885 op
= cast
<UnaryOperator
>(expr
);
886 if (op
->getOpcode() != UO_AddrOf
)
888 return op
->getSubExpr();
891 /* Construct a pet_expr corresponding to the function call argument "expr".
892 * The argument appears in position "pos" of a call to function "fd".
894 * If we are passing along a pointer to an array element
895 * or an entire row or even higher dimensional slice of an array,
896 * then the function being called may write into the array.
898 * We assume here that if the function is declared to take a pointer
899 * to a const type, then the function may only perform a read
900 * and that otherwise, it may either perform a read or a write (or both).
901 * We only perform this check if "detect_writes" is set.
903 __isl_give pet_expr
*PetScan::extract_argument(FunctionDecl
*fd
, int pos
,
904 Expr
*expr
, bool detect_writes
)
908 int is_addr
= 0, is_partial
= 0;
910 expr
= pet_clang_strip_casts(expr
);
911 arg
= extract_addr_of_arg(expr
);
916 res
= extract_expr(expr
);
919 if (array_depth(expr
->getType().getTypePtr()) > 0)
921 if (detect_writes
&& (is_addr
|| is_partial
) &&
922 pet_expr_get_type(res
) == pet_expr_access
) {
924 if (!fd
->hasPrototype()) {
925 report_prototype_required(expr
);
926 return pet_expr_free(res
);
928 parm
= fd
->getParamDecl(pos
);
929 if (!const_base(parm
->getType()))
930 res
= mark_may_write(res
);
934 res
= pet_expr_new_unary(0, pet_op_address_of
, res
);
938 /* Find the first FunctionDecl with the given name.
939 * "call" is the corresponding call expression and is only used
940 * for reporting errors.
942 * Return NULL on error.
944 FunctionDecl
*PetScan::find_decl_from_name(CallExpr
*call
, string name
)
946 TranslationUnitDecl
*tu
= ast_context
.getTranslationUnitDecl();
947 DeclContext::decl_iterator begin
= tu
->decls_begin();
948 DeclContext::decl_iterator end
= tu
->decls_end();
949 for (DeclContext::decl_iterator i
= begin
; i
!= end
; ++i
) {
950 FunctionDecl
*fd
= dyn_cast
<FunctionDecl
>(*i
);
953 if (fd
->getName().str().compare(name
) != 0)
957 report_missing_summary_function_body(call
);
960 report_missing_summary_function(call
);
964 /* Return the FunctionDecl for the summary function associated to the
965 * function called by "call".
967 * In particular, if the pencil option is set, then
968 * search for an annotate attribute formatted as
969 * "pencil_access(name)", where "name" is the name of the summary function.
971 * If no summary function was specified, then return the FunctionDecl
972 * that is actually being called.
974 * Return NULL on error.
976 FunctionDecl
*PetScan::get_summary_function(CallExpr
*call
)
978 FunctionDecl
*decl
= call
->getDirectCallee();
982 if (!options
->pencil
)
985 specific_attr_iterator
<AnnotateAttr
> begin
, end
, i
;
986 begin
= decl
->specific_attr_begin
<AnnotateAttr
>();
987 end
= decl
->specific_attr_end
<AnnotateAttr
>();
988 for (i
= begin
; i
!= end
; ++i
) {
989 string attr
= (*i
)->getAnnotation().str();
991 const char prefix
[] = "pencil_access(";
992 size_t start
= attr
.find(prefix
);
993 if (start
== string::npos
)
995 start
+= strlen(prefix
);
996 string name
= attr
.substr(start
, attr
.find(')') - start
);
998 return find_decl_from_name(call
, name
);
1004 /* Construct a pet_expr representing a function call.
1006 * In the special case of a "call" to __pencil_assume,
1007 * construct an assume expression instead.
1009 * In the case of a "call" to __pencil_kill, the arguments
1010 * are neither read nor written (only killed), so there
1011 * is no need to check for writes to these arguments.
1013 * __pencil_assume and __pencil_kill are only recognized
1014 * when the pencil option is set.
1016 __isl_give pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1018 pet_expr
*res
= NULL
;
1024 fd
= expr
->getDirectCallee();
1030 name
= fd
->getDeclName().getAsString();
1031 n_arg
= expr
->getNumArgs();
1033 if (options
->pencil
&& n_arg
== 1 && name
== "__pencil_assume")
1034 return extract_assume(expr
->getArg(0));
1035 is_kill
= options
->pencil
&& name
== "__pencil_kill";
1037 res
= pet_expr_new_call(ctx
, name
.c_str(), n_arg
);
1041 for (int i
= 0; i
< n_arg
; ++i
) {
1042 Expr
*arg
= expr
->getArg(i
);
1043 res
= pet_expr_set_arg(res
, i
,
1044 PetScan::extract_argument(fd
, i
, arg
, !is_kill
));
1047 fd
= get_summary_function(expr
);
1049 return pet_expr_free(res
);
1051 res
= set_summary(res
, fd
);
1056 /* Construct a pet_expr representing a (C style) cast.
1058 __isl_give pet_expr
*PetScan::extract_expr(CStyleCastExpr
*expr
)
1063 arg
= extract_expr(expr
->getSubExpr());
1067 type
= expr
->getTypeAsWritten();
1068 return pet_expr_new_cast(type
.getAsString().c_str(), arg
);
1071 /* Construct a pet_expr representing an integer.
1073 __isl_give pet_expr
*PetScan::extract_expr(IntegerLiteral
*expr
)
1075 return pet_expr_new_int(extract_int(expr
));
1078 /* Construct a pet_expr representing the integer enum constant "ecd".
1080 __isl_give pet_expr
*PetScan::extract_expr(EnumConstantDecl
*ecd
)
1083 const llvm::APSInt
&init
= ecd
->getInitVal();
1084 v
= ::extract_int(ctx
, init
.isSigned(), init
);
1085 return pet_expr_new_int(v
);
1088 /* Try and construct a pet_expr representing "expr".
1090 __isl_give pet_expr
*PetScan::extract_expr(Expr
*expr
)
1092 switch (expr
->getStmtClass()) {
1093 case Stmt::UnaryOperatorClass
:
1094 return extract_expr(cast
<UnaryOperator
>(expr
));
1095 case Stmt::CompoundAssignOperatorClass
:
1096 case Stmt::BinaryOperatorClass
:
1097 return extract_expr(cast
<BinaryOperator
>(expr
));
1098 case Stmt::ImplicitCastExprClass
:
1099 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1100 case Stmt::ArraySubscriptExprClass
:
1101 case Stmt::DeclRefExprClass
:
1102 case Stmt::MemberExprClass
:
1103 return extract_access_expr(expr
);
1104 case Stmt::IntegerLiteralClass
:
1105 return extract_expr(cast
<IntegerLiteral
>(expr
));
1106 case Stmt::FloatingLiteralClass
:
1107 return extract_expr(cast
<FloatingLiteral
>(expr
));
1108 case Stmt::ParenExprClass
:
1109 return extract_expr(cast
<ParenExpr
>(expr
));
1110 case Stmt::ConditionalOperatorClass
:
1111 return extract_expr(cast
<ConditionalOperator
>(expr
));
1112 case Stmt::CallExprClass
:
1113 return extract_expr(cast
<CallExpr
>(expr
));
1114 case Stmt::CStyleCastExprClass
:
1115 return extract_expr(cast
<CStyleCastExpr
>(expr
));
1122 /* Check if the given initialization statement is an assignment.
1123 * If so, return that assignment. Otherwise return NULL.
1125 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1127 BinaryOperator
*ass
;
1129 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1132 ass
= cast
<BinaryOperator
>(init
);
1133 if (ass
->getOpcode() != BO_Assign
)
1139 /* Check if the given initialization statement is a declaration
1140 * of a single variable.
1141 * If so, return that declaration. Otherwise return NULL.
1143 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1147 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1150 decl
= cast
<DeclStmt
>(init
);
1152 if (!decl
->isSingleDecl())
1155 return decl
->getSingleDecl();
1158 /* Given the assignment operator in the initialization of a for loop,
1159 * extract the induction variable, i.e., the (integer)variable being
1162 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1169 lhs
= init
->getLHS();
1170 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1175 ref
= cast
<DeclRefExpr
>(lhs
);
1176 decl
= ref
->getDecl();
1177 type
= decl
->getType().getTypePtr();
1179 if (!type
->isIntegerType()) {
1187 /* Given the initialization statement of a for loop and the single
1188 * declaration in this initialization statement,
1189 * extract the induction variable, i.e., the (integer) variable being
1192 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1196 vd
= cast
<VarDecl
>(decl
);
1198 const QualType type
= vd
->getType();
1199 if (!type
->isIntegerType()) {
1204 if (!vd
->getInit()) {
1212 /* Check that op is of the form iv++ or iv--.
1213 * Return a pet_expr representing "1" or "-1" accordingly.
1215 __isl_give pet_expr
*PetScan::extract_unary_increment(
1216 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1222 if (!op
->isIncrementDecrementOp()) {
1227 sub
= op
->getSubExpr();
1228 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1233 ref
= cast
<DeclRefExpr
>(sub
);
1234 if (ref
->getDecl() != iv
) {
1239 if (op
->isIncrementOp())
1240 v
= isl_val_one(ctx
);
1242 v
= isl_val_negone(ctx
);
1244 return pet_expr_new_int(v
);
1247 /* Check if op is of the form
1251 * and return the increment "expr - iv" as a pet_expr.
1253 __isl_give pet_expr
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1254 clang::ValueDecl
*iv
)
1259 pet_expr
*expr
, *expr_iv
;
1261 if (op
->getOpcode() != BO_Assign
) {
1267 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1272 ref
= cast
<DeclRefExpr
>(lhs
);
1273 if (ref
->getDecl() != iv
) {
1278 expr
= extract_expr(op
->getRHS());
1279 expr_iv
= extract_expr(lhs
);
1281 type_size
= pet_clang_get_type_size(iv
->getType(), ast_context
);
1282 return pet_expr_new_binary(type_size
, pet_op_sub
, expr
, expr_iv
);
1285 /* Check that op is of the form iv += cst or iv -= cst
1286 * and return a pet_expr corresponding to cst or -cst accordingly.
1288 __isl_give pet_expr
*PetScan::extract_compound_increment(
1289 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1295 BinaryOperatorKind opcode
;
1297 opcode
= op
->getOpcode();
1298 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1302 if (opcode
== BO_SubAssign
)
1306 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1311 ref
= cast
<DeclRefExpr
>(lhs
);
1312 if (ref
->getDecl() != iv
) {
1317 expr
= extract_expr(op
->getRHS());
1320 type_size
= pet_clang_get_type_size(op
->getType(), ast_context
);
1321 expr
= pet_expr_new_unary(type_size
, pet_op_minus
, expr
);
1327 /* Check that the increment of the given for loop increments
1328 * (or decrements) the induction variable "iv" and return
1329 * the increment as a pet_expr if successful.
1331 __isl_give pet_expr
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1334 Stmt
*inc
= stmt
->getInc();
1337 report_missing_increment(stmt
);
1341 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1342 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1343 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1344 return extract_compound_increment(
1345 cast
<CompoundAssignOperator
>(inc
), iv
);
1346 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1347 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1353 /* Construct a pet_tree for a while loop.
1355 * If we were only able to extract part of the body, then simply
1358 __isl_give pet_tree
*PetScan::extract(WhileStmt
*stmt
)
1363 tree
= extract(stmt
->getBody());
1366 pe_cond
= extract_expr(stmt
->getCond());
1367 tree
= pet_tree_new_while(pe_cond
, tree
);
1372 /* Construct a pet_tree for a for statement.
1373 * The for loop is required to be of one of the following forms
1375 * for (i = init; condition; ++i)
1376 * for (i = init; condition; --i)
1377 * for (i = init; condition; i += constant)
1378 * for (i = init; condition; i -= constant)
1380 * We extract a pet_tree for the body and then include it in a pet_tree
1381 * of type pet_tree_for.
1383 * As a special case, we also allow a for loop of the form
1387 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1389 * If we were only able to extract part of the body, then simply
1392 __isl_give pet_tree
*PetScan::extract_for(ForStmt
*stmt
)
1394 BinaryOperator
*ass
;
1400 struct pet_scop
*scop
;
1403 pet_expr
*pe_init
, *pe_inc
, *pe_iv
, *pe_cond
;
1405 independent
= is_current_stmt_marked_independent();
1407 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc()) {
1408 tree
= extract(stmt
->getBody());
1411 tree
= pet_tree_new_infinite_loop(tree
);
1415 init
= stmt
->getInit();
1420 if ((ass
= initialization_assignment(init
)) != NULL
) {
1421 iv
= extract_induction_variable(ass
);
1424 lhs
= ass
->getLHS();
1425 rhs
= ass
->getRHS();
1426 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
1427 VarDecl
*var
= extract_induction_variable(init
, decl
);
1431 rhs
= var
->getInit();
1432 lhs
= create_DeclRefExpr(var
);
1434 unsupported(stmt
->getInit());
1438 declared
= !initialization_assignment(stmt
->getInit());
1439 tree
= extract(stmt
->getBody());
1442 pe_iv
= extract_access_expr(iv
);
1443 pe_iv
= mark_write(pe_iv
);
1444 pe_init
= extract_expr(rhs
);
1445 if (!stmt
->getCond())
1446 pe_cond
= pet_expr_new_int(isl_val_one(ctx
));
1448 pe_cond
= extract_expr(stmt
->getCond());
1449 pe_inc
= extract_increment(stmt
, iv
);
1450 tree
= pet_tree_new_for(independent
, declared
, pe_iv
, pe_init
, pe_cond
,
1455 /* Store the names of the variables declared in decl_context
1456 * in the set declared_names. Make sure to only do this once by
1457 * setting declared_names_collected.
1459 void PetScan::collect_declared_names()
1461 DeclContext
*DC
= decl_context
;
1462 DeclContext::decl_iterator it
;
1464 if (declared_names_collected
)
1467 for (it
= DC
->decls_begin(); it
!= DC
->decls_end(); ++it
) {
1471 if (!isa
<NamedDecl
>(D
))
1473 named
= cast
<NamedDecl
>(D
);
1474 declared_names
.insert(named
->getName().str());
1477 declared_names_collected
= true;
1480 /* Add the names in "names" that are not also in this->declared_names
1481 * to this->used_names.
1482 * It is up to the caller to make sure that declared_names has been
1483 * populated, if needed.
1485 void PetScan::add_new_used_names(const std::set
<std::string
> &names
)
1487 std::set
<std::string
>::const_iterator it
;
1489 for (it
= names
.begin(); it
!= names
.end(); ++it
) {
1490 if (declared_names
.find(*it
) != declared_names
.end())
1492 used_names
.insert(*it
);
1496 /* Is the name "name" used in any declaration other than "decl"?
1498 * If the name was found to be in use before, the consider it to be in use.
1499 * Otherwise, check the DeclContext of the function containing the scop
1500 * as well as all ancestors of this DeclContext for declarations
1501 * other than "decl" that declare something called "name".
1503 bool PetScan::name_in_use(const string
&name
, Decl
*decl
)
1506 DeclContext::decl_iterator it
;
1508 if (used_names
.find(name
) != used_names
.end())
1511 for (DC
= decl_context
; DC
; DC
= DC
->getParent()) {
1512 for (it
= DC
->decls_begin(); it
!= DC
->decls_end(); ++it
) {
1518 if (!isa
<NamedDecl
>(D
))
1520 named
= cast
<NamedDecl
>(D
);
1521 if (named
->getName().str() == name
)
1529 /* Generate a new name based on "name" that is not in use.
1530 * Do so by adding a suffix _i, with i an integer.
1532 string
PetScan::generate_new_name(const string
&name
)
1537 std::ostringstream oss
;
1538 oss
<< name
<< "_" << n_rename
++;
1539 new_name
= oss
.str();
1540 } while (name_in_use(new_name
, NULL
));
1545 /* Try and construct a pet_tree corresponding to a compound statement.
1547 * "skip_declarations" is set if we should skip initial declarations
1548 * in the children of the compound statements.
1550 * Collect a new set of declarations for the current compound statement.
1551 * If any of the names in these declarations is also used by another
1552 * declaration reachable from the current function, then rename it
1553 * to a name that is not already in use.
1554 * In particular, keep track of the old and new names in a pet_substituter
1555 * and apply the substitutions to the pet_tree corresponding to the
1556 * compound statement.
1558 __isl_give pet_tree
*PetScan::extract(CompoundStmt
*stmt
,
1559 bool skip_declarations
)
1562 std::vector
<VarDecl
*> saved_declarations
;
1563 std::vector
<VarDecl
*>::iterator it
;
1564 pet_substituter substituter
;
1566 saved_declarations
= declarations
;
1567 declarations
.clear();
1568 tree
= extract(stmt
->children(), true, skip_declarations
);
1569 for (it
= declarations
.begin(); it
!= declarations
.end(); ++it
) {
1572 VarDecl
*decl
= *it
;
1573 string name
= decl
->getName().str();
1574 bool in_use
= name_in_use(name
, decl
);
1576 used_names
.insert(name
);
1580 name
= generate_new_name(name
);
1581 id
= pet_id_from_name_and_decl(ctx
, name
.c_str(), decl
);
1582 expr
= pet_id_create_index_expr(id
);
1583 expr
= extract_access_expr(decl
->getType(), expr
);
1584 id
= pet_id_from_decl(ctx
, decl
);
1585 substituter
.add_sub(id
, expr
);
1586 used_names
.insert(name
);
1588 tree
= substituter
.substitute(tree
);
1589 declarations
= saved_declarations
;
1594 /* Return the file offset of the expansion location of "Loc".
1596 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
1598 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
1601 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1603 /* Return a SourceLocation for the location after the first semicolon
1604 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1605 * call it and also skip trailing spaces and newline.
1607 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
1608 const LangOptions
&LO
)
1610 return Lexer::findLocationAfterToken(loc
, tok::semi
, SM
, LO
, true);
1615 /* Return a SourceLocation for the location after the first semicolon
1616 * after "loc". If Lexer::findLocationAfterToken is not available,
1617 * we look in the underlying character data for the first semicolon.
1619 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
1620 const LangOptions
&LO
)
1623 const char *s
= SM
.getCharacterData(loc
);
1625 semi
= strchr(s
, ';');
1627 return SourceLocation();
1628 return loc
.getFileLocWithOffset(semi
+ 1 - s
);
1633 /* If the token at "loc" is the first token on the line, then return
1634 * a location referring to the start of the line and set *indent
1635 * to the indentation of "loc"
1636 * Otherwise, return "loc" and set *indent to "".
1638 * This function is used to extend a scop to the start of the line
1639 * if the first token of the scop is also the first token on the line.
1641 * We look for the first token on the line. If its location is equal to "loc",
1642 * then the latter is the location of the first token on the line.
1644 static SourceLocation
move_to_start_of_line_if_first_token(SourceLocation loc
,
1645 SourceManager
&SM
, const LangOptions
&LO
, char **indent
)
1647 std::pair
<FileID
, unsigned> file_offset_pair
;
1648 llvm::StringRef file
;
1651 SourceLocation token_loc
, line_loc
;
1655 loc
= SM
.getExpansionLoc(loc
);
1656 col
= SM
.getExpansionColumnNumber(loc
);
1657 line_loc
= loc
.getLocWithOffset(1 - col
);
1658 file_offset_pair
= SM
.getDecomposedLoc(line_loc
);
1659 file
= SM
.getBufferData(file_offset_pair
.first
, NULL
);
1660 pos
= file
.data() + file_offset_pair
.second
;
1662 Lexer
lexer(SM
.getLocForStartOfFile(file_offset_pair
.first
), LO
,
1663 file
.begin(), pos
, file
.end());
1664 lexer
.LexFromRawLexer(tok
);
1665 token_loc
= tok
.getLocation();
1667 s
= SM
.getCharacterData(line_loc
);
1668 *indent
= strndup(s
, token_loc
== loc
? col
- 1 : 0);
1670 if (token_loc
== loc
)
1676 /* Construct a pet_loc corresponding to the region covered by "range".
1677 * If "skip_semi" is set, then we assume "range" is followed by
1678 * a semicolon and also include this semicolon.
1680 __isl_give pet_loc
*PetScan::construct_pet_loc(SourceRange range
,
1683 SourceLocation loc
= range
.getBegin();
1684 SourceManager
&SM
= PP
.getSourceManager();
1685 const LangOptions
&LO
= PP
.getLangOpts();
1686 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
1687 unsigned start
, end
;
1690 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
, &indent
);
1691 start
= getExpansionOffset(SM
, loc
);
1692 loc
= range
.getEnd();
1694 loc
= location_after_semi(loc
, SM
, LO
);
1696 loc
= PP
.getLocForEndOfToken(loc
);
1697 end
= getExpansionOffset(SM
, loc
);
1699 return pet_loc_alloc(ctx
, start
, end
, line
, indent
);
1702 /* Convert a top-level pet_expr to an expression pet_tree.
1704 __isl_give pet_tree
*PetScan::extract(__isl_take pet_expr
*expr
,
1705 SourceRange range
, bool skip_semi
)
1710 tree
= pet_tree_new_expr(expr
);
1711 loc
= construct_pet_loc(range
, skip_semi
);
1712 tree
= pet_tree_set_loc(tree
, loc
);
1717 /* Construct a pet_tree for an if statement.
1719 __isl_give pet_tree
*PetScan::extract(IfStmt
*stmt
)
1722 pet_tree
*tree
, *tree_else
;
1723 struct pet_scop
*scop
;
1726 pe_cond
= extract_expr(stmt
->getCond());
1727 tree
= extract(stmt
->getThen());
1728 if (stmt
->getElse()) {
1729 tree_else
= extract(stmt
->getElse());
1730 if (options
->autodetect
) {
1731 if (tree
&& !tree_else
) {
1733 pet_expr_free(pe_cond
);
1736 if (!tree
&& tree_else
) {
1738 pet_expr_free(pe_cond
);
1742 tree
= pet_tree_new_if_else(pe_cond
, tree
, tree_else
);
1744 tree
= pet_tree_new_if(pe_cond
, tree
);
1748 /* Try and construct a pet_tree for a label statement.
1750 __isl_give pet_tree
*PetScan::extract(LabelStmt
*stmt
)
1755 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
1757 tree
= extract(stmt
->getSubStmt());
1758 tree
= pet_tree_set_label(tree
, label
);
1762 /* Update the location of "tree" to include the source range of "stmt".
1764 * Actually, we create a new location based on the source range of "stmt" and
1765 * then extend this new location to include the region of the original location.
1766 * This ensures that the line number of the final location refers to "stmt".
1768 __isl_give pet_tree
*PetScan::update_loc(__isl_take pet_tree
*tree
, Stmt
*stmt
)
1770 pet_loc
*loc
, *tree_loc
;
1772 tree_loc
= pet_tree_get_loc(tree
);
1773 loc
= construct_pet_loc(stmt
->getSourceRange(), false);
1774 loc
= pet_loc_update_start_end_from_loc(loc
, tree_loc
);
1775 pet_loc_free(tree_loc
);
1777 tree
= pet_tree_set_loc(tree
, loc
);
1781 /* Is "expr" of a type that can be converted to an access expression?
1783 static bool is_access_expr_type(Expr
*expr
)
1785 switch (expr
->getStmtClass()) {
1786 case Stmt::ArraySubscriptExprClass
:
1787 case Stmt::DeclRefExprClass
:
1788 case Stmt::MemberExprClass
:
1795 /* Tell the pet_inliner "inliner" about the formal arguments
1796 * in "fd" and the corresponding actual arguments in "call".
1797 * Return 0 if this was successful and -1 otherwise.
1799 * Any pointer argument is treated as an array.
1800 * The other arguments are treated as scalars.
1802 * In case of scalars, there is no restriction on the actual argument.
1803 * This actual argument is assigned to a variable with a name
1804 * that is derived from the name of the corresponding formal argument,
1805 * but made not to conflict with any variable names that are
1808 * In case of arrays, the actual argument needs to be an expression
1809 * of a type that can be converted to an access expression or the address
1810 * of such an expression, ignoring implicit and redundant casts.
1812 int PetScan::set_inliner_arguments(pet_inliner
&inliner
, CallExpr
*call
,
1817 n
= fd
->getNumParams();
1818 for (int i
= 0; i
< n
; ++i
) {
1819 ParmVarDecl
*parm
= fd
->getParamDecl(i
);
1820 QualType type
= parm
->getType();
1825 arg
= call
->getArg(i
);
1826 if (array_depth(type
.getTypePtr()) == 0) {
1827 string name
= parm
->getName().str();
1828 if (name_in_use(name
, NULL
))
1829 name
= generate_new_name(name
);
1830 inliner
.add_scalar_arg(parm
, name
, extract_expr(arg
));
1833 arg
= pet_clang_strip_casts(arg
);
1834 sub
= extract_addr_of_arg(arg
);
1837 arg
= pet_clang_strip_casts(sub
);
1839 if (!is_access_expr_type(arg
)) {
1840 report_unsupported_inline_function_argument(arg
);
1843 expr
= extract_access_expr(arg
);
1846 inliner
.add_array_arg(parm
, expr
, is_addr
);
1852 /* Try and construct a pet_tree from the body of "fd" using the actual
1853 * arguments in "call" in place of the formal arguments.
1854 * "fd" is assumed to point to the declaration with a function body.
1855 * In particular, construct a block that consists of assignments
1856 * of (parts of) the actual arguments to temporary variables
1857 * followed by the inlined function body with the formal arguments
1858 * replaced by (expressions containing) these temporary variables.
1860 * The actual inlining is taken care of by the pet_inliner function.
1861 * This function merely calls set_inliner_arguments to tell
1862 * the pet_inliner about the actual arguments, extracts a pet_tree
1863 * from the body of the called function and then passes this pet_tree
1864 * to the pet_inliner.
1866 * During the extraction of the function body, all variables names
1867 * that are declared in the calling function as well all variable
1868 * names that are known to be in use are considered to be in use
1869 * in the called function to ensure that there is no naming conflict.
1870 * Similarly, the additional names that are in use in the called function
1871 * are considered to be in use in the calling function as well.
1873 * The location of the pet_tree is reset to the call site to ensure
1874 * that the extent of the scop does not include the body of the called
1877 __isl_give pet_tree
*PetScan::extract_inlined_call(CallExpr
*call
,
1880 int save_autodetect
;
1883 pet_inliner
inliner(ctx
, n_arg
, ast_context
);
1885 if (set_inliner_arguments(inliner
, call
, fd
) < 0)
1888 save_autodetect
= options
->autodetect
;
1889 options
->autodetect
= 0;
1890 PetScan
body_scan(PP
, ast_context
, fd
, loc
, options
,
1891 isl_union_map_copy(value_bounds
), independent
);
1892 collect_declared_names();
1893 body_scan
.add_new_used_names(declared_names
);
1894 body_scan
.add_new_used_names(used_names
);
1895 tree
= body_scan
.extract(fd
->getBody(), false);
1896 add_new_used_names(body_scan
.used_names
);
1897 options
->autodetect
= save_autodetect
;
1899 tree_loc
= construct_pet_loc(call
->getSourceRange(), true);
1900 tree
= pet_tree_set_loc(tree
, tree_loc
);
1902 return inliner
.inline_tree(tree
);
1905 /* Try and construct a pet_tree corresponding
1906 * to the expression statement "stmt".
1908 * If the outer expression is a function call and if the corresponding
1909 * function body is marked "inline", then return a pet_tree
1910 * corresponding to the inlined function.
1912 __isl_give pet_tree
*PetScan::extract_expr_stmt(Stmt
*stmt
)
1916 if (stmt
->getStmtClass() == Stmt::CallExprClass
) {
1917 CallExpr
*call
= cast
<CallExpr
>(stmt
);
1918 FunctionDecl
*fd
= call
->getDirectCallee();
1919 fd
= pet_clang_find_function_decl_with_body(fd
);
1920 if (fd
&& fd
->isInlineSpecified())
1921 return extract_inlined_call(call
, fd
);
1924 expr
= extract_expr(cast
<Expr
>(stmt
));
1925 return extract(expr
, stmt
->getSourceRange(), true);
1928 /* Try and construct a pet_tree corresponding to "stmt".
1930 * If "stmt" is a compound statement, then "skip_declarations"
1931 * indicates whether we should skip initial declarations in the
1932 * compound statement.
1934 * If the constructed pet_tree is not a (possibly) partial representation
1935 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1936 * In particular, if skip_declarations is set, then we may have skipped
1937 * declarations inside "stmt" and so the pet_scop may not represent
1938 * the entire "stmt".
1939 * Note that this function may be called with "stmt" referring to the entire
1940 * body of the function, including the outer braces. In such cases,
1941 * skip_declarations will be set and the braces will not be taken into
1942 * account in tree->loc.
1944 __isl_give pet_tree
*PetScan::extract(Stmt
*stmt
, bool skip_declarations
)
1948 set_current_stmt(stmt
);
1950 if (isa
<Expr
>(stmt
))
1951 return extract_expr_stmt(cast
<Expr
>(stmt
));
1953 switch (stmt
->getStmtClass()) {
1954 case Stmt::WhileStmtClass
:
1955 tree
= extract(cast
<WhileStmt
>(stmt
));
1957 case Stmt::ForStmtClass
:
1958 tree
= extract_for(cast
<ForStmt
>(stmt
));
1960 case Stmt::IfStmtClass
:
1961 tree
= extract(cast
<IfStmt
>(stmt
));
1963 case Stmt::CompoundStmtClass
:
1964 tree
= extract(cast
<CompoundStmt
>(stmt
), skip_declarations
);
1966 case Stmt::LabelStmtClass
:
1967 tree
= extract(cast
<LabelStmt
>(stmt
));
1969 case Stmt::ContinueStmtClass
:
1970 tree
= pet_tree_new_continue(ctx
);
1972 case Stmt::BreakStmtClass
:
1973 tree
= pet_tree_new_break(ctx
);
1975 case Stmt::DeclStmtClass
:
1976 tree
= extract(cast
<DeclStmt
>(stmt
));
1979 report_unsupported_statement_type(stmt
);
1983 if (partial
|| skip_declarations
)
1986 return update_loc(tree
, stmt
);
1989 /* Given a sequence of statements "stmt_range" of which the first "n_decl"
1990 * are declarations and of which the remaining statements are represented
1991 * by "tree", try and extend "tree" to include the last sequence of
1992 * the initial declarations that can be completely extracted.
1994 * We start collecting the initial declarations and start over
1995 * whenever we come across a declaration that we cannot extract.
1996 * If we have been able to extract any declarations, then we
1997 * copy over the contents of "tree" at the end of the declarations.
1998 * Otherwise, we simply return the original "tree".
2000 __isl_give pet_tree
*PetScan::insert_initial_declarations(
2001 __isl_take pet_tree
*tree
, int n_decl
, StmtRange stmt_range
)
2009 n_stmt
= pet_tree_block_n_child(tree
);
2010 is_block
= pet_tree_block_get_block(tree
);
2011 res
= pet_tree_new_block(ctx
, is_block
, n_decl
+ n_stmt
);
2013 for (i
= stmt_range
.first
; n_decl
; ++i
, --n_decl
) {
2017 tree_i
= extract(child
);
2018 if (tree_i
&& !partial
) {
2019 res
= pet_tree_block_add_child(res
, tree_i
);
2022 pet_tree_free(tree_i
);
2024 if (pet_tree_block_n_child(res
) == 0)
2027 res
= pet_tree_new_block(ctx
, is_block
, n_decl
+ n_stmt
);
2030 if (pet_tree_block_n_child(res
) == 0) {
2035 for (j
= 0; j
< n_stmt
; ++j
) {
2038 tree_i
= pet_tree_block_get_child(tree
, j
);
2039 res
= pet_tree_block_add_child(res
, tree_i
);
2041 pet_tree_free(tree
);
2046 /* Try and construct a pet_tree corresponding to (part of)
2047 * a sequence of statements.
2049 * "block" is set if the sequence represents the children of
2050 * a compound statement.
2051 * "skip_declarations" is set if we should skip initial declarations
2052 * in the sequence of statements.
2054 * If autodetect is set, then we allow the extraction of only a subrange
2055 * of the sequence of statements. However, if there is at least one
2056 * kill and there is some subsequent statement for which we could not
2057 * construct a tree, then turn off the "block" property of the tree
2058 * such that no extra kill will be introduced at the end of the (partial)
2059 * block. If, on the other hand, the final range contains
2060 * no statements, then we discard the entire range.
2062 * If the entire range was extracted, apart from some initial declarations,
2063 * then we try and extend the range with the latest of those initial
2066 __isl_give pet_tree
*PetScan::extract(StmtRange stmt_range
, bool block
,
2067 bool skip_declarations
)
2071 bool has_kills
= false;
2072 bool partial_range
= false;
2075 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
)
2078 tree
= pet_tree_new_block(ctx
, block
, j
);
2081 i
= stmt_range
.first
;
2082 if (skip_declarations
)
2083 for (; i
!= stmt_range
.second
; ++i
) {
2084 if ((*i
)->getStmtClass() != Stmt::DeclStmtClass
)
2089 for (; i
!= stmt_range
.second
; ++i
) {
2093 tree_i
= extract(child
);
2094 if (pet_tree_block_n_child(tree
) != 0 && partial
) {
2095 pet_tree_free(tree_i
);
2098 if (tree_i
&& child
->getStmtClass() == Stmt::DeclStmtClass
&&
2101 if (options
->autodetect
) {
2103 tree
= pet_tree_block_add_child(tree
, tree_i
);
2105 partial_range
= true;
2106 if (pet_tree_block_n_child(tree
) != 0 && !tree_i
)
2109 tree
= pet_tree_block_add_child(tree
, tree_i
);
2112 if (partial
|| !tree
)
2121 tree
= pet_tree_block_set_block(tree
, 0);
2122 } else if (partial_range
) {
2123 if (pet_tree_block_n_child(tree
) == 0) {
2124 pet_tree_free(tree
);
2128 } else if (skip
> 0)
2129 tree
= insert_initial_declarations(tree
, skip
, stmt_range
);
2135 static __isl_give pet_expr
*get_array_size(__isl_keep pet_expr
*access
,
2137 static struct pet_array
*extract_array(__isl_keep pet_expr
*access
,
2138 __isl_keep pet_context
*pc
, void *user
);
2141 /* Construct a pet_expr that holds the sizes of the array accessed
2143 * This function is used as a callback to pet_context_add_parameters,
2144 * which is also passed a pointer to the PetScan object.
2146 static __isl_give pet_expr
*get_array_size(__isl_keep pet_expr
*access
,
2149 PetScan
*ps
= (PetScan
*) user
;
2153 id
= pet_expr_access_get_id(access
);
2154 type
= pet_id_get_array_type(id
).getTypePtr();
2156 return ps
->get_array_size(type
);
2159 /* Construct and return a pet_array corresponding to the variable
2160 * accessed by "access".
2161 * This function is used as a callback to pet_scop_from_pet_tree,
2162 * which is also passed a pointer to the PetScan object.
2164 static struct pet_array
*extract_array(__isl_keep pet_expr
*access
,
2165 __isl_keep pet_context
*pc
, void *user
)
2167 PetScan
*ps
= (PetScan
*) user
;
2172 ctx
= pet_expr_get_ctx(access
);
2173 id
= pet_expr_access_get_id(access
);
2174 array
= ps
->extract_array(id
, NULL
, pc
);
2180 /* Extract a function summary from the body of "fd".
2182 * We extract a scop from the function body in a context with as
2183 * parameters the integer arguments of the function.
2184 * We turn off autodetection (in case it was set) to ensure that
2185 * the entire function body is considered.
2186 * We then collect the accessed array elements and attach them
2187 * to the corresponding array arguments, taking into account
2188 * that the function body may access members of array elements.
2190 * The reason for representing the integer arguments as parameters in
2191 * the context is that if we were to instead start with a context
2192 * with the function arguments as initial dimensions, then we would not
2193 * be able to refer to them from the array extents, without turning
2194 * array extents into maps.
2196 * The result is stored in the summary_cache cache so that we can reuse
2197 * it if this method gets called on the same function again later on.
2199 __isl_give pet_function_summary
*PetScan::get_summary(FunctionDecl
*fd
)
2205 pet_function_summary
*summary
;
2208 int save_autodetect
;
2209 struct pet_scop
*scop
;
2211 isl_union_set
*may_read
, *may_write
, *must_write
;
2212 isl_union_map
*to_inner
;
2214 if (summary_cache
.find(fd
) != summary_cache
.end())
2215 return pet_function_summary_copy(summary_cache
[fd
]);
2217 space
= isl_space_set_alloc(ctx
, 0, 0);
2219 n
= fd
->getNumParams();
2220 summary
= pet_function_summary_alloc(ctx
, n
);
2221 for (int i
= 0; i
< n
; ++i
) {
2222 ParmVarDecl
*parm
= fd
->getParamDecl(i
);
2223 QualType type
= parm
->getType();
2226 if (!type
->isIntegerType())
2228 id
= pet_id_from_decl(ctx
, parm
);
2229 space
= isl_space_insert_dims(space
, isl_dim_param
, 0, 1);
2230 space
= isl_space_set_dim_id(space
, isl_dim_param
, 0,
2232 summary
= pet_function_summary_set_int(summary
, i
, id
);
2235 save_autodetect
= options
->autodetect
;
2236 options
->autodetect
= 0;
2237 PetScan
body_scan(PP
, ast_context
, fd
, loc
, options
,
2238 isl_union_map_copy(value_bounds
), independent
);
2240 tree
= body_scan
.extract(fd
->getBody(), false);
2242 domain
= isl_set_universe(space
);
2243 pc
= pet_context_alloc(domain
);
2244 pc
= pet_context_add_parameters(pc
, tree
,
2245 &::get_array_size
, &body_scan
);
2246 int_size
= size_in_bytes(ast_context
, ast_context
.IntTy
);
2247 scop
= pet_scop_from_pet_tree(tree
, int_size
,
2248 &::extract_array
, &body_scan
, pc
);
2249 scop
= scan_arrays(scop
, pc
);
2250 may_read
= isl_union_map_range(pet_scop_collect_may_reads(scop
));
2251 may_write
= isl_union_map_range(pet_scop_collect_may_writes(scop
));
2252 must_write
= isl_union_map_range(pet_scop_collect_must_writes(scop
));
2253 to_inner
= pet_scop_compute_outer_to_inner(scop
);
2254 pet_scop_free(scop
);
2256 for (int i
= 0; i
< n
; ++i
) {
2257 ParmVarDecl
*parm
= fd
->getParamDecl(i
);
2258 QualType type
= parm
->getType();
2259 struct pet_array
*array
;
2261 isl_union_set
*data_set
;
2262 isl_union_set
*may_read_i
, *may_write_i
, *must_write_i
;
2264 if (array_depth(type
.getTypePtr()) == 0)
2267 array
= body_scan
.extract_array(parm
, NULL
, pc
);
2268 space
= array
? isl_set_get_space(array
->extent
) : NULL
;
2269 pet_array_free(array
);
2270 data_set
= isl_union_set_from_set(isl_set_universe(space
));
2271 data_set
= isl_union_set_apply(data_set
,
2272 isl_union_map_copy(to_inner
));
2273 may_read_i
= isl_union_set_intersect(
2274 isl_union_set_copy(may_read
),
2275 isl_union_set_copy(data_set
));
2276 may_write_i
= isl_union_set_intersect(
2277 isl_union_set_copy(may_write
),
2278 isl_union_set_copy(data_set
));
2279 must_write_i
= isl_union_set_intersect(
2280 isl_union_set_copy(must_write
), data_set
);
2281 summary
= pet_function_summary_set_array(summary
, i
,
2282 may_read_i
, may_write_i
, must_write_i
);
2285 isl_union_set_free(may_read
);
2286 isl_union_set_free(may_write
);
2287 isl_union_set_free(must_write
);
2288 isl_union_map_free(to_inner
);
2290 options
->autodetect
= save_autodetect
;
2291 pet_context_free(pc
);
2293 summary_cache
[fd
] = pet_function_summary_copy(summary
);
2298 /* If "fd" has a function body, then extract a function summary from
2299 * this body and attach it to the call expression "expr".
2301 * Even if a function body is available, "fd" itself may point
2302 * to a declaration without function body. We therefore first
2303 * replace it by the declaration that comes with a body (if any).
2305 __isl_give pet_expr
*PetScan::set_summary(__isl_take pet_expr
*expr
,
2308 pet_function_summary
*summary
;
2312 fd
= pet_clang_find_function_decl_with_body(fd
);
2316 summary
= get_summary(fd
);
2318 expr
= pet_expr_call_set_summary(expr
, summary
);
2323 /* Extract a pet_scop from "tree".
2325 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
2326 * then add pet_arrays for all accessed arrays.
2327 * We populate the pet_context with assignments for all parameters used
2328 * inside "tree" or any of the size expressions for the arrays accessed
2329 * by "tree" so that they can be used in affine expressions.
2331 struct pet_scop
*PetScan::extract_scop(__isl_take pet_tree
*tree
)
2338 int_size
= size_in_bytes(ast_context
, ast_context
.IntTy
);
2340 domain
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2341 pc
= pet_context_alloc(domain
);
2342 pc
= pet_context_add_parameters(pc
, tree
, &::get_array_size
, this);
2343 scop
= pet_scop_from_pet_tree(tree
, int_size
,
2344 &::extract_array
, this, pc
);
2345 scop
= scan_arrays(scop
, pc
);
2346 pet_context_free(pc
);
2351 /* Check if the scop marked by the user is exactly this Stmt
2352 * or part of this Stmt.
2353 * If so, return a pet_scop corresponding to the marked region.
2354 * Otherwise, return NULL.
2356 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
2358 SourceManager
&SM
= PP
.getSourceManager();
2359 unsigned start_off
, end_off
;
2361 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
2362 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
2364 if (start_off
> loc
.end
)
2366 if (end_off
< loc
.start
)
2369 if (start_off
>= loc
.start
&& end_off
<= loc
.end
)
2370 return extract_scop(extract(stmt
));
2373 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
2374 Stmt
*child
= *start
;
2377 start_off
= getExpansionOffset(SM
, child
->getLocStart());
2378 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
2379 if (start_off
< loc
.start
&& end_off
>= loc
.end
)
2381 if (start_off
>= loc
.start
)
2386 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
2388 start_off
= SM
.getFileOffset(child
->getLocStart());
2389 if (start_off
>= loc
.end
)
2393 return extract_scop(extract(StmtRange(start
, end
), false, false));
2396 /* Set the size of index "pos" of "array" to "size".
2397 * In particular, add a constraint of the form
2401 * to array->extent and a constraint of the form
2405 * to array->context.
2407 * The domain of "size" is assumed to be zero-dimensional.
2409 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
2410 __isl_take isl_pw_aff
*size
)
2423 valid
= isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
)));
2424 array
->context
= isl_set_intersect(array
->context
, valid
);
2426 dim
= isl_set_get_space(array
->extent
);
2427 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2428 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
2429 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
2430 index
= isl_pw_aff_alloc(univ
, aff
);
2432 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
2433 isl_set_dim(array
->extent
, isl_dim_set
));
2434 id
= isl_set_get_tuple_id(array
->extent
);
2435 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
2436 bound
= isl_pw_aff_lt_set(index
, size
);
2438 array
->extent
= isl_set_intersect(array
->extent
, bound
);
2440 if (!array
->context
|| !array
->extent
)
2441 return pet_array_free(array
);
2445 isl_pw_aff_free(size
);
2449 #ifdef HAVE_DECAYEDTYPE
2451 /* If "type" is a decayed type, then set *decayed to true and
2452 * return the original type.
2454 static const Type
*undecay(const Type
*type
, bool *decayed
)
2456 *decayed
= isa
<DecayedType
>(type
);
2458 type
= cast
<DecayedType
>(type
)->getOriginalType().getTypePtr();
2464 /* If "type" is a decayed type, then set *decayed to true and
2465 * return the original type.
2466 * Since this version of clang does not define a DecayedType,
2467 * we cannot obtain the original type even if it had been decayed and
2468 * we set *decayed to false.
2470 static const Type
*undecay(const Type
*type
, bool *decayed
)
2478 /* Figure out the size of the array at position "pos" and all
2479 * subsequent positions from "type" and update the corresponding
2480 * argument of "expr" accordingly.
2482 * The initial type (when pos is zero) may be a pointer type decayed
2483 * from an array type, if this initial type is the type of a function
2484 * argument. This only happens if the original array type has
2485 * a constant size in the outer dimension as otherwise we get
2486 * a VariableArrayType. Try and obtain this original type (if available) and
2487 * take the outer array size into account if it was marked static.
2489 __isl_give pet_expr
*PetScan::set_upper_bounds(__isl_take pet_expr
*expr
,
2490 const Type
*type
, int pos
)
2492 const ArrayType
*atype
;
2494 bool decayed
= false;
2500 type
= undecay(type
, &decayed
);
2502 if (type
->isPointerType()) {
2503 type
= type
->getPointeeType().getTypePtr();
2504 return set_upper_bounds(expr
, type
, pos
+ 1);
2506 if (!type
->isArrayType())
2509 type
= type
->getCanonicalTypeInternal().getTypePtr();
2510 atype
= cast
<ArrayType
>(type
);
2512 if (decayed
&& atype
->getSizeModifier() != ArrayType::Static
) {
2513 type
= atype
->getElementType().getTypePtr();
2514 return set_upper_bounds(expr
, type
, pos
+ 1);
2517 if (type
->isConstantArrayType()) {
2518 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
2519 size
= extract_expr(ca
->getSize());
2520 expr
= pet_expr_set_arg(expr
, pos
, size
);
2521 } else if (type
->isVariableArrayType()) {
2522 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
2523 size
= extract_expr(vla
->getSizeExpr());
2524 expr
= pet_expr_set_arg(expr
, pos
, size
);
2527 type
= atype
->getElementType().getTypePtr();
2529 return set_upper_bounds(expr
, type
, pos
+ 1);
2532 /* Construct a pet_expr that holds the sizes of an array of the given type.
2533 * The returned expression is a call expression with as arguments
2534 * the sizes in each dimension. If we are unable to derive the size
2535 * in a given dimension, then the corresponding argument is set to infinity.
2536 * In fact, we initialize all arguments to infinity and then update
2537 * them if we are able to figure out the size.
2539 * The result is stored in the type_size cache so that we can reuse
2540 * it if this method gets called on the same type again later on.
2542 __isl_give pet_expr
*PetScan::get_array_size(const Type
*type
)
2545 pet_expr
*expr
, *inf
;
2547 if (type_size
.find(type
) != type_size
.end())
2548 return pet_expr_copy(type_size
[type
]);
2550 depth
= array_depth(type
);
2551 inf
= pet_expr_new_int(isl_val_infty(ctx
));
2552 expr
= pet_expr_new_call(ctx
, "bounds", depth
);
2553 for (int i
= 0; i
< depth
; ++i
)
2554 expr
= pet_expr_set_arg(expr
, i
, pet_expr_copy(inf
));
2557 expr
= set_upper_bounds(expr
, type
, 0);
2558 type_size
[type
] = pet_expr_copy(expr
);
2563 /* Does "expr" represent the "integer" infinity?
2565 static int is_infty(__isl_keep pet_expr
*expr
)
2570 if (pet_expr_get_type(expr
) != pet_expr_int
)
2572 v
= pet_expr_int_get_val(expr
);
2573 res
= isl_val_is_infty(v
);
2579 /* Figure out the dimensions of an array "array" based on its type
2580 * "type" and update "array" accordingly.
2582 * We first construct a pet_expr that holds the sizes of the array
2583 * in each dimension. The resulting expression may containing
2584 * infinity values for dimension where we are unable to derive
2585 * a size expression.
2587 * The arguments of the size expression that have a value different from
2588 * infinity are then converted to an affine expression
2589 * within the context "pc" and incorporated into the size of "array".
2590 * If we are unable to convert a size expression to an affine expression or
2591 * if the size is not a (symbolic) constant,
2592 * then we leave the corresponding size of "array" untouched.
2594 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
2595 const Type
*type
, __isl_keep pet_context
*pc
)
2603 expr
= get_array_size(type
);
2605 n
= pet_expr_get_n_arg(expr
);
2606 for (int i
= 0; i
< n
; ++i
) {
2610 arg
= pet_expr_get_arg(expr
, i
);
2611 if (!is_infty(arg
)) {
2614 size
= pet_expr_extract_affine(arg
, pc
);
2615 dim
= isl_pw_aff_dim(size
, isl_dim_in
);
2617 array
= pet_array_free(array
);
2618 else if (isl_pw_aff_involves_nan(size
) ||
2619 isl_pw_aff_involves_dims(size
, isl_dim_in
, 0, dim
))
2620 isl_pw_aff_free(size
);
2622 size
= isl_pw_aff_drop_dims(size
,
2623 isl_dim_in
, 0, dim
);
2624 array
= update_size(array
, i
, size
);
2629 pet_expr_free(expr
);
2634 /* Does "decl" have a definition that we can keep track of in a pet_type?
2636 static bool has_printable_definition(RecordDecl
*decl
)
2638 if (!decl
->getDeclName())
2640 return decl
->getLexicalDeclContext() == decl
->getDeclContext();
2643 /* Construct and return a pet_array corresponding to the variable
2644 * represented by "id".
2645 * In particular, initialize array->extent to
2647 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2649 * and then call set_upper_bounds to set the upper bounds on the indices
2650 * based on the type of the variable. The upper bounds are converted
2651 * to affine expressions within the context "pc".
2653 * If the base type is that of a record with a top-level definition or
2654 * of a typedef and if "types" is not null, then the RecordDecl or
2655 * TypedefType corresponding to the type
2656 * is added to "types".
2658 * If the base type is that of a record with no top-level definition,
2659 * then we replace it by "<subfield>".
2661 struct pet_array
*PetScan::extract_array(__isl_keep isl_id
*id
,
2662 PetTypes
*types
, __isl_keep pet_context
*pc
)
2664 struct pet_array
*array
;
2665 QualType qt
= pet_id_get_array_type(id
);
2666 const Type
*type
= qt
.getTypePtr();
2667 int depth
= array_depth(type
);
2668 QualType base
= pet_clang_base_type(qt
);
2672 array
= isl_calloc_type(ctx
, struct pet_array
);
2676 space
= isl_space_set_alloc(ctx
, 0, depth
);
2677 space
= isl_space_set_tuple_id(space
, isl_dim_set
, isl_id_copy(id
));
2679 array
->extent
= isl_set_nat_universe(space
);
2681 space
= isl_space_params_alloc(ctx
, 0);
2682 array
->context
= isl_set_universe(space
);
2684 array
= set_upper_bounds(array
, type
, pc
);
2688 name
= base
.getAsString();
2691 if (isa
<TypedefType
>(base
)) {
2692 types
->insert(cast
<TypedefType
>(base
)->getDecl());
2693 } else if (base
->isRecordType()) {
2694 RecordDecl
*decl
= pet_clang_record_decl(base
);
2695 TypedefNameDecl
*typedecl
;
2696 typedecl
= decl
->getTypedefNameForAnonDecl();
2698 types
->insert(typedecl
);
2699 else if (has_printable_definition(decl
))
2700 types
->insert(decl
);
2702 name
= "<subfield>";
2706 array
->element_type
= strdup(name
.c_str());
2707 array
->element_is_record
= base
->isRecordType();
2708 array
->element_size
= size_in_bytes(ast_context
, base
);
2713 /* Construct and return a pet_array corresponding to the variable "decl".
2715 struct pet_array
*PetScan::extract_array(ValueDecl
*decl
,
2716 PetTypes
*types
, __isl_keep pet_context
*pc
)
2721 id
= pet_id_from_decl(ctx
, decl
);
2722 array
= extract_array(id
, types
, pc
);
2728 /* Construct and return a pet_array corresponding to the sequence
2729 * of declarations "decls".
2730 * The upper bounds of the array are converted to affine expressions
2731 * within the context "pc".
2732 * If the sequence contains a single declaration, then it corresponds
2733 * to a simple array access. Otherwise, it corresponds to a member access,
2734 * with the declaration for the substructure following that of the containing
2735 * structure in the sequence of declarations.
2736 * We start with the outermost substructure and then combine it with
2737 * information from the inner structures.
2739 * Additionally, keep track of all required types in "types".
2741 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
,
2742 vector
<ValueDecl
*> decls
, PetTypes
*types
, __isl_keep pet_context
*pc
)
2744 struct pet_array
*array
;
2745 vector
<ValueDecl
*>::iterator it
;
2749 array
= extract_array(*it
, types
, pc
);
2751 for (++it
; it
!= decls
.end(); ++it
) {
2752 struct pet_array
*parent
;
2753 const char *base_name
, *field_name
;
2757 array
= extract_array(*it
, types
, pc
);
2759 return pet_array_free(parent
);
2761 base_name
= isl_set_get_tuple_name(parent
->extent
);
2762 field_name
= isl_set_get_tuple_name(array
->extent
);
2763 product_name
= pet_array_member_access_name(ctx
,
2764 base_name
, field_name
);
2766 array
->extent
= isl_set_product(isl_set_copy(parent
->extent
),
2769 array
->extent
= isl_set_set_tuple_name(array
->extent
,
2771 array
->context
= isl_set_intersect(array
->context
,
2772 isl_set_copy(parent
->context
));
2774 pet_array_free(parent
);
2777 if (!array
->extent
|| !array
->context
|| !product_name
)
2778 return pet_array_free(array
);
2784 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
2785 RecordDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2786 std::set
<TypeDecl
*> &types_done
);
2787 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
2788 TypedefNameDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2789 std::set
<TypeDecl
*> &types_done
);
2791 /* For each of the fields of "decl" that is itself a record type
2792 * or a typedef, add a corresponding pet_type to "scop".
2794 static struct pet_scop
*add_field_types(isl_ctx
*ctx
, struct pet_scop
*scop
,
2795 RecordDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2796 std::set
<TypeDecl
*> &types_done
)
2798 RecordDecl::field_iterator it
;
2800 for (it
= decl
->field_begin(); it
!= decl
->field_end(); ++it
) {
2801 QualType type
= it
->getType();
2803 if (isa
<TypedefType
>(type
)) {
2804 TypedefNameDecl
*typedefdecl
;
2806 typedefdecl
= cast
<TypedefType
>(type
)->getDecl();
2807 scop
= add_type(ctx
, scop
, typedefdecl
,
2808 PP
, types
, types_done
);
2809 } else if (type
->isRecordType()) {
2812 record
= pet_clang_record_decl(type
);
2813 scop
= add_type(ctx
, scop
, record
,
2814 PP
, types
, types_done
);
2821 /* Add a pet_type corresponding to "decl" to "scop", provided
2822 * it is a member of types.records and it has not been added before
2823 * (i.e., it is not a member of "types_done").
2825 * Since we want the user to be able to print the types
2826 * in the order in which they appear in the scop, we need to
2827 * make sure that types of fields in a structure appear before
2828 * that structure. We therefore call ourselves recursively
2829 * through add_field_types on the types of all record subfields.
2831 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
2832 RecordDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2833 std::set
<TypeDecl
*> &types_done
)
2836 llvm::raw_string_ostream
S(s
);
2838 if (types
.records
.find(decl
) == types
.records
.end())
2840 if (types_done
.find(decl
) != types_done
.end())
2843 add_field_types(ctx
, scop
, decl
, PP
, types
, types_done
);
2845 if (strlen(decl
->getName().str().c_str()) == 0)
2848 decl
->print(S
, PrintingPolicy(PP
.getLangOpts()));
2851 scop
->types
[scop
->n_type
] = pet_type_alloc(ctx
,
2852 decl
->getName().str().c_str(), s
.c_str());
2853 if (!scop
->types
[scop
->n_type
])
2854 return pet_scop_free(scop
);
2856 types_done
.insert(decl
);
2863 /* Add a pet_type corresponding to "decl" to "scop", provided
2864 * it is a member of types.typedefs and it has not been added before
2865 * (i.e., it is not a member of "types_done").
2867 * If the underlying type is a structure, then we print the typedef
2868 * ourselves since clang does not print the definition of the structure
2869 * in the typedef. We also make sure in this case that the types of
2870 * the fields in the structure are added first.
2872 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
2873 TypedefNameDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2874 std::set
<TypeDecl
*> &types_done
)
2877 llvm::raw_string_ostream
S(s
);
2878 QualType qt
= decl
->getUnderlyingType();
2880 if (types
.typedefs
.find(decl
) == types
.typedefs
.end())
2882 if (types_done
.find(decl
) != types_done
.end())
2885 if (qt
->isRecordType()) {
2886 RecordDecl
*rec
= pet_clang_record_decl(qt
);
2888 add_field_types(ctx
, scop
, rec
, PP
, types
, types_done
);
2890 rec
->print(S
, PrintingPolicy(PP
.getLangOpts()));
2892 S
<< decl
->getName();
2894 decl
->print(S
, PrintingPolicy(PP
.getLangOpts()));
2898 scop
->types
[scop
->n_type
] = pet_type_alloc(ctx
,
2899 decl
->getName().str().c_str(), s
.c_str());
2900 if (!scop
->types
[scop
->n_type
])
2901 return pet_scop_free(scop
);
2903 types_done
.insert(decl
);
2910 /* Construct a list of pet_arrays, one for each array (or scalar)
2911 * accessed inside "scop", add this list to "scop" and return the result.
2912 * The upper bounds of the arrays are converted to affine expressions
2913 * within the context "pc".
2915 * The context of "scop" is updated with the intersection of
2916 * the contexts of all arrays, i.e., constraints on the parameters
2917 * that ensure that the arrays have a valid (non-negative) size.
2919 * If any of the extracted arrays refers to a member access or
2920 * has a typedef'd type as base type,
2921 * then also add the required types to "scop".
2923 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
,
2924 __isl_keep pet_context
*pc
)
2927 array_desc_set arrays
;
2928 array_desc_set::iterator it
;
2930 std::set
<TypeDecl
*> types_done
;
2931 std::set
<clang::RecordDecl
*, less_name
>::iterator records_it
;
2932 std::set
<clang::TypedefNameDecl
*, less_name
>::iterator typedefs_it
;
2934 struct pet_array
**scop_arrays
;
2939 pet_scop_collect_arrays(scop
, arrays
);
2940 if (arrays
.size() == 0)
2943 n_array
= scop
->n_array
;
2945 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
2946 n_array
+ arrays
.size());
2949 scop
->arrays
= scop_arrays
;
2951 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
2952 struct pet_array
*array
;
2953 array
= extract_array(ctx
, *it
, &types
, pc
);
2954 scop
->arrays
[n_array
+ i
] = array
;
2955 if (!scop
->arrays
[n_array
+ i
])
2958 scop
->context
= isl_set_intersect(scop
->context
,
2959 isl_set_copy(array
->context
));
2964 n
= types
.records
.size() + types
.typedefs
.size();
2968 scop
->types
= isl_alloc_array(ctx
, struct pet_type
*, n
);
2972 for (records_it
= types
.records
.begin();
2973 records_it
!= types
.records
.end(); ++records_it
)
2974 scop
= add_type(ctx
, scop
, *records_it
, PP
, types
, types_done
);
2976 for (typedefs_it
= types
.typedefs
.begin();
2977 typedefs_it
!= types
.typedefs
.end(); ++typedefs_it
)
2978 scop
= add_type(ctx
, scop
, *typedefs_it
, PP
, types
, types_done
);
2982 pet_scop_free(scop
);
2986 /* Bound all parameters in scop->context to the possible values
2987 * of the corresponding C variable.
2989 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
2996 n
= isl_set_dim(scop
->context
, isl_dim_param
);
2997 for (int i
= 0; i
< n
; ++i
) {
3001 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
3002 if (pet_nested_in_id(id
)) {
3004 isl_die(isl_set_get_ctx(scop
->context
),
3006 "unresolved nested parameter", goto error
);
3008 decl
= pet_id_get_decl(id
);
3011 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
3019 pet_scop_free(scop
);
3023 /* Construct a pet_scop from the given function.
3025 * If the scop was delimited by scop and endscop pragmas, then we override
3026 * the file offsets by those derived from the pragmas.
3028 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
3033 stmt
= fd
->getBody();
3035 if (options
->autodetect
) {
3036 set_current_stmt(stmt
);
3037 scop
= extract_scop(extract(stmt
, true));
3039 current_line
= loc
.start_line
;
3041 scop
= pet_scop_update_start_end(scop
, loc
.start
, loc
.end
);
3043 scop
= add_parameter_bounds(scop
);
3044 scop
= pet_scop_gist(scop
, value_bounds
);
3049 /* Update this->last_line and this->current_line based on the fact
3050 * that we are about to consider "stmt".
3052 void PetScan::set_current_stmt(Stmt
*stmt
)
3054 SourceLocation loc
= stmt
->getLocStart();
3055 SourceManager
&SM
= PP
.getSourceManager();
3057 last_line
= current_line
;
3058 current_line
= SM
.getExpansionLineNumber(loc
);
3061 /* Is the current statement marked by an independent pragma?
3062 * That is, is there an independent pragma on a line between
3063 * the line of the current statement and the line of the previous statement.
3064 * The search is not implemented very efficiently. We currently
3065 * assume that there are only a few independent pragmas, if any.
3067 bool PetScan::is_current_stmt_marked_independent()
3069 for (int i
= 0; i
< independent
.size(); ++i
) {
3070 unsigned line
= independent
[i
].line
;
3072 if (last_line
< line
&& line
< current_line
)