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>
60 #include "scop_plus.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
);
192 /* Mark "decl" as having an unknown value in "assigned_value".
194 * If no (known or unknown) value was assigned to "decl" before,
195 * then it may have been treated as a parameter before and may
196 * therefore appear in a value assigned to another variable.
197 * If so, this assignment needs to be turned into an unknown value too.
199 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
202 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
204 it
= assigned_value
.find(decl
);
206 assigned_value
[decl
] = NULL
;
208 if (it
!= assigned_value
.end())
211 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
212 isl_pw_aff
*pa
= it
->second
;
213 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
215 for (int i
= 0; i
< nparam
; ++i
) {
218 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
220 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
221 if (isl_id_get_user(id
) == decl
)
228 /* Look for any assignments to scalar variables in part of the parse
229 * tree and set assigned_value to NULL for each of them.
230 * Also reset assigned_value if the address of a scalar variable
231 * is being taken. As an exception, if the address is passed to a function
232 * that is declared to receive a const pointer, then assigned_value is
235 * This ensures that we won't use any previously stored value
236 * in the current subtree and its parents.
238 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
239 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
240 set
<UnaryOperator
*> skip
;
242 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
243 assigned_value(assigned_value
) {}
245 /* Check for "address of" operators whose value is passed
246 * to a const pointer argument and add them to "skip", so that
247 * we can skip them in VisitUnaryOperator.
249 bool VisitCallExpr(CallExpr
*expr
) {
251 fd
= expr
->getDirectCallee();
254 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
255 Expr
*arg
= expr
->getArg(i
);
257 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
258 ImplicitCastExpr
*ice
;
259 ice
= cast
<ImplicitCastExpr
>(arg
);
260 arg
= ice
->getSubExpr();
262 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
264 op
= cast
<UnaryOperator
>(arg
);
265 if (op
->getOpcode() != UO_AddrOf
)
267 if (const_base(fd
->getParamDecl(i
)->getType()))
273 bool VisitUnaryOperator(UnaryOperator
*expr
) {
278 switch (expr
->getOpcode()) {
288 if (skip
.find(expr
) != skip
.end())
291 arg
= expr
->getSubExpr();
292 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
294 ref
= cast
<DeclRefExpr
>(arg
);
295 decl
= ref
->getDecl();
296 clear_assignment(assigned_value
, decl
);
300 bool VisitBinaryOperator(BinaryOperator
*expr
) {
305 if (!expr
->isAssignmentOp())
307 lhs
= expr
->getLHS();
308 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
310 ref
= cast
<DeclRefExpr
>(lhs
);
311 decl
= ref
->getDecl();
312 clear_assignment(assigned_value
, decl
);
317 /* Keep a copy of the currently assigned values.
319 * Any variable that is assigned a value inside the current scope
320 * is removed again when we leave the scope (either because it wasn't
321 * stored in the cache or because it has a different value in the cache).
323 struct assigned_value_cache
{
324 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
325 map
<ValueDecl
*, isl_pw_aff
*> cache
;
327 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
328 assigned_value(assigned_value
), cache(assigned_value
) {}
329 ~assigned_value_cache() {
330 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
331 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
334 (cache
.find(it
->first
) != cache
.end() &&
335 cache
[it
->first
] != it
->second
))
336 cache
[it
->first
] = NULL
;
338 assigned_value
= cache
;
342 /* Convert the mapping from identifiers to values in "assigned_value"
343 * to a pet_context to be used by pet_expr_extract_*.
344 * In particular, the clang identifiers are wrapped in an isl_id and
345 * a NULL value (representing an unknown value) is replaced by a NaN.
347 static __isl_give pet_context
*convert_assignments(isl_ctx
*ctx
,
348 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
)
351 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
353 pc
= pet_context_alloc(isl_space_set_alloc(ctx
, 0, 0));
355 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
356 ValueDecl
*decl
= it
->first
;
357 isl_pw_aff
*pa
= it
->second
;
360 id
= create_decl_id(ctx
, decl
);
362 pc
= pet_context_set_value(pc
, id
, isl_pw_aff_copy(pa
));
364 pc
= pet_context_mark_unknown(pc
, id
);
370 /* Insert an expression into the collection of expressions,
371 * provided it is not already in there.
372 * The isl_pw_affs are freed in the destructor.
374 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
376 std::set
<isl_pw_aff
*>::iterator it
;
378 if (expressions
.find(expr
) == expressions
.end())
379 expressions
.insert(expr
);
381 isl_pw_aff_free(expr
);
386 std::set
<isl_pw_aff
*>::iterator it
;
388 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
389 isl_pw_aff_free(*it
);
391 isl_union_map_free(value_bounds
);
394 /* Report a diagnostic, unless autodetect is set.
396 void PetScan::report(Stmt
*stmt
, unsigned id
)
398 if (options
->autodetect
)
401 SourceLocation loc
= stmt
->getLocStart();
402 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
403 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
406 /* Called if we found something we (currently) cannot handle.
407 * We'll provide more informative warnings later.
409 * We only actually complain if autodetect is false.
411 void PetScan::unsupported(Stmt
*stmt
)
413 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
414 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
419 /* Report a missing prototype, unless autodetect is set.
421 void PetScan::report_prototype_required(Stmt
*stmt
)
423 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
424 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
425 "prototype required");
429 /* Report a missing increment, unless autodetect is set.
431 void PetScan::report_missing_increment(Stmt
*stmt
)
433 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
434 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
435 "missing increment");
439 /* Extract an integer from "expr".
441 __isl_give isl_val
*PetScan::extract_int(isl_ctx
*ctx
, IntegerLiteral
*expr
)
443 const Type
*type
= expr
->getType().getTypePtr();
444 int is_signed
= type
->hasSignedIntegerRepresentation();
445 llvm::APInt val
= expr
->getValue();
446 int is_negative
= is_signed
&& val
.isNegative();
452 v
= extract_unsigned(ctx
, val
);
459 /* Extract an integer from "val", which is assumed to be non-negative.
461 __isl_give isl_val
*PetScan::extract_unsigned(isl_ctx
*ctx
,
462 const llvm::APInt
&val
)
465 const uint64_t *data
;
467 data
= val
.getRawData();
468 n
= val
.getNumWords();
469 return isl_val_int_from_chunks(ctx
, n
, sizeof(uint64_t), data
);
472 /* Extract an integer from "expr".
473 * Return NULL if "expr" does not (obviously) represent an integer.
475 __isl_give isl_val
*PetScan::extract_int(clang::ParenExpr
*expr
)
477 return extract_int(expr
->getSubExpr());
480 /* Extract an integer from "expr".
481 * Return NULL if "expr" does not (obviously) represent an integer.
483 __isl_give isl_val
*PetScan::extract_int(clang::Expr
*expr
)
485 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
486 return extract_int(ctx
, cast
<IntegerLiteral
>(expr
));
487 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
488 return extract_int(cast
<ParenExpr
>(expr
));
494 /* Extract an affine expression from the APInt "val", which is assumed
495 * to be non-negative.
496 * If the value of "val" is "v", then the returned expression
501 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
503 isl_space
*space
= isl_space_set_alloc(ctx
, 0, 0);
504 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(space
));
505 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
506 isl_set
*dom
= isl_set_universe(space
);
509 v
= extract_unsigned(ctx
, val
);
510 aff
= isl_aff_add_constant_val(aff
, v
);
512 return isl_pw_aff_alloc(dom
, aff
);
515 /* Return the number of bits needed to represent the type "qt",
516 * if it is an integer type. Otherwise return 0.
517 * If qt is signed then return the opposite of the number of bits.
519 static int get_type_size(QualType qt
, ASTContext
&ast_context
)
523 if (!qt
->isIntegerType())
526 size
= ast_context
.getIntWidth(qt
);
527 if (!qt
->isUnsignedIntegerType())
533 /* Return the number of bits needed to represent the type of "decl",
534 * if it is an integer type. Otherwise return 0.
535 * If qt is signed then return the opposite of the number of bits.
537 static int get_type_size(ValueDecl
*decl
)
539 return get_type_size(decl
->getType(), decl
->getASTContext());
542 /* Bound parameter "pos" of "set" to the possible values of "decl".
544 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
545 unsigned pos
, ValueDecl
*decl
)
551 ctx
= isl_set_get_ctx(set
);
552 type_size
= get_type_size(decl
);
554 isl_die(ctx
, isl_error_invalid
, "not an integer type",
555 return isl_set_free(set
));
557 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
558 bound
= isl_val_int_from_ui(ctx
, type_size
);
559 bound
= isl_val_2exp(bound
);
560 bound
= isl_val_sub_ui(bound
, 1);
561 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
, bound
);
563 bound
= isl_val_int_from_ui(ctx
, -type_size
- 1);
564 bound
= isl_val_2exp(bound
);
565 bound
= isl_val_sub_ui(bound
, 1);
566 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
,
567 isl_val_copy(bound
));
568 bound
= isl_val_neg(bound
);
569 bound
= isl_val_sub_ui(bound
, 1);
570 set
= isl_set_lower_bound_val(set
, isl_dim_param
, pos
, bound
);
576 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
578 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
579 __isl_take isl_set
*dom
)
582 pa
= isl_set_indicator_function(set
);
583 pa
= isl_pw_aff_intersect_domain(pa
, isl_set_coalesce(dom
));
587 /* Extract an affine expression, if possible, from "expr".
588 * Otherwise return NULL.
590 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
596 pe
= extract_expr(expr
);
599 pc
= convert_assignments(ctx
, assigned_value
);
600 pe
= pet_expr_plug_in_args(pe
, pc
);
601 pa
= pet_expr_extract_affine(pe
, pc
);
602 if (isl_pw_aff_involves_nan(pa
)) {
604 pa
= isl_pw_aff_free(pa
);
606 pet_context_free(pc
);
612 __isl_give pet_expr
*PetScan::extract_index_expr(ImplicitCastExpr
*expr
)
614 return extract_index_expr(expr
->getSubExpr());
617 /* Return the depth of an array of the given type.
619 static int array_depth(const Type
*type
)
621 if (type
->isPointerType())
622 return 1 + array_depth(type
->getPointeeType().getTypePtr());
623 if (type
->isArrayType()) {
624 const ArrayType
*atype
;
625 type
= type
->getCanonicalTypeInternal().getTypePtr();
626 atype
= cast
<ArrayType
>(type
);
627 return 1 + array_depth(atype
->getElementType().getTypePtr());
632 /* Return the depth of the array accessed by the index expression "index".
633 * If "index" is an affine expression, i.e., if it does not access
634 * any array, then return 1.
635 * If "index" represent a member access, i.e., if its range is a wrapped
636 * relation, then return the sum of the depth of the array of structures
637 * and that of the member inside the structure.
639 static int extract_depth(__isl_keep isl_multi_pw_aff
*index
)
647 if (isl_multi_pw_aff_range_is_wrapping(index
)) {
648 int domain_depth
, range_depth
;
649 isl_multi_pw_aff
*domain
, *range
;
651 domain
= isl_multi_pw_aff_copy(index
);
652 domain
= isl_multi_pw_aff_range_factor_domain(domain
);
653 domain_depth
= extract_depth(domain
);
654 isl_multi_pw_aff_free(domain
);
655 range
= isl_multi_pw_aff_copy(index
);
656 range
= isl_multi_pw_aff_range_factor_range(range
);
657 range_depth
= extract_depth(range
);
658 isl_multi_pw_aff_free(range
);
660 return domain_depth
+ range_depth
;
663 if (!isl_multi_pw_aff_has_tuple_id(index
, isl_dim_out
))
666 id
= isl_multi_pw_aff_get_tuple_id(index
, isl_dim_out
);
669 decl
= (ValueDecl
*) isl_id_get_user(id
);
672 return array_depth(decl
->getType().getTypePtr());
675 /* Return the depth of the array accessed by the access expression "expr".
677 static int extract_depth(__isl_keep pet_expr
*expr
)
679 isl_multi_pw_aff
*index
;
682 index
= pet_expr_access_get_index(expr
);
683 depth
= extract_depth(index
);
684 isl_multi_pw_aff_free(index
);
689 /* Construct a pet_expr representing an index expression for an access
690 * to the variable referenced by "expr".
692 __isl_give pet_expr
*PetScan::extract_index_expr(DeclRefExpr
*expr
)
694 return extract_index_expr(expr
->getDecl());
697 /* Construct a pet_expr representing an index expression for an access
698 * to the variable "decl".
700 __isl_give pet_expr
*PetScan::extract_index_expr(ValueDecl
*decl
)
702 isl_id
*id
= create_decl_id(ctx
, decl
);
703 isl_space
*space
= isl_space_alloc(ctx
, 0, 0, 0);
705 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
707 return pet_expr_from_index(isl_multi_pw_aff_zero(space
));
710 /* Construct a pet_expr representing the index expression "expr"
711 * Return NULL on error.
713 __isl_give pet_expr
*PetScan::extract_index_expr(Expr
*expr
)
715 switch (expr
->getStmtClass()) {
716 case Stmt::ImplicitCastExprClass
:
717 return extract_index_expr(cast
<ImplicitCastExpr
>(expr
));
718 case Stmt::DeclRefExprClass
:
719 return extract_index_expr(cast
<DeclRefExpr
>(expr
));
720 case Stmt::ArraySubscriptExprClass
:
721 return extract_index_expr(cast
<ArraySubscriptExpr
>(expr
));
722 case Stmt::IntegerLiteralClass
:
723 return extract_expr(cast
<IntegerLiteral
>(expr
));
724 case Stmt::MemberExprClass
:
725 return extract_index_expr(cast
<MemberExpr
>(expr
));
732 /* Extract an index expression from the given array subscript expression.
734 * We first extract an index expression from the base.
735 * This will result in an index expression with a range that corresponds
736 * to the earlier indices.
737 * We then extract the current index and let
738 * pet_expr_access_subscript combine the two.
740 __isl_give pet_expr
*PetScan::extract_index_expr(ArraySubscriptExpr
*expr
)
742 Expr
*base
= expr
->getBase();
743 Expr
*idx
= expr
->getIdx();
747 base_expr
= extract_index_expr(base
);
748 index
= extract_expr(idx
);
750 base_expr
= pet_expr_access_subscript(base_expr
, index
);
755 /* Extract an index expression from a member expression.
757 * If the base access (to the structure containing the member)
762 * and the member is called "f", then the member access is of
767 * If the member access is to an anonymous struct, then simply return
771 * If the member access in the source code is of the form
775 * then it is treated as
779 __isl_give pet_expr
*PetScan::extract_index_expr(MemberExpr
*expr
)
781 Expr
*base
= expr
->getBase();
782 FieldDecl
*field
= cast
<FieldDecl
>(expr
->getMemberDecl());
783 pet_expr
*base_index
;
786 base_index
= extract_index_expr(base
);
788 if (expr
->isArrow()) {
789 pet_expr
*index
= pet_expr_new_int(isl_val_zero(ctx
));
790 base_index
= pet_expr_access_subscript(base_index
, index
);
793 if (field
->isAnonymousStructOrUnion())
796 id
= create_decl_id(ctx
, field
);
798 return pet_expr_access_member(base_index
, id
);
801 /* Check if "expr" calls function "minmax" with two arguments and if so
802 * make lhs and rhs refer to these two arguments.
804 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
810 if (expr
->getStmtClass() != Stmt::CallExprClass
)
813 call
= cast
<CallExpr
>(expr
);
814 fd
= call
->getDirectCallee();
818 if (call
->getNumArgs() != 2)
821 name
= fd
->getDeclName().getAsString();
825 lhs
= call
->getArg(0);
826 rhs
= call
->getArg(1);
831 /* Check if "expr" is of the form min(lhs, rhs) and if so make
832 * lhs and rhs refer to the two arguments.
834 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
836 return is_minmax(expr
, "min", lhs
, rhs
);
839 /* Check if "expr" is of the form max(lhs, rhs) and if so make
840 * lhs and rhs refer to the two arguments.
842 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
844 return is_minmax(expr
, "max", lhs
, rhs
);
847 /* Extract an affine expressions representing the comparison "LHS op RHS"
848 * "comp" is the original statement that "LHS op RHS" is derived from
849 * and is used for diagnostics.
851 * If the comparison is of the form
855 * then the expression is constructed as the conjunction of
860 * A similar optimization is performed for max(a,b) <= c.
861 * We do this because that will lead to simpler representations
863 * If isl is ever enhanced to explicitly deal with min and max expressions,
864 * this optimization can be removed.
866 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
867 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
874 enum pet_op_type type
;
877 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
879 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
881 if (op
== BO_LT
|| op
== BO_LE
) {
883 if (is_min(RHS
, expr1
, expr2
)) {
884 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
885 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
886 return pet_and(lhs
, rhs
);
888 if (is_max(LHS
, expr1
, expr2
)) {
889 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
890 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
891 return pet_and(lhs
, rhs
);
895 lhs
= extract_affine(LHS
);
896 rhs
= extract_affine(RHS
);
898 type
= BinaryOperatorKind2pet_op_type(op
);
899 return pet_comparison(type
, lhs
, rhs
);
902 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
904 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
905 comp
->getRHS(), comp
);
908 /* Extract an affine expression from a boolean expression.
909 * In particular, return the expression "expr ? 1 : 0".
910 * Return NULL if we are unable to extract an affine expression.
912 * We first convert the clang::Expr to a pet_expr and
913 * then extract an affine expression from that pet_expr.
915 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
922 isl_set
*u
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
923 return indicator_function(u
, isl_set_copy(u
));
926 pe
= extract_expr(expr
);
927 pc
= convert_assignments(ctx
, assigned_value
);
928 pe
= pet_expr_plug_in_args(pe
, pc
);
929 pc
= pet_context_set_allow_nested(pc
, nesting_enabled
);
930 cond
= pet_expr_extract_affine_condition(pe
, pc
);
931 if (isl_pw_aff_involves_nan(cond
))
932 cond
= isl_pw_aff_free(cond
);
933 pet_context_free(pc
);
938 /* Mark the given access pet_expr as a write.
940 static __isl_give pet_expr
*mark_write(__isl_take pet_expr
*access
)
942 access
= pet_expr_access_set_write(access
, 1);
943 access
= pet_expr_access_set_read(access
, 0);
948 /* Construct a pet_expr representing a unary operator expression.
950 __isl_give pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
955 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
956 if (op
== pet_op_last
) {
961 arg
= extract_expr(expr
->getSubExpr());
963 if (expr
->isIncrementDecrementOp() &&
964 pet_expr_get_type(arg
) == pet_expr_access
) {
965 arg
= mark_write(arg
);
966 arg
= pet_expr_access_set_read(arg
, 1);
969 return pet_expr_new_unary(op
, arg
);
972 /* If the access expression "expr" writes to a (non-virtual) scalar,
973 * then mark the scalar as having an unknown value in "assigned_value".
975 static int clear_write(__isl_keep pet_expr
*expr
, void *user
)
979 PetScan
*ps
= (PetScan
*) user
;
981 if (!pet_expr_access_is_write(expr
))
983 if (!pet_expr_is_scalar_access(expr
))
986 id
= pet_expr_access_get_id(expr
);
987 decl
= (ValueDecl
*) isl_id_get_user(id
);
991 clear_assignment(ps
->assigned_value
, decl
);
996 /* Take into account the writes in "stmt".
997 * That is, first mark all scalar variables that are written by "stmt"
998 * as having an unknown value. Afterwards,
999 * if "stmt" is a top-level (i.e., unconditional) assignment
1000 * to a scalar variable, then update "assigned_value" accordingly.
1002 * In particular, if the lhs of the assignment is a scalar variable, then mark
1003 * the variable as having been assigned. If, furthermore, the rhs
1004 * is an affine expression, then keep track of this value in assigned_value
1005 * so that we can plug it in when we later come across the same variable.
1007 * We skip assignments to virtual arrays (those with NULL user pointer).
1009 void PetScan::handle_writes(struct pet_stmt
*stmt
)
1011 pet_expr
*body
= stmt
->body
;
1018 pet_expr_foreach_access_expr(body
, &clear_write
, this);
1020 if (!pet_stmt_is_assign(stmt
))
1022 if (!isl_set_plain_is_universe(stmt
->domain
))
1024 arg
= pet_expr_get_arg(body
, 0);
1025 if (!pet_expr_is_scalar_access(arg
)) {
1030 id
= pet_expr_access_get_id(arg
);
1031 decl
= (ValueDecl
*) isl_id_get_user(id
);
1038 arg
= pet_expr_get_arg(body
, 1);
1039 pc
= convert_assignments(ctx
, assigned_value
);
1040 pa
= pet_expr_extract_affine(arg
, pc
);
1041 pet_context_free(pc
);
1042 clear_assignment(assigned_value
, decl
);
1045 if (isl_pw_aff_involves_nan(pa
))
1046 pa
= isl_pw_aff_free(pa
);
1049 assigned_value
[decl
] = pa
;
1050 insert_expression(pa
);
1053 /* Update "assigned_value" based on the write accesses (and, in particular,
1054 * assignments) in "scop".
1056 void PetScan::handle_writes(struct pet_scop
*scop
)
1060 for (int i
= 0; i
< scop
->n_stmt
; ++i
)
1061 handle_writes(scop
->stmts
[i
]);
1064 /* Construct a pet_expr representing a binary operator expression.
1066 * If the top level operator is an assignment and the LHS is an access,
1067 * then we mark that access as a write. If the operator is a compound
1068 * assignment, the access is marked as both a read and a write.
1070 __isl_give pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1073 pet_expr
*lhs
, *rhs
;
1074 enum pet_op_type op
;
1076 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1077 if (op
== pet_op_last
) {
1082 lhs
= extract_expr(expr
->getLHS());
1083 rhs
= extract_expr(expr
->getRHS());
1085 if (expr
->isAssignmentOp() &&
1086 pet_expr_get_type(lhs
) == pet_expr_access
) {
1087 lhs
= mark_write(lhs
);
1088 if (expr
->isCompoundAssignmentOp())
1089 lhs
= pet_expr_access_set_read(lhs
, 1);
1092 type_size
= get_type_size(expr
->getType(), ast_context
);
1093 return pet_expr_new_binary(type_size
, op
, lhs
, rhs
);
1096 /* Construct a pet_scop with a single statement killing the entire
1099 struct pet_scop
*PetScan::kill(Stmt
*stmt
, struct pet_array
*array
)
1103 isl_multi_pw_aff
*index
;
1109 access
= isl_map_from_range(isl_set_copy(array
->extent
));
1110 id
= isl_set_get_tuple_id(array
->extent
);
1111 space
= isl_space_alloc(ctx
, 0, 0, 0);
1112 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
1113 index
= isl_multi_pw_aff_zero(space
);
1114 expr
= pet_expr_kill_from_access_and_index(access
, index
);
1115 return extract(expr
, stmt
->getSourceRange(), false);
1118 /* Construct a pet_scop for a (single) variable declaration.
1120 * The scop contains the variable being declared (as an array)
1121 * and a statement killing the array.
1123 * If the variable is initialized in the AST, then the scop
1124 * also contains an assignment to the variable.
1126 struct pet_scop
*PetScan::extract(DeclStmt
*stmt
)
1131 pet_expr
*lhs
, *rhs
, *pe
;
1132 struct pet_scop
*scop_decl
, *scop
;
1133 struct pet_array
*array
;
1135 if (!stmt
->isSingleDecl()) {
1140 decl
= stmt
->getSingleDecl();
1141 vd
= cast
<VarDecl
>(decl
);
1143 array
= extract_array(ctx
, vd
, NULL
);
1145 array
->declared
= 1;
1146 scop_decl
= kill(stmt
, array
);
1147 scop_decl
= pet_scop_add_array(scop_decl
, array
);
1152 lhs
= extract_access_expr(vd
);
1153 rhs
= extract_expr(vd
->getInit());
1155 lhs
= mark_write(lhs
);
1157 type_size
= get_type_size(vd
->getType(), ast_context
);
1158 pe
= pet_expr_new_binary(type_size
, pet_op_assign
, lhs
, rhs
);
1159 scop
= extract(pe
, stmt
->getSourceRange(), false);
1161 scop_decl
= pet_scop_prefix(scop_decl
, 0);
1162 scop
= pet_scop_prefix(scop
, 1);
1164 scop
= pet_scop_add_seq(ctx
, scop_decl
, scop
);
1169 /* Construct a pet_expr representing a conditional operation.
1171 __isl_give pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1173 pet_expr
*cond
, *lhs
, *rhs
;
1176 cond
= extract_expr(expr
->getCond());
1177 lhs
= extract_expr(expr
->getTrueExpr());
1178 rhs
= extract_expr(expr
->getFalseExpr());
1180 return pet_expr_new_ternary(cond
, lhs
, rhs
);
1183 __isl_give pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1185 return extract_expr(expr
->getSubExpr());
1188 /* Construct a pet_expr representing a floating point value.
1190 * If the floating point literal does not appear in a macro,
1191 * then we use the original representation in the source code
1192 * as the string representation. Otherwise, we use the pretty
1193 * printer to produce a string representation.
1195 __isl_give pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1199 const LangOptions
&LO
= PP
.getLangOpts();
1200 SourceLocation loc
= expr
->getLocation();
1202 if (!loc
.isMacroID()) {
1203 SourceManager
&SM
= PP
.getSourceManager();
1204 unsigned len
= Lexer::MeasureTokenLength(loc
, SM
, LO
);
1205 s
= string(SM
.getCharacterData(loc
), len
);
1207 llvm::raw_string_ostream
S(s
);
1208 expr
->printPretty(S
, 0, PrintingPolicy(LO
));
1211 d
= expr
->getValueAsApproximateDouble();
1212 return pet_expr_new_double(ctx
, d
, s
.c_str());
1215 /* Convert the index expression "index" into an access pet_expr of type "qt".
1217 __isl_give pet_expr
*PetScan::extract_access_expr(QualType qt
,
1218 __isl_take pet_expr
*index
)
1223 depth
= extract_depth(index
);
1224 type_size
= get_type_size(qt
, ast_context
);
1226 index
= pet_expr_set_type_size(index
, type_size
);
1227 index
= pet_expr_access_set_depth(index
, depth
);
1232 /* Extract an index expression from "expr" and then convert it into
1233 * an access pet_expr.
1235 __isl_give pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1237 return extract_access_expr(expr
->getType(), extract_index_expr(expr
));
1240 /* Extract an index expression from "decl" and then convert it into
1241 * an access pet_expr.
1243 __isl_give pet_expr
*PetScan::extract_access_expr(ValueDecl
*decl
)
1245 return extract_access_expr(decl
->getType(), extract_index_expr(decl
));
1248 __isl_give pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1250 return extract_expr(expr
->getSubExpr());
1253 /* Extract an assume statement from the argument "expr"
1254 * of a __pencil_assume statement.
1256 __isl_give pet_expr
*PetScan::extract_assume(Expr
*expr
)
1261 cond
= try_extract_affine_condition(expr
);
1263 res
= extract_expr(expr
);
1265 isl_multi_pw_aff
*index
;
1266 index
= isl_multi_pw_aff_from_pw_aff(cond
);
1267 res
= pet_expr_from_index(index
);
1269 return pet_expr_new_unary(pet_op_assume
, res
);
1272 /* Construct a pet_expr corresponding to the function call argument "expr".
1273 * The argument appears in position "pos" of a call to function "fd".
1275 * If we are passing along a pointer to an array element
1276 * or an entire row or even higher dimensional slice of an array,
1277 * then the function being called may write into the array.
1279 * We assume here that if the function is declared to take a pointer
1280 * to a const type, then the function will perform a read
1281 * and that otherwise, it will perform a write.
1283 __isl_give pet_expr
*PetScan::extract_argument(FunctionDecl
*fd
, int pos
,
1287 int is_addr
= 0, is_partial
= 0;
1290 if (expr
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1291 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(expr
);
1292 expr
= ice
->getSubExpr();
1294 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1295 UnaryOperator
*op
= cast
<UnaryOperator
>(expr
);
1296 if (op
->getOpcode() == UO_AddrOf
) {
1298 expr
= op
->getSubExpr();
1301 res
= extract_expr(expr
);
1304 sc
= expr
->getStmtClass();
1305 if ((sc
== Stmt::ArraySubscriptExprClass
||
1306 sc
== Stmt::MemberExprClass
) &&
1307 array_depth(expr
->getType().getTypePtr()) > 0)
1309 if ((is_addr
|| is_partial
) &&
1310 pet_expr_get_type(res
) == pet_expr_access
) {
1312 if (!fd
->hasPrototype()) {
1313 report_prototype_required(expr
);
1314 return pet_expr_free(res
);
1316 parm
= fd
->getParamDecl(pos
);
1317 if (!const_base(parm
->getType()))
1318 res
= mark_write(res
);
1322 res
= pet_expr_new_unary(pet_op_address_of
, res
);
1326 /* Construct a pet_expr representing a function call.
1328 * In the special case of a "call" to __pencil_assume,
1329 * construct an assume expression instead.
1331 __isl_give pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1333 pet_expr
*res
= NULL
;
1338 fd
= expr
->getDirectCallee();
1344 name
= fd
->getDeclName().getAsString();
1345 n_arg
= expr
->getNumArgs();
1347 if (n_arg
== 1 && name
== "__pencil_assume")
1348 return extract_assume(expr
->getArg(0));
1350 res
= pet_expr_new_call(ctx
, name
.c_str(), n_arg
);
1354 for (int i
= 0; i
< n_arg
; ++i
) {
1355 Expr
*arg
= expr
->getArg(i
);
1356 res
= pet_expr_set_arg(res
, i
,
1357 PetScan::extract_argument(fd
, i
, arg
));
1363 /* Construct a pet_expr representing a (C style) cast.
1365 __isl_give pet_expr
*PetScan::extract_expr(CStyleCastExpr
*expr
)
1370 arg
= extract_expr(expr
->getSubExpr());
1374 type
= expr
->getTypeAsWritten();
1375 return pet_expr_new_cast(type
.getAsString().c_str(), arg
);
1378 /* Construct a pet_expr representing an integer.
1380 __isl_give pet_expr
*PetScan::extract_expr(IntegerLiteral
*expr
)
1382 return pet_expr_new_int(extract_int(expr
));
1385 /* Try and construct a pet_expr representing "expr".
1387 __isl_give pet_expr
*PetScan::extract_expr(Expr
*expr
)
1389 switch (expr
->getStmtClass()) {
1390 case Stmt::UnaryOperatorClass
:
1391 return extract_expr(cast
<UnaryOperator
>(expr
));
1392 case Stmt::CompoundAssignOperatorClass
:
1393 case Stmt::BinaryOperatorClass
:
1394 return extract_expr(cast
<BinaryOperator
>(expr
));
1395 case Stmt::ImplicitCastExprClass
:
1396 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1397 case Stmt::ArraySubscriptExprClass
:
1398 case Stmt::DeclRefExprClass
:
1399 case Stmt::MemberExprClass
:
1400 return extract_access_expr(expr
);
1401 case Stmt::IntegerLiteralClass
:
1402 return extract_expr(cast
<IntegerLiteral
>(expr
));
1403 case Stmt::FloatingLiteralClass
:
1404 return extract_expr(cast
<FloatingLiteral
>(expr
));
1405 case Stmt::ParenExprClass
:
1406 return extract_expr(cast
<ParenExpr
>(expr
));
1407 case Stmt::ConditionalOperatorClass
:
1408 return extract_expr(cast
<ConditionalOperator
>(expr
));
1409 case Stmt::CallExprClass
:
1410 return extract_expr(cast
<CallExpr
>(expr
));
1411 case Stmt::CStyleCastExprClass
:
1412 return extract_expr(cast
<CStyleCastExpr
>(expr
));
1419 /* Check if the given initialization statement is an assignment.
1420 * If so, return that assignment. Otherwise return NULL.
1422 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1424 BinaryOperator
*ass
;
1426 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1429 ass
= cast
<BinaryOperator
>(init
);
1430 if (ass
->getOpcode() != BO_Assign
)
1436 /* Check if the given initialization statement is a declaration
1437 * of a single variable.
1438 * If so, return that declaration. Otherwise return NULL.
1440 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1444 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1447 decl
= cast
<DeclStmt
>(init
);
1449 if (!decl
->isSingleDecl())
1452 return decl
->getSingleDecl();
1455 /* Given the assignment operator in the initialization of a for loop,
1456 * extract the induction variable, i.e., the (integer)variable being
1459 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1466 lhs
= init
->getLHS();
1467 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1472 ref
= cast
<DeclRefExpr
>(lhs
);
1473 decl
= ref
->getDecl();
1474 type
= decl
->getType().getTypePtr();
1476 if (!type
->isIntegerType()) {
1484 /* Given the initialization statement of a for loop and the single
1485 * declaration in this initialization statement,
1486 * extract the induction variable, i.e., the (integer) variable being
1489 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1493 vd
= cast
<VarDecl
>(decl
);
1495 const QualType type
= vd
->getType();
1496 if (!type
->isIntegerType()) {
1501 if (!vd
->getInit()) {
1509 /* Check that op is of the form iv++ or iv--.
1510 * Return a pet_expr representing "1" or "-1" accordingly.
1512 __isl_give pet_expr
*PetScan::extract_unary_increment(
1513 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1519 if (!op
->isIncrementDecrementOp()) {
1524 sub
= op
->getSubExpr();
1525 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1530 ref
= cast
<DeclRefExpr
>(sub
);
1531 if (ref
->getDecl() != iv
) {
1536 if (op
->isIncrementOp())
1537 v
= isl_val_one(ctx
);
1539 v
= isl_val_negone(ctx
);
1541 return pet_expr_new_int(v
);
1544 /* Check if op is of the form
1548 * and return the increment "expr - iv" as a pet_expr.
1550 __isl_give pet_expr
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1551 clang::ValueDecl
*iv
)
1556 pet_expr
*expr
, *expr_iv
;
1558 if (op
->getOpcode() != BO_Assign
) {
1564 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1569 ref
= cast
<DeclRefExpr
>(lhs
);
1570 if (ref
->getDecl() != iv
) {
1575 expr
= extract_expr(op
->getRHS());
1576 expr_iv
= extract_expr(lhs
);
1578 type_size
= get_type_size(iv
->getType(), ast_context
);
1579 return pet_expr_new_binary(type_size
, pet_op_sub
, expr
, expr_iv
);
1582 /* Check that op is of the form iv += cst or iv -= cst
1583 * and return a pet_expr corresponding to cst or -cst accordingly.
1585 __isl_give pet_expr
*PetScan::extract_compound_increment(
1586 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1592 BinaryOperatorKind opcode
;
1594 opcode
= op
->getOpcode();
1595 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1599 if (opcode
== BO_SubAssign
)
1603 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1608 ref
= cast
<DeclRefExpr
>(lhs
);
1609 if (ref
->getDecl() != iv
) {
1614 expr
= extract_expr(op
->getRHS());
1616 expr
= pet_expr_new_unary(pet_op_minus
, expr
);
1621 /* Check that the increment of the given for loop increments
1622 * (or decrements) the induction variable "iv" and return
1623 * the increment as a pet_expr if successful.
1625 __isl_give pet_expr
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1628 Stmt
*inc
= stmt
->getInc();
1631 report_missing_increment(stmt
);
1635 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1636 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1637 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1638 return extract_compound_increment(
1639 cast
<CompoundAssignOperator
>(inc
), iv
);
1640 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1641 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1647 /* Embed the given iteration domain in an extra outer loop
1648 * with induction variable "var".
1649 * If this variable appeared as a parameter in the constraints,
1650 * it is replaced by the new outermost dimension.
1652 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1653 __isl_take isl_id
*var
)
1657 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1658 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1660 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1661 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1668 /* Return those elements in the space of "cond" that come after
1669 * (based on "sign") an element in "cond".
1671 static __isl_give isl_set
*after(__isl_take isl_set
*cond
, int sign
)
1673 isl_map
*previous_to_this
;
1676 previous_to_this
= isl_map_lex_lt(isl_set_get_space(cond
));
1678 previous_to_this
= isl_map_lex_gt(isl_set_get_space(cond
));
1680 cond
= isl_set_apply(cond
, previous_to_this
);
1685 /* Create the infinite iteration domain
1687 * { [id] : id >= 0 }
1689 * If "scop" has an affine skip of type pet_skip_later,
1690 * then remove those iterations i that have an earlier iteration
1691 * where the skip condition is satisfied, meaning that iteration i
1693 * Since we are dealing with a loop without loop iterator,
1694 * the skip condition cannot refer to the current loop iterator and
1695 * so effectively, the returned set is of the form
1697 * { [0]; [id] : id >= 1 and not skip }
1699 static __isl_give isl_set
*infinite_domain(__isl_take isl_id
*id
,
1700 struct pet_scop
*scop
)
1702 isl_ctx
*ctx
= isl_id_get_ctx(id
);
1706 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
1707 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, id
);
1709 if (!pet_scop_has_affine_skip(scop
, pet_skip_later
))
1712 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
1713 skip
= embed(skip
, isl_id_copy(id
));
1714 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
1715 domain
= isl_set_subtract(domain
, after(skip
, 1));
1720 /* Create an identity affine expression on the space containing "domain",
1721 * which is assumed to be one-dimensional.
1723 static __isl_give isl_aff
*identity_aff(__isl_keep isl_set
*domain
)
1725 isl_local_space
*ls
;
1727 ls
= isl_local_space_from_space(isl_set_get_space(domain
));
1728 return isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
1731 /* Create an affine expression that maps elements
1732 * of a single-dimensional array "id_test" to the previous element
1733 * (according to "inc"), provided this element belongs to "domain".
1734 * That is, create the affine expression
1736 * { id[x] -> id[x - inc] : x - inc in domain }
1738 static __isl_give isl_multi_pw_aff
*map_to_previous(__isl_take isl_id
*id_test
,
1739 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
1742 isl_local_space
*ls
;
1744 isl_multi_pw_aff
*prev
;
1746 space
= isl_set_get_space(domain
);
1747 ls
= isl_local_space_from_space(space
);
1748 aff
= isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
1749 aff
= isl_aff_add_constant_val(aff
, isl_val_neg(inc
));
1750 prev
= isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
1751 domain
= isl_set_preimage_multi_pw_aff(domain
,
1752 isl_multi_pw_aff_copy(prev
));
1753 prev
= isl_multi_pw_aff_intersect_domain(prev
, domain
);
1754 prev
= isl_multi_pw_aff_set_tuple_id(prev
, isl_dim_out
, id_test
);
1759 /* Add an implication to "scop" expressing that if an element of
1760 * virtual array "id_test" has value "satisfied" then all previous elements
1761 * of this array also have that value. The set of previous elements
1762 * is bounded by "domain". If "sign" is negative then the iterator
1763 * is decreasing and we express that all subsequent array elements
1764 * (but still defined previously) have the same value.
1766 static struct pet_scop
*add_implication(struct pet_scop
*scop
,
1767 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
, int sign
,
1773 domain
= isl_set_set_tuple_id(domain
, id_test
);
1774 space
= isl_set_get_space(domain
);
1776 map
= isl_map_lex_ge(space
);
1778 map
= isl_map_lex_le(space
);
1779 map
= isl_map_intersect_range(map
, domain
);
1780 scop
= pet_scop_add_implication(scop
, map
, satisfied
);
1785 /* Add a filter to "scop" that imposes that it is only executed
1786 * when the variable identified by "id_test" has a zero value
1787 * for all previous iterations of "domain".
1789 * In particular, add a filter that imposes that the array
1790 * has a zero value at the previous iteration of domain and
1791 * add an implication that implies that it then has that
1792 * value for all previous iterations.
1794 static struct pet_scop
*scop_add_break(struct pet_scop
*scop
,
1795 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
,
1796 __isl_take isl_val
*inc
)
1798 isl_multi_pw_aff
*prev
;
1799 int sign
= isl_val_sgn(inc
);
1801 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
1802 scop
= add_implication(scop
, id_test
, domain
, sign
, 0);
1803 scop
= pet_scop_filter(scop
, prev
, 0);
1808 /* Construct a pet_scop for an infinite loop around the given body.
1810 * We extract a pet_scop for the body and then embed it in a loop with
1819 * If the body contains any break, then it is taken into
1820 * account in infinite_domain (if the skip condition is affine)
1821 * or in scop_add_break (if the skip condition is not affine).
1823 * If we were only able to extract part of the body, then simply
1826 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
1828 isl_id
*id
, *id_test
;
1831 struct pet_scop
*scop
;
1834 scop
= extract(body
);
1840 id
= isl_id_alloc(ctx
, "t", NULL
);
1841 domain
= infinite_domain(isl_id_copy(id
), scop
);
1842 ident
= identity_aff(domain
);
1844 has_var_break
= pet_scop_has_var_skip(scop
, pet_skip_later
);
1846 id_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
1848 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
1849 isl_aff_copy(ident
), ident
, id
);
1851 scop
= scop_add_break(scop
, id_test
, domain
, isl_val_one(ctx
));
1853 isl_set_free(domain
);
1858 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1864 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
1866 clear_assignments
clear(assigned_value
);
1867 clear
.TraverseStmt(stmt
->getBody());
1869 return extract_infinite_loop(stmt
->getBody());
1872 /* Add an array with the given extent (range of "index") to the list
1873 * of arrays in "scop" and return the extended pet_scop.
1874 * The array is marked as attaining values 0 and 1 only and
1875 * as each element being assigned at most once.
1877 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
1878 __isl_keep isl_multi_pw_aff
*index
, clang::ASTContext
&ast_ctx
)
1880 int int_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
1882 return pet_scop_add_boolean_array(scop
, isl_multi_pw_aff_copy(index
),
1886 /* Construct a pet_scop for a while loop of the form
1891 * In particular, construct a scop for an infinite loop around body and
1892 * intersect the domain with the affine expression.
1893 * Note that this intersection may result in an empty loop.
1895 struct pet_scop
*PetScan::extract_affine_while(__isl_take isl_pw_aff
*pa
,
1898 struct pet_scop
*scop
;
1902 valid
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
1903 dom
= isl_pw_aff_non_zero_set(pa
);
1904 scop
= extract_infinite_loop(body
);
1905 scop
= pet_scop_restrict(scop
, isl_set_params(dom
));
1906 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid
));
1911 /* Construct a scop for a while, given the scops for the condition
1912 * and the body, the filter identifier and the iteration domain of
1915 * In particular, the scop for the condition is filtered to depend
1916 * on "id_test" evaluating to true for all previous iterations
1917 * of the loop, while the scop for the body is filtered to depend
1918 * on "id_test" evaluating to true for all iterations up to the
1919 * current iteration.
1920 * The actual filter only imposes that this virtual array has
1921 * value one on the previous or the current iteration.
1922 * The fact that this condition also applies to the previous
1923 * iterations is enforced by an implication.
1925 * These filtered scops are then combined into a single scop.
1927 * "sign" is positive if the iterator increases and negative
1930 static struct pet_scop
*scop_add_while(struct pet_scop
*scop_cond
,
1931 struct pet_scop
*scop_body
, __isl_take isl_id
*id_test
,
1932 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
1934 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
1936 isl_multi_pw_aff
*test_index
;
1937 isl_multi_pw_aff
*prev
;
1938 int sign
= isl_val_sgn(inc
);
1939 struct pet_scop
*scop
;
1941 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
1942 scop_cond
= pet_scop_filter(scop_cond
, prev
, 1);
1944 space
= isl_space_map_from_set(isl_set_get_space(domain
));
1945 test_index
= isl_multi_pw_aff_identity(space
);
1946 test_index
= isl_multi_pw_aff_set_tuple_id(test_index
, isl_dim_out
,
1947 isl_id_copy(id_test
));
1948 scop_body
= pet_scop_filter(scop_body
, test_index
, 1);
1950 scop
= pet_scop_add_seq(ctx
, scop_cond
, scop_body
);
1951 scop
= add_implication(scop
, id_test
, domain
, sign
, 1);
1956 /* Check if the while loop is of the form
1958 * while (affine expression)
1961 * If so, call extract_affine_while to construct a scop.
1963 * Otherwise, extract the body and pass control to extract_while
1964 * to extend the iteration domain with an infinite loop.
1965 * If we were only able to extract part of the body, then simply
1968 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
1971 int test_nr
, stmt_nr
;
1973 struct pet_scop
*scop_body
;
1975 cond
= stmt
->getCond();
1981 clear_assignments
clear(assigned_value
);
1982 clear
.TraverseStmt(stmt
->getBody());
1984 pa
= try_extract_affine_condition(cond
);
1986 return extract_affine_while(pa
, stmt
->getBody());
1988 if (!allow_nested
) {
1995 scop_body
= extract(stmt
->getBody());
1999 return extract_while(cond
, test_nr
, stmt_nr
, scop_body
, NULL
);
2002 /* Construct a generic while scop, with iteration domain
2003 * { [t] : t >= 0 } around "scop_body". The scop consists of two parts,
2004 * one for evaluating the condition "cond" and one for the body.
2005 * "test_nr" is the sequence number of the virtual test variable that contains
2006 * the result of the condition and "stmt_nr" is the sequence number
2007 * of the statement that evaluates the condition.
2008 * If "scop_inc" is not NULL, then it is added at the end of the body,
2009 * after replacing any skip conditions resulting from continue statements
2010 * by the skip conditions resulting from break statements (if any).
2012 * The schedule is adjusted to reflect that the condition is evaluated
2013 * before the body is executed and the body is filtered to depend
2014 * on the result of the condition evaluating to true on all iterations
2015 * up to the current iteration, while the evaluation of the condition itself
2016 * is filtered to depend on the result of the condition evaluating to true
2017 * on all previous iterations.
2018 * The context of the scop representing the body is dropped
2019 * because we don't know how many times the body will be executed,
2022 * If the body contains any break, then it is taken into
2023 * account in infinite_domain (if the skip condition is affine)
2024 * or in scop_add_break (if the skip condition is not affine).
2026 struct pet_scop
*PetScan::extract_while(Expr
*cond
, int test_nr
, int stmt_nr
,
2027 struct pet_scop
*scop_body
, struct pet_scop
*scop_inc
)
2029 isl_id
*id
, *id_test
, *id_break_test
;
2032 isl_multi_pw_aff
*test_index
;
2033 struct pet_scop
*scop
;
2036 test_index
= pet_create_test_index(ctx
, test_nr
);
2037 scop
= extract_non_affine_condition(cond
, stmt_nr
,
2038 isl_multi_pw_aff_copy(test_index
));
2039 scop
= scop_add_array(scop
, test_index
, ast_context
);
2040 id_test
= isl_multi_pw_aff_get_tuple_id(test_index
, isl_dim_out
);
2041 isl_multi_pw_aff_free(test_index
);
2043 id
= isl_id_alloc(ctx
, "t", NULL
);
2044 domain
= infinite_domain(isl_id_copy(id
), scop_body
);
2045 ident
= identity_aff(domain
);
2047 has_var_break
= pet_scop_has_var_skip(scop_body
, pet_skip_later
);
2049 id_break_test
= pet_scop_get_skip_id(scop_body
, pet_skip_later
);
2051 scop
= pet_scop_prefix(scop
, 0);
2052 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), isl_aff_copy(ident
),
2053 isl_aff_copy(ident
), isl_id_copy(id
));
2054 scop_body
= pet_scop_reset_context(scop_body
);
2055 scop_body
= pet_scop_prefix(scop_body
, 1);
2057 scop_inc
= pet_scop_prefix(scop_inc
, 2);
2058 if (pet_scop_has_skip(scop_body
, pet_skip_later
)) {
2059 isl_multi_pw_aff
*skip
;
2060 skip
= pet_scop_get_skip(scop_body
, pet_skip_later
);
2061 scop_body
= pet_scop_set_skip(scop_body
,
2062 pet_skip_now
, skip
);
2064 pet_scop_reset_skip(scop_body
, pet_skip_now
);
2065 scop_body
= pet_scop_add_seq(ctx
, scop_body
, scop_inc
);
2067 scop_body
= pet_scop_embed(scop_body
, isl_set_copy(domain
),
2068 isl_aff_copy(ident
), ident
, id
);
2070 if (has_var_break
) {
2071 scop
= scop_add_break(scop
, isl_id_copy(id_break_test
),
2072 isl_set_copy(domain
), isl_val_one(ctx
));
2073 scop_body
= scop_add_break(scop_body
, id_break_test
,
2074 isl_set_copy(domain
), isl_val_one(ctx
));
2076 scop
= scop_add_while(scop
, scop_body
, id_test
, domain
,
2082 /* Check whether "cond" expresses a simple loop bound
2083 * on the only set dimension.
2084 * In particular, if "up" is set then "cond" should contain only
2085 * upper bounds on the set dimension.
2086 * Otherwise, it should contain only lower bounds.
2088 static bool is_simple_bound(__isl_keep isl_set
*cond
, __isl_keep isl_val
*inc
)
2090 if (isl_val_is_pos(inc
))
2091 return !isl_set_dim_has_any_lower_bound(cond
, isl_dim_set
, 0);
2093 return !isl_set_dim_has_any_upper_bound(cond
, isl_dim_set
, 0);
2096 /* Extend a condition on a given iteration of a loop to one that
2097 * imposes the same condition on all previous iterations.
2098 * "domain" expresses the lower [upper] bound on the iterations
2099 * when inc is positive [negative].
2101 * In particular, we construct the condition (when inc is positive)
2103 * forall i' : (domain(i') and i' <= i) => cond(i')
2105 * which is equivalent to
2107 * not exists i' : domain(i') and i' <= i and not cond(i')
2109 * We construct this set by negating cond, applying a map
2111 * { [i'] -> [i] : domain(i') and i' <= i }
2113 * and then negating the result again.
2115 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
2116 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2118 isl_map
*previous_to_this
;
2120 if (isl_val_is_pos(inc
))
2121 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
2123 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
2125 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
2127 cond
= isl_set_complement(cond
);
2128 cond
= isl_set_apply(cond
, previous_to_this
);
2129 cond
= isl_set_complement(cond
);
2136 /* Construct a domain of the form
2138 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2140 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
2141 __isl_take isl_pw_aff
*init
, __isl_take isl_val
*inc
)
2147 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
2148 dim
= isl_pw_aff_get_domain_space(init
);
2149 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2150 aff
= isl_aff_add_coefficient_val(aff
, isl_dim_in
, 0, inc
);
2151 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2153 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2154 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2155 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2156 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2158 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2160 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2162 return isl_set_params(set
);
2165 /* Assuming "cond" represents a bound on a loop where the loop
2166 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2169 * Under the given assumptions, wrapping is only possible if "cond" allows
2170 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2171 * increasing iterator and 0 in case of a decreasing iterator.
2173 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
,
2174 __isl_keep isl_val
*inc
)
2181 test
= isl_set_copy(cond
);
2183 ctx
= isl_set_get_ctx(test
);
2184 if (isl_val_is_neg(inc
))
2185 limit
= isl_val_zero(ctx
);
2187 limit
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2188 limit
= isl_val_2exp(limit
);
2189 limit
= isl_val_sub_ui(limit
, 1);
2192 test
= isl_set_fix_val(cond
, isl_dim_set
, 0, limit
);
2193 cw
= !isl_set_is_empty(test
);
2199 /* Given a one-dimensional space, construct the following affine expression
2202 * { [v] -> [v mod 2^width] }
2204 * where width is the number of bits used to represent the values
2205 * of the unsigned variable "iv".
2207 static __isl_give isl_aff
*compute_wrapping(__isl_take isl_space
*dim
,
2214 ctx
= isl_space_get_ctx(dim
);
2215 mod
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2216 mod
= isl_val_2exp(mod
);
2218 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2219 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2220 aff
= isl_aff_mod_val(aff
, mod
);
2225 /* Project out the parameter "id" from "set".
2227 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2228 __isl_keep isl_id
*id
)
2232 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2234 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2239 /* Compute the set of parameters for which "set1" is a subset of "set2".
2241 * set1 is a subset of set2 if
2243 * forall i in set1 : i in set2
2247 * not exists i in set1 and i not in set2
2251 * not exists i in set1 \ set2
2253 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2254 __isl_take isl_set
*set2
)
2256 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2259 /* Compute the set of parameter values for which "cond" holds
2260 * on the next iteration for each element of "dom".
2262 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2263 * and then compute the set of parameters for which the result is a subset
2266 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2267 __isl_take isl_set
*dom
, __isl_take isl_val
*inc
)
2273 space
= isl_set_get_space(dom
);
2274 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2275 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2276 aff
= isl_aff_add_constant_val(aff
, inc
);
2277 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2279 dom
= isl_set_apply(dom
, next
);
2281 return enforce_subset(dom
, cond
);
2284 /* Extract the for loop "stmt" as a while loop.
2285 * "iv" is the loop iterator. "init" is the initialization.
2286 * "inc" is the increment.
2288 * That is, the for loop has the form
2290 * for (iv = init; cond; iv += inc)
2301 * except that the skips resulting from any continue statements
2302 * in body do not apply to the increment, but are replaced by the skips
2303 * resulting from break statements.
2305 * If "iv" is declared in the for loop, then it is killed before
2306 * and after the loop.
2308 struct pet_scop
*PetScan::extract_non_affine_for(ForStmt
*stmt
, ValueDecl
*iv
,
2309 __isl_take pet_expr
*init
, __isl_take pet_expr
*inc
)
2312 int test_nr
, stmt_nr
;
2314 struct pet_scop
*scop_init
, *scop_inc
, *scop
, *scop_body
;
2316 struct pet_array
*array
;
2317 struct pet_scop
*scop_kill
;
2319 if (!allow_nested
) {
2324 clear_assignment(assigned_value
, iv
);
2326 declared
= !initialization_assignment(stmt
->getInit());
2328 expr_iv
= extract_access_expr(iv
);
2329 expr_iv
= mark_write(expr_iv
);
2330 type_size
= pet_expr_get_type_size(expr_iv
);
2331 init
= pet_expr_new_binary(type_size
, pet_op_assign
, expr_iv
, init
);
2332 scop_init
= extract(init
, stmt
->getInit()->getSourceRange(), false);
2333 scop_init
= pet_scop_prefix(scop_init
, declared
);
2337 scop_body
= extract(stmt
->getBody());
2339 pet_scop_free(scop_init
);
2343 expr_iv
= extract_access_expr(iv
);
2344 expr_iv
= mark_write(expr_iv
);
2345 type_size
= pet_expr_get_type_size(expr_iv
);
2346 inc
= pet_expr_new_binary(type_size
, pet_op_add_assign
, expr_iv
, inc
);
2347 scop_inc
= extract(inc
, stmt
->getInc()->getSourceRange(), false);
2349 pet_scop_free(scop_init
);
2350 pet_scop_free(scop_body
);
2354 scop
= extract_while(stmt
->getCond(), test_nr
, stmt_nr
, scop_body
,
2357 scop
= pet_scop_prefix(scop
, declared
+ 1);
2358 scop
= pet_scop_add_seq(ctx
, scop_init
, scop
);
2363 array
= extract_array(ctx
, iv
, NULL
);
2365 array
->declared
= 1;
2366 scop_kill
= kill(stmt
, array
);
2367 scop_kill
= pet_scop_prefix(scop_kill
, 0);
2368 scop
= pet_scop_add_seq(ctx
, scop_kill
, scop
);
2369 scop_kill
= kill(stmt
, array
);
2370 scop_kill
= pet_scop_add_array(scop_kill
, array
);
2371 scop_kill
= pet_scop_prefix(scop_kill
, 3);
2372 scop
= pet_scop_add_seq(ctx
, scop
, scop_kill
);
2377 /* Construct a pet_scop for a for statement.
2378 * The for loop is required to be of one of the following forms
2380 * for (i = init; condition; ++i)
2381 * for (i = init; condition; --i)
2382 * for (i = init; condition; i += constant)
2383 * for (i = init; condition; i -= constant)
2385 * The initialization of the for loop should either be an assignment
2386 * of a static affine value to an integer variable, or a declaration
2387 * of such a variable with initialization.
2389 * If the initialization or the increment do not satisfy the above
2390 * conditions, i.e., if the initialization is not static affine
2391 * or the increment is not constant, then the for loop is extracted
2392 * as a while loop instead.
2394 * The condition is allowed to contain nested accesses, provided
2395 * they are not being written to inside the body of the loop.
2396 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2397 * essentially treated as a while loop, with iteration domain
2398 * { [i] : i >= init }.
2400 * We extract a pet_scop for the body and then embed it in a loop with
2401 * iteration domain and schedule
2403 * { [i] : i >= init and condition' }
2408 * { [i] : i <= init and condition' }
2411 * Where condition' is equal to condition if the latter is
2412 * a simple upper [lower] bound and a condition that is extended
2413 * to apply to all previous iterations otherwise.
2415 * If the condition is non-affine, then we drop the condition from the
2416 * iteration domain and instead create a separate statement
2417 * for evaluating the condition. The body is then filtered to depend
2418 * on the result of the condition evaluating to true on all iterations
2419 * up to the current iteration, while the evaluation the condition itself
2420 * is filtered to depend on the result of the condition evaluating to true
2421 * on all previous iterations.
2422 * The context of the scop representing the body is dropped
2423 * because we don't know how many times the body will be executed,
2426 * If the stride of the loop is not 1, then "i >= init" is replaced by
2428 * (exists a: i = init + stride * a and a >= 0)
2430 * If the loop iterator i is unsigned, then wrapping may occur.
2431 * We therefore use a virtual iterator instead that does not wrap.
2432 * However, the condition in the code applies
2433 * to the wrapped value, so we need to change condition(i)
2434 * into condition([i % 2^width]). Similarly, we replace all accesses
2435 * to the original iterator by the wrapping of the virtual iterator.
2436 * Note that there may be no need to perform this final wrapping
2437 * if the loop condition (after wrapping) satisfies certain conditions.
2438 * However, the is_simple_bound condition is not enough since it doesn't
2439 * check if there even is an upper bound.
2441 * Wrapping on unsigned iterators can be avoided entirely if
2442 * loop condition is simple, the loop iterator is incremented
2443 * [decremented] by one and the last value before wrapping cannot
2444 * possibly satisfy the loop condition.
2446 * Before extracting a pet_scop from the body we remove all
2447 * assignments in assigned_value to variables that are assigned
2448 * somewhere in the body of the loop.
2450 * Valid parameters for a for loop are those for which the initial
2451 * value itself, the increment on each domain iteration and
2452 * the condition on both the initial value and
2453 * the result of incrementing the iterator for each iteration of the domain
2455 * If the loop condition is non-affine, then we only consider validity
2456 * of the initial value.
2458 * If the body contains any break, then we keep track of it in "skip"
2459 * (if the skip condition is affine) or it is handled in scop_add_break
2460 * (if the skip condition is not affine).
2461 * Note that the affine break condition needs to be considered with
2462 * respect to previous iterations in the virtual domain (if any).
2464 * If we were only able to extract part of the body, then simply
2467 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2469 BinaryOperator
*ass
;
2474 isl_local_space
*ls
;
2477 isl_set
*cond
= NULL
;
2478 isl_set
*skip
= NULL
;
2479 isl_id
*id
, *id_test
= NULL
, *id_break_test
;
2480 struct pet_scop
*scop
, *scop_cond
= NULL
;
2481 assigned_value_cache
cache(assigned_value
);
2487 bool has_affine_break
;
2489 isl_aff
*wrap
= NULL
;
2490 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2491 isl_set
*valid_init
;
2492 isl_set
*valid_cond
;
2493 isl_set
*valid_cond_init
;
2494 isl_set
*valid_cond_next
;
2497 pet_expr
*pe_init
, *pe_inc
;
2498 pet_context
*pc
, *pc_init_val
;
2500 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2501 return extract_infinite_for(stmt
);
2503 init
= stmt
->getInit();
2508 if ((ass
= initialization_assignment(init
)) != NULL
) {
2509 iv
= extract_induction_variable(ass
);
2512 lhs
= ass
->getLHS();
2513 rhs
= ass
->getRHS();
2514 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2515 VarDecl
*var
= extract_induction_variable(init
, decl
);
2519 rhs
= var
->getInit();
2520 lhs
= create_DeclRefExpr(var
);
2522 unsupported(stmt
->getInit());
2526 id
= create_decl_id(ctx
, iv
);
2528 assigned_value
.erase(iv
);
2529 clear_assignments
clear(assigned_value
);
2530 clear
.TraverseStmt(stmt
->getBody());
2532 pe_init
= extract_expr(rhs
);
2533 pe_inc
= extract_increment(stmt
, iv
);
2534 pc
= convert_assignments(ctx
, assigned_value
);
2535 pc_init_val
= pet_context_copy(pc
);
2536 pc_init_val
= pet_context_mark_unknown(pc_init_val
, isl_id_copy(id
));
2537 init_val
= pet_expr_extract_affine(pe_init
, pc_init_val
);
2538 pet_context_free(pc_init_val
);
2539 pa_inc
= pet_expr_extract_affine(pe_inc
, pc
);
2540 pet_context_free(pc
);
2541 inc
= pet_extract_cst(pa_inc
);
2542 if (!pe_init
|| !pe_inc
|| !inc
|| isl_val_is_nan(inc
) ||
2543 isl_pw_aff_involves_nan(pa_inc
) ||
2544 isl_pw_aff_involves_nan(init_val
)) {
2547 isl_pw_aff_free(pa_inc
);
2548 isl_pw_aff_free(init_val
);
2549 if (pe_init
&& pe_inc
&& !(pa_inc
&& !inc
))
2550 return extract_non_affine_for(stmt
, iv
,
2552 pet_expr_free(pe_init
);
2553 pet_expr_free(pe_inc
);
2556 pet_expr_free(pe_init
);
2557 pet_expr_free(pe_inc
);
2559 pa
= try_extract_nested_condition(stmt
->getCond());
2560 if (allow_nested
&& (!pa
|| pet_nested_any_in_pw_aff(pa
)))
2563 scop
= extract(stmt
->getBody());
2566 isl_pw_aff_free(init_val
);
2567 isl_pw_aff_free(pa_inc
);
2568 isl_pw_aff_free(pa
);
2573 valid_inc
= isl_pw_aff_domain(pa_inc
);
2575 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2577 has_affine_break
= scop
&&
2578 pet_scop_has_affine_skip(scop
, pet_skip_later
);
2579 if (has_affine_break
)
2580 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
2581 has_var_break
= scop
&& pet_scop_has_var_skip(scop
, pet_skip_later
);
2583 id_break_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
2585 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2586 isl_pw_aff_free(pa
);
2590 if (!allow_nested
&& !pa
)
2591 pa
= try_extract_affine_condition(stmt
->getCond());
2592 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2593 cond
= isl_pw_aff_non_zero_set(pa
);
2594 if (allow_nested
&& !cond
) {
2595 isl_multi_pw_aff
*test_index
;
2596 int save_n_stmt
= n_stmt
;
2597 test_index
= pet_create_test_index(ctx
, n_test
++);
2599 scop_cond
= extract_non_affine_condition(stmt
->getCond(),
2600 n_stmt
++, isl_multi_pw_aff_copy(test_index
));
2601 n_stmt
= save_n_stmt
;
2602 scop_cond
= scop_add_array(scop_cond
, test_index
, ast_context
);
2603 id_test
= isl_multi_pw_aff_get_tuple_id(test_index
,
2605 isl_multi_pw_aff_free(test_index
);
2606 scop_cond
= pet_scop_prefix(scop_cond
, 0);
2607 scop
= pet_scop_reset_context(scop
);
2608 scop
= pet_scop_prefix(scop
, 1);
2609 cond
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2612 cond
= embed(cond
, isl_id_copy(id
));
2613 skip
= embed(skip
, isl_id_copy(id
));
2614 valid_cond
= isl_set_coalesce(valid_cond
);
2615 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
2616 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
2617 is_one
= isl_val_is_one(inc
) || isl_val_is_negone(inc
);
2618 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2620 valid_cond_init
= enforce_subset(
2621 isl_map_range(isl_map_from_pw_aff(isl_pw_aff_copy(init_val
))),
2622 isl_set_copy(valid_cond
));
2623 if (is_one
&& !is_virtual
) {
2624 isl_pw_aff_free(init_val
);
2625 pa
= extract_comparison(isl_val_is_pos(inc
) ? BO_GE
: BO_LE
,
2627 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2628 valid_init
= set_project_out_by_id(valid_init
, id
);
2629 domain
= isl_pw_aff_non_zero_set(pa
);
2631 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
2632 domain
= strided_domain(isl_id_copy(id
), init_val
,
2636 domain
= embed(domain
, isl_id_copy(id
));
2639 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2640 rev_wrap
= isl_map_from_aff(isl_aff_copy(wrap
));
2641 rev_wrap
= isl_map_reverse(rev_wrap
);
2642 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
2643 skip
= isl_set_apply(skip
, isl_map_copy(rev_wrap
));
2644 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
2645 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
2647 is_simple
= is_simple_bound(cond
, inc
);
2649 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2650 is_simple
= is_simple_bound(cond
, inc
);
2653 cond
= valid_for_each_iteration(cond
,
2654 isl_set_copy(domain
), isl_val_copy(inc
));
2655 domain
= isl_set_intersect(domain
, cond
);
2656 if (has_affine_break
) {
2657 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2658 skip
= after(skip
, isl_val_sgn(inc
));
2659 domain
= isl_set_subtract(domain
, skip
);
2661 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2662 ls
= isl_local_space_from_space(isl_set_get_space(domain
));
2663 sched
= isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
2664 if (isl_val_is_neg(inc
))
2665 sched
= isl_aff_neg(sched
);
2667 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
),
2669 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
2672 wrap
= identity_aff(domain
);
2674 scop_cond
= pet_scop_embed(scop_cond
, isl_set_copy(domain
),
2675 isl_aff_copy(sched
), isl_aff_copy(wrap
), isl_id_copy(id
));
2676 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), sched
, wrap
, id
);
2677 scop
= resolve_nested(scop
);
2679 scop
= scop_add_break(scop
, id_break_test
, isl_set_copy(domain
),
2682 scop
= scop_add_while(scop_cond
, scop
, id_test
, domain
,
2684 isl_set_free(valid_inc
);
2686 scop
= pet_scop_restrict_context(scop
, valid_inc
);
2687 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
2688 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
2689 isl_set_free(domain
);
2691 clear_assignment(assigned_value
, iv
);
2695 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid_init
));
2700 /* Try and construct a pet_scop corresponding to a compound statement.
2702 * "skip_declarations" is set if we should skip initial declarations
2703 * in the children of the compound statements. This then implies
2704 * that this sequence of children should not be treated as a block
2705 * since the initial statements may be skipped.
2707 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
, bool skip_declarations
)
2709 return extract(stmt
->children(), !skip_declarations
, skip_declarations
);
2712 /* For each nested access parameter in "space",
2713 * construct a corresponding pet_expr, place it in args and
2714 * record its position in "param2pos".
2715 * "n_arg" is the number of elements that are already in args.
2716 * The position recorded in "param2pos" takes this number into account.
2717 * If the pet_expr corresponding to a parameter is identical to
2718 * the pet_expr corresponding to an earlier parameter, then these two
2719 * parameters are made to refer to the same element in args.
2721 * Return the final number of elements in args or -1 if an error has occurred.
2723 int PetScan::extract_nested(__isl_keep isl_space
*space
,
2724 int n_arg
, pet_expr
**args
, std::map
<int,int> ¶m2pos
)
2728 nparam
= isl_space_dim(space
, isl_dim_param
);
2729 for (int i
= 0; i
< nparam
; ++i
) {
2731 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2733 if (!pet_nested_in_id(id
)) {
2738 args
[n_arg
] = pet_nested_extract_expr(id
);
2743 for (j
= 0; j
< n_arg
; ++j
)
2744 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
2748 pet_expr_free(args
[n_arg
]);
2752 param2pos
[i
] = n_arg
++;
2758 /* For each nested access parameter in the access relations in "expr",
2759 * construct a corresponding pet_expr, append it to the arguments of "expr"
2760 * and record its position in "param2pos" (relative to the initial
2761 * number of arguments).
2762 * n is the number of nested access parameters.
2764 __isl_give pet_expr
*PetScan::extract_nested(__isl_take pet_expr
*expr
, int n
,
2765 std::map
<int,int> ¶m2pos
)
2771 args
= isl_calloc_array(ctx
, pet_expr
*, n
);
2773 return pet_expr_free(expr
);
2775 n_arg
= pet_expr_get_n_arg(expr
);
2776 space
= pet_expr_access_get_parameter_space(expr
);
2777 n
= extract_nested(space
, 0, args
, param2pos
);
2778 isl_space_free(space
);
2781 expr
= pet_expr_free(expr
);
2783 expr
= pet_expr_set_n_arg(expr
, n_arg
+ n
);
2785 for (i
= 0; i
< n
; ++i
)
2786 expr
= pet_expr_set_arg(expr
, n_arg
+ i
, args
[i
]);
2792 /* Are "expr1" and "expr2" both array accesses such that
2793 * the access relation of "expr1" is a subset of that of "expr2"?
2794 * Only take into account the first "n_arg" arguments.
2796 static int is_sub_access(__isl_keep pet_expr
*expr1
, __isl_keep pet_expr
*expr2
,
2800 isl_map
*access1
, *access2
;
2804 if (!expr1
|| !expr2
)
2806 if (pet_expr_get_type(expr1
) != pet_expr_access
)
2808 if (pet_expr_get_type(expr2
) != pet_expr_access
)
2810 if (pet_expr_is_affine(expr1
))
2812 if (pet_expr_is_affine(expr2
))
2814 n1
= pet_expr_get_n_arg(expr1
);
2817 n2
= pet_expr_get_n_arg(expr2
);
2822 for (i
= 0; i
< n1
; ++i
) {
2823 pet_expr
*arg1
, *arg2
;
2825 arg1
= pet_expr_get_arg(expr1
, i
);
2826 arg2
= pet_expr_get_arg(expr2
, i
);
2827 equal
= pet_expr_is_equal(arg1
, arg2
);
2828 pet_expr_free(arg1
);
2829 pet_expr_free(arg2
);
2830 if (equal
< 0 || !equal
)
2833 id1
= pet_expr_access_get_id(expr1
);
2834 id2
= pet_expr_access_get_id(expr2
);
2842 access1
= pet_expr_access_get_access(expr1
);
2843 access2
= pet_expr_access_get_access(expr2
);
2844 is_subset
= isl_map_is_subset(access1
, access2
);
2845 isl_map_free(access1
);
2846 isl_map_free(access2
);
2851 /* Mark self dependences among the arguments of "expr" starting at "first".
2852 * These arguments have already been added to the list of arguments
2853 * but are not yet referenced directly from the index expression.
2854 * Instead, they are still referenced through parameters encoding
2857 * In particular, if "expr" is a read access, then check the arguments
2858 * starting at "first" to see if "expr" accesses a subset of
2859 * the elements accessed by the argument, or under more restrictive conditions.
2860 * If so, then this nested access can be removed from the constraints
2861 * governing the outer access. There is no point in restricting
2862 * accesses to an array if in order to evaluate the restriction,
2863 * we have to access the same elements (or more).
2865 * Rather than removing the argument at this point (which would
2866 * complicate the resolution of the other nested accesses), we simply
2867 * mark it here by replacing it by a NaN pet_expr.
2868 * These NaNs are then later removed in remove_marked_self_dependences.
2870 static __isl_give pet_expr
*mark_self_dependences(__isl_take pet_expr
*expr
,
2875 if (pet_expr_access_is_write(expr
))
2878 n
= pet_expr_get_n_arg(expr
);
2879 for (int i
= first
; i
< n
; ++i
) {
2883 arg
= pet_expr_get_arg(expr
, i
);
2884 mark
= is_sub_access(expr
, arg
, first
);
2887 return pet_expr_free(expr
);
2891 arg
= pet_expr_new_int(isl_val_nan(pet_expr_get_ctx(expr
)));
2892 expr
= pet_expr_set_arg(expr
, i
, arg
);
2898 /* Is "expr" a NaN integer expression?
2900 static int expr_is_nan(__isl_keep pet_expr
*expr
)
2905 if (pet_expr_get_type(expr
) != pet_expr_int
)
2908 v
= pet_expr_int_get_val(expr
);
2909 is_nan
= isl_val_is_nan(v
);
2915 /* Check if we have marked any self dependences (as NaNs)
2916 * in mark_self_dependences and remove them here.
2917 * It is safe to project them out since these arguments
2918 * can at most be referenced from the condition of the access relation,
2919 * but do not appear in the index expression.
2920 * "dim" is the dimension of the iteration domain.
2922 static __isl_give pet_expr
*remove_marked_self_dependences(
2923 __isl_take pet_expr
*expr
, int dim
, int first
)
2927 n
= pet_expr_get_n_arg(expr
);
2928 for (int i
= n
- 1; i
>= first
; --i
) {
2932 arg
= pet_expr_get_arg(expr
, i
);
2933 is_nan
= expr_is_nan(arg
);
2937 expr
= pet_expr_access_project_out_arg(expr
, dim
, i
);
2943 /* Look for parameters in any access relation in "expr" that
2944 * refer to nested accesses. In particular, these are
2945 * parameters with name "__pet_expr".
2947 * If there are any such parameters, then the domain of the index
2948 * expression and the access relation, which is either [] or
2949 * [[] -> [a_1,...,a_m]] at this point, is replaced by [[] -> [t_1,...,t_n]] or
2950 * [[] -> [a_1,...,a_m,t_1,...,t_n]], with m the original number of arguments
2951 * (n_arg) and n the number of these parameters
2952 * (after identifying identical nested accesses).
2954 * This transformation is performed in several steps.
2955 * We first extract the arguments in extract_nested.
2956 * param2pos maps the original parameter position to the position
2957 * of the argument beyond the initial (n_arg) number of arguments.
2958 * Then we move these parameters to input dimensions.
2959 * t2pos maps the positions of these temporary input dimensions
2960 * to the positions of the corresponding arguments.
2961 * Finally, we express these temporary dimensions in terms of the domain
2962 * [[] -> [a_1,...,a_m,t_1,...,t_n]] and precompose index expression and access
2963 * relations with this function.
2965 __isl_give pet_expr
*PetScan::resolve_nested(__isl_take pet_expr
*expr
)
2970 isl_local_space
*ls
;
2973 std::map
<int,int> param2pos
;
2974 std::map
<int,int> t2pos
;
2979 n_arg
= pet_expr_get_n_arg(expr
);
2980 for (int i
= 0; i
< n_arg
; ++i
) {
2982 arg
= pet_expr_get_arg(expr
, i
);
2983 arg
= resolve_nested(arg
);
2984 expr
= pet_expr_set_arg(expr
, i
, arg
);
2987 if (pet_expr_get_type(expr
) != pet_expr_access
)
2990 space
= pet_expr_access_get_parameter_space(expr
);
2991 n
= pet_nested_n_in_space(space
);
2992 isl_space_free(space
);
2996 expr
= extract_nested(expr
, n
, param2pos
);
3000 expr
= pet_expr_access_align_params(expr
);
3001 expr
= mark_self_dependences(expr
, n_arg
);
3006 space
= pet_expr_access_get_parameter_space(expr
);
3007 nparam
= isl_space_dim(space
, isl_dim_param
);
3008 for (int i
= nparam
- 1; i
>= 0; --i
) {
3009 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
3010 if (!pet_nested_in_id(id
)) {
3015 expr
= pet_expr_access_move_dims(expr
,
3016 isl_dim_in
, n_arg
+ n
, isl_dim_param
, i
, 1);
3017 t2pos
[n
] = n_arg
+ param2pos
[i
];
3022 isl_space_free(space
);
3024 space
= pet_expr_access_get_parameter_space(expr
);
3025 space
= isl_space_set_from_params(space
);
3026 space
= isl_space_add_dims(space
, isl_dim_set
,
3027 pet_expr_get_n_arg(expr
));
3028 space
= isl_space_wrap(isl_space_from_range(space
));
3029 ls
= isl_local_space_from_space(isl_space_copy(space
));
3030 space
= isl_space_from_domain(space
);
3031 space
= isl_space_add_dims(space
, isl_dim_out
, n_arg
+ n
);
3032 ma
= isl_multi_aff_zero(space
);
3034 for (int i
= 0; i
< n_arg
; ++i
) {
3035 aff
= isl_aff_var_on_domain(isl_local_space_copy(ls
),
3037 ma
= isl_multi_aff_set_aff(ma
, i
, aff
);
3039 for (int i
= 0; i
< n
; ++i
) {
3040 aff
= isl_aff_var_on_domain(isl_local_space_copy(ls
),
3041 isl_dim_set
, t2pos
[i
]);
3042 ma
= isl_multi_aff_set_aff(ma
, n_arg
+ i
, aff
);
3044 isl_local_space_free(ls
);
3046 expr
= pet_expr_access_pullback_multi_aff(expr
, ma
);
3048 expr
= remove_marked_self_dependences(expr
, 0, n_arg
);
3053 /* Return the file offset of the expansion location of "Loc".
3055 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
3057 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
3060 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3062 /* Return a SourceLocation for the location after the first semicolon
3063 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3064 * call it and also skip trailing spaces and newline.
3066 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3067 const LangOptions
&LO
)
3069 return Lexer::findLocationAfterToken(loc
, tok::semi
, SM
, LO
, true);
3074 /* Return a SourceLocation for the location after the first semicolon
3075 * after "loc". If Lexer::findLocationAfterToken is not available,
3076 * we look in the underlying character data for the first semicolon.
3078 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3079 const LangOptions
&LO
)
3082 const char *s
= SM
.getCharacterData(loc
);
3084 semi
= strchr(s
, ';');
3086 return SourceLocation();
3087 return loc
.getFileLocWithOffset(semi
+ 1 - s
);
3092 /* If the token at "loc" is the first token on the line, then return
3093 * a location referring to the start of the line.
3094 * Otherwise, return "loc".
3096 * This function is used to extend a scop to the start of the line
3097 * if the first token of the scop is also the first token on the line.
3099 * We look for the first token on the line. If its location is equal to "loc",
3100 * then the latter is the location of the first token on the line.
3102 static SourceLocation
move_to_start_of_line_if_first_token(SourceLocation loc
,
3103 SourceManager
&SM
, const LangOptions
&LO
)
3105 std::pair
<FileID
, unsigned> file_offset_pair
;
3106 llvm::StringRef file
;
3109 SourceLocation token_loc
, line_loc
;
3112 loc
= SM
.getExpansionLoc(loc
);
3113 col
= SM
.getExpansionColumnNumber(loc
);
3114 line_loc
= loc
.getLocWithOffset(1 - col
);
3115 file_offset_pair
= SM
.getDecomposedLoc(line_loc
);
3116 file
= SM
.getBufferData(file_offset_pair
.first
, NULL
);
3117 pos
= file
.data() + file_offset_pair
.second
;
3119 Lexer
lexer(SM
.getLocForStartOfFile(file_offset_pair
.first
), LO
,
3120 file
.begin(), pos
, file
.end());
3121 lexer
.LexFromRawLexer(tok
);
3122 token_loc
= tok
.getLocation();
3124 if (token_loc
== loc
)
3130 /* Update start and end of "scop" to include the region covered by "range".
3131 * If "skip_semi" is set, then we assume "range" is followed by
3132 * a semicolon and also include this semicolon.
3134 struct pet_scop
*PetScan::update_scop_start_end(struct pet_scop
*scop
,
3135 SourceRange range
, bool skip_semi
)
3137 SourceLocation loc
= range
.getBegin();
3138 SourceManager
&SM
= PP
.getSourceManager();
3139 const LangOptions
&LO
= PP
.getLangOpts();
3140 unsigned start
, end
;
3142 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
);
3143 start
= getExpansionOffset(SM
, loc
);
3144 loc
= range
.getEnd();
3146 loc
= location_after_semi(loc
, SM
, LO
);
3148 loc
= PP
.getLocForEndOfToken(loc
);
3149 end
= getExpansionOffset(SM
, loc
);
3151 scop
= pet_scop_update_start_end(scop
, start
, end
);
3155 /* Convert a top-level pet_expr to a pet_scop with one statement.
3156 * This mainly involves resolving nested expression parameters
3157 * and setting the name of the iteration space.
3158 * The name is given by "label" if it is non-NULL. Otherwise,
3159 * it is of the form S_<n_stmt>.
3160 * start and end of the pet_scop are derived from "range" and "skip_semi".
3161 * In particular, if "skip_semi" is set then the semicolon following "range"
3164 struct pet_scop
*PetScan::extract(__isl_take pet_expr
*expr
, SourceRange range
,
3165 bool skip_semi
, __isl_take isl_id
*label
)
3167 struct pet_stmt
*ps
;
3168 struct pet_scop
*scop
;
3169 SourceLocation loc
= range
.getBegin();
3170 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3173 pc
= convert_assignments(ctx
, assigned_value
);
3174 expr
= pet_expr_plug_in_args(expr
, pc
);
3175 pet_context_free(pc
);
3177 expr
= resolve_nested(expr
);
3178 ps
= pet_stmt_from_pet_expr(line
, label
, n_stmt
++, expr
);
3179 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3181 scop
= update_scop_start_end(scop
, range
, skip_semi
);
3185 /* Check if we can extract an affine constraint from "expr".
3186 * Return the constraint as an isl_set if we can and NULL otherwise.
3187 * We turn on autodetection so that we won't generate any warnings
3188 * and turn off nesting, so that we won't accept any non-affine constructs.
3190 __isl_give isl_pw_aff
*PetScan::try_extract_affine_condition(Expr
*expr
)
3193 int save_autodetect
= options
->autodetect
;
3194 bool save_nesting
= nesting_enabled
;
3196 options
->autodetect
= 1;
3197 nesting_enabled
= false;
3199 cond
= extract_condition(expr
);
3201 options
->autodetect
= save_autodetect
;
3202 nesting_enabled
= save_nesting
;
3207 /* Check whether "expr" is an affine constraint.
3209 bool PetScan::is_affine_condition(Expr
*expr
)
3213 cond
= try_extract_affine_condition(expr
);
3214 isl_pw_aff_free(cond
);
3216 return cond
!= NULL
;
3219 /* Check if we can extract a condition from "expr".
3220 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3221 * If allow_nested is set, then the condition may involve parameters
3222 * corresponding to nested accesses.
3223 * We turn on autodetection so that we won't generate any warnings.
3225 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
3228 int save_autodetect
= options
->autodetect
;
3229 bool save_nesting
= nesting_enabled
;
3231 options
->autodetect
= 1;
3232 nesting_enabled
= allow_nested
;
3233 cond
= extract_condition(expr
);
3235 options
->autodetect
= save_autodetect
;
3236 nesting_enabled
= save_nesting
;
3241 /* If the top-level expression of "stmt" is an assignment, then
3242 * return that assignment as a BinaryOperator.
3243 * Otherwise return NULL.
3245 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
3247 BinaryOperator
*ass
;
3251 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
3254 ass
= cast
<BinaryOperator
>(stmt
);
3255 if(ass
->getOpcode() != BO_Assign
)
3261 /* Check if the given if statement is a conditional assignement
3262 * with a non-affine condition. If so, construct a pet_scop
3263 * corresponding to this conditional assignment. Otherwise return NULL.
3265 * In particular we check if "stmt" is of the form
3272 * where a is some array or scalar access.
3273 * The constructed pet_scop then corresponds to the expression
3275 * a = condition ? f(...) : g(...)
3277 * All access relations in f(...) are intersected with condition
3278 * while all access relation in g(...) are intersected with the complement.
3280 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
3282 BinaryOperator
*ass_then
, *ass_else
;
3283 pet_expr
*write_then
, *write_else
;
3284 isl_set
*cond
, *comp
;
3285 isl_multi_pw_aff
*index
;
3289 pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
;
3290 bool save_nesting
= nesting_enabled
;
3292 if (!options
->detect_conditional_assignment
)
3295 ass_then
= top_assignment_or_null(stmt
->getThen());
3296 ass_else
= top_assignment_or_null(stmt
->getElse());
3298 if (!ass_then
|| !ass_else
)
3301 if (is_affine_condition(stmt
->getCond()))
3304 write_then
= extract_access_expr(ass_then
->getLHS());
3305 write_else
= extract_access_expr(ass_else
->getLHS());
3307 equal
= pet_expr_is_equal(write_then
, write_else
);
3308 pet_expr_free(write_else
);
3309 if (equal
< 0 || !equal
) {
3310 pet_expr_free(write_then
);
3314 nesting_enabled
= allow_nested
;
3315 pa
= extract_condition(stmt
->getCond());
3316 nesting_enabled
= save_nesting
;
3317 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
3318 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
3319 index
= isl_multi_pw_aff_from_pw_aff(pa
);
3321 pe_cond
= pet_expr_from_index(index
);
3323 pe_then
= extract_expr(ass_then
->getRHS());
3324 pe_then
= pet_expr_restrict(pe_then
, cond
);
3325 pe_else
= extract_expr(ass_else
->getRHS());
3326 pe_else
= pet_expr_restrict(pe_else
, comp
);
3328 pe
= pet_expr_new_ternary(pe_cond
, pe_then
, pe_else
);
3329 write_then
= pet_expr_access_set_write(write_then
, 1);
3330 write_then
= pet_expr_access_set_read(write_then
, 0);
3331 type_size
= get_type_size(ass_then
->getType(), ast_context
);
3332 pe
= pet_expr_new_binary(type_size
, pet_op_assign
, write_then
, pe
);
3333 return extract(pe
, stmt
->getSourceRange(), false);
3336 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3337 * evaluating "cond" and writing the result to a virtual scalar,
3338 * as expressed by "index".
3340 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
, int stmt_nr
,
3341 __isl_take isl_multi_pw_aff
*index
)
3343 pet_expr
*expr
, *write
;
3344 struct pet_stmt
*ps
;
3345 SourceLocation loc
= cond
->getLocStart();
3346 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3349 write
= pet_expr_from_index(index
);
3350 write
= pet_expr_access_set_write(write
, 1);
3351 write
= pet_expr_access_set_read(write
, 0);
3352 expr
= extract_expr(cond
);
3354 pc
= convert_assignments(ctx
, assigned_value
);
3355 expr
= pet_expr_plug_in_args(expr
, pc
);
3356 pet_context_free(pc
);
3358 expr
= resolve_nested(expr
);
3359 expr
= pet_expr_new_binary(1, pet_op_assign
, write
, expr
);
3360 ps
= pet_stmt_from_pet_expr(line
, NULL
, stmt_nr
, expr
);
3361 return pet_scop_from_pet_stmt(ctx
, ps
);
3365 static __isl_give pet_expr
*embed_access(__isl_take pet_expr
*expr
,
3369 /* Precompose the access relation and the index expression associated
3370 * to "expr" with the function pointed to by "user",
3371 * thereby embedding the access relation in the domain of this function.
3372 * The initial domain of the access relation and the index expression
3373 * is the zero-dimensional domain.
3375 static __isl_give pet_expr
*embed_access(__isl_take pet_expr
*expr
, void *user
)
3377 isl_multi_aff
*ma
= (isl_multi_aff
*) user
;
3379 return pet_expr_access_pullback_multi_aff(expr
, isl_multi_aff_copy(ma
));
3382 /* Precompose all access relations in "expr" with "ma", thereby
3383 * embedding them in the domain of "ma".
3385 static __isl_give pet_expr
*embed(__isl_take pet_expr
*expr
,
3386 __isl_keep isl_multi_aff
*ma
)
3388 return pet_expr_map_access(expr
, &embed_access
, ma
);
3391 /* For each nested access parameter in the domain of "stmt",
3392 * construct a corresponding pet_expr, place it before the original
3393 * elements in stmt->args and record its position in "param2pos".
3394 * n is the number of nested access parameters.
3396 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
3397 std::map
<int,int> ¶m2pos
)
3404 n_arg
= stmt
->n_arg
;
3405 args
= isl_calloc_array(ctx
, pet_expr
*, n
+ n_arg
);
3409 space
= isl_set_get_space(stmt
->domain
);
3410 n_arg
= extract_nested(space
, 0, args
, param2pos
);
3411 isl_space_free(space
);
3416 for (i
= 0; i
< stmt
->n_arg
; ++i
)
3417 args
[n_arg
+ i
] = stmt
->args
[i
];
3420 stmt
->n_arg
+= n_arg
;
3425 for (i
= 0; i
< n
; ++i
)
3426 pet_expr_free(args
[i
]);
3429 pet_stmt_free(stmt
);
3433 /* Check whether any of the arguments i of "stmt" starting at position "n"
3434 * is equal to one of the first "n" arguments j.
3435 * If so, combine the constraints on arguments i and j and remove
3438 static struct pet_stmt
*remove_duplicate_arguments(struct pet_stmt
*stmt
, int n
)
3447 if (n
== stmt
->n_arg
)
3450 map
= isl_set_unwrap(stmt
->domain
);
3452 for (i
= stmt
->n_arg
- 1; i
>= n
; --i
) {
3453 for (j
= 0; j
< n
; ++j
)
3454 if (pet_expr_is_equal(stmt
->args
[i
], stmt
->args
[j
]))
3459 map
= isl_map_equate(map
, isl_dim_out
, i
, isl_dim_out
, j
);
3460 map
= isl_map_project_out(map
, isl_dim_out
, i
, 1);
3462 pet_expr_free(stmt
->args
[i
]);
3463 for (j
= i
; j
+ 1 < stmt
->n_arg
; ++j
)
3464 stmt
->args
[j
] = stmt
->args
[j
+ 1];
3468 stmt
->domain
= isl_map_wrap(map
);
3473 pet_stmt_free(stmt
);
3477 /* Look for parameters in the iteration domain of "stmt" that
3478 * refer to nested accesses. In particular, these are
3479 * parameters with name "__pet_expr".
3481 * If there are any such parameters, then as many extra variables
3482 * (after identifying identical nested accesses) are inserted in the
3483 * range of the map wrapped inside the domain, before the original variables.
3484 * If the original domain is not a wrapped map, then a new wrapped
3485 * map is created with zero output dimensions.
3486 * The parameters are then equated to the corresponding output dimensions
3487 * and subsequently projected out, from the iteration domain,
3488 * the schedule and the access relations.
3489 * For each of the output dimensions, a corresponding argument
3490 * expression is inserted. Initially they are created with
3491 * a zero-dimensional domain, so they have to be embedded
3492 * in the current iteration domain.
3493 * param2pos maps the position of the parameter to the position
3494 * of the corresponding output dimension in the wrapped map.
3496 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3504 std::map
<int,int> param2pos
;
3509 n
= pet_nested_n_in_set(stmt
->domain
);
3513 n_arg
= stmt
->n_arg
;
3514 stmt
= extract_nested(stmt
, n
, param2pos
);
3518 n
= stmt
->n_arg
- n_arg
;
3519 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3520 if (isl_set_is_wrapping(stmt
->domain
))
3521 map
= isl_set_unwrap(stmt
->domain
);
3523 map
= isl_map_from_domain(stmt
->domain
);
3524 map
= isl_map_insert_dims(map
, isl_dim_out
, 0, n
);
3526 for (int i
= nparam
- 1; i
>= 0; --i
) {
3529 if (!pet_nested_in_map(map
, i
))
3532 id
= pet_expr_access_get_id(stmt
->args
[param2pos
[i
]]);
3533 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3534 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3536 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3539 stmt
->domain
= isl_map_wrap(map
);
3541 space
= isl_space_unwrap(isl_set_get_space(stmt
->domain
));
3542 space
= isl_space_from_domain(isl_space_domain(space
));
3543 ma
= isl_multi_aff_zero(space
);
3544 for (int pos
= 0; pos
< n
; ++pos
)
3545 stmt
->args
[pos
] = embed(stmt
->args
[pos
], ma
);
3546 isl_multi_aff_free(ma
);
3548 stmt
= pet_stmt_remove_nested_parameters(stmt
);
3549 stmt
= remove_duplicate_arguments(stmt
, n
);
3554 /* For each statement in "scop", move the parameters that correspond
3555 * to nested access into the ranges of the domains and create
3556 * corresponding argument expressions.
3558 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3563 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3564 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3565 if (!scop
->stmts
[i
])
3571 pet_scop_free(scop
);
3575 /* Given an access expression "expr", is the variable accessed by
3576 * "expr" assigned anywhere inside "scop"?
3578 static bool is_assigned(__isl_keep pet_expr
*expr
, pet_scop
*scop
)
3580 bool assigned
= false;
3583 id
= pet_expr_access_get_id(expr
);
3584 assigned
= pet_scop_writes(scop
, id
);
3590 /* Are all nested access parameters in "pa" allowed given "scop".
3591 * In particular, is none of them written by anywhere inside "scop".
3593 * If "scop" has any skip conditions, then no nested access parameters
3594 * are allowed. In particular, if there is any nested access in a guard
3595 * for a piece of code containing a "continue", then we want to introduce
3596 * a separate statement for evaluating this guard so that we can express
3597 * that the result is false for all previous iterations.
3599 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3606 if (!pet_nested_any_in_pw_aff(pa
))
3609 if (pet_scop_has_skip(scop
, pet_skip_now
))
3612 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3613 for (int i
= 0; i
< nparam
; ++i
) {
3614 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3618 if (!pet_nested_in_id(id
)) {
3623 expr
= pet_nested_extract_expr(id
);
3624 allowed
= pet_expr_get_type(expr
) == pet_expr_access
&&
3625 !is_assigned(expr
, scop
);
3627 pet_expr_free(expr
);
3637 /* Construct a pet_scop for a non-affine if statement.
3639 * We create a separate statement that writes the result
3640 * of the non-affine condition to a virtual scalar.
3641 * A constraint requiring the value of this virtual scalar to be one
3642 * is added to the iteration domains of the then branch.
3643 * Similarly, a constraint requiring the value of this virtual scalar
3644 * to be zero is added to the iteration domains of the else branch, if any.
3645 * We adjust the schedules to ensure that the virtual scalar is written
3646 * before it is read.
3648 * If there are any breaks or continues in the then and/or else
3649 * branches, then we may have to compute a new skip condition.
3650 * This is handled using a pet_skip_info object.
3651 * On initialization, the object checks if skip conditions need
3652 * to be computed. If so, it does so in pet_skip_info_if_extract_index and
3653 * adds them in pet_skip_info_if_add.
3655 struct pet_scop
*PetScan::extract_non_affine_if(Expr
*cond
,
3656 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3657 bool have_else
, int stmt_id
)
3659 struct pet_scop
*scop
;
3660 isl_multi_pw_aff
*test_index
;
3662 int save_n_stmt
= n_stmt
;
3664 test_index
= pet_create_test_index(ctx
, n_test
++);
3666 scop
= extract_non_affine_condition(cond
, n_stmt
++,
3667 isl_multi_pw_aff_copy(test_index
));
3668 n_stmt
= save_n_stmt
;
3669 scop
= scop_add_array(scop
, test_index
, ast_context
);
3672 pet_skip_info_if_init(&skip
, ctx
, scop_then
, scop_else
, have_else
, 0);
3673 int_size
= ast_context
.getTypeInfo(ast_context
.IntTy
).first
/ 8;
3674 pet_skip_info_if_extract_index(&skip
, test_index
, int_size
,
3677 scop
= pet_scop_prefix(scop
, 0);
3678 scop_then
= pet_scop_prefix(scop_then
, 1);
3679 scop_then
= pet_scop_filter(scop_then
,
3680 isl_multi_pw_aff_copy(test_index
), 1);
3682 scop_else
= pet_scop_prefix(scop_else
, 1);
3683 scop_else
= pet_scop_filter(scop_else
, test_index
, 0);
3684 scop_then
= pet_scop_add_par(ctx
, scop_then
, scop_else
);
3686 isl_multi_pw_aff_free(test_index
);
3688 scop
= pet_scop_add_seq(ctx
, scop
, scop_then
);
3690 scop
= pet_skip_info_if_add(&skip
, scop
, 2);
3695 /* Construct a pet_scop for an if statement.
3697 * If the condition fits the pattern of a conditional assignment,
3698 * then it is handled by extract_conditional_assignment.
3699 * Otherwise, we do the following.
3701 * If the condition is affine, then the condition is added
3702 * to the iteration domains of the then branch, while the
3703 * opposite of the condition in added to the iteration domains
3704 * of the else branch, if any.
3705 * We allow the condition to be dynamic, i.e., to refer to
3706 * scalars or array elements that may be written to outside
3707 * of the given if statement. These nested accesses are then represented
3708 * as output dimensions in the wrapping iteration domain.
3709 * If it is also written _inside_ the then or else branch, then
3710 * we treat the condition as non-affine.
3711 * As explained in extract_non_affine_if, this will introduce
3712 * an extra statement.
3713 * For aesthetic reasons, we want this statement to have a statement
3714 * number that is lower than those of the then and else branches.
3715 * In order to evaluate if we will need such a statement, however, we
3716 * first construct scops for the then and else branches.
3717 * We therefore reserve a statement number if we might have to
3718 * introduce such an extra statement.
3720 * If the condition is not affine, then the scop is created in
3721 * extract_non_affine_if.
3723 * If there are any breaks or continues in the then and/or else
3724 * branches, then we may have to compute a new skip condition.
3725 * This is handled using a pet_skip_info object.
3726 * On initialization, the object checks if skip conditions need
3727 * to be computed. If so, it does so in pet_skip_info_if_extract_cond and
3728 * adds them in pet_skip_info_if_add.
3730 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
3732 struct pet_scop
*scop_then
, *scop_else
= NULL
, *scop
;
3739 clear_assignments
clear(assigned_value
);
3740 clear
.TraverseStmt(stmt
->getThen());
3741 if (stmt
->getElse())
3742 clear
.TraverseStmt(stmt
->getElse());
3744 scop
= extract_conditional_assignment(stmt
);
3748 cond
= try_extract_nested_condition(stmt
->getCond());
3749 if (allow_nested
&& (!cond
|| pet_nested_any_in_pw_aff(cond
)))
3753 assigned_value_cache
cache(assigned_value
);
3754 scop_then
= extract(stmt
->getThen());
3757 if (stmt
->getElse()) {
3758 assigned_value_cache
cache(assigned_value
);
3759 scop_else
= extract(stmt
->getElse());
3760 if (options
->autodetect
) {
3761 if (scop_then
&& !scop_else
) {
3763 isl_pw_aff_free(cond
);
3766 if (!scop_then
&& scop_else
) {
3768 isl_pw_aff_free(cond
);
3775 (!is_nested_allowed(cond
, scop_then
) ||
3776 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
3777 isl_pw_aff_free(cond
);
3780 if (allow_nested
&& !cond
)
3781 return extract_non_affine_if(stmt
->getCond(), scop_then
,
3782 scop_else
, stmt
->getElse(), stmt_id
);
3785 cond
= extract_condition(stmt
->getCond());
3788 pet_skip_info_if_init(&skip
, ctx
, scop_then
, scop_else
,
3789 stmt
->getElse() != NULL
, 1);
3790 pet_skip_info_if_extract_cond(&skip
, cond
, int_size
, &n_stmt
, &n_test
);
3792 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
3793 set
= isl_pw_aff_non_zero_set(cond
);
3794 scop
= pet_scop_restrict(scop_then
, isl_set_params(isl_set_copy(set
)));
3796 if (stmt
->getElse()) {
3797 set
= isl_set_subtract(isl_set_copy(valid
), set
);
3798 scop_else
= pet_scop_restrict(scop_else
, isl_set_params(set
));
3799 scop
= pet_scop_add_par(ctx
, scop
, scop_else
);
3802 scop
= resolve_nested(scop
);
3803 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid
));
3805 if (pet_skip_info_has_skip(&skip
))
3806 scop
= pet_scop_prefix(scop
, 0);
3807 scop
= pet_skip_info_if_add(&skip
, scop
, 1);
3812 /* Try and construct a pet_scop for a label statement.
3813 * We currently only allow labels on expression statements.
3815 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
3820 sub
= stmt
->getSubStmt();
3821 if (!isa
<Expr
>(sub
)) {
3826 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
3828 return extract(extract_expr(cast
<Expr
>(sub
)), stmt
->getSourceRange(),
3832 /* Return a one-dimensional multi piecewise affine expression that is equal
3833 * to the constant 1 and is defined over a zero-dimensional domain.
3835 static __isl_give isl_multi_pw_aff
*one_mpa(isl_ctx
*ctx
)
3838 isl_local_space
*ls
;
3841 space
= isl_space_set_alloc(ctx
, 0, 0);
3842 ls
= isl_local_space_from_space(space
);
3843 aff
= isl_aff_zero_on_domain(ls
);
3844 aff
= isl_aff_set_constant_si(aff
, 1);
3846 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
3849 /* Construct a pet_scop for a continue statement.
3851 * We simply create an empty scop with a universal pet_skip_now
3852 * skip condition. This skip condition will then be taken into
3853 * account by the enclosing loop construct, possibly after
3854 * being incorporated into outer skip conditions.
3856 struct pet_scop
*PetScan::extract(ContinueStmt
*stmt
)
3860 scop
= pet_scop_empty(ctx
);
3864 scop
= pet_scop_set_skip(scop
, pet_skip_now
, one_mpa(ctx
));
3869 /* Construct a pet_scop for a break statement.
3871 * We simply create an empty scop with both a universal pet_skip_now
3872 * skip condition and a universal pet_skip_later skip condition.
3873 * These skip conditions will then be taken into
3874 * account by the enclosing loop construct, possibly after
3875 * being incorporated into outer skip conditions.
3877 struct pet_scop
*PetScan::extract(BreakStmt
*stmt
)
3880 isl_multi_pw_aff
*skip
;
3882 scop
= pet_scop_empty(ctx
);
3886 skip
= one_mpa(ctx
);
3887 scop
= pet_scop_set_skip(scop
, pet_skip_now
,
3888 isl_multi_pw_aff_copy(skip
));
3889 scop
= pet_scop_set_skip(scop
, pet_skip_later
, skip
);
3894 /* Try and construct a pet_scop corresponding to "stmt".
3896 * If "stmt" is a compound statement, then "skip_declarations"
3897 * indicates whether we should skip initial declarations in the
3898 * compound statement.
3900 * If the constructed pet_scop is not a (possibly) partial representation
3901 * of "stmt", we update start and end of the pet_scop to those of "stmt".
3902 * In particular, if skip_declarations is set, then we may have skipped
3903 * declarations inside "stmt" and so the pet_scop may not represent
3904 * the entire "stmt".
3905 * Note that this function may be called with "stmt" referring to the entire
3906 * body of the function, including the outer braces. In such cases,
3907 * skip_declarations will be set and the braces will not be taken into
3908 * account in scop->start and scop->end.
3910 struct pet_scop
*PetScan::extract(Stmt
*stmt
, bool skip_declarations
)
3912 struct pet_scop
*scop
;
3914 if (isa
<Expr
>(stmt
))
3915 return extract(extract_expr(cast
<Expr
>(stmt
)),
3916 stmt
->getSourceRange(), true);
3918 switch (stmt
->getStmtClass()) {
3919 case Stmt::WhileStmtClass
:
3920 scop
= extract(cast
<WhileStmt
>(stmt
));
3922 case Stmt::ForStmtClass
:
3923 scop
= extract_for(cast
<ForStmt
>(stmt
));
3925 case Stmt::IfStmtClass
:
3926 scop
= extract(cast
<IfStmt
>(stmt
));
3928 case Stmt::CompoundStmtClass
:
3929 scop
= extract(cast
<CompoundStmt
>(stmt
), skip_declarations
);
3931 case Stmt::LabelStmtClass
:
3932 scop
= extract(cast
<LabelStmt
>(stmt
));
3934 case Stmt::ContinueStmtClass
:
3935 scop
= extract(cast
<ContinueStmt
>(stmt
));
3937 case Stmt::BreakStmtClass
:
3938 scop
= extract(cast
<BreakStmt
>(stmt
));
3940 case Stmt::DeclStmtClass
:
3941 scop
= extract(cast
<DeclStmt
>(stmt
));
3948 if (partial
|| skip_declarations
)
3951 scop
= update_scop_start_end(scop
, stmt
->getSourceRange(), false);
3956 /* Extract a clone of the kill statement in "scop".
3957 * "scop" is expected to have been created from a DeclStmt
3958 * and should have the kill as its first statement.
3960 struct pet_stmt
*PetScan::extract_kill(struct pet_scop
*scop
)
3963 struct pet_stmt
*stmt
;
3964 isl_multi_pw_aff
*index
;
3970 if (scop
->n_stmt
< 1)
3971 isl_die(ctx
, isl_error_internal
,
3972 "expecting at least one statement", return NULL
);
3973 stmt
= scop
->stmts
[0];
3974 if (!pet_stmt_is_kill(stmt
))
3975 isl_die(ctx
, isl_error_internal
,
3976 "expecting kill statement", return NULL
);
3978 arg
= pet_expr_get_arg(stmt
->body
, 0);
3979 index
= pet_expr_access_get_index(arg
);
3980 access
= pet_expr_access_get_access(arg
);
3982 index
= isl_multi_pw_aff_reset_tuple_id(index
, isl_dim_in
);
3983 access
= isl_map_reset_tuple_id(access
, isl_dim_in
);
3984 kill
= pet_expr_kill_from_access_and_index(access
, index
);
3985 return pet_stmt_from_pet_expr(stmt
->line
, NULL
, n_stmt
++, kill
);
3988 /* Mark all arrays in "scop" as being exposed.
3990 static struct pet_scop
*mark_exposed(struct pet_scop
*scop
)
3994 for (int i
= 0; i
< scop
->n_array
; ++i
)
3995 scop
->arrays
[i
]->exposed
= 1;
3999 /* Try and construct a pet_scop corresponding to (part of)
4000 * a sequence of statements.
4002 * "block" is set if the sequence respresents the children of
4003 * a compound statement.
4004 * "skip_declarations" is set if we should skip initial declarations
4005 * in the sequence of statements.
4007 * After extracting a statement, we update "assigned_value"
4008 * based on the top-level assignments in the statement
4009 * so that we can exploit them in subsequent statements in the same block.
4011 * If there are any breaks or continues in the individual statements,
4012 * then we may have to compute a new skip condition.
4013 * This is handled using a pet_skip_info object.
4014 * On initialization, the object checks if skip conditions need
4015 * to be computed. If so, it does so in pet_skip_info_seq_extract and
4016 * adds them in pet_skip_info_seq_add.
4018 * If "block" is set, then we need to insert kill statements at
4019 * the end of the block for any array that has been declared by
4020 * one of the statements in the sequence. Each of these declarations
4021 * results in the construction of a kill statement at the place
4022 * of the declaration, so we simply collect duplicates of
4023 * those kill statements and append these duplicates to the constructed scop.
4025 * If "block" is not set, then any array declared by one of the statements
4026 * in the sequence is marked as being exposed.
4028 * If autodetect is set, then we allow the extraction of only a subrange
4029 * of the sequence of statements. However, if there is at least one statement
4030 * for which we could not construct a scop and the final range contains
4031 * either no statements or at least one kill, then we discard the entire
4034 struct pet_scop
*PetScan::extract(StmtRange stmt_range
, bool block
,
4035 bool skip_declarations
)
4041 bool partial_range
= false;
4042 set
<struct pet_stmt
*> kills
;
4043 set
<struct pet_stmt
*>::iterator it
;
4045 int_size
= ast_context
.getTypeInfo(ast_context
.IntTy
).first
/ 8;
4047 scop
= pet_scop_empty(ctx
);
4048 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
4050 struct pet_scop
*scop_i
;
4052 if (scop
->n_stmt
== 0 && skip_declarations
&&
4053 child
->getStmtClass() == Stmt::DeclStmtClass
)
4056 scop_i
= extract(child
);
4057 if (scop
->n_stmt
!= 0 && partial
) {
4058 pet_scop_free(scop_i
);
4061 handle_writes(scop_i
);
4063 pet_skip_info_seq_init(&skip
, ctx
, scop
, scop_i
);
4064 pet_skip_info_seq_extract(&skip
, int_size
, &n_stmt
, &n_test
);
4065 if (pet_skip_info_has_skip(&skip
))
4066 scop_i
= pet_scop_prefix(scop_i
, 0);
4067 if (scop_i
&& child
->getStmtClass() == Stmt::DeclStmtClass
) {
4069 kills
.insert(extract_kill(scop_i
));
4071 scop_i
= mark_exposed(scop_i
);
4073 scop_i
= pet_scop_prefix(scop_i
, j
);
4074 if (options
->autodetect
) {
4076 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4078 partial_range
= true;
4079 if (scop
->n_stmt
!= 0 && !scop_i
)
4082 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4085 scop
= pet_skip_info_seq_add(&skip
, scop
, j
);
4087 if (partial
|| !scop
)
4091 for (it
= kills
.begin(); it
!= kills
.end(); ++it
) {
4093 scop_j
= pet_scop_from_pet_stmt(ctx
, *it
);
4094 scop_j
= pet_scop_prefix(scop_j
, j
);
4095 scop
= pet_scop_add_seq(ctx
, scop
, scop_j
);
4098 if (scop
&& partial_range
) {
4099 if (scop
->n_stmt
== 0 || kills
.size() != 0) {
4100 pet_scop_free(scop
);
4109 /* Check if the scop marked by the user is exactly this Stmt
4110 * or part of this Stmt.
4111 * If so, return a pet_scop corresponding to the marked region.
4112 * Otherwise, return NULL.
4114 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
4116 SourceManager
&SM
= PP
.getSourceManager();
4117 unsigned start_off
, end_off
;
4119 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
4120 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
4122 if (start_off
> loc
.end
)
4124 if (end_off
< loc
.start
)
4126 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
4127 return extract(stmt
);
4131 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
4132 Stmt
*child
= *start
;
4135 start_off
= getExpansionOffset(SM
, child
->getLocStart());
4136 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
4137 if (start_off
< loc
.start
&& end_off
>= loc
.end
)
4139 if (start_off
>= loc
.start
)
4144 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
4146 start_off
= SM
.getFileOffset(child
->getLocStart());
4147 if (start_off
>= loc
.end
)
4151 return extract(StmtRange(start
, end
), false, false);
4154 /* Set the size of index "pos" of "array" to "size".
4155 * In particular, add a constraint of the form
4159 * to array->extent and a constraint of the form
4163 * to array->context.
4165 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
4166 __isl_take isl_pw_aff
*size
)
4176 valid
= isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
)));
4177 array
->context
= isl_set_intersect(array
->context
, valid
);
4179 dim
= isl_set_get_space(array
->extent
);
4180 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
4181 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
4182 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
4183 index
= isl_pw_aff_alloc(univ
, aff
);
4185 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
4186 isl_set_dim(array
->extent
, isl_dim_set
));
4187 id
= isl_set_get_tuple_id(array
->extent
);
4188 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
4189 bound
= isl_pw_aff_lt_set(index
, size
);
4191 array
->extent
= isl_set_intersect(array
->extent
, bound
);
4193 if (!array
->context
|| !array
->extent
)
4198 pet_array_free(array
);
4202 /* Figure out the size of the array at position "pos" and all
4203 * subsequent positions from "type" and update "array" accordingly.
4205 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
4206 const Type
*type
, int pos
)
4208 const ArrayType
*atype
;
4214 if (type
->isPointerType()) {
4215 type
= type
->getPointeeType().getTypePtr();
4216 return set_upper_bounds(array
, type
, pos
+ 1);
4218 if (!type
->isArrayType())
4221 type
= type
->getCanonicalTypeInternal().getTypePtr();
4222 atype
= cast
<ArrayType
>(type
);
4224 if (type
->isConstantArrayType()) {
4225 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
4226 size
= extract_affine(ca
->getSize());
4227 array
= update_size(array
, pos
, size
);
4228 } else if (type
->isVariableArrayType()) {
4229 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
4230 size
= extract_affine(vla
->getSizeExpr());
4231 array
= update_size(array
, pos
, size
);
4234 type
= atype
->getElementType().getTypePtr();
4236 return set_upper_bounds(array
, type
, pos
+ 1);
4239 /* Is "T" the type of a variable length array with static size?
4241 static bool is_vla_with_static_size(QualType T
)
4243 const VariableArrayType
*vlatype
;
4245 if (!T
->isVariableArrayType())
4247 vlatype
= cast
<VariableArrayType
>(T
);
4248 return vlatype
->getSizeModifier() == VariableArrayType::Static
;
4251 /* Return the type of "decl" as an array.
4253 * In particular, if "decl" is a parameter declaration that
4254 * is a variable length array with a static size, then
4255 * return the original type (i.e., the variable length array).
4256 * Otherwise, return the type of decl.
4258 static QualType
get_array_type(ValueDecl
*decl
)
4263 parm
= dyn_cast
<ParmVarDecl
>(decl
);
4265 return decl
->getType();
4267 T
= parm
->getOriginalType();
4268 if (!is_vla_with_static_size(T
))
4269 return decl
->getType();
4273 /* Does "decl" have definition that we can keep track of in a pet_type?
4275 static bool has_printable_definition(RecordDecl
*decl
)
4277 if (!decl
->getDeclName())
4279 return decl
->getLexicalDeclContext() == decl
->getDeclContext();
4282 /* Construct and return a pet_array corresponding to the variable "decl".
4283 * In particular, initialize array->extent to
4285 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4287 * and then call set_upper_bounds to set the upper bounds on the indices
4288 * based on the type of the variable.
4290 * If the base type is that of a record with a top-level definition and
4291 * if "types" is not null, then the RecordDecl corresponding to the type
4292 * is added to "types".
4294 * If the base type is that of a record with no top-level definition,
4295 * then we replace it by "<subfield>".
4297 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
,
4298 lex_recorddecl_set
*types
)
4300 struct pet_array
*array
;
4301 QualType qt
= get_array_type(decl
);
4302 const Type
*type
= qt
.getTypePtr();
4303 int depth
= array_depth(type
);
4304 QualType base
= pet_clang_base_type(qt
);
4309 array
= isl_calloc_type(ctx
, struct pet_array
);
4313 id
= create_decl_id(ctx
, decl
);
4314 dim
= isl_space_set_alloc(ctx
, 0, depth
);
4315 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
4317 array
->extent
= isl_set_nat_universe(dim
);
4319 dim
= isl_space_params_alloc(ctx
, 0);
4320 array
->context
= isl_set_universe(dim
);
4322 array
= set_upper_bounds(array
, type
, 0);
4326 name
= base
.getAsString();
4328 if (types
&& base
->isRecordType()) {
4329 RecordDecl
*decl
= pet_clang_record_decl(base
);
4330 if (has_printable_definition(decl
))
4331 types
->insert(decl
);
4333 name
= "<subfield>";
4336 array
->element_type
= strdup(name
.c_str());
4337 array
->element_is_record
= base
->isRecordType();
4338 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
4343 /* Construct and return a pet_array corresponding to the sequence
4344 * of declarations "decls".
4345 * If the sequence contains a single declaration, then it corresponds
4346 * to a simple array access. Otherwise, it corresponds to a member access,
4347 * with the declaration for the substructure following that of the containing
4348 * structure in the sequence of declarations.
4349 * We start with the outermost substructure and then combine it with
4350 * information from the inner structures.
4352 * Additionally, keep track of all required types in "types".
4354 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
,
4355 vector
<ValueDecl
*> decls
, lex_recorddecl_set
*types
)
4357 struct pet_array
*array
;
4358 vector
<ValueDecl
*>::iterator it
;
4362 array
= extract_array(ctx
, *it
, types
);
4364 for (++it
; it
!= decls
.end(); ++it
) {
4365 struct pet_array
*parent
;
4366 const char *base_name
, *field_name
;
4370 array
= extract_array(ctx
, *it
, types
);
4372 return pet_array_free(parent
);
4374 base_name
= isl_set_get_tuple_name(parent
->extent
);
4375 field_name
= isl_set_get_tuple_name(array
->extent
);
4376 product_name
= pet_array_member_access_name(ctx
,
4377 base_name
, field_name
);
4379 array
->extent
= isl_set_product(isl_set_copy(parent
->extent
),
4382 array
->extent
= isl_set_set_tuple_name(array
->extent
,
4384 array
->context
= isl_set_intersect(array
->context
,
4385 isl_set_copy(parent
->context
));
4387 pet_array_free(parent
);
4390 if (!array
->extent
|| !array
->context
|| !product_name
)
4391 return pet_array_free(array
);
4397 /* Add a pet_type corresponding to "decl" to "scop, provided
4398 * it is a member of "types" and it has not been added before
4399 * (i.e., it is not a member of "types_done".
4401 * Since we want the user to be able to print the types
4402 * in the order in which they appear in the scop, we need to
4403 * make sure that types of fields in a structure appear before
4404 * that structure. We therefore call ourselves recursively
4405 * on the types of all record subfields.
4407 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
4408 RecordDecl
*decl
, Preprocessor
&PP
, lex_recorddecl_set
&types
,
4409 lex_recorddecl_set
&types_done
)
4412 llvm::raw_string_ostream
S(s
);
4413 RecordDecl::field_iterator it
;
4415 if (types
.find(decl
) == types
.end())
4417 if (types_done
.find(decl
) != types_done
.end())
4420 for (it
= decl
->field_begin(); it
!= decl
->field_end(); ++it
) {
4422 QualType type
= it
->getType();
4424 if (!type
->isRecordType())
4426 record
= pet_clang_record_decl(type
);
4427 scop
= add_type(ctx
, scop
, record
, PP
, types
, types_done
);
4430 if (strlen(decl
->getName().str().c_str()) == 0)
4433 decl
->print(S
, PrintingPolicy(PP
.getLangOpts()));
4436 scop
->types
[scop
->n_type
] = pet_type_alloc(ctx
,
4437 decl
->getName().str().c_str(), s
.c_str());
4438 if (!scop
->types
[scop
->n_type
])
4439 return pet_scop_free(scop
);
4441 types_done
.insert(decl
);
4448 /* Construct a list of pet_arrays, one for each array (or scalar)
4449 * accessed inside "scop", add this list to "scop" and return the result.
4451 * The context of "scop" is updated with the intersection of
4452 * the contexts of all arrays, i.e., constraints on the parameters
4453 * that ensure that the arrays have a valid (non-negative) size.
4455 * If the any of the extracted arrays refers to a member access,
4456 * then also add the required types to "scop".
4458 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
4461 array_desc_set arrays
;
4462 array_desc_set::iterator it
;
4463 lex_recorddecl_set types
;
4464 lex_recorddecl_set types_done
;
4465 lex_recorddecl_set::iterator types_it
;
4467 struct pet_array
**scop_arrays
;
4472 pet_scop_collect_arrays(scop
, arrays
);
4473 if (arrays
.size() == 0)
4476 n_array
= scop
->n_array
;
4478 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
4479 n_array
+ arrays
.size());
4482 scop
->arrays
= scop_arrays
;
4484 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
4485 struct pet_array
*array
;
4486 array
= extract_array(ctx
, *it
, &types
);
4487 scop
->arrays
[n_array
+ i
] = array
;
4488 if (!scop
->arrays
[n_array
+ i
])
4491 scop
->context
= isl_set_intersect(scop
->context
,
4492 isl_set_copy(array
->context
));
4497 if (types
.size() == 0)
4500 scop
->types
= isl_alloc_array(ctx
, struct pet_type
*, types
.size());
4504 for (types_it
= types
.begin(); types_it
!= types
.end(); ++types_it
)
4505 scop
= add_type(ctx
, scop
, *types_it
, PP
, types
, types_done
);
4509 pet_scop_free(scop
);
4513 /* Bound all parameters in scop->context to the possible values
4514 * of the corresponding C variable.
4516 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
4523 n
= isl_set_dim(scop
->context
, isl_dim_param
);
4524 for (int i
= 0; i
< n
; ++i
) {
4528 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
4529 if (pet_nested_in_id(id
)) {
4531 isl_die(isl_set_get_ctx(scop
->context
),
4533 "unresolved nested parameter", goto error
);
4535 decl
= (ValueDecl
*) isl_id_get_user(id
);
4538 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
4546 pet_scop_free(scop
);
4550 /* Construct a pet_scop from the given function.
4552 * If the scop was delimited by scop and endscop pragmas, then we override
4553 * the file offsets by those derived from the pragmas.
4555 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
4560 stmt
= fd
->getBody();
4562 if (options
->autodetect
)
4563 scop
= extract(stmt
, true);
4566 scop
= pet_scop_update_start_end(scop
, loc
.start
, loc
.end
);
4568 scop
= pet_scop_detect_parameter_accesses(scop
);
4569 scop
= scan_arrays(scop
);
4570 scop
= add_parameter_bounds(scop
);
4571 scop
= pet_scop_gist(scop
, value_bounds
);