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 IntegerLiteral "expr".
493 * If the value of "expr" is "v", then the returned expression
498 __isl_give isl_pw_aff
*PetScan::extract_affine(IntegerLiteral
*expr
)
500 isl_space
*space
= isl_space_set_alloc(ctx
, 0, 0);
501 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(space
));
502 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
503 isl_set
*dom
= isl_set_universe(space
);
506 v
= extract_int(expr
);
507 aff
= isl_aff_add_constant_val(aff
, v
);
509 return isl_pw_aff_alloc(dom
, aff
);
512 /* Extract an affine expression from the APInt "val", which is assumed
513 * to be non-negative.
514 * If the value of "val" is "v", then the returned expression
519 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
521 isl_space
*space
= isl_space_set_alloc(ctx
, 0, 0);
522 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(space
));
523 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
524 isl_set
*dom
= isl_set_universe(space
);
527 v
= extract_unsigned(ctx
, val
);
528 aff
= isl_aff_add_constant_val(aff
, v
);
530 return isl_pw_aff_alloc(dom
, aff
);
533 __isl_give isl_pw_aff
*PetScan::extract_affine(ImplicitCastExpr
*expr
)
535 return extract_affine(expr
->getSubExpr());
538 /* Return the number of bits needed to represent the type "qt",
539 * if it is an integer type. Otherwise return 0.
540 * If qt is signed then return the opposite of the number of bits.
542 static int get_type_size(QualType qt
, ASTContext
&ast_context
)
546 if (!qt
->isIntegerType())
549 size
= ast_context
.getIntWidth(qt
);
550 if (!qt
->isUnsignedIntegerType())
556 /* Return the number of bits needed to represent the type of "decl",
557 * if it is an integer type. Otherwise return 0.
558 * If qt is signed then return the opposite of the number of bits.
560 static int get_type_size(ValueDecl
*decl
)
562 return get_type_size(decl
->getType(), decl
->getASTContext());
565 /* Bound parameter "pos" of "set" to the possible values of "decl".
567 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
568 unsigned pos
, ValueDecl
*decl
)
574 ctx
= isl_set_get_ctx(set
);
575 type_size
= get_type_size(decl
);
577 isl_die(ctx
, isl_error_invalid
, "not an integer type",
578 return isl_set_free(set
));
580 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
581 bound
= isl_val_int_from_ui(ctx
, type_size
);
582 bound
= isl_val_2exp(bound
);
583 bound
= isl_val_sub_ui(bound
, 1);
584 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
, bound
);
586 bound
= isl_val_int_from_ui(ctx
, -type_size
- 1);
587 bound
= isl_val_2exp(bound
);
588 bound
= isl_val_sub_ui(bound
, 1);
589 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
,
590 isl_val_copy(bound
));
591 bound
= isl_val_neg(bound
);
592 bound
= isl_val_sub_ui(bound
, 1);
593 set
= isl_set_lower_bound_val(set
, isl_dim_param
, pos
, bound
);
599 /* Extract an affine expression from the DeclRefExpr "expr".
601 * If the variable has been assigned a value, then we check whether
602 * we know what (affine) value was assigned.
603 * If so, we return this value. Otherwise we convert "expr"
604 * to an extra parameter (provided nesting_enabled is set).
606 * Otherwise, we simply return an expression that is equal
607 * to a parameter corresponding to the referenced variable.
609 __isl_give isl_pw_aff
*PetScan::extract_affine(DeclRefExpr
*expr
)
611 ValueDecl
*decl
= expr
->getDecl();
612 const Type
*type
= decl
->getType().getTypePtr();
618 if (!type
->isIntegerType()) {
623 if (assigned_value
.find(decl
) != assigned_value
.end()) {
624 if (assigned_value
[decl
])
625 return isl_pw_aff_copy(assigned_value
[decl
]);
627 return nested_access(expr
);
630 id
= create_decl_id(ctx
, decl
);
631 space
= isl_space_set_alloc(ctx
, 1, 0);
633 space
= isl_space_set_dim_id(space
, isl_dim_param
, 0, id
);
635 dom
= isl_set_universe(isl_space_copy(space
));
636 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
637 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
639 return isl_pw_aff_alloc(dom
, aff
);
642 /* Extract an affine expression from an integer division operation.
643 * In particular, if "expr" is lhs/rhs, then return
645 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
647 * The second argument (rhs) is required to be a (positive) integer constant.
649 __isl_give isl_pw_aff
*PetScan::extract_affine_div(BinaryOperator
*expr
)
652 isl_pw_aff
*rhs
, *lhs
;
654 rhs
= extract_affine(expr
->getRHS());
655 is_cst
= isl_pw_aff_is_cst(rhs
);
656 if (is_cst
< 0 || !is_cst
) {
657 isl_pw_aff_free(rhs
);
663 lhs
= extract_affine(expr
->getLHS());
665 return isl_pw_aff_tdiv_q(lhs
, rhs
);
668 /* Extract an affine expression from a modulo operation.
669 * In particular, if "expr" is lhs/rhs, then return
671 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
673 * The second argument (rhs) is required to be a (positive) integer constant.
675 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
678 isl_pw_aff
*rhs
, *lhs
;
680 rhs
= extract_affine(expr
->getRHS());
681 is_cst
= isl_pw_aff_is_cst(rhs
);
682 if (is_cst
< 0 || !is_cst
) {
683 isl_pw_aff_free(rhs
);
689 lhs
= extract_affine(expr
->getLHS());
691 return isl_pw_aff_tdiv_r(lhs
, rhs
);
694 /* Extract an affine expression from a multiplication operation.
695 * This is only allowed if at least one of the two arguments
696 * is a (piecewise) constant.
698 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
703 lhs
= extract_affine(expr
->getLHS());
704 rhs
= extract_affine(expr
->getRHS());
706 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
707 isl_pw_aff_free(lhs
);
708 isl_pw_aff_free(rhs
);
713 return isl_pw_aff_mul(lhs
, rhs
);
716 /* Extract an affine expression from an addition or subtraction operation.
718 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
723 lhs
= extract_affine(expr
->getLHS());
724 rhs
= extract_affine(expr
->getRHS());
726 switch (expr
->getOpcode()) {
728 return isl_pw_aff_add(lhs
, rhs
);
730 return isl_pw_aff_sub(lhs
, rhs
);
732 isl_pw_aff_free(lhs
);
733 isl_pw_aff_free(rhs
);
743 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
749 ctx
= isl_pw_aff_get_ctx(pwaff
);
750 mod
= isl_val_int_from_ui(ctx
, width
);
751 mod
= isl_val_2exp(mod
);
753 pwaff
= isl_pw_aff_mod_val(pwaff
, mod
);
758 /* Limit the domain of "pwaff" to those elements where the function
761 * 2^{width-1} <= pwaff < 2^{width-1}
763 static __isl_give isl_pw_aff
*avoid_overflow(__isl_take isl_pw_aff
*pwaff
,
768 isl_space
*space
= isl_pw_aff_get_domain_space(pwaff
);
769 isl_local_space
*ls
= isl_local_space_from_space(space
);
774 ctx
= isl_pw_aff_get_ctx(pwaff
);
775 v
= isl_val_int_from_ui(ctx
, width
- 1);
778 bound
= isl_aff_zero_on_domain(ls
);
779 bound
= isl_aff_add_constant_val(bound
, v
);
780 b
= isl_pw_aff_from_aff(bound
);
782 dom
= isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff
), isl_pw_aff_copy(b
));
783 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
785 b
= isl_pw_aff_neg(b
);
786 dom
= isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff
), b
);
787 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
792 /* Handle potential overflows on signed computations.
794 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
795 * the we adjust the domain of "pa" to avoid overflows.
797 __isl_give isl_pw_aff
*PetScan::signed_overflow(__isl_take isl_pw_aff
*pa
,
800 if (options
->signed_overflow
== PET_OVERFLOW_AVOID
)
801 pa
= avoid_overflow(pa
, width
);
806 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
808 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
809 __isl_take isl_set
*dom
)
812 pa
= isl_set_indicator_function(set
);
813 pa
= isl_pw_aff_intersect_domain(pa
, isl_set_coalesce(dom
));
817 /* Extract an affine expression from some binary operations.
818 * If the result of the expression is unsigned, then we wrap it
819 * based on the size of the type. Otherwise, we ensure that
820 * no overflow occurs.
822 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
827 switch (expr
->getOpcode()) {
830 res
= extract_affine_add(expr
);
833 res
= extract_affine_div(expr
);
836 res
= extract_affine_mod(expr
);
839 res
= extract_affine_mul(expr
);
849 return extract_condition(expr
);
855 width
= ast_context
.getIntWidth(expr
->getType());
856 if (expr
->getType()->isUnsignedIntegerType())
857 res
= wrap(res
, width
);
859 res
= signed_overflow(res
, width
);
864 /* Extract an affine expression from a negation operation.
866 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
868 if (expr
->getOpcode() == UO_Minus
)
869 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
870 if (expr
->getOpcode() == UO_LNot
)
871 return extract_condition(expr
);
877 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
879 return extract_affine(expr
->getSubExpr());
882 /* Extract an affine expression from some special function calls.
883 * In particular, we handle "min", "max", "ceild", "floord",
884 * "intMod", "intFloor" and "intCeil".
885 * In case of the latter five, the second argument needs to be
886 * a (positive) integer constant.
888 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
892 isl_pw_aff
*aff1
, *aff2
;
894 fd
= expr
->getDirectCallee();
900 name
= fd
->getDeclName().getAsString();
901 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
902 !(expr
->getNumArgs() == 2 && name
== "max") &&
903 !(expr
->getNumArgs() == 2 && name
== "intMod") &&
904 !(expr
->getNumArgs() == 2 && name
== "intFloor") &&
905 !(expr
->getNumArgs() == 2 && name
== "intCeil") &&
906 !(expr
->getNumArgs() == 2 && name
== "floord") &&
907 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
912 if (name
== "min" || name
== "max") {
913 aff1
= extract_affine(expr
->getArg(0));
914 aff2
= extract_affine(expr
->getArg(1));
917 aff1
= isl_pw_aff_min(aff1
, aff2
);
919 aff1
= isl_pw_aff_max(aff1
, aff2
);
920 } else if (name
== "intMod") {
922 Expr
*arg2
= expr
->getArg(1);
924 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
928 aff1
= extract_affine(expr
->getArg(0));
929 v
= extract_int(cast
<IntegerLiteral
>(arg2
));
930 aff1
= isl_pw_aff_mod_val(aff1
, v
);
931 } else if (name
== "floord" || name
== "ceild" ||
932 name
== "intFloor" || name
== "intCeil") {
934 Expr
*arg2
= expr
->getArg(1);
936 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
940 aff1
= extract_affine(expr
->getArg(0));
941 v
= extract_int(cast
<IntegerLiteral
>(arg2
));
942 aff1
= isl_pw_aff_scale_down_val(aff1
, v
);
943 if (name
== "floord" || name
== "intFloor")
944 aff1
= isl_pw_aff_floor(aff1
);
946 aff1
= isl_pw_aff_ceil(aff1
);
955 /* This method is called when we come across an access that is
956 * nested in what is supposed to be an affine expression.
957 * If nesting is allowed, we return a new parameter that corresponds
958 * to this nested access. Otherwise, we simply complain.
960 * Note that we currently don't allow nested accesses themselves
961 * to contain any nested accesses, so we check if we can extract
962 * the access without any nesting and complain if we can't.
964 * The new parameter is resolved in resolve_nested.
966 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
972 isl_multi_pw_aff
*index
;
974 if (!nesting_enabled
) {
979 allow_nested
= false;
980 index
= extract_index(expr
);
986 isl_multi_pw_aff_free(index
);
988 id
= pet_nested_clang_expr(ctx
, expr
);
989 space
= isl_space_set_alloc(ctx
, 1, 0);
991 space
= isl_space_set_dim_id(space
, isl_dim_param
, 0, id
);
993 dom
= isl_set_universe(isl_space_copy(space
));
994 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
995 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
997 return isl_pw_aff_alloc(dom
, aff
);
1000 /* Affine expressions are not supposed to contain array accesses,
1001 * but if nesting is allowed, we return a parameter corresponding
1002 * to the array access.
1004 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
1006 return nested_access(expr
);
1009 /* Affine expressions are not supposed to contain member accesses,
1010 * but if nesting is allowed, we return a parameter corresponding
1011 * to the member access.
1013 __isl_give isl_pw_aff
*PetScan::extract_affine(MemberExpr
*expr
)
1015 return nested_access(expr
);
1018 /* Extract an affine expression from a conditional operation.
1020 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
1022 isl_pw_aff
*cond
, *lhs
, *rhs
;
1024 cond
= extract_condition(expr
->getCond());
1025 lhs
= extract_affine(expr
->getTrueExpr());
1026 rhs
= extract_affine(expr
->getFalseExpr());
1028 return isl_pw_aff_cond(cond
, lhs
, rhs
);
1031 /* Extract an affine expression, if possible, from "expr".
1032 * Otherwise return NULL.
1034 * The result has an anonymous zero-dimensional domain.
1036 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
1038 switch (expr
->getStmtClass()) {
1039 case Stmt::ImplicitCastExprClass
:
1040 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
1041 case Stmt::IntegerLiteralClass
:
1042 return extract_affine(cast
<IntegerLiteral
>(expr
));
1043 case Stmt::DeclRefExprClass
:
1044 return extract_affine(cast
<DeclRefExpr
>(expr
));
1045 case Stmt::BinaryOperatorClass
:
1046 return extract_affine(cast
<BinaryOperator
>(expr
));
1047 case Stmt::UnaryOperatorClass
:
1048 return extract_affine(cast
<UnaryOperator
>(expr
));
1049 case Stmt::ParenExprClass
:
1050 return extract_affine(cast
<ParenExpr
>(expr
));
1051 case Stmt::CallExprClass
:
1052 return extract_affine(cast
<CallExpr
>(expr
));
1053 case Stmt::ArraySubscriptExprClass
:
1054 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
1055 case Stmt::MemberExprClass
:
1056 return extract_affine(cast
<MemberExpr
>(expr
));
1057 case Stmt::ConditionalOperatorClass
:
1058 return extract_affine(cast
<ConditionalOperator
>(expr
));
1065 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ImplicitCastExpr
*expr
)
1067 return extract_index(expr
->getSubExpr());
1070 /* Return the depth of an array of the given type.
1072 static int array_depth(const Type
*type
)
1074 if (type
->isPointerType())
1075 return 1 + array_depth(type
->getPointeeType().getTypePtr());
1076 if (type
->isArrayType()) {
1077 const ArrayType
*atype
;
1078 type
= type
->getCanonicalTypeInternal().getTypePtr();
1079 atype
= cast
<ArrayType
>(type
);
1080 return 1 + array_depth(atype
->getElementType().getTypePtr());
1085 /* Return the depth of the array accessed by the index expression "index".
1086 * If "index" is an affine expression, i.e., if it does not access
1087 * any array, then return 1.
1088 * If "index" represent a member access, i.e., if its range is a wrapped
1089 * relation, then return the sum of the depth of the array of structures
1090 * and that of the member inside the structure.
1092 static int extract_depth(__isl_keep isl_multi_pw_aff
*index
)
1100 if (isl_multi_pw_aff_range_is_wrapping(index
)) {
1101 int domain_depth
, range_depth
;
1102 isl_multi_pw_aff
*domain
, *range
;
1104 domain
= isl_multi_pw_aff_copy(index
);
1105 domain
= isl_multi_pw_aff_range_factor_domain(domain
);
1106 domain_depth
= extract_depth(domain
);
1107 isl_multi_pw_aff_free(domain
);
1108 range
= isl_multi_pw_aff_copy(index
);
1109 range
= isl_multi_pw_aff_range_factor_range(range
);
1110 range_depth
= extract_depth(range
);
1111 isl_multi_pw_aff_free(range
);
1113 return domain_depth
+ range_depth
;
1116 if (!isl_multi_pw_aff_has_tuple_id(index
, isl_dim_out
))
1119 id
= isl_multi_pw_aff_get_tuple_id(index
, isl_dim_out
);
1122 decl
= (ValueDecl
*) isl_id_get_user(id
);
1125 return array_depth(decl
->getType().getTypePtr());
1128 /* Extract an index expression from a reference to a variable.
1129 * If the variable has name "A", then the returned index expression
1134 __isl_give isl_multi_pw_aff
*PetScan::extract_index(DeclRefExpr
*expr
)
1136 return extract_index(expr
->getDecl());
1139 /* Extract an index expression from a variable.
1140 * If the variable has name "A", then the returned index expression
1145 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ValueDecl
*decl
)
1147 isl_id
*id
= create_decl_id(ctx
, decl
);
1148 isl_space
*space
= isl_space_alloc(ctx
, 0, 0, 0);
1150 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
1152 return isl_multi_pw_aff_zero(space
);
1155 /* Extract an index expression from an integer contant.
1156 * If the value of the constant is "v", then the returned access relation
1161 __isl_give isl_multi_pw_aff
*PetScan::extract_index(IntegerLiteral
*expr
)
1163 isl_multi_pw_aff
*mpa
;
1165 mpa
= isl_multi_pw_aff_from_pw_aff(extract_affine(expr
));
1169 /* Try and extract an index expression from the given Expr.
1170 * Return NULL if it doesn't work out.
1172 __isl_give isl_multi_pw_aff
*PetScan::extract_index(Expr
*expr
)
1174 switch (expr
->getStmtClass()) {
1175 case Stmt::ImplicitCastExprClass
:
1176 return extract_index(cast
<ImplicitCastExpr
>(expr
));
1177 case Stmt::DeclRefExprClass
:
1178 return extract_index(cast
<DeclRefExpr
>(expr
));
1179 case Stmt::ArraySubscriptExprClass
:
1180 return extract_index(cast
<ArraySubscriptExpr
>(expr
));
1181 case Stmt::IntegerLiteralClass
:
1182 return extract_index(cast
<IntegerLiteral
>(expr
));
1183 case Stmt::MemberExprClass
:
1184 return extract_index(cast
<MemberExpr
>(expr
));
1191 /* Given a partial index expression "base" and an extra index "index",
1192 * append the extra index to "base" and return the result.
1193 * Additionally, add the constraints that the extra index is non-negative.
1194 * If "index" represent a member access, i.e., if its range is a wrapped
1195 * relation, then we recursively extend the range of this nested relation.
1197 * The inputs "base" and "index", as well as the result, all have
1198 * an anonymous zero-dimensional domain.
1200 static __isl_give isl_multi_pw_aff
*subscript(__isl_take isl_multi_pw_aff
*base
,
1201 __isl_take isl_pw_aff
*index
)
1205 isl_multi_pw_aff
*access
;
1208 member_access
= isl_multi_pw_aff_range_is_wrapping(base
);
1209 if (member_access
< 0)
1211 if (member_access
) {
1212 isl_multi_pw_aff
*domain
, *range
;
1215 id
= isl_multi_pw_aff_get_tuple_id(base
, isl_dim_out
);
1216 domain
= isl_multi_pw_aff_copy(base
);
1217 domain
= isl_multi_pw_aff_range_factor_domain(domain
);
1218 range
= isl_multi_pw_aff_range_factor_range(base
);
1219 range
= subscript(range
, index
);
1220 access
= isl_multi_pw_aff_range_product(domain
, range
);
1221 access
= isl_multi_pw_aff_set_tuple_id(access
, isl_dim_out
, id
);
1225 id
= isl_multi_pw_aff_get_tuple_id(base
, isl_dim_set
);
1226 domain
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(index
));
1227 index
= isl_pw_aff_intersect_domain(index
, domain
);
1228 access
= isl_multi_pw_aff_from_pw_aff(index
);
1229 access
= isl_multi_pw_aff_flat_range_product(base
, access
);
1230 access
= isl_multi_pw_aff_set_tuple_id(access
, isl_dim_set
, id
);
1234 isl_multi_pw_aff_free(base
);
1235 isl_pw_aff_free(index
);
1239 /* Extract an index expression from the given array subscript expression.
1240 * If nesting is allowed in general, then we turn it on while
1241 * examining the index expression.
1243 * We first extract an index expression from the base.
1244 * This will result in an index expression with a range that corresponds
1245 * to the earlier indices.
1246 * We then extract the current index, restrict its domain
1247 * to those values that result in a non-negative index and
1248 * append the index to the base index expression.
1250 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ArraySubscriptExpr
*expr
)
1252 Expr
*base
= expr
->getBase();
1253 Expr
*idx
= expr
->getIdx();
1255 isl_multi_pw_aff
*base_access
;
1256 isl_multi_pw_aff
*access
;
1257 bool save_nesting
= nesting_enabled
;
1259 nesting_enabled
= allow_nested
;
1261 base_access
= extract_index(base
);
1262 index
= extract_affine(idx
);
1264 nesting_enabled
= save_nesting
;
1266 access
= subscript(base_access
, index
);
1271 /* Construct a name for a member access by concatenating the name
1272 * of the array of structures and the member, separated by an underscore.
1274 * The caller is responsible for freeing the result.
1276 static char *member_access_name(isl_ctx
*ctx
, const char *base
,
1282 len
= strlen(base
) + 1 + strlen(field
);
1283 name
= isl_alloc_array(ctx
, char, len
+ 1);
1286 snprintf(name
, len
+ 1, "%s_%s", base
, field
);
1291 /* Given an index expression "base" for an element of an array of structures
1292 * and an expression "field" for the field member being accessed, construct
1293 * an index expression for an access to that member of the given structure.
1294 * In particular, take the range product of "base" and "field" and
1295 * attach a name to the result.
1297 static __isl_give isl_multi_pw_aff
*member(__isl_take isl_multi_pw_aff
*base
,
1298 __isl_take isl_multi_pw_aff
*field
)
1301 isl_multi_pw_aff
*access
;
1302 const char *base_name
, *field_name
;
1305 ctx
= isl_multi_pw_aff_get_ctx(base
);
1307 base_name
= isl_multi_pw_aff_get_tuple_name(base
, isl_dim_out
);
1308 field_name
= isl_multi_pw_aff_get_tuple_name(field
, isl_dim_out
);
1309 name
= member_access_name(ctx
, base_name
, field_name
);
1311 access
= isl_multi_pw_aff_range_product(base
, field
);
1313 access
= isl_multi_pw_aff_set_tuple_name(access
, isl_dim_out
, name
);
1319 /* Extract an index expression from a member expression.
1321 * If the base access (to the structure containing the member)
1326 * and the member is called "f", then the member access is of
1329 * [] -> A_f[A[..] -> f[]]
1331 * If the member access is to an anonymous struct, then simply return
1335 * If the member access in the source code is of the form
1339 * then it is treated as
1343 __isl_give isl_multi_pw_aff
*PetScan::extract_index(MemberExpr
*expr
)
1345 Expr
*base
= expr
->getBase();
1346 FieldDecl
*field
= cast
<FieldDecl
>(expr
->getMemberDecl());
1347 isl_multi_pw_aff
*base_access
, *field_access
;
1351 base_access
= extract_index(base
);
1353 if (expr
->isArrow()) {
1354 isl_space
*space
= isl_space_set_alloc(ctx
, 0, 0);
1355 isl_local_space
*ls
= isl_local_space_from_space(space
);
1356 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
1357 isl_pw_aff
*index
= isl_pw_aff_from_aff(aff
);
1358 base_access
= subscript(base_access
, index
);
1361 if (field
->isAnonymousStructOrUnion())
1364 id
= create_decl_id(ctx
, field
);
1365 space
= isl_multi_pw_aff_get_domain_space(base_access
);
1366 space
= isl_space_from_domain(space
);
1367 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
1368 field_access
= isl_multi_pw_aff_zero(space
);
1370 return member(base_access
, field_access
);
1373 /* Check if "expr" calls function "minmax" with two arguments and if so
1374 * make lhs and rhs refer to these two arguments.
1376 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
1382 if (expr
->getStmtClass() != Stmt::CallExprClass
)
1385 call
= cast
<CallExpr
>(expr
);
1386 fd
= call
->getDirectCallee();
1390 if (call
->getNumArgs() != 2)
1393 name
= fd
->getDeclName().getAsString();
1397 lhs
= call
->getArg(0);
1398 rhs
= call
->getArg(1);
1403 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1404 * lhs and rhs refer to the two arguments.
1406 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1408 return is_minmax(expr
, "min", lhs
, rhs
);
1411 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1412 * lhs and rhs refer to the two arguments.
1414 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1416 return is_minmax(expr
, "max", lhs
, rhs
);
1419 /* Extract an affine expressions representing the comparison "LHS op RHS"
1420 * "comp" is the original statement that "LHS op RHS" is derived from
1421 * and is used for diagnostics.
1423 * If the comparison is of the form
1427 * then the expression is constructed as the conjunction of
1432 * A similar optimization is performed for max(a,b) <= c.
1433 * We do this because that will lead to simpler representations
1434 * of the expression.
1435 * If isl is ever enhanced to explicitly deal with min and max expressions,
1436 * this optimization can be removed.
1438 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
1439 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
1446 enum pet_op_type type
;
1449 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
1451 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
1453 if (op
== BO_LT
|| op
== BO_LE
) {
1454 Expr
*expr1
, *expr2
;
1455 if (is_min(RHS
, expr1
, expr2
)) {
1456 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
1457 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
1458 return pet_and(lhs
, rhs
);
1460 if (is_max(LHS
, expr1
, expr2
)) {
1461 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
1462 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
1463 return pet_and(lhs
, rhs
);
1467 lhs
= extract_affine(LHS
);
1468 rhs
= extract_affine(RHS
);
1470 type
= BinaryOperatorKind2pet_op_type(op
);
1471 return pet_comparison(type
, lhs
, rhs
);
1474 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
1476 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1477 comp
->getRHS(), comp
);
1480 /* Extract an affine expression from a boolean expression.
1481 * In particular, return the expression "expr ? 1 : 0".
1482 * Return NULL if we are unable to extract an affine expression.
1484 * We first convert the clang::Expr to a pet_expr and
1485 * then extract an affine expression from that pet_expr.
1487 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
1494 isl_set
*u
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
1495 return indicator_function(u
, isl_set_copy(u
));
1498 pe
= extract_expr(expr
);
1499 pc
= convert_assignments(ctx
, assigned_value
);
1500 pc
= pet_context_set_allow_nested(pc
, nesting_enabled
);
1501 cond
= pet_expr_extract_affine_condition(pe
, pc
);
1502 if (isl_pw_aff_involves_nan(cond
))
1503 cond
= isl_pw_aff_free(cond
);
1504 pet_context_free(pc
);
1509 /* Construct a pet_expr representing a unary operator expression.
1511 __isl_give pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1514 enum pet_op_type op
;
1516 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1517 if (op
== pet_op_last
) {
1522 arg
= extract_expr(expr
->getSubExpr());
1524 if (expr
->isIncrementDecrementOp() &&
1525 pet_expr_get_type(arg
) == pet_expr_access
) {
1526 arg
= mark_write(arg
);
1527 arg
= pet_expr_access_set_read(arg
, 1);
1530 return pet_expr_new_unary(op
, arg
);
1533 /* Mark the given access pet_expr as a write.
1534 * If a scalar is being accessed, then mark its value
1535 * as unknown in assigned_value.
1537 __isl_give pet_expr
*PetScan::mark_write(__isl_take pet_expr
*access
)
1542 access
= pet_expr_access_set_write(access
, 1);
1543 access
= pet_expr_access_set_read(access
, 0);
1545 if (!access
|| !pet_expr_is_scalar_access(access
))
1548 id
= pet_expr_access_get_id(access
);
1549 decl
= (ValueDecl
*) isl_id_get_user(id
);
1550 clear_assignment(assigned_value
, decl
);
1556 /* Assign "rhs" to "lhs".
1558 * In particular, if "lhs" is a scalar variable, then mark
1559 * the variable as having been assigned. If, furthermore, "rhs"
1560 * is an affine expression, then keep track of this value in assigned_value
1561 * so that we can plug it in when we later come across the same variable.
1563 void PetScan::assign(__isl_keep pet_expr
*lhs
, Expr
*rhs
)
1571 if (!pet_expr_is_scalar_access(lhs
))
1574 id
= pet_expr_access_get_id(lhs
);
1575 decl
= (ValueDecl
*) isl_id_get_user(id
);
1578 pa
= try_extract_affine(rhs
);
1579 clear_assignment(assigned_value
, decl
);
1582 assigned_value
[decl
] = pa
;
1583 insert_expression(pa
);
1586 /* Construct a pet_expr representing a binary operator expression.
1588 * If the top level operator is an assignment and the LHS is an access,
1589 * then we mark that access as a write. If the operator is a compound
1590 * assignment, the access is marked as both a read and a write.
1592 * If "expr" assigns something to a scalar variable, then we mark
1593 * the variable as having been assigned. If, furthermore, the expression
1594 * is affine, then keep track of this value in assigned_value
1595 * so that we can plug it in when we later come across the same variable.
1597 __isl_give pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1600 pet_expr
*lhs
, *rhs
;
1601 enum pet_op_type op
;
1603 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1604 if (op
== pet_op_last
) {
1609 lhs
= extract_expr(expr
->getLHS());
1610 rhs
= extract_expr(expr
->getRHS());
1612 if (expr
->isAssignmentOp() &&
1613 pet_expr_get_type(lhs
) == pet_expr_access
) {
1614 lhs
= mark_write(lhs
);
1615 if (expr
->isCompoundAssignmentOp())
1616 lhs
= pet_expr_access_set_read(lhs
, 1);
1619 if (expr
->getOpcode() == BO_Assign
)
1620 assign(lhs
, expr
->getRHS());
1622 type_size
= get_type_size(expr
->getType(), ast_context
);
1623 return pet_expr_new_binary(type_size
, op
, lhs
, rhs
);
1626 /* Construct a pet_scop with a single statement killing the entire
1629 struct pet_scop
*PetScan::kill(Stmt
*stmt
, struct pet_array
*array
)
1633 isl_multi_pw_aff
*index
;
1639 access
= isl_map_from_range(isl_set_copy(array
->extent
));
1640 id
= isl_set_get_tuple_id(array
->extent
);
1641 space
= isl_space_alloc(ctx
, 0, 0, 0);
1642 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
1643 index
= isl_multi_pw_aff_zero(space
);
1644 expr
= pet_expr_kill_from_access_and_index(access
, index
);
1645 return extract(expr
, stmt
->getSourceRange(), false);
1648 /* Construct a pet_scop for a (single) variable declaration.
1650 * The scop contains the variable being declared (as an array)
1651 * and a statement killing the array.
1653 * If the variable is initialized in the AST, then the scop
1654 * also contains an assignment to the variable.
1656 struct pet_scop
*PetScan::extract(DeclStmt
*stmt
)
1661 pet_expr
*lhs
, *rhs
, *pe
;
1662 struct pet_scop
*scop_decl
, *scop
;
1663 struct pet_array
*array
;
1665 if (!stmt
->isSingleDecl()) {
1670 decl
= stmt
->getSingleDecl();
1671 vd
= cast
<VarDecl
>(decl
);
1673 array
= extract_array(ctx
, vd
, NULL
);
1675 array
->declared
= 1;
1676 scop_decl
= kill(stmt
, array
);
1677 scop_decl
= pet_scop_add_array(scop_decl
, array
);
1682 lhs
= extract_access_expr(vd
);
1683 rhs
= extract_expr(vd
->getInit());
1685 lhs
= mark_write(lhs
);
1686 assign(lhs
, vd
->getInit());
1688 type_size
= get_type_size(vd
->getType(), ast_context
);
1689 pe
= pet_expr_new_binary(type_size
, pet_op_assign
, lhs
, rhs
);
1690 scop
= extract(pe
, stmt
->getSourceRange(), false);
1692 scop_decl
= pet_scop_prefix(scop_decl
, 0);
1693 scop
= pet_scop_prefix(scop
, 1);
1695 scop
= pet_scop_add_seq(ctx
, scop_decl
, scop
);
1700 /* Construct a pet_expr representing a conditional operation.
1702 * We first try to extract the condition as an affine expression.
1703 * If that fails, we construct a pet_expr tree representing the condition.
1705 __isl_give pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1707 pet_expr
*cond
, *lhs
, *rhs
;
1710 pa
= try_extract_affine(expr
->getCond());
1712 isl_multi_pw_aff
*test
= isl_multi_pw_aff_from_pw_aff(pa
);
1713 cond
= pet_expr_from_index(test
);
1715 cond
= extract_expr(expr
->getCond());
1716 lhs
= extract_expr(expr
->getTrueExpr());
1717 rhs
= extract_expr(expr
->getFalseExpr());
1719 return pet_expr_new_ternary(cond
, lhs
, rhs
);
1722 __isl_give pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1724 return extract_expr(expr
->getSubExpr());
1727 /* Construct a pet_expr representing a floating point value.
1729 * If the floating point literal does not appear in a macro,
1730 * then we use the original representation in the source code
1731 * as the string representation. Otherwise, we use the pretty
1732 * printer to produce a string representation.
1734 __isl_give pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1738 const LangOptions
&LO
= PP
.getLangOpts();
1739 SourceLocation loc
= expr
->getLocation();
1741 if (!loc
.isMacroID()) {
1742 SourceManager
&SM
= PP
.getSourceManager();
1743 unsigned len
= Lexer::MeasureTokenLength(loc
, SM
, LO
);
1744 s
= string(SM
.getCharacterData(loc
), len
);
1746 llvm::raw_string_ostream
S(s
);
1747 expr
->printPretty(S
, 0, PrintingPolicy(LO
));
1750 d
= expr
->getValueAsApproximateDouble();
1751 return pet_expr_new_double(ctx
, d
, s
.c_str());
1754 /* Convert the index expression "index" into an access pet_expr of type "qt".
1756 __isl_give pet_expr
*PetScan::extract_access_expr(QualType qt
,
1757 __isl_take isl_multi_pw_aff
*index
)
1763 depth
= extract_depth(index
);
1764 type_size
= get_type_size(qt
, ast_context
);
1766 pe
= pet_expr_from_index_and_depth(type_size
, index
, depth
);
1771 /* Extract an index expression from "expr" and then convert it into
1772 * an access pet_expr.
1774 __isl_give pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1776 return extract_access_expr(expr
->getType(), extract_index(expr
));
1779 /* Extract an index expression from "decl" and then convert it into
1780 * an access pet_expr.
1782 __isl_give pet_expr
*PetScan::extract_access_expr(ValueDecl
*decl
)
1784 return extract_access_expr(decl
->getType(), extract_index(decl
));
1787 __isl_give pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1789 return extract_expr(expr
->getSubExpr());
1792 /* Extract an assume statement from the argument "expr"
1793 * of a __pencil_assume statement.
1795 __isl_give pet_expr
*PetScan::extract_assume(Expr
*expr
)
1800 cond
= try_extract_affine_condition(expr
);
1802 res
= extract_expr(expr
);
1804 isl_multi_pw_aff
*index
;
1805 index
= isl_multi_pw_aff_from_pw_aff(cond
);
1806 res
= pet_expr_from_index(index
);
1808 return pet_expr_new_unary(pet_op_assume
, res
);
1811 /* Construct a pet_expr corresponding to the function call argument "expr".
1812 * The argument appears in position "pos" of a call to function "fd".
1814 * If we are passing along a pointer to an array element
1815 * or an entire row or even higher dimensional slice of an array,
1816 * then the function being called may write into the array.
1818 * We assume here that if the function is declared to take a pointer
1819 * to a const type, then the function will perform a read
1820 * and that otherwise, it will perform a write.
1822 __isl_give pet_expr
*PetScan::extract_argument(FunctionDecl
*fd
, int pos
,
1826 int is_addr
= 0, is_partial
= 0;
1829 if (expr
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1830 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(expr
);
1831 expr
= ice
->getSubExpr();
1833 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1834 UnaryOperator
*op
= cast
<UnaryOperator
>(expr
);
1835 if (op
->getOpcode() == UO_AddrOf
) {
1837 expr
= op
->getSubExpr();
1840 res
= extract_expr(expr
);
1843 sc
= expr
->getStmtClass();
1844 if ((sc
== Stmt::ArraySubscriptExprClass
||
1845 sc
== Stmt::MemberExprClass
) &&
1846 array_depth(expr
->getType().getTypePtr()) > 0)
1848 if ((is_addr
|| is_partial
) &&
1849 pet_expr_get_type(res
) == pet_expr_access
) {
1851 if (!fd
->hasPrototype()) {
1852 report_prototype_required(expr
);
1853 return pet_expr_free(res
);
1855 parm
= fd
->getParamDecl(pos
);
1856 if (!const_base(parm
->getType()))
1857 res
= mark_write(res
);
1861 res
= pet_expr_new_unary(pet_op_address_of
, res
);
1865 /* Construct a pet_expr representing a function call.
1867 * In the special case of a "call" to __pencil_assume,
1868 * construct an assume expression instead.
1870 __isl_give pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1872 pet_expr
*res
= NULL
;
1877 fd
= expr
->getDirectCallee();
1883 name
= fd
->getDeclName().getAsString();
1884 n_arg
= expr
->getNumArgs();
1886 if (n_arg
== 1 && name
== "__pencil_assume")
1887 return extract_assume(expr
->getArg(0));
1889 res
= pet_expr_new_call(ctx
, name
.c_str(), n_arg
);
1893 for (int i
= 0; i
< n_arg
; ++i
) {
1894 Expr
*arg
= expr
->getArg(i
);
1895 res
= pet_expr_set_arg(res
, i
,
1896 PetScan::extract_argument(fd
, i
, arg
));
1902 /* Construct a pet_expr representing a (C style) cast.
1904 __isl_give pet_expr
*PetScan::extract_expr(CStyleCastExpr
*expr
)
1909 arg
= extract_expr(expr
->getSubExpr());
1913 type
= expr
->getTypeAsWritten();
1914 return pet_expr_new_cast(type
.getAsString().c_str(), arg
);
1917 /* Construct a pet_expr representing an integer.
1919 __isl_give pet_expr
*PetScan::extract_expr(IntegerLiteral
*expr
)
1921 return pet_expr_new_int(extract_int(expr
));
1924 /* Try and construct a pet_expr representing "expr".
1926 __isl_give pet_expr
*PetScan::extract_expr(Expr
*expr
)
1928 switch (expr
->getStmtClass()) {
1929 case Stmt::UnaryOperatorClass
:
1930 return extract_expr(cast
<UnaryOperator
>(expr
));
1931 case Stmt::CompoundAssignOperatorClass
:
1932 case Stmt::BinaryOperatorClass
:
1933 return extract_expr(cast
<BinaryOperator
>(expr
));
1934 case Stmt::ImplicitCastExprClass
:
1935 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1936 case Stmt::ArraySubscriptExprClass
:
1937 case Stmt::DeclRefExprClass
:
1938 case Stmt::MemberExprClass
:
1939 return extract_access_expr(expr
);
1940 case Stmt::IntegerLiteralClass
:
1941 return extract_expr(cast
<IntegerLiteral
>(expr
));
1942 case Stmt::FloatingLiteralClass
:
1943 return extract_expr(cast
<FloatingLiteral
>(expr
));
1944 case Stmt::ParenExprClass
:
1945 return extract_expr(cast
<ParenExpr
>(expr
));
1946 case Stmt::ConditionalOperatorClass
:
1947 return extract_expr(cast
<ConditionalOperator
>(expr
));
1948 case Stmt::CallExprClass
:
1949 return extract_expr(cast
<CallExpr
>(expr
));
1950 case Stmt::CStyleCastExprClass
:
1951 return extract_expr(cast
<CStyleCastExpr
>(expr
));
1958 /* Check if the given initialization statement is an assignment.
1959 * If so, return that assignment. Otherwise return NULL.
1961 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1963 BinaryOperator
*ass
;
1965 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1968 ass
= cast
<BinaryOperator
>(init
);
1969 if (ass
->getOpcode() != BO_Assign
)
1975 /* Check if the given initialization statement is a declaration
1976 * of a single variable.
1977 * If so, return that declaration. Otherwise return NULL.
1979 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1983 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1986 decl
= cast
<DeclStmt
>(init
);
1988 if (!decl
->isSingleDecl())
1991 return decl
->getSingleDecl();
1994 /* Given the assignment operator in the initialization of a for loop,
1995 * extract the induction variable, i.e., the (integer)variable being
1998 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
2005 lhs
= init
->getLHS();
2006 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
2011 ref
= cast
<DeclRefExpr
>(lhs
);
2012 decl
= ref
->getDecl();
2013 type
= decl
->getType().getTypePtr();
2015 if (!type
->isIntegerType()) {
2023 /* Given the initialization statement of a for loop and the single
2024 * declaration in this initialization statement,
2025 * extract the induction variable, i.e., the (integer) variable being
2028 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
2032 vd
= cast
<VarDecl
>(decl
);
2034 const QualType type
= vd
->getType();
2035 if (!type
->isIntegerType()) {
2040 if (!vd
->getInit()) {
2048 /* Check that op is of the form iv++ or iv--.
2049 * Return a pet_expr representing "1" or "-1" accordingly.
2051 __isl_give pet_expr
*PetScan::extract_unary_increment(
2052 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
2058 if (!op
->isIncrementDecrementOp()) {
2063 sub
= op
->getSubExpr();
2064 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
2069 ref
= cast
<DeclRefExpr
>(sub
);
2070 if (ref
->getDecl() != iv
) {
2075 if (op
->isIncrementOp())
2076 v
= isl_val_one(ctx
);
2078 v
= isl_val_negone(ctx
);
2080 return pet_expr_new_int(v
);
2083 /* Check if op is of the form
2087 * and return the increment "expr - iv" as a pet_expr.
2089 __isl_give pet_expr
*PetScan::extract_binary_increment(BinaryOperator
*op
,
2090 clang::ValueDecl
*iv
)
2095 pet_expr
*expr
, *expr_iv
;
2097 if (op
->getOpcode() != BO_Assign
) {
2103 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
2108 ref
= cast
<DeclRefExpr
>(lhs
);
2109 if (ref
->getDecl() != iv
) {
2114 expr
= extract_expr(op
->getRHS());
2115 expr_iv
= extract_expr(lhs
);
2117 type_size
= get_type_size(iv
->getType(), ast_context
);
2118 return pet_expr_new_binary(type_size
, pet_op_sub
, expr
, expr_iv
);
2121 /* Check that op is of the form iv += cst or iv -= cst
2122 * and return a pet_expr corresponding to cst or -cst accordingly.
2124 __isl_give pet_expr
*PetScan::extract_compound_increment(
2125 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
2131 BinaryOperatorKind opcode
;
2133 opcode
= op
->getOpcode();
2134 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
2138 if (opcode
== BO_SubAssign
)
2142 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
2147 ref
= cast
<DeclRefExpr
>(lhs
);
2148 if (ref
->getDecl() != iv
) {
2153 expr
= extract_expr(op
->getRHS());
2155 expr
= pet_expr_new_unary(pet_op_minus
, expr
);
2160 /* Check that the increment of the given for loop increments
2161 * (or decrements) the induction variable "iv" and return
2162 * the increment as a pet_expr if successful.
2164 __isl_give pet_expr
*PetScan::extract_increment(clang::ForStmt
*stmt
,
2167 Stmt
*inc
= stmt
->getInc();
2170 report_missing_increment(stmt
);
2174 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
2175 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
2176 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
2177 return extract_compound_increment(
2178 cast
<CompoundAssignOperator
>(inc
), iv
);
2179 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
2180 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
2186 /* Embed the given iteration domain in an extra outer loop
2187 * with induction variable "var".
2188 * If this variable appeared as a parameter in the constraints,
2189 * it is replaced by the new outermost dimension.
2191 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
2192 __isl_take isl_id
*var
)
2196 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
2197 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
2199 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
2200 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2207 /* Return those elements in the space of "cond" that come after
2208 * (based on "sign") an element in "cond".
2210 static __isl_give isl_set
*after(__isl_take isl_set
*cond
, int sign
)
2212 isl_map
*previous_to_this
;
2215 previous_to_this
= isl_map_lex_lt(isl_set_get_space(cond
));
2217 previous_to_this
= isl_map_lex_gt(isl_set_get_space(cond
));
2219 cond
= isl_set_apply(cond
, previous_to_this
);
2224 /* Create the infinite iteration domain
2226 * { [id] : id >= 0 }
2228 * If "scop" has an affine skip of type pet_skip_later,
2229 * then remove those iterations i that have an earlier iteration
2230 * where the skip condition is satisfied, meaning that iteration i
2232 * Since we are dealing with a loop without loop iterator,
2233 * the skip condition cannot refer to the current loop iterator and
2234 * so effectively, the returned set is of the form
2236 * { [0]; [id] : id >= 1 and not skip }
2238 static __isl_give isl_set
*infinite_domain(__isl_take isl_id
*id
,
2239 struct pet_scop
*scop
)
2241 isl_ctx
*ctx
= isl_id_get_ctx(id
);
2245 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
2246 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, id
);
2248 if (!pet_scop_has_affine_skip(scop
, pet_skip_later
))
2251 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
2252 skip
= embed(skip
, isl_id_copy(id
));
2253 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2254 domain
= isl_set_subtract(domain
, after(skip
, 1));
2259 /* Create an identity affine expression on the space containing "domain",
2260 * which is assumed to be one-dimensional.
2262 static __isl_give isl_aff
*identity_aff(__isl_keep isl_set
*domain
)
2264 isl_local_space
*ls
;
2266 ls
= isl_local_space_from_space(isl_set_get_space(domain
));
2267 return isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
2270 /* Create an affine expression that maps elements
2271 * of a single-dimensional array "id_test" to the previous element
2272 * (according to "inc"), provided this element belongs to "domain".
2273 * That is, create the affine expression
2275 * { id[x] -> id[x - inc] : x - inc in domain }
2277 static __isl_give isl_multi_pw_aff
*map_to_previous(__isl_take isl_id
*id_test
,
2278 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2281 isl_local_space
*ls
;
2283 isl_multi_pw_aff
*prev
;
2285 space
= isl_set_get_space(domain
);
2286 ls
= isl_local_space_from_space(space
);
2287 aff
= isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
2288 aff
= isl_aff_add_constant_val(aff
, isl_val_neg(inc
));
2289 prev
= isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
2290 domain
= isl_set_preimage_multi_pw_aff(domain
,
2291 isl_multi_pw_aff_copy(prev
));
2292 prev
= isl_multi_pw_aff_intersect_domain(prev
, domain
);
2293 prev
= isl_multi_pw_aff_set_tuple_id(prev
, isl_dim_out
, id_test
);
2298 /* Add an implication to "scop" expressing that if an element of
2299 * virtual array "id_test" has value "satisfied" then all previous elements
2300 * of this array also have that value. The set of previous elements
2301 * is bounded by "domain". If "sign" is negative then the iterator
2302 * is decreasing and we express that all subsequent array elements
2303 * (but still defined previously) have the same value.
2305 static struct pet_scop
*add_implication(struct pet_scop
*scop
,
2306 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
, int sign
,
2312 domain
= isl_set_set_tuple_id(domain
, id_test
);
2313 space
= isl_set_get_space(domain
);
2315 map
= isl_map_lex_ge(space
);
2317 map
= isl_map_lex_le(space
);
2318 map
= isl_map_intersect_range(map
, domain
);
2319 scop
= pet_scop_add_implication(scop
, map
, satisfied
);
2324 /* Add a filter to "scop" that imposes that it is only executed
2325 * when the variable identified by "id_test" has a zero value
2326 * for all previous iterations of "domain".
2328 * In particular, add a filter that imposes that the array
2329 * has a zero value at the previous iteration of domain and
2330 * add an implication that implies that it then has that
2331 * value for all previous iterations.
2333 static struct pet_scop
*scop_add_break(struct pet_scop
*scop
,
2334 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
,
2335 __isl_take isl_val
*inc
)
2337 isl_multi_pw_aff
*prev
;
2338 int sign
= isl_val_sgn(inc
);
2340 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
2341 scop
= add_implication(scop
, id_test
, domain
, sign
, 0);
2342 scop
= pet_scop_filter(scop
, prev
, 0);
2347 /* Construct a pet_scop for an infinite loop around the given body.
2349 * We extract a pet_scop for the body and then embed it in a loop with
2358 * If the body contains any break, then it is taken into
2359 * account in infinite_domain (if the skip condition is affine)
2360 * or in scop_add_break (if the skip condition is not affine).
2362 * If we were only able to extract part of the body, then simply
2365 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
2367 isl_id
*id
, *id_test
;
2370 struct pet_scop
*scop
;
2373 scop
= extract(body
);
2379 id
= isl_id_alloc(ctx
, "t", NULL
);
2380 domain
= infinite_domain(isl_id_copy(id
), scop
);
2381 ident
= identity_aff(domain
);
2383 has_var_break
= pet_scop_has_var_skip(scop
, pet_skip_later
);
2385 id_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
2387 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
2388 isl_aff_copy(ident
), ident
, id
);
2390 scop
= scop_add_break(scop
, id_test
, domain
, isl_val_one(ctx
));
2392 isl_set_free(domain
);
2397 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2403 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
2405 clear_assignments
clear(assigned_value
);
2406 clear
.TraverseStmt(stmt
->getBody());
2408 return extract_infinite_loop(stmt
->getBody());
2411 /* Add an array with the given extent (range of "index") to the list
2412 * of arrays in "scop" and return the extended pet_scop.
2413 * The array is marked as attaining values 0 and 1 only and
2414 * as each element being assigned at most once.
2416 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2417 __isl_keep isl_multi_pw_aff
*index
, clang::ASTContext
&ast_ctx
)
2419 int int_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
2421 return pet_scop_add_boolean_array(scop
, isl_multi_pw_aff_copy(index
),
2425 /* Construct a pet_scop for a while loop of the form
2430 * In particular, construct a scop for an infinite loop around body and
2431 * intersect the domain with the affine expression.
2432 * Note that this intersection may result in an empty loop.
2434 struct pet_scop
*PetScan::extract_affine_while(__isl_take isl_pw_aff
*pa
,
2437 struct pet_scop
*scop
;
2441 valid
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2442 dom
= isl_pw_aff_non_zero_set(pa
);
2443 scop
= extract_infinite_loop(body
);
2444 scop
= pet_scop_restrict(scop
, isl_set_params(dom
));
2445 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid
));
2450 /* Construct a scop for a while, given the scops for the condition
2451 * and the body, the filter identifier and the iteration domain of
2454 * In particular, the scop for the condition is filtered to depend
2455 * on "id_test" evaluating to true for all previous iterations
2456 * of the loop, while the scop for the body is filtered to depend
2457 * on "id_test" evaluating to true for all iterations up to the
2458 * current iteration.
2459 * The actual filter only imposes that this virtual array has
2460 * value one on the previous or the current iteration.
2461 * The fact that this condition also applies to the previous
2462 * iterations is enforced by an implication.
2464 * These filtered scops are then combined into a single scop.
2466 * "sign" is positive if the iterator increases and negative
2469 static struct pet_scop
*scop_add_while(struct pet_scop
*scop_cond
,
2470 struct pet_scop
*scop_body
, __isl_take isl_id
*id_test
,
2471 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2473 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
2475 isl_multi_pw_aff
*test_index
;
2476 isl_multi_pw_aff
*prev
;
2477 int sign
= isl_val_sgn(inc
);
2478 struct pet_scop
*scop
;
2480 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
2481 scop_cond
= pet_scop_filter(scop_cond
, prev
, 1);
2483 space
= isl_space_map_from_set(isl_set_get_space(domain
));
2484 test_index
= isl_multi_pw_aff_identity(space
);
2485 test_index
= isl_multi_pw_aff_set_tuple_id(test_index
, isl_dim_out
,
2486 isl_id_copy(id_test
));
2487 scop_body
= pet_scop_filter(scop_body
, test_index
, 1);
2489 scop
= pet_scop_add_seq(ctx
, scop_cond
, scop_body
);
2490 scop
= add_implication(scop
, id_test
, domain
, sign
, 1);
2495 /* Check if the while loop is of the form
2497 * while (affine expression)
2500 * If so, call extract_affine_while to construct a scop.
2502 * Otherwise, extract the body and pass control to extract_while
2503 * to extend the iteration domain with an infinite loop.
2504 * If we were only able to extract part of the body, then simply
2507 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
2510 int test_nr
, stmt_nr
;
2512 struct pet_scop
*scop_body
;
2514 cond
= stmt
->getCond();
2520 clear_assignments
clear(assigned_value
);
2521 clear
.TraverseStmt(stmt
->getBody());
2523 pa
= try_extract_affine_condition(cond
);
2525 return extract_affine_while(pa
, stmt
->getBody());
2527 if (!allow_nested
) {
2534 scop_body
= extract(stmt
->getBody());
2538 return extract_while(cond
, test_nr
, stmt_nr
, scop_body
, NULL
);
2541 /* Construct a generic while scop, with iteration domain
2542 * { [t] : t >= 0 } around "scop_body". The scop consists of two parts,
2543 * one for evaluating the condition "cond" and one for the body.
2544 * "test_nr" is the sequence number of the virtual test variable that contains
2545 * the result of the condition and "stmt_nr" is the sequence number
2546 * of the statement that evaluates the condition.
2547 * If "scop_inc" is not NULL, then it is added at the end of the body,
2548 * after replacing any skip conditions resulting from continue statements
2549 * by the skip conditions resulting from break statements (if any).
2551 * The schedule is adjusted to reflect that the condition is evaluated
2552 * before the body is executed and the body is filtered to depend
2553 * on the result of the condition evaluating to true on all iterations
2554 * up to the current iteration, while the evaluation of the condition itself
2555 * is filtered to depend on the result of the condition evaluating to true
2556 * on all previous iterations.
2557 * The context of the scop representing the body is dropped
2558 * because we don't know how many times the body will be executed,
2561 * If the body contains any break, then it is taken into
2562 * account in infinite_domain (if the skip condition is affine)
2563 * or in scop_add_break (if the skip condition is not affine).
2565 struct pet_scop
*PetScan::extract_while(Expr
*cond
, int test_nr
, int stmt_nr
,
2566 struct pet_scop
*scop_body
, struct pet_scop
*scop_inc
)
2568 isl_id
*id
, *id_test
, *id_break_test
;
2571 isl_multi_pw_aff
*test_index
;
2572 struct pet_scop
*scop
;
2575 test_index
= pet_create_test_index(ctx
, test_nr
);
2576 scop
= extract_non_affine_condition(cond
, stmt_nr
,
2577 isl_multi_pw_aff_copy(test_index
));
2578 scop
= scop_add_array(scop
, test_index
, ast_context
);
2579 id_test
= isl_multi_pw_aff_get_tuple_id(test_index
, isl_dim_out
);
2580 isl_multi_pw_aff_free(test_index
);
2582 id
= isl_id_alloc(ctx
, "t", NULL
);
2583 domain
= infinite_domain(isl_id_copy(id
), scop_body
);
2584 ident
= identity_aff(domain
);
2586 has_var_break
= pet_scop_has_var_skip(scop_body
, pet_skip_later
);
2588 id_break_test
= pet_scop_get_skip_id(scop_body
, pet_skip_later
);
2590 scop
= pet_scop_prefix(scop
, 0);
2591 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), isl_aff_copy(ident
),
2592 isl_aff_copy(ident
), isl_id_copy(id
));
2593 scop_body
= pet_scop_reset_context(scop_body
);
2594 scop_body
= pet_scop_prefix(scop_body
, 1);
2596 scop_inc
= pet_scop_prefix(scop_inc
, 2);
2597 if (pet_scop_has_skip(scop_body
, pet_skip_later
)) {
2598 isl_multi_pw_aff
*skip
;
2599 skip
= pet_scop_get_skip(scop_body
, pet_skip_later
);
2600 scop_body
= pet_scop_set_skip(scop_body
,
2601 pet_skip_now
, skip
);
2603 pet_scop_reset_skip(scop_body
, pet_skip_now
);
2604 scop_body
= pet_scop_add_seq(ctx
, scop_body
, scop_inc
);
2606 scop_body
= pet_scop_embed(scop_body
, isl_set_copy(domain
),
2607 isl_aff_copy(ident
), ident
, id
);
2609 if (has_var_break
) {
2610 scop
= scop_add_break(scop
, isl_id_copy(id_break_test
),
2611 isl_set_copy(domain
), isl_val_one(ctx
));
2612 scop_body
= scop_add_break(scop_body
, id_break_test
,
2613 isl_set_copy(domain
), isl_val_one(ctx
));
2615 scop
= scop_add_while(scop
, scop_body
, id_test
, domain
,
2621 /* Check whether "cond" expresses a simple loop bound
2622 * on the only set dimension.
2623 * In particular, if "up" is set then "cond" should contain only
2624 * upper bounds on the set dimension.
2625 * Otherwise, it should contain only lower bounds.
2627 static bool is_simple_bound(__isl_keep isl_set
*cond
, __isl_keep isl_val
*inc
)
2629 if (isl_val_is_pos(inc
))
2630 return !isl_set_dim_has_any_lower_bound(cond
, isl_dim_set
, 0);
2632 return !isl_set_dim_has_any_upper_bound(cond
, isl_dim_set
, 0);
2635 /* Extend a condition on a given iteration of a loop to one that
2636 * imposes the same condition on all previous iterations.
2637 * "domain" expresses the lower [upper] bound on the iterations
2638 * when inc is positive [negative].
2640 * In particular, we construct the condition (when inc is positive)
2642 * forall i' : (domain(i') and i' <= i) => cond(i')
2644 * which is equivalent to
2646 * not exists i' : domain(i') and i' <= i and not cond(i')
2648 * We construct this set by negating cond, applying a map
2650 * { [i'] -> [i] : domain(i') and i' <= i }
2652 * and then negating the result again.
2654 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
2655 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2657 isl_map
*previous_to_this
;
2659 if (isl_val_is_pos(inc
))
2660 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
2662 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
2664 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
2666 cond
= isl_set_complement(cond
);
2667 cond
= isl_set_apply(cond
, previous_to_this
);
2668 cond
= isl_set_complement(cond
);
2675 /* Construct a domain of the form
2677 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2679 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
2680 __isl_take isl_pw_aff
*init
, __isl_take isl_val
*inc
)
2686 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
2687 dim
= isl_pw_aff_get_domain_space(init
);
2688 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2689 aff
= isl_aff_add_coefficient_val(aff
, isl_dim_in
, 0, inc
);
2690 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2692 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2693 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2694 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2695 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2697 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2699 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2701 return isl_set_params(set
);
2704 /* Assuming "cond" represents a bound on a loop where the loop
2705 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2708 * Under the given assumptions, wrapping is only possible if "cond" allows
2709 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2710 * increasing iterator and 0 in case of a decreasing iterator.
2712 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
,
2713 __isl_keep isl_val
*inc
)
2720 test
= isl_set_copy(cond
);
2722 ctx
= isl_set_get_ctx(test
);
2723 if (isl_val_is_neg(inc
))
2724 limit
= isl_val_zero(ctx
);
2726 limit
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2727 limit
= isl_val_2exp(limit
);
2728 limit
= isl_val_sub_ui(limit
, 1);
2731 test
= isl_set_fix_val(cond
, isl_dim_set
, 0, limit
);
2732 cw
= !isl_set_is_empty(test
);
2738 /* Given a one-dimensional space, construct the following affine expression
2741 * { [v] -> [v mod 2^width] }
2743 * where width is the number of bits used to represent the values
2744 * of the unsigned variable "iv".
2746 static __isl_give isl_aff
*compute_wrapping(__isl_take isl_space
*dim
,
2753 ctx
= isl_space_get_ctx(dim
);
2754 mod
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2755 mod
= isl_val_2exp(mod
);
2757 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2758 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2759 aff
= isl_aff_mod_val(aff
, mod
);
2764 /* Project out the parameter "id" from "set".
2766 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2767 __isl_keep isl_id
*id
)
2771 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2773 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2778 /* Compute the set of parameters for which "set1" is a subset of "set2".
2780 * set1 is a subset of set2 if
2782 * forall i in set1 : i in set2
2786 * not exists i in set1 and i not in set2
2790 * not exists i in set1 \ set2
2792 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2793 __isl_take isl_set
*set2
)
2795 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2798 /* Compute the set of parameter values for which "cond" holds
2799 * on the next iteration for each element of "dom".
2801 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2802 * and then compute the set of parameters for which the result is a subset
2805 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2806 __isl_take isl_set
*dom
, __isl_take isl_val
*inc
)
2812 space
= isl_set_get_space(dom
);
2813 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2814 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2815 aff
= isl_aff_add_constant_val(aff
, inc
);
2816 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2818 dom
= isl_set_apply(dom
, next
);
2820 return enforce_subset(dom
, cond
);
2823 /* Extract the for loop "stmt" as a while loop.
2824 * "iv" is the loop iterator. "init" is the initialization.
2825 * "inc" is the increment.
2827 * That is, the for loop has the form
2829 * for (iv = init; cond; iv += inc)
2840 * except that the skips resulting from any continue statements
2841 * in body do not apply to the increment, but are replaced by the skips
2842 * resulting from break statements.
2844 * If "iv" is declared in the for loop, then it is killed before
2845 * and after the loop.
2847 struct pet_scop
*PetScan::extract_non_affine_for(ForStmt
*stmt
, ValueDecl
*iv
,
2848 __isl_take pet_expr
*init
, __isl_take pet_expr
*inc
)
2851 int test_nr
, stmt_nr
;
2853 struct pet_scop
*scop_init
, *scop_inc
, *scop
, *scop_body
;
2855 struct pet_array
*array
;
2856 struct pet_scop
*scop_kill
;
2858 if (!allow_nested
) {
2863 clear_assignment(assigned_value
, iv
);
2865 declared
= !initialization_assignment(stmt
->getInit());
2867 expr_iv
= extract_access_expr(iv
);
2868 expr_iv
= mark_write(expr_iv
);
2869 type_size
= pet_expr_get_type_size(expr_iv
);
2870 init
= pet_expr_new_binary(type_size
, pet_op_assign
, expr_iv
, init
);
2871 scop_init
= extract(init
, stmt
->getInit()->getSourceRange(), false);
2872 scop_init
= pet_scop_prefix(scop_init
, declared
);
2876 scop_body
= extract(stmt
->getBody());
2878 pet_scop_free(scop_init
);
2882 expr_iv
= extract_access_expr(iv
);
2883 expr_iv
= mark_write(expr_iv
);
2884 type_size
= pet_expr_get_type_size(expr_iv
);
2885 inc
= pet_expr_new_binary(type_size
, pet_op_add_assign
, expr_iv
, inc
);
2886 scop_inc
= extract(inc
, stmt
->getInc()->getSourceRange(), false);
2888 pet_scop_free(scop_init
);
2889 pet_scop_free(scop_body
);
2893 scop
= extract_while(stmt
->getCond(), test_nr
, stmt_nr
, scop_body
,
2896 scop
= pet_scop_prefix(scop
, declared
+ 1);
2897 scop
= pet_scop_add_seq(ctx
, scop_init
, scop
);
2902 array
= extract_array(ctx
, iv
, NULL
);
2904 array
->declared
= 1;
2905 scop_kill
= kill(stmt
, array
);
2906 scop_kill
= pet_scop_prefix(scop_kill
, 0);
2907 scop
= pet_scop_add_seq(ctx
, scop_kill
, scop
);
2908 scop_kill
= kill(stmt
, array
);
2909 scop_kill
= pet_scop_add_array(scop_kill
, array
);
2910 scop_kill
= pet_scop_prefix(scop_kill
, 3);
2911 scop
= pet_scop_add_seq(ctx
, scop
, scop_kill
);
2916 /* Construct a pet_scop for a for statement.
2917 * The for loop is required to be of one of the following forms
2919 * for (i = init; condition; ++i)
2920 * for (i = init; condition; --i)
2921 * for (i = init; condition; i += constant)
2922 * for (i = init; condition; i -= constant)
2924 * The initialization of the for loop should either be an assignment
2925 * of a static affine value to an integer variable, or a declaration
2926 * of such a variable with initialization.
2928 * If the initialization or the increment do not satisfy the above
2929 * conditions, i.e., if the initialization is not static affine
2930 * or the increment is not constant, then the for loop is extracted
2931 * as a while loop instead.
2933 * The condition is allowed to contain nested accesses, provided
2934 * they are not being written to inside the body of the loop.
2935 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2936 * essentially treated as a while loop, with iteration domain
2937 * { [i] : i >= init }.
2939 * We extract a pet_scop for the body and then embed it in a loop with
2940 * iteration domain and schedule
2942 * { [i] : i >= init and condition' }
2947 * { [i] : i <= init and condition' }
2950 * Where condition' is equal to condition if the latter is
2951 * a simple upper [lower] bound and a condition that is extended
2952 * to apply to all previous iterations otherwise.
2954 * If the condition is non-affine, then we drop the condition from the
2955 * iteration domain and instead create a separate statement
2956 * for evaluating the condition. The body is then filtered to depend
2957 * on the result of the condition evaluating to true on all iterations
2958 * up to the current iteration, while the evaluation the condition itself
2959 * is filtered to depend on the result of the condition evaluating to true
2960 * on all previous iterations.
2961 * The context of the scop representing the body is dropped
2962 * because we don't know how many times the body will be executed,
2965 * If the stride of the loop is not 1, then "i >= init" is replaced by
2967 * (exists a: i = init + stride * a and a >= 0)
2969 * If the loop iterator i is unsigned, then wrapping may occur.
2970 * We therefore use a virtual iterator instead that does not wrap.
2971 * However, the condition in the code applies
2972 * to the wrapped value, so we need to change condition(i)
2973 * into condition([i % 2^width]). Similarly, we replace all accesses
2974 * to the original iterator by the wrapping of the virtual iterator.
2975 * Note that there may be no need to perform this final wrapping
2976 * if the loop condition (after wrapping) satisfies certain conditions.
2977 * However, the is_simple_bound condition is not enough since it doesn't
2978 * check if there even is an upper bound.
2980 * Wrapping on unsigned iterators can be avoided entirely if
2981 * loop condition is simple, the loop iterator is incremented
2982 * [decremented] by one and the last value before wrapping cannot
2983 * possibly satisfy the loop condition.
2985 * Before extracting a pet_scop from the body we remove all
2986 * assignments in assigned_value to variables that are assigned
2987 * somewhere in the body of the loop.
2989 * Valid parameters for a for loop are those for which the initial
2990 * value itself, the increment on each domain iteration and
2991 * the condition on both the initial value and
2992 * the result of incrementing the iterator for each iteration of the domain
2994 * If the loop condition is non-affine, then we only consider validity
2995 * of the initial value.
2997 * If the body contains any break, then we keep track of it in "skip"
2998 * (if the skip condition is affine) or it is handled in scop_add_break
2999 * (if the skip condition is not affine).
3000 * Note that the affine break condition needs to be considered with
3001 * respect to previous iterations in the virtual domain (if any).
3003 * If we were only able to extract part of the body, then simply
3006 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
3008 BinaryOperator
*ass
;
3013 isl_local_space
*ls
;
3016 isl_set
*cond
= NULL
;
3017 isl_set
*skip
= NULL
;
3018 isl_id
*id
, *id_test
= NULL
, *id_break_test
;
3019 struct pet_scop
*scop
, *scop_cond
= NULL
;
3020 assigned_value_cache
cache(assigned_value
);
3026 bool has_affine_break
;
3028 isl_aff
*wrap
= NULL
;
3029 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
3030 isl_set
*valid_init
;
3031 isl_set
*valid_cond
;
3032 isl_set
*valid_cond_init
;
3033 isl_set
*valid_cond_next
;
3036 pet_expr
*pe_init
, *pe_inc
;
3037 pet_context
*pc
, *pc_init_val
;
3039 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
3040 return extract_infinite_for(stmt
);
3042 init
= stmt
->getInit();
3047 if ((ass
= initialization_assignment(init
)) != NULL
) {
3048 iv
= extract_induction_variable(ass
);
3051 lhs
= ass
->getLHS();
3052 rhs
= ass
->getRHS();
3053 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
3054 VarDecl
*var
= extract_induction_variable(init
, decl
);
3058 rhs
= var
->getInit();
3059 lhs
= create_DeclRefExpr(var
);
3061 unsupported(stmt
->getInit());
3065 id
= create_decl_id(ctx
, iv
);
3067 assigned_value
.erase(iv
);
3068 clear_assignments
clear(assigned_value
);
3069 clear
.TraverseStmt(stmt
->getBody());
3071 pe_init
= extract_expr(rhs
);
3072 pe_inc
= extract_increment(stmt
, iv
);
3073 pc
= convert_assignments(ctx
, assigned_value
);
3074 pc_init_val
= pet_context_copy(pc
);
3075 pc_init_val
= pet_context_mark_unknown(pc_init_val
, isl_id_copy(id
));
3076 init_val
= pet_expr_extract_affine(pe_init
, pc_init_val
);
3077 pet_context_free(pc_init_val
);
3078 pa_inc
= pet_expr_extract_affine(pe_inc
, pc
);
3079 pet_context_free(pc
);
3080 inc
= pet_extract_cst(pa_inc
);
3081 if (!pe_init
|| !pe_inc
|| !inc
|| isl_val_is_nan(inc
) ||
3082 isl_pw_aff_involves_nan(pa_inc
) ||
3083 isl_pw_aff_involves_nan(init_val
)) {
3086 isl_pw_aff_free(pa_inc
);
3087 isl_pw_aff_free(init_val
);
3088 if (pe_init
&& pe_inc
&& !(pa_inc
&& !inc
))
3089 return extract_non_affine_for(stmt
, iv
,
3091 pet_expr_free(pe_init
);
3092 pet_expr_free(pe_inc
);
3095 pet_expr_free(pe_init
);
3096 pet_expr_free(pe_inc
);
3098 pa
= try_extract_nested_condition(stmt
->getCond());
3099 if (allow_nested
&& (!pa
|| pet_nested_any_in_pw_aff(pa
)))
3102 scop
= extract(stmt
->getBody());
3105 isl_pw_aff_free(init_val
);
3106 isl_pw_aff_free(pa_inc
);
3107 isl_pw_aff_free(pa
);
3112 valid_inc
= isl_pw_aff_domain(pa_inc
);
3114 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
3116 has_affine_break
= scop
&&
3117 pet_scop_has_affine_skip(scop
, pet_skip_later
);
3118 if (has_affine_break
)
3119 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
3120 has_var_break
= scop
&& pet_scop_has_var_skip(scop
, pet_skip_later
);
3122 id_break_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
3124 if (pa
&& !is_nested_allowed(pa
, scop
)) {
3125 isl_pw_aff_free(pa
);
3129 if (!allow_nested
&& !pa
)
3130 pa
= try_extract_affine_condition(stmt
->getCond());
3131 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
3132 cond
= isl_pw_aff_non_zero_set(pa
);
3133 if (allow_nested
&& !cond
) {
3134 isl_multi_pw_aff
*test_index
;
3135 int save_n_stmt
= n_stmt
;
3136 test_index
= pet_create_test_index(ctx
, n_test
++);
3138 scop_cond
= extract_non_affine_condition(stmt
->getCond(),
3139 n_stmt
++, isl_multi_pw_aff_copy(test_index
));
3140 n_stmt
= save_n_stmt
;
3141 scop_cond
= scop_add_array(scop_cond
, test_index
, ast_context
);
3142 id_test
= isl_multi_pw_aff_get_tuple_id(test_index
,
3144 isl_multi_pw_aff_free(test_index
);
3145 scop_cond
= pet_scop_prefix(scop_cond
, 0);
3146 scop
= pet_scop_reset_context(scop
);
3147 scop
= pet_scop_prefix(scop
, 1);
3148 cond
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
3151 cond
= embed(cond
, isl_id_copy(id
));
3152 skip
= embed(skip
, isl_id_copy(id
));
3153 valid_cond
= isl_set_coalesce(valid_cond
);
3154 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
3155 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
3156 is_one
= isl_val_is_one(inc
) || isl_val_is_negone(inc
);
3157 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
3159 valid_cond_init
= enforce_subset(
3160 isl_map_range(isl_map_from_pw_aff(isl_pw_aff_copy(init_val
))),
3161 isl_set_copy(valid_cond
));
3162 if (is_one
&& !is_virtual
) {
3163 isl_pw_aff_free(init_val
);
3164 pa
= extract_comparison(isl_val_is_pos(inc
) ? BO_GE
: BO_LE
,
3166 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
3167 valid_init
= set_project_out_by_id(valid_init
, id
);
3168 domain
= isl_pw_aff_non_zero_set(pa
);
3170 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
3171 domain
= strided_domain(isl_id_copy(id
), init_val
,
3175 domain
= embed(domain
, isl_id_copy(id
));
3178 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
3179 rev_wrap
= isl_map_from_aff(isl_aff_copy(wrap
));
3180 rev_wrap
= isl_map_reverse(rev_wrap
);
3181 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
3182 skip
= isl_set_apply(skip
, isl_map_copy(rev_wrap
));
3183 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
3184 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
3186 is_simple
= is_simple_bound(cond
, inc
);
3188 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
3189 is_simple
= is_simple_bound(cond
, inc
);
3192 cond
= valid_for_each_iteration(cond
,
3193 isl_set_copy(domain
), isl_val_copy(inc
));
3194 domain
= isl_set_intersect(domain
, cond
);
3195 if (has_affine_break
) {
3196 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
3197 skip
= after(skip
, isl_val_sgn(inc
));
3198 domain
= isl_set_subtract(domain
, skip
);
3200 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
3201 ls
= isl_local_space_from_space(isl_set_get_space(domain
));
3202 sched
= isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
3203 if (isl_val_is_neg(inc
))
3204 sched
= isl_aff_neg(sched
);
3206 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
),
3208 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
3211 wrap
= identity_aff(domain
);
3213 scop_cond
= pet_scop_embed(scop_cond
, isl_set_copy(domain
),
3214 isl_aff_copy(sched
), isl_aff_copy(wrap
), isl_id_copy(id
));
3215 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), sched
, wrap
, id
);
3216 scop
= resolve_nested(scop
);
3218 scop
= scop_add_break(scop
, id_break_test
, isl_set_copy(domain
),
3221 scop
= scop_add_while(scop_cond
, scop
, id_test
, domain
,
3223 isl_set_free(valid_inc
);
3225 scop
= pet_scop_restrict_context(scop
, valid_inc
);
3226 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
3227 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
3228 isl_set_free(domain
);
3230 clear_assignment(assigned_value
, iv
);
3234 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid_init
));
3239 /* Try and construct a pet_scop corresponding to a compound statement.
3241 * "skip_declarations" is set if we should skip initial declarations
3242 * in the children of the compound statements. This then implies
3243 * that this sequence of children should not be treated as a block
3244 * since the initial statements may be skipped.
3246 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
, bool skip_declarations
)
3248 return extract(stmt
->children(), !skip_declarations
, skip_declarations
);
3251 /* Extract a pet_expr from an isl_id created by either pet_nested_clang_expr or
3252 * pet_nested_pet_expr.
3253 * In the first case, the isl_id has no name and
3254 * the user pointer points to a clang::Expr object.
3255 * In the second case, the isl_id has name "__pet_expr" and
3256 * the user pointer points to a pet_expr object.
3258 __isl_give pet_expr
*PetScan::extract_expr(__isl_keep isl_id
*id
)
3260 if (!isl_id_get_name(id
))
3261 return extract_expr((Expr
*) isl_id_get_user(id
));
3263 return pet_expr_copy((pet_expr
*) isl_id_get_user(id
));
3266 /* For each nested access parameter in "space",
3267 * construct a corresponding pet_expr, place it in args and
3268 * record its position in "param2pos".
3269 * "n_arg" is the number of elements that are already in args.
3270 * The position recorded in "param2pos" takes this number into account.
3271 * If the pet_expr corresponding to a parameter is identical to
3272 * the pet_expr corresponding to an earlier parameter, then these two
3273 * parameters are made to refer to the same element in args.
3275 * Return the final number of elements in args or -1 if an error has occurred.
3277 int PetScan::extract_nested(__isl_keep isl_space
*space
,
3278 int n_arg
, pet_expr
**args
, std::map
<int,int> ¶m2pos
)
3282 nparam
= isl_space_dim(space
, isl_dim_param
);
3283 for (int i
= 0; i
< nparam
; ++i
) {
3285 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
3287 if (!pet_nested_in_id(id
)) {
3292 args
[n_arg
] = extract_expr(id
);
3297 for (j
= 0; j
< n_arg
; ++j
)
3298 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
3302 pet_expr_free(args
[n_arg
]);
3306 param2pos
[i
] = n_arg
++;
3312 /* For each nested access parameter in the access relations in "expr",
3313 * construct a corresponding pet_expr, place it in the arguments of "expr"
3314 * and record its position in "param2pos".
3315 * n is the number of nested access parameters.
3317 __isl_give pet_expr
*PetScan::extract_nested(__isl_take pet_expr
*expr
, int n
,
3318 std::map
<int,int> ¶m2pos
)
3324 args
= isl_calloc_array(ctx
, pet_expr
*, n
);
3326 return pet_expr_free(expr
);
3328 space
= pet_expr_access_get_parameter_space(expr
);
3329 n
= extract_nested(space
, 0, args
, param2pos
);
3330 isl_space_free(space
);
3333 expr
= pet_expr_free(expr
);
3335 expr
= pet_expr_set_n_arg(expr
, n
);
3337 for (i
= 0; i
< n
; ++i
)
3338 expr
= pet_expr_set_arg(expr
, i
, args
[i
]);
3344 /* Look for parameters in any access relation in "expr" that
3345 * refer to nested accesses. In particular, these are
3346 * parameters with either no name or with name "__pet_expr".
3348 * If there are any such parameters, then the domain of the index
3349 * expression and the access relation, which is still [] at this point,
3350 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
3351 * (after identifying identical nested accesses).
3353 * This transformation is performed in several steps.
3354 * We first extract the arguments in extract_nested.
3355 * param2pos maps the original parameter position to the position
3357 * Then we move these parameters to input dimensions.
3358 * t2pos maps the positions of these temporary input dimensions
3359 * to the positions of the corresponding arguments.
3360 * Finally, we express these temporary dimensions in terms of the domain
3361 * [[] -> [t_1,...,t_n]] and precompose index expression and access
3362 * relations with this function.
3364 __isl_give pet_expr
*PetScan::resolve_nested(__isl_take pet_expr
*expr
)
3369 isl_local_space
*ls
;
3372 std::map
<int,int> param2pos
;
3373 std::map
<int,int> t2pos
;
3378 n
= pet_expr_get_n_arg(expr
);
3379 for (int i
= 0; i
< n
; ++i
) {
3381 arg
= pet_expr_get_arg(expr
, i
);
3382 arg
= resolve_nested(arg
);
3383 expr
= pet_expr_set_arg(expr
, i
, arg
);
3386 if (pet_expr_get_type(expr
) != pet_expr_access
)
3389 space
= pet_expr_access_get_parameter_space(expr
);
3390 n
= pet_nested_n_in_space(space
);
3391 isl_space_free(space
);
3395 expr
= extract_nested(expr
, n
, param2pos
);
3399 expr
= pet_expr_access_align_params(expr
);
3404 space
= pet_expr_access_get_parameter_space(expr
);
3405 nparam
= isl_space_dim(space
, isl_dim_param
);
3406 for (int i
= nparam
- 1; i
>= 0; --i
) {
3407 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
3408 if (!pet_nested_in_id(id
)) {
3413 expr
= pet_expr_access_move_dims(expr
,
3414 isl_dim_in
, n
, isl_dim_param
, i
, 1);
3415 t2pos
[n
] = param2pos
[i
];
3420 isl_space_free(space
);
3422 space
= pet_expr_access_get_parameter_space(expr
);
3423 space
= isl_space_set_from_params(space
);
3424 space
= isl_space_add_dims(space
, isl_dim_set
,
3425 pet_expr_get_n_arg(expr
));
3426 space
= isl_space_wrap(isl_space_from_range(space
));
3427 ls
= isl_local_space_from_space(isl_space_copy(space
));
3428 space
= isl_space_from_domain(space
);
3429 space
= isl_space_add_dims(space
, isl_dim_out
, n
);
3430 ma
= isl_multi_aff_zero(space
);
3432 for (int i
= 0; i
< n
; ++i
) {
3433 aff
= isl_aff_var_on_domain(isl_local_space_copy(ls
),
3434 isl_dim_set
, t2pos
[i
]);
3435 ma
= isl_multi_aff_set_aff(ma
, i
, aff
);
3437 isl_local_space_free(ls
);
3439 expr
= pet_expr_access_pullback_multi_aff(expr
, ma
);
3444 /* Return the file offset of the expansion location of "Loc".
3446 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
3448 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
3451 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3453 /* Return a SourceLocation for the location after the first semicolon
3454 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3455 * call it and also skip trailing spaces and newline.
3457 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3458 const LangOptions
&LO
)
3460 return Lexer::findLocationAfterToken(loc
, tok::semi
, SM
, LO
, true);
3465 /* Return a SourceLocation for the location after the first semicolon
3466 * after "loc". If Lexer::findLocationAfterToken is not available,
3467 * we look in the underlying character data for the first semicolon.
3469 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3470 const LangOptions
&LO
)
3473 const char *s
= SM
.getCharacterData(loc
);
3475 semi
= strchr(s
, ';');
3477 return SourceLocation();
3478 return loc
.getFileLocWithOffset(semi
+ 1 - s
);
3483 /* If the token at "loc" is the first token on the line, then return
3484 * a location referring to the start of the line.
3485 * Otherwise, return "loc".
3487 * This function is used to extend a scop to the start of the line
3488 * if the first token of the scop is also the first token on the line.
3490 * We look for the first token on the line. If its location is equal to "loc",
3491 * then the latter is the location of the first token on the line.
3493 static SourceLocation
move_to_start_of_line_if_first_token(SourceLocation loc
,
3494 SourceManager
&SM
, const LangOptions
&LO
)
3496 std::pair
<FileID
, unsigned> file_offset_pair
;
3497 llvm::StringRef file
;
3500 SourceLocation token_loc
, line_loc
;
3503 loc
= SM
.getExpansionLoc(loc
);
3504 col
= SM
.getExpansionColumnNumber(loc
);
3505 line_loc
= loc
.getLocWithOffset(1 - col
);
3506 file_offset_pair
= SM
.getDecomposedLoc(line_loc
);
3507 file
= SM
.getBufferData(file_offset_pair
.first
, NULL
);
3508 pos
= file
.data() + file_offset_pair
.second
;
3510 Lexer
lexer(SM
.getLocForStartOfFile(file_offset_pair
.first
), LO
,
3511 file
.begin(), pos
, file
.end());
3512 lexer
.LexFromRawLexer(tok
);
3513 token_loc
= tok
.getLocation();
3515 if (token_loc
== loc
)
3521 /* Update start and end of "scop" to include the region covered by "range".
3522 * If "skip_semi" is set, then we assume "range" is followed by
3523 * a semicolon and also include this semicolon.
3525 struct pet_scop
*PetScan::update_scop_start_end(struct pet_scop
*scop
,
3526 SourceRange range
, bool skip_semi
)
3528 SourceLocation loc
= range
.getBegin();
3529 SourceManager
&SM
= PP
.getSourceManager();
3530 const LangOptions
&LO
= PP
.getLangOpts();
3531 unsigned start
, end
;
3533 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
);
3534 start
= getExpansionOffset(SM
, loc
);
3535 loc
= range
.getEnd();
3537 loc
= location_after_semi(loc
, SM
, LO
);
3539 loc
= PP
.getLocForEndOfToken(loc
);
3540 end
= getExpansionOffset(SM
, loc
);
3542 scop
= pet_scop_update_start_end(scop
, start
, end
);
3546 /* Convert a top-level pet_expr to a pet_scop with one statement.
3547 * This mainly involves resolving nested expression parameters
3548 * and setting the name of the iteration space.
3549 * The name is given by "label" if it is non-NULL. Otherwise,
3550 * it is of the form S_<n_stmt>.
3551 * start and end of the pet_scop are derived from "range" and "skip_semi".
3552 * In particular, if "skip_semi" is set then the semicolon following "range"
3555 struct pet_scop
*PetScan::extract(__isl_take pet_expr
*expr
, SourceRange range
,
3556 bool skip_semi
, __isl_take isl_id
*label
)
3558 struct pet_stmt
*ps
;
3559 struct pet_scop
*scop
;
3560 SourceLocation loc
= range
.getBegin();
3561 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3563 expr
= resolve_nested(expr
);
3564 ps
= pet_stmt_from_pet_expr(line
, label
, n_stmt
++, expr
);
3565 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3567 scop
= update_scop_start_end(scop
, range
, skip_semi
);
3571 /* Check if we can extract an affine expression from "expr".
3572 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3573 * We turn on autodetection so that we won't generate any warnings
3574 * and turn off nesting, so that we won't accept any non-affine constructs.
3576 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
3579 int save_autodetect
= options
->autodetect
;
3580 bool save_nesting
= nesting_enabled
;
3582 options
->autodetect
= 1;
3583 nesting_enabled
= false;
3585 pwaff
= extract_affine(expr
);
3587 options
->autodetect
= save_autodetect
;
3588 nesting_enabled
= save_nesting
;
3593 /* Check if we can extract an affine constraint from "expr".
3594 * Return the constraint as an isl_set if we can and NULL otherwise.
3595 * We turn on autodetection so that we won't generate any warnings
3596 * and turn off nesting, so that we won't accept any non-affine constructs.
3598 __isl_give isl_pw_aff
*PetScan::try_extract_affine_condition(Expr
*expr
)
3601 int save_autodetect
= options
->autodetect
;
3602 bool save_nesting
= nesting_enabled
;
3604 options
->autodetect
= 1;
3605 nesting_enabled
= false;
3607 cond
= extract_condition(expr
);
3609 options
->autodetect
= save_autodetect
;
3610 nesting_enabled
= save_nesting
;
3615 /* Check whether "expr" is an affine constraint.
3617 bool PetScan::is_affine_condition(Expr
*expr
)
3621 cond
= try_extract_affine_condition(expr
);
3622 isl_pw_aff_free(cond
);
3624 return cond
!= NULL
;
3627 /* Check if we can extract a condition from "expr".
3628 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3629 * If allow_nested is set, then the condition may involve parameters
3630 * corresponding to nested accesses.
3631 * We turn on autodetection so that we won't generate any warnings.
3633 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
3636 int save_autodetect
= options
->autodetect
;
3637 bool save_nesting
= nesting_enabled
;
3639 options
->autodetect
= 1;
3640 nesting_enabled
= allow_nested
;
3641 cond
= extract_condition(expr
);
3643 options
->autodetect
= save_autodetect
;
3644 nesting_enabled
= save_nesting
;
3649 /* If the top-level expression of "stmt" is an assignment, then
3650 * return that assignment as a BinaryOperator.
3651 * Otherwise return NULL.
3653 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
3655 BinaryOperator
*ass
;
3659 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
3662 ass
= cast
<BinaryOperator
>(stmt
);
3663 if(ass
->getOpcode() != BO_Assign
)
3669 /* Check if the given if statement is a conditional assignement
3670 * with a non-affine condition. If so, construct a pet_scop
3671 * corresponding to this conditional assignment. Otherwise return NULL.
3673 * In particular we check if "stmt" is of the form
3680 * where a is some array or scalar access.
3681 * The constructed pet_scop then corresponds to the expression
3683 * a = condition ? f(...) : g(...)
3685 * All access relations in f(...) are intersected with condition
3686 * while all access relation in g(...) are intersected with the complement.
3688 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
3690 BinaryOperator
*ass_then
, *ass_else
;
3691 isl_multi_pw_aff
*write_then
, *write_else
;
3692 isl_set
*cond
, *comp
;
3693 isl_multi_pw_aff
*index
;
3697 pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
3698 bool save_nesting
= nesting_enabled
;
3700 if (!options
->detect_conditional_assignment
)
3703 ass_then
= top_assignment_or_null(stmt
->getThen());
3704 ass_else
= top_assignment_or_null(stmt
->getElse());
3706 if (!ass_then
|| !ass_else
)
3709 if (is_affine_condition(stmt
->getCond()))
3712 write_then
= extract_index(ass_then
->getLHS());
3713 write_else
= extract_index(ass_else
->getLHS());
3715 equal
= isl_multi_pw_aff_plain_is_equal(write_then
, write_else
);
3716 isl_multi_pw_aff_free(write_else
);
3717 if (equal
< 0 || !equal
) {
3718 isl_multi_pw_aff_free(write_then
);
3722 nesting_enabled
= allow_nested
;
3723 pa
= extract_condition(stmt
->getCond());
3724 nesting_enabled
= save_nesting
;
3725 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
3726 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
3727 index
= isl_multi_pw_aff_from_pw_aff(pa
);
3729 pe_cond
= pet_expr_from_index(index
);
3731 pe_then
= extract_expr(ass_then
->getRHS());
3732 pe_then
= pet_expr_restrict(pe_then
, cond
);
3733 pe_else
= extract_expr(ass_else
->getRHS());
3734 pe_else
= pet_expr_restrict(pe_else
, comp
);
3736 pe
= pet_expr_new_ternary(pe_cond
, pe_then
, pe_else
);
3737 type_size
= get_type_size(ass_then
->getType(), ast_context
);
3738 pe_write
= pet_expr_from_index_and_depth(type_size
, write_then
,
3739 extract_depth(write_then
));
3740 pe_write
= pet_expr_access_set_write(pe_write
, 1);
3741 pe_write
= pet_expr_access_set_read(pe_write
, 0);
3742 pe
= pet_expr_new_binary(type_size
, pet_op_assign
, pe_write
, pe
);
3743 return extract(pe
, stmt
->getSourceRange(), false);
3746 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3747 * evaluating "cond" and writing the result to a virtual scalar,
3748 * as expressed by "index".
3750 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
, int stmt_nr
,
3751 __isl_take isl_multi_pw_aff
*index
)
3753 pet_expr
*expr
, *write
;
3754 struct pet_stmt
*ps
;
3755 SourceLocation loc
= cond
->getLocStart();
3756 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3758 write
= pet_expr_from_index(index
);
3759 write
= pet_expr_access_set_write(write
, 1);
3760 write
= pet_expr_access_set_read(write
, 0);
3761 expr
= extract_expr(cond
);
3762 expr
= resolve_nested(expr
);
3763 expr
= pet_expr_new_binary(1, pet_op_assign
, write
, expr
);
3764 ps
= pet_stmt_from_pet_expr(line
, NULL
, stmt_nr
, expr
);
3765 return pet_scop_from_pet_stmt(ctx
, ps
);
3769 static __isl_give pet_expr
*embed_access(__isl_take pet_expr
*expr
,
3773 /* Precompose the access relation and the index expression associated
3774 * to "expr" with the function pointed to by "user",
3775 * thereby embedding the access relation in the domain of this function.
3776 * The initial domain of the access relation and the index expression
3777 * is the zero-dimensional domain.
3779 static __isl_give pet_expr
*embed_access(__isl_take pet_expr
*expr
, void *user
)
3781 isl_multi_aff
*ma
= (isl_multi_aff
*) user
;
3783 return pet_expr_access_pullback_multi_aff(expr
, isl_multi_aff_copy(ma
));
3786 /* Precompose all access relations in "expr" with "ma", thereby
3787 * embedding them in the domain of "ma".
3789 static __isl_give pet_expr
*embed(__isl_take pet_expr
*expr
,
3790 __isl_keep isl_multi_aff
*ma
)
3792 return pet_expr_map_access(expr
, &embed_access
, ma
);
3795 /* For each nested access parameter in the domain of "stmt",
3796 * construct a corresponding pet_expr, place it before the original
3797 * elements in stmt->args and record its position in "param2pos".
3798 * n is the number of nested access parameters.
3800 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
3801 std::map
<int,int> ¶m2pos
)
3808 n_arg
= stmt
->n_arg
;
3809 args
= isl_calloc_array(ctx
, pet_expr
*, n
+ n_arg
);
3813 space
= isl_set_get_space(stmt
->domain
);
3814 n_arg
= extract_nested(space
, 0, args
, param2pos
);
3815 isl_space_free(space
);
3820 for (i
= 0; i
< stmt
->n_arg
; ++i
)
3821 args
[n_arg
+ i
] = stmt
->args
[i
];
3824 stmt
->n_arg
+= n_arg
;
3829 for (i
= 0; i
< n
; ++i
)
3830 pet_expr_free(args
[i
]);
3833 pet_stmt_free(stmt
);
3837 /* Check whether any of the arguments i of "stmt" starting at position "n"
3838 * is equal to one of the first "n" arguments j.
3839 * If so, combine the constraints on arguments i and j and remove
3842 static struct pet_stmt
*remove_duplicate_arguments(struct pet_stmt
*stmt
, int n
)
3851 if (n
== stmt
->n_arg
)
3854 map
= isl_set_unwrap(stmt
->domain
);
3856 for (i
= stmt
->n_arg
- 1; i
>= n
; --i
) {
3857 for (j
= 0; j
< n
; ++j
)
3858 if (pet_expr_is_equal(stmt
->args
[i
], stmt
->args
[j
]))
3863 map
= isl_map_equate(map
, isl_dim_out
, i
, isl_dim_out
, j
);
3864 map
= isl_map_project_out(map
, isl_dim_out
, i
, 1);
3866 pet_expr_free(stmt
->args
[i
]);
3867 for (j
= i
; j
+ 1 < stmt
->n_arg
; ++j
)
3868 stmt
->args
[j
] = stmt
->args
[j
+ 1];
3872 stmt
->domain
= isl_map_wrap(map
);
3877 pet_stmt_free(stmt
);
3881 /* Look for parameters in the iteration domain of "stmt" that
3882 * refer to nested accesses. In particular, these are
3883 * parameters with either no name or with name "__pet_expr".
3885 * If there are any such parameters, then as many extra variables
3886 * (after identifying identical nested accesses) are inserted in the
3887 * range of the map wrapped inside the domain, before the original variables.
3888 * If the original domain is not a wrapped map, then a new wrapped
3889 * map is created with zero output dimensions.
3890 * The parameters are then equated to the corresponding output dimensions
3891 * and subsequently projected out, from the iteration domain,
3892 * the schedule and the access relations.
3893 * For each of the output dimensions, a corresponding argument
3894 * expression is inserted. Initially they are created with
3895 * a zero-dimensional domain, so they have to be embedded
3896 * in the current iteration domain.
3897 * param2pos maps the position of the parameter to the position
3898 * of the corresponding output dimension in the wrapped map.
3900 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3908 std::map
<int,int> param2pos
;
3913 n
= pet_nested_n_in_set(stmt
->domain
);
3917 n_arg
= stmt
->n_arg
;
3918 stmt
= extract_nested(stmt
, n
, param2pos
);
3922 n
= stmt
->n_arg
- n_arg
;
3923 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3924 if (isl_set_is_wrapping(stmt
->domain
))
3925 map
= isl_set_unwrap(stmt
->domain
);
3927 map
= isl_map_from_domain(stmt
->domain
);
3928 map
= isl_map_insert_dims(map
, isl_dim_out
, 0, n
);
3930 for (int i
= nparam
- 1; i
>= 0; --i
) {
3933 if (!pet_nested_in_map(map
, i
))
3936 id
= pet_expr_access_get_id(stmt
->args
[param2pos
[i
]]);
3937 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3938 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3940 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3943 stmt
->domain
= isl_map_wrap(map
);
3945 space
= isl_space_unwrap(isl_set_get_space(stmt
->domain
));
3946 space
= isl_space_from_domain(isl_space_domain(space
));
3947 ma
= isl_multi_aff_zero(space
);
3948 for (int pos
= 0; pos
< n
; ++pos
)
3949 stmt
->args
[pos
] = embed(stmt
->args
[pos
], ma
);
3950 isl_multi_aff_free(ma
);
3952 stmt
= pet_stmt_remove_nested_parameters(stmt
);
3953 stmt
= remove_duplicate_arguments(stmt
, n
);
3958 /* For each statement in "scop", move the parameters that correspond
3959 * to nested access into the ranges of the domains and create
3960 * corresponding argument expressions.
3962 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3967 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3968 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3969 if (!scop
->stmts
[i
])
3975 pet_scop_free(scop
);
3979 /* Given an access expression "expr", is the variable accessed by
3980 * "expr" assigned anywhere inside "scop"?
3982 static bool is_assigned(__isl_keep pet_expr
*expr
, pet_scop
*scop
)
3984 bool assigned
= false;
3987 id
= pet_expr_access_get_id(expr
);
3988 assigned
= pet_scop_writes(scop
, id
);
3994 /* Are all nested access parameters in "pa" allowed given "scop".
3995 * In particular, is none of them written by anywhere inside "scop".
3997 * If "scop" has any skip conditions, then no nested access parameters
3998 * are allowed. In particular, if there is any nested access in a guard
3999 * for a piece of code containing a "continue", then we want to introduce
4000 * a separate statement for evaluating this guard so that we can express
4001 * that the result is false for all previous iterations.
4003 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
4010 if (!pet_nested_any_in_pw_aff(pa
))
4013 if (pet_scop_has_skip(scop
, pet_skip_now
))
4016 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
4017 for (int i
= 0; i
< nparam
; ++i
) {
4018 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
4022 if (!pet_nested_in_id(id
)) {
4027 expr
= extract_expr(id
);
4028 allowed
= pet_expr_get_type(expr
) == pet_expr_access
&&
4029 !is_assigned(expr
, scop
);
4031 pet_expr_free(expr
);
4041 /* Construct a pet_scop for a non-affine if statement.
4043 * We create a separate statement that writes the result
4044 * of the non-affine condition to a virtual scalar.
4045 * A constraint requiring the value of this virtual scalar to be one
4046 * is added to the iteration domains of the then branch.
4047 * Similarly, a constraint requiring the value of this virtual scalar
4048 * to be zero is added to the iteration domains of the else branch, if any.
4049 * We adjust the schedules to ensure that the virtual scalar is written
4050 * before it is read.
4052 * If there are any breaks or continues in the then and/or else
4053 * branches, then we may have to compute a new skip condition.
4054 * This is handled using a pet_skip_info object.
4055 * On initialization, the object checks if skip conditions need
4056 * to be computed. If so, it does so in pet_skip_info_if_extract_index and
4057 * adds them in pet_skip_info_if_add.
4059 struct pet_scop
*PetScan::extract_non_affine_if(Expr
*cond
,
4060 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
4061 bool have_else
, int stmt_id
)
4063 struct pet_scop
*scop
;
4064 isl_multi_pw_aff
*test_index
;
4066 int save_n_stmt
= n_stmt
;
4068 test_index
= pet_create_test_index(ctx
, n_test
++);
4070 scop
= extract_non_affine_condition(cond
, n_stmt
++,
4071 isl_multi_pw_aff_copy(test_index
));
4072 n_stmt
= save_n_stmt
;
4073 scop
= scop_add_array(scop
, test_index
, ast_context
);
4076 pet_skip_info_if_init(&skip
, ctx
, scop_then
, scop_else
, have_else
, 0);
4077 int_size
= ast_context
.getTypeInfo(ast_context
.IntTy
).first
/ 8;
4078 pet_skip_info_if_extract_index(&skip
, test_index
, int_size
,
4081 scop
= pet_scop_prefix(scop
, 0);
4082 scop_then
= pet_scop_prefix(scop_then
, 1);
4083 scop_then
= pet_scop_filter(scop_then
,
4084 isl_multi_pw_aff_copy(test_index
), 1);
4086 scop_else
= pet_scop_prefix(scop_else
, 1);
4087 scop_else
= pet_scop_filter(scop_else
, test_index
, 0);
4088 scop_then
= pet_scop_add_par(ctx
, scop_then
, scop_else
);
4090 isl_multi_pw_aff_free(test_index
);
4092 scop
= pet_scop_add_seq(ctx
, scop
, scop_then
);
4094 scop
= pet_skip_info_if_add(&skip
, scop
, 2);
4099 /* Construct a pet_scop for an if statement.
4101 * If the condition fits the pattern of a conditional assignment,
4102 * then it is handled by extract_conditional_assignment.
4103 * Otherwise, we do the following.
4105 * If the condition is affine, then the condition is added
4106 * to the iteration domains of the then branch, while the
4107 * opposite of the condition in added to the iteration domains
4108 * of the else branch, if any.
4109 * We allow the condition to be dynamic, i.e., to refer to
4110 * scalars or array elements that may be written to outside
4111 * of the given if statement. These nested accesses are then represented
4112 * as output dimensions in the wrapping iteration domain.
4113 * If it is also written _inside_ the then or else branch, then
4114 * we treat the condition as non-affine.
4115 * As explained in extract_non_affine_if, this will introduce
4116 * an extra statement.
4117 * For aesthetic reasons, we want this statement to have a statement
4118 * number that is lower than those of the then and else branches.
4119 * In order to evaluate if we will need such a statement, however, we
4120 * first construct scops for the then and else branches.
4121 * We therefore reserve a statement number if we might have to
4122 * introduce such an extra statement.
4124 * If the condition is not affine, then the scop is created in
4125 * extract_non_affine_if.
4127 * If there are any breaks or continues in the then and/or else
4128 * branches, then we may have to compute a new skip condition.
4129 * This is handled using a pet_skip_info object.
4130 * On initialization, the object checks if skip conditions need
4131 * to be computed. If so, it does so in pet_skip_info_if_extract_cond and
4132 * adds them in pet_skip_info_if_add.
4134 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
4136 struct pet_scop
*scop_then
, *scop_else
= NULL
, *scop
;
4143 clear_assignments
clear(assigned_value
);
4144 clear
.TraverseStmt(stmt
->getThen());
4145 if (stmt
->getElse())
4146 clear
.TraverseStmt(stmt
->getElse());
4148 scop
= extract_conditional_assignment(stmt
);
4152 cond
= try_extract_nested_condition(stmt
->getCond());
4153 if (allow_nested
&& (!cond
|| pet_nested_any_in_pw_aff(cond
)))
4157 assigned_value_cache
cache(assigned_value
);
4158 scop_then
= extract(stmt
->getThen());
4161 if (stmt
->getElse()) {
4162 assigned_value_cache
cache(assigned_value
);
4163 scop_else
= extract(stmt
->getElse());
4164 if (options
->autodetect
) {
4165 if (scop_then
&& !scop_else
) {
4167 isl_pw_aff_free(cond
);
4170 if (!scop_then
&& scop_else
) {
4172 isl_pw_aff_free(cond
);
4179 (!is_nested_allowed(cond
, scop_then
) ||
4180 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
4181 isl_pw_aff_free(cond
);
4184 if (allow_nested
&& !cond
)
4185 return extract_non_affine_if(stmt
->getCond(), scop_then
,
4186 scop_else
, stmt
->getElse(), stmt_id
);
4189 cond
= extract_condition(stmt
->getCond());
4192 pet_skip_info_if_init(&skip
, ctx
, scop_then
, scop_else
,
4193 stmt
->getElse() != NULL
, 1);
4194 pet_skip_info_if_extract_cond(&skip
, cond
, int_size
, &n_stmt
, &n_test
);
4196 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
4197 set
= isl_pw_aff_non_zero_set(cond
);
4198 scop
= pet_scop_restrict(scop_then
, isl_set_params(isl_set_copy(set
)));
4200 if (stmt
->getElse()) {
4201 set
= isl_set_subtract(isl_set_copy(valid
), set
);
4202 scop_else
= pet_scop_restrict(scop_else
, isl_set_params(set
));
4203 scop
= pet_scop_add_par(ctx
, scop
, scop_else
);
4206 scop
= resolve_nested(scop
);
4207 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid
));
4209 if (pet_skip_info_has_skip(&skip
))
4210 scop
= pet_scop_prefix(scop
, 0);
4211 scop
= pet_skip_info_if_add(&skip
, scop
, 1);
4216 /* Try and construct a pet_scop for a label statement.
4217 * We currently only allow labels on expression statements.
4219 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
4224 sub
= stmt
->getSubStmt();
4225 if (!isa
<Expr
>(sub
)) {
4230 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
4232 return extract(extract_expr(cast
<Expr
>(sub
)), stmt
->getSourceRange(),
4236 /* Return a one-dimensional multi piecewise affine expression that is equal
4237 * to the constant 1 and is defined over a zero-dimensional domain.
4239 static __isl_give isl_multi_pw_aff
*one_mpa(isl_ctx
*ctx
)
4242 isl_local_space
*ls
;
4245 space
= isl_space_set_alloc(ctx
, 0, 0);
4246 ls
= isl_local_space_from_space(space
);
4247 aff
= isl_aff_zero_on_domain(ls
);
4248 aff
= isl_aff_set_constant_si(aff
, 1);
4250 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
4253 /* Construct a pet_scop for a continue statement.
4255 * We simply create an empty scop with a universal pet_skip_now
4256 * skip condition. This skip condition will then be taken into
4257 * account by the enclosing loop construct, possibly after
4258 * being incorporated into outer skip conditions.
4260 struct pet_scop
*PetScan::extract(ContinueStmt
*stmt
)
4264 scop
= pet_scop_empty(ctx
);
4268 scop
= pet_scop_set_skip(scop
, pet_skip_now
, one_mpa(ctx
));
4273 /* Construct a pet_scop for a break statement.
4275 * We simply create an empty scop with both a universal pet_skip_now
4276 * skip condition and a universal pet_skip_later skip condition.
4277 * These skip conditions will then be taken into
4278 * account by the enclosing loop construct, possibly after
4279 * being incorporated into outer skip conditions.
4281 struct pet_scop
*PetScan::extract(BreakStmt
*stmt
)
4284 isl_multi_pw_aff
*skip
;
4286 scop
= pet_scop_empty(ctx
);
4290 skip
= one_mpa(ctx
);
4291 scop
= pet_scop_set_skip(scop
, pet_skip_now
,
4292 isl_multi_pw_aff_copy(skip
));
4293 scop
= pet_scop_set_skip(scop
, pet_skip_later
, skip
);
4298 /* Try and construct a pet_scop corresponding to "stmt".
4300 * If "stmt" is a compound statement, then "skip_declarations"
4301 * indicates whether we should skip initial declarations in the
4302 * compound statement.
4304 * If the constructed pet_scop is not a (possibly) partial representation
4305 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4306 * In particular, if skip_declarations is set, then we may have skipped
4307 * declarations inside "stmt" and so the pet_scop may not represent
4308 * the entire "stmt".
4309 * Note that this function may be called with "stmt" referring to the entire
4310 * body of the function, including the outer braces. In such cases,
4311 * skip_declarations will be set and the braces will not be taken into
4312 * account in scop->start and scop->end.
4314 struct pet_scop
*PetScan::extract(Stmt
*stmt
, bool skip_declarations
)
4316 struct pet_scop
*scop
;
4318 if (isa
<Expr
>(stmt
))
4319 return extract(extract_expr(cast
<Expr
>(stmt
)),
4320 stmt
->getSourceRange(), true);
4322 switch (stmt
->getStmtClass()) {
4323 case Stmt::WhileStmtClass
:
4324 scop
= extract(cast
<WhileStmt
>(stmt
));
4326 case Stmt::ForStmtClass
:
4327 scop
= extract_for(cast
<ForStmt
>(stmt
));
4329 case Stmt::IfStmtClass
:
4330 scop
= extract(cast
<IfStmt
>(stmt
));
4332 case Stmt::CompoundStmtClass
:
4333 scop
= extract(cast
<CompoundStmt
>(stmt
), skip_declarations
);
4335 case Stmt::LabelStmtClass
:
4336 scop
= extract(cast
<LabelStmt
>(stmt
));
4338 case Stmt::ContinueStmtClass
:
4339 scop
= extract(cast
<ContinueStmt
>(stmt
));
4341 case Stmt::BreakStmtClass
:
4342 scop
= extract(cast
<BreakStmt
>(stmt
));
4344 case Stmt::DeclStmtClass
:
4345 scop
= extract(cast
<DeclStmt
>(stmt
));
4352 if (partial
|| skip_declarations
)
4355 scop
= update_scop_start_end(scop
, stmt
->getSourceRange(), false);
4360 /* Extract a clone of the kill statement in "scop".
4361 * "scop" is expected to have been created from a DeclStmt
4362 * and should have the kill as its first statement.
4364 struct pet_stmt
*PetScan::extract_kill(struct pet_scop
*scop
)
4367 struct pet_stmt
*stmt
;
4368 isl_multi_pw_aff
*index
;
4374 if (scop
->n_stmt
< 1)
4375 isl_die(ctx
, isl_error_internal
,
4376 "expecting at least one statement", return NULL
);
4377 stmt
= scop
->stmts
[0];
4378 if (!pet_stmt_is_kill(stmt
))
4379 isl_die(ctx
, isl_error_internal
,
4380 "expecting kill statement", return NULL
);
4382 arg
= pet_expr_get_arg(stmt
->body
, 0);
4383 index
= pet_expr_access_get_index(arg
);
4384 access
= pet_expr_access_get_access(arg
);
4386 index
= isl_multi_pw_aff_reset_tuple_id(index
, isl_dim_in
);
4387 access
= isl_map_reset_tuple_id(access
, isl_dim_in
);
4388 kill
= pet_expr_kill_from_access_and_index(access
, index
);
4389 return pet_stmt_from_pet_expr(stmt
->line
, NULL
, n_stmt
++, kill
);
4392 /* Mark all arrays in "scop" as being exposed.
4394 static struct pet_scop
*mark_exposed(struct pet_scop
*scop
)
4398 for (int i
= 0; i
< scop
->n_array
; ++i
)
4399 scop
->arrays
[i
]->exposed
= 1;
4403 /* Try and construct a pet_scop corresponding to (part of)
4404 * a sequence of statements.
4406 * "block" is set if the sequence respresents the children of
4407 * a compound statement.
4408 * "skip_declarations" is set if we should skip initial declarations
4409 * in the sequence of statements.
4411 * If there are any breaks or continues in the individual statements,
4412 * then we may have to compute a new skip condition.
4413 * This is handled using a pet_skip_info object.
4414 * On initialization, the object checks if skip conditions need
4415 * to be computed. If so, it does so in pet_skip_info_seq_extract and
4416 * adds them in pet_skip_info_seq_add.
4418 * If "block" is set, then we need to insert kill statements at
4419 * the end of the block for any array that has been declared by
4420 * one of the statements in the sequence. Each of these declarations
4421 * results in the construction of a kill statement at the place
4422 * of the declaration, so we simply collect duplicates of
4423 * those kill statements and append these duplicates to the constructed scop.
4425 * If "block" is not set, then any array declared by one of the statements
4426 * in the sequence is marked as being exposed.
4428 * If autodetect is set, then we allow the extraction of only a subrange
4429 * of the sequence of statements. However, if there is at least one statement
4430 * for which we could not construct a scop and the final range contains
4431 * either no statements or at least one kill, then we discard the entire
4434 struct pet_scop
*PetScan::extract(StmtRange stmt_range
, bool block
,
4435 bool skip_declarations
)
4441 bool partial_range
= false;
4442 set
<struct pet_stmt
*> kills
;
4443 set
<struct pet_stmt
*>::iterator it
;
4445 int_size
= ast_context
.getTypeInfo(ast_context
.IntTy
).first
/ 8;
4447 scop
= pet_scop_empty(ctx
);
4448 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
4450 struct pet_scop
*scop_i
;
4452 if (scop
->n_stmt
== 0 && skip_declarations
&&
4453 child
->getStmtClass() == Stmt::DeclStmtClass
)
4456 scop_i
= extract(child
);
4457 if (scop
->n_stmt
!= 0 && partial
) {
4458 pet_scop_free(scop_i
);
4462 pet_skip_info_seq_init(&skip
, ctx
, scop
, scop_i
);
4463 pet_skip_info_seq_extract(&skip
, int_size
, &n_stmt
, &n_test
);
4464 if (pet_skip_info_has_skip(&skip
))
4465 scop_i
= pet_scop_prefix(scop_i
, 0);
4466 if (scop_i
&& child
->getStmtClass() == Stmt::DeclStmtClass
) {
4468 kills
.insert(extract_kill(scop_i
));
4470 scop_i
= mark_exposed(scop_i
);
4472 scop_i
= pet_scop_prefix(scop_i
, j
);
4473 if (options
->autodetect
) {
4475 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4477 partial_range
= true;
4478 if (scop
->n_stmt
!= 0 && !scop_i
)
4481 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4484 scop
= pet_skip_info_seq_add(&skip
, scop
, j
);
4486 if (partial
|| !scop
)
4490 for (it
= kills
.begin(); it
!= kills
.end(); ++it
) {
4492 scop_j
= pet_scop_from_pet_stmt(ctx
, *it
);
4493 scop_j
= pet_scop_prefix(scop_j
, j
);
4494 scop
= pet_scop_add_seq(ctx
, scop
, scop_j
);
4497 if (scop
&& partial_range
) {
4498 if (scop
->n_stmt
== 0 || kills
.size() != 0) {
4499 pet_scop_free(scop
);
4508 /* Check if the scop marked by the user is exactly this Stmt
4509 * or part of this Stmt.
4510 * If so, return a pet_scop corresponding to the marked region.
4511 * Otherwise, return NULL.
4513 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
4515 SourceManager
&SM
= PP
.getSourceManager();
4516 unsigned start_off
, end_off
;
4518 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
4519 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
4521 if (start_off
> loc
.end
)
4523 if (end_off
< loc
.start
)
4525 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
4526 return extract(stmt
);
4530 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
4531 Stmt
*child
= *start
;
4534 start_off
= getExpansionOffset(SM
, child
->getLocStart());
4535 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
4536 if (start_off
< loc
.start
&& end_off
>= loc
.end
)
4538 if (start_off
>= loc
.start
)
4543 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
4545 start_off
= SM
.getFileOffset(child
->getLocStart());
4546 if (start_off
>= loc
.end
)
4550 return extract(StmtRange(start
, end
), false, false);
4553 /* Set the size of index "pos" of "array" to "size".
4554 * In particular, add a constraint of the form
4558 * to array->extent and a constraint of the form
4562 * to array->context.
4564 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
4565 __isl_take isl_pw_aff
*size
)
4575 valid
= isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
)));
4576 array
->context
= isl_set_intersect(array
->context
, valid
);
4578 dim
= isl_set_get_space(array
->extent
);
4579 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
4580 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
4581 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
4582 index
= isl_pw_aff_alloc(univ
, aff
);
4584 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
4585 isl_set_dim(array
->extent
, isl_dim_set
));
4586 id
= isl_set_get_tuple_id(array
->extent
);
4587 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
4588 bound
= isl_pw_aff_lt_set(index
, size
);
4590 array
->extent
= isl_set_intersect(array
->extent
, bound
);
4592 if (!array
->context
|| !array
->extent
)
4597 pet_array_free(array
);
4601 /* Figure out the size of the array at position "pos" and all
4602 * subsequent positions from "type" and update "array" accordingly.
4604 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
4605 const Type
*type
, int pos
)
4607 const ArrayType
*atype
;
4613 if (type
->isPointerType()) {
4614 type
= type
->getPointeeType().getTypePtr();
4615 return set_upper_bounds(array
, type
, pos
+ 1);
4617 if (!type
->isArrayType())
4620 type
= type
->getCanonicalTypeInternal().getTypePtr();
4621 atype
= cast
<ArrayType
>(type
);
4623 if (type
->isConstantArrayType()) {
4624 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
4625 size
= extract_affine(ca
->getSize());
4626 array
= update_size(array
, pos
, size
);
4627 } else if (type
->isVariableArrayType()) {
4628 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
4629 size
= extract_affine(vla
->getSizeExpr());
4630 array
= update_size(array
, pos
, size
);
4633 type
= atype
->getElementType().getTypePtr();
4635 return set_upper_bounds(array
, type
, pos
+ 1);
4638 /* Is "T" the type of a variable length array with static size?
4640 static bool is_vla_with_static_size(QualType T
)
4642 const VariableArrayType
*vlatype
;
4644 if (!T
->isVariableArrayType())
4646 vlatype
= cast
<VariableArrayType
>(T
);
4647 return vlatype
->getSizeModifier() == VariableArrayType::Static
;
4650 /* Return the type of "decl" as an array.
4652 * In particular, if "decl" is a parameter declaration that
4653 * is a variable length array with a static size, then
4654 * return the original type (i.e., the variable length array).
4655 * Otherwise, return the type of decl.
4657 static QualType
get_array_type(ValueDecl
*decl
)
4662 parm
= dyn_cast
<ParmVarDecl
>(decl
);
4664 return decl
->getType();
4666 T
= parm
->getOriginalType();
4667 if (!is_vla_with_static_size(T
))
4668 return decl
->getType();
4672 /* Does "decl" have definition that we can keep track of in a pet_type?
4674 static bool has_printable_definition(RecordDecl
*decl
)
4676 if (!decl
->getDeclName())
4678 return decl
->getLexicalDeclContext() == decl
->getDeclContext();
4681 /* Construct and return a pet_array corresponding to the variable "decl".
4682 * In particular, initialize array->extent to
4684 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4686 * and then call set_upper_bounds to set the upper bounds on the indices
4687 * based on the type of the variable.
4689 * If the base type is that of a record with a top-level definition and
4690 * if "types" is not null, then the RecordDecl corresponding to the type
4691 * is added to "types".
4693 * If the base type is that of a record with no top-level definition,
4694 * then we replace it by "<subfield>".
4696 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
,
4697 lex_recorddecl_set
*types
)
4699 struct pet_array
*array
;
4700 QualType qt
= get_array_type(decl
);
4701 const Type
*type
= qt
.getTypePtr();
4702 int depth
= array_depth(type
);
4703 QualType base
= pet_clang_base_type(qt
);
4708 array
= isl_calloc_type(ctx
, struct pet_array
);
4712 id
= create_decl_id(ctx
, decl
);
4713 dim
= isl_space_set_alloc(ctx
, 0, depth
);
4714 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
4716 array
->extent
= isl_set_nat_universe(dim
);
4718 dim
= isl_space_params_alloc(ctx
, 0);
4719 array
->context
= isl_set_universe(dim
);
4721 array
= set_upper_bounds(array
, type
, 0);
4725 name
= base
.getAsString();
4727 if (types
&& base
->isRecordType()) {
4728 RecordDecl
*decl
= pet_clang_record_decl(base
);
4729 if (has_printable_definition(decl
))
4730 types
->insert(decl
);
4732 name
= "<subfield>";
4735 array
->element_type
= strdup(name
.c_str());
4736 array
->element_is_record
= base
->isRecordType();
4737 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
4742 /* Construct and return a pet_array corresponding to the sequence
4743 * of declarations "decls".
4744 * If the sequence contains a single declaration, then it corresponds
4745 * to a simple array access. Otherwise, it corresponds to a member access,
4746 * with the declaration for the substructure following that of the containing
4747 * structure in the sequence of declarations.
4748 * We start with the outermost substructure and then combine it with
4749 * information from the inner structures.
4751 * Additionally, keep track of all required types in "types".
4753 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
,
4754 vector
<ValueDecl
*> decls
, lex_recorddecl_set
*types
)
4756 struct pet_array
*array
;
4757 vector
<ValueDecl
*>::iterator it
;
4761 array
= extract_array(ctx
, *it
, types
);
4763 for (++it
; it
!= decls
.end(); ++it
) {
4764 struct pet_array
*parent
;
4765 const char *base_name
, *field_name
;
4769 array
= extract_array(ctx
, *it
, types
);
4771 return pet_array_free(parent
);
4773 base_name
= isl_set_get_tuple_name(parent
->extent
);
4774 field_name
= isl_set_get_tuple_name(array
->extent
);
4775 product_name
= member_access_name(ctx
, base_name
, field_name
);
4777 array
->extent
= isl_set_product(isl_set_copy(parent
->extent
),
4780 array
->extent
= isl_set_set_tuple_name(array
->extent
,
4782 array
->context
= isl_set_intersect(array
->context
,
4783 isl_set_copy(parent
->context
));
4785 pet_array_free(parent
);
4788 if (!array
->extent
|| !array
->context
|| !product_name
)
4789 return pet_array_free(array
);
4795 /* Add a pet_type corresponding to "decl" to "scop, provided
4796 * it is a member of "types" and it has not been added before
4797 * (i.e., it is not a member of "types_done".
4799 * Since we want the user to be able to print the types
4800 * in the order in which they appear in the scop, we need to
4801 * make sure that types of fields in a structure appear before
4802 * that structure. We therefore call ourselves recursively
4803 * on the types of all record subfields.
4805 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
4806 RecordDecl
*decl
, Preprocessor
&PP
, lex_recorddecl_set
&types
,
4807 lex_recorddecl_set
&types_done
)
4810 llvm::raw_string_ostream
S(s
);
4811 RecordDecl::field_iterator it
;
4813 if (types
.find(decl
) == types
.end())
4815 if (types_done
.find(decl
) != types_done
.end())
4818 for (it
= decl
->field_begin(); it
!= decl
->field_end(); ++it
) {
4820 QualType type
= it
->getType();
4822 if (!type
->isRecordType())
4824 record
= pet_clang_record_decl(type
);
4825 scop
= add_type(ctx
, scop
, record
, PP
, types
, types_done
);
4828 if (strlen(decl
->getName().str().c_str()) == 0)
4831 decl
->print(S
, PrintingPolicy(PP
.getLangOpts()));
4834 scop
->types
[scop
->n_type
] = pet_type_alloc(ctx
,
4835 decl
->getName().str().c_str(), s
.c_str());
4836 if (!scop
->types
[scop
->n_type
])
4837 return pet_scop_free(scop
);
4839 types_done
.insert(decl
);
4846 /* Construct a list of pet_arrays, one for each array (or scalar)
4847 * accessed inside "scop", add this list to "scop" and return the result.
4849 * The context of "scop" is updated with the intersection of
4850 * the contexts of all arrays, i.e., constraints on the parameters
4851 * that ensure that the arrays have a valid (non-negative) size.
4853 * If the any of the extracted arrays refers to a member access,
4854 * then also add the required types to "scop".
4856 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
4859 array_desc_set arrays
;
4860 array_desc_set::iterator it
;
4861 lex_recorddecl_set types
;
4862 lex_recorddecl_set types_done
;
4863 lex_recorddecl_set::iterator types_it
;
4865 struct pet_array
**scop_arrays
;
4870 pet_scop_collect_arrays(scop
, arrays
);
4871 if (arrays
.size() == 0)
4874 n_array
= scop
->n_array
;
4876 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
4877 n_array
+ arrays
.size());
4880 scop
->arrays
= scop_arrays
;
4882 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
4883 struct pet_array
*array
;
4884 array
= extract_array(ctx
, *it
, &types
);
4885 scop
->arrays
[n_array
+ i
] = array
;
4886 if (!scop
->arrays
[n_array
+ i
])
4889 scop
->context
= isl_set_intersect(scop
->context
,
4890 isl_set_copy(array
->context
));
4895 if (types
.size() == 0)
4898 scop
->types
= isl_alloc_array(ctx
, struct pet_type
*, types
.size());
4902 for (types_it
= types
.begin(); types_it
!= types
.end(); ++types_it
)
4903 scop
= add_type(ctx
, scop
, *types_it
, PP
, types
, types_done
);
4907 pet_scop_free(scop
);
4911 /* Bound all parameters in scop->context to the possible values
4912 * of the corresponding C variable.
4914 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
4921 n
= isl_set_dim(scop
->context
, isl_dim_param
);
4922 for (int i
= 0; i
< n
; ++i
) {
4926 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
4927 if (pet_nested_in_id(id
)) {
4929 isl_die(isl_set_get_ctx(scop
->context
),
4931 "unresolved nested parameter", goto error
);
4933 decl
= (ValueDecl
*) isl_id_get_user(id
);
4936 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
4944 pet_scop_free(scop
);
4948 /* Construct a pet_scop from the given function.
4950 * If the scop was delimited by scop and endscop pragmas, then we override
4951 * the file offsets by those derived from the pragmas.
4953 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
4958 stmt
= fd
->getBody();
4960 if (options
->autodetect
)
4961 scop
= extract(stmt
, true);
4964 scop
= pet_scop_update_start_end(scop
, loc
.start
, loc
.end
);
4966 scop
= pet_scop_detect_parameter_accesses(scop
);
4967 scop
= scan_arrays(scop
);
4968 scop
= add_parameter_bounds(scop
);
4969 scop
= pet_scop_gist(scop
, value_bounds
);