2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2014 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
39 #include <llvm/Support/raw_ostream.h>
40 #include <clang/AST/ASTContext.h>
41 #include <clang/AST/ASTDiagnostic.h>
42 #include <clang/AST/Expr.h>
43 #include <clang/AST/RecursiveASTVisitor.h>
46 #include <isl/space.h>
59 #include "scop_plus.h"
61 #include "tree2scop.h"
66 using namespace clang
;
68 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
78 return pet_op_post_inc
;
80 return pet_op_post_dec
;
82 return pet_op_pre_inc
;
84 return pet_op_pre_dec
;
90 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
94 return pet_op_add_assign
;
96 return pet_op_sub_assign
;
98 return pet_op_mul_assign
;
100 return pet_op_div_assign
;
102 return pet_op_assign
;
144 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
145 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
147 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
148 SourceLocation(), var
, false, var
->getInnerLocStart(),
149 var
->getType(), VK_LValue
);
151 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
152 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
154 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
155 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
159 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
161 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
162 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
166 /* Check if the element type corresponding to the given array type
167 * has a const qualifier.
169 static bool const_base(QualType qt
)
171 const Type
*type
= qt
.getTypePtr();
173 if (type
->isPointerType())
174 return const_base(type
->getPointeeType());
175 if (type
->isArrayType()) {
176 const ArrayType
*atype
;
177 type
= type
->getCanonicalTypeInternal().getTypePtr();
178 atype
= cast
<ArrayType
>(type
);
179 return const_base(atype
->getElementType());
182 return qt
.isConstQualified();
185 /* Create an isl_id that refers to the named declarator "decl".
187 static __isl_give isl_id
*create_decl_id(isl_ctx
*ctx
, NamedDecl
*decl
)
189 return isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
194 std::map
<const Type
*, pet_expr
*>::iterator it
;
195 std::map
<FunctionDecl
*, pet_function_summary
*>::iterator it_s
;
197 for (it
= type_size
.begin(); it
!= type_size
.end(); ++it
)
198 pet_expr_free(it
->second
);
199 for (it_s
= summary_cache
.begin(); it_s
!= summary_cache
.end(); ++it_s
)
200 pet_function_summary_free(it_s
->second
);
202 isl_union_map_free(value_bounds
);
205 /* Report a diagnostic, unless autodetect is set.
207 void PetScan::report(Stmt
*stmt
, unsigned id
)
209 if (options
->autodetect
)
212 SourceLocation loc
= stmt
->getLocStart();
213 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
214 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
217 /* Called if we found something we (currently) cannot handle.
218 * We'll provide more informative warnings later.
220 * We only actually complain if autodetect is false.
222 void PetScan::unsupported(Stmt
*stmt
)
224 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
225 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
230 /* Report a missing prototype, unless autodetect is set.
232 void PetScan::report_prototype_required(Stmt
*stmt
)
234 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
235 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
236 "prototype required");
240 /* Report a missing increment, unless autodetect is set.
242 void PetScan::report_missing_increment(Stmt
*stmt
)
244 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
245 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
246 "missing increment");
250 /* Extract an integer from "val", which is assumed to be non-negative.
252 static __isl_give isl_val
*extract_unsigned(isl_ctx
*ctx
,
253 const llvm::APInt
&val
)
256 const uint64_t *data
;
258 data
= val
.getRawData();
259 n
= val
.getNumWords();
260 return isl_val_int_from_chunks(ctx
, n
, sizeof(uint64_t), data
);
263 /* Extract an integer from "val". If "is_signed" is set, then "val"
264 * is signed. Otherwise it it unsigned.
266 static __isl_give isl_val
*extract_int(isl_ctx
*ctx
, bool is_signed
,
269 int is_negative
= is_signed
&& val
.isNegative();
275 v
= extract_unsigned(ctx
, val
);
282 /* Extract an integer from "expr".
284 __isl_give isl_val
*PetScan::extract_int(isl_ctx
*ctx
, IntegerLiteral
*expr
)
286 const Type
*type
= expr
->getType().getTypePtr();
287 bool is_signed
= type
->hasSignedIntegerRepresentation();
289 return ::extract_int(ctx
, is_signed
, expr
->getValue());
292 /* Extract an integer from "expr".
293 * Return NULL if "expr" does not (obviously) represent an integer.
295 __isl_give isl_val
*PetScan::extract_int(clang::ParenExpr
*expr
)
297 return extract_int(expr
->getSubExpr());
300 /* Extract an integer from "expr".
301 * Return NULL if "expr" does not (obviously) represent an integer.
303 __isl_give isl_val
*PetScan::extract_int(clang::Expr
*expr
)
305 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
306 return extract_int(ctx
, cast
<IntegerLiteral
>(expr
));
307 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
308 return extract_int(cast
<ParenExpr
>(expr
));
314 /* Extract a pet_expr from the APInt "val", which is assumed
315 * to be non-negative.
317 __isl_give pet_expr
*PetScan::extract_expr(const llvm::APInt
&val
)
319 return pet_expr_new_int(extract_unsigned(ctx
, val
));
322 /* Return the number of bits needed to represent the type "qt",
323 * if it is an integer type. Otherwise return 0.
324 * If qt is signed then return the opposite of the number of bits.
326 static int get_type_size(QualType qt
, ASTContext
&ast_context
)
330 if (!qt
->isIntegerType())
333 size
= ast_context
.getIntWidth(qt
);
334 if (!qt
->isUnsignedIntegerType())
340 /* Return the number of bits needed to represent the type of "decl",
341 * if it is an integer type. Otherwise return 0.
342 * If qt is signed then return the opposite of the number of bits.
344 static int get_type_size(ValueDecl
*decl
)
346 return get_type_size(decl
->getType(), decl
->getASTContext());
349 /* Bound parameter "pos" of "set" to the possible values of "decl".
351 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
352 unsigned pos
, ValueDecl
*decl
)
358 ctx
= isl_set_get_ctx(set
);
359 type_size
= get_type_size(decl
);
361 isl_die(ctx
, isl_error_invalid
, "not an integer type",
362 return isl_set_free(set
));
364 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
365 bound
= isl_val_int_from_ui(ctx
, type_size
);
366 bound
= isl_val_2exp(bound
);
367 bound
= isl_val_sub_ui(bound
, 1);
368 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
, bound
);
370 bound
= isl_val_int_from_ui(ctx
, -type_size
- 1);
371 bound
= isl_val_2exp(bound
);
372 bound
= isl_val_sub_ui(bound
, 1);
373 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
,
374 isl_val_copy(bound
));
375 bound
= isl_val_neg(bound
);
376 bound
= isl_val_sub_ui(bound
, 1);
377 set
= isl_set_lower_bound_val(set
, isl_dim_param
, pos
, bound
);
383 __isl_give pet_expr
*PetScan::extract_index_expr(ImplicitCastExpr
*expr
)
385 return extract_index_expr(expr
->getSubExpr());
388 /* Return the depth of an array of the given type.
390 static int array_depth(const Type
*type
)
392 if (type
->isPointerType())
393 return 1 + array_depth(type
->getPointeeType().getTypePtr());
394 if (type
->isArrayType()) {
395 const ArrayType
*atype
;
396 type
= type
->getCanonicalTypeInternal().getTypePtr();
397 atype
= cast
<ArrayType
>(type
);
398 return 1 + array_depth(atype
->getElementType().getTypePtr());
403 /* Return the depth of the array accessed by the index expression "index".
404 * If "index" is an affine expression, i.e., if it does not access
405 * any array, then return 1.
406 * If "index" represent a member access, i.e., if its range is a wrapped
407 * relation, then return the sum of the depth of the array of structures
408 * and that of the member inside the structure.
410 static int extract_depth(__isl_keep isl_multi_pw_aff
*index
)
418 if (isl_multi_pw_aff_range_is_wrapping(index
)) {
419 int domain_depth
, range_depth
;
420 isl_multi_pw_aff
*domain
, *range
;
422 domain
= isl_multi_pw_aff_copy(index
);
423 domain
= isl_multi_pw_aff_range_factor_domain(domain
);
424 domain_depth
= extract_depth(domain
);
425 isl_multi_pw_aff_free(domain
);
426 range
= isl_multi_pw_aff_copy(index
);
427 range
= isl_multi_pw_aff_range_factor_range(range
);
428 range_depth
= extract_depth(range
);
429 isl_multi_pw_aff_free(range
);
431 return domain_depth
+ range_depth
;
434 if (!isl_multi_pw_aff_has_tuple_id(index
, isl_dim_out
))
437 id
= isl_multi_pw_aff_get_tuple_id(index
, isl_dim_out
);
440 decl
= (ValueDecl
*) isl_id_get_user(id
);
443 return array_depth(decl
->getType().getTypePtr());
446 /* Return the depth of the array accessed by the access expression "expr".
448 static int extract_depth(__isl_keep pet_expr
*expr
)
450 isl_multi_pw_aff
*index
;
453 index
= pet_expr_access_get_index(expr
);
454 depth
= extract_depth(index
);
455 isl_multi_pw_aff_free(index
);
460 /* Construct a pet_expr representing an index expression for an access
461 * to the variable referenced by "expr".
463 * If "expr" references an enum constant, then return an integer expression
464 * instead, representing the value of the enum constant.
466 __isl_give pet_expr
*PetScan::extract_index_expr(DeclRefExpr
*expr
)
468 return extract_index_expr(expr
->getDecl());
471 /* Construct a pet_expr representing an index expression for an access
472 * to the variable "decl".
474 * If "decl" is an enum constant, then we return an integer expression
475 * instead, representing the value of the enum constant.
477 __isl_give pet_expr
*PetScan::extract_index_expr(ValueDecl
*decl
)
482 if (isa
<EnumConstantDecl
>(decl
))
483 return extract_expr(cast
<EnumConstantDecl
>(decl
));
485 id
= create_decl_id(ctx
, decl
);
486 space
= isl_space_alloc(ctx
, 0, 0, 0);
487 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
489 return pet_expr_from_index(isl_multi_pw_aff_zero(space
));
492 /* Construct a pet_expr representing the index expression "expr"
493 * Return NULL on error.
495 * If "expr" is a reference to an enum constant, then return
496 * an integer expression instead, representing the value of the enum constant.
498 __isl_give pet_expr
*PetScan::extract_index_expr(Expr
*expr
)
500 switch (expr
->getStmtClass()) {
501 case Stmt::ImplicitCastExprClass
:
502 return extract_index_expr(cast
<ImplicitCastExpr
>(expr
));
503 case Stmt::DeclRefExprClass
:
504 return extract_index_expr(cast
<DeclRefExpr
>(expr
));
505 case Stmt::ArraySubscriptExprClass
:
506 return extract_index_expr(cast
<ArraySubscriptExpr
>(expr
));
507 case Stmt::IntegerLiteralClass
:
508 return extract_expr(cast
<IntegerLiteral
>(expr
));
509 case Stmt::MemberExprClass
:
510 return extract_index_expr(cast
<MemberExpr
>(expr
));
517 /* Extract an index expression from the given array subscript expression.
519 * We first extract an index expression from the base.
520 * This will result in an index expression with a range that corresponds
521 * to the earlier indices.
522 * We then extract the current index and let
523 * pet_expr_access_subscript combine the two.
525 __isl_give pet_expr
*PetScan::extract_index_expr(ArraySubscriptExpr
*expr
)
527 Expr
*base
= expr
->getBase();
528 Expr
*idx
= expr
->getIdx();
532 base_expr
= extract_index_expr(base
);
533 index
= extract_expr(idx
);
535 base_expr
= pet_expr_access_subscript(base_expr
, index
);
540 /* Extract an index expression from a member expression.
542 * If the base access (to the structure containing the member)
547 * and the member is called "f", then the member access is of
552 * If the member access is to an anonymous struct, then simply return
556 * If the member access in the source code is of the form
560 * then it is treated as
564 __isl_give pet_expr
*PetScan::extract_index_expr(MemberExpr
*expr
)
566 Expr
*base
= expr
->getBase();
567 FieldDecl
*field
= cast
<FieldDecl
>(expr
->getMemberDecl());
568 pet_expr
*base_index
;
571 base_index
= extract_index_expr(base
);
573 if (expr
->isArrow()) {
574 pet_expr
*index
= pet_expr_new_int(isl_val_zero(ctx
));
575 base_index
= pet_expr_access_subscript(base_index
, index
);
578 if (field
->isAnonymousStructOrUnion())
581 id
= create_decl_id(ctx
, field
);
583 return pet_expr_access_member(base_index
, id
);
586 /* Mark the given access pet_expr as a write.
588 static __isl_give pet_expr
*mark_write(__isl_take pet_expr
*access
)
590 access
= pet_expr_access_set_write(access
, 1);
591 access
= pet_expr_access_set_read(access
, 0);
596 /* Construct a pet_expr representing a unary operator expression.
598 __isl_give pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
603 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
604 if (op
== pet_op_last
) {
609 arg
= extract_expr(expr
->getSubExpr());
611 if (expr
->isIncrementDecrementOp() &&
612 pet_expr_get_type(arg
) == pet_expr_access
) {
613 arg
= mark_write(arg
);
614 arg
= pet_expr_access_set_read(arg
, 1);
617 return pet_expr_new_unary(op
, arg
);
620 /* Construct a pet_expr representing a binary operator expression.
622 * If the top level operator is an assignment and the LHS is an access,
623 * then we mark that access as a write. If the operator is a compound
624 * assignment, the access is marked as both a read and a write.
626 __isl_give pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
632 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
633 if (op
== pet_op_last
) {
638 lhs
= extract_expr(expr
->getLHS());
639 rhs
= extract_expr(expr
->getRHS());
641 if (expr
->isAssignmentOp() &&
642 pet_expr_get_type(lhs
) == pet_expr_access
) {
643 lhs
= mark_write(lhs
);
644 if (expr
->isCompoundAssignmentOp())
645 lhs
= pet_expr_access_set_read(lhs
, 1);
648 type_size
= get_type_size(expr
->getType(), ast_context
);
649 return pet_expr_new_binary(type_size
, op
, lhs
, rhs
);
652 /* Construct a pet_tree for a (single) variable declaration.
654 __isl_give pet_tree
*PetScan::extract(DeclStmt
*stmt
)
661 if (!stmt
->isSingleDecl()) {
666 decl
= stmt
->getSingleDecl();
667 vd
= cast
<VarDecl
>(decl
);
669 lhs
= extract_access_expr(vd
);
670 lhs
= mark_write(lhs
);
672 tree
= pet_tree_new_decl(lhs
);
674 rhs
= extract_expr(vd
->getInit());
675 tree
= pet_tree_new_decl_init(lhs
, rhs
);
681 /* Construct a pet_expr representing a conditional operation.
683 __isl_give pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
685 pet_expr
*cond
, *lhs
, *rhs
;
688 cond
= extract_expr(expr
->getCond());
689 lhs
= extract_expr(expr
->getTrueExpr());
690 rhs
= extract_expr(expr
->getFalseExpr());
692 return pet_expr_new_ternary(cond
, lhs
, rhs
);
695 __isl_give pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
697 return extract_expr(expr
->getSubExpr());
700 /* Construct a pet_expr representing a floating point value.
702 * If the floating point literal does not appear in a macro,
703 * then we use the original representation in the source code
704 * as the string representation. Otherwise, we use the pretty
705 * printer to produce a string representation.
707 __isl_give pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
711 const LangOptions
&LO
= PP
.getLangOpts();
712 SourceLocation loc
= expr
->getLocation();
714 if (!loc
.isMacroID()) {
715 SourceManager
&SM
= PP
.getSourceManager();
716 unsigned len
= Lexer::MeasureTokenLength(loc
, SM
, LO
);
717 s
= string(SM
.getCharacterData(loc
), len
);
719 llvm::raw_string_ostream
S(s
);
720 expr
->printPretty(S
, 0, PrintingPolicy(LO
));
723 d
= expr
->getValueAsApproximateDouble();
724 return pet_expr_new_double(ctx
, d
, s
.c_str());
727 /* Convert the index expression "index" into an access pet_expr of type "qt".
729 __isl_give pet_expr
*PetScan::extract_access_expr(QualType qt
,
730 __isl_take pet_expr
*index
)
735 depth
= extract_depth(index
);
736 type_size
= get_type_size(qt
, ast_context
);
738 index
= pet_expr_set_type_size(index
, type_size
);
739 index
= pet_expr_access_set_depth(index
, depth
);
744 /* Extract an index expression from "expr" and then convert it into
745 * an access pet_expr.
747 * If "expr" is a reference to an enum constant, then return
748 * an integer expression instead, representing the value of the enum constant.
750 __isl_give pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
754 index
= extract_index_expr(expr
);
756 if (pet_expr_get_type(index
) == pet_expr_int
)
759 return extract_access_expr(expr
->getType(), index
);
762 /* Extract an index expression from "decl" and then convert it into
763 * an access pet_expr.
765 __isl_give pet_expr
*PetScan::extract_access_expr(ValueDecl
*decl
)
767 return extract_access_expr(decl
->getType(), extract_index_expr(decl
));
770 __isl_give pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
772 return extract_expr(expr
->getSubExpr());
775 /* Extract an assume statement from the argument "expr"
776 * of a __pencil_assume statement.
778 __isl_give pet_expr
*PetScan::extract_assume(Expr
*expr
)
780 return pet_expr_new_unary(pet_op_assume
, extract_expr(expr
));
783 /* Construct a pet_expr corresponding to the function call argument "expr".
784 * The argument appears in position "pos" of a call to function "fd".
786 * If we are passing along a pointer to an array element
787 * or an entire row or even higher dimensional slice of an array,
788 * then the function being called may write into the array.
790 * We assume here that if the function is declared to take a pointer
791 * to a const type, then the function will perform a read
792 * and that otherwise, it will perform a write.
794 __isl_give pet_expr
*PetScan::extract_argument(FunctionDecl
*fd
, int pos
,
798 int is_addr
= 0, is_partial
= 0;
801 if (expr
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
802 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(expr
);
803 expr
= ice
->getSubExpr();
805 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
) {
806 UnaryOperator
*op
= cast
<UnaryOperator
>(expr
);
807 if (op
->getOpcode() == UO_AddrOf
) {
809 expr
= op
->getSubExpr();
812 res
= extract_expr(expr
);
815 sc
= expr
->getStmtClass();
816 if ((sc
== Stmt::ArraySubscriptExprClass
||
817 sc
== Stmt::DeclRefExprClass
||
818 sc
== Stmt::MemberExprClass
) &&
819 array_depth(expr
->getType().getTypePtr()) > 0)
821 if ((is_addr
|| is_partial
) &&
822 pet_expr_get_type(res
) == pet_expr_access
) {
824 if (!fd
->hasPrototype()) {
825 report_prototype_required(expr
);
826 return pet_expr_free(res
);
828 parm
= fd
->getParamDecl(pos
);
829 if (!const_base(parm
->getType()))
830 res
= mark_write(res
);
834 res
= pet_expr_new_unary(pet_op_address_of
, res
);
838 /* Construct a pet_expr representing a function call.
840 * In the special case of a "call" to __pencil_assume,
841 * construct an assume expression instead.
843 __isl_give pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
845 pet_expr
*res
= NULL
;
850 fd
= expr
->getDirectCallee();
856 name
= fd
->getDeclName().getAsString();
857 n_arg
= expr
->getNumArgs();
859 if (n_arg
== 1 && name
== "__pencil_assume")
860 return extract_assume(expr
->getArg(0));
862 res
= pet_expr_new_call(ctx
, name
.c_str(), n_arg
);
866 for (int i
= 0; i
< n_arg
; ++i
) {
867 Expr
*arg
= expr
->getArg(i
);
868 res
= pet_expr_set_arg(res
, i
,
869 PetScan::extract_argument(fd
, i
, arg
));
872 res
= set_summary(res
, fd
);
877 /* Construct a pet_expr representing a (C style) cast.
879 __isl_give pet_expr
*PetScan::extract_expr(CStyleCastExpr
*expr
)
884 arg
= extract_expr(expr
->getSubExpr());
888 type
= expr
->getTypeAsWritten();
889 return pet_expr_new_cast(type
.getAsString().c_str(), arg
);
892 /* Construct a pet_expr representing an integer.
894 __isl_give pet_expr
*PetScan::extract_expr(IntegerLiteral
*expr
)
896 return pet_expr_new_int(extract_int(expr
));
899 /* Construct a pet_expr representing the integer enum constant "ecd".
901 __isl_give pet_expr
*PetScan::extract_expr(EnumConstantDecl
*ecd
)
904 const llvm::APSInt
&init
= ecd
->getInitVal();
905 v
= ::extract_int(ctx
, init
.isSigned(), init
);
906 return pet_expr_new_int(v
);
909 /* Try and construct a pet_expr representing "expr".
911 __isl_give pet_expr
*PetScan::extract_expr(Expr
*expr
)
913 switch (expr
->getStmtClass()) {
914 case Stmt::UnaryOperatorClass
:
915 return extract_expr(cast
<UnaryOperator
>(expr
));
916 case Stmt::CompoundAssignOperatorClass
:
917 case Stmt::BinaryOperatorClass
:
918 return extract_expr(cast
<BinaryOperator
>(expr
));
919 case Stmt::ImplicitCastExprClass
:
920 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
921 case Stmt::ArraySubscriptExprClass
:
922 case Stmt::DeclRefExprClass
:
923 case Stmt::MemberExprClass
:
924 return extract_access_expr(expr
);
925 case Stmt::IntegerLiteralClass
:
926 return extract_expr(cast
<IntegerLiteral
>(expr
));
927 case Stmt::FloatingLiteralClass
:
928 return extract_expr(cast
<FloatingLiteral
>(expr
));
929 case Stmt::ParenExprClass
:
930 return extract_expr(cast
<ParenExpr
>(expr
));
931 case Stmt::ConditionalOperatorClass
:
932 return extract_expr(cast
<ConditionalOperator
>(expr
));
933 case Stmt::CallExprClass
:
934 return extract_expr(cast
<CallExpr
>(expr
));
935 case Stmt::CStyleCastExprClass
:
936 return extract_expr(cast
<CStyleCastExpr
>(expr
));
943 /* Check if the given initialization statement is an assignment.
944 * If so, return that assignment. Otherwise return NULL.
946 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
950 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
953 ass
= cast
<BinaryOperator
>(init
);
954 if (ass
->getOpcode() != BO_Assign
)
960 /* Check if the given initialization statement is a declaration
961 * of a single variable.
962 * If so, return that declaration. Otherwise return NULL.
964 Decl
*PetScan::initialization_declaration(Stmt
*init
)
968 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
971 decl
= cast
<DeclStmt
>(init
);
973 if (!decl
->isSingleDecl())
976 return decl
->getSingleDecl();
979 /* Given the assignment operator in the initialization of a for loop,
980 * extract the induction variable, i.e., the (integer)variable being
983 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
990 lhs
= init
->getLHS();
991 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
996 ref
= cast
<DeclRefExpr
>(lhs
);
997 decl
= ref
->getDecl();
998 type
= decl
->getType().getTypePtr();
1000 if (!type
->isIntegerType()) {
1008 /* Given the initialization statement of a for loop and the single
1009 * declaration in this initialization statement,
1010 * extract the induction variable, i.e., the (integer) variable being
1013 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1017 vd
= cast
<VarDecl
>(decl
);
1019 const QualType type
= vd
->getType();
1020 if (!type
->isIntegerType()) {
1025 if (!vd
->getInit()) {
1033 /* Check that op is of the form iv++ or iv--.
1034 * Return a pet_expr representing "1" or "-1" accordingly.
1036 __isl_give pet_expr
*PetScan::extract_unary_increment(
1037 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1043 if (!op
->isIncrementDecrementOp()) {
1048 sub
= op
->getSubExpr();
1049 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1054 ref
= cast
<DeclRefExpr
>(sub
);
1055 if (ref
->getDecl() != iv
) {
1060 if (op
->isIncrementOp())
1061 v
= isl_val_one(ctx
);
1063 v
= isl_val_negone(ctx
);
1065 return pet_expr_new_int(v
);
1068 /* Check if op is of the form
1072 * and return the increment "expr - iv" as a pet_expr.
1074 __isl_give pet_expr
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1075 clang::ValueDecl
*iv
)
1080 pet_expr
*expr
, *expr_iv
;
1082 if (op
->getOpcode() != BO_Assign
) {
1088 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1093 ref
= cast
<DeclRefExpr
>(lhs
);
1094 if (ref
->getDecl() != iv
) {
1099 expr
= extract_expr(op
->getRHS());
1100 expr_iv
= extract_expr(lhs
);
1102 type_size
= get_type_size(iv
->getType(), ast_context
);
1103 return pet_expr_new_binary(type_size
, pet_op_sub
, expr
, expr_iv
);
1106 /* Check that op is of the form iv += cst or iv -= cst
1107 * and return a pet_expr corresponding to cst or -cst accordingly.
1109 __isl_give pet_expr
*PetScan::extract_compound_increment(
1110 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1116 BinaryOperatorKind opcode
;
1118 opcode
= op
->getOpcode();
1119 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1123 if (opcode
== BO_SubAssign
)
1127 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1132 ref
= cast
<DeclRefExpr
>(lhs
);
1133 if (ref
->getDecl() != iv
) {
1138 expr
= extract_expr(op
->getRHS());
1140 expr
= pet_expr_new_unary(pet_op_minus
, expr
);
1145 /* Check that the increment of the given for loop increments
1146 * (or decrements) the induction variable "iv" and return
1147 * the increment as a pet_expr if successful.
1149 __isl_give pet_expr
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1152 Stmt
*inc
= stmt
->getInc();
1155 report_missing_increment(stmt
);
1159 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1160 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1161 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1162 return extract_compound_increment(
1163 cast
<CompoundAssignOperator
>(inc
), iv
);
1164 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1165 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1171 /* Construct a pet_tree for a while loop.
1173 * If we were only able to extract part of the body, then simply
1176 __isl_give pet_tree
*PetScan::extract(WhileStmt
*stmt
)
1181 tree
= extract(stmt
->getBody());
1184 pe_cond
= extract_expr(stmt
->getCond());
1185 tree
= pet_tree_new_while(pe_cond
, tree
);
1190 /* Construct a pet_tree for a for statement.
1191 * The for loop is required to be of one of the following forms
1193 * for (i = init; condition; ++i)
1194 * for (i = init; condition; --i)
1195 * for (i = init; condition; i += constant)
1196 * for (i = init; condition; i -= constant)
1198 * We extract a pet_tree for the body and then include it in a pet_tree
1199 * of type pet_tree_for.
1201 * As a special case, we also allow a for loop of the form
1205 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1207 * If we were only able to extract part of the body, then simply
1210 __isl_give pet_tree
*PetScan::extract_for(ForStmt
*stmt
)
1212 BinaryOperator
*ass
;
1218 struct pet_scop
*scop
;
1221 pet_expr
*pe_init
, *pe_inc
, *pe_iv
, *pe_cond
;
1223 independent
= is_current_stmt_marked_independent();
1225 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc()) {
1226 tree
= extract(stmt
->getBody());
1229 tree
= pet_tree_new_infinite_loop(tree
);
1233 init
= stmt
->getInit();
1238 if ((ass
= initialization_assignment(init
)) != NULL
) {
1239 iv
= extract_induction_variable(ass
);
1242 lhs
= ass
->getLHS();
1243 rhs
= ass
->getRHS();
1244 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
1245 VarDecl
*var
= extract_induction_variable(init
, decl
);
1249 rhs
= var
->getInit();
1250 lhs
= create_DeclRefExpr(var
);
1252 unsupported(stmt
->getInit());
1256 declared
= !initialization_assignment(stmt
->getInit());
1257 tree
= extract(stmt
->getBody());
1260 pe_iv
= extract_access_expr(iv
);
1261 pe_iv
= mark_write(pe_iv
);
1262 pe_init
= extract_expr(rhs
);
1263 if (!stmt
->getCond())
1264 pe_cond
= pet_expr_new_int(isl_val_one(ctx
));
1266 pe_cond
= extract_expr(stmt
->getCond());
1267 pe_inc
= extract_increment(stmt
, iv
);
1268 tree
= pet_tree_new_for(independent
, declared
, pe_iv
, pe_init
, pe_cond
,
1273 /* Try and construct a pet_tree corresponding to a compound statement.
1275 * "skip_declarations" is set if we should skip initial declarations
1276 * in the children of the compound statements. This then implies
1277 * that this sequence of children should not be treated as a block
1278 * since the initial statements may be skipped.
1280 __isl_give pet_tree
*PetScan::extract(CompoundStmt
*stmt
,
1281 bool skip_declarations
)
1283 return extract(stmt
->children(), !skip_declarations
, skip_declarations
);
1286 /* Return the file offset of the expansion location of "Loc".
1288 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
1290 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
1293 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1295 /* Return a SourceLocation for the location after the first semicolon
1296 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1297 * call it and also skip trailing spaces and newline.
1299 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
1300 const LangOptions
&LO
)
1302 return Lexer::findLocationAfterToken(loc
, tok::semi
, SM
, LO
, true);
1307 /* Return a SourceLocation for the location after the first semicolon
1308 * after "loc". If Lexer::findLocationAfterToken is not available,
1309 * we look in the underlying character data for the first semicolon.
1311 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
1312 const LangOptions
&LO
)
1315 const char *s
= SM
.getCharacterData(loc
);
1317 semi
= strchr(s
, ';');
1319 return SourceLocation();
1320 return loc
.getFileLocWithOffset(semi
+ 1 - s
);
1325 /* If the token at "loc" is the first token on the line, then return
1326 * a location referring to the start of the line and set *indent
1327 * to the indentation of "loc"
1328 * Otherwise, return "loc" and set *indent to "".
1330 * This function is used to extend a scop to the start of the line
1331 * if the first token of the scop is also the first token on the line.
1333 * We look for the first token on the line. If its location is equal to "loc",
1334 * then the latter is the location of the first token on the line.
1336 static SourceLocation
move_to_start_of_line_if_first_token(SourceLocation loc
,
1337 SourceManager
&SM
, const LangOptions
&LO
, char **indent
)
1339 std::pair
<FileID
, unsigned> file_offset_pair
;
1340 llvm::StringRef file
;
1343 SourceLocation token_loc
, line_loc
;
1347 loc
= SM
.getExpansionLoc(loc
);
1348 col
= SM
.getExpansionColumnNumber(loc
);
1349 line_loc
= loc
.getLocWithOffset(1 - col
);
1350 file_offset_pair
= SM
.getDecomposedLoc(line_loc
);
1351 file
= SM
.getBufferData(file_offset_pair
.first
, NULL
);
1352 pos
= file
.data() + file_offset_pair
.second
;
1354 Lexer
lexer(SM
.getLocForStartOfFile(file_offset_pair
.first
), LO
,
1355 file
.begin(), pos
, file
.end());
1356 lexer
.LexFromRawLexer(tok
);
1357 token_loc
= tok
.getLocation();
1359 s
= SM
.getCharacterData(line_loc
);
1360 *indent
= strndup(s
, token_loc
== loc
? col
- 1 : 0);
1362 if (token_loc
== loc
)
1368 /* Construct a pet_loc corresponding to the region covered by "range".
1369 * If "skip_semi" is set, then we assume "range" is followed by
1370 * a semicolon and also include this semicolon.
1372 __isl_give pet_loc
*PetScan::construct_pet_loc(SourceRange range
,
1375 SourceLocation loc
= range
.getBegin();
1376 SourceManager
&SM
= PP
.getSourceManager();
1377 const LangOptions
&LO
= PP
.getLangOpts();
1378 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
1379 unsigned start
, end
;
1382 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
, &indent
);
1383 start
= getExpansionOffset(SM
, loc
);
1384 loc
= range
.getEnd();
1386 loc
= location_after_semi(loc
, SM
, LO
);
1388 loc
= PP
.getLocForEndOfToken(loc
);
1389 end
= getExpansionOffset(SM
, loc
);
1391 return pet_loc_alloc(ctx
, start
, end
, line
, indent
);
1394 /* Convert a top-level pet_expr to an expression pet_tree.
1396 __isl_give pet_tree
*PetScan::extract(__isl_take pet_expr
*expr
,
1397 SourceRange range
, bool skip_semi
)
1402 tree
= pet_tree_new_expr(expr
);
1403 loc
= construct_pet_loc(range
, skip_semi
);
1404 tree
= pet_tree_set_loc(tree
, loc
);
1409 /* Construct a pet_tree for an if statement.
1411 __isl_give pet_tree
*PetScan::extract(IfStmt
*stmt
)
1414 pet_tree
*tree
, *tree_else
;
1415 struct pet_scop
*scop
;
1418 pe_cond
= extract_expr(stmt
->getCond());
1419 tree
= extract(stmt
->getThen());
1420 if (stmt
->getElse()) {
1421 tree_else
= extract(stmt
->getElse());
1422 if (options
->autodetect
) {
1423 if (tree
&& !tree_else
) {
1425 pet_expr_free(pe_cond
);
1428 if (!tree
&& tree_else
) {
1430 pet_expr_free(pe_cond
);
1434 tree
= pet_tree_new_if_else(pe_cond
, tree
, tree_else
);
1436 tree
= pet_tree_new_if(pe_cond
, tree
);
1440 /* Try and construct a pet_tree for a label statement.
1441 * We currently only allow labels on expression statements.
1443 __isl_give pet_tree
*PetScan::extract(LabelStmt
*stmt
)
1449 sub
= stmt
->getSubStmt();
1450 if (!isa
<Expr
>(sub
)) {
1455 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
1457 tree
= extract(extract_expr(cast
<Expr
>(sub
)), stmt
->getSourceRange(),
1459 tree
= pet_tree_set_label(tree
, label
);
1463 /* Update the location of "tree" to include the source range of "stmt".
1465 * Actually, we create a new location based on the source range of "stmt" and
1466 * then extend this new location to include the region of the original location.
1467 * This ensures that the line number of the final location refers to "stmt".
1469 __isl_give pet_tree
*PetScan::update_loc(__isl_take pet_tree
*tree
, Stmt
*stmt
)
1471 pet_loc
*loc
, *tree_loc
;
1473 tree_loc
= pet_tree_get_loc(tree
);
1474 loc
= construct_pet_loc(stmt
->getSourceRange(), false);
1475 loc
= pet_loc_update_start_end_from_loc(loc
, tree_loc
);
1476 pet_loc_free(tree_loc
);
1478 tree
= pet_tree_set_loc(tree
, loc
);
1482 /* Try and construct a pet_tree corresponding to "stmt".
1484 * If "stmt" is a compound statement, then "skip_declarations"
1485 * indicates whether we should skip initial declarations in the
1486 * compound statement.
1488 * If the constructed pet_tree is not a (possibly) partial representation
1489 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1490 * In particular, if skip_declarations is set, then we may have skipped
1491 * declarations inside "stmt" and so the pet_scop may not represent
1492 * the entire "stmt".
1493 * Note that this function may be called with "stmt" referring to the entire
1494 * body of the function, including the outer braces. In such cases,
1495 * skip_declarations will be set and the braces will not be taken into
1496 * account in tree->loc.
1498 __isl_give pet_tree
*PetScan::extract(Stmt
*stmt
, bool skip_declarations
)
1502 set_current_stmt(stmt
);
1504 if (isa
<Expr
>(stmt
))
1505 return extract(extract_expr(cast
<Expr
>(stmt
)),
1506 stmt
->getSourceRange(), true);
1508 switch (stmt
->getStmtClass()) {
1509 case Stmt::WhileStmtClass
:
1510 tree
= extract(cast
<WhileStmt
>(stmt
));
1512 case Stmt::ForStmtClass
:
1513 tree
= extract_for(cast
<ForStmt
>(stmt
));
1515 case Stmt::IfStmtClass
:
1516 tree
= extract(cast
<IfStmt
>(stmt
));
1518 case Stmt::CompoundStmtClass
:
1519 tree
= extract(cast
<CompoundStmt
>(stmt
), skip_declarations
);
1521 case Stmt::LabelStmtClass
:
1522 tree
= extract(cast
<LabelStmt
>(stmt
));
1524 case Stmt::ContinueStmtClass
:
1525 tree
= pet_tree_new_continue(ctx
);
1527 case Stmt::BreakStmtClass
:
1528 tree
= pet_tree_new_break(ctx
);
1530 case Stmt::DeclStmtClass
:
1531 tree
= extract(cast
<DeclStmt
>(stmt
));
1538 if (partial
|| skip_declarations
)
1541 return update_loc(tree
, stmt
);
1544 /* Try and construct a pet_tree corresponding to (part of)
1545 * a sequence of statements.
1547 * "block" is set if the sequence represents the children of
1548 * a compound statement.
1549 * "skip_declarations" is set if we should skip initial declarations
1550 * in the sequence of statements.
1552 * If autodetect is set, then we allow the extraction of only a subrange
1553 * of the sequence of statements. However, if there is at least one statement
1554 * for which we could not construct a scop and the final range contains
1555 * either no statements or at least one kill, then we discard the entire
1558 __isl_give pet_tree
*PetScan::extract(StmtRange stmt_range
, bool block
,
1559 bool skip_declarations
)
1563 bool has_kills
= false;
1564 bool partial_range
= false;
1566 set
<struct pet_stmt
*> kills
;
1567 set
<struct pet_stmt
*>::iterator it
;
1569 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
)
1572 tree
= pet_tree_new_block(ctx
, block
, j
);
1574 for (i
= stmt_range
.first
; i
!= stmt_range
.second
; ++i
) {
1578 if (pet_tree_block_n_child(tree
) == 0 && skip_declarations
&&
1579 child
->getStmtClass() == Stmt::DeclStmtClass
)
1582 tree_i
= extract(child
);
1583 if (pet_tree_block_n_child(tree
) != 0 && partial
) {
1584 pet_tree_free(tree_i
);
1587 if (tree_i
&& child
->getStmtClass() == Stmt::DeclStmtClass
&&
1590 if (options
->autodetect
) {
1592 tree
= pet_tree_block_add_child(tree
, tree_i
);
1594 partial_range
= true;
1595 if (pet_tree_block_n_child(tree
) != 0 && !tree_i
)
1598 tree
= pet_tree_block_add_child(tree
, tree_i
);
1601 if (partial
|| !tree
)
1605 if (tree
&& partial_range
) {
1606 if (pet_tree_block_n_child(tree
) == 0 || has_kills
) {
1607 pet_tree_free(tree
);
1616 /* Is "T" the type of a variable length array with static size?
1618 static bool is_vla_with_static_size(QualType T
)
1620 const VariableArrayType
*vlatype
;
1622 if (!T
->isVariableArrayType())
1624 vlatype
= cast
<VariableArrayType
>(T
);
1625 return vlatype
->getSizeModifier() == VariableArrayType::Static
;
1628 /* Return the type of "decl" as an array.
1630 * In particular, if "decl" is a parameter declaration that
1631 * is a variable length array with a static size, then
1632 * return the original type (i.e., the variable length array).
1633 * Otherwise, return the type of decl.
1635 static QualType
get_array_type(ValueDecl
*decl
)
1640 parm
= dyn_cast
<ParmVarDecl
>(decl
);
1642 return decl
->getType();
1644 T
= parm
->getOriginalType();
1645 if (!is_vla_with_static_size(T
))
1646 return decl
->getType();
1651 static __isl_give pet_expr
*get_array_size(__isl_keep pet_expr
*access
,
1653 static struct pet_array
*extract_array(__isl_keep pet_expr
*access
,
1654 __isl_keep pet_context
*pc
, void *user
);
1657 /* Construct a pet_expr that holds the sizes of the array accessed
1659 * This function is used as a callback to pet_context_add_parameters,
1660 * which is also passed a pointer to the PetScan object.
1662 static __isl_give pet_expr
*get_array_size(__isl_keep pet_expr
*access
,
1665 PetScan
*ps
= (PetScan
*) user
;
1670 id
= pet_expr_access_get_id(access
);
1671 decl
= (ValueDecl
*) isl_id_get_user(id
);
1673 type
= get_array_type(decl
).getTypePtr();
1674 return ps
->get_array_size(type
);
1677 /* Construct and return a pet_array corresponding to the variable
1678 * accessed by "access".
1679 * This function is used as a callback to pet_scop_from_pet_tree,
1680 * which is also passed a pointer to the PetScan object.
1682 static struct pet_array
*extract_array(__isl_keep pet_expr
*access
,
1683 __isl_keep pet_context
*pc
, void *user
)
1685 PetScan
*ps
= (PetScan
*) user
;
1690 ctx
= pet_expr_get_ctx(access
);
1691 id
= pet_expr_access_get_id(access
);
1692 iv
= (ValueDecl
*) isl_id_get_user(id
);
1694 return ps
->extract_array(ctx
, iv
, NULL
, pc
);
1697 /* Extract a function summary from the body of "fd".
1699 * We extract a scop from the function body in a context with as
1700 * parameters the integer arguments of the function.
1701 * We turn off autodetection (in case it was set) to ensure that
1702 * the entire function body is considered.
1703 * We then collect the accessed array elements and attach them
1704 * to the corresponding array arguments, taking into account
1705 * that the function body may access members of array elements.
1707 * The reason for representing the integer arguments as parameters in
1708 * the context is that if we were to instead start with a context
1709 * with the function arguments as initial dimensions, then we would not
1710 * be able to refer to them from the array extents, without turning
1711 * array extents into maps.
1713 * The result is stored in the summary_cache cache so that we can reuse
1714 * it if this method gets called on the same function again later on.
1716 __isl_give pet_function_summary
*PetScan::get_summary(FunctionDecl
*fd
)
1722 pet_function_summary
*summary
;
1725 int save_autodetect
;
1726 struct pet_scop
*scop
;
1728 isl_union_set
*may_read
, *may_write
, *must_write
;
1729 isl_union_map
*to_inner
;
1731 if (summary_cache
.find(fd
) != summary_cache
.end())
1732 return pet_function_summary_copy(summary_cache
[fd
]);
1734 space
= isl_space_set_alloc(ctx
, 0, 0);
1736 n
= fd
->getNumParams();
1737 summary
= pet_function_summary_alloc(ctx
, n
);
1738 for (int i
= 0; i
< n
; ++i
) {
1739 ParmVarDecl
*parm
= fd
->getParamDecl(i
);
1740 QualType type
= parm
->getType();
1743 if (!type
->isIntegerType())
1745 id
= create_decl_id(ctx
, parm
);
1746 space
= isl_space_insert_dims(space
, isl_dim_param
, 0, 1);
1747 space
= isl_space_set_dim_id(space
, isl_dim_param
, 0,
1749 summary
= pet_function_summary_set_int(summary
, i
, id
);
1752 save_autodetect
= options
->autodetect
;
1753 options
->autodetect
= 0;
1754 PetScan
body_scan(PP
, ast_context
, loc
, options
,
1755 isl_union_map_copy(value_bounds
), independent
);
1757 tree
= body_scan
.extract(fd
->getBody(), false);
1759 domain
= isl_set_universe(space
);
1760 pc
= pet_context_alloc(domain
);
1761 pc
= pet_context_add_parameters(pc
, tree
,
1762 &::get_array_size
, &body_scan
);
1763 int_size
= ast_context
.getTypeInfo(ast_context
.IntTy
).first
/ 8;
1764 scop
= pet_scop_from_pet_tree(tree
, int_size
,
1765 &::extract_array
, &body_scan
, pc
);
1766 scop
= scan_arrays(scop
, pc
);
1767 may_read
= isl_union_map_range(pet_scop_collect_may_reads(scop
));
1768 may_write
= isl_union_map_range(pet_scop_collect_may_writes(scop
));
1769 must_write
= isl_union_map_range(pet_scop_collect_must_writes(scop
));
1770 to_inner
= pet_scop_compute_outer_to_inner(scop
);
1771 pet_scop_free(scop
);
1773 for (int i
= 0; i
< n
; ++i
) {
1774 ParmVarDecl
*parm
= fd
->getParamDecl(i
);
1775 QualType type
= parm
->getType();
1776 struct pet_array
*array
;
1778 isl_union_set
*data_set
;
1779 isl_union_set
*may_read_i
, *may_write_i
, *must_write_i
;
1781 if (array_depth(type
.getTypePtr()) == 0)
1784 array
= body_scan
.extract_array(ctx
, parm
, NULL
, pc
);
1785 space
= array
? isl_set_get_space(array
->extent
) : NULL
;
1786 pet_array_free(array
);
1787 data_set
= isl_union_set_from_set(isl_set_universe(space
));
1788 data_set
= isl_union_set_apply(data_set
,
1789 isl_union_map_copy(to_inner
));
1790 may_read_i
= isl_union_set_intersect(
1791 isl_union_set_copy(may_read
),
1792 isl_union_set_copy(data_set
));
1793 may_write_i
= isl_union_set_intersect(
1794 isl_union_set_copy(may_write
),
1795 isl_union_set_copy(data_set
));
1796 must_write_i
= isl_union_set_intersect(
1797 isl_union_set_copy(must_write
), data_set
);
1798 summary
= pet_function_summary_set_array(summary
, i
,
1799 may_read_i
, may_write_i
, must_write_i
);
1802 isl_union_set_free(may_read
);
1803 isl_union_set_free(may_write
);
1804 isl_union_set_free(must_write
);
1805 isl_union_map_free(to_inner
);
1807 options
->autodetect
= save_autodetect
;
1808 pet_context_free(pc
);
1810 summary_cache
[fd
] = pet_function_summary_copy(summary
);
1815 /* If "fd" has a function body, then extract a function summary from
1816 * this body and attach it to the call expression "expr".
1818 * Even if a function body is available, "fd" itself may point
1819 * to a declaration without function body. We therefore first
1820 * replace it by the declaration that comes with a body (if any).
1822 * It is not clear why hasBody takes a reference to a const FunctionDecl *.
1823 * It seems that it is possible to directly use the iterators to obtain
1824 * a non-const pointer.
1825 * Since we are not going to use the pointer to modify anything anyway,
1826 * it seems safe to drop the constness. The alternative would be to
1827 * modify a lot of other functions to include const qualifiers.
1829 __isl_give pet_expr
*PetScan::set_summary(__isl_take pet_expr
*expr
,
1832 pet_function_summary
*summary
;
1833 const FunctionDecl
*def
;
1837 if (!fd
->hasBody(def
))
1840 fd
= const_cast<FunctionDecl
*>(def
);
1842 summary
= get_summary(fd
);
1844 expr
= pet_expr_call_set_summary(expr
, summary
);
1849 /* Extract a pet_scop from "tree".
1851 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
1852 * then add pet_arrays for all accessed arrays.
1853 * We populate the pet_context with assignments for all parameters used
1854 * inside "tree" or any of the size expressions for the arrays accessed
1855 * by "tree" so that they can be used in affine expressions.
1857 struct pet_scop
*PetScan::extract_scop(__isl_take pet_tree
*tree
)
1864 int_size
= ast_context
.getTypeInfo(ast_context
.IntTy
).first
/ 8;
1866 domain
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
1867 pc
= pet_context_alloc(domain
);
1868 pc
= pet_context_add_parameters(pc
, tree
, &::get_array_size
, this);
1869 scop
= pet_scop_from_pet_tree(tree
, int_size
,
1870 &::extract_array
, this, pc
);
1871 scop
= scan_arrays(scop
, pc
);
1872 pet_context_free(pc
);
1877 /* Check if the scop marked by the user is exactly this Stmt
1878 * or part of this Stmt.
1879 * If so, return a pet_scop corresponding to the marked region.
1880 * Otherwise, return NULL.
1882 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
1884 SourceManager
&SM
= PP
.getSourceManager();
1885 unsigned start_off
, end_off
;
1887 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
1888 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
1890 if (start_off
> loc
.end
)
1892 if (end_off
< loc
.start
)
1895 if (start_off
>= loc
.start
&& end_off
<= loc
.end
)
1896 return extract_scop(extract(stmt
));
1899 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
1900 Stmt
*child
= *start
;
1903 start_off
= getExpansionOffset(SM
, child
->getLocStart());
1904 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
1905 if (start_off
< loc
.start
&& end_off
>= loc
.end
)
1907 if (start_off
>= loc
.start
)
1912 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
1914 start_off
= SM
.getFileOffset(child
->getLocStart());
1915 if (start_off
>= loc
.end
)
1919 return extract_scop(extract(StmtRange(start
, end
), false, false));
1922 /* Set the size of index "pos" of "array" to "size".
1923 * In particular, add a constraint of the form
1927 * to array->extent and a constraint of the form
1931 * to array->context.
1933 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
1934 __isl_take isl_pw_aff
*size
)
1947 valid
= isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
)));
1948 array
->context
= isl_set_intersect(array
->context
, valid
);
1950 dim
= isl_set_get_space(array
->extent
);
1951 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1952 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
1953 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
1954 index
= isl_pw_aff_alloc(univ
, aff
);
1956 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
1957 isl_set_dim(array
->extent
, isl_dim_set
));
1958 id
= isl_set_get_tuple_id(array
->extent
);
1959 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
1960 bound
= isl_pw_aff_lt_set(index
, size
);
1962 array
->extent
= isl_set_intersect(array
->extent
, bound
);
1964 if (!array
->context
|| !array
->extent
)
1965 return pet_array_free(array
);
1969 isl_pw_aff_free(size
);
1973 #ifdef HAVE_DECAYEDTYPE
1975 /* If "type" is a decayed type, then set *decayed to true and
1976 * return the original type.
1978 static const Type
*undecay(const Type
*type
, bool *decayed
)
1980 *decayed
= isa
<DecayedType
>(type
);
1982 type
= cast
<DecayedType
>(type
)->getOriginalType().getTypePtr();
1988 /* If "type" is a decayed type, then set *decayed to true and
1989 * return the original type.
1990 * Since this version of clang does not define a DecayedType,
1991 * we cannot obtain the original type even if it had been decayed and
1992 * we set *decayed to false.
1994 static const Type
*undecay(const Type
*type
, bool *decayed
)
2002 /* Figure out the size of the array at position "pos" and all
2003 * subsequent positions from "type" and update the corresponding
2004 * argument of "expr" accordingly.
2006 * The initial type (when pos is zero) may be a pointer type decayed
2007 * from an array type, if this initial type is the type of a function
2008 * argument. This only happens if the original array type has
2009 * a constant size in the outer dimension as otherwise we get
2010 * a VariableArrayType. Try and obtain this original type (if available) and
2011 * take the outer array size into account if it was marked static.
2013 __isl_give pet_expr
*PetScan::set_upper_bounds(__isl_take pet_expr
*expr
,
2014 const Type
*type
, int pos
)
2016 const ArrayType
*atype
;
2018 bool decayed
= false;
2024 type
= undecay(type
, &decayed
);
2026 if (type
->isPointerType()) {
2027 type
= type
->getPointeeType().getTypePtr();
2028 return set_upper_bounds(expr
, type
, pos
+ 1);
2030 if (!type
->isArrayType())
2033 type
= type
->getCanonicalTypeInternal().getTypePtr();
2034 atype
= cast
<ArrayType
>(type
);
2036 if (decayed
&& atype
->getSizeModifier() != ArrayType::Static
) {
2037 type
= atype
->getElementType().getTypePtr();
2038 return set_upper_bounds(expr
, type
, pos
+ 1);
2041 if (type
->isConstantArrayType()) {
2042 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
2043 size
= extract_expr(ca
->getSize());
2044 expr
= pet_expr_set_arg(expr
, pos
, size
);
2045 } else if (type
->isVariableArrayType()) {
2046 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
2047 size
= extract_expr(vla
->getSizeExpr());
2048 expr
= pet_expr_set_arg(expr
, pos
, size
);
2051 type
= atype
->getElementType().getTypePtr();
2053 return set_upper_bounds(expr
, type
, pos
+ 1);
2056 /* Construct a pet_expr that holds the sizes of an array of the given type.
2057 * The returned expression is a call expression with as arguments
2058 * the sizes in each dimension. If we are unable to derive the size
2059 * in a given dimension, then the corresponding argument is set to infinity.
2060 * In fact, we initialize all arguments to infinity and then update
2061 * them if we are able to figure out the size.
2063 * The result is stored in the type_size cache so that we can reuse
2064 * it if this method gets called on the same type again later on.
2066 __isl_give pet_expr
*PetScan::get_array_size(const Type
*type
)
2069 pet_expr
*expr
, *inf
;
2071 if (type_size
.find(type
) != type_size
.end())
2072 return pet_expr_copy(type_size
[type
]);
2074 depth
= array_depth(type
);
2075 inf
= pet_expr_new_int(isl_val_infty(ctx
));
2076 expr
= pet_expr_new_call(ctx
, "bounds", depth
);
2077 for (int i
= 0; i
< depth
; ++i
)
2078 expr
= pet_expr_set_arg(expr
, i
, pet_expr_copy(inf
));
2081 expr
= set_upper_bounds(expr
, type
, 0);
2082 type_size
[type
] = pet_expr_copy(expr
);
2087 /* Does "expr" represent the "integer" infinity?
2089 static int is_infty(__isl_keep pet_expr
*expr
)
2094 if (pet_expr_get_type(expr
) != pet_expr_int
)
2096 v
= pet_expr_int_get_val(expr
);
2097 res
= isl_val_is_infty(v
);
2103 /* Figure out the dimensions of an array "array" based on its type
2104 * "type" and update "array" accordingly.
2106 * We first construct a pet_expr that holds the sizes of the array
2107 * in each dimension. The resulting expression may containing
2108 * infinity values for dimension where we are unable to derive
2109 * a size expression.
2111 * The arguments of the size expression that have a value different from
2112 * infinity are then converted to an affine expression
2113 * within the context "pc" and incorporated into the size of "array".
2114 * If we are unable to convert a size expression to an affine expression,
2115 * then we leave the corresponding size of "array" untouched.
2117 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
2118 const Type
*type
, __isl_keep pet_context
*pc
)
2126 expr
= get_array_size(type
);
2128 n
= pet_expr_get_n_arg(expr
);
2129 for (int i
= 0; i
< n
; ++i
) {
2133 arg
= pet_expr_get_arg(expr
, i
);
2134 if (!is_infty(arg
)) {
2135 size
= pet_expr_extract_affine(arg
, pc
);
2137 array
= pet_array_free(array
);
2138 else if (isl_pw_aff_involves_nan(size
))
2139 isl_pw_aff_free(size
);
2141 array
= update_size(array
, i
, size
);
2145 pet_expr_free(expr
);
2150 /* Does "decl" have definition that we can keep track of in a pet_type?
2152 static bool has_printable_definition(RecordDecl
*decl
)
2154 if (!decl
->getDeclName())
2156 return decl
->getLexicalDeclContext() == decl
->getDeclContext();
2159 /* Construct and return a pet_array corresponding to the variable "decl".
2160 * In particular, initialize array->extent to
2162 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2164 * and then call set_upper_bounds to set the upper bounds on the indices
2165 * based on the type of the variable. The upper bounds are converted
2166 * to affine expressions within the context "pc".
2168 * If the base type is that of a record with a top-level definition and
2169 * if "types" is not null, then the RecordDecl corresponding to the type
2170 * is added to "types".
2172 * If the base type is that of a record with no top-level definition,
2173 * then we replace it by "<subfield>".
2175 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
,
2176 lex_recorddecl_set
*types
, __isl_keep pet_context
*pc
)
2178 struct pet_array
*array
;
2179 QualType qt
= get_array_type(decl
);
2180 const Type
*type
= qt
.getTypePtr();
2181 int depth
= array_depth(type
);
2182 QualType base
= pet_clang_base_type(qt
);
2187 array
= isl_calloc_type(ctx
, struct pet_array
);
2191 id
= create_decl_id(ctx
, decl
);
2192 dim
= isl_space_set_alloc(ctx
, 0, depth
);
2193 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
2195 array
->extent
= isl_set_nat_universe(dim
);
2197 dim
= isl_space_params_alloc(ctx
, 0);
2198 array
->context
= isl_set_universe(dim
);
2200 array
= set_upper_bounds(array
, type
, pc
);
2204 name
= base
.getAsString();
2206 if (types
&& base
->isRecordType()) {
2207 RecordDecl
*decl
= pet_clang_record_decl(base
);
2208 if (has_printable_definition(decl
))
2209 types
->insert(decl
);
2211 name
= "<subfield>";
2214 array
->element_type
= strdup(name
.c_str());
2215 array
->element_is_record
= base
->isRecordType();
2216 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
2221 /* Construct and return a pet_array corresponding to the sequence
2222 * of declarations "decls".
2223 * The upper bounds of the array are converted to affine expressions
2224 * within the context "pc".
2225 * If the sequence contains a single declaration, then it corresponds
2226 * to a simple array access. Otherwise, it corresponds to a member access,
2227 * with the declaration for the substructure following that of the containing
2228 * structure in the sequence of declarations.
2229 * We start with the outermost substructure and then combine it with
2230 * information from the inner structures.
2232 * Additionally, keep track of all required types in "types".
2234 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
,
2235 vector
<ValueDecl
*> decls
, lex_recorddecl_set
*types
,
2236 __isl_keep pet_context
*pc
)
2238 struct pet_array
*array
;
2239 vector
<ValueDecl
*>::iterator it
;
2243 array
= extract_array(ctx
, *it
, types
, pc
);
2245 for (++it
; it
!= decls
.end(); ++it
) {
2246 struct pet_array
*parent
;
2247 const char *base_name
, *field_name
;
2251 array
= extract_array(ctx
, *it
, types
, pc
);
2253 return pet_array_free(parent
);
2255 base_name
= isl_set_get_tuple_name(parent
->extent
);
2256 field_name
= isl_set_get_tuple_name(array
->extent
);
2257 product_name
= pet_array_member_access_name(ctx
,
2258 base_name
, field_name
);
2260 array
->extent
= isl_set_product(isl_set_copy(parent
->extent
),
2263 array
->extent
= isl_set_set_tuple_name(array
->extent
,
2265 array
->context
= isl_set_intersect(array
->context
,
2266 isl_set_copy(parent
->context
));
2268 pet_array_free(parent
);
2271 if (!array
->extent
|| !array
->context
|| !product_name
)
2272 return pet_array_free(array
);
2278 /* Add a pet_type corresponding to "decl" to "scop, provided
2279 * it is a member of "types" and it has not been added before
2280 * (i.e., it is not a member of "types_done".
2282 * Since we want the user to be able to print the types
2283 * in the order in which they appear in the scop, we need to
2284 * make sure that types of fields in a structure appear before
2285 * that structure. We therefore call ourselves recursively
2286 * on the types of all record subfields.
2288 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
2289 RecordDecl
*decl
, Preprocessor
&PP
, lex_recorddecl_set
&types
,
2290 lex_recorddecl_set
&types_done
)
2293 llvm::raw_string_ostream
S(s
);
2294 RecordDecl::field_iterator it
;
2296 if (types
.find(decl
) == types
.end())
2298 if (types_done
.find(decl
) != types_done
.end())
2301 for (it
= decl
->field_begin(); it
!= decl
->field_end(); ++it
) {
2303 QualType type
= it
->getType();
2305 if (!type
->isRecordType())
2307 record
= pet_clang_record_decl(type
);
2308 scop
= add_type(ctx
, scop
, record
, PP
, types
, types_done
);
2311 if (strlen(decl
->getName().str().c_str()) == 0)
2314 decl
->print(S
, PrintingPolicy(PP
.getLangOpts()));
2317 scop
->types
[scop
->n_type
] = pet_type_alloc(ctx
,
2318 decl
->getName().str().c_str(), s
.c_str());
2319 if (!scop
->types
[scop
->n_type
])
2320 return pet_scop_free(scop
);
2322 types_done
.insert(decl
);
2329 /* Construct a list of pet_arrays, one for each array (or scalar)
2330 * accessed inside "scop", add this list to "scop" and return the result.
2331 * The upper bounds of the arrays are converted to affine expressions
2332 * within the context "pc".
2334 * The context of "scop" is updated with the intersection of
2335 * the contexts of all arrays, i.e., constraints on the parameters
2336 * that ensure that the arrays have a valid (non-negative) size.
2338 * If the any of the extracted arrays refers to a member access,
2339 * then also add the required types to "scop".
2341 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
,
2342 __isl_keep pet_context
*pc
)
2345 array_desc_set arrays
;
2346 array_desc_set::iterator it
;
2347 lex_recorddecl_set types
;
2348 lex_recorddecl_set types_done
;
2349 lex_recorddecl_set::iterator types_it
;
2351 struct pet_array
**scop_arrays
;
2356 pet_scop_collect_arrays(scop
, arrays
);
2357 if (arrays
.size() == 0)
2360 n_array
= scop
->n_array
;
2362 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
2363 n_array
+ arrays
.size());
2366 scop
->arrays
= scop_arrays
;
2368 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
2369 struct pet_array
*array
;
2370 array
= extract_array(ctx
, *it
, &types
, pc
);
2371 scop
->arrays
[n_array
+ i
] = array
;
2372 if (!scop
->arrays
[n_array
+ i
])
2375 scop
->context
= isl_set_intersect(scop
->context
,
2376 isl_set_copy(array
->context
));
2381 if (types
.size() == 0)
2384 scop
->types
= isl_alloc_array(ctx
, struct pet_type
*, types
.size());
2388 for (types_it
= types
.begin(); types_it
!= types
.end(); ++types_it
)
2389 scop
= add_type(ctx
, scop
, *types_it
, PP
, types
, types_done
);
2393 pet_scop_free(scop
);
2397 /* Bound all parameters in scop->context to the possible values
2398 * of the corresponding C variable.
2400 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
2407 n
= isl_set_dim(scop
->context
, isl_dim_param
);
2408 for (int i
= 0; i
< n
; ++i
) {
2412 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
2413 if (pet_nested_in_id(id
)) {
2415 isl_die(isl_set_get_ctx(scop
->context
),
2417 "unresolved nested parameter", goto error
);
2419 decl
= (ValueDecl
*) isl_id_get_user(id
);
2422 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
2430 pet_scop_free(scop
);
2434 /* Construct a pet_scop from the given function.
2436 * If the scop was delimited by scop and endscop pragmas, then we override
2437 * the file offsets by those derived from the pragmas.
2439 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
2444 stmt
= fd
->getBody();
2446 if (options
->autodetect
) {
2447 set_current_stmt(stmt
);
2448 scop
= extract_scop(extract(stmt
, true));
2450 current_line
= loc
.start_line
;
2452 scop
= pet_scop_update_start_end(scop
, loc
.start
, loc
.end
);
2454 scop
= add_parameter_bounds(scop
);
2455 scop
= pet_scop_gist(scop
, value_bounds
);
2460 /* Update this->last_line and this->current_line based on the fact
2461 * that we are about to consider "stmt".
2463 void PetScan::set_current_stmt(Stmt
*stmt
)
2465 SourceLocation loc
= stmt
->getLocStart();
2466 SourceManager
&SM
= PP
.getSourceManager();
2468 last_line
= current_line
;
2469 current_line
= SM
.getExpansionLineNumber(loc
);
2472 /* Is the current statement marked by an independent pragma?
2473 * That is, is there an independent pragma on a line between
2474 * the line of the current statement and the line of the previous statement.
2475 * The search is not implemented very efficiently. We currently
2476 * assume that there are only a few independent pragmas, if any.
2478 bool PetScan::is_current_stmt_marked_independent()
2480 for (int i
= 0; i
< independent
.size(); ++i
) {
2481 unsigned line
= independent
[i
].line
;
2483 if (last_line
< line
&& line
< current_line
)