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>
57 #include "scop_plus.h"
63 using namespace clang
;
65 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
75 return pet_op_post_inc
;
77 return pet_op_post_dec
;
79 return pet_op_pre_inc
;
81 return pet_op_pre_dec
;
87 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
91 return pet_op_add_assign
;
93 return pet_op_sub_assign
;
95 return pet_op_mul_assign
;
97 return pet_op_div_assign
;
141 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
142 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
144 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
145 SourceLocation(), var
, false, var
->getInnerLocStart(),
146 var
->getType(), VK_LValue
);
148 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
149 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
151 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
152 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
156 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
158 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
159 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
163 /* Check if the element type corresponding to the given array type
164 * has a const qualifier.
166 static bool const_base(QualType qt
)
168 const Type
*type
= qt
.getTypePtr();
170 if (type
->isPointerType())
171 return const_base(type
->getPointeeType());
172 if (type
->isArrayType()) {
173 const ArrayType
*atype
;
174 type
= type
->getCanonicalTypeInternal().getTypePtr();
175 atype
= cast
<ArrayType
>(type
);
176 return const_base(atype
->getElementType());
179 return qt
.isConstQualified();
182 /* Mark "decl" as having an unknown value in "assigned_value".
184 * If no (known or unknown) value was assigned to "decl" before,
185 * then it may have been treated as a parameter before and may
186 * therefore appear in a value assigned to another variable.
187 * If so, this assignment needs to be turned into an unknown value too.
189 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
192 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
194 it
= assigned_value
.find(decl
);
196 assigned_value
[decl
] = NULL
;
198 if (it
!= assigned_value
.end())
201 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
202 isl_pw_aff
*pa
= it
->second
;
203 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
205 for (int i
= 0; i
< nparam
; ++i
) {
208 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
210 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
211 if (isl_id_get_user(id
) == decl
)
218 /* Look for any assignments to scalar variables in part of the parse
219 * tree and set assigned_value to NULL for each of them.
220 * Also reset assigned_value if the address of a scalar variable
221 * is being taken. As an exception, if the address is passed to a function
222 * that is declared to receive a const pointer, then assigned_value is
225 * This ensures that we won't use any previously stored value
226 * in the current subtree and its parents.
228 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
229 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
230 set
<UnaryOperator
*> skip
;
232 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
233 assigned_value(assigned_value
) {}
235 /* Check for "address of" operators whose value is passed
236 * to a const pointer argument and add them to "skip", so that
237 * we can skip them in VisitUnaryOperator.
239 bool VisitCallExpr(CallExpr
*expr
) {
241 fd
= expr
->getDirectCallee();
244 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
245 Expr
*arg
= expr
->getArg(i
);
247 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
248 ImplicitCastExpr
*ice
;
249 ice
= cast
<ImplicitCastExpr
>(arg
);
250 arg
= ice
->getSubExpr();
252 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
254 op
= cast
<UnaryOperator
>(arg
);
255 if (op
->getOpcode() != UO_AddrOf
)
257 if (const_base(fd
->getParamDecl(i
)->getType()))
263 bool VisitUnaryOperator(UnaryOperator
*expr
) {
268 switch (expr
->getOpcode()) {
278 if (skip
.find(expr
) != skip
.end())
281 arg
= expr
->getSubExpr();
282 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
284 ref
= cast
<DeclRefExpr
>(arg
);
285 decl
= ref
->getDecl();
286 clear_assignment(assigned_value
, decl
);
290 bool VisitBinaryOperator(BinaryOperator
*expr
) {
295 if (!expr
->isAssignmentOp())
297 lhs
= expr
->getLHS();
298 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
300 ref
= cast
<DeclRefExpr
>(lhs
);
301 decl
= ref
->getDecl();
302 clear_assignment(assigned_value
, decl
);
307 /* Keep a copy of the currently assigned values.
309 * Any variable that is assigned a value inside the current scope
310 * is removed again when we leave the scope (either because it wasn't
311 * stored in the cache or because it has a different value in the cache).
313 struct assigned_value_cache
{
314 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
315 map
<ValueDecl
*, isl_pw_aff
*> cache
;
317 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
318 assigned_value(assigned_value
), cache(assigned_value
) {}
319 ~assigned_value_cache() {
320 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
321 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
324 (cache
.find(it
->first
) != cache
.end() &&
325 cache
[it
->first
] != it
->second
))
326 cache
[it
->first
] = NULL
;
328 assigned_value
= cache
;
332 /* Insert an expression into the collection of expressions,
333 * provided it is not already in there.
334 * The isl_pw_affs are freed in the destructor.
336 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
338 std::set
<isl_pw_aff
*>::iterator it
;
340 if (expressions
.find(expr
) == expressions
.end())
341 expressions
.insert(expr
);
343 isl_pw_aff_free(expr
);
348 std::set
<isl_pw_aff
*>::iterator it
;
350 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
351 isl_pw_aff_free(*it
);
353 isl_union_map_free(value_bounds
);
356 /* Report a diagnostic, unless autodetect is set.
358 void PetScan::report(Stmt
*stmt
, unsigned id
)
360 if (options
->autodetect
)
363 SourceLocation loc
= stmt
->getLocStart();
364 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
365 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
368 /* Called if we found something we (currently) cannot handle.
369 * We'll provide more informative warnings later.
371 * We only actually complain if autodetect is false.
373 void PetScan::unsupported(Stmt
*stmt
)
375 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
376 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
381 /* Report a missing prototype, unless autodetect is set.
383 void PetScan::report_prototype_required(Stmt
*stmt
)
385 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
386 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
387 "prototype required");
391 /* Report a missing increment, unless autodetect is set.
393 void PetScan::report_missing_increment(Stmt
*stmt
)
395 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
396 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
397 "missing increment");
401 /* Extract an integer from "expr".
403 __isl_give isl_val
*PetScan::extract_int(isl_ctx
*ctx
, IntegerLiteral
*expr
)
405 const Type
*type
= expr
->getType().getTypePtr();
406 int is_signed
= type
->hasSignedIntegerRepresentation();
407 llvm::APInt val
= expr
->getValue();
408 int is_negative
= is_signed
&& val
.isNegative();
414 v
= extract_unsigned(ctx
, val
);
421 /* Extract an integer from "val", which is assumed to be non-negative.
423 __isl_give isl_val
*PetScan::extract_unsigned(isl_ctx
*ctx
,
424 const llvm::APInt
&val
)
427 const uint64_t *data
;
429 data
= val
.getRawData();
430 n
= val
.getNumWords();
431 return isl_val_int_from_chunks(ctx
, n
, sizeof(uint64_t), data
);
434 /* Extract an integer from "expr".
435 * Return NULL if "expr" does not (obviously) represent an integer.
437 __isl_give isl_val
*PetScan::extract_int(clang::ParenExpr
*expr
)
439 return extract_int(expr
->getSubExpr());
442 /* Extract an integer from "expr".
443 * Return NULL if "expr" does not (obviously) represent an integer.
445 __isl_give isl_val
*PetScan::extract_int(clang::Expr
*expr
)
447 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
448 return extract_int(ctx
, cast
<IntegerLiteral
>(expr
));
449 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
450 return extract_int(cast
<ParenExpr
>(expr
));
456 /* Extract an affine expression from the IntegerLiteral "expr".
458 __isl_give isl_pw_aff
*PetScan::extract_affine(IntegerLiteral
*expr
)
460 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
461 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
462 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
463 isl_set
*dom
= isl_set_universe(dim
);
466 v
= extract_int(expr
);
467 aff
= isl_aff_add_constant_val(aff
, v
);
469 return isl_pw_aff_alloc(dom
, aff
);
472 /* Extract an affine expression from the APInt "val", which is assumed
473 * to be non-negative.
475 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
477 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
478 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
479 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
480 isl_set
*dom
= isl_set_universe(dim
);
483 v
= extract_unsigned(ctx
, val
);
484 aff
= isl_aff_add_constant_val(aff
, v
);
486 return isl_pw_aff_alloc(dom
, aff
);
489 __isl_give isl_pw_aff
*PetScan::extract_affine(ImplicitCastExpr
*expr
)
491 return extract_affine(expr
->getSubExpr());
494 /* Return the number of bits needed to represent the type "qt",
495 * if it is an integer type. Otherwise return 0.
496 * If qt is signed then return the opposite of the number of bits.
498 static int get_type_size(QualType qt
, ASTContext
&ast_context
)
502 if (!qt
->isIntegerType())
505 size
= ast_context
.getIntWidth(qt
);
506 if (!qt
->isUnsignedIntegerType())
512 /* Return the number of bits needed to represent the type of "decl",
513 * if it is an integer type. Otherwise return 0.
514 * If qt is signed then return the opposite of the number of bits.
516 static int get_type_size(ValueDecl
*decl
)
518 return get_type_size(decl
->getType(), decl
->getASTContext());
521 /* Bound parameter "pos" of "set" to the possible values of "decl".
523 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
524 unsigned pos
, ValueDecl
*decl
)
530 ctx
= isl_set_get_ctx(set
);
531 type_size
= get_type_size(decl
);
533 isl_die(ctx
, isl_error_invalid
, "not an integer type",
534 return isl_set_free(set
));
536 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
537 bound
= isl_val_int_from_ui(ctx
, type_size
);
538 bound
= isl_val_2exp(bound
);
539 bound
= isl_val_sub_ui(bound
, 1);
540 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
, bound
);
542 bound
= isl_val_int_from_ui(ctx
, -type_size
- 1);
543 bound
= isl_val_2exp(bound
);
544 bound
= isl_val_sub_ui(bound
, 1);
545 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
,
546 isl_val_copy(bound
));
547 bound
= isl_val_neg(bound
);
548 bound
= isl_val_sub_ui(bound
, 1);
549 set
= isl_set_lower_bound_val(set
, isl_dim_param
, pos
, bound
);
555 /* Extract an affine expression from the DeclRefExpr "expr".
557 * If the variable has been assigned a value, then we check whether
558 * we know what (affine) value was assigned.
559 * If so, we return this value. Otherwise we convert "expr"
560 * to an extra parameter (provided nesting_enabled is set).
562 * Otherwise, we simply return an expression that is equal
563 * to a parameter corresponding to the referenced variable.
565 __isl_give isl_pw_aff
*PetScan::extract_affine(DeclRefExpr
*expr
)
567 ValueDecl
*decl
= expr
->getDecl();
568 const Type
*type
= decl
->getType().getTypePtr();
574 if (!type
->isIntegerType()) {
579 if (assigned_value
.find(decl
) != assigned_value
.end()) {
580 if (assigned_value
[decl
])
581 return isl_pw_aff_copy(assigned_value
[decl
]);
583 return nested_access(expr
);
586 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
587 dim
= isl_space_params_alloc(ctx
, 1);
589 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
591 dom
= isl_set_universe(isl_space_copy(dim
));
592 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
593 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
595 return isl_pw_aff_alloc(dom
, aff
);
598 /* Extract an affine expression from an integer division operation.
599 * In particular, if "expr" is lhs/rhs, then return
601 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
603 * The second argument (rhs) is required to be a (positive) integer constant.
605 __isl_give isl_pw_aff
*PetScan::extract_affine_div(BinaryOperator
*expr
)
608 isl_pw_aff
*rhs
, *lhs
;
610 rhs
= extract_affine(expr
->getRHS());
611 is_cst
= isl_pw_aff_is_cst(rhs
);
612 if (is_cst
< 0 || !is_cst
) {
613 isl_pw_aff_free(rhs
);
619 lhs
= extract_affine(expr
->getLHS());
621 return isl_pw_aff_tdiv_q(lhs
, rhs
);
624 /* Extract an affine expression from a modulo operation.
625 * In particular, if "expr" is lhs/rhs, then return
627 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
629 * The second argument (rhs) is required to be a (positive) integer constant.
631 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
634 isl_pw_aff
*rhs
, *lhs
;
636 rhs
= extract_affine(expr
->getRHS());
637 is_cst
= isl_pw_aff_is_cst(rhs
);
638 if (is_cst
< 0 || !is_cst
) {
639 isl_pw_aff_free(rhs
);
645 lhs
= extract_affine(expr
->getLHS());
647 return isl_pw_aff_tdiv_r(lhs
, rhs
);
650 /* Extract an affine expression from a multiplication operation.
651 * This is only allowed if at least one of the two arguments
652 * is a (piecewise) constant.
654 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
659 lhs
= extract_affine(expr
->getLHS());
660 rhs
= extract_affine(expr
->getRHS());
662 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
663 isl_pw_aff_free(lhs
);
664 isl_pw_aff_free(rhs
);
669 return isl_pw_aff_mul(lhs
, rhs
);
672 /* Extract an affine expression from an addition or subtraction operation.
674 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
679 lhs
= extract_affine(expr
->getLHS());
680 rhs
= extract_affine(expr
->getRHS());
682 switch (expr
->getOpcode()) {
684 return isl_pw_aff_add(lhs
, rhs
);
686 return isl_pw_aff_sub(lhs
, rhs
);
688 isl_pw_aff_free(lhs
);
689 isl_pw_aff_free(rhs
);
699 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
705 ctx
= isl_pw_aff_get_ctx(pwaff
);
706 mod
= isl_val_int_from_ui(ctx
, width
);
707 mod
= isl_val_2exp(mod
);
709 pwaff
= isl_pw_aff_mod_val(pwaff
, mod
);
714 /* Limit the domain of "pwaff" to those elements where the function
717 * 2^{width-1} <= pwaff < 2^{width-1}
719 static __isl_give isl_pw_aff
*avoid_overflow(__isl_take isl_pw_aff
*pwaff
,
724 isl_space
*space
= isl_pw_aff_get_domain_space(pwaff
);
725 isl_local_space
*ls
= isl_local_space_from_space(space
);
730 ctx
= isl_pw_aff_get_ctx(pwaff
);
731 v
= isl_val_int_from_ui(ctx
, width
- 1);
734 bound
= isl_aff_zero_on_domain(ls
);
735 bound
= isl_aff_add_constant_val(bound
, v
);
736 b
= isl_pw_aff_from_aff(bound
);
738 dom
= isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff
), isl_pw_aff_copy(b
));
739 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
741 b
= isl_pw_aff_neg(b
);
742 dom
= isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff
), b
);
743 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
748 /* Handle potential overflows on signed computations.
750 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
751 * the we adjust the domain of "pa" to avoid overflows.
753 __isl_give isl_pw_aff
*PetScan::signed_overflow(__isl_take isl_pw_aff
*pa
,
756 if (options
->signed_overflow
== PET_OVERFLOW_AVOID
)
757 pa
= avoid_overflow(pa
, width
);
762 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
764 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
765 __isl_take isl_set
*dom
)
768 pa
= isl_set_indicator_function(set
);
769 pa
= isl_pw_aff_intersect_domain(pa
, isl_set_coalesce(dom
));
773 /* Extract an affine expression from some binary operations.
774 * If the result of the expression is unsigned, then we wrap it
775 * based on the size of the type. Otherwise, we ensure that
776 * no overflow occurs.
778 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
783 switch (expr
->getOpcode()) {
786 res
= extract_affine_add(expr
);
789 res
= extract_affine_div(expr
);
792 res
= extract_affine_mod(expr
);
795 res
= extract_affine_mul(expr
);
805 return extract_condition(expr
);
811 width
= ast_context
.getIntWidth(expr
->getType());
812 if (expr
->getType()->isUnsignedIntegerType())
813 res
= wrap(res
, width
);
815 res
= signed_overflow(res
, width
);
820 /* Extract an affine expression from a negation operation.
822 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
824 if (expr
->getOpcode() == UO_Minus
)
825 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
826 if (expr
->getOpcode() == UO_LNot
)
827 return extract_condition(expr
);
833 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
835 return extract_affine(expr
->getSubExpr());
838 /* Extract an affine expression from some special function calls.
839 * In particular, we handle "min", "max", "ceild", "floord",
840 * "intMod", "intFloor" and "intCeil".
841 * In case of the latter five, the second argument needs to be
842 * a (positive) integer constant.
844 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
848 isl_pw_aff
*aff1
, *aff2
;
850 fd
= expr
->getDirectCallee();
856 name
= fd
->getDeclName().getAsString();
857 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
858 !(expr
->getNumArgs() == 2 && name
== "max") &&
859 !(expr
->getNumArgs() == 2 && name
== "intMod") &&
860 !(expr
->getNumArgs() == 2 && name
== "intFloor") &&
861 !(expr
->getNumArgs() == 2 && name
== "intCeil") &&
862 !(expr
->getNumArgs() == 2 && name
== "floord") &&
863 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
868 if (name
== "min" || name
== "max") {
869 aff1
= extract_affine(expr
->getArg(0));
870 aff2
= extract_affine(expr
->getArg(1));
873 aff1
= isl_pw_aff_min(aff1
, aff2
);
875 aff1
= isl_pw_aff_max(aff1
, aff2
);
876 } else if (name
== "intMod") {
878 Expr
*arg2
= expr
->getArg(1);
880 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
884 aff1
= extract_affine(expr
->getArg(0));
885 v
= extract_int(cast
<IntegerLiteral
>(arg2
));
886 aff1
= isl_pw_aff_mod_val(aff1
, v
);
887 } else if (name
== "floord" || name
== "ceild" ||
888 name
== "intFloor" || name
== "intCeil") {
890 Expr
*arg2
= expr
->getArg(1);
892 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
896 aff1
= extract_affine(expr
->getArg(0));
897 v
= extract_int(cast
<IntegerLiteral
>(arg2
));
898 aff1
= isl_pw_aff_scale_down_val(aff1
, v
);
899 if (name
== "floord" || name
== "intFloor")
900 aff1
= isl_pw_aff_floor(aff1
);
902 aff1
= isl_pw_aff_ceil(aff1
);
911 /* This method is called when we come across an access that is
912 * nested in what is supposed to be an affine expression.
913 * If nesting is allowed, we return a new parameter that corresponds
914 * to this nested access. Otherwise, we simply complain.
916 * Note that we currently don't allow nested accesses themselves
917 * to contain any nested accesses, so we check if we can extract
918 * the access without any nesting and complain if we can't.
920 * The new parameter is resolved in resolve_nested.
922 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
928 isl_multi_pw_aff
*index
;
930 if (!nesting_enabled
) {
935 allow_nested
= false;
936 index
= extract_index(expr
);
942 isl_multi_pw_aff_free(index
);
944 id
= pet_nested_clang_expr(ctx
, expr
);
945 dim
= isl_space_params_alloc(ctx
, 1);
947 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
949 dom
= isl_set_universe(isl_space_copy(dim
));
950 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
951 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
953 return isl_pw_aff_alloc(dom
, aff
);
956 /* Affine expressions are not supposed to contain array accesses,
957 * but if nesting is allowed, we return a parameter corresponding
958 * to the array access.
960 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
962 return nested_access(expr
);
965 /* Affine expressions are not supposed to contain member accesses,
966 * but if nesting is allowed, we return a parameter corresponding
967 * to the member access.
969 __isl_give isl_pw_aff
*PetScan::extract_affine(MemberExpr
*expr
)
971 return nested_access(expr
);
974 /* Extract an affine expression from a conditional operation.
976 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
978 isl_pw_aff
*cond
, *lhs
, *rhs
;
980 cond
= extract_condition(expr
->getCond());
981 lhs
= extract_affine(expr
->getTrueExpr());
982 rhs
= extract_affine(expr
->getFalseExpr());
984 return isl_pw_aff_cond(cond
, lhs
, rhs
);
987 /* Extract an affine expression, if possible, from "expr".
988 * Otherwise return NULL.
990 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
992 switch (expr
->getStmtClass()) {
993 case Stmt::ImplicitCastExprClass
:
994 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
995 case Stmt::IntegerLiteralClass
:
996 return extract_affine(cast
<IntegerLiteral
>(expr
));
997 case Stmt::DeclRefExprClass
:
998 return extract_affine(cast
<DeclRefExpr
>(expr
));
999 case Stmt::BinaryOperatorClass
:
1000 return extract_affine(cast
<BinaryOperator
>(expr
));
1001 case Stmt::UnaryOperatorClass
:
1002 return extract_affine(cast
<UnaryOperator
>(expr
));
1003 case Stmt::ParenExprClass
:
1004 return extract_affine(cast
<ParenExpr
>(expr
));
1005 case Stmt::CallExprClass
:
1006 return extract_affine(cast
<CallExpr
>(expr
));
1007 case Stmt::ArraySubscriptExprClass
:
1008 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
1009 case Stmt::MemberExprClass
:
1010 return extract_affine(cast
<MemberExpr
>(expr
));
1011 case Stmt::ConditionalOperatorClass
:
1012 return extract_affine(cast
<ConditionalOperator
>(expr
));
1019 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ImplicitCastExpr
*expr
)
1021 return extract_index(expr
->getSubExpr());
1024 /* Return the depth of an array of the given type.
1026 static int array_depth(const Type
*type
)
1028 if (type
->isPointerType())
1029 return 1 + array_depth(type
->getPointeeType().getTypePtr());
1030 if (type
->isArrayType()) {
1031 const ArrayType
*atype
;
1032 type
= type
->getCanonicalTypeInternal().getTypePtr();
1033 atype
= cast
<ArrayType
>(type
);
1034 return 1 + array_depth(atype
->getElementType().getTypePtr());
1039 /* Return the depth of the array accessed by the index expression "index".
1040 * If "index" is an affine expression, i.e., if it does not access
1041 * any array, then return 1.
1042 * If "index" represent a member access, i.e., if its range is a wrapped
1043 * relation, then return the sum of the depth of the array of structures
1044 * and that of the member inside the structure.
1046 static int extract_depth(__isl_keep isl_multi_pw_aff
*index
)
1054 if (isl_multi_pw_aff_range_is_wrapping(index
)) {
1055 int domain_depth
, range_depth
;
1056 isl_multi_pw_aff
*domain
, *range
;
1058 domain
= isl_multi_pw_aff_copy(index
);
1059 domain
= isl_multi_pw_aff_range_factor_domain(domain
);
1060 domain_depth
= extract_depth(domain
);
1061 isl_multi_pw_aff_free(domain
);
1062 range
= isl_multi_pw_aff_copy(index
);
1063 range
= isl_multi_pw_aff_range_factor_range(range
);
1064 range_depth
= extract_depth(range
);
1065 isl_multi_pw_aff_free(range
);
1067 return domain_depth
+ range_depth
;
1070 if (!isl_multi_pw_aff_has_tuple_id(index
, isl_dim_out
))
1073 id
= isl_multi_pw_aff_get_tuple_id(index
, isl_dim_out
);
1076 decl
= (ValueDecl
*) isl_id_get_user(id
);
1079 return array_depth(decl
->getType().getTypePtr());
1082 /* Extract an index expression from a reference to a variable.
1083 * If the variable has name "A", then the returned index expression
1088 __isl_give isl_multi_pw_aff
*PetScan::extract_index(DeclRefExpr
*expr
)
1090 return extract_index(expr
->getDecl());
1093 /* Extract an index expression from a variable.
1094 * If the variable has name "A", then the returned index expression
1099 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ValueDecl
*decl
)
1101 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
1102 isl_space
*space
= isl_space_alloc(ctx
, 0, 0, 0);
1104 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
1106 return isl_multi_pw_aff_zero(space
);
1109 /* Extract an index expression from an integer contant.
1110 * If the value of the constant is "v", then the returned access relation
1115 __isl_give isl_multi_pw_aff
*PetScan::extract_index(IntegerLiteral
*expr
)
1117 isl_multi_pw_aff
*mpa
;
1119 mpa
= isl_multi_pw_aff_from_pw_aff(extract_affine(expr
));
1120 mpa
= isl_multi_pw_aff_from_range(mpa
);
1124 /* Try and extract an index expression from the given Expr.
1125 * Return NULL if it doesn't work out.
1127 __isl_give isl_multi_pw_aff
*PetScan::extract_index(Expr
*expr
)
1129 switch (expr
->getStmtClass()) {
1130 case Stmt::ImplicitCastExprClass
:
1131 return extract_index(cast
<ImplicitCastExpr
>(expr
));
1132 case Stmt::DeclRefExprClass
:
1133 return extract_index(cast
<DeclRefExpr
>(expr
));
1134 case Stmt::ArraySubscriptExprClass
:
1135 return extract_index(cast
<ArraySubscriptExpr
>(expr
));
1136 case Stmt::IntegerLiteralClass
:
1137 return extract_index(cast
<IntegerLiteral
>(expr
));
1138 case Stmt::MemberExprClass
:
1139 return extract_index(cast
<MemberExpr
>(expr
));
1146 /* Given a partial index expression "base" and an extra index "index",
1147 * append the extra index to "base" and return the result.
1148 * Additionally, add the constraints that the extra index is non-negative.
1149 * If "index" represent a member access, i.e., if its range is a wrapped
1150 * relation, then we recursively extend the range of this nested relation.
1152 static __isl_give isl_multi_pw_aff
*subscript(__isl_take isl_multi_pw_aff
*base
,
1153 __isl_take isl_pw_aff
*index
)
1157 isl_multi_pw_aff
*access
;
1160 member_access
= isl_multi_pw_aff_range_is_wrapping(base
);
1161 if (member_access
< 0)
1163 if (member_access
) {
1164 isl_multi_pw_aff
*domain
, *range
;
1167 id
= isl_multi_pw_aff_get_tuple_id(base
, isl_dim_out
);
1168 domain
= isl_multi_pw_aff_copy(base
);
1169 domain
= isl_multi_pw_aff_range_factor_domain(domain
);
1170 range
= isl_multi_pw_aff_range_factor_range(base
);
1171 range
= subscript(range
, index
);
1172 access
= isl_multi_pw_aff_range_product(domain
, range
);
1173 access
= isl_multi_pw_aff_set_tuple_id(access
, isl_dim_out
, id
);
1177 id
= isl_multi_pw_aff_get_tuple_id(base
, isl_dim_set
);
1178 index
= isl_pw_aff_from_range(index
);
1179 domain
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(index
));
1180 index
= isl_pw_aff_intersect_domain(index
, domain
);
1181 access
= isl_multi_pw_aff_from_pw_aff(index
);
1182 access
= isl_multi_pw_aff_flat_range_product(base
, access
);
1183 access
= isl_multi_pw_aff_set_tuple_id(access
, isl_dim_set
, id
);
1187 isl_multi_pw_aff_free(base
);
1188 isl_pw_aff_free(index
);
1192 /* Extract an index expression from the given array subscript expression.
1193 * If nesting is allowed in general, then we turn it on while
1194 * examining the index expression.
1196 * We first extract an index expression from the base.
1197 * This will result in an index expression with a range that corresponds
1198 * to the earlier indices.
1199 * We then extract the current index, restrict its domain
1200 * to those values that result in a non-negative index and
1201 * append the index to the base index expression.
1203 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ArraySubscriptExpr
*expr
)
1205 Expr
*base
= expr
->getBase();
1206 Expr
*idx
= expr
->getIdx();
1208 isl_multi_pw_aff
*base_access
;
1209 isl_multi_pw_aff
*access
;
1210 bool save_nesting
= nesting_enabled
;
1212 nesting_enabled
= allow_nested
;
1214 base_access
= extract_index(base
);
1215 index
= extract_affine(idx
);
1217 nesting_enabled
= save_nesting
;
1219 access
= subscript(base_access
, index
);
1224 /* Construct a name for a member access by concatenating the name
1225 * of the array of structures and the member, separated by an underscore.
1227 * The caller is responsible for freeing the result.
1229 static char *member_access_name(isl_ctx
*ctx
, const char *base
,
1235 len
= strlen(base
) + 1 + strlen(field
);
1236 name
= isl_alloc_array(ctx
, char, len
+ 1);
1239 snprintf(name
, len
+ 1, "%s_%s", base
, field
);
1244 /* Given an index expression "base" for an element of an array of structures
1245 * and an expression "field" for the field member being accessed, construct
1246 * an index expression for an access to that member of the given structure.
1247 * In particular, take the range product of "base" and "field" and
1248 * attach a name to the result.
1250 static __isl_give isl_multi_pw_aff
*member(__isl_take isl_multi_pw_aff
*base
,
1251 __isl_take isl_multi_pw_aff
*field
)
1254 isl_multi_pw_aff
*access
;
1255 const char *base_name
, *field_name
;
1258 ctx
= isl_multi_pw_aff_get_ctx(base
);
1260 base_name
= isl_multi_pw_aff_get_tuple_name(base
, isl_dim_out
);
1261 field_name
= isl_multi_pw_aff_get_tuple_name(field
, isl_dim_out
);
1262 name
= member_access_name(ctx
, base_name
, field_name
);
1264 access
= isl_multi_pw_aff_range_product(base
, field
);
1266 access
= isl_multi_pw_aff_set_tuple_name(access
, isl_dim_out
, name
);
1272 /* Extract an index expression from a member expression.
1274 * If the base access (to the structure containing the member)
1279 * and the member is called "f", then the member access is of
1282 * [] -> A_f[A[..] -> f[]]
1284 * If the member access is to an anonymous struct, then simply return
1288 * If the member access in the source code is of the form
1292 * then it is treated as
1296 __isl_give isl_multi_pw_aff
*PetScan::extract_index(MemberExpr
*expr
)
1298 Expr
*base
= expr
->getBase();
1299 FieldDecl
*field
= cast
<FieldDecl
>(expr
->getMemberDecl());
1300 isl_multi_pw_aff
*base_access
, *field_access
;
1304 base_access
= extract_index(base
);
1306 if (expr
->isArrow()) {
1307 isl_space
*space
= isl_space_params_alloc(ctx
, 0);
1308 isl_local_space
*ls
= isl_local_space_from_space(space
);
1309 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
1310 isl_pw_aff
*index
= isl_pw_aff_from_aff(aff
);
1311 base_access
= subscript(base_access
, index
);
1314 if (field
->isAnonymousStructOrUnion())
1317 id
= isl_id_alloc(ctx
, field
->getName().str().c_str(), field
);
1318 space
= isl_multi_pw_aff_get_domain_space(base_access
);
1319 space
= isl_space_from_domain(space
);
1320 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
1321 field_access
= isl_multi_pw_aff_zero(space
);
1323 return member(base_access
, field_access
);
1326 /* Check if "expr" calls function "minmax" with two arguments and if so
1327 * make lhs and rhs refer to these two arguments.
1329 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
1335 if (expr
->getStmtClass() != Stmt::CallExprClass
)
1338 call
= cast
<CallExpr
>(expr
);
1339 fd
= call
->getDirectCallee();
1343 if (call
->getNumArgs() != 2)
1346 name
= fd
->getDeclName().getAsString();
1350 lhs
= call
->getArg(0);
1351 rhs
= call
->getArg(1);
1356 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1357 * lhs and rhs refer to the two arguments.
1359 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1361 return is_minmax(expr
, "min", lhs
, rhs
);
1364 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1365 * lhs and rhs refer to the two arguments.
1367 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1369 return is_minmax(expr
, "max", lhs
, rhs
);
1372 /* Return "lhs && rhs", with shortcut semantics.
1373 * That is, if lhs is false, then the result is defined even if rhs is not.
1374 * In practice, we compute lhs ? rhs : lhs.
1376 static __isl_give isl_pw_aff
*pw_aff_and_then(__isl_take isl_pw_aff
*lhs
,
1377 __isl_take isl_pw_aff
*rhs
)
1379 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), rhs
, lhs
);
1382 /* Return "lhs || rhs", with shortcut semantics.
1383 * That is, if lhs is true, then the result is defined even if rhs is not.
1384 * In practice, we compute lhs ? lhs : rhs.
1386 static __isl_give isl_pw_aff
*pw_aff_or_else(__isl_take isl_pw_aff
*lhs
,
1387 __isl_take isl_pw_aff
*rhs
)
1389 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), lhs
, rhs
);
1392 /* Extract an affine expressions representing the comparison "LHS op RHS"
1393 * "comp" is the original statement that "LHS op RHS" is derived from
1394 * and is used for diagnostics.
1396 * If the comparison is of the form
1400 * then the expression is constructed as the conjunction of
1405 * A similar optimization is performed for max(a,b) <= c.
1406 * We do this because that will lead to simpler representations
1407 * of the expression.
1408 * If isl is ever enhanced to explicitly deal with min and max expressions,
1409 * this optimization can be removed.
1411 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
1412 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
1419 enum pet_op_type type
;
1422 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
1424 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
1426 if (op
== BO_LT
|| op
== BO_LE
) {
1427 Expr
*expr1
, *expr2
;
1428 if (is_min(RHS
, expr1
, expr2
)) {
1429 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
1430 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
1431 return pet_and(lhs
, rhs
);
1433 if (is_max(LHS
, expr1
, expr2
)) {
1434 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
1435 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
1436 return pet_and(lhs
, rhs
);
1440 lhs
= extract_affine(LHS
);
1441 rhs
= extract_affine(RHS
);
1443 type
= BinaryOperatorKind2pet_op_type(op
);
1444 return pet_comparison(type
, lhs
, rhs
);
1447 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
1449 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1450 comp
->getRHS(), comp
);
1453 /* Extract an affine expression representing the negation (logical not)
1454 * of a subexpression.
1456 __isl_give isl_pw_aff
*PetScan::extract_boolean(UnaryOperator
*op
)
1460 cond
= extract_condition(op
->getSubExpr());
1461 return pet_not(cond
);
1464 /* Extract an affine expression representing the disjunction (logical or)
1465 * or conjunction (logical and) of two subexpressions.
1467 __isl_give isl_pw_aff
*PetScan::extract_boolean(BinaryOperator
*comp
)
1469 isl_pw_aff
*lhs
, *rhs
;
1471 lhs
= extract_condition(comp
->getLHS());
1472 rhs
= extract_condition(comp
->getRHS());
1474 switch (comp
->getOpcode()) {
1476 return pw_aff_and_then(lhs
, rhs
);
1478 return pw_aff_or_else(lhs
, rhs
);
1480 isl_pw_aff_free(lhs
);
1481 isl_pw_aff_free(rhs
);
1488 __isl_give isl_pw_aff
*PetScan::extract_condition(UnaryOperator
*expr
)
1490 switch (expr
->getOpcode()) {
1492 return extract_boolean(expr
);
1499 /* Extract the affine expression "expr != 0 ? 1 : 0".
1501 __isl_give isl_pw_aff
*PetScan::extract_implicit_condition(Expr
*expr
)
1506 res
= extract_affine(expr
);
1508 dom
= isl_pw_aff_domain(isl_pw_aff_copy(res
));
1509 set
= isl_pw_aff_non_zero_set(res
);
1511 res
= indicator_function(set
, dom
);
1516 /* Extract an affine expression from a boolean expression.
1517 * In particular, return the expression "expr ? 1 : 0".
1519 * If the expression doesn't look like a condition, we assume it
1520 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1522 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
1524 BinaryOperator
*comp
;
1527 isl_set
*u
= isl_set_universe(isl_space_params_alloc(ctx
, 0));
1528 return indicator_function(u
, isl_set_copy(u
));
1531 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1532 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1534 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1535 return extract_condition(cast
<UnaryOperator
>(expr
));
1537 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1538 return extract_implicit_condition(expr
);
1540 comp
= cast
<BinaryOperator
>(expr
);
1541 switch (comp
->getOpcode()) {
1548 return extract_comparison(comp
);
1551 return extract_boolean(comp
);
1553 return extract_implicit_condition(expr
);
1557 /* Construct a pet_expr representing a unary operator expression.
1559 __isl_give pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1562 enum pet_op_type op
;
1564 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1565 if (op
== pet_op_last
) {
1570 arg
= extract_expr(expr
->getSubExpr());
1572 if (expr
->isIncrementDecrementOp() &&
1573 pet_expr_get_type(arg
) == pet_expr_access
) {
1574 arg
= mark_write(arg
);
1575 arg
= pet_expr_access_set_read(arg
, 1);
1578 return pet_expr_new_unary(op
, arg
);
1581 /* Mark the given access pet_expr as a write.
1582 * If a scalar is being accessed, then mark its value
1583 * as unknown in assigned_value.
1585 __isl_give pet_expr
*PetScan::mark_write(__isl_take pet_expr
*access
)
1590 access
= pet_expr_access_set_write(access
, 1);
1591 access
= pet_expr_access_set_read(access
, 0);
1593 if (!access
|| !pet_expr_is_scalar_access(access
))
1596 id
= pet_expr_access_get_id(access
);
1597 decl
= (ValueDecl
*) isl_id_get_user(id
);
1598 clear_assignment(assigned_value
, decl
);
1604 /* Assign "rhs" to "lhs".
1606 * In particular, if "lhs" is a scalar variable, then mark
1607 * the variable as having been assigned. If, furthermore, "rhs"
1608 * is an affine expression, then keep track of this value in assigned_value
1609 * so that we can plug it in when we later come across the same variable.
1611 void PetScan::assign(__isl_keep pet_expr
*lhs
, Expr
*rhs
)
1619 if (!pet_expr_is_scalar_access(lhs
))
1622 id
= pet_expr_access_get_id(lhs
);
1623 decl
= (ValueDecl
*) isl_id_get_user(id
);
1626 pa
= try_extract_affine(rhs
);
1627 clear_assignment(assigned_value
, decl
);
1630 assigned_value
[decl
] = pa
;
1631 insert_expression(pa
);
1634 /* Construct a pet_expr representing a binary operator expression.
1636 * If the top level operator is an assignment and the LHS is an access,
1637 * then we mark that access as a write. If the operator is a compound
1638 * assignment, the access is marked as both a read and a write.
1640 * If "expr" assigns something to a scalar variable, then we mark
1641 * the variable as having been assigned. If, furthermore, the expression
1642 * is affine, then keep track of this value in assigned_value
1643 * so that we can plug it in when we later come across the same variable.
1645 __isl_give pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1648 pet_expr
*lhs
, *rhs
;
1649 enum pet_op_type op
;
1651 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1652 if (op
== pet_op_last
) {
1657 lhs
= extract_expr(expr
->getLHS());
1658 rhs
= extract_expr(expr
->getRHS());
1660 if (expr
->isAssignmentOp() &&
1661 pet_expr_get_type(lhs
) == pet_expr_access
) {
1662 lhs
= mark_write(lhs
);
1663 if (expr
->isCompoundAssignmentOp())
1664 lhs
= pet_expr_access_set_read(lhs
, 1);
1667 if (expr
->getOpcode() == BO_Assign
)
1668 assign(lhs
, expr
->getRHS());
1670 type_size
= get_type_size(expr
->getType(), ast_context
);
1671 return pet_expr_new_binary(type_size
, op
, lhs
, rhs
);
1674 /* Construct a pet_scop with a single statement killing the entire
1677 struct pet_scop
*PetScan::kill(Stmt
*stmt
, struct pet_array
*array
)
1681 isl_multi_pw_aff
*index
;
1687 access
= isl_map_from_range(isl_set_copy(array
->extent
));
1688 id
= isl_set_get_tuple_id(array
->extent
);
1689 space
= isl_space_alloc(ctx
, 0, 0, 0);
1690 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
1691 index
= isl_multi_pw_aff_zero(space
);
1692 expr
= pet_expr_kill_from_access_and_index(access
, index
);
1693 return extract(stmt
, expr
);
1696 /* Construct a pet_scop for a (single) variable declaration.
1698 * The scop contains the variable being declared (as an array)
1699 * and a statement killing the array.
1701 * If the variable is initialized in the AST, then the scop
1702 * also contains an assignment to the variable.
1704 struct pet_scop
*PetScan::extract(DeclStmt
*stmt
)
1709 pet_expr
*lhs
, *rhs
, *pe
;
1710 struct pet_scop
*scop_decl
, *scop
;
1711 struct pet_array
*array
;
1713 if (!stmt
->isSingleDecl()) {
1718 decl
= stmt
->getSingleDecl();
1719 vd
= cast
<VarDecl
>(decl
);
1721 array
= extract_array(ctx
, vd
, NULL
);
1723 array
->declared
= 1;
1724 scop_decl
= kill(stmt
, array
);
1725 scop_decl
= pet_scop_add_array(scop_decl
, array
);
1730 lhs
= extract_access_expr(vd
);
1731 rhs
= extract_expr(vd
->getInit());
1733 lhs
= mark_write(lhs
);
1734 assign(lhs
, vd
->getInit());
1736 type_size
= get_type_size(vd
->getType(), ast_context
);
1737 pe
= pet_expr_new_binary(type_size
, pet_op_assign
, lhs
, rhs
);
1738 scop
= extract(stmt
, pe
);
1740 scop_decl
= pet_scop_prefix(scop_decl
, 0);
1741 scop
= pet_scop_prefix(scop
, 1);
1743 scop
= pet_scop_add_seq(ctx
, scop_decl
, scop
);
1748 /* Construct a pet_expr representing a conditional operation.
1750 * We first try to extract the condition as an affine expression.
1751 * If that fails, we construct a pet_expr tree representing the condition.
1753 __isl_give pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1755 pet_expr
*cond
, *lhs
, *rhs
;
1758 pa
= try_extract_affine(expr
->getCond());
1760 isl_multi_pw_aff
*test
= isl_multi_pw_aff_from_pw_aff(pa
);
1761 test
= isl_multi_pw_aff_from_range(test
);
1762 cond
= pet_expr_from_index(test
);
1764 cond
= extract_expr(expr
->getCond());
1765 lhs
= extract_expr(expr
->getTrueExpr());
1766 rhs
= extract_expr(expr
->getFalseExpr());
1768 return pet_expr_new_ternary(cond
, lhs
, rhs
);
1771 __isl_give pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1773 return extract_expr(expr
->getSubExpr());
1776 /* Construct a pet_expr representing a floating point value.
1778 * If the floating point literal does not appear in a macro,
1779 * then we use the original representation in the source code
1780 * as the string representation. Otherwise, we use the pretty
1781 * printer to produce a string representation.
1783 __isl_give pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1787 const LangOptions
&LO
= PP
.getLangOpts();
1788 SourceLocation loc
= expr
->getLocation();
1790 if (!loc
.isMacroID()) {
1791 SourceManager
&SM
= PP
.getSourceManager();
1792 unsigned len
= Lexer::MeasureTokenLength(loc
, SM
, LO
);
1793 s
= string(SM
.getCharacterData(loc
), len
);
1795 llvm::raw_string_ostream
S(s
);
1796 expr
->printPretty(S
, 0, PrintingPolicy(LO
));
1799 d
= expr
->getValueAsApproximateDouble();
1800 return pet_expr_new_double(ctx
, d
, s
.c_str());
1803 /* Convert the index expression "index" into an access pet_expr of type "qt".
1805 __isl_give pet_expr
*PetScan::extract_access_expr(QualType qt
,
1806 __isl_take isl_multi_pw_aff
*index
)
1812 depth
= extract_depth(index
);
1813 type_size
= get_type_size(qt
, ast_context
);
1815 pe
= pet_expr_from_index_and_depth(type_size
, index
, depth
);
1820 /* Extract an index expression from "expr" and then convert it into
1821 * an access pet_expr.
1823 __isl_give pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1825 return extract_access_expr(expr
->getType(), extract_index(expr
));
1828 /* Extract an index expression from "decl" and then convert it into
1829 * an access pet_expr.
1831 __isl_give pet_expr
*PetScan::extract_access_expr(ValueDecl
*decl
)
1833 return extract_access_expr(decl
->getType(), extract_index(decl
));
1836 __isl_give pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1838 return extract_expr(expr
->getSubExpr());
1841 /* Extract an assume statement from the argument "expr"
1842 * of a __pencil_assume statement.
1844 __isl_give pet_expr
*PetScan::extract_assume(Expr
*expr
)
1849 cond
= try_extract_affine_condition(expr
);
1851 res
= extract_expr(expr
);
1853 isl_multi_pw_aff
*index
;
1854 index
= isl_multi_pw_aff_from_pw_aff(cond
);
1855 index
= isl_multi_pw_aff_from_range(index
);
1856 res
= pet_expr_from_index(index
);
1858 return pet_expr_new_unary(pet_op_assume
, res
);
1861 /* Construct a pet_expr corresponding to the function call argument "expr".
1862 * The argument appears in position "pos" of a call to function "fd".
1864 * If we are passing along a pointer to an array element
1865 * or an entire row or even higher dimensional slice of an array,
1866 * then the function being called may write into the array.
1868 * We assume here that if the function is declared to take a pointer
1869 * to a const type, then the function will perform a read
1870 * and that otherwise, it will perform a write.
1872 __isl_give pet_expr
*PetScan::extract_argument(FunctionDecl
*fd
, int pos
,
1876 int is_addr
= 0, is_partial
= 0;
1879 if (expr
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1880 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(expr
);
1881 expr
= ice
->getSubExpr();
1883 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1884 UnaryOperator
*op
= cast
<UnaryOperator
>(expr
);
1885 if (op
->getOpcode() == UO_AddrOf
) {
1887 expr
= op
->getSubExpr();
1890 res
= extract_expr(expr
);
1893 sc
= expr
->getStmtClass();
1894 if ((sc
== Stmt::ArraySubscriptExprClass
||
1895 sc
== Stmt::MemberExprClass
) &&
1896 array_depth(expr
->getType().getTypePtr()) > 0)
1898 if ((is_addr
|| is_partial
) &&
1899 pet_expr_get_type(res
) == pet_expr_access
) {
1901 if (!fd
->hasPrototype()) {
1902 report_prototype_required(expr
);
1903 return pet_expr_free(res
);
1905 parm
= fd
->getParamDecl(pos
);
1906 if (!const_base(parm
->getType()))
1907 res
= mark_write(res
);
1911 res
= pet_expr_new_unary(pet_op_address_of
, res
);
1915 /* Construct a pet_expr representing a function call.
1917 * In the special case of a "call" to __pencil_assume,
1918 * construct an assume expression instead.
1920 __isl_give pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1922 pet_expr
*res
= NULL
;
1927 fd
= expr
->getDirectCallee();
1933 name
= fd
->getDeclName().getAsString();
1934 n_arg
= expr
->getNumArgs();
1936 if (n_arg
== 1 && name
== "__pencil_assume")
1937 return extract_assume(expr
->getArg(0));
1939 res
= pet_expr_new_call(ctx
, name
.c_str(), n_arg
);
1943 for (int i
= 0; i
< n_arg
; ++i
) {
1944 Expr
*arg
= expr
->getArg(i
);
1945 res
= pet_expr_set_arg(res
, i
,
1946 PetScan::extract_argument(fd
, i
, arg
));
1952 /* Construct a pet_expr representing a (C style) cast.
1954 __isl_give pet_expr
*PetScan::extract_expr(CStyleCastExpr
*expr
)
1959 arg
= extract_expr(expr
->getSubExpr());
1963 type
= expr
->getTypeAsWritten();
1964 return pet_expr_new_cast(type
.getAsString().c_str(), arg
);
1967 /* Construct a pet_expr representing an integer.
1969 __isl_give pet_expr
*PetScan::extract_expr(IntegerLiteral
*expr
)
1971 return pet_expr_new_int(extract_int(expr
));
1974 /* Try and construct a pet_expr representing "expr".
1976 __isl_give pet_expr
*PetScan::extract_expr(Expr
*expr
)
1978 switch (expr
->getStmtClass()) {
1979 case Stmt::UnaryOperatorClass
:
1980 return extract_expr(cast
<UnaryOperator
>(expr
));
1981 case Stmt::CompoundAssignOperatorClass
:
1982 case Stmt::BinaryOperatorClass
:
1983 return extract_expr(cast
<BinaryOperator
>(expr
));
1984 case Stmt::ImplicitCastExprClass
:
1985 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1986 case Stmt::ArraySubscriptExprClass
:
1987 case Stmt::DeclRefExprClass
:
1988 case Stmt::MemberExprClass
:
1989 return extract_access_expr(expr
);
1990 case Stmt::IntegerLiteralClass
:
1991 return extract_expr(cast
<IntegerLiteral
>(expr
));
1992 case Stmt::FloatingLiteralClass
:
1993 return extract_expr(cast
<FloatingLiteral
>(expr
));
1994 case Stmt::ParenExprClass
:
1995 return extract_expr(cast
<ParenExpr
>(expr
));
1996 case Stmt::ConditionalOperatorClass
:
1997 return extract_expr(cast
<ConditionalOperator
>(expr
));
1998 case Stmt::CallExprClass
:
1999 return extract_expr(cast
<CallExpr
>(expr
));
2000 case Stmt::CStyleCastExprClass
:
2001 return extract_expr(cast
<CStyleCastExpr
>(expr
));
2008 /* Check if the given initialization statement is an assignment.
2009 * If so, return that assignment. Otherwise return NULL.
2011 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
2013 BinaryOperator
*ass
;
2015 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
2018 ass
= cast
<BinaryOperator
>(init
);
2019 if (ass
->getOpcode() != BO_Assign
)
2025 /* Check if the given initialization statement is a declaration
2026 * of a single variable.
2027 * If so, return that declaration. Otherwise return NULL.
2029 Decl
*PetScan::initialization_declaration(Stmt
*init
)
2033 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
2036 decl
= cast
<DeclStmt
>(init
);
2038 if (!decl
->isSingleDecl())
2041 return decl
->getSingleDecl();
2044 /* Given the assignment operator in the initialization of a for loop,
2045 * extract the induction variable, i.e., the (integer)variable being
2048 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
2055 lhs
= init
->getLHS();
2056 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
2061 ref
= cast
<DeclRefExpr
>(lhs
);
2062 decl
= ref
->getDecl();
2063 type
= decl
->getType().getTypePtr();
2065 if (!type
->isIntegerType()) {
2073 /* Given the initialization statement of a for loop and the single
2074 * declaration in this initialization statement,
2075 * extract the induction variable, i.e., the (integer) variable being
2078 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
2082 vd
= cast
<VarDecl
>(decl
);
2084 const QualType type
= vd
->getType();
2085 if (!type
->isIntegerType()) {
2090 if (!vd
->getInit()) {
2098 /* Check that op is of the form iv++ or iv--.
2099 * Return an affine expression "1" or "-1" accordingly.
2101 __isl_give isl_pw_aff
*PetScan::extract_unary_increment(
2102 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
2109 if (!op
->isIncrementDecrementOp()) {
2114 sub
= op
->getSubExpr();
2115 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
2120 ref
= cast
<DeclRefExpr
>(sub
);
2121 if (ref
->getDecl() != iv
) {
2126 space
= isl_space_params_alloc(ctx
, 0);
2127 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2129 if (op
->isIncrementOp())
2130 aff
= isl_aff_add_constant_si(aff
, 1);
2132 aff
= isl_aff_add_constant_si(aff
, -1);
2134 return isl_pw_aff_from_aff(aff
);
2137 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
2138 * has a single constant expression, then put this constant in *user.
2139 * The caller is assumed to have checked that this function will
2140 * be called exactly once.
2142 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
2145 isl_val
**inc
= (isl_val
**)user
;
2148 if (isl_aff_is_cst(aff
))
2149 *inc
= isl_aff_get_constant_val(aff
);
2159 /* Check if op is of the form
2163 * and return inc as an affine expression.
2165 * We extract an affine expression from the RHS, subtract iv and return
2168 __isl_give isl_pw_aff
*PetScan::extract_binary_increment(BinaryOperator
*op
,
2169 clang::ValueDecl
*iv
)
2178 if (op
->getOpcode() != BO_Assign
) {
2184 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
2189 ref
= cast
<DeclRefExpr
>(lhs
);
2190 if (ref
->getDecl() != iv
) {
2195 val
= extract_affine(op
->getRHS());
2197 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
2199 dim
= isl_space_params_alloc(ctx
, 1);
2200 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2201 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2202 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2204 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
2209 /* Check that op is of the form iv += cst or iv -= cst
2210 * and return an affine expression corresponding oto cst or -cst accordingly.
2212 __isl_give isl_pw_aff
*PetScan::extract_compound_increment(
2213 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
2219 BinaryOperatorKind opcode
;
2221 opcode
= op
->getOpcode();
2222 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
2226 if (opcode
== BO_SubAssign
)
2230 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
2235 ref
= cast
<DeclRefExpr
>(lhs
);
2236 if (ref
->getDecl() != iv
) {
2241 val
= extract_affine(op
->getRHS());
2243 val
= isl_pw_aff_neg(val
);
2248 /* Check that the increment of the given for loop increments
2249 * (or decrements) the induction variable "iv" and return
2250 * the increment as an affine expression if successful.
2252 __isl_give isl_pw_aff
*PetScan::extract_increment(clang::ForStmt
*stmt
,
2255 Stmt
*inc
= stmt
->getInc();
2258 report_missing_increment(stmt
);
2262 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
2263 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
2264 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
2265 return extract_compound_increment(
2266 cast
<CompoundAssignOperator
>(inc
), iv
);
2267 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
2268 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
2274 /* Embed the given iteration domain in an extra outer loop
2275 * with induction variable "var".
2276 * If this variable appeared as a parameter in the constraints,
2277 * it is replaced by the new outermost dimension.
2279 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
2280 __isl_take isl_id
*var
)
2284 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
2285 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
2287 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
2288 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2295 /* Return those elements in the space of "cond" that come after
2296 * (based on "sign") an element in "cond".
2298 static __isl_give isl_set
*after(__isl_take isl_set
*cond
, int sign
)
2300 isl_map
*previous_to_this
;
2303 previous_to_this
= isl_map_lex_lt(isl_set_get_space(cond
));
2305 previous_to_this
= isl_map_lex_gt(isl_set_get_space(cond
));
2307 cond
= isl_set_apply(cond
, previous_to_this
);
2312 /* Create the infinite iteration domain
2314 * { [id] : id >= 0 }
2316 * If "scop" has an affine skip of type pet_skip_later,
2317 * then remove those iterations i that have an earlier iteration
2318 * where the skip condition is satisfied, meaning that iteration i
2320 * Since we are dealing with a loop without loop iterator,
2321 * the skip condition cannot refer to the current loop iterator and
2322 * so effectively, the returned set is of the form
2324 * { [0]; [id] : id >= 1 and not skip }
2326 static __isl_give isl_set
*infinite_domain(__isl_take isl_id
*id
,
2327 struct pet_scop
*scop
)
2329 isl_ctx
*ctx
= isl_id_get_ctx(id
);
2333 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
2334 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, id
);
2336 if (!pet_scop_has_affine_skip(scop
, pet_skip_later
))
2339 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
2340 skip
= embed(skip
, isl_id_copy(id
));
2341 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2342 domain
= isl_set_subtract(domain
, after(skip
, 1));
2347 /* Create an identity affine expression on the space containing "domain",
2348 * which is assumed to be one-dimensional.
2350 static __isl_give isl_aff
*identity_aff(__isl_keep isl_set
*domain
)
2352 isl_local_space
*ls
;
2354 ls
= isl_local_space_from_space(isl_set_get_space(domain
));
2355 return isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
2358 /* Create an affine expression that maps elements
2359 * of a single-dimensional array "id_test" to the previous element
2360 * (according to "inc"), provided this element belongs to "domain".
2361 * That is, create the affine expression
2363 * { id[x] -> id[x - inc] : x - inc in domain }
2365 static __isl_give isl_multi_pw_aff
*map_to_previous(__isl_take isl_id
*id_test
,
2366 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2369 isl_local_space
*ls
;
2371 isl_multi_pw_aff
*prev
;
2373 space
= isl_set_get_space(domain
);
2374 ls
= isl_local_space_from_space(space
);
2375 aff
= isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
2376 aff
= isl_aff_add_constant_val(aff
, isl_val_neg(inc
));
2377 prev
= isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
2378 domain
= isl_set_preimage_multi_pw_aff(domain
,
2379 isl_multi_pw_aff_copy(prev
));
2380 prev
= isl_multi_pw_aff_intersect_domain(prev
, domain
);
2381 prev
= isl_multi_pw_aff_set_tuple_id(prev
, isl_dim_out
, id_test
);
2386 /* Add an implication to "scop" expressing that if an element of
2387 * virtual array "id_test" has value "satisfied" then all previous elements
2388 * of this array also have that value. The set of previous elements
2389 * is bounded by "domain". If "sign" is negative then the iterator
2390 * is decreasing and we express that all subsequent array elements
2391 * (but still defined previously) have the same value.
2393 static struct pet_scop
*add_implication(struct pet_scop
*scop
,
2394 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
, int sign
,
2400 domain
= isl_set_set_tuple_id(domain
, id_test
);
2401 space
= isl_set_get_space(domain
);
2403 map
= isl_map_lex_ge(space
);
2405 map
= isl_map_lex_le(space
);
2406 map
= isl_map_intersect_range(map
, domain
);
2407 scop
= pet_scop_add_implication(scop
, map
, satisfied
);
2412 /* Add a filter to "scop" that imposes that it is only executed
2413 * when the variable identified by "id_test" has a zero value
2414 * for all previous iterations of "domain".
2416 * In particular, add a filter that imposes that the array
2417 * has a zero value at the previous iteration of domain and
2418 * add an implication that implies that it then has that
2419 * value for all previous iterations.
2421 static struct pet_scop
*scop_add_break(struct pet_scop
*scop
,
2422 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
,
2423 __isl_take isl_val
*inc
)
2425 isl_multi_pw_aff
*prev
;
2426 int sign
= isl_val_sgn(inc
);
2428 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
2429 scop
= add_implication(scop
, id_test
, domain
, sign
, 0);
2430 scop
= pet_scop_filter(scop
, prev
, 0);
2435 /* Construct a pet_scop for an infinite loop around the given body.
2437 * We extract a pet_scop for the body and then embed it in a loop with
2446 * If the body contains any break, then it is taken into
2447 * account in infinite_domain (if the skip condition is affine)
2448 * or in scop_add_break (if the skip condition is not affine).
2450 * If we were only able to extract part of the body, then simply
2453 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
2455 isl_id
*id
, *id_test
;
2458 struct pet_scop
*scop
;
2461 scop
= extract(body
);
2467 id
= isl_id_alloc(ctx
, "t", NULL
);
2468 domain
= infinite_domain(isl_id_copy(id
), scop
);
2469 ident
= identity_aff(domain
);
2471 has_var_break
= pet_scop_has_var_skip(scop
, pet_skip_later
);
2473 id_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
2475 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
2476 isl_aff_copy(ident
), ident
, id
);
2478 scop
= scop_add_break(scop
, id_test
, domain
, isl_val_one(ctx
));
2480 isl_set_free(domain
);
2485 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2491 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
2493 clear_assignments
clear(assigned_value
);
2494 clear
.TraverseStmt(stmt
->getBody());
2496 return extract_infinite_loop(stmt
->getBody());
2499 /* Add an array with the given extent (range of "index") to the list
2500 * of arrays in "scop" and return the extended pet_scop.
2501 * The array is marked as attaining values 0 and 1 only and
2502 * as each element being assigned at most once.
2504 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2505 __isl_keep isl_multi_pw_aff
*index
, clang::ASTContext
&ast_ctx
)
2507 int int_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
2509 return pet_scop_add_boolean_array(scop
, isl_multi_pw_aff_copy(index
),
2513 /* Construct a pet_scop for a while loop of the form
2518 * In particular, construct a scop for an infinite loop around body and
2519 * intersect the domain with the affine expression.
2520 * Note that this intersection may result in an empty loop.
2522 struct pet_scop
*PetScan::extract_affine_while(__isl_take isl_pw_aff
*pa
,
2525 struct pet_scop
*scop
;
2529 valid
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2530 dom
= isl_pw_aff_non_zero_set(pa
);
2531 scop
= extract_infinite_loop(body
);
2532 scop
= pet_scop_restrict(scop
, dom
);
2533 scop
= pet_scop_restrict_context(scop
, valid
);
2538 /* Construct a scop for a while, given the scops for the condition
2539 * and the body, the filter identifier and the iteration domain of
2542 * In particular, the scop for the condition is filtered to depend
2543 * on "id_test" evaluating to true for all previous iterations
2544 * of the loop, while the scop for the body is filtered to depend
2545 * on "id_test" evaluating to true for all iterations up to the
2546 * current iteration.
2547 * The actual filter only imposes that this virtual array has
2548 * value one on the previous or the current iteration.
2549 * The fact that this condition also applies to the previous
2550 * iterations is enforced by an implication.
2552 * These filtered scops are then combined into a single scop.
2554 * "sign" is positive if the iterator increases and negative
2557 static struct pet_scop
*scop_add_while(struct pet_scop
*scop_cond
,
2558 struct pet_scop
*scop_body
, __isl_take isl_id
*id_test
,
2559 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2561 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
2563 isl_multi_pw_aff
*test_index
;
2564 isl_multi_pw_aff
*prev
;
2565 int sign
= isl_val_sgn(inc
);
2566 struct pet_scop
*scop
;
2568 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
2569 scop_cond
= pet_scop_filter(scop_cond
, prev
, 1);
2571 space
= isl_space_map_from_set(isl_set_get_space(domain
));
2572 test_index
= isl_multi_pw_aff_identity(space
);
2573 test_index
= isl_multi_pw_aff_set_tuple_id(test_index
, isl_dim_out
,
2574 isl_id_copy(id_test
));
2575 scop_body
= pet_scop_filter(scop_body
, test_index
, 1);
2577 scop
= pet_scop_add_seq(ctx
, scop_cond
, scop_body
);
2578 scop
= add_implication(scop
, id_test
, domain
, sign
, 1);
2583 /* Check if the while loop is of the form
2585 * while (affine expression)
2588 * If so, call extract_affine_while to construct a scop.
2590 * Otherwise, construct a generic while scop, with iteration domain
2591 * { [t] : t >= 0 }. The scop consists of two parts, one for
2592 * evaluating the condition and one for the body.
2593 * The schedule is adjusted to reflect that the condition is evaluated
2594 * before the body is executed and the body is filtered to depend
2595 * on the result of the condition evaluating to true on all iterations
2596 * up to the current iteration, while the evaluation of the condition itself
2597 * is filtered to depend on the result of the condition evaluating to true
2598 * on all previous iterations.
2599 * The context of the scop representing the body is dropped
2600 * because we don't know how many times the body will be executed,
2603 * If the body contains any break, then it is taken into
2604 * account in infinite_domain (if the skip condition is affine)
2605 * or in scop_add_break (if the skip condition is not affine).
2607 * If we were only able to extract part of the body, then simply
2610 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
2613 int test_nr
, stmt_nr
;
2614 isl_id
*id
, *id_test
, *id_break_test
;
2615 isl_multi_pw_aff
*test_index
;
2619 struct pet_scop
*scop
, *scop_body
;
2622 cond
= stmt
->getCond();
2628 clear_assignments
clear(assigned_value
);
2629 clear
.TraverseStmt(stmt
->getBody());
2631 pa
= try_extract_affine_condition(cond
);
2633 return extract_affine_while(pa
, stmt
->getBody());
2635 if (!allow_nested
) {
2642 scop_body
= extract(stmt
->getBody());
2646 test_index
= pet_create_test_index(ctx
, test_nr
);
2647 scop
= extract_non_affine_condition(cond
, stmt_nr
,
2648 isl_multi_pw_aff_copy(test_index
));
2649 scop
= scop_add_array(scop
, test_index
, ast_context
);
2650 id_test
= isl_multi_pw_aff_get_tuple_id(test_index
, isl_dim_out
);
2651 isl_multi_pw_aff_free(test_index
);
2653 id
= isl_id_alloc(ctx
, "t", NULL
);
2654 domain
= infinite_domain(isl_id_copy(id
), scop_body
);
2655 ident
= identity_aff(domain
);
2657 has_var_break
= pet_scop_has_var_skip(scop_body
, pet_skip_later
);
2659 id_break_test
= pet_scop_get_skip_id(scop_body
, pet_skip_later
);
2661 scop
= pet_scop_prefix(scop
, 0);
2662 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), isl_aff_copy(ident
),
2663 isl_aff_copy(ident
), isl_id_copy(id
));
2664 scop_body
= pet_scop_reset_context(scop_body
);
2665 scop_body
= pet_scop_prefix(scop_body
, 1);
2666 scop_body
= pet_scop_embed(scop_body
, isl_set_copy(domain
),
2667 isl_aff_copy(ident
), ident
, id
);
2669 if (has_var_break
) {
2670 scop
= scop_add_break(scop
, isl_id_copy(id_break_test
),
2671 isl_set_copy(domain
), isl_val_one(ctx
));
2672 scop_body
= scop_add_break(scop_body
, id_break_test
,
2673 isl_set_copy(domain
), isl_val_one(ctx
));
2675 scop
= scop_add_while(scop
, scop_body
, id_test
, domain
,
2681 /* Check whether "cond" expresses a simple loop bound
2682 * on the only set dimension.
2683 * In particular, if "up" is set then "cond" should contain only
2684 * upper bounds on the set dimension.
2685 * Otherwise, it should contain only lower bounds.
2687 static bool is_simple_bound(__isl_keep isl_set
*cond
, __isl_keep isl_val
*inc
)
2689 if (isl_val_is_pos(inc
))
2690 return !isl_set_dim_has_any_lower_bound(cond
, isl_dim_set
, 0);
2692 return !isl_set_dim_has_any_upper_bound(cond
, isl_dim_set
, 0);
2695 /* Extend a condition on a given iteration of a loop to one that
2696 * imposes the same condition on all previous iterations.
2697 * "domain" expresses the lower [upper] bound on the iterations
2698 * when inc is positive [negative].
2700 * In particular, we construct the condition (when inc is positive)
2702 * forall i' : (domain(i') and i' <= i) => cond(i')
2704 * which is equivalent to
2706 * not exists i' : domain(i') and i' <= i and not cond(i')
2708 * We construct this set by negating cond, applying a map
2710 * { [i'] -> [i] : domain(i') and i' <= i }
2712 * and then negating the result again.
2714 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
2715 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2717 isl_map
*previous_to_this
;
2719 if (isl_val_is_pos(inc
))
2720 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
2722 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
2724 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
2726 cond
= isl_set_complement(cond
);
2727 cond
= isl_set_apply(cond
, previous_to_this
);
2728 cond
= isl_set_complement(cond
);
2735 /* Construct a domain of the form
2737 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2739 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
2740 __isl_take isl_pw_aff
*init
, __isl_take isl_val
*inc
)
2746 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
2747 dim
= isl_pw_aff_get_domain_space(init
);
2748 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2749 aff
= isl_aff_add_coefficient_val(aff
, isl_dim_in
, 0, inc
);
2750 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2752 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2753 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2754 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2755 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2757 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2759 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2761 return isl_set_params(set
);
2764 /* Assuming "cond" represents a bound on a loop where the loop
2765 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2768 * Under the given assumptions, wrapping is only possible if "cond" allows
2769 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2770 * increasing iterator and 0 in case of a decreasing iterator.
2772 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
,
2773 __isl_keep isl_val
*inc
)
2780 test
= isl_set_copy(cond
);
2782 ctx
= isl_set_get_ctx(test
);
2783 if (isl_val_is_neg(inc
))
2784 limit
= isl_val_zero(ctx
);
2786 limit
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2787 limit
= isl_val_2exp(limit
);
2788 limit
= isl_val_sub_ui(limit
, 1);
2791 test
= isl_set_fix_val(cond
, isl_dim_set
, 0, limit
);
2792 cw
= !isl_set_is_empty(test
);
2798 /* Given a one-dimensional space, construct the following affine expression
2801 * { [v] -> [v mod 2^width] }
2803 * where width is the number of bits used to represent the values
2804 * of the unsigned variable "iv".
2806 static __isl_give isl_aff
*compute_wrapping(__isl_take isl_space
*dim
,
2813 ctx
= isl_space_get_ctx(dim
);
2814 mod
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2815 mod
= isl_val_2exp(mod
);
2817 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2818 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2819 aff
= isl_aff_mod_val(aff
, mod
);
2824 /* Project out the parameter "id" from "set".
2826 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2827 __isl_keep isl_id
*id
)
2831 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2833 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2838 /* Compute the set of parameters for which "set1" is a subset of "set2".
2840 * set1 is a subset of set2 if
2842 * forall i in set1 : i in set2
2846 * not exists i in set1 and i not in set2
2850 * not exists i in set1 \ set2
2852 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2853 __isl_take isl_set
*set2
)
2855 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2858 /* Compute the set of parameter values for which "cond" holds
2859 * on the next iteration for each element of "dom".
2861 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2862 * and then compute the set of parameters for which the result is a subset
2865 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2866 __isl_take isl_set
*dom
, __isl_take isl_val
*inc
)
2872 space
= isl_set_get_space(dom
);
2873 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2874 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2875 aff
= isl_aff_add_constant_val(aff
, inc
);
2876 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2878 dom
= isl_set_apply(dom
, next
);
2880 return enforce_subset(dom
, cond
);
2883 /* Construct a pet_scop for a for statement.
2884 * The for loop is required to be of the form
2886 * for (i = init; condition; ++i)
2890 * for (i = init; condition; --i)
2892 * The initialization of the for loop should either be an assignment
2893 * to an integer variable, or a declaration of such a variable with
2896 * The condition is allowed to contain nested accesses, provided
2897 * they are not being written to inside the body of the loop.
2898 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2899 * essentially treated as a while loop, with iteration domain
2900 * { [i] : i >= init }.
2902 * We extract a pet_scop for the body and then embed it in a loop with
2903 * iteration domain and schedule
2905 * { [i] : i >= init and condition' }
2910 * { [i] : i <= init and condition' }
2913 * Where condition' is equal to condition if the latter is
2914 * a simple upper [lower] bound and a condition that is extended
2915 * to apply to all previous iterations otherwise.
2917 * If the condition is non-affine, then we drop the condition from the
2918 * iteration domain and instead create a separate statement
2919 * for evaluating the condition. The body is then filtered to depend
2920 * on the result of the condition evaluating to true on all iterations
2921 * up to the current iteration, while the evaluation the condition itself
2922 * is filtered to depend on the result of the condition evaluating to true
2923 * on all previous iterations.
2924 * The context of the scop representing the body is dropped
2925 * because we don't know how many times the body will be executed,
2928 * If the stride of the loop is not 1, then "i >= init" is replaced by
2930 * (exists a: i = init + stride * a and a >= 0)
2932 * If the loop iterator i is unsigned, then wrapping may occur.
2933 * We therefore use a virtual iterator instead that does not wrap.
2934 * However, the condition in the code applies
2935 * to the wrapped value, so we need to change condition(i)
2936 * into condition([i % 2^width]). Similarly, we replace all accesses
2937 * to the original iterator by the wrapping of the virtual iterator.
2938 * Note that there may be no need to perform this final wrapping
2939 * if the loop condition (after wrapping) satisfies certain conditions.
2940 * However, the is_simple_bound condition is not enough since it doesn't
2941 * check if there even is an upper bound.
2943 * Wrapping on unsigned iterators can be avoided entirely if
2944 * loop condition is simple, the loop iterator is incremented
2945 * [decremented] by one and the last value before wrapping cannot
2946 * possibly satisfy the loop condition.
2948 * Before extracting a pet_scop from the body we remove all
2949 * assignments in assigned_value to variables that are assigned
2950 * somewhere in the body of the loop.
2952 * Valid parameters for a for loop are those for which the initial
2953 * value itself, the increment on each domain iteration and
2954 * the condition on both the initial value and
2955 * the result of incrementing the iterator for each iteration of the domain
2957 * If the loop condition is non-affine, then we only consider validity
2958 * of the initial value.
2960 * If the body contains any break, then we keep track of it in "skip"
2961 * (if the skip condition is affine) or it is handled in scop_add_break
2962 * (if the skip condition is not affine).
2963 * Note that the affine break condition needs to be considered with
2964 * respect to previous iterations in the virtual domain (if any).
2966 * If we were only able to extract part of the body, then simply
2969 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2971 BinaryOperator
*ass
;
2976 isl_local_space
*ls
;
2979 isl_set
*cond
= NULL
;
2980 isl_set
*skip
= NULL
;
2981 isl_id
*id
, *id_test
= NULL
, *id_break_test
;
2982 struct pet_scop
*scop
, *scop_cond
= NULL
;
2983 assigned_value_cache
cache(assigned_value
);
2990 bool has_affine_break
;
2992 isl_aff
*wrap
= NULL
;
2993 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2994 isl_set
*valid_init
;
2995 isl_set
*valid_cond
;
2996 isl_set
*valid_cond_init
;
2997 isl_set
*valid_cond_next
;
3001 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
3002 return extract_infinite_for(stmt
);
3004 init
= stmt
->getInit();
3009 if ((ass
= initialization_assignment(init
)) != NULL
) {
3010 iv
= extract_induction_variable(ass
);
3013 lhs
= ass
->getLHS();
3014 rhs
= ass
->getRHS();
3015 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
3016 VarDecl
*var
= extract_induction_variable(init
, decl
);
3020 rhs
= var
->getInit();
3021 lhs
= create_DeclRefExpr(var
);
3023 unsupported(stmt
->getInit());
3027 assigned_value
.erase(iv
);
3028 clear_assignments
clear(assigned_value
);
3029 clear
.TraverseStmt(stmt
->getBody());
3031 was_assigned
= assigned_value
.find(iv
) != assigned_value
.end();
3032 clear_assignment(assigned_value
, iv
);
3033 init_val
= extract_affine(rhs
);
3035 assigned_value
.erase(iv
);
3039 pa_inc
= extract_increment(stmt
, iv
);
3041 isl_pw_aff_free(init_val
);
3046 if (isl_pw_aff_n_piece(pa_inc
) != 1 ||
3047 isl_pw_aff_foreach_piece(pa_inc
, &extract_cst
, &inc
) < 0) {
3048 isl_pw_aff_free(init_val
);
3049 isl_pw_aff_free(pa_inc
);
3050 unsupported(stmt
->getInc());
3055 pa
= try_extract_nested_condition(stmt
->getCond());
3056 if (allow_nested
&& (!pa
|| pet_nested_any_in_pw_aff(pa
)))
3059 scop
= extract(stmt
->getBody());
3061 isl_pw_aff_free(init_val
);
3062 isl_pw_aff_free(pa_inc
);
3063 isl_pw_aff_free(pa
);
3068 valid_inc
= isl_pw_aff_domain(pa_inc
);
3070 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
3072 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
3074 has_affine_break
= scop
&&
3075 pet_scop_has_affine_skip(scop
, pet_skip_later
);
3076 if (has_affine_break
)
3077 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
3078 has_var_break
= scop
&& pet_scop_has_var_skip(scop
, pet_skip_later
);
3080 id_break_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
3082 if (pa
&& !is_nested_allowed(pa
, scop
)) {
3083 isl_pw_aff_free(pa
);
3087 if (!allow_nested
&& !pa
)
3088 pa
= try_extract_affine_condition(stmt
->getCond());
3089 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
3090 cond
= isl_pw_aff_non_zero_set(pa
);
3091 if (allow_nested
&& !cond
) {
3092 isl_multi_pw_aff
*test_index
;
3093 int save_n_stmt
= n_stmt
;
3094 test_index
= pet_create_test_index(ctx
, n_test
++);
3096 scop_cond
= extract_non_affine_condition(stmt
->getCond(),
3097 n_stmt
++, isl_multi_pw_aff_copy(test_index
));
3098 n_stmt
= save_n_stmt
;
3099 scop_cond
= scop_add_array(scop_cond
, test_index
, ast_context
);
3100 id_test
= isl_multi_pw_aff_get_tuple_id(test_index
,
3102 isl_multi_pw_aff_free(test_index
);
3103 scop_cond
= pet_scop_prefix(scop_cond
, 0);
3104 scop
= pet_scop_reset_context(scop
);
3105 scop
= pet_scop_prefix(scop
, 1);
3106 cond
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
3109 cond
= embed(cond
, isl_id_copy(id
));
3110 skip
= embed(skip
, isl_id_copy(id
));
3111 valid_cond
= isl_set_coalesce(valid_cond
);
3112 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
3113 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
3114 is_one
= isl_val_is_one(inc
) || isl_val_is_negone(inc
);
3115 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
3117 valid_cond_init
= enforce_subset(
3118 isl_set_from_pw_aff(isl_pw_aff_copy(init_val
)),
3119 isl_set_copy(valid_cond
));
3120 if (is_one
&& !is_virtual
) {
3121 isl_pw_aff_free(init_val
);
3122 pa
= extract_comparison(isl_val_is_pos(inc
) ? BO_GE
: BO_LE
,
3124 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
3125 valid_init
= set_project_out_by_id(valid_init
, id
);
3126 domain
= isl_pw_aff_non_zero_set(pa
);
3128 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
3129 domain
= strided_domain(isl_id_copy(id
), init_val
,
3133 domain
= embed(domain
, isl_id_copy(id
));
3136 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
3137 rev_wrap
= isl_map_from_aff(isl_aff_copy(wrap
));
3138 rev_wrap
= isl_map_reverse(rev_wrap
);
3139 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
3140 skip
= isl_set_apply(skip
, isl_map_copy(rev_wrap
));
3141 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
3142 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
3144 is_simple
= is_simple_bound(cond
, inc
);
3146 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
3147 is_simple
= is_simple_bound(cond
, inc
);
3150 cond
= valid_for_each_iteration(cond
,
3151 isl_set_copy(domain
), isl_val_copy(inc
));
3152 domain
= isl_set_intersect(domain
, cond
);
3153 if (has_affine_break
) {
3154 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
3155 skip
= after(skip
, isl_val_sgn(inc
));
3156 domain
= isl_set_subtract(domain
, skip
);
3158 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
3159 ls
= isl_local_space_from_space(isl_set_get_space(domain
));
3160 sched
= isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
3161 if (isl_val_is_neg(inc
))
3162 sched
= isl_aff_neg(sched
);
3164 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
),
3166 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
3169 wrap
= identity_aff(domain
);
3171 scop_cond
= pet_scop_embed(scop_cond
, isl_set_copy(domain
),
3172 isl_aff_copy(sched
), isl_aff_copy(wrap
), isl_id_copy(id
));
3173 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), sched
, wrap
, id
);
3174 scop
= resolve_nested(scop
);
3176 scop
= scop_add_break(scop
, id_break_test
, isl_set_copy(domain
),
3179 scop
= scop_add_while(scop_cond
, scop
, id_test
, domain
,
3181 isl_set_free(valid_inc
);
3183 scop
= pet_scop_restrict_context(scop
, valid_inc
);
3184 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
3185 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
3186 isl_set_free(domain
);
3188 clear_assignment(assigned_value
, iv
);
3192 scop
= pet_scop_restrict_context(scop
, valid_init
);
3197 /* Try and construct a pet_scop corresponding to a compound statement.
3199 * "skip_declarations" is set if we should skip initial declarations
3200 * in the children of the compound statements. This then implies
3201 * that this sequence of children should not be treated as a block
3202 * since the initial statements may be skipped.
3204 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
, bool skip_declarations
)
3206 return extract(stmt
->children(), !skip_declarations
, skip_declarations
);
3209 /* For each nested access parameter in "space",
3210 * construct a corresponding pet_expr, place it in args and
3211 * record its position in "param2pos".
3212 * "n_arg" is the number of elements that are already in args.
3213 * The position recorded in "param2pos" takes this number into account.
3214 * If the pet_expr corresponding to a parameter is identical to
3215 * the pet_expr corresponding to an earlier parameter, then these two
3216 * parameters are made to refer to the same element in args.
3218 * Return the final number of elements in args or -1 if an error has occurred.
3220 int PetScan::extract_nested(__isl_keep isl_space
*space
,
3221 int n_arg
, pet_expr
**args
, std::map
<int,int> ¶m2pos
)
3225 nparam
= isl_space_dim(space
, isl_dim_param
);
3226 for (int i
= 0; i
< nparam
; ++i
) {
3228 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
3231 if (!pet_nested_in_id(id
)) {
3236 nested
= (Expr
*) isl_id_get_user(id
);
3237 args
[n_arg
] = extract_expr(nested
);
3242 for (j
= 0; j
< n_arg
; ++j
)
3243 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
3247 pet_expr_free(args
[n_arg
]);
3251 param2pos
[i
] = n_arg
++;
3257 /* For each nested access parameter in the access relations in "expr",
3258 * construct a corresponding pet_expr, place it in the arguments of "expr"
3259 * and record its position in "param2pos".
3260 * n is the number of nested access parameters.
3262 __isl_give pet_expr
*PetScan::extract_nested(__isl_take pet_expr
*expr
, int n
,
3263 std::map
<int,int> ¶m2pos
)
3269 args
= isl_calloc_array(ctx
, pet_expr
*, n
);
3271 return pet_expr_free(expr
);
3273 space
= pet_expr_access_get_parameter_space(expr
);
3274 n
= extract_nested(space
, 0, args
, param2pos
);
3275 isl_space_free(space
);
3278 expr
= pet_expr_free(expr
);
3280 expr
= pet_expr_set_n_arg(expr
, n
);
3282 for (i
= 0; i
< n
; ++i
)
3283 expr
= pet_expr_set_arg(expr
, i
, args
[i
]);
3289 /* Look for parameters in any access relation in "expr" that
3290 * refer to nested accesses. In particular, these are
3291 * parameters with no name.
3293 * If there are any such parameters, then the domain of the index
3294 * expression and the access relation, which is still [] at this point,
3295 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
3296 * (after identifying identical nested accesses).
3298 * This transformation is performed in several steps.
3299 * We first extract the arguments in extract_nested.
3300 * param2pos maps the original parameter position to the position
3302 * Then we move these parameters to input dimensions.
3303 * t2pos maps the positions of these temporary input dimensions
3304 * to the positions of the corresponding arguments.
3305 * Finally, we express these temporary dimensions in terms of the domain
3306 * [[] -> [t_1,...,t_n]] and precompose index expression and access
3307 * relations with this function.
3309 __isl_give pet_expr
*PetScan::resolve_nested(__isl_take pet_expr
*expr
)
3314 isl_local_space
*ls
;
3317 std::map
<int,int> param2pos
;
3318 std::map
<int,int> t2pos
;
3323 n
= pet_expr_get_n_arg(expr
);
3324 for (int i
= 0; i
< n
; ++i
) {
3326 arg
= pet_expr_get_arg(expr
, i
);
3327 arg
= resolve_nested(arg
);
3328 expr
= pet_expr_set_arg(expr
, i
, arg
);
3331 if (pet_expr_get_type(expr
) != pet_expr_access
)
3334 space
= pet_expr_access_get_parameter_space(expr
);
3335 n
= pet_nested_n_in_space(space
);
3336 isl_space_free(space
);
3340 expr
= extract_nested(expr
, n
, param2pos
);
3344 expr
= pet_expr_access_align_params(expr
);
3349 space
= pet_expr_access_get_parameter_space(expr
);
3350 nparam
= isl_space_dim(space
, isl_dim_param
);
3351 for (int i
= nparam
- 1; i
>= 0; --i
) {
3352 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
3353 if (!pet_nested_in_id(id
)) {
3358 expr
= pet_expr_access_move_dims(expr
,
3359 isl_dim_in
, n
, isl_dim_param
, i
, 1);
3360 t2pos
[n
] = param2pos
[i
];
3365 isl_space_free(space
);
3367 space
= pet_expr_access_get_parameter_space(expr
);
3368 space
= isl_space_set_from_params(space
);
3369 space
= isl_space_add_dims(space
, isl_dim_set
,
3370 pet_expr_get_n_arg(expr
));
3371 space
= isl_space_wrap(isl_space_from_range(space
));
3372 ls
= isl_local_space_from_space(isl_space_copy(space
));
3373 space
= isl_space_from_domain(space
);
3374 space
= isl_space_add_dims(space
, isl_dim_out
, n
);
3375 ma
= isl_multi_aff_zero(space
);
3377 for (int i
= 0; i
< n
; ++i
) {
3378 aff
= isl_aff_var_on_domain(isl_local_space_copy(ls
),
3379 isl_dim_set
, t2pos
[i
]);
3380 ma
= isl_multi_aff_set_aff(ma
, i
, aff
);
3382 isl_local_space_free(ls
);
3384 expr
= pet_expr_access_pullback_multi_aff(expr
, ma
);
3389 /* Return the file offset of the expansion location of "Loc".
3391 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
3393 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
3396 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3398 /* Return a SourceLocation for the location after the first semicolon
3399 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3400 * call it and also skip trailing spaces and newline.
3402 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3403 const LangOptions
&LO
)
3405 return Lexer::findLocationAfterToken(loc
, tok::semi
, SM
, LO
, true);
3410 /* Return a SourceLocation for the location after the first semicolon
3411 * after "loc". If Lexer::findLocationAfterToken is not available,
3412 * we look in the underlying character data for the first semicolon.
3414 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3415 const LangOptions
&LO
)
3418 const char *s
= SM
.getCharacterData(loc
);
3420 semi
= strchr(s
, ';');
3422 return SourceLocation();
3423 return loc
.getFileLocWithOffset(semi
+ 1 - s
);
3428 /* If the token at "loc" is the first token on the line, then return
3429 * a location referring to the start of the line.
3430 * Otherwise, return "loc".
3432 * This function is used to extend a scop to the start of the line
3433 * if the first token of the scop is also the first token on the line.
3435 * We look for the first token on the line. If its location is equal to "loc",
3436 * then the latter is the location of the first token on the line.
3438 static SourceLocation
move_to_start_of_line_if_first_token(SourceLocation loc
,
3439 SourceManager
&SM
, const LangOptions
&LO
)
3441 std::pair
<FileID
, unsigned> file_offset_pair
;
3442 llvm::StringRef file
;
3445 SourceLocation token_loc
, line_loc
;
3448 loc
= SM
.getExpansionLoc(loc
);
3449 col
= SM
.getExpansionColumnNumber(loc
);
3450 line_loc
= loc
.getLocWithOffset(1 - col
);
3451 file_offset_pair
= SM
.getDecomposedLoc(line_loc
);
3452 file
= SM
.getBufferData(file_offset_pair
.first
, NULL
);
3453 pos
= file
.data() + file_offset_pair
.second
;
3455 Lexer
lexer(SM
.getLocForStartOfFile(file_offset_pair
.first
), LO
,
3456 file
.begin(), pos
, file
.end());
3457 lexer
.LexFromRawLexer(tok
);
3458 token_loc
= tok
.getLocation();
3460 if (token_loc
== loc
)
3466 /* Update start and end of "scop" to include the region covered by "range".
3467 * If "skip_semi" is set, then we assume "range" is followed by
3468 * a semicolon and also include this semicolon.
3470 struct pet_scop
*PetScan::update_scop_start_end(struct pet_scop
*scop
,
3471 SourceRange range
, bool skip_semi
)
3473 SourceLocation loc
= range
.getBegin();
3474 SourceManager
&SM
= PP
.getSourceManager();
3475 const LangOptions
&LO
= PP
.getLangOpts();
3476 unsigned start
, end
;
3478 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
);
3479 start
= getExpansionOffset(SM
, loc
);
3480 loc
= range
.getEnd();
3482 loc
= location_after_semi(loc
, SM
, LO
);
3484 loc
= PP
.getLocForEndOfToken(loc
);
3485 end
= getExpansionOffset(SM
, loc
);
3487 scop
= pet_scop_update_start_end(scop
, start
, end
);
3491 /* Convert a top-level pet_expr to a pet_scop with one statement.
3492 * This mainly involves resolving nested expression parameters
3493 * and setting the name of the iteration space.
3494 * The name is given by "label" if it is non-NULL. Otherwise,
3495 * it is of the form S_<n_stmt>.
3496 * start and end of the pet_scop are derived from those of "stmt".
3497 * If "stmt" is an expression statement, then its range does not
3498 * include the semicolon, while it should be included in the pet_scop.
3500 struct pet_scop
*PetScan::extract(Stmt
*stmt
, __isl_take pet_expr
*expr
,
3501 __isl_take isl_id
*label
)
3503 struct pet_stmt
*ps
;
3504 struct pet_scop
*scop
;
3505 SourceLocation loc
= stmt
->getLocStart();
3506 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3509 expr
= resolve_nested(expr
);
3510 ps
= pet_stmt_from_pet_expr(line
, label
, n_stmt
++, expr
);
3511 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3513 skip_semi
= isa
<Expr
>(stmt
);
3514 scop
= update_scop_start_end(scop
, stmt
->getSourceRange(), skip_semi
);
3518 /* Check if we can extract an affine expression from "expr".
3519 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3520 * We turn on autodetection so that we won't generate any warnings
3521 * and turn off nesting, so that we won't accept any non-affine constructs.
3523 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
3526 int save_autodetect
= options
->autodetect
;
3527 bool save_nesting
= nesting_enabled
;
3529 options
->autodetect
= 1;
3530 nesting_enabled
= false;
3532 pwaff
= extract_affine(expr
);
3534 options
->autodetect
= save_autodetect
;
3535 nesting_enabled
= save_nesting
;
3540 /* Check if we can extract an affine constraint from "expr".
3541 * Return the constraint as an isl_set if we can and NULL otherwise.
3542 * We turn on autodetection so that we won't generate any warnings
3543 * and turn off nesting, so that we won't accept any non-affine constructs.
3545 __isl_give isl_pw_aff
*PetScan::try_extract_affine_condition(Expr
*expr
)
3548 int save_autodetect
= options
->autodetect
;
3549 bool save_nesting
= nesting_enabled
;
3551 options
->autodetect
= 1;
3552 nesting_enabled
= false;
3554 cond
= extract_condition(expr
);
3556 options
->autodetect
= save_autodetect
;
3557 nesting_enabled
= save_nesting
;
3562 /* Check whether "expr" is an affine constraint.
3564 bool PetScan::is_affine_condition(Expr
*expr
)
3568 cond
= try_extract_affine_condition(expr
);
3569 isl_pw_aff_free(cond
);
3571 return cond
!= NULL
;
3574 /* Check if we can extract a condition from "expr".
3575 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3576 * If allow_nested is set, then the condition may involve parameters
3577 * corresponding to nested accesses.
3578 * We turn on autodetection so that we won't generate any warnings.
3580 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
3583 int save_autodetect
= options
->autodetect
;
3584 bool save_nesting
= nesting_enabled
;
3586 options
->autodetect
= 1;
3587 nesting_enabled
= allow_nested
;
3588 cond
= extract_condition(expr
);
3590 options
->autodetect
= save_autodetect
;
3591 nesting_enabled
= save_nesting
;
3596 /* If the top-level expression of "stmt" is an assignment, then
3597 * return that assignment as a BinaryOperator.
3598 * Otherwise return NULL.
3600 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
3602 BinaryOperator
*ass
;
3606 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
3609 ass
= cast
<BinaryOperator
>(stmt
);
3610 if(ass
->getOpcode() != BO_Assign
)
3616 /* Check if the given if statement is a conditional assignement
3617 * with a non-affine condition. If so, construct a pet_scop
3618 * corresponding to this conditional assignment. Otherwise return NULL.
3620 * In particular we check if "stmt" is of the form
3627 * where a is some array or scalar access.
3628 * The constructed pet_scop then corresponds to the expression
3630 * a = condition ? f(...) : g(...)
3632 * All access relations in f(...) are intersected with condition
3633 * while all access relation in g(...) are intersected with the complement.
3635 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
3637 BinaryOperator
*ass_then
, *ass_else
;
3638 isl_multi_pw_aff
*write_then
, *write_else
;
3639 isl_set
*cond
, *comp
;
3640 isl_multi_pw_aff
*index
;
3644 pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
3645 bool save_nesting
= nesting_enabled
;
3647 if (!options
->detect_conditional_assignment
)
3650 ass_then
= top_assignment_or_null(stmt
->getThen());
3651 ass_else
= top_assignment_or_null(stmt
->getElse());
3653 if (!ass_then
|| !ass_else
)
3656 if (is_affine_condition(stmt
->getCond()))
3659 write_then
= extract_index(ass_then
->getLHS());
3660 write_else
= extract_index(ass_else
->getLHS());
3662 equal
= isl_multi_pw_aff_plain_is_equal(write_then
, write_else
);
3663 isl_multi_pw_aff_free(write_else
);
3664 if (equal
< 0 || !equal
) {
3665 isl_multi_pw_aff_free(write_then
);
3669 nesting_enabled
= allow_nested
;
3670 pa
= extract_condition(stmt
->getCond());
3671 nesting_enabled
= save_nesting
;
3672 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
3673 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
3674 index
= isl_multi_pw_aff_from_range(isl_multi_pw_aff_from_pw_aff(pa
));
3676 pe_cond
= pet_expr_from_index(index
);
3678 pe_then
= extract_expr(ass_then
->getRHS());
3679 pe_then
= pet_expr_restrict(pe_then
, cond
);
3680 pe_else
= extract_expr(ass_else
->getRHS());
3681 pe_else
= pet_expr_restrict(pe_else
, comp
);
3683 pe
= pet_expr_new_ternary(pe_cond
, pe_then
, pe_else
);
3684 type_size
= get_type_size(ass_then
->getType(), ast_context
);
3685 pe_write
= pet_expr_from_index_and_depth(type_size
, write_then
,
3686 extract_depth(write_then
));
3687 pe_write
= pet_expr_access_set_write(pe_write
, 1);
3688 pe_write
= pet_expr_access_set_read(pe_write
, 0);
3689 pe
= pet_expr_new_binary(type_size
, pet_op_assign
, pe_write
, pe
);
3690 return extract(stmt
, pe
);
3693 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3694 * evaluating "cond" and writing the result to a virtual scalar,
3695 * as expressed by "index".
3697 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
, int stmt_nr
,
3698 __isl_take isl_multi_pw_aff
*index
)
3700 pet_expr
*expr
, *write
;
3701 struct pet_stmt
*ps
;
3702 SourceLocation loc
= cond
->getLocStart();
3703 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3705 write
= pet_expr_from_index(index
);
3706 write
= pet_expr_access_set_write(write
, 1);
3707 write
= pet_expr_access_set_read(write
, 0);
3708 expr
= extract_expr(cond
);
3709 expr
= resolve_nested(expr
);
3710 expr
= pet_expr_new_binary(1, pet_op_assign
, write
, expr
);
3711 ps
= pet_stmt_from_pet_expr(line
, NULL
, stmt_nr
, expr
);
3712 return pet_scop_from_pet_stmt(ctx
, ps
);
3716 static __isl_give pet_expr
*embed_access(__isl_take pet_expr
*expr
,
3720 /* Precompose the access relation and the index expression associated
3721 * to "expr" with the function pointed to by "user",
3722 * thereby embedding the access relation in the domain of this function.
3723 * The initial domain of the access relation and the index expression
3724 * is the zero-dimensional domain.
3726 static __isl_give pet_expr
*embed_access(__isl_take pet_expr
*expr
, void *user
)
3728 isl_multi_aff
*ma
= (isl_multi_aff
*) user
;
3730 return pet_expr_access_pullback_multi_aff(expr
, isl_multi_aff_copy(ma
));
3733 /* Precompose all access relations in "expr" with "ma", thereby
3734 * embedding them in the domain of "ma".
3736 static __isl_give pet_expr
*embed(__isl_take pet_expr
*expr
,
3737 __isl_keep isl_multi_aff
*ma
)
3739 return pet_expr_map_access(expr
, &embed_access
, ma
);
3742 /* For each nested access parameter in the domain of "stmt",
3743 * construct a corresponding pet_expr, place it before the original
3744 * elements in stmt->args and record its position in "param2pos".
3745 * n is the number of nested access parameters.
3747 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
3748 std::map
<int,int> ¶m2pos
)
3755 n_arg
= stmt
->n_arg
;
3756 args
= isl_calloc_array(ctx
, pet_expr
*, n
+ n_arg
);
3760 space
= isl_set_get_space(stmt
->domain
);
3761 n_arg
= extract_nested(space
, 0, args
, param2pos
);
3762 isl_space_free(space
);
3767 for (i
= 0; i
< stmt
->n_arg
; ++i
)
3768 args
[n_arg
+ i
] = stmt
->args
[i
];
3771 stmt
->n_arg
+= n_arg
;
3776 for (i
= 0; i
< n
; ++i
)
3777 pet_expr_free(args
[i
]);
3780 pet_stmt_free(stmt
);
3784 /* Check whether any of the arguments i of "stmt" starting at position "n"
3785 * is equal to one of the first "n" arguments j.
3786 * If so, combine the constraints on arguments i and j and remove
3789 static struct pet_stmt
*remove_duplicate_arguments(struct pet_stmt
*stmt
, int n
)
3798 if (n
== stmt
->n_arg
)
3801 map
= isl_set_unwrap(stmt
->domain
);
3803 for (i
= stmt
->n_arg
- 1; i
>= n
; --i
) {
3804 for (j
= 0; j
< n
; ++j
)
3805 if (pet_expr_is_equal(stmt
->args
[i
], stmt
->args
[j
]))
3810 map
= isl_map_equate(map
, isl_dim_out
, i
, isl_dim_out
, j
);
3811 map
= isl_map_project_out(map
, isl_dim_out
, i
, 1);
3813 pet_expr_free(stmt
->args
[i
]);
3814 for (j
= i
; j
+ 1 < stmt
->n_arg
; ++j
)
3815 stmt
->args
[j
] = stmt
->args
[j
+ 1];
3819 stmt
->domain
= isl_map_wrap(map
);
3824 pet_stmt_free(stmt
);
3828 /* Look for parameters in the iteration domain of "stmt" that
3829 * refer to nested accesses. In particular, these are
3830 * parameters with no name.
3832 * If there are any such parameters, then as many extra variables
3833 * (after identifying identical nested accesses) are inserted in the
3834 * range of the map wrapped inside the domain, before the original variables.
3835 * If the original domain is not a wrapped map, then a new wrapped
3836 * map is created with zero output dimensions.
3837 * The parameters are then equated to the corresponding output dimensions
3838 * and subsequently projected out, from the iteration domain,
3839 * the schedule and the access relations.
3840 * For each of the output dimensions, a corresponding argument
3841 * expression is inserted. Initially they are created with
3842 * a zero-dimensional domain, so they have to be embedded
3843 * in the current iteration domain.
3844 * param2pos maps the position of the parameter to the position
3845 * of the corresponding output dimension in the wrapped map.
3847 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3855 std::map
<int,int> param2pos
;
3860 n
= pet_nested_n_in_set(stmt
->domain
);
3864 n_arg
= stmt
->n_arg
;
3865 stmt
= extract_nested(stmt
, n
, param2pos
);
3869 n
= stmt
->n_arg
- n_arg
;
3870 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3871 if (isl_set_is_wrapping(stmt
->domain
))
3872 map
= isl_set_unwrap(stmt
->domain
);
3874 map
= isl_map_from_domain(stmt
->domain
);
3875 map
= isl_map_insert_dims(map
, isl_dim_out
, 0, n
);
3877 for (int i
= nparam
- 1; i
>= 0; --i
) {
3880 if (!pet_nested_in_map(map
, i
))
3883 id
= pet_expr_access_get_id(stmt
->args
[param2pos
[i
]]);
3884 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3885 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3887 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3890 stmt
->domain
= isl_map_wrap(map
);
3892 space
= isl_space_unwrap(isl_set_get_space(stmt
->domain
));
3893 space
= isl_space_from_domain(isl_space_domain(space
));
3894 ma
= isl_multi_aff_zero(space
);
3895 for (int pos
= 0; pos
< n
; ++pos
)
3896 stmt
->args
[pos
] = embed(stmt
->args
[pos
], ma
);
3897 isl_multi_aff_free(ma
);
3899 stmt
= pet_stmt_remove_nested_parameters(stmt
);
3900 stmt
= remove_duplicate_arguments(stmt
, n
);
3905 /* For each statement in "scop", move the parameters that correspond
3906 * to nested access into the ranges of the domains and create
3907 * corresponding argument expressions.
3909 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3914 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3915 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3916 if (!scop
->stmts
[i
])
3922 pet_scop_free(scop
);
3926 /* Given an access expression "expr", is the variable accessed by
3927 * "expr" assigned anywhere inside "scop"?
3929 static bool is_assigned(__isl_keep pet_expr
*expr
, pet_scop
*scop
)
3931 bool assigned
= false;
3934 id
= pet_expr_access_get_id(expr
);
3935 assigned
= pet_scop_writes(scop
, id
);
3941 /* Are all nested access parameters in "pa" allowed given "scop".
3942 * In particular, is none of them written by anywhere inside "scop".
3944 * If "scop" has any skip conditions, then no nested access parameters
3945 * are allowed. In particular, if there is any nested access in a guard
3946 * for a piece of code containing a "continue", then we want to introduce
3947 * a separate statement for evaluating this guard so that we can express
3948 * that the result is false for all previous iterations.
3950 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3957 if (!pet_nested_any_in_pw_aff(pa
))
3960 if (pet_scop_has_skip(scop
, pet_skip_now
))
3963 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3964 for (int i
= 0; i
< nparam
; ++i
) {
3966 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3970 if (!pet_nested_in_id(id
)) {
3975 nested
= (Expr
*) isl_id_get_user(id
);
3976 expr
= extract_expr(nested
);
3977 allowed
= pet_expr_get_type(expr
) == pet_expr_access
&&
3978 !is_assigned(expr
, scop
);
3980 pet_expr_free(expr
);
3990 /* Construct a pet_scop for a non-affine if statement.
3992 * We create a separate statement that writes the result
3993 * of the non-affine condition to a virtual scalar.
3994 * A constraint requiring the value of this virtual scalar to be one
3995 * is added to the iteration domains of the then branch.
3996 * Similarly, a constraint requiring the value of this virtual scalar
3997 * to be zero is added to the iteration domains of the else branch, if any.
3998 * We adjust the schedules to ensure that the virtual scalar is written
3999 * before it is read.
4001 * If there are any breaks or continues in the then and/or else
4002 * branches, then we may have to compute a new skip condition.
4003 * This is handled using a pet_skip_info object.
4004 * On initialization, the object checks if skip conditions need
4005 * to be computed. If so, it does so in pet_skip_info_if_extract_index and
4006 * adds them in pet_skip_info_if_add.
4008 struct pet_scop
*PetScan::extract_non_affine_if(Expr
*cond
,
4009 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
4010 bool have_else
, int stmt_id
)
4012 struct pet_scop
*scop
;
4013 isl_multi_pw_aff
*test_index
;
4015 int save_n_stmt
= n_stmt
;
4017 test_index
= pet_create_test_index(ctx
, n_test
++);
4019 scop
= extract_non_affine_condition(cond
, n_stmt
++,
4020 isl_multi_pw_aff_copy(test_index
));
4021 n_stmt
= save_n_stmt
;
4022 scop
= scop_add_array(scop
, test_index
, ast_context
);
4025 pet_skip_info_if_init(&skip
, ctx
, scop_then
, scop_else
, have_else
, 0);
4026 int_size
= ast_context
.getTypeInfo(ast_context
.IntTy
).first
/ 8;
4027 pet_skip_info_if_extract_index(&skip
, test_index
, int_size
,
4030 scop
= pet_scop_prefix(scop
, 0);
4031 scop_then
= pet_scop_prefix(scop_then
, 1);
4032 scop_then
= pet_scop_filter(scop_then
,
4033 isl_multi_pw_aff_copy(test_index
), 1);
4035 scop_else
= pet_scop_prefix(scop_else
, 1);
4036 scop_else
= pet_scop_filter(scop_else
, test_index
, 0);
4037 scop_then
= pet_scop_add_par(ctx
, scop_then
, scop_else
);
4039 isl_multi_pw_aff_free(test_index
);
4041 scop
= pet_scop_add_seq(ctx
, scop
, scop_then
);
4043 scop
= pet_skip_info_if_add(&skip
, scop
, 2);
4048 /* Construct a pet_scop for an if statement.
4050 * If the condition fits the pattern of a conditional assignment,
4051 * then it is handled by extract_conditional_assignment.
4052 * Otherwise, we do the following.
4054 * If the condition is affine, then the condition is added
4055 * to the iteration domains of the then branch, while the
4056 * opposite of the condition in added to the iteration domains
4057 * of the else branch, if any.
4058 * We allow the condition to be dynamic, i.e., to refer to
4059 * scalars or array elements that may be written to outside
4060 * of the given if statement. These nested accesses are then represented
4061 * as output dimensions in the wrapping iteration domain.
4062 * If it is also written _inside_ the then or else branch, then
4063 * we treat the condition as non-affine.
4064 * As explained in extract_non_affine_if, this will introduce
4065 * an extra statement.
4066 * For aesthetic reasons, we want this statement to have a statement
4067 * number that is lower than those of the then and else branches.
4068 * In order to evaluate if we will need such a statement, however, we
4069 * first construct scops for the then and else branches.
4070 * We therefore reserve a statement number if we might have to
4071 * introduce such an extra statement.
4073 * If the condition is not affine, then the scop is created in
4074 * extract_non_affine_if.
4076 * If there are any breaks or continues in the then and/or else
4077 * branches, then we may have to compute a new skip condition.
4078 * This is handled using a pet_skip_info object.
4079 * On initialization, the object checks if skip conditions need
4080 * to be computed. If so, it does so in pet_skip_info_if_extract_cond and
4081 * adds them in pet_skip_info_if_add.
4083 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
4085 struct pet_scop
*scop_then
, *scop_else
= NULL
, *scop
;
4092 clear_assignments
clear(assigned_value
);
4093 clear
.TraverseStmt(stmt
->getThen());
4094 if (stmt
->getElse())
4095 clear
.TraverseStmt(stmt
->getElse());
4097 scop
= extract_conditional_assignment(stmt
);
4101 cond
= try_extract_nested_condition(stmt
->getCond());
4102 if (allow_nested
&& (!cond
|| pet_nested_any_in_pw_aff(cond
)))
4106 assigned_value_cache
cache(assigned_value
);
4107 scop_then
= extract(stmt
->getThen());
4110 if (stmt
->getElse()) {
4111 assigned_value_cache
cache(assigned_value
);
4112 scop_else
= extract(stmt
->getElse());
4113 if (options
->autodetect
) {
4114 if (scop_then
&& !scop_else
) {
4116 isl_pw_aff_free(cond
);
4119 if (!scop_then
&& scop_else
) {
4121 isl_pw_aff_free(cond
);
4128 (!is_nested_allowed(cond
, scop_then
) ||
4129 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
4130 isl_pw_aff_free(cond
);
4133 if (allow_nested
&& !cond
)
4134 return extract_non_affine_if(stmt
->getCond(), scop_then
,
4135 scop_else
, stmt
->getElse(), stmt_id
);
4138 cond
= extract_condition(stmt
->getCond());
4141 pet_skip_info_if_init(&skip
, ctx
, scop_then
, scop_else
,
4142 stmt
->getElse() != NULL
, 1);
4143 pet_skip_info_if_extract_cond(&skip
, cond
, int_size
, &n_stmt
, &n_test
);
4145 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
4146 set
= isl_pw_aff_non_zero_set(cond
);
4147 scop
= pet_scop_restrict(scop_then
, isl_set_copy(set
));
4149 if (stmt
->getElse()) {
4150 set
= isl_set_subtract(isl_set_copy(valid
), set
);
4151 scop_else
= pet_scop_restrict(scop_else
, set
);
4152 scop
= pet_scop_add_par(ctx
, scop
, scop_else
);
4155 scop
= resolve_nested(scop
);
4156 scop
= pet_scop_restrict_context(scop
, valid
);
4158 if (pet_skip_info_has_skip(&skip
))
4159 scop
= pet_scop_prefix(scop
, 0);
4160 scop
= pet_skip_info_if_add(&skip
, scop
, 1);
4165 /* Try and construct a pet_scop for a label statement.
4166 * We currently only allow labels on expression statements.
4168 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
4173 sub
= stmt
->getSubStmt();
4174 if (!isa
<Expr
>(sub
)) {
4179 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
4181 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
4184 /* Return a one-dimensional multi piecewise affine expression that is equal
4185 * to the constant 1 and is defined over a zero-dimensional domain.
4187 static __isl_give isl_multi_pw_aff
*one_mpa(isl_ctx
*ctx
)
4190 isl_local_space
*ls
;
4193 space
= isl_space_set_alloc(ctx
, 0, 0);
4194 ls
= isl_local_space_from_space(space
);
4195 aff
= isl_aff_zero_on_domain(ls
);
4196 aff
= isl_aff_set_constant_si(aff
, 1);
4198 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
4201 /* Construct a pet_scop for a continue statement.
4203 * We simply create an empty scop with a universal pet_skip_now
4204 * skip condition. This skip condition will then be taken into
4205 * account by the enclosing loop construct, possibly after
4206 * being incorporated into outer skip conditions.
4208 struct pet_scop
*PetScan::extract(ContinueStmt
*stmt
)
4212 scop
= pet_scop_empty(ctx
);
4216 scop
= pet_scop_set_skip(scop
, pet_skip_now
, one_mpa(ctx
));
4221 /* Construct a pet_scop for a break statement.
4223 * We simply create an empty scop with both a universal pet_skip_now
4224 * skip condition and a universal pet_skip_later skip condition.
4225 * These skip conditions will then be taken into
4226 * account by the enclosing loop construct, possibly after
4227 * being incorporated into outer skip conditions.
4229 struct pet_scop
*PetScan::extract(BreakStmt
*stmt
)
4232 isl_multi_pw_aff
*skip
;
4234 scop
= pet_scop_empty(ctx
);
4238 skip
= one_mpa(ctx
);
4239 scop
= pet_scop_set_skip(scop
, pet_skip_now
,
4240 isl_multi_pw_aff_copy(skip
));
4241 scop
= pet_scop_set_skip(scop
, pet_skip_later
, skip
);
4246 /* Try and construct a pet_scop corresponding to "stmt".
4248 * If "stmt" is a compound statement, then "skip_declarations"
4249 * indicates whether we should skip initial declarations in the
4250 * compound statement.
4252 * If the constructed pet_scop is not a (possibly) partial representation
4253 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4254 * In particular, if skip_declarations is set, then we may have skipped
4255 * declarations inside "stmt" and so the pet_scop may not represent
4256 * the entire "stmt".
4257 * Note that this function may be called with "stmt" referring to the entire
4258 * body of the function, including the outer braces. In such cases,
4259 * skip_declarations will be set and the braces will not be taken into
4260 * account in scop->start and scop->end.
4262 struct pet_scop
*PetScan::extract(Stmt
*stmt
, bool skip_declarations
)
4264 struct pet_scop
*scop
;
4266 if (isa
<Expr
>(stmt
))
4267 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
4269 switch (stmt
->getStmtClass()) {
4270 case Stmt::WhileStmtClass
:
4271 scop
= extract(cast
<WhileStmt
>(stmt
));
4273 case Stmt::ForStmtClass
:
4274 scop
= extract_for(cast
<ForStmt
>(stmt
));
4276 case Stmt::IfStmtClass
:
4277 scop
= extract(cast
<IfStmt
>(stmt
));
4279 case Stmt::CompoundStmtClass
:
4280 scop
= extract(cast
<CompoundStmt
>(stmt
), skip_declarations
);
4282 case Stmt::LabelStmtClass
:
4283 scop
= extract(cast
<LabelStmt
>(stmt
));
4285 case Stmt::ContinueStmtClass
:
4286 scop
= extract(cast
<ContinueStmt
>(stmt
));
4288 case Stmt::BreakStmtClass
:
4289 scop
= extract(cast
<BreakStmt
>(stmt
));
4291 case Stmt::DeclStmtClass
:
4292 scop
= extract(cast
<DeclStmt
>(stmt
));
4299 if (partial
|| skip_declarations
)
4302 scop
= update_scop_start_end(scop
, stmt
->getSourceRange(), false);
4307 /* Extract a clone of the kill statement in "scop".
4308 * "scop" is expected to have been created from a DeclStmt
4309 * and should have the kill as its first statement.
4311 struct pet_stmt
*PetScan::extract_kill(struct pet_scop
*scop
)
4314 struct pet_stmt
*stmt
;
4315 isl_multi_pw_aff
*index
;
4321 if (scop
->n_stmt
< 1)
4322 isl_die(ctx
, isl_error_internal
,
4323 "expecting at least one statement", return NULL
);
4324 stmt
= scop
->stmts
[0];
4325 if (!pet_stmt_is_kill(stmt
))
4326 isl_die(ctx
, isl_error_internal
,
4327 "expecting kill statement", return NULL
);
4329 arg
= pet_expr_get_arg(stmt
->body
, 0);
4330 index
= pet_expr_access_get_index(arg
);
4331 access
= pet_expr_access_get_access(arg
);
4333 index
= isl_multi_pw_aff_reset_tuple_id(index
, isl_dim_in
);
4334 access
= isl_map_reset_tuple_id(access
, isl_dim_in
);
4335 kill
= pet_expr_kill_from_access_and_index(access
, index
);
4336 return pet_stmt_from_pet_expr(stmt
->line
, NULL
, n_stmt
++, kill
);
4339 /* Mark all arrays in "scop" as being exposed.
4341 static struct pet_scop
*mark_exposed(struct pet_scop
*scop
)
4345 for (int i
= 0; i
< scop
->n_array
; ++i
)
4346 scop
->arrays
[i
]->exposed
= 1;
4350 /* Try and construct a pet_scop corresponding to (part of)
4351 * a sequence of statements.
4353 * "block" is set if the sequence respresents the children of
4354 * a compound statement.
4355 * "skip_declarations" is set if we should skip initial declarations
4356 * in the sequence of statements.
4358 * If there are any breaks or continues in the individual statements,
4359 * then we may have to compute a new skip condition.
4360 * This is handled using a pet_skip_info object.
4361 * On initialization, the object checks if skip conditions need
4362 * to be computed. If so, it does so in pet_skip_info_seq_extract and
4363 * adds them in pet_skip_info_seq_add.
4365 * If "block" is set, then we need to insert kill statements at
4366 * the end of the block for any array that has been declared by
4367 * one of the statements in the sequence. Each of these declarations
4368 * results in the construction of a kill statement at the place
4369 * of the declaration, so we simply collect duplicates of
4370 * those kill statements and append these duplicates to the constructed scop.
4372 * If "block" is not set, then any array declared by one of the statements
4373 * in the sequence is marked as being exposed.
4375 * If autodetect is set, then we allow the extraction of only a subrange
4376 * of the sequence of statements. However, if there is at least one statement
4377 * for which we could not construct a scop and the final range contains
4378 * either no statements or at least one kill, then we discard the entire
4381 struct pet_scop
*PetScan::extract(StmtRange stmt_range
, bool block
,
4382 bool skip_declarations
)
4388 bool partial_range
= false;
4389 set
<struct pet_stmt
*> kills
;
4390 set
<struct pet_stmt
*>::iterator it
;
4392 int_size
= ast_context
.getTypeInfo(ast_context
.IntTy
).first
/ 8;
4394 scop
= pet_scop_empty(ctx
);
4395 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
4397 struct pet_scop
*scop_i
;
4399 if (scop
->n_stmt
== 0 && skip_declarations
&&
4400 child
->getStmtClass() == Stmt::DeclStmtClass
)
4403 scop_i
= extract(child
);
4404 if (scop
->n_stmt
!= 0 && partial
) {
4405 pet_scop_free(scop_i
);
4409 pet_skip_info_seq_init(&skip
, ctx
, scop
, scop_i
);
4410 pet_skip_info_seq_extract(&skip
, int_size
, &n_stmt
, &n_test
);
4411 if (pet_skip_info_has_skip(&skip
))
4412 scop_i
= pet_scop_prefix(scop_i
, 0);
4413 if (scop_i
&& child
->getStmtClass() == Stmt::DeclStmtClass
) {
4415 kills
.insert(extract_kill(scop_i
));
4417 scop_i
= mark_exposed(scop_i
);
4419 scop_i
= pet_scop_prefix(scop_i
, j
);
4420 if (options
->autodetect
) {
4422 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4424 partial_range
= true;
4425 if (scop
->n_stmt
!= 0 && !scop_i
)
4428 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4431 scop
= pet_skip_info_seq_add(&skip
, scop
, j
);
4433 if (partial
|| !scop
)
4437 for (it
= kills
.begin(); it
!= kills
.end(); ++it
) {
4439 scop_j
= pet_scop_from_pet_stmt(ctx
, *it
);
4440 scop_j
= pet_scop_prefix(scop_j
, j
);
4441 scop
= pet_scop_add_seq(ctx
, scop
, scop_j
);
4444 if (scop
&& partial_range
) {
4445 if (scop
->n_stmt
== 0 || kills
.size() != 0) {
4446 pet_scop_free(scop
);
4455 /* Check if the scop marked by the user is exactly this Stmt
4456 * or part of this Stmt.
4457 * If so, return a pet_scop corresponding to the marked region.
4458 * Otherwise, return NULL.
4460 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
4462 SourceManager
&SM
= PP
.getSourceManager();
4463 unsigned start_off
, end_off
;
4465 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
4466 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
4468 if (start_off
> loc
.end
)
4470 if (end_off
< loc
.start
)
4472 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
4473 return extract(stmt
);
4477 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
4478 Stmt
*child
= *start
;
4481 start_off
= getExpansionOffset(SM
, child
->getLocStart());
4482 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
4483 if (start_off
< loc
.start
&& end_off
>= loc
.end
)
4485 if (start_off
>= loc
.start
)
4490 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
4492 start_off
= SM
.getFileOffset(child
->getLocStart());
4493 if (start_off
>= loc
.end
)
4497 return extract(StmtRange(start
, end
), false, false);
4500 /* Set the size of index "pos" of "array" to "size".
4501 * In particular, add a constraint of the form
4505 * to array->extent and a constraint of the form
4509 * to array->context.
4511 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
4512 __isl_take isl_pw_aff
*size
)
4522 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
4523 array
->context
= isl_set_intersect(array
->context
, valid
);
4525 dim
= isl_set_get_space(array
->extent
);
4526 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
4527 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
4528 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
4529 index
= isl_pw_aff_alloc(univ
, aff
);
4531 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
4532 isl_set_dim(array
->extent
, isl_dim_set
));
4533 id
= isl_set_get_tuple_id(array
->extent
);
4534 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
4535 bound
= isl_pw_aff_lt_set(index
, size
);
4537 array
->extent
= isl_set_intersect(array
->extent
, bound
);
4539 if (!array
->context
|| !array
->extent
)
4544 pet_array_free(array
);
4548 /* Figure out the size of the array at position "pos" and all
4549 * subsequent positions from "type" and update "array" accordingly.
4551 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
4552 const Type
*type
, int pos
)
4554 const ArrayType
*atype
;
4560 if (type
->isPointerType()) {
4561 type
= type
->getPointeeType().getTypePtr();
4562 return set_upper_bounds(array
, type
, pos
+ 1);
4564 if (!type
->isArrayType())
4567 type
= type
->getCanonicalTypeInternal().getTypePtr();
4568 atype
= cast
<ArrayType
>(type
);
4570 if (type
->isConstantArrayType()) {
4571 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
4572 size
= extract_affine(ca
->getSize());
4573 array
= update_size(array
, pos
, size
);
4574 } else if (type
->isVariableArrayType()) {
4575 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
4576 size
= extract_affine(vla
->getSizeExpr());
4577 array
= update_size(array
, pos
, size
);
4580 type
= atype
->getElementType().getTypePtr();
4582 return set_upper_bounds(array
, type
, pos
+ 1);
4585 /* Is "T" the type of a variable length array with static size?
4587 static bool is_vla_with_static_size(QualType T
)
4589 const VariableArrayType
*vlatype
;
4591 if (!T
->isVariableArrayType())
4593 vlatype
= cast
<VariableArrayType
>(T
);
4594 return vlatype
->getSizeModifier() == VariableArrayType::Static
;
4597 /* Return the type of "decl" as an array.
4599 * In particular, if "decl" is a parameter declaration that
4600 * is a variable length array with a static size, then
4601 * return the original type (i.e., the variable length array).
4602 * Otherwise, return the type of decl.
4604 static QualType
get_array_type(ValueDecl
*decl
)
4609 parm
= dyn_cast
<ParmVarDecl
>(decl
);
4611 return decl
->getType();
4613 T
= parm
->getOriginalType();
4614 if (!is_vla_with_static_size(T
))
4615 return decl
->getType();
4619 /* Does "decl" have definition that we can keep track of in a pet_type?
4621 static bool has_printable_definition(RecordDecl
*decl
)
4623 if (!decl
->getDeclName())
4625 return decl
->getLexicalDeclContext() == decl
->getDeclContext();
4628 /* Construct and return a pet_array corresponding to the variable "decl".
4629 * In particular, initialize array->extent to
4631 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4633 * and then call set_upper_bounds to set the upper bounds on the indices
4634 * based on the type of the variable.
4636 * If the base type is that of a record with a top-level definition and
4637 * if "types" is not null, then the RecordDecl corresponding to the type
4638 * is added to "types".
4640 * If the base type is that of a record with no top-level definition,
4641 * then we replace it by "<subfield>".
4643 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
,
4644 lex_recorddecl_set
*types
)
4646 struct pet_array
*array
;
4647 QualType qt
= get_array_type(decl
);
4648 const Type
*type
= qt
.getTypePtr();
4649 int depth
= array_depth(type
);
4650 QualType base
= pet_clang_base_type(qt
);
4655 array
= isl_calloc_type(ctx
, struct pet_array
);
4659 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
4660 dim
= isl_space_set_alloc(ctx
, 0, depth
);
4661 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
4663 array
->extent
= isl_set_nat_universe(dim
);
4665 dim
= isl_space_params_alloc(ctx
, 0);
4666 array
->context
= isl_set_universe(dim
);
4668 array
= set_upper_bounds(array
, type
, 0);
4672 name
= base
.getAsString();
4674 if (types
&& base
->isRecordType()) {
4675 RecordDecl
*decl
= pet_clang_record_decl(base
);
4676 if (has_printable_definition(decl
))
4677 types
->insert(decl
);
4679 name
= "<subfield>";
4682 array
->element_type
= strdup(name
.c_str());
4683 array
->element_is_record
= base
->isRecordType();
4684 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
4689 /* Construct and return a pet_array corresponding to the sequence
4690 * of declarations "decls".
4691 * If the sequence contains a single declaration, then it corresponds
4692 * to a simple array access. Otherwise, it corresponds to a member access,
4693 * with the declaration for the substructure following that of the containing
4694 * structure in the sequence of declarations.
4695 * We start with the outermost substructure and then combine it with
4696 * information from the inner structures.
4698 * Additionally, keep track of all required types in "types".
4700 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
,
4701 vector
<ValueDecl
*> decls
, lex_recorddecl_set
*types
)
4703 struct pet_array
*array
;
4704 vector
<ValueDecl
*>::iterator it
;
4708 array
= extract_array(ctx
, *it
, types
);
4710 for (++it
; it
!= decls
.end(); ++it
) {
4711 struct pet_array
*parent
;
4712 const char *base_name
, *field_name
;
4716 array
= extract_array(ctx
, *it
, types
);
4718 return pet_array_free(parent
);
4720 base_name
= isl_set_get_tuple_name(parent
->extent
);
4721 field_name
= isl_set_get_tuple_name(array
->extent
);
4722 product_name
= member_access_name(ctx
, base_name
, field_name
);
4724 array
->extent
= isl_set_product(isl_set_copy(parent
->extent
),
4727 array
->extent
= isl_set_set_tuple_name(array
->extent
,
4729 array
->context
= isl_set_intersect(array
->context
,
4730 isl_set_copy(parent
->context
));
4732 pet_array_free(parent
);
4735 if (!array
->extent
|| !array
->context
|| !product_name
)
4736 return pet_array_free(array
);
4742 /* Add a pet_type corresponding to "decl" to "scop, provided
4743 * it is a member of "types" and it has not been added before
4744 * (i.e., it is not a member of "types_done".
4746 * Since we want the user to be able to print the types
4747 * in the order in which they appear in the scop, we need to
4748 * make sure that types of fields in a structure appear before
4749 * that structure. We therefore call ourselves recursively
4750 * on the types of all record subfields.
4752 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
4753 RecordDecl
*decl
, Preprocessor
&PP
, lex_recorddecl_set
&types
,
4754 lex_recorddecl_set
&types_done
)
4757 llvm::raw_string_ostream
S(s
);
4758 RecordDecl::field_iterator it
;
4760 if (types
.find(decl
) == types
.end())
4762 if (types_done
.find(decl
) != types_done
.end())
4765 for (it
= decl
->field_begin(); it
!= decl
->field_end(); ++it
) {
4767 QualType type
= it
->getType();
4769 if (!type
->isRecordType())
4771 record
= pet_clang_record_decl(type
);
4772 scop
= add_type(ctx
, scop
, record
, PP
, types
, types_done
);
4775 if (strlen(decl
->getName().str().c_str()) == 0)
4778 decl
->print(S
, PrintingPolicy(PP
.getLangOpts()));
4781 scop
->types
[scop
->n_type
] = pet_type_alloc(ctx
,
4782 decl
->getName().str().c_str(), s
.c_str());
4783 if (!scop
->types
[scop
->n_type
])
4784 return pet_scop_free(scop
);
4786 types_done
.insert(decl
);
4793 /* Construct a list of pet_arrays, one for each array (or scalar)
4794 * accessed inside "scop", add this list to "scop" and return the result.
4796 * The context of "scop" is updated with the intersection of
4797 * the contexts of all arrays, i.e., constraints on the parameters
4798 * that ensure that the arrays have a valid (non-negative) size.
4800 * If the any of the extracted arrays refers to a member access,
4801 * then also add the required types to "scop".
4803 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
4806 array_desc_set arrays
;
4807 array_desc_set::iterator it
;
4808 lex_recorddecl_set types
;
4809 lex_recorddecl_set types_done
;
4810 lex_recorddecl_set::iterator types_it
;
4812 struct pet_array
**scop_arrays
;
4817 pet_scop_collect_arrays(scop
, arrays
);
4818 if (arrays
.size() == 0)
4821 n_array
= scop
->n_array
;
4823 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
4824 n_array
+ arrays
.size());
4827 scop
->arrays
= scop_arrays
;
4829 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
4830 struct pet_array
*array
;
4831 array
= extract_array(ctx
, *it
, &types
);
4832 scop
->arrays
[n_array
+ i
] = array
;
4833 if (!scop
->arrays
[n_array
+ i
])
4836 scop
->context
= isl_set_intersect(scop
->context
,
4837 isl_set_copy(array
->context
));
4842 if (types
.size() == 0)
4845 scop
->types
= isl_alloc_array(ctx
, struct pet_type
*, types
.size());
4849 for (types_it
= types
.begin(); types_it
!= types
.end(); ++types_it
)
4850 scop
= add_type(ctx
, scop
, *types_it
, PP
, types
, types_done
);
4854 pet_scop_free(scop
);
4858 /* Bound all parameters in scop->context to the possible values
4859 * of the corresponding C variable.
4861 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
4868 n
= isl_set_dim(scop
->context
, isl_dim_param
);
4869 for (int i
= 0; i
< n
; ++i
) {
4873 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
4874 if (pet_nested_in_id(id
)) {
4876 isl_die(isl_set_get_ctx(scop
->context
),
4878 "unresolved nested parameter", goto error
);
4880 decl
= (ValueDecl
*) isl_id_get_user(id
);
4883 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
4891 pet_scop_free(scop
);
4895 /* Construct a pet_scop from the given function.
4897 * If the scop was delimited by scop and endscop pragmas, then we override
4898 * the file offsets by those derived from the pragmas.
4900 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
4905 stmt
= fd
->getBody();
4907 if (options
->autodetect
)
4908 scop
= extract(stmt
, true);
4911 scop
= pet_scop_update_start_end(scop
, loc
.start
, loc
.end
);
4913 scop
= pet_scop_detect_parameter_accesses(scop
);
4914 scop
= scan_arrays(scop
);
4915 scop
= add_parameter_bounds(scop
);
4916 scop
= pet_scop_gist(scop
, value_bounds
);