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>
58 #include "scop_plus.h"
64 using namespace clang
;
66 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
76 return pet_op_post_inc
;
78 return pet_op_post_dec
;
80 return pet_op_pre_inc
;
82 return pet_op_pre_dec
;
88 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
92 return pet_op_add_assign
;
94 return pet_op_sub_assign
;
96 return pet_op_mul_assign
;
98 return pet_op_div_assign
;
100 return pet_op_assign
;
142 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
143 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
145 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
146 SourceLocation(), var
, false, var
->getInnerLocStart(),
147 var
->getType(), VK_LValue
);
149 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
150 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
152 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
153 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
157 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
159 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
160 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
164 /* Check if the element type corresponding to the given array type
165 * has a const qualifier.
167 static bool const_base(QualType qt
)
169 const Type
*type
= qt
.getTypePtr();
171 if (type
->isPointerType())
172 return const_base(type
->getPointeeType());
173 if (type
->isArrayType()) {
174 const ArrayType
*atype
;
175 type
= type
->getCanonicalTypeInternal().getTypePtr();
176 atype
= cast
<ArrayType
>(type
);
177 return const_base(atype
->getElementType());
180 return qt
.isConstQualified();
183 /* Create an isl_id that refers to the named declarator "decl".
185 static __isl_give isl_id
*create_decl_id(isl_ctx
*ctx
, NamedDecl
*decl
)
187 return isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
190 /* Mark "decl" as having an unknown value in "assigned_value".
192 * If no (known or unknown) value was assigned to "decl" before,
193 * then it may have been treated as a parameter before and may
194 * therefore appear in a value assigned to another variable.
195 * If so, this assignment needs to be turned into an unknown value too.
197 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
200 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
202 it
= assigned_value
.find(decl
);
204 assigned_value
[decl
] = NULL
;
206 if (it
!= assigned_value
.end())
209 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
210 isl_pw_aff
*pa
= it
->second
;
211 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
213 for (int i
= 0; i
< nparam
; ++i
) {
216 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
218 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
219 if (isl_id_get_user(id
) == decl
)
226 /* Look for any assignments to scalar variables in part of the parse
227 * tree and set assigned_value to NULL for each of them.
228 * Also reset assigned_value if the address of a scalar variable
229 * is being taken. As an exception, if the address is passed to a function
230 * that is declared to receive a const pointer, then assigned_value is
233 * This ensures that we won't use any previously stored value
234 * in the current subtree and its parents.
236 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
237 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
238 set
<UnaryOperator
*> skip
;
240 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
241 assigned_value(assigned_value
) {}
243 /* Check for "address of" operators whose value is passed
244 * to a const pointer argument and add them to "skip", so that
245 * we can skip them in VisitUnaryOperator.
247 bool VisitCallExpr(CallExpr
*expr
) {
249 fd
= expr
->getDirectCallee();
252 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
253 Expr
*arg
= expr
->getArg(i
);
255 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
256 ImplicitCastExpr
*ice
;
257 ice
= cast
<ImplicitCastExpr
>(arg
);
258 arg
= ice
->getSubExpr();
260 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
262 op
= cast
<UnaryOperator
>(arg
);
263 if (op
->getOpcode() != UO_AddrOf
)
265 if (const_base(fd
->getParamDecl(i
)->getType()))
271 bool VisitUnaryOperator(UnaryOperator
*expr
) {
276 switch (expr
->getOpcode()) {
286 if (skip
.find(expr
) != skip
.end())
289 arg
= expr
->getSubExpr();
290 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
292 ref
= cast
<DeclRefExpr
>(arg
);
293 decl
= ref
->getDecl();
294 clear_assignment(assigned_value
, decl
);
298 bool VisitBinaryOperator(BinaryOperator
*expr
) {
303 if (!expr
->isAssignmentOp())
305 lhs
= expr
->getLHS();
306 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
308 ref
= cast
<DeclRefExpr
>(lhs
);
309 decl
= ref
->getDecl();
310 clear_assignment(assigned_value
, decl
);
315 /* Keep a copy of the currently assigned values.
317 * Any variable that is assigned a value inside the current scope
318 * is removed again when we leave the scope (either because it wasn't
319 * stored in the cache or because it has a different value in the cache).
321 struct assigned_value_cache
{
322 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
323 map
<ValueDecl
*, isl_pw_aff
*> cache
;
325 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
326 assigned_value(assigned_value
), cache(assigned_value
) {}
327 ~assigned_value_cache() {
328 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
329 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
332 (cache
.find(it
->first
) != cache
.end() &&
333 cache
[it
->first
] != it
->second
))
334 cache
[it
->first
] = NULL
;
336 assigned_value
= cache
;
340 /* Convert the mapping from identifiers to values in "assigned_value"
341 * to a pet_context to be used by pet_expr_extract_*.
342 * In particular, the clang identifiers are wrapped in an isl_id and
343 * a NULL value (representing an unknown value) is replaced by a NaN.
345 static __isl_give pet_context
*convert_assignments(isl_ctx
*ctx
,
346 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
)
349 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
351 pc
= pet_context_alloc(isl_space_set_alloc(ctx
, 0, 0));
353 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
354 ValueDecl
*decl
= it
->first
;
355 isl_pw_aff
*pa
= it
->second
;
358 id
= create_decl_id(ctx
, decl
);
360 pc
= pet_context_set_value(pc
, id
, isl_pw_aff_copy(pa
));
362 pc
= pet_context_mark_unknown(pc
, id
);
368 /* Insert an expression into the collection of expressions,
369 * provided it is not already in there.
370 * The isl_pw_affs are freed in the destructor.
372 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
374 std::set
<isl_pw_aff
*>::iterator it
;
376 if (expressions
.find(expr
) == expressions
.end())
377 expressions
.insert(expr
);
379 isl_pw_aff_free(expr
);
384 std::set
<isl_pw_aff
*>::iterator it
;
386 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
387 isl_pw_aff_free(*it
);
389 isl_union_map_free(value_bounds
);
392 /* Report a diagnostic, unless autodetect is set.
394 void PetScan::report(Stmt
*stmt
, unsigned id
)
396 if (options
->autodetect
)
399 SourceLocation loc
= stmt
->getLocStart();
400 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
401 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
404 /* Called if we found something we (currently) cannot handle.
405 * We'll provide more informative warnings later.
407 * We only actually complain if autodetect is false.
409 void PetScan::unsupported(Stmt
*stmt
)
411 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
412 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
417 /* Report a missing prototype, unless autodetect is set.
419 void PetScan::report_prototype_required(Stmt
*stmt
)
421 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
422 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
423 "prototype required");
427 /* Report a missing increment, unless autodetect is set.
429 void PetScan::report_missing_increment(Stmt
*stmt
)
431 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
432 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
433 "missing increment");
437 /* Extract an integer from "expr".
439 __isl_give isl_val
*PetScan::extract_int(isl_ctx
*ctx
, IntegerLiteral
*expr
)
441 const Type
*type
= expr
->getType().getTypePtr();
442 int is_signed
= type
->hasSignedIntegerRepresentation();
443 llvm::APInt val
= expr
->getValue();
444 int is_negative
= is_signed
&& val
.isNegative();
450 v
= extract_unsigned(ctx
, val
);
457 /* Extract an integer from "val", which is assumed to be non-negative.
459 __isl_give isl_val
*PetScan::extract_unsigned(isl_ctx
*ctx
,
460 const llvm::APInt
&val
)
463 const uint64_t *data
;
465 data
= val
.getRawData();
466 n
= val
.getNumWords();
467 return isl_val_int_from_chunks(ctx
, n
, sizeof(uint64_t), data
);
470 /* Extract an integer from "expr".
471 * Return NULL if "expr" does not (obviously) represent an integer.
473 __isl_give isl_val
*PetScan::extract_int(clang::ParenExpr
*expr
)
475 return extract_int(expr
->getSubExpr());
478 /* Extract an integer from "expr".
479 * Return NULL if "expr" does not (obviously) represent an integer.
481 __isl_give isl_val
*PetScan::extract_int(clang::Expr
*expr
)
483 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
484 return extract_int(ctx
, cast
<IntegerLiteral
>(expr
));
485 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
486 return extract_int(cast
<ParenExpr
>(expr
));
492 /* Extract an affine expression from the APInt "val", which is assumed
493 * to be non-negative.
494 * If the value of "val" is "v", then the returned expression
499 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
501 isl_space
*space
= isl_space_set_alloc(ctx
, 0, 0);
502 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(space
));
503 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
504 isl_set
*dom
= isl_set_universe(space
);
507 v
= extract_unsigned(ctx
, val
);
508 aff
= isl_aff_add_constant_val(aff
, v
);
510 return isl_pw_aff_alloc(dom
, aff
);
513 /* Return the number of bits needed to represent the type "qt",
514 * if it is an integer type. Otherwise return 0.
515 * If qt is signed then return the opposite of the number of bits.
517 static int get_type_size(QualType qt
, ASTContext
&ast_context
)
521 if (!qt
->isIntegerType())
524 size
= ast_context
.getIntWidth(qt
);
525 if (!qt
->isUnsignedIntegerType())
531 /* Return the number of bits needed to represent the type of "decl",
532 * if it is an integer type. Otherwise return 0.
533 * If qt is signed then return the opposite of the number of bits.
535 static int get_type_size(ValueDecl
*decl
)
537 return get_type_size(decl
->getType(), decl
->getASTContext());
540 /* Bound parameter "pos" of "set" to the possible values of "decl".
542 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
543 unsigned pos
, ValueDecl
*decl
)
549 ctx
= isl_set_get_ctx(set
);
550 type_size
= get_type_size(decl
);
552 isl_die(ctx
, isl_error_invalid
, "not an integer type",
553 return isl_set_free(set
));
555 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
556 bound
= isl_val_int_from_ui(ctx
, type_size
);
557 bound
= isl_val_2exp(bound
);
558 bound
= isl_val_sub_ui(bound
, 1);
559 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
, bound
);
561 bound
= isl_val_int_from_ui(ctx
, -type_size
- 1);
562 bound
= isl_val_2exp(bound
);
563 bound
= isl_val_sub_ui(bound
, 1);
564 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
,
565 isl_val_copy(bound
));
566 bound
= isl_val_neg(bound
);
567 bound
= isl_val_sub_ui(bound
, 1);
568 set
= isl_set_lower_bound_val(set
, isl_dim_param
, pos
, bound
);
574 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
576 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
577 __isl_take isl_set
*dom
)
580 pa
= isl_set_indicator_function(set
);
581 pa
= isl_pw_aff_intersect_domain(pa
, isl_set_coalesce(dom
));
585 /* Extract an affine expression, if possible, from "expr".
586 * Otherwise return NULL.
588 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
594 pe
= extract_expr(expr
);
597 pc
= convert_assignments(ctx
, assigned_value
);
598 pc
= pet_context_set_allow_nested(pc
, nesting_enabled
);
599 pa
= pet_expr_extract_affine(pe
, pc
);
600 if (isl_pw_aff_involves_nan(pa
)) {
602 pa
= isl_pw_aff_free(pa
);
604 pet_context_free(pc
);
610 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ImplicitCastExpr
*expr
)
612 return extract_index(expr
->getSubExpr());
615 /* Return the depth of an array of the given type.
617 static int array_depth(const Type
*type
)
619 if (type
->isPointerType())
620 return 1 + array_depth(type
->getPointeeType().getTypePtr());
621 if (type
->isArrayType()) {
622 const ArrayType
*atype
;
623 type
= type
->getCanonicalTypeInternal().getTypePtr();
624 atype
= cast
<ArrayType
>(type
);
625 return 1 + array_depth(atype
->getElementType().getTypePtr());
630 /* Return the depth of the array accessed by the index expression "index".
631 * If "index" is an affine expression, i.e., if it does not access
632 * any array, then return 1.
633 * If "index" represent a member access, i.e., if its range is a wrapped
634 * relation, then return the sum of the depth of the array of structures
635 * and that of the member inside the structure.
637 static int extract_depth(__isl_keep isl_multi_pw_aff
*index
)
645 if (isl_multi_pw_aff_range_is_wrapping(index
)) {
646 int domain_depth
, range_depth
;
647 isl_multi_pw_aff
*domain
, *range
;
649 domain
= isl_multi_pw_aff_copy(index
);
650 domain
= isl_multi_pw_aff_range_factor_domain(domain
);
651 domain_depth
= extract_depth(domain
);
652 isl_multi_pw_aff_free(domain
);
653 range
= isl_multi_pw_aff_copy(index
);
654 range
= isl_multi_pw_aff_range_factor_range(range
);
655 range_depth
= extract_depth(range
);
656 isl_multi_pw_aff_free(range
);
658 return domain_depth
+ range_depth
;
661 if (!isl_multi_pw_aff_has_tuple_id(index
, isl_dim_out
))
664 id
= isl_multi_pw_aff_get_tuple_id(index
, isl_dim_out
);
667 decl
= (ValueDecl
*) isl_id_get_user(id
);
670 return array_depth(decl
->getType().getTypePtr());
673 /* Extract an index expression from a reference to a variable.
674 * If the variable has name "A", then the returned index expression
679 __isl_give isl_multi_pw_aff
*PetScan::extract_index(DeclRefExpr
*expr
)
681 return extract_index(expr
->getDecl());
684 /* Extract an index expression from a variable.
685 * If the variable has name "A", then the returned index expression
690 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ValueDecl
*decl
)
692 isl_id
*id
= create_decl_id(ctx
, decl
);
693 isl_space
*space
= isl_space_alloc(ctx
, 0, 0, 0);
695 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
697 return isl_multi_pw_aff_zero(space
);
700 /* Extract an index expression from an integer contant.
701 * If the value of the constant is "v", then the returned access relation
706 __isl_give isl_multi_pw_aff
*PetScan::extract_index(IntegerLiteral
*expr
)
708 isl_multi_pw_aff
*mpa
;
710 mpa
= isl_multi_pw_aff_from_pw_aff(extract_affine(expr
));
714 /* Try and extract an index expression from the given Expr.
715 * Return NULL if it doesn't work out.
717 __isl_give isl_multi_pw_aff
*PetScan::extract_index(Expr
*expr
)
719 switch (expr
->getStmtClass()) {
720 case Stmt::ImplicitCastExprClass
:
721 return extract_index(cast
<ImplicitCastExpr
>(expr
));
722 case Stmt::DeclRefExprClass
:
723 return extract_index(cast
<DeclRefExpr
>(expr
));
724 case Stmt::ArraySubscriptExprClass
:
725 return extract_index(cast
<ArraySubscriptExpr
>(expr
));
726 case Stmt::IntegerLiteralClass
:
727 return extract_index(cast
<IntegerLiteral
>(expr
));
728 case Stmt::MemberExprClass
:
729 return extract_index(cast
<MemberExpr
>(expr
));
736 /* Given a partial index expression "base" and an extra index "index",
737 * append the extra index to "base" and return the result.
738 * Additionally, add the constraints that the extra index is non-negative.
739 * If "index" represent a member access, i.e., if its range is a wrapped
740 * relation, then we recursively extend the range of this nested relation.
742 * The inputs "base" and "index", as well as the result, all have
743 * an anonymous zero-dimensional domain.
745 static __isl_give isl_multi_pw_aff
*subscript(__isl_take isl_multi_pw_aff
*base
,
746 __isl_take isl_pw_aff
*index
)
750 isl_multi_pw_aff
*access
;
753 member_access
= isl_multi_pw_aff_range_is_wrapping(base
);
754 if (member_access
< 0)
757 isl_multi_pw_aff
*domain
, *range
;
760 id
= isl_multi_pw_aff_get_tuple_id(base
, isl_dim_out
);
761 domain
= isl_multi_pw_aff_copy(base
);
762 domain
= isl_multi_pw_aff_range_factor_domain(domain
);
763 range
= isl_multi_pw_aff_range_factor_range(base
);
764 range
= subscript(range
, index
);
765 access
= isl_multi_pw_aff_range_product(domain
, range
);
766 access
= isl_multi_pw_aff_set_tuple_id(access
, isl_dim_out
, id
);
770 id
= isl_multi_pw_aff_get_tuple_id(base
, isl_dim_set
);
771 domain
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(index
));
772 index
= isl_pw_aff_intersect_domain(index
, domain
);
773 access
= isl_multi_pw_aff_from_pw_aff(index
);
774 access
= isl_multi_pw_aff_flat_range_product(base
, access
);
775 access
= isl_multi_pw_aff_set_tuple_id(access
, isl_dim_set
, id
);
779 isl_multi_pw_aff_free(base
);
780 isl_pw_aff_free(index
);
784 /* Extract an index expression from the given array subscript expression.
785 * If nesting is allowed in general, then we turn it on while
786 * examining the index expression.
788 * We first extract an index expression from the base.
789 * This will result in an index expression with a range that corresponds
790 * to the earlier indices.
791 * We then extract the current index, restrict its domain
792 * to those values that result in a non-negative index and
793 * append the index to the base index expression.
795 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ArraySubscriptExpr
*expr
)
797 Expr
*base
= expr
->getBase();
798 Expr
*idx
= expr
->getIdx();
800 isl_multi_pw_aff
*base_access
;
801 isl_multi_pw_aff
*access
;
802 bool save_nesting
= nesting_enabled
;
804 nesting_enabled
= allow_nested
;
806 base_access
= extract_index(base
);
807 index
= extract_affine(idx
);
809 nesting_enabled
= save_nesting
;
811 access
= subscript(base_access
, index
);
816 /* Construct a name for a member access by concatenating the name
817 * of the array of structures and the member, separated by an underscore.
819 * The caller is responsible for freeing the result.
821 static char *member_access_name(isl_ctx
*ctx
, const char *base
,
827 len
= strlen(base
) + 1 + strlen(field
);
828 name
= isl_alloc_array(ctx
, char, len
+ 1);
831 snprintf(name
, len
+ 1, "%s_%s", base
, field
);
836 /* Given an index expression "base" for an element of an array of structures
837 * and an expression "field" for the field member being accessed, construct
838 * an index expression for an access to that member of the given structure.
839 * In particular, take the range product of "base" and "field" and
840 * attach a name to the result.
842 static __isl_give isl_multi_pw_aff
*member(__isl_take isl_multi_pw_aff
*base
,
843 __isl_take isl_multi_pw_aff
*field
)
846 isl_multi_pw_aff
*access
;
847 const char *base_name
, *field_name
;
850 ctx
= isl_multi_pw_aff_get_ctx(base
);
852 base_name
= isl_multi_pw_aff_get_tuple_name(base
, isl_dim_out
);
853 field_name
= isl_multi_pw_aff_get_tuple_name(field
, isl_dim_out
);
854 name
= member_access_name(ctx
, base_name
, field_name
);
856 access
= isl_multi_pw_aff_range_product(base
, field
);
858 access
= isl_multi_pw_aff_set_tuple_name(access
, isl_dim_out
, name
);
864 /* Extract an index expression from a member expression.
866 * If the base access (to the structure containing the member)
871 * and the member is called "f", then the member access is of
874 * [] -> A_f[A[..] -> f[]]
876 * If the member access is to an anonymous struct, then simply return
880 * If the member access in the source code is of the form
884 * then it is treated as
888 __isl_give isl_multi_pw_aff
*PetScan::extract_index(MemberExpr
*expr
)
890 Expr
*base
= expr
->getBase();
891 FieldDecl
*field
= cast
<FieldDecl
>(expr
->getMemberDecl());
892 isl_multi_pw_aff
*base_access
, *field_access
;
896 base_access
= extract_index(base
);
898 if (expr
->isArrow()) {
899 isl_space
*space
= isl_space_set_alloc(ctx
, 0, 0);
900 isl_local_space
*ls
= isl_local_space_from_space(space
);
901 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
902 isl_pw_aff
*index
= isl_pw_aff_from_aff(aff
);
903 base_access
= subscript(base_access
, index
);
906 if (field
->isAnonymousStructOrUnion())
909 id
= create_decl_id(ctx
, field
);
910 space
= isl_multi_pw_aff_get_domain_space(base_access
);
911 space
= isl_space_from_domain(space
);
912 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
913 field_access
= isl_multi_pw_aff_zero(space
);
915 return member(base_access
, field_access
);
918 /* Check if "expr" calls function "minmax" with two arguments and if so
919 * make lhs and rhs refer to these two arguments.
921 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
927 if (expr
->getStmtClass() != Stmt::CallExprClass
)
930 call
= cast
<CallExpr
>(expr
);
931 fd
= call
->getDirectCallee();
935 if (call
->getNumArgs() != 2)
938 name
= fd
->getDeclName().getAsString();
942 lhs
= call
->getArg(0);
943 rhs
= call
->getArg(1);
948 /* Check if "expr" is of the form min(lhs, rhs) and if so make
949 * lhs and rhs refer to the two arguments.
951 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
953 return is_minmax(expr
, "min", lhs
, rhs
);
956 /* Check if "expr" is of the form max(lhs, rhs) and if so make
957 * lhs and rhs refer to the two arguments.
959 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
961 return is_minmax(expr
, "max", lhs
, rhs
);
964 /* Extract an affine expressions representing the comparison "LHS op RHS"
965 * "comp" is the original statement that "LHS op RHS" is derived from
966 * and is used for diagnostics.
968 * If the comparison is of the form
972 * then the expression is constructed as the conjunction of
977 * A similar optimization is performed for max(a,b) <= c.
978 * We do this because that will lead to simpler representations
980 * If isl is ever enhanced to explicitly deal with min and max expressions,
981 * this optimization can be removed.
983 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
984 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
991 enum pet_op_type type
;
994 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
996 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
998 if (op
== BO_LT
|| op
== BO_LE
) {
1000 if (is_min(RHS
, expr1
, expr2
)) {
1001 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
1002 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
1003 return pet_and(lhs
, rhs
);
1005 if (is_max(LHS
, expr1
, expr2
)) {
1006 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
1007 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
1008 return pet_and(lhs
, rhs
);
1012 lhs
= extract_affine(LHS
);
1013 rhs
= extract_affine(RHS
);
1015 type
= BinaryOperatorKind2pet_op_type(op
);
1016 return pet_comparison(type
, lhs
, rhs
);
1019 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
1021 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1022 comp
->getRHS(), comp
);
1025 /* Extract an affine expression from a boolean expression.
1026 * In particular, return the expression "expr ? 1 : 0".
1027 * Return NULL if we are unable to extract an affine expression.
1029 * We first convert the clang::Expr to a pet_expr and
1030 * then extract an affine expression from that pet_expr.
1032 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
1039 isl_set
*u
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
1040 return indicator_function(u
, isl_set_copy(u
));
1043 pe
= extract_expr(expr
);
1044 pc
= convert_assignments(ctx
, assigned_value
);
1045 pc
= pet_context_set_allow_nested(pc
, nesting_enabled
);
1046 cond
= pet_expr_extract_affine_condition(pe
, pc
);
1047 if (isl_pw_aff_involves_nan(cond
))
1048 cond
= isl_pw_aff_free(cond
);
1049 pet_context_free(pc
);
1054 /* Construct a pet_expr representing a unary operator expression.
1056 __isl_give pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1059 enum pet_op_type op
;
1061 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1062 if (op
== pet_op_last
) {
1067 arg
= extract_expr(expr
->getSubExpr());
1069 if (expr
->isIncrementDecrementOp() &&
1070 pet_expr_get_type(arg
) == pet_expr_access
) {
1071 arg
= mark_write(arg
);
1072 arg
= pet_expr_access_set_read(arg
, 1);
1075 return pet_expr_new_unary(op
, arg
);
1078 /* Mark the given access pet_expr as a write.
1079 * If a scalar is being accessed, then mark its value
1080 * as unknown in assigned_value.
1082 __isl_give pet_expr
*PetScan::mark_write(__isl_take pet_expr
*access
)
1087 access
= pet_expr_access_set_write(access
, 1);
1088 access
= pet_expr_access_set_read(access
, 0);
1090 if (!access
|| !pet_expr_is_scalar_access(access
))
1093 id
= pet_expr_access_get_id(access
);
1094 decl
= (ValueDecl
*) isl_id_get_user(id
);
1095 clear_assignment(assigned_value
, decl
);
1101 /* Assign "rhs" to "lhs".
1103 * In particular, if "lhs" is a scalar variable, then mark
1104 * the variable as having been assigned. If, furthermore, "rhs"
1105 * is an affine expression, then keep track of this value in assigned_value
1106 * so that we can plug it in when we later come across the same variable.
1108 void PetScan::assign(__isl_keep pet_expr
*lhs
, Expr
*rhs
)
1116 if (!pet_expr_is_scalar_access(lhs
))
1119 id
= pet_expr_access_get_id(lhs
);
1120 decl
= (ValueDecl
*) isl_id_get_user(id
);
1123 pa
= try_extract_affine(rhs
);
1124 clear_assignment(assigned_value
, decl
);
1127 assigned_value
[decl
] = pa
;
1128 insert_expression(pa
);
1131 /* Construct a pet_expr representing a binary operator expression.
1133 * If the top level operator is an assignment and the LHS is an access,
1134 * then we mark that access as a write. If the operator is a compound
1135 * assignment, the access is marked as both a read and a write.
1137 * If "expr" assigns something to a scalar variable, then we mark
1138 * the variable as having been assigned. If, furthermore, the expression
1139 * is affine, then keep track of this value in assigned_value
1140 * so that we can plug it in when we later come across the same variable.
1142 __isl_give pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1145 pet_expr
*lhs
, *rhs
;
1146 enum pet_op_type op
;
1148 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1149 if (op
== pet_op_last
) {
1154 lhs
= extract_expr(expr
->getLHS());
1155 rhs
= extract_expr(expr
->getRHS());
1157 if (expr
->isAssignmentOp() &&
1158 pet_expr_get_type(lhs
) == pet_expr_access
) {
1159 lhs
= mark_write(lhs
);
1160 if (expr
->isCompoundAssignmentOp())
1161 lhs
= pet_expr_access_set_read(lhs
, 1);
1164 if (expr
->getOpcode() == BO_Assign
)
1165 assign(lhs
, expr
->getRHS());
1167 type_size
= get_type_size(expr
->getType(), ast_context
);
1168 return pet_expr_new_binary(type_size
, op
, lhs
, rhs
);
1171 /* Construct a pet_scop with a single statement killing the entire
1174 struct pet_scop
*PetScan::kill(Stmt
*stmt
, struct pet_array
*array
)
1178 isl_multi_pw_aff
*index
;
1184 access
= isl_map_from_range(isl_set_copy(array
->extent
));
1185 id
= isl_set_get_tuple_id(array
->extent
);
1186 space
= isl_space_alloc(ctx
, 0, 0, 0);
1187 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
1188 index
= isl_multi_pw_aff_zero(space
);
1189 expr
= pet_expr_kill_from_access_and_index(access
, index
);
1190 return extract(expr
, stmt
->getSourceRange(), false);
1193 /* Construct a pet_scop for a (single) variable declaration.
1195 * The scop contains the variable being declared (as an array)
1196 * and a statement killing the array.
1198 * If the variable is initialized in the AST, then the scop
1199 * also contains an assignment to the variable.
1201 struct pet_scop
*PetScan::extract(DeclStmt
*stmt
)
1206 pet_expr
*lhs
, *rhs
, *pe
;
1207 struct pet_scop
*scop_decl
, *scop
;
1208 struct pet_array
*array
;
1210 if (!stmt
->isSingleDecl()) {
1215 decl
= stmt
->getSingleDecl();
1216 vd
= cast
<VarDecl
>(decl
);
1218 array
= extract_array(ctx
, vd
, NULL
);
1220 array
->declared
= 1;
1221 scop_decl
= kill(stmt
, array
);
1222 scop_decl
= pet_scop_add_array(scop_decl
, array
);
1227 lhs
= extract_access_expr(vd
);
1228 rhs
= extract_expr(vd
->getInit());
1230 lhs
= mark_write(lhs
);
1231 assign(lhs
, vd
->getInit());
1233 type_size
= get_type_size(vd
->getType(), ast_context
);
1234 pe
= pet_expr_new_binary(type_size
, pet_op_assign
, lhs
, rhs
);
1235 scop
= extract(pe
, stmt
->getSourceRange(), false);
1237 scop_decl
= pet_scop_prefix(scop_decl
, 0);
1238 scop
= pet_scop_prefix(scop
, 1);
1240 scop
= pet_scop_add_seq(ctx
, scop_decl
, scop
);
1245 /* Construct a pet_expr representing a conditional operation.
1247 * We first try to extract the condition as an affine expression.
1248 * If that fails, we construct a pet_expr tree representing the condition.
1250 __isl_give pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1252 pet_expr
*cond
, *lhs
, *rhs
;
1255 pa
= try_extract_affine(expr
->getCond());
1257 isl_multi_pw_aff
*test
= isl_multi_pw_aff_from_pw_aff(pa
);
1258 cond
= pet_expr_from_index(test
);
1260 cond
= extract_expr(expr
->getCond());
1261 lhs
= extract_expr(expr
->getTrueExpr());
1262 rhs
= extract_expr(expr
->getFalseExpr());
1264 return pet_expr_new_ternary(cond
, lhs
, rhs
);
1267 __isl_give pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1269 return extract_expr(expr
->getSubExpr());
1272 /* Construct a pet_expr representing a floating point value.
1274 * If the floating point literal does not appear in a macro,
1275 * then we use the original representation in the source code
1276 * as the string representation. Otherwise, we use the pretty
1277 * printer to produce a string representation.
1279 __isl_give pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1283 const LangOptions
&LO
= PP
.getLangOpts();
1284 SourceLocation loc
= expr
->getLocation();
1286 if (!loc
.isMacroID()) {
1287 SourceManager
&SM
= PP
.getSourceManager();
1288 unsigned len
= Lexer::MeasureTokenLength(loc
, SM
, LO
);
1289 s
= string(SM
.getCharacterData(loc
), len
);
1291 llvm::raw_string_ostream
S(s
);
1292 expr
->printPretty(S
, 0, PrintingPolicy(LO
));
1295 d
= expr
->getValueAsApproximateDouble();
1296 return pet_expr_new_double(ctx
, d
, s
.c_str());
1299 /* Convert the index expression "index" into an access pet_expr of type "qt".
1301 __isl_give pet_expr
*PetScan::extract_access_expr(QualType qt
,
1302 __isl_take isl_multi_pw_aff
*index
)
1308 depth
= extract_depth(index
);
1309 type_size
= get_type_size(qt
, ast_context
);
1311 pe
= pet_expr_from_index_and_depth(type_size
, index
, depth
);
1316 /* Extract an index expression from "expr" and then convert it into
1317 * an access pet_expr.
1319 __isl_give pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1321 return extract_access_expr(expr
->getType(), extract_index(expr
));
1324 /* Extract an index expression from "decl" and then convert it into
1325 * an access pet_expr.
1327 __isl_give pet_expr
*PetScan::extract_access_expr(ValueDecl
*decl
)
1329 return extract_access_expr(decl
->getType(), extract_index(decl
));
1332 __isl_give pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1334 return extract_expr(expr
->getSubExpr());
1337 /* Extract an assume statement from the argument "expr"
1338 * of a __pencil_assume statement.
1340 __isl_give pet_expr
*PetScan::extract_assume(Expr
*expr
)
1345 cond
= try_extract_affine_condition(expr
);
1347 res
= extract_expr(expr
);
1349 isl_multi_pw_aff
*index
;
1350 index
= isl_multi_pw_aff_from_pw_aff(cond
);
1351 res
= pet_expr_from_index(index
);
1353 return pet_expr_new_unary(pet_op_assume
, res
);
1356 /* Construct a pet_expr corresponding to the function call argument "expr".
1357 * The argument appears in position "pos" of a call to function "fd".
1359 * If we are passing along a pointer to an array element
1360 * or an entire row or even higher dimensional slice of an array,
1361 * then the function being called may write into the array.
1363 * We assume here that if the function is declared to take a pointer
1364 * to a const type, then the function will perform a read
1365 * and that otherwise, it will perform a write.
1367 __isl_give pet_expr
*PetScan::extract_argument(FunctionDecl
*fd
, int pos
,
1371 int is_addr
= 0, is_partial
= 0;
1374 if (expr
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1375 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(expr
);
1376 expr
= ice
->getSubExpr();
1378 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1379 UnaryOperator
*op
= cast
<UnaryOperator
>(expr
);
1380 if (op
->getOpcode() == UO_AddrOf
) {
1382 expr
= op
->getSubExpr();
1385 res
= extract_expr(expr
);
1388 sc
= expr
->getStmtClass();
1389 if ((sc
== Stmt::ArraySubscriptExprClass
||
1390 sc
== Stmt::MemberExprClass
) &&
1391 array_depth(expr
->getType().getTypePtr()) > 0)
1393 if ((is_addr
|| is_partial
) &&
1394 pet_expr_get_type(res
) == pet_expr_access
) {
1396 if (!fd
->hasPrototype()) {
1397 report_prototype_required(expr
);
1398 return pet_expr_free(res
);
1400 parm
= fd
->getParamDecl(pos
);
1401 if (!const_base(parm
->getType()))
1402 res
= mark_write(res
);
1406 res
= pet_expr_new_unary(pet_op_address_of
, res
);
1410 /* Construct a pet_expr representing a function call.
1412 * In the special case of a "call" to __pencil_assume,
1413 * construct an assume expression instead.
1415 __isl_give pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1417 pet_expr
*res
= NULL
;
1422 fd
= expr
->getDirectCallee();
1428 name
= fd
->getDeclName().getAsString();
1429 n_arg
= expr
->getNumArgs();
1431 if (n_arg
== 1 && name
== "__pencil_assume")
1432 return extract_assume(expr
->getArg(0));
1434 res
= pet_expr_new_call(ctx
, name
.c_str(), n_arg
);
1438 for (int i
= 0; i
< n_arg
; ++i
) {
1439 Expr
*arg
= expr
->getArg(i
);
1440 res
= pet_expr_set_arg(res
, i
,
1441 PetScan::extract_argument(fd
, i
, arg
));
1447 /* Construct a pet_expr representing a (C style) cast.
1449 __isl_give pet_expr
*PetScan::extract_expr(CStyleCastExpr
*expr
)
1454 arg
= extract_expr(expr
->getSubExpr());
1458 type
= expr
->getTypeAsWritten();
1459 return pet_expr_new_cast(type
.getAsString().c_str(), arg
);
1462 /* Construct a pet_expr representing an integer.
1464 __isl_give pet_expr
*PetScan::extract_expr(IntegerLiteral
*expr
)
1466 return pet_expr_new_int(extract_int(expr
));
1469 /* Try and construct a pet_expr representing "expr".
1471 __isl_give pet_expr
*PetScan::extract_expr(Expr
*expr
)
1473 switch (expr
->getStmtClass()) {
1474 case Stmt::UnaryOperatorClass
:
1475 return extract_expr(cast
<UnaryOperator
>(expr
));
1476 case Stmt::CompoundAssignOperatorClass
:
1477 case Stmt::BinaryOperatorClass
:
1478 return extract_expr(cast
<BinaryOperator
>(expr
));
1479 case Stmt::ImplicitCastExprClass
:
1480 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1481 case Stmt::ArraySubscriptExprClass
:
1482 case Stmt::DeclRefExprClass
:
1483 case Stmt::MemberExprClass
:
1484 return extract_access_expr(expr
);
1485 case Stmt::IntegerLiteralClass
:
1486 return extract_expr(cast
<IntegerLiteral
>(expr
));
1487 case Stmt::FloatingLiteralClass
:
1488 return extract_expr(cast
<FloatingLiteral
>(expr
));
1489 case Stmt::ParenExprClass
:
1490 return extract_expr(cast
<ParenExpr
>(expr
));
1491 case Stmt::ConditionalOperatorClass
:
1492 return extract_expr(cast
<ConditionalOperator
>(expr
));
1493 case Stmt::CallExprClass
:
1494 return extract_expr(cast
<CallExpr
>(expr
));
1495 case Stmt::CStyleCastExprClass
:
1496 return extract_expr(cast
<CStyleCastExpr
>(expr
));
1503 /* Check if the given initialization statement is an assignment.
1504 * If so, return that assignment. Otherwise return NULL.
1506 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1508 BinaryOperator
*ass
;
1510 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1513 ass
= cast
<BinaryOperator
>(init
);
1514 if (ass
->getOpcode() != BO_Assign
)
1520 /* Check if the given initialization statement is a declaration
1521 * of a single variable.
1522 * If so, return that declaration. Otherwise return NULL.
1524 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1528 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1531 decl
= cast
<DeclStmt
>(init
);
1533 if (!decl
->isSingleDecl())
1536 return decl
->getSingleDecl();
1539 /* Given the assignment operator in the initialization of a for loop,
1540 * extract the induction variable, i.e., the (integer)variable being
1543 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1550 lhs
= init
->getLHS();
1551 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1556 ref
= cast
<DeclRefExpr
>(lhs
);
1557 decl
= ref
->getDecl();
1558 type
= decl
->getType().getTypePtr();
1560 if (!type
->isIntegerType()) {
1568 /* Given the initialization statement of a for loop and the single
1569 * declaration in this initialization statement,
1570 * extract the induction variable, i.e., the (integer) variable being
1573 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1577 vd
= cast
<VarDecl
>(decl
);
1579 const QualType type
= vd
->getType();
1580 if (!type
->isIntegerType()) {
1585 if (!vd
->getInit()) {
1593 /* Check that op is of the form iv++ or iv--.
1594 * Return a pet_expr representing "1" or "-1" accordingly.
1596 __isl_give pet_expr
*PetScan::extract_unary_increment(
1597 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1603 if (!op
->isIncrementDecrementOp()) {
1608 sub
= op
->getSubExpr();
1609 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1614 ref
= cast
<DeclRefExpr
>(sub
);
1615 if (ref
->getDecl() != iv
) {
1620 if (op
->isIncrementOp())
1621 v
= isl_val_one(ctx
);
1623 v
= isl_val_negone(ctx
);
1625 return pet_expr_new_int(v
);
1628 /* Check if op is of the form
1632 * and return the increment "expr - iv" as a pet_expr.
1634 __isl_give pet_expr
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1635 clang::ValueDecl
*iv
)
1640 pet_expr
*expr
, *expr_iv
;
1642 if (op
->getOpcode() != BO_Assign
) {
1648 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1653 ref
= cast
<DeclRefExpr
>(lhs
);
1654 if (ref
->getDecl() != iv
) {
1659 expr
= extract_expr(op
->getRHS());
1660 expr_iv
= extract_expr(lhs
);
1662 type_size
= get_type_size(iv
->getType(), ast_context
);
1663 return pet_expr_new_binary(type_size
, pet_op_sub
, expr
, expr_iv
);
1666 /* Check that op is of the form iv += cst or iv -= cst
1667 * and return a pet_expr corresponding to cst or -cst accordingly.
1669 __isl_give pet_expr
*PetScan::extract_compound_increment(
1670 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1676 BinaryOperatorKind opcode
;
1678 opcode
= op
->getOpcode();
1679 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1683 if (opcode
== BO_SubAssign
)
1687 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1692 ref
= cast
<DeclRefExpr
>(lhs
);
1693 if (ref
->getDecl() != iv
) {
1698 expr
= extract_expr(op
->getRHS());
1700 expr
= pet_expr_new_unary(pet_op_minus
, expr
);
1705 /* Check that the increment of the given for loop increments
1706 * (or decrements) the induction variable "iv" and return
1707 * the increment as a pet_expr if successful.
1709 __isl_give pet_expr
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1712 Stmt
*inc
= stmt
->getInc();
1715 report_missing_increment(stmt
);
1719 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1720 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1721 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1722 return extract_compound_increment(
1723 cast
<CompoundAssignOperator
>(inc
), iv
);
1724 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1725 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1731 /* Embed the given iteration domain in an extra outer loop
1732 * with induction variable "var".
1733 * If this variable appeared as a parameter in the constraints,
1734 * it is replaced by the new outermost dimension.
1736 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1737 __isl_take isl_id
*var
)
1741 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1742 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1744 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1745 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1752 /* Return those elements in the space of "cond" that come after
1753 * (based on "sign") an element in "cond".
1755 static __isl_give isl_set
*after(__isl_take isl_set
*cond
, int sign
)
1757 isl_map
*previous_to_this
;
1760 previous_to_this
= isl_map_lex_lt(isl_set_get_space(cond
));
1762 previous_to_this
= isl_map_lex_gt(isl_set_get_space(cond
));
1764 cond
= isl_set_apply(cond
, previous_to_this
);
1769 /* Create the infinite iteration domain
1771 * { [id] : id >= 0 }
1773 * If "scop" has an affine skip of type pet_skip_later,
1774 * then remove those iterations i that have an earlier iteration
1775 * where the skip condition is satisfied, meaning that iteration i
1777 * Since we are dealing with a loop without loop iterator,
1778 * the skip condition cannot refer to the current loop iterator and
1779 * so effectively, the returned set is of the form
1781 * { [0]; [id] : id >= 1 and not skip }
1783 static __isl_give isl_set
*infinite_domain(__isl_take isl_id
*id
,
1784 struct pet_scop
*scop
)
1786 isl_ctx
*ctx
= isl_id_get_ctx(id
);
1790 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
1791 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, id
);
1793 if (!pet_scop_has_affine_skip(scop
, pet_skip_later
))
1796 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
1797 skip
= embed(skip
, isl_id_copy(id
));
1798 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
1799 domain
= isl_set_subtract(domain
, after(skip
, 1));
1804 /* Create an identity affine expression on the space containing "domain",
1805 * which is assumed to be one-dimensional.
1807 static __isl_give isl_aff
*identity_aff(__isl_keep isl_set
*domain
)
1809 isl_local_space
*ls
;
1811 ls
= isl_local_space_from_space(isl_set_get_space(domain
));
1812 return isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
1815 /* Create an affine expression that maps elements
1816 * of a single-dimensional array "id_test" to the previous element
1817 * (according to "inc"), provided this element belongs to "domain".
1818 * That is, create the affine expression
1820 * { id[x] -> id[x - inc] : x - inc in domain }
1822 static __isl_give isl_multi_pw_aff
*map_to_previous(__isl_take isl_id
*id_test
,
1823 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
1826 isl_local_space
*ls
;
1828 isl_multi_pw_aff
*prev
;
1830 space
= isl_set_get_space(domain
);
1831 ls
= isl_local_space_from_space(space
);
1832 aff
= isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
1833 aff
= isl_aff_add_constant_val(aff
, isl_val_neg(inc
));
1834 prev
= isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
1835 domain
= isl_set_preimage_multi_pw_aff(domain
,
1836 isl_multi_pw_aff_copy(prev
));
1837 prev
= isl_multi_pw_aff_intersect_domain(prev
, domain
);
1838 prev
= isl_multi_pw_aff_set_tuple_id(prev
, isl_dim_out
, id_test
);
1843 /* Add an implication to "scop" expressing that if an element of
1844 * virtual array "id_test" has value "satisfied" then all previous elements
1845 * of this array also have that value. The set of previous elements
1846 * is bounded by "domain". If "sign" is negative then the iterator
1847 * is decreasing and we express that all subsequent array elements
1848 * (but still defined previously) have the same value.
1850 static struct pet_scop
*add_implication(struct pet_scop
*scop
,
1851 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
, int sign
,
1857 domain
= isl_set_set_tuple_id(domain
, id_test
);
1858 space
= isl_set_get_space(domain
);
1860 map
= isl_map_lex_ge(space
);
1862 map
= isl_map_lex_le(space
);
1863 map
= isl_map_intersect_range(map
, domain
);
1864 scop
= pet_scop_add_implication(scop
, map
, satisfied
);
1869 /* Add a filter to "scop" that imposes that it is only executed
1870 * when the variable identified by "id_test" has a zero value
1871 * for all previous iterations of "domain".
1873 * In particular, add a filter that imposes that the array
1874 * has a zero value at the previous iteration of domain and
1875 * add an implication that implies that it then has that
1876 * value for all previous iterations.
1878 static struct pet_scop
*scop_add_break(struct pet_scop
*scop
,
1879 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
,
1880 __isl_take isl_val
*inc
)
1882 isl_multi_pw_aff
*prev
;
1883 int sign
= isl_val_sgn(inc
);
1885 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
1886 scop
= add_implication(scop
, id_test
, domain
, sign
, 0);
1887 scop
= pet_scop_filter(scop
, prev
, 0);
1892 /* Construct a pet_scop for an infinite loop around the given body.
1894 * We extract a pet_scop for the body and then embed it in a loop with
1903 * If the body contains any break, then it is taken into
1904 * account in infinite_domain (if the skip condition is affine)
1905 * or in scop_add_break (if the skip condition is not affine).
1907 * If we were only able to extract part of the body, then simply
1910 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
1912 isl_id
*id
, *id_test
;
1915 struct pet_scop
*scop
;
1918 scop
= extract(body
);
1924 id
= isl_id_alloc(ctx
, "t", NULL
);
1925 domain
= infinite_domain(isl_id_copy(id
), scop
);
1926 ident
= identity_aff(domain
);
1928 has_var_break
= pet_scop_has_var_skip(scop
, pet_skip_later
);
1930 id_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
1932 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
1933 isl_aff_copy(ident
), ident
, id
);
1935 scop
= scop_add_break(scop
, id_test
, domain
, isl_val_one(ctx
));
1937 isl_set_free(domain
);
1942 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1948 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
1950 clear_assignments
clear(assigned_value
);
1951 clear
.TraverseStmt(stmt
->getBody());
1953 return extract_infinite_loop(stmt
->getBody());
1956 /* Add an array with the given extent (range of "index") to the list
1957 * of arrays in "scop" and return the extended pet_scop.
1958 * The array is marked as attaining values 0 and 1 only and
1959 * as each element being assigned at most once.
1961 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
1962 __isl_keep isl_multi_pw_aff
*index
, clang::ASTContext
&ast_ctx
)
1964 int int_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
1966 return pet_scop_add_boolean_array(scop
, isl_multi_pw_aff_copy(index
),
1970 /* Construct a pet_scop for a while loop of the form
1975 * In particular, construct a scop for an infinite loop around body and
1976 * intersect the domain with the affine expression.
1977 * Note that this intersection may result in an empty loop.
1979 struct pet_scop
*PetScan::extract_affine_while(__isl_take isl_pw_aff
*pa
,
1982 struct pet_scop
*scop
;
1986 valid
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
1987 dom
= isl_pw_aff_non_zero_set(pa
);
1988 scop
= extract_infinite_loop(body
);
1989 scop
= pet_scop_restrict(scop
, isl_set_params(dom
));
1990 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid
));
1995 /* Construct a scop for a while, given the scops for the condition
1996 * and the body, the filter identifier and the iteration domain of
1999 * In particular, the scop for the condition is filtered to depend
2000 * on "id_test" evaluating to true for all previous iterations
2001 * of the loop, while the scop for the body is filtered to depend
2002 * on "id_test" evaluating to true for all iterations up to the
2003 * current iteration.
2004 * The actual filter only imposes that this virtual array has
2005 * value one on the previous or the current iteration.
2006 * The fact that this condition also applies to the previous
2007 * iterations is enforced by an implication.
2009 * These filtered scops are then combined into a single scop.
2011 * "sign" is positive if the iterator increases and negative
2014 static struct pet_scop
*scop_add_while(struct pet_scop
*scop_cond
,
2015 struct pet_scop
*scop_body
, __isl_take isl_id
*id_test
,
2016 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2018 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
2020 isl_multi_pw_aff
*test_index
;
2021 isl_multi_pw_aff
*prev
;
2022 int sign
= isl_val_sgn(inc
);
2023 struct pet_scop
*scop
;
2025 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
2026 scop_cond
= pet_scop_filter(scop_cond
, prev
, 1);
2028 space
= isl_space_map_from_set(isl_set_get_space(domain
));
2029 test_index
= isl_multi_pw_aff_identity(space
);
2030 test_index
= isl_multi_pw_aff_set_tuple_id(test_index
, isl_dim_out
,
2031 isl_id_copy(id_test
));
2032 scop_body
= pet_scop_filter(scop_body
, test_index
, 1);
2034 scop
= pet_scop_add_seq(ctx
, scop_cond
, scop_body
);
2035 scop
= add_implication(scop
, id_test
, domain
, sign
, 1);
2040 /* Check if the while loop is of the form
2042 * while (affine expression)
2045 * If so, call extract_affine_while to construct a scop.
2047 * Otherwise, extract the body and pass control to extract_while
2048 * to extend the iteration domain with an infinite loop.
2049 * If we were only able to extract part of the body, then simply
2052 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
2055 int test_nr
, stmt_nr
;
2057 struct pet_scop
*scop_body
;
2059 cond
= stmt
->getCond();
2065 clear_assignments
clear(assigned_value
);
2066 clear
.TraverseStmt(stmt
->getBody());
2068 pa
= try_extract_affine_condition(cond
);
2070 return extract_affine_while(pa
, stmt
->getBody());
2072 if (!allow_nested
) {
2079 scop_body
= extract(stmt
->getBody());
2083 return extract_while(cond
, test_nr
, stmt_nr
, scop_body
, NULL
);
2086 /* Construct a generic while scop, with iteration domain
2087 * { [t] : t >= 0 } around "scop_body". The scop consists of two parts,
2088 * one for evaluating the condition "cond" and one for the body.
2089 * "test_nr" is the sequence number of the virtual test variable that contains
2090 * the result of the condition and "stmt_nr" is the sequence number
2091 * of the statement that evaluates the condition.
2092 * If "scop_inc" is not NULL, then it is added at the end of the body,
2093 * after replacing any skip conditions resulting from continue statements
2094 * by the skip conditions resulting from break statements (if any).
2096 * The schedule is adjusted to reflect that the condition is evaluated
2097 * before the body is executed and the body is filtered to depend
2098 * on the result of the condition evaluating to true on all iterations
2099 * up to the current iteration, while the evaluation of the condition itself
2100 * is filtered to depend on the result of the condition evaluating to true
2101 * on all previous iterations.
2102 * The context of the scop representing the body is dropped
2103 * because we don't know how many times the body will be executed,
2106 * If the body contains any break, then it is taken into
2107 * account in infinite_domain (if the skip condition is affine)
2108 * or in scop_add_break (if the skip condition is not affine).
2110 struct pet_scop
*PetScan::extract_while(Expr
*cond
, int test_nr
, int stmt_nr
,
2111 struct pet_scop
*scop_body
, struct pet_scop
*scop_inc
)
2113 isl_id
*id
, *id_test
, *id_break_test
;
2116 isl_multi_pw_aff
*test_index
;
2117 struct pet_scop
*scop
;
2120 test_index
= pet_create_test_index(ctx
, test_nr
);
2121 scop
= extract_non_affine_condition(cond
, stmt_nr
,
2122 isl_multi_pw_aff_copy(test_index
));
2123 scop
= scop_add_array(scop
, test_index
, ast_context
);
2124 id_test
= isl_multi_pw_aff_get_tuple_id(test_index
, isl_dim_out
);
2125 isl_multi_pw_aff_free(test_index
);
2127 id
= isl_id_alloc(ctx
, "t", NULL
);
2128 domain
= infinite_domain(isl_id_copy(id
), scop_body
);
2129 ident
= identity_aff(domain
);
2131 has_var_break
= pet_scop_has_var_skip(scop_body
, pet_skip_later
);
2133 id_break_test
= pet_scop_get_skip_id(scop_body
, pet_skip_later
);
2135 scop
= pet_scop_prefix(scop
, 0);
2136 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), isl_aff_copy(ident
),
2137 isl_aff_copy(ident
), isl_id_copy(id
));
2138 scop_body
= pet_scop_reset_context(scop_body
);
2139 scop_body
= pet_scop_prefix(scop_body
, 1);
2141 scop_inc
= pet_scop_prefix(scop_inc
, 2);
2142 if (pet_scop_has_skip(scop_body
, pet_skip_later
)) {
2143 isl_multi_pw_aff
*skip
;
2144 skip
= pet_scop_get_skip(scop_body
, pet_skip_later
);
2145 scop_body
= pet_scop_set_skip(scop_body
,
2146 pet_skip_now
, skip
);
2148 pet_scop_reset_skip(scop_body
, pet_skip_now
);
2149 scop_body
= pet_scop_add_seq(ctx
, scop_body
, scop_inc
);
2151 scop_body
= pet_scop_embed(scop_body
, isl_set_copy(domain
),
2152 isl_aff_copy(ident
), ident
, id
);
2154 if (has_var_break
) {
2155 scop
= scop_add_break(scop
, isl_id_copy(id_break_test
),
2156 isl_set_copy(domain
), isl_val_one(ctx
));
2157 scop_body
= scop_add_break(scop_body
, id_break_test
,
2158 isl_set_copy(domain
), isl_val_one(ctx
));
2160 scop
= scop_add_while(scop
, scop_body
, id_test
, domain
,
2166 /* Check whether "cond" expresses a simple loop bound
2167 * on the only set dimension.
2168 * In particular, if "up" is set then "cond" should contain only
2169 * upper bounds on the set dimension.
2170 * Otherwise, it should contain only lower bounds.
2172 static bool is_simple_bound(__isl_keep isl_set
*cond
, __isl_keep isl_val
*inc
)
2174 if (isl_val_is_pos(inc
))
2175 return !isl_set_dim_has_any_lower_bound(cond
, isl_dim_set
, 0);
2177 return !isl_set_dim_has_any_upper_bound(cond
, isl_dim_set
, 0);
2180 /* Extend a condition on a given iteration of a loop to one that
2181 * imposes the same condition on all previous iterations.
2182 * "domain" expresses the lower [upper] bound on the iterations
2183 * when inc is positive [negative].
2185 * In particular, we construct the condition (when inc is positive)
2187 * forall i' : (domain(i') and i' <= i) => cond(i')
2189 * which is equivalent to
2191 * not exists i' : domain(i') and i' <= i and not cond(i')
2193 * We construct this set by negating cond, applying a map
2195 * { [i'] -> [i] : domain(i') and i' <= i }
2197 * and then negating the result again.
2199 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
2200 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2202 isl_map
*previous_to_this
;
2204 if (isl_val_is_pos(inc
))
2205 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
2207 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
2209 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
2211 cond
= isl_set_complement(cond
);
2212 cond
= isl_set_apply(cond
, previous_to_this
);
2213 cond
= isl_set_complement(cond
);
2220 /* Construct a domain of the form
2222 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2224 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
2225 __isl_take isl_pw_aff
*init
, __isl_take isl_val
*inc
)
2231 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
2232 dim
= isl_pw_aff_get_domain_space(init
);
2233 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2234 aff
= isl_aff_add_coefficient_val(aff
, isl_dim_in
, 0, inc
);
2235 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2237 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2238 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2239 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2240 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2242 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2244 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2246 return isl_set_params(set
);
2249 /* Assuming "cond" represents a bound on a loop where the loop
2250 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2253 * Under the given assumptions, wrapping is only possible if "cond" allows
2254 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2255 * increasing iterator and 0 in case of a decreasing iterator.
2257 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
,
2258 __isl_keep isl_val
*inc
)
2265 test
= isl_set_copy(cond
);
2267 ctx
= isl_set_get_ctx(test
);
2268 if (isl_val_is_neg(inc
))
2269 limit
= isl_val_zero(ctx
);
2271 limit
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2272 limit
= isl_val_2exp(limit
);
2273 limit
= isl_val_sub_ui(limit
, 1);
2276 test
= isl_set_fix_val(cond
, isl_dim_set
, 0, limit
);
2277 cw
= !isl_set_is_empty(test
);
2283 /* Given a one-dimensional space, construct the following affine expression
2286 * { [v] -> [v mod 2^width] }
2288 * where width is the number of bits used to represent the values
2289 * of the unsigned variable "iv".
2291 static __isl_give isl_aff
*compute_wrapping(__isl_take isl_space
*dim
,
2298 ctx
= isl_space_get_ctx(dim
);
2299 mod
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2300 mod
= isl_val_2exp(mod
);
2302 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2303 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2304 aff
= isl_aff_mod_val(aff
, mod
);
2309 /* Project out the parameter "id" from "set".
2311 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2312 __isl_keep isl_id
*id
)
2316 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2318 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2323 /* Compute the set of parameters for which "set1" is a subset of "set2".
2325 * set1 is a subset of set2 if
2327 * forall i in set1 : i in set2
2331 * not exists i in set1 and i not in set2
2335 * not exists i in set1 \ set2
2337 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2338 __isl_take isl_set
*set2
)
2340 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2343 /* Compute the set of parameter values for which "cond" holds
2344 * on the next iteration for each element of "dom".
2346 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2347 * and then compute the set of parameters for which the result is a subset
2350 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2351 __isl_take isl_set
*dom
, __isl_take isl_val
*inc
)
2357 space
= isl_set_get_space(dom
);
2358 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2359 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2360 aff
= isl_aff_add_constant_val(aff
, inc
);
2361 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2363 dom
= isl_set_apply(dom
, next
);
2365 return enforce_subset(dom
, cond
);
2368 /* Extract the for loop "stmt" as a while loop.
2369 * "iv" is the loop iterator. "init" is the initialization.
2370 * "inc" is the increment.
2372 * That is, the for loop has the form
2374 * for (iv = init; cond; iv += inc)
2385 * except that the skips resulting from any continue statements
2386 * in body do not apply to the increment, but are replaced by the skips
2387 * resulting from break statements.
2389 * If "iv" is declared in the for loop, then it is killed before
2390 * and after the loop.
2392 struct pet_scop
*PetScan::extract_non_affine_for(ForStmt
*stmt
, ValueDecl
*iv
,
2393 __isl_take pet_expr
*init
, __isl_take pet_expr
*inc
)
2396 int test_nr
, stmt_nr
;
2398 struct pet_scop
*scop_init
, *scop_inc
, *scop
, *scop_body
;
2400 struct pet_array
*array
;
2401 struct pet_scop
*scop_kill
;
2403 if (!allow_nested
) {
2408 clear_assignment(assigned_value
, iv
);
2410 declared
= !initialization_assignment(stmt
->getInit());
2412 expr_iv
= extract_access_expr(iv
);
2413 expr_iv
= mark_write(expr_iv
);
2414 type_size
= pet_expr_get_type_size(expr_iv
);
2415 init
= pet_expr_new_binary(type_size
, pet_op_assign
, expr_iv
, init
);
2416 scop_init
= extract(init
, stmt
->getInit()->getSourceRange(), false);
2417 scop_init
= pet_scop_prefix(scop_init
, declared
);
2421 scop_body
= extract(stmt
->getBody());
2423 pet_scop_free(scop_init
);
2427 expr_iv
= extract_access_expr(iv
);
2428 expr_iv
= mark_write(expr_iv
);
2429 type_size
= pet_expr_get_type_size(expr_iv
);
2430 inc
= pet_expr_new_binary(type_size
, pet_op_add_assign
, expr_iv
, inc
);
2431 scop_inc
= extract(inc
, stmt
->getInc()->getSourceRange(), false);
2433 pet_scop_free(scop_init
);
2434 pet_scop_free(scop_body
);
2438 scop
= extract_while(stmt
->getCond(), test_nr
, stmt_nr
, scop_body
,
2441 scop
= pet_scop_prefix(scop
, declared
+ 1);
2442 scop
= pet_scop_add_seq(ctx
, scop_init
, scop
);
2447 array
= extract_array(ctx
, iv
, NULL
);
2449 array
->declared
= 1;
2450 scop_kill
= kill(stmt
, array
);
2451 scop_kill
= pet_scop_prefix(scop_kill
, 0);
2452 scop
= pet_scop_add_seq(ctx
, scop_kill
, scop
);
2453 scop_kill
= kill(stmt
, array
);
2454 scop_kill
= pet_scop_add_array(scop_kill
, array
);
2455 scop_kill
= pet_scop_prefix(scop_kill
, 3);
2456 scop
= pet_scop_add_seq(ctx
, scop
, scop_kill
);
2461 /* Construct a pet_scop for a for statement.
2462 * The for loop is required to be of one of the following forms
2464 * for (i = init; condition; ++i)
2465 * for (i = init; condition; --i)
2466 * for (i = init; condition; i += constant)
2467 * for (i = init; condition; i -= constant)
2469 * The initialization of the for loop should either be an assignment
2470 * of a static affine value to an integer variable, or a declaration
2471 * of such a variable with initialization.
2473 * If the initialization or the increment do not satisfy the above
2474 * conditions, i.e., if the initialization is not static affine
2475 * or the increment is not constant, then the for loop is extracted
2476 * as a while loop instead.
2478 * The condition is allowed to contain nested accesses, provided
2479 * they are not being written to inside the body of the loop.
2480 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2481 * essentially treated as a while loop, with iteration domain
2482 * { [i] : i >= init }.
2484 * We extract a pet_scop for the body and then embed it in a loop with
2485 * iteration domain and schedule
2487 * { [i] : i >= init and condition' }
2492 * { [i] : i <= init and condition' }
2495 * Where condition' is equal to condition if the latter is
2496 * a simple upper [lower] bound and a condition that is extended
2497 * to apply to all previous iterations otherwise.
2499 * If the condition is non-affine, then we drop the condition from the
2500 * iteration domain and instead create a separate statement
2501 * for evaluating the condition. The body is then filtered to depend
2502 * on the result of the condition evaluating to true on all iterations
2503 * up to the current iteration, while the evaluation the condition itself
2504 * is filtered to depend on the result of the condition evaluating to true
2505 * on all previous iterations.
2506 * The context of the scop representing the body is dropped
2507 * because we don't know how many times the body will be executed,
2510 * If the stride of the loop is not 1, then "i >= init" is replaced by
2512 * (exists a: i = init + stride * a and a >= 0)
2514 * If the loop iterator i is unsigned, then wrapping may occur.
2515 * We therefore use a virtual iterator instead that does not wrap.
2516 * However, the condition in the code applies
2517 * to the wrapped value, so we need to change condition(i)
2518 * into condition([i % 2^width]). Similarly, we replace all accesses
2519 * to the original iterator by the wrapping of the virtual iterator.
2520 * Note that there may be no need to perform this final wrapping
2521 * if the loop condition (after wrapping) satisfies certain conditions.
2522 * However, the is_simple_bound condition is not enough since it doesn't
2523 * check if there even is an upper bound.
2525 * Wrapping on unsigned iterators can be avoided entirely if
2526 * loop condition is simple, the loop iterator is incremented
2527 * [decremented] by one and the last value before wrapping cannot
2528 * possibly satisfy the loop condition.
2530 * Before extracting a pet_scop from the body we remove all
2531 * assignments in assigned_value to variables that are assigned
2532 * somewhere in the body of the loop.
2534 * Valid parameters for a for loop are those for which the initial
2535 * value itself, the increment on each domain iteration and
2536 * the condition on both the initial value and
2537 * the result of incrementing the iterator for each iteration of the domain
2539 * If the loop condition is non-affine, then we only consider validity
2540 * of the initial value.
2542 * If the body contains any break, then we keep track of it in "skip"
2543 * (if the skip condition is affine) or it is handled in scop_add_break
2544 * (if the skip condition is not affine).
2545 * Note that the affine break condition needs to be considered with
2546 * respect to previous iterations in the virtual domain (if any).
2548 * If we were only able to extract part of the body, then simply
2551 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2553 BinaryOperator
*ass
;
2558 isl_local_space
*ls
;
2561 isl_set
*cond
= NULL
;
2562 isl_set
*skip
= NULL
;
2563 isl_id
*id
, *id_test
= NULL
, *id_break_test
;
2564 struct pet_scop
*scop
, *scop_cond
= NULL
;
2565 assigned_value_cache
cache(assigned_value
);
2571 bool has_affine_break
;
2573 isl_aff
*wrap
= NULL
;
2574 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2575 isl_set
*valid_init
;
2576 isl_set
*valid_cond
;
2577 isl_set
*valid_cond_init
;
2578 isl_set
*valid_cond_next
;
2581 pet_expr
*pe_init
, *pe_inc
;
2582 pet_context
*pc
, *pc_init_val
;
2584 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2585 return extract_infinite_for(stmt
);
2587 init
= stmt
->getInit();
2592 if ((ass
= initialization_assignment(init
)) != NULL
) {
2593 iv
= extract_induction_variable(ass
);
2596 lhs
= ass
->getLHS();
2597 rhs
= ass
->getRHS();
2598 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2599 VarDecl
*var
= extract_induction_variable(init
, decl
);
2603 rhs
= var
->getInit();
2604 lhs
= create_DeclRefExpr(var
);
2606 unsupported(stmt
->getInit());
2610 id
= create_decl_id(ctx
, iv
);
2612 assigned_value
.erase(iv
);
2613 clear_assignments
clear(assigned_value
);
2614 clear
.TraverseStmt(stmt
->getBody());
2616 pe_init
= extract_expr(rhs
);
2617 pe_inc
= extract_increment(stmt
, iv
);
2618 pc
= convert_assignments(ctx
, assigned_value
);
2619 pc_init_val
= pet_context_copy(pc
);
2620 pc_init_val
= pet_context_mark_unknown(pc_init_val
, isl_id_copy(id
));
2621 init_val
= pet_expr_extract_affine(pe_init
, pc_init_val
);
2622 pet_context_free(pc_init_val
);
2623 pa_inc
= pet_expr_extract_affine(pe_inc
, pc
);
2624 pet_context_free(pc
);
2625 inc
= pet_extract_cst(pa_inc
);
2626 if (!pe_init
|| !pe_inc
|| !inc
|| isl_val_is_nan(inc
) ||
2627 isl_pw_aff_involves_nan(pa_inc
) ||
2628 isl_pw_aff_involves_nan(init_val
)) {
2631 isl_pw_aff_free(pa_inc
);
2632 isl_pw_aff_free(init_val
);
2633 if (pe_init
&& pe_inc
&& !(pa_inc
&& !inc
))
2634 return extract_non_affine_for(stmt
, iv
,
2636 pet_expr_free(pe_init
);
2637 pet_expr_free(pe_inc
);
2640 pet_expr_free(pe_init
);
2641 pet_expr_free(pe_inc
);
2643 pa
= try_extract_nested_condition(stmt
->getCond());
2644 if (allow_nested
&& (!pa
|| pet_nested_any_in_pw_aff(pa
)))
2647 scop
= extract(stmt
->getBody());
2650 isl_pw_aff_free(init_val
);
2651 isl_pw_aff_free(pa_inc
);
2652 isl_pw_aff_free(pa
);
2657 valid_inc
= isl_pw_aff_domain(pa_inc
);
2659 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2661 has_affine_break
= scop
&&
2662 pet_scop_has_affine_skip(scop
, pet_skip_later
);
2663 if (has_affine_break
)
2664 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
2665 has_var_break
= scop
&& pet_scop_has_var_skip(scop
, pet_skip_later
);
2667 id_break_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
2669 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2670 isl_pw_aff_free(pa
);
2674 if (!allow_nested
&& !pa
)
2675 pa
= try_extract_affine_condition(stmt
->getCond());
2676 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2677 cond
= isl_pw_aff_non_zero_set(pa
);
2678 if (allow_nested
&& !cond
) {
2679 isl_multi_pw_aff
*test_index
;
2680 int save_n_stmt
= n_stmt
;
2681 test_index
= pet_create_test_index(ctx
, n_test
++);
2683 scop_cond
= extract_non_affine_condition(stmt
->getCond(),
2684 n_stmt
++, isl_multi_pw_aff_copy(test_index
));
2685 n_stmt
= save_n_stmt
;
2686 scop_cond
= scop_add_array(scop_cond
, test_index
, ast_context
);
2687 id_test
= isl_multi_pw_aff_get_tuple_id(test_index
,
2689 isl_multi_pw_aff_free(test_index
);
2690 scop_cond
= pet_scop_prefix(scop_cond
, 0);
2691 scop
= pet_scop_reset_context(scop
);
2692 scop
= pet_scop_prefix(scop
, 1);
2693 cond
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2696 cond
= embed(cond
, isl_id_copy(id
));
2697 skip
= embed(skip
, isl_id_copy(id
));
2698 valid_cond
= isl_set_coalesce(valid_cond
);
2699 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
2700 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
2701 is_one
= isl_val_is_one(inc
) || isl_val_is_negone(inc
);
2702 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2704 valid_cond_init
= enforce_subset(
2705 isl_map_range(isl_map_from_pw_aff(isl_pw_aff_copy(init_val
))),
2706 isl_set_copy(valid_cond
));
2707 if (is_one
&& !is_virtual
) {
2708 isl_pw_aff_free(init_val
);
2709 pa
= extract_comparison(isl_val_is_pos(inc
) ? BO_GE
: BO_LE
,
2711 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2712 valid_init
= set_project_out_by_id(valid_init
, id
);
2713 domain
= isl_pw_aff_non_zero_set(pa
);
2715 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
2716 domain
= strided_domain(isl_id_copy(id
), init_val
,
2720 domain
= embed(domain
, isl_id_copy(id
));
2723 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2724 rev_wrap
= isl_map_from_aff(isl_aff_copy(wrap
));
2725 rev_wrap
= isl_map_reverse(rev_wrap
);
2726 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
2727 skip
= isl_set_apply(skip
, isl_map_copy(rev_wrap
));
2728 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
2729 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
2731 is_simple
= is_simple_bound(cond
, inc
);
2733 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2734 is_simple
= is_simple_bound(cond
, inc
);
2737 cond
= valid_for_each_iteration(cond
,
2738 isl_set_copy(domain
), isl_val_copy(inc
));
2739 domain
= isl_set_intersect(domain
, cond
);
2740 if (has_affine_break
) {
2741 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2742 skip
= after(skip
, isl_val_sgn(inc
));
2743 domain
= isl_set_subtract(domain
, skip
);
2745 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2746 ls
= isl_local_space_from_space(isl_set_get_space(domain
));
2747 sched
= isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
2748 if (isl_val_is_neg(inc
))
2749 sched
= isl_aff_neg(sched
);
2751 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
),
2753 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
2756 wrap
= identity_aff(domain
);
2758 scop_cond
= pet_scop_embed(scop_cond
, isl_set_copy(domain
),
2759 isl_aff_copy(sched
), isl_aff_copy(wrap
), isl_id_copy(id
));
2760 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), sched
, wrap
, id
);
2761 scop
= resolve_nested(scop
);
2763 scop
= scop_add_break(scop
, id_break_test
, isl_set_copy(domain
),
2766 scop
= scop_add_while(scop_cond
, scop
, id_test
, domain
,
2768 isl_set_free(valid_inc
);
2770 scop
= pet_scop_restrict_context(scop
, valid_inc
);
2771 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
2772 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
2773 isl_set_free(domain
);
2775 clear_assignment(assigned_value
, iv
);
2779 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid_init
));
2784 /* Try and construct a pet_scop corresponding to a compound statement.
2786 * "skip_declarations" is set if we should skip initial declarations
2787 * in the children of the compound statements. This then implies
2788 * that this sequence of children should not be treated as a block
2789 * since the initial statements may be skipped.
2791 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
, bool skip_declarations
)
2793 return extract(stmt
->children(), !skip_declarations
, skip_declarations
);
2796 /* Extract a pet_expr from an isl_id created by pet_nested_pet_expr.
2797 * Such an isl_id has name "__pet_expr" and
2798 * the user pointer points to a pet_expr object.
2800 __isl_give pet_expr
*PetScan::extract_expr(__isl_keep isl_id
*id
)
2802 return pet_expr_copy((pet_expr
*) isl_id_get_user(id
));
2805 /* For each nested access parameter in "space",
2806 * construct a corresponding pet_expr, place it in args and
2807 * record its position in "param2pos".
2808 * "n_arg" is the number of elements that are already in args.
2809 * The position recorded in "param2pos" takes this number into account.
2810 * If the pet_expr corresponding to a parameter is identical to
2811 * the pet_expr corresponding to an earlier parameter, then these two
2812 * parameters are made to refer to the same element in args.
2814 * Return the final number of elements in args or -1 if an error has occurred.
2816 int PetScan::extract_nested(__isl_keep isl_space
*space
,
2817 int n_arg
, pet_expr
**args
, std::map
<int,int> ¶m2pos
)
2821 nparam
= isl_space_dim(space
, isl_dim_param
);
2822 for (int i
= 0; i
< nparam
; ++i
) {
2824 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2826 if (!pet_nested_in_id(id
)) {
2831 args
[n_arg
] = extract_expr(id
);
2836 for (j
= 0; j
< n_arg
; ++j
)
2837 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
2841 pet_expr_free(args
[n_arg
]);
2845 param2pos
[i
] = n_arg
++;
2851 /* For each nested access parameter in the access relations in "expr",
2852 * construct a corresponding pet_expr, place it in the arguments of "expr"
2853 * and record its position in "param2pos".
2854 * n is the number of nested access parameters.
2856 __isl_give pet_expr
*PetScan::extract_nested(__isl_take pet_expr
*expr
, int n
,
2857 std::map
<int,int> ¶m2pos
)
2863 args
= isl_calloc_array(ctx
, pet_expr
*, n
);
2865 return pet_expr_free(expr
);
2867 space
= pet_expr_access_get_parameter_space(expr
);
2868 n
= extract_nested(space
, 0, args
, param2pos
);
2869 isl_space_free(space
);
2872 expr
= pet_expr_free(expr
);
2874 expr
= pet_expr_set_n_arg(expr
, n
);
2876 for (i
= 0; i
< n
; ++i
)
2877 expr
= pet_expr_set_arg(expr
, i
, args
[i
]);
2883 /* Look for parameters in any access relation in "expr" that
2884 * refer to nested accesses. In particular, these are
2885 * parameters with name "__pet_expr".
2887 * If there are any such parameters, then the domain of the index
2888 * expression and the access relation, which is still [] at this point,
2889 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
2890 * (after identifying identical nested accesses).
2892 * This transformation is performed in several steps.
2893 * We first extract the arguments in extract_nested.
2894 * param2pos maps the original parameter position to the position
2896 * Then we move these parameters to input dimensions.
2897 * t2pos maps the positions of these temporary input dimensions
2898 * to the positions of the corresponding arguments.
2899 * Finally, we express these temporary dimensions in terms of the domain
2900 * [[] -> [t_1,...,t_n]] and precompose index expression and access
2901 * relations with this function.
2903 __isl_give pet_expr
*PetScan::resolve_nested(__isl_take pet_expr
*expr
)
2908 isl_local_space
*ls
;
2911 std::map
<int,int> param2pos
;
2912 std::map
<int,int> t2pos
;
2917 n
= pet_expr_get_n_arg(expr
);
2918 for (int i
= 0; i
< n
; ++i
) {
2920 arg
= pet_expr_get_arg(expr
, i
);
2921 arg
= resolve_nested(arg
);
2922 expr
= pet_expr_set_arg(expr
, i
, arg
);
2925 if (pet_expr_get_type(expr
) != pet_expr_access
)
2928 space
= pet_expr_access_get_parameter_space(expr
);
2929 n
= pet_nested_n_in_space(space
);
2930 isl_space_free(space
);
2934 expr
= extract_nested(expr
, n
, param2pos
);
2938 expr
= pet_expr_access_align_params(expr
);
2943 space
= pet_expr_access_get_parameter_space(expr
);
2944 nparam
= isl_space_dim(space
, isl_dim_param
);
2945 for (int i
= nparam
- 1; i
>= 0; --i
) {
2946 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2947 if (!pet_nested_in_id(id
)) {
2952 expr
= pet_expr_access_move_dims(expr
,
2953 isl_dim_in
, n
, isl_dim_param
, i
, 1);
2954 t2pos
[n
] = param2pos
[i
];
2959 isl_space_free(space
);
2961 space
= pet_expr_access_get_parameter_space(expr
);
2962 space
= isl_space_set_from_params(space
);
2963 space
= isl_space_add_dims(space
, isl_dim_set
,
2964 pet_expr_get_n_arg(expr
));
2965 space
= isl_space_wrap(isl_space_from_range(space
));
2966 ls
= isl_local_space_from_space(isl_space_copy(space
));
2967 space
= isl_space_from_domain(space
);
2968 space
= isl_space_add_dims(space
, isl_dim_out
, n
);
2969 ma
= isl_multi_aff_zero(space
);
2971 for (int i
= 0; i
< n
; ++i
) {
2972 aff
= isl_aff_var_on_domain(isl_local_space_copy(ls
),
2973 isl_dim_set
, t2pos
[i
]);
2974 ma
= isl_multi_aff_set_aff(ma
, i
, aff
);
2976 isl_local_space_free(ls
);
2978 expr
= pet_expr_access_pullback_multi_aff(expr
, ma
);
2983 /* Return the file offset of the expansion location of "Loc".
2985 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
2987 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
2990 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
2992 /* Return a SourceLocation for the location after the first semicolon
2993 * after "loc". If Lexer::findLocationAfterToken is available, we simply
2994 * call it and also skip trailing spaces and newline.
2996 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
2997 const LangOptions
&LO
)
2999 return Lexer::findLocationAfterToken(loc
, tok::semi
, SM
, LO
, true);
3004 /* Return a SourceLocation for the location after the first semicolon
3005 * after "loc". If Lexer::findLocationAfterToken is not available,
3006 * we look in the underlying character data for the first semicolon.
3008 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3009 const LangOptions
&LO
)
3012 const char *s
= SM
.getCharacterData(loc
);
3014 semi
= strchr(s
, ';');
3016 return SourceLocation();
3017 return loc
.getFileLocWithOffset(semi
+ 1 - s
);
3022 /* If the token at "loc" is the first token on the line, then return
3023 * a location referring to the start of the line.
3024 * Otherwise, return "loc".
3026 * This function is used to extend a scop to the start of the line
3027 * if the first token of the scop is also the first token on the line.
3029 * We look for the first token on the line. If its location is equal to "loc",
3030 * then the latter is the location of the first token on the line.
3032 static SourceLocation
move_to_start_of_line_if_first_token(SourceLocation loc
,
3033 SourceManager
&SM
, const LangOptions
&LO
)
3035 std::pair
<FileID
, unsigned> file_offset_pair
;
3036 llvm::StringRef file
;
3039 SourceLocation token_loc
, line_loc
;
3042 loc
= SM
.getExpansionLoc(loc
);
3043 col
= SM
.getExpansionColumnNumber(loc
);
3044 line_loc
= loc
.getLocWithOffset(1 - col
);
3045 file_offset_pair
= SM
.getDecomposedLoc(line_loc
);
3046 file
= SM
.getBufferData(file_offset_pair
.first
, NULL
);
3047 pos
= file
.data() + file_offset_pair
.second
;
3049 Lexer
lexer(SM
.getLocForStartOfFile(file_offset_pair
.first
), LO
,
3050 file
.begin(), pos
, file
.end());
3051 lexer
.LexFromRawLexer(tok
);
3052 token_loc
= tok
.getLocation();
3054 if (token_loc
== loc
)
3060 /* Update start and end of "scop" to include the region covered by "range".
3061 * If "skip_semi" is set, then we assume "range" is followed by
3062 * a semicolon and also include this semicolon.
3064 struct pet_scop
*PetScan::update_scop_start_end(struct pet_scop
*scop
,
3065 SourceRange range
, bool skip_semi
)
3067 SourceLocation loc
= range
.getBegin();
3068 SourceManager
&SM
= PP
.getSourceManager();
3069 const LangOptions
&LO
= PP
.getLangOpts();
3070 unsigned start
, end
;
3072 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
);
3073 start
= getExpansionOffset(SM
, loc
);
3074 loc
= range
.getEnd();
3076 loc
= location_after_semi(loc
, SM
, LO
);
3078 loc
= PP
.getLocForEndOfToken(loc
);
3079 end
= getExpansionOffset(SM
, loc
);
3081 scop
= pet_scop_update_start_end(scop
, start
, end
);
3085 /* Convert a top-level pet_expr to a pet_scop with one statement.
3086 * This mainly involves resolving nested expression parameters
3087 * and setting the name of the iteration space.
3088 * The name is given by "label" if it is non-NULL. Otherwise,
3089 * it is of the form S_<n_stmt>.
3090 * start and end of the pet_scop are derived from "range" and "skip_semi".
3091 * In particular, if "skip_semi" is set then the semicolon following "range"
3094 struct pet_scop
*PetScan::extract(__isl_take pet_expr
*expr
, SourceRange range
,
3095 bool skip_semi
, __isl_take isl_id
*label
)
3097 struct pet_stmt
*ps
;
3098 struct pet_scop
*scop
;
3099 SourceLocation loc
= range
.getBegin();
3100 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3102 expr
= resolve_nested(expr
);
3103 ps
= pet_stmt_from_pet_expr(line
, label
, n_stmt
++, expr
);
3104 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3106 scop
= update_scop_start_end(scop
, range
, skip_semi
);
3110 /* Check if we can extract an affine expression from "expr".
3111 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3112 * We turn on autodetection so that we won't generate any warnings
3113 * and turn off nesting, so that we won't accept any non-affine constructs.
3115 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
3118 int save_autodetect
= options
->autodetect
;
3119 bool save_nesting
= nesting_enabled
;
3121 options
->autodetect
= 1;
3122 nesting_enabled
= false;
3124 pwaff
= extract_affine(expr
);
3126 options
->autodetect
= save_autodetect
;
3127 nesting_enabled
= save_nesting
;
3132 /* Check if we can extract an affine constraint from "expr".
3133 * Return the constraint as an isl_set if we can and NULL otherwise.
3134 * We turn on autodetection so that we won't generate any warnings
3135 * and turn off nesting, so that we won't accept any non-affine constructs.
3137 __isl_give isl_pw_aff
*PetScan::try_extract_affine_condition(Expr
*expr
)
3140 int save_autodetect
= options
->autodetect
;
3141 bool save_nesting
= nesting_enabled
;
3143 options
->autodetect
= 1;
3144 nesting_enabled
= false;
3146 cond
= extract_condition(expr
);
3148 options
->autodetect
= save_autodetect
;
3149 nesting_enabled
= save_nesting
;
3154 /* Check whether "expr" is an affine constraint.
3156 bool PetScan::is_affine_condition(Expr
*expr
)
3160 cond
= try_extract_affine_condition(expr
);
3161 isl_pw_aff_free(cond
);
3163 return cond
!= NULL
;
3166 /* Check if we can extract a condition from "expr".
3167 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3168 * If allow_nested is set, then the condition may involve parameters
3169 * corresponding to nested accesses.
3170 * We turn on autodetection so that we won't generate any warnings.
3172 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
3175 int save_autodetect
= options
->autodetect
;
3176 bool save_nesting
= nesting_enabled
;
3178 options
->autodetect
= 1;
3179 nesting_enabled
= allow_nested
;
3180 cond
= extract_condition(expr
);
3182 options
->autodetect
= save_autodetect
;
3183 nesting_enabled
= save_nesting
;
3188 /* If the top-level expression of "stmt" is an assignment, then
3189 * return that assignment as a BinaryOperator.
3190 * Otherwise return NULL.
3192 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
3194 BinaryOperator
*ass
;
3198 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
3201 ass
= cast
<BinaryOperator
>(stmt
);
3202 if(ass
->getOpcode() != BO_Assign
)
3208 /* Check if the given if statement is a conditional assignement
3209 * with a non-affine condition. If so, construct a pet_scop
3210 * corresponding to this conditional assignment. Otherwise return NULL.
3212 * In particular we check if "stmt" is of the form
3219 * where a is some array or scalar access.
3220 * The constructed pet_scop then corresponds to the expression
3222 * a = condition ? f(...) : g(...)
3224 * All access relations in f(...) are intersected with condition
3225 * while all access relation in g(...) are intersected with the complement.
3227 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
3229 BinaryOperator
*ass_then
, *ass_else
;
3230 isl_multi_pw_aff
*write_then
, *write_else
;
3231 isl_set
*cond
, *comp
;
3232 isl_multi_pw_aff
*index
;
3236 pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
3237 bool save_nesting
= nesting_enabled
;
3239 if (!options
->detect_conditional_assignment
)
3242 ass_then
= top_assignment_or_null(stmt
->getThen());
3243 ass_else
= top_assignment_or_null(stmt
->getElse());
3245 if (!ass_then
|| !ass_else
)
3248 if (is_affine_condition(stmt
->getCond()))
3251 write_then
= extract_index(ass_then
->getLHS());
3252 write_else
= extract_index(ass_else
->getLHS());
3254 equal
= isl_multi_pw_aff_plain_is_equal(write_then
, write_else
);
3255 isl_multi_pw_aff_free(write_else
);
3256 if (equal
< 0 || !equal
) {
3257 isl_multi_pw_aff_free(write_then
);
3261 nesting_enabled
= allow_nested
;
3262 pa
= extract_condition(stmt
->getCond());
3263 nesting_enabled
= save_nesting
;
3264 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
3265 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
3266 index
= isl_multi_pw_aff_from_pw_aff(pa
);
3268 pe_cond
= pet_expr_from_index(index
);
3270 pe_then
= extract_expr(ass_then
->getRHS());
3271 pe_then
= pet_expr_restrict(pe_then
, cond
);
3272 pe_else
= extract_expr(ass_else
->getRHS());
3273 pe_else
= pet_expr_restrict(pe_else
, comp
);
3275 pe
= pet_expr_new_ternary(pe_cond
, pe_then
, pe_else
);
3276 type_size
= get_type_size(ass_then
->getType(), ast_context
);
3277 pe_write
= pet_expr_from_index_and_depth(type_size
, write_then
,
3278 extract_depth(write_then
));
3279 pe_write
= pet_expr_access_set_write(pe_write
, 1);
3280 pe_write
= pet_expr_access_set_read(pe_write
, 0);
3281 pe
= pet_expr_new_binary(type_size
, pet_op_assign
, pe_write
, pe
);
3282 return extract(pe
, stmt
->getSourceRange(), false);
3285 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3286 * evaluating "cond" and writing the result to a virtual scalar,
3287 * as expressed by "index".
3289 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
, int stmt_nr
,
3290 __isl_take isl_multi_pw_aff
*index
)
3292 pet_expr
*expr
, *write
;
3293 struct pet_stmt
*ps
;
3294 SourceLocation loc
= cond
->getLocStart();
3295 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3297 write
= pet_expr_from_index(index
);
3298 write
= pet_expr_access_set_write(write
, 1);
3299 write
= pet_expr_access_set_read(write
, 0);
3300 expr
= extract_expr(cond
);
3301 expr
= resolve_nested(expr
);
3302 expr
= pet_expr_new_binary(1, pet_op_assign
, write
, expr
);
3303 ps
= pet_stmt_from_pet_expr(line
, NULL
, stmt_nr
, expr
);
3304 return pet_scop_from_pet_stmt(ctx
, ps
);
3308 static __isl_give pet_expr
*embed_access(__isl_take pet_expr
*expr
,
3312 /* Precompose the access relation and the index expression associated
3313 * to "expr" with the function pointed to by "user",
3314 * thereby embedding the access relation in the domain of this function.
3315 * The initial domain of the access relation and the index expression
3316 * is the zero-dimensional domain.
3318 static __isl_give pet_expr
*embed_access(__isl_take pet_expr
*expr
, void *user
)
3320 isl_multi_aff
*ma
= (isl_multi_aff
*) user
;
3322 return pet_expr_access_pullback_multi_aff(expr
, isl_multi_aff_copy(ma
));
3325 /* Precompose all access relations in "expr" with "ma", thereby
3326 * embedding them in the domain of "ma".
3328 static __isl_give pet_expr
*embed(__isl_take pet_expr
*expr
,
3329 __isl_keep isl_multi_aff
*ma
)
3331 return pet_expr_map_access(expr
, &embed_access
, ma
);
3334 /* For each nested access parameter in the domain of "stmt",
3335 * construct a corresponding pet_expr, place it before the original
3336 * elements in stmt->args and record its position in "param2pos".
3337 * n is the number of nested access parameters.
3339 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
3340 std::map
<int,int> ¶m2pos
)
3347 n_arg
= stmt
->n_arg
;
3348 args
= isl_calloc_array(ctx
, pet_expr
*, n
+ n_arg
);
3352 space
= isl_set_get_space(stmt
->domain
);
3353 n_arg
= extract_nested(space
, 0, args
, param2pos
);
3354 isl_space_free(space
);
3359 for (i
= 0; i
< stmt
->n_arg
; ++i
)
3360 args
[n_arg
+ i
] = stmt
->args
[i
];
3363 stmt
->n_arg
+= n_arg
;
3368 for (i
= 0; i
< n
; ++i
)
3369 pet_expr_free(args
[i
]);
3372 pet_stmt_free(stmt
);
3376 /* Check whether any of the arguments i of "stmt" starting at position "n"
3377 * is equal to one of the first "n" arguments j.
3378 * If so, combine the constraints on arguments i and j and remove
3381 static struct pet_stmt
*remove_duplicate_arguments(struct pet_stmt
*stmt
, int n
)
3390 if (n
== stmt
->n_arg
)
3393 map
= isl_set_unwrap(stmt
->domain
);
3395 for (i
= stmt
->n_arg
- 1; i
>= n
; --i
) {
3396 for (j
= 0; j
< n
; ++j
)
3397 if (pet_expr_is_equal(stmt
->args
[i
], stmt
->args
[j
]))
3402 map
= isl_map_equate(map
, isl_dim_out
, i
, isl_dim_out
, j
);
3403 map
= isl_map_project_out(map
, isl_dim_out
, i
, 1);
3405 pet_expr_free(stmt
->args
[i
]);
3406 for (j
= i
; j
+ 1 < stmt
->n_arg
; ++j
)
3407 stmt
->args
[j
] = stmt
->args
[j
+ 1];
3411 stmt
->domain
= isl_map_wrap(map
);
3416 pet_stmt_free(stmt
);
3420 /* Look for parameters in the iteration domain of "stmt" that
3421 * refer to nested accesses. In particular, these are
3422 * parameters with name "__pet_expr".
3424 * If there are any such parameters, then as many extra variables
3425 * (after identifying identical nested accesses) are inserted in the
3426 * range of the map wrapped inside the domain, before the original variables.
3427 * If the original domain is not a wrapped map, then a new wrapped
3428 * map is created with zero output dimensions.
3429 * The parameters are then equated to the corresponding output dimensions
3430 * and subsequently projected out, from the iteration domain,
3431 * the schedule and the access relations.
3432 * For each of the output dimensions, a corresponding argument
3433 * expression is inserted. Initially they are created with
3434 * a zero-dimensional domain, so they have to be embedded
3435 * in the current iteration domain.
3436 * param2pos maps the position of the parameter to the position
3437 * of the corresponding output dimension in the wrapped map.
3439 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3447 std::map
<int,int> param2pos
;
3452 n
= pet_nested_n_in_set(stmt
->domain
);
3456 n_arg
= stmt
->n_arg
;
3457 stmt
= extract_nested(stmt
, n
, param2pos
);
3461 n
= stmt
->n_arg
- n_arg
;
3462 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3463 if (isl_set_is_wrapping(stmt
->domain
))
3464 map
= isl_set_unwrap(stmt
->domain
);
3466 map
= isl_map_from_domain(stmt
->domain
);
3467 map
= isl_map_insert_dims(map
, isl_dim_out
, 0, n
);
3469 for (int i
= nparam
- 1; i
>= 0; --i
) {
3472 if (!pet_nested_in_map(map
, i
))
3475 id
= pet_expr_access_get_id(stmt
->args
[param2pos
[i
]]);
3476 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3477 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3479 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3482 stmt
->domain
= isl_map_wrap(map
);
3484 space
= isl_space_unwrap(isl_set_get_space(stmt
->domain
));
3485 space
= isl_space_from_domain(isl_space_domain(space
));
3486 ma
= isl_multi_aff_zero(space
);
3487 for (int pos
= 0; pos
< n
; ++pos
)
3488 stmt
->args
[pos
] = embed(stmt
->args
[pos
], ma
);
3489 isl_multi_aff_free(ma
);
3491 stmt
= pet_stmt_remove_nested_parameters(stmt
);
3492 stmt
= remove_duplicate_arguments(stmt
, n
);
3497 /* For each statement in "scop", move the parameters that correspond
3498 * to nested access into the ranges of the domains and create
3499 * corresponding argument expressions.
3501 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3506 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3507 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3508 if (!scop
->stmts
[i
])
3514 pet_scop_free(scop
);
3518 /* Given an access expression "expr", is the variable accessed by
3519 * "expr" assigned anywhere inside "scop"?
3521 static bool is_assigned(__isl_keep pet_expr
*expr
, pet_scop
*scop
)
3523 bool assigned
= false;
3526 id
= pet_expr_access_get_id(expr
);
3527 assigned
= pet_scop_writes(scop
, id
);
3533 /* Are all nested access parameters in "pa" allowed given "scop".
3534 * In particular, is none of them written by anywhere inside "scop".
3536 * If "scop" has any skip conditions, then no nested access parameters
3537 * are allowed. In particular, if there is any nested access in a guard
3538 * for a piece of code containing a "continue", then we want to introduce
3539 * a separate statement for evaluating this guard so that we can express
3540 * that the result is false for all previous iterations.
3542 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3549 if (!pet_nested_any_in_pw_aff(pa
))
3552 if (pet_scop_has_skip(scop
, pet_skip_now
))
3555 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3556 for (int i
= 0; i
< nparam
; ++i
) {
3557 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3561 if (!pet_nested_in_id(id
)) {
3566 expr
= extract_expr(id
);
3567 allowed
= pet_expr_get_type(expr
) == pet_expr_access
&&
3568 !is_assigned(expr
, scop
);
3570 pet_expr_free(expr
);
3580 /* Construct a pet_scop for a non-affine if statement.
3582 * We create a separate statement that writes the result
3583 * of the non-affine condition to a virtual scalar.
3584 * A constraint requiring the value of this virtual scalar to be one
3585 * is added to the iteration domains of the then branch.
3586 * Similarly, a constraint requiring the value of this virtual scalar
3587 * to be zero is added to the iteration domains of the else branch, if any.
3588 * We adjust the schedules to ensure that the virtual scalar is written
3589 * before it is read.
3591 * If there are any breaks or continues in the then and/or else
3592 * branches, then we may have to compute a new skip condition.
3593 * This is handled using a pet_skip_info object.
3594 * On initialization, the object checks if skip conditions need
3595 * to be computed. If so, it does so in pet_skip_info_if_extract_index and
3596 * adds them in pet_skip_info_if_add.
3598 struct pet_scop
*PetScan::extract_non_affine_if(Expr
*cond
,
3599 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3600 bool have_else
, int stmt_id
)
3602 struct pet_scop
*scop
;
3603 isl_multi_pw_aff
*test_index
;
3605 int save_n_stmt
= n_stmt
;
3607 test_index
= pet_create_test_index(ctx
, n_test
++);
3609 scop
= extract_non_affine_condition(cond
, n_stmt
++,
3610 isl_multi_pw_aff_copy(test_index
));
3611 n_stmt
= save_n_stmt
;
3612 scop
= scop_add_array(scop
, test_index
, ast_context
);
3615 pet_skip_info_if_init(&skip
, ctx
, scop_then
, scop_else
, have_else
, 0);
3616 int_size
= ast_context
.getTypeInfo(ast_context
.IntTy
).first
/ 8;
3617 pet_skip_info_if_extract_index(&skip
, test_index
, int_size
,
3620 scop
= pet_scop_prefix(scop
, 0);
3621 scop_then
= pet_scop_prefix(scop_then
, 1);
3622 scop_then
= pet_scop_filter(scop_then
,
3623 isl_multi_pw_aff_copy(test_index
), 1);
3625 scop_else
= pet_scop_prefix(scop_else
, 1);
3626 scop_else
= pet_scop_filter(scop_else
, test_index
, 0);
3627 scop_then
= pet_scop_add_par(ctx
, scop_then
, scop_else
);
3629 isl_multi_pw_aff_free(test_index
);
3631 scop
= pet_scop_add_seq(ctx
, scop
, scop_then
);
3633 scop
= pet_skip_info_if_add(&skip
, scop
, 2);
3638 /* Construct a pet_scop for an if statement.
3640 * If the condition fits the pattern of a conditional assignment,
3641 * then it is handled by extract_conditional_assignment.
3642 * Otherwise, we do the following.
3644 * If the condition is affine, then the condition is added
3645 * to the iteration domains of the then branch, while the
3646 * opposite of the condition in added to the iteration domains
3647 * of the else branch, if any.
3648 * We allow the condition to be dynamic, i.e., to refer to
3649 * scalars or array elements that may be written to outside
3650 * of the given if statement. These nested accesses are then represented
3651 * as output dimensions in the wrapping iteration domain.
3652 * If it is also written _inside_ the then or else branch, then
3653 * we treat the condition as non-affine.
3654 * As explained in extract_non_affine_if, this will introduce
3655 * an extra statement.
3656 * For aesthetic reasons, we want this statement to have a statement
3657 * number that is lower than those of the then and else branches.
3658 * In order to evaluate if we will need such a statement, however, we
3659 * first construct scops for the then and else branches.
3660 * We therefore reserve a statement number if we might have to
3661 * introduce such an extra statement.
3663 * If the condition is not affine, then the scop is created in
3664 * extract_non_affine_if.
3666 * If there are any breaks or continues in the then and/or else
3667 * branches, then we may have to compute a new skip condition.
3668 * This is handled using a pet_skip_info object.
3669 * On initialization, the object checks if skip conditions need
3670 * to be computed. If so, it does so in pet_skip_info_if_extract_cond and
3671 * adds them in pet_skip_info_if_add.
3673 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
3675 struct pet_scop
*scop_then
, *scop_else
= NULL
, *scop
;
3682 clear_assignments
clear(assigned_value
);
3683 clear
.TraverseStmt(stmt
->getThen());
3684 if (stmt
->getElse())
3685 clear
.TraverseStmt(stmt
->getElse());
3687 scop
= extract_conditional_assignment(stmt
);
3691 cond
= try_extract_nested_condition(stmt
->getCond());
3692 if (allow_nested
&& (!cond
|| pet_nested_any_in_pw_aff(cond
)))
3696 assigned_value_cache
cache(assigned_value
);
3697 scop_then
= extract(stmt
->getThen());
3700 if (stmt
->getElse()) {
3701 assigned_value_cache
cache(assigned_value
);
3702 scop_else
= extract(stmt
->getElse());
3703 if (options
->autodetect
) {
3704 if (scop_then
&& !scop_else
) {
3706 isl_pw_aff_free(cond
);
3709 if (!scop_then
&& scop_else
) {
3711 isl_pw_aff_free(cond
);
3718 (!is_nested_allowed(cond
, scop_then
) ||
3719 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
3720 isl_pw_aff_free(cond
);
3723 if (allow_nested
&& !cond
)
3724 return extract_non_affine_if(stmt
->getCond(), scop_then
,
3725 scop_else
, stmt
->getElse(), stmt_id
);
3728 cond
= extract_condition(stmt
->getCond());
3731 pet_skip_info_if_init(&skip
, ctx
, scop_then
, scop_else
,
3732 stmt
->getElse() != NULL
, 1);
3733 pet_skip_info_if_extract_cond(&skip
, cond
, int_size
, &n_stmt
, &n_test
);
3735 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
3736 set
= isl_pw_aff_non_zero_set(cond
);
3737 scop
= pet_scop_restrict(scop_then
, isl_set_params(isl_set_copy(set
)));
3739 if (stmt
->getElse()) {
3740 set
= isl_set_subtract(isl_set_copy(valid
), set
);
3741 scop_else
= pet_scop_restrict(scop_else
, isl_set_params(set
));
3742 scop
= pet_scop_add_par(ctx
, scop
, scop_else
);
3745 scop
= resolve_nested(scop
);
3746 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid
));
3748 if (pet_skip_info_has_skip(&skip
))
3749 scop
= pet_scop_prefix(scop
, 0);
3750 scop
= pet_skip_info_if_add(&skip
, scop
, 1);
3755 /* Try and construct a pet_scop for a label statement.
3756 * We currently only allow labels on expression statements.
3758 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
3763 sub
= stmt
->getSubStmt();
3764 if (!isa
<Expr
>(sub
)) {
3769 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
3771 return extract(extract_expr(cast
<Expr
>(sub
)), stmt
->getSourceRange(),
3775 /* Return a one-dimensional multi piecewise affine expression that is equal
3776 * to the constant 1 and is defined over a zero-dimensional domain.
3778 static __isl_give isl_multi_pw_aff
*one_mpa(isl_ctx
*ctx
)
3781 isl_local_space
*ls
;
3784 space
= isl_space_set_alloc(ctx
, 0, 0);
3785 ls
= isl_local_space_from_space(space
);
3786 aff
= isl_aff_zero_on_domain(ls
);
3787 aff
= isl_aff_set_constant_si(aff
, 1);
3789 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
3792 /* Construct a pet_scop for a continue statement.
3794 * We simply create an empty scop with a universal pet_skip_now
3795 * skip condition. This skip condition will then be taken into
3796 * account by the enclosing loop construct, possibly after
3797 * being incorporated into outer skip conditions.
3799 struct pet_scop
*PetScan::extract(ContinueStmt
*stmt
)
3803 scop
= pet_scop_empty(ctx
);
3807 scop
= pet_scop_set_skip(scop
, pet_skip_now
, one_mpa(ctx
));
3812 /* Construct a pet_scop for a break statement.
3814 * We simply create an empty scop with both a universal pet_skip_now
3815 * skip condition and a universal pet_skip_later skip condition.
3816 * These skip conditions will then be taken into
3817 * account by the enclosing loop construct, possibly after
3818 * being incorporated into outer skip conditions.
3820 struct pet_scop
*PetScan::extract(BreakStmt
*stmt
)
3823 isl_multi_pw_aff
*skip
;
3825 scop
= pet_scop_empty(ctx
);
3829 skip
= one_mpa(ctx
);
3830 scop
= pet_scop_set_skip(scop
, pet_skip_now
,
3831 isl_multi_pw_aff_copy(skip
));
3832 scop
= pet_scop_set_skip(scop
, pet_skip_later
, skip
);
3837 /* Try and construct a pet_scop corresponding to "stmt".
3839 * If "stmt" is a compound statement, then "skip_declarations"
3840 * indicates whether we should skip initial declarations in the
3841 * compound statement.
3843 * If the constructed pet_scop is not a (possibly) partial representation
3844 * of "stmt", we update start and end of the pet_scop to those of "stmt".
3845 * In particular, if skip_declarations is set, then we may have skipped
3846 * declarations inside "stmt" and so the pet_scop may not represent
3847 * the entire "stmt".
3848 * Note that this function may be called with "stmt" referring to the entire
3849 * body of the function, including the outer braces. In such cases,
3850 * skip_declarations will be set and the braces will not be taken into
3851 * account in scop->start and scop->end.
3853 struct pet_scop
*PetScan::extract(Stmt
*stmt
, bool skip_declarations
)
3855 struct pet_scop
*scop
;
3857 if (isa
<Expr
>(stmt
))
3858 return extract(extract_expr(cast
<Expr
>(stmt
)),
3859 stmt
->getSourceRange(), true);
3861 switch (stmt
->getStmtClass()) {
3862 case Stmt::WhileStmtClass
:
3863 scop
= extract(cast
<WhileStmt
>(stmt
));
3865 case Stmt::ForStmtClass
:
3866 scop
= extract_for(cast
<ForStmt
>(stmt
));
3868 case Stmt::IfStmtClass
:
3869 scop
= extract(cast
<IfStmt
>(stmt
));
3871 case Stmt::CompoundStmtClass
:
3872 scop
= extract(cast
<CompoundStmt
>(stmt
), skip_declarations
);
3874 case Stmt::LabelStmtClass
:
3875 scop
= extract(cast
<LabelStmt
>(stmt
));
3877 case Stmt::ContinueStmtClass
:
3878 scop
= extract(cast
<ContinueStmt
>(stmt
));
3880 case Stmt::BreakStmtClass
:
3881 scop
= extract(cast
<BreakStmt
>(stmt
));
3883 case Stmt::DeclStmtClass
:
3884 scop
= extract(cast
<DeclStmt
>(stmt
));
3891 if (partial
|| skip_declarations
)
3894 scop
= update_scop_start_end(scop
, stmt
->getSourceRange(), false);
3899 /* Extract a clone of the kill statement in "scop".
3900 * "scop" is expected to have been created from a DeclStmt
3901 * and should have the kill as its first statement.
3903 struct pet_stmt
*PetScan::extract_kill(struct pet_scop
*scop
)
3906 struct pet_stmt
*stmt
;
3907 isl_multi_pw_aff
*index
;
3913 if (scop
->n_stmt
< 1)
3914 isl_die(ctx
, isl_error_internal
,
3915 "expecting at least one statement", return NULL
);
3916 stmt
= scop
->stmts
[0];
3917 if (!pet_stmt_is_kill(stmt
))
3918 isl_die(ctx
, isl_error_internal
,
3919 "expecting kill statement", return NULL
);
3921 arg
= pet_expr_get_arg(stmt
->body
, 0);
3922 index
= pet_expr_access_get_index(arg
);
3923 access
= pet_expr_access_get_access(arg
);
3925 index
= isl_multi_pw_aff_reset_tuple_id(index
, isl_dim_in
);
3926 access
= isl_map_reset_tuple_id(access
, isl_dim_in
);
3927 kill
= pet_expr_kill_from_access_and_index(access
, index
);
3928 return pet_stmt_from_pet_expr(stmt
->line
, NULL
, n_stmt
++, kill
);
3931 /* Mark all arrays in "scop" as being exposed.
3933 static struct pet_scop
*mark_exposed(struct pet_scop
*scop
)
3937 for (int i
= 0; i
< scop
->n_array
; ++i
)
3938 scop
->arrays
[i
]->exposed
= 1;
3942 /* Try and construct a pet_scop corresponding to (part of)
3943 * a sequence of statements.
3945 * "block" is set if the sequence respresents the children of
3946 * a compound statement.
3947 * "skip_declarations" is set if we should skip initial declarations
3948 * in the sequence of statements.
3950 * If there are any breaks or continues in the individual statements,
3951 * then we may have to compute a new skip condition.
3952 * This is handled using a pet_skip_info object.
3953 * On initialization, the object checks if skip conditions need
3954 * to be computed. If so, it does so in pet_skip_info_seq_extract and
3955 * adds them in pet_skip_info_seq_add.
3957 * If "block" is set, then we need to insert kill statements at
3958 * the end of the block for any array that has been declared by
3959 * one of the statements in the sequence. Each of these declarations
3960 * results in the construction of a kill statement at the place
3961 * of the declaration, so we simply collect duplicates of
3962 * those kill statements and append these duplicates to the constructed scop.
3964 * If "block" is not set, then any array declared by one of the statements
3965 * in the sequence is marked as being exposed.
3967 * If autodetect is set, then we allow the extraction of only a subrange
3968 * of the sequence of statements. However, if there is at least one statement
3969 * for which we could not construct a scop and the final range contains
3970 * either no statements or at least one kill, then we discard the entire
3973 struct pet_scop
*PetScan::extract(StmtRange stmt_range
, bool block
,
3974 bool skip_declarations
)
3980 bool partial_range
= false;
3981 set
<struct pet_stmt
*> kills
;
3982 set
<struct pet_stmt
*>::iterator it
;
3984 int_size
= ast_context
.getTypeInfo(ast_context
.IntTy
).first
/ 8;
3986 scop
= pet_scop_empty(ctx
);
3987 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
3989 struct pet_scop
*scop_i
;
3991 if (scop
->n_stmt
== 0 && skip_declarations
&&
3992 child
->getStmtClass() == Stmt::DeclStmtClass
)
3995 scop_i
= extract(child
);
3996 if (scop
->n_stmt
!= 0 && partial
) {
3997 pet_scop_free(scop_i
);
4001 pet_skip_info_seq_init(&skip
, ctx
, scop
, scop_i
);
4002 pet_skip_info_seq_extract(&skip
, int_size
, &n_stmt
, &n_test
);
4003 if (pet_skip_info_has_skip(&skip
))
4004 scop_i
= pet_scop_prefix(scop_i
, 0);
4005 if (scop_i
&& child
->getStmtClass() == Stmt::DeclStmtClass
) {
4007 kills
.insert(extract_kill(scop_i
));
4009 scop_i
= mark_exposed(scop_i
);
4011 scop_i
= pet_scop_prefix(scop_i
, j
);
4012 if (options
->autodetect
) {
4014 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4016 partial_range
= true;
4017 if (scop
->n_stmt
!= 0 && !scop_i
)
4020 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4023 scop
= pet_skip_info_seq_add(&skip
, scop
, j
);
4025 if (partial
|| !scop
)
4029 for (it
= kills
.begin(); it
!= kills
.end(); ++it
) {
4031 scop_j
= pet_scop_from_pet_stmt(ctx
, *it
);
4032 scop_j
= pet_scop_prefix(scop_j
, j
);
4033 scop
= pet_scop_add_seq(ctx
, scop
, scop_j
);
4036 if (scop
&& partial_range
) {
4037 if (scop
->n_stmt
== 0 || kills
.size() != 0) {
4038 pet_scop_free(scop
);
4047 /* Check if the scop marked by the user is exactly this Stmt
4048 * or part of this Stmt.
4049 * If so, return a pet_scop corresponding to the marked region.
4050 * Otherwise, return NULL.
4052 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
4054 SourceManager
&SM
= PP
.getSourceManager();
4055 unsigned start_off
, end_off
;
4057 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
4058 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
4060 if (start_off
> loc
.end
)
4062 if (end_off
< loc
.start
)
4064 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
4065 return extract(stmt
);
4069 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
4070 Stmt
*child
= *start
;
4073 start_off
= getExpansionOffset(SM
, child
->getLocStart());
4074 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
4075 if (start_off
< loc
.start
&& end_off
>= loc
.end
)
4077 if (start_off
>= loc
.start
)
4082 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
4084 start_off
= SM
.getFileOffset(child
->getLocStart());
4085 if (start_off
>= loc
.end
)
4089 return extract(StmtRange(start
, end
), false, false);
4092 /* Set the size of index "pos" of "array" to "size".
4093 * In particular, add a constraint of the form
4097 * to array->extent and a constraint of the form
4101 * to array->context.
4103 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
4104 __isl_take isl_pw_aff
*size
)
4114 valid
= isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
)));
4115 array
->context
= isl_set_intersect(array
->context
, valid
);
4117 dim
= isl_set_get_space(array
->extent
);
4118 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
4119 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
4120 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
4121 index
= isl_pw_aff_alloc(univ
, aff
);
4123 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
4124 isl_set_dim(array
->extent
, isl_dim_set
));
4125 id
= isl_set_get_tuple_id(array
->extent
);
4126 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
4127 bound
= isl_pw_aff_lt_set(index
, size
);
4129 array
->extent
= isl_set_intersect(array
->extent
, bound
);
4131 if (!array
->context
|| !array
->extent
)
4136 pet_array_free(array
);
4140 /* Figure out the size of the array at position "pos" and all
4141 * subsequent positions from "type" and update "array" accordingly.
4143 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
4144 const Type
*type
, int pos
)
4146 const ArrayType
*atype
;
4152 if (type
->isPointerType()) {
4153 type
= type
->getPointeeType().getTypePtr();
4154 return set_upper_bounds(array
, type
, pos
+ 1);
4156 if (!type
->isArrayType())
4159 type
= type
->getCanonicalTypeInternal().getTypePtr();
4160 atype
= cast
<ArrayType
>(type
);
4162 if (type
->isConstantArrayType()) {
4163 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
4164 size
= extract_affine(ca
->getSize());
4165 array
= update_size(array
, pos
, size
);
4166 } else if (type
->isVariableArrayType()) {
4167 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
4168 size
= extract_affine(vla
->getSizeExpr());
4169 array
= update_size(array
, pos
, size
);
4172 type
= atype
->getElementType().getTypePtr();
4174 return set_upper_bounds(array
, type
, pos
+ 1);
4177 /* Is "T" the type of a variable length array with static size?
4179 static bool is_vla_with_static_size(QualType T
)
4181 const VariableArrayType
*vlatype
;
4183 if (!T
->isVariableArrayType())
4185 vlatype
= cast
<VariableArrayType
>(T
);
4186 return vlatype
->getSizeModifier() == VariableArrayType::Static
;
4189 /* Return the type of "decl" as an array.
4191 * In particular, if "decl" is a parameter declaration that
4192 * is a variable length array with a static size, then
4193 * return the original type (i.e., the variable length array).
4194 * Otherwise, return the type of decl.
4196 static QualType
get_array_type(ValueDecl
*decl
)
4201 parm
= dyn_cast
<ParmVarDecl
>(decl
);
4203 return decl
->getType();
4205 T
= parm
->getOriginalType();
4206 if (!is_vla_with_static_size(T
))
4207 return decl
->getType();
4211 /* Does "decl" have definition that we can keep track of in a pet_type?
4213 static bool has_printable_definition(RecordDecl
*decl
)
4215 if (!decl
->getDeclName())
4217 return decl
->getLexicalDeclContext() == decl
->getDeclContext();
4220 /* Construct and return a pet_array corresponding to the variable "decl".
4221 * In particular, initialize array->extent to
4223 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4225 * and then call set_upper_bounds to set the upper bounds on the indices
4226 * based on the type of the variable.
4228 * If the base type is that of a record with a top-level definition and
4229 * if "types" is not null, then the RecordDecl corresponding to the type
4230 * is added to "types".
4232 * If the base type is that of a record with no top-level definition,
4233 * then we replace it by "<subfield>".
4235 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
,
4236 lex_recorddecl_set
*types
)
4238 struct pet_array
*array
;
4239 QualType qt
= get_array_type(decl
);
4240 const Type
*type
= qt
.getTypePtr();
4241 int depth
= array_depth(type
);
4242 QualType base
= pet_clang_base_type(qt
);
4247 array
= isl_calloc_type(ctx
, struct pet_array
);
4251 id
= create_decl_id(ctx
, decl
);
4252 dim
= isl_space_set_alloc(ctx
, 0, depth
);
4253 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
4255 array
->extent
= isl_set_nat_universe(dim
);
4257 dim
= isl_space_params_alloc(ctx
, 0);
4258 array
->context
= isl_set_universe(dim
);
4260 array
= set_upper_bounds(array
, type
, 0);
4264 name
= base
.getAsString();
4266 if (types
&& base
->isRecordType()) {
4267 RecordDecl
*decl
= pet_clang_record_decl(base
);
4268 if (has_printable_definition(decl
))
4269 types
->insert(decl
);
4271 name
= "<subfield>";
4274 array
->element_type
= strdup(name
.c_str());
4275 array
->element_is_record
= base
->isRecordType();
4276 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
4281 /* Construct and return a pet_array corresponding to the sequence
4282 * of declarations "decls".
4283 * If the sequence contains a single declaration, then it corresponds
4284 * to a simple array access. Otherwise, it corresponds to a member access,
4285 * with the declaration for the substructure following that of the containing
4286 * structure in the sequence of declarations.
4287 * We start with the outermost substructure and then combine it with
4288 * information from the inner structures.
4290 * Additionally, keep track of all required types in "types".
4292 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
,
4293 vector
<ValueDecl
*> decls
, lex_recorddecl_set
*types
)
4295 struct pet_array
*array
;
4296 vector
<ValueDecl
*>::iterator it
;
4300 array
= extract_array(ctx
, *it
, types
);
4302 for (++it
; it
!= decls
.end(); ++it
) {
4303 struct pet_array
*parent
;
4304 const char *base_name
, *field_name
;
4308 array
= extract_array(ctx
, *it
, types
);
4310 return pet_array_free(parent
);
4312 base_name
= isl_set_get_tuple_name(parent
->extent
);
4313 field_name
= isl_set_get_tuple_name(array
->extent
);
4314 product_name
= member_access_name(ctx
, base_name
, field_name
);
4316 array
->extent
= isl_set_product(isl_set_copy(parent
->extent
),
4319 array
->extent
= isl_set_set_tuple_name(array
->extent
,
4321 array
->context
= isl_set_intersect(array
->context
,
4322 isl_set_copy(parent
->context
));
4324 pet_array_free(parent
);
4327 if (!array
->extent
|| !array
->context
|| !product_name
)
4328 return pet_array_free(array
);
4334 /* Add a pet_type corresponding to "decl" to "scop, provided
4335 * it is a member of "types" and it has not been added before
4336 * (i.e., it is not a member of "types_done".
4338 * Since we want the user to be able to print the types
4339 * in the order in which they appear in the scop, we need to
4340 * make sure that types of fields in a structure appear before
4341 * that structure. We therefore call ourselves recursively
4342 * on the types of all record subfields.
4344 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
4345 RecordDecl
*decl
, Preprocessor
&PP
, lex_recorddecl_set
&types
,
4346 lex_recorddecl_set
&types_done
)
4349 llvm::raw_string_ostream
S(s
);
4350 RecordDecl::field_iterator it
;
4352 if (types
.find(decl
) == types
.end())
4354 if (types_done
.find(decl
) != types_done
.end())
4357 for (it
= decl
->field_begin(); it
!= decl
->field_end(); ++it
) {
4359 QualType type
= it
->getType();
4361 if (!type
->isRecordType())
4363 record
= pet_clang_record_decl(type
);
4364 scop
= add_type(ctx
, scop
, record
, PP
, types
, types_done
);
4367 if (strlen(decl
->getName().str().c_str()) == 0)
4370 decl
->print(S
, PrintingPolicy(PP
.getLangOpts()));
4373 scop
->types
[scop
->n_type
] = pet_type_alloc(ctx
,
4374 decl
->getName().str().c_str(), s
.c_str());
4375 if (!scop
->types
[scop
->n_type
])
4376 return pet_scop_free(scop
);
4378 types_done
.insert(decl
);
4385 /* Construct a list of pet_arrays, one for each array (or scalar)
4386 * accessed inside "scop", add this list to "scop" and return the result.
4388 * The context of "scop" is updated with the intersection of
4389 * the contexts of all arrays, i.e., constraints on the parameters
4390 * that ensure that the arrays have a valid (non-negative) size.
4392 * If the any of the extracted arrays refers to a member access,
4393 * then also add the required types to "scop".
4395 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
4398 array_desc_set arrays
;
4399 array_desc_set::iterator it
;
4400 lex_recorddecl_set types
;
4401 lex_recorddecl_set types_done
;
4402 lex_recorddecl_set::iterator types_it
;
4404 struct pet_array
**scop_arrays
;
4409 pet_scop_collect_arrays(scop
, arrays
);
4410 if (arrays
.size() == 0)
4413 n_array
= scop
->n_array
;
4415 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
4416 n_array
+ arrays
.size());
4419 scop
->arrays
= scop_arrays
;
4421 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
4422 struct pet_array
*array
;
4423 array
= extract_array(ctx
, *it
, &types
);
4424 scop
->arrays
[n_array
+ i
] = array
;
4425 if (!scop
->arrays
[n_array
+ i
])
4428 scop
->context
= isl_set_intersect(scop
->context
,
4429 isl_set_copy(array
->context
));
4434 if (types
.size() == 0)
4437 scop
->types
= isl_alloc_array(ctx
, struct pet_type
*, types
.size());
4441 for (types_it
= types
.begin(); types_it
!= types
.end(); ++types_it
)
4442 scop
= add_type(ctx
, scop
, *types_it
, PP
, types
, types_done
);
4446 pet_scop_free(scop
);
4450 /* Bound all parameters in scop->context to the possible values
4451 * of the corresponding C variable.
4453 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
4460 n
= isl_set_dim(scop
->context
, isl_dim_param
);
4461 for (int i
= 0; i
< n
; ++i
) {
4465 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
4466 if (pet_nested_in_id(id
)) {
4468 isl_die(isl_set_get_ctx(scop
->context
),
4470 "unresolved nested parameter", goto error
);
4472 decl
= (ValueDecl
*) isl_id_get_user(id
);
4475 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
4483 pet_scop_free(scop
);
4487 /* Construct a pet_scop from the given function.
4489 * If the scop was delimited by scop and endscop pragmas, then we override
4490 * the file offsets by those derived from the pragmas.
4492 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
4497 stmt
= fd
->getBody();
4499 if (options
->autodetect
)
4500 scop
= extract(stmt
, true);
4503 scop
= pet_scop_update_start_end(scop
, loc
.start
, loc
.end
);
4505 scop
= pet_scop_detect_parameter_accesses(scop
);
4506 scop
= scan_arrays(scop
);
4507 scop
= add_parameter_bounds(scop
);
4508 scop
= pet_scop_gist(scop
, value_bounds
);