2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012 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
38 #include <clang/AST/ASTDiagnostic.h>
39 #include <clang/AST/Expr.h>
40 #include <clang/AST/RecursiveASTVisitor.h>
43 #include <isl/space.h>
49 #include "scop_plus.h"
54 using namespace clang
;
56 #ifdef DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION
57 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
59 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
60 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
64 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
66 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
67 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
71 /* Check if the element type corresponding to the given array type
72 * has a const qualifier.
74 static bool const_base(QualType qt
)
76 const Type
*type
= qt
.getTypePtr();
78 if (type
->isPointerType())
79 return const_base(type
->getPointeeType());
80 if (type
->isArrayType()) {
81 const ArrayType
*atype
;
82 type
= type
->getCanonicalTypeInternal().getTypePtr();
83 atype
= cast
<ArrayType
>(type
);
84 return const_base(atype
->getElementType());
87 return qt
.isConstQualified();
90 /* Mark "decl" as having an unknown value in "assigned_value".
92 * If no (known or unknown) value was assigned to "decl" before,
93 * then it may have been treated as a parameter before and may
94 * therefore appear in a value assigned to another variable.
95 * If so, this assignment needs to be turned into an unknown value too.
97 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
100 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
102 it
= assigned_value
.find(decl
);
104 assigned_value
[decl
] = NULL
;
106 if (it
== assigned_value
.end())
109 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
110 isl_pw_aff
*pa
= it
->second
;
111 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
113 for (int i
= 0; i
< nparam
; ++i
) {
116 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
118 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
119 if (isl_id_get_user(id
) == decl
)
126 /* Look for any assignments to scalar variables in part of the parse
127 * tree and set assigned_value to NULL for each of them.
128 * Also reset assigned_value if the address of a scalar variable
129 * is being taken. As an exception, if the address is passed to a function
130 * that is declared to receive a const pointer, then assigned_value is
133 * This ensures that we won't use any previously stored value
134 * in the current subtree and its parents.
136 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
137 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
138 set
<UnaryOperator
*> skip
;
140 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
141 assigned_value(assigned_value
) {}
143 /* Check for "address of" operators whose value is passed
144 * to a const pointer argument and add them to "skip", so that
145 * we can skip them in VisitUnaryOperator.
147 bool VisitCallExpr(CallExpr
*expr
) {
149 fd
= expr
->getDirectCallee();
152 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
153 Expr
*arg
= expr
->getArg(i
);
155 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
156 ImplicitCastExpr
*ice
;
157 ice
= cast
<ImplicitCastExpr
>(arg
);
158 arg
= ice
->getSubExpr();
160 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
162 op
= cast
<UnaryOperator
>(arg
);
163 if (op
->getOpcode() != UO_AddrOf
)
165 if (const_base(fd
->getParamDecl(i
)->getType()))
171 bool VisitUnaryOperator(UnaryOperator
*expr
) {
176 if (expr
->getOpcode() != UO_AddrOf
)
178 if (skip
.find(expr
) != skip
.end())
181 arg
= expr
->getSubExpr();
182 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
184 ref
= cast
<DeclRefExpr
>(arg
);
185 decl
= ref
->getDecl();
186 clear_assignment(assigned_value
, decl
);
190 bool VisitBinaryOperator(BinaryOperator
*expr
) {
195 if (!expr
->isAssignmentOp())
197 lhs
= expr
->getLHS();
198 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
200 ref
= cast
<DeclRefExpr
>(lhs
);
201 decl
= ref
->getDecl();
202 clear_assignment(assigned_value
, decl
);
207 /* Keep a copy of the currently assigned values.
209 * Any variable that is assigned a value inside the current scope
210 * is removed again when we leave the scope (either because it wasn't
211 * stored in the cache or because it has a different value in the cache).
213 struct assigned_value_cache
{
214 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
215 map
<ValueDecl
*, isl_pw_aff
*> cache
;
217 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
218 assigned_value(assigned_value
), cache(assigned_value
) {}
219 ~assigned_value_cache() {
220 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
221 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
224 (cache
.find(it
->first
) != cache
.end() &&
225 cache
[it
->first
] != it
->second
))
226 cache
[it
->first
] = NULL
;
228 assigned_value
= cache
;
232 /* Insert an expression into the collection of expressions,
233 * provided it is not already in there.
234 * The isl_pw_affs are freed in the destructor.
236 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
238 std::set
<isl_pw_aff
*>::iterator it
;
240 if (expressions
.find(expr
) == expressions
.end())
241 expressions
.insert(expr
);
243 isl_pw_aff_free(expr
);
248 std::set
<isl_pw_aff
*>::iterator it
;
250 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
251 isl_pw_aff_free(*it
);
253 isl_union_map_free(value_bounds
);
256 /* Called if we found something we (currently) cannot handle.
257 * We'll provide more informative warnings later.
259 * We only actually complain if autodetect is false.
261 void PetScan::unsupported(Stmt
*stmt
, const char *msg
)
266 SourceLocation loc
= stmt
->getLocStart();
267 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
268 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
269 msg
? msg
: "unsupported");
270 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
273 /* Extract an integer from "expr" and store it in "v".
275 int PetScan::extract_int(IntegerLiteral
*expr
, isl_int
*v
)
277 const Type
*type
= expr
->getType().getTypePtr();
278 int is_signed
= type
->hasSignedIntegerRepresentation();
281 int64_t i
= expr
->getValue().getSExtValue();
282 isl_int_set_si(*v
, i
);
284 uint64_t i
= expr
->getValue().getZExtValue();
285 isl_int_set_ui(*v
, i
);
291 /* Extract an integer from "expr" and store it in "v".
292 * Return -1 if "expr" does not (obviously) represent an integer.
294 int PetScan::extract_int(clang::ParenExpr
*expr
, isl_int
*v
)
296 return extract_int(expr
->getSubExpr(), v
);
299 /* Extract an integer from "expr" and store it in "v".
300 * Return -1 if "expr" does not (obviously) represent an integer.
302 int PetScan::extract_int(clang::Expr
*expr
, isl_int
*v
)
304 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
305 return extract_int(cast
<IntegerLiteral
>(expr
), v
);
306 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
307 return extract_int(cast
<ParenExpr
>(expr
), v
);
313 /* Extract an affine expression from the IntegerLiteral "expr".
315 __isl_give isl_pw_aff
*PetScan::extract_affine(IntegerLiteral
*expr
)
317 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
318 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
319 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
320 isl_set
*dom
= isl_set_universe(dim
);
324 extract_int(expr
, &v
);
325 aff
= isl_aff_add_constant(aff
, v
);
328 return isl_pw_aff_alloc(dom
, aff
);
331 /* Extract an affine expression from the APInt "val".
333 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
335 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
336 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
337 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
338 isl_set
*dom
= isl_set_universe(dim
);
342 isl_int_set_ui(v
, val
.getZExtValue());
343 aff
= isl_aff_add_constant(aff
, v
);
346 return isl_pw_aff_alloc(dom
, aff
);
349 __isl_give isl_pw_aff
*PetScan::extract_affine(ImplicitCastExpr
*expr
)
351 return extract_affine(expr
->getSubExpr());
354 static unsigned get_type_size(ValueDecl
*decl
)
356 return decl
->getASTContext().getIntWidth(decl
->getType());
359 /* Bound parameter "pos" of "set" to the possible values of "decl".
361 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
362 unsigned pos
, ValueDecl
*decl
)
369 width
= get_type_size(decl
);
370 if (decl
->getType()->isUnsignedIntegerType()) {
371 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
372 isl_int_set_si(v
, 1);
373 isl_int_mul_2exp(v
, v
, width
);
374 isl_int_sub_ui(v
, v
, 1);
375 set
= isl_set_upper_bound(set
, isl_dim_param
, pos
, v
);
377 isl_int_set_si(v
, 1);
378 isl_int_mul_2exp(v
, v
, width
- 1);
379 isl_int_sub_ui(v
, v
, 1);
380 set
= isl_set_upper_bound(set
, isl_dim_param
, pos
, v
);
382 isl_int_sub_ui(v
, v
, 1);
383 set
= isl_set_lower_bound(set
, isl_dim_param
, pos
, v
);
391 /* Extract an affine expression from the DeclRefExpr "expr".
393 * If the variable has been assigned a value, then we check whether
394 * we know what (affine) value was assigned.
395 * If so, we return this value. Otherwise we convert "expr"
396 * to an extra parameter (provided nesting_enabled is set).
398 * Otherwise, we simply return an expression that is equal
399 * to a parameter corresponding to the referenced variable.
401 __isl_give isl_pw_aff
*PetScan::extract_affine(DeclRefExpr
*expr
)
403 ValueDecl
*decl
= expr
->getDecl();
404 const Type
*type
= decl
->getType().getTypePtr();
410 if (!type
->isIntegerType()) {
415 if (assigned_value
.find(decl
) != assigned_value
.end()) {
416 if (assigned_value
[decl
])
417 return isl_pw_aff_copy(assigned_value
[decl
]);
419 return nested_access(expr
);
422 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
423 dim
= isl_space_params_alloc(ctx
, 1);
425 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
427 dom
= isl_set_universe(isl_space_copy(dim
));
428 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
429 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
431 return isl_pw_aff_alloc(dom
, aff
);
434 /* Extract an affine expression from an integer division operation.
435 * In particular, if "expr" is lhs/rhs, then return
437 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
439 * The second argument (rhs) is required to be a (positive) integer constant.
441 __isl_give isl_pw_aff
*PetScan::extract_affine_div(BinaryOperator
*expr
)
444 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
449 rhs_expr
= expr
->getRHS();
451 if (extract_int(rhs_expr
, &v
) < 0) {
456 lhs
= extract_affine(expr
->getLHS());
457 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
459 lhs
= isl_pw_aff_scale_down(lhs
, v
);
462 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(lhs
));
463 lhs_c
= isl_pw_aff_ceil(lhs
);
464 res
= isl_pw_aff_cond(isl_set_indicator_function(cond
), lhs_f
, lhs_c
);
469 /* Extract an affine expression from a modulo operation.
470 * In particular, if "expr" is lhs/rhs, then return
472 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
474 * The second argument (rhs) is required to be a (positive) integer constant.
476 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
479 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
484 rhs_expr
= expr
->getRHS();
485 if (rhs_expr
->getStmtClass() != Stmt::IntegerLiteralClass
) {
490 lhs
= extract_affine(expr
->getLHS());
491 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
494 extract_int(cast
<IntegerLiteral
>(rhs_expr
), &v
);
495 res
= isl_pw_aff_scale_down(isl_pw_aff_copy(lhs
), v
);
497 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(res
));
498 lhs_c
= isl_pw_aff_ceil(res
);
499 res
= isl_pw_aff_cond(isl_set_indicator_function(cond
), lhs_f
, lhs_c
);
501 res
= isl_pw_aff_scale(res
, v
);
504 res
= isl_pw_aff_sub(lhs
, res
);
509 /* Extract an affine expression from a multiplication operation.
510 * This is only allowed if at least one of the two arguments
511 * is a (piecewise) constant.
513 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
518 lhs
= extract_affine(expr
->getLHS());
519 rhs
= extract_affine(expr
->getRHS());
521 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
522 isl_pw_aff_free(lhs
);
523 isl_pw_aff_free(rhs
);
528 return isl_pw_aff_mul(lhs
, rhs
);
531 /* Extract an affine expression from an addition or subtraction operation.
533 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
538 lhs
= extract_affine(expr
->getLHS());
539 rhs
= extract_affine(expr
->getRHS());
541 switch (expr
->getOpcode()) {
543 return isl_pw_aff_add(lhs
, rhs
);
545 return isl_pw_aff_sub(lhs
, rhs
);
547 isl_pw_aff_free(lhs
);
548 isl_pw_aff_free(rhs
);
558 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
564 isl_int_set_si(mod
, 1);
565 isl_int_mul_2exp(mod
, mod
, width
);
567 pwaff
= isl_pw_aff_mod(pwaff
, mod
);
574 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
576 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
577 __isl_take isl_set
*dom
)
580 pa
= isl_set_indicator_function(set
);
581 pa
= isl_pw_aff_intersect_domain(pa
, dom
);
585 /* Extract an affine expression from some binary operations.
586 * If the result of the expression is unsigned, then we wrap it
587 * based on the size of the type.
589 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
593 switch (expr
->getOpcode()) {
596 res
= extract_affine_add(expr
);
599 res
= extract_affine_div(expr
);
602 res
= extract_affine_mod(expr
);
605 res
= extract_affine_mul(expr
);
615 res
= extract_condition(expr
);
622 if (expr
->getType()->isUnsignedIntegerType())
623 res
= wrap(res
, ast_context
.getIntWidth(expr
->getType()));
628 /* Extract an affine expression from a negation operation.
630 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
632 if (expr
->getOpcode() == UO_Minus
)
633 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
634 if (expr
->getOpcode() == UO_LNot
)
635 return extract_condition(expr
);
641 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
643 return extract_affine(expr
->getSubExpr());
646 /* Extract an affine expression from some special function calls.
647 * In particular, we handle "min", "max", "ceild" and "floord".
648 * In case of the latter two, the second argument needs to be
649 * a (positive) integer constant.
651 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
655 isl_pw_aff
*aff1
, *aff2
;
657 fd
= expr
->getDirectCallee();
663 name
= fd
->getDeclName().getAsString();
664 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
665 !(expr
->getNumArgs() == 2 && name
== "max") &&
666 !(expr
->getNumArgs() == 2 && name
== "floord") &&
667 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
672 if (name
== "min" || name
== "max") {
673 aff1
= extract_affine(expr
->getArg(0));
674 aff2
= extract_affine(expr
->getArg(1));
677 aff1
= isl_pw_aff_min(aff1
, aff2
);
679 aff1
= isl_pw_aff_max(aff1
, aff2
);
680 } else if (name
== "floord" || name
== "ceild") {
682 Expr
*arg2
= expr
->getArg(1);
684 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
688 aff1
= extract_affine(expr
->getArg(0));
690 extract_int(cast
<IntegerLiteral
>(arg2
), &v
);
691 aff1
= isl_pw_aff_scale_down(aff1
, v
);
693 if (name
== "floord")
694 aff1
= isl_pw_aff_floor(aff1
);
696 aff1
= isl_pw_aff_ceil(aff1
);
706 /* This method is called when we come across an access that is
707 * nested in what is supposed to be an affine expression.
708 * If nesting is allowed, we return a new parameter that corresponds
709 * to this nested access. Otherwise, we simply complain.
711 * The new parameter is resolved in resolve_nested.
713 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
720 if (!nesting_enabled
) {
725 id
= isl_id_alloc(ctx
, NULL
, expr
);
726 dim
= isl_space_params_alloc(ctx
, 1);
728 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
730 dom
= isl_set_universe(isl_space_copy(dim
));
731 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
732 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
734 return isl_pw_aff_alloc(dom
, aff
);
737 /* Affine expressions are not supposed to contain array accesses,
738 * but if nesting is allowed, we return a parameter corresponding
739 * to the array access.
741 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
743 return nested_access(expr
);
746 /* Extract an affine expression from a conditional operation.
748 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
750 isl_pw_aff
*cond
, *lhs
, *rhs
, *res
;
752 cond
= extract_condition(expr
->getCond());
753 lhs
= extract_affine(expr
->getTrueExpr());
754 rhs
= extract_affine(expr
->getFalseExpr());
756 return isl_pw_aff_cond(cond
, lhs
, rhs
);
759 /* Extract an affine expression, if possible, from "expr".
760 * Otherwise return NULL.
762 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
764 switch (expr
->getStmtClass()) {
765 case Stmt::ImplicitCastExprClass
:
766 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
767 case Stmt::IntegerLiteralClass
:
768 return extract_affine(cast
<IntegerLiteral
>(expr
));
769 case Stmt::DeclRefExprClass
:
770 return extract_affine(cast
<DeclRefExpr
>(expr
));
771 case Stmt::BinaryOperatorClass
:
772 return extract_affine(cast
<BinaryOperator
>(expr
));
773 case Stmt::UnaryOperatorClass
:
774 return extract_affine(cast
<UnaryOperator
>(expr
));
775 case Stmt::ParenExprClass
:
776 return extract_affine(cast
<ParenExpr
>(expr
));
777 case Stmt::CallExprClass
:
778 return extract_affine(cast
<CallExpr
>(expr
));
779 case Stmt::ArraySubscriptExprClass
:
780 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
781 case Stmt::ConditionalOperatorClass
:
782 return extract_affine(cast
<ConditionalOperator
>(expr
));
789 __isl_give isl_map
*PetScan::extract_access(ImplicitCastExpr
*expr
)
791 return extract_access(expr
->getSubExpr());
794 /* Return the depth of an array of the given type.
796 static int array_depth(const Type
*type
)
798 if (type
->isPointerType())
799 return 1 + array_depth(type
->getPointeeType().getTypePtr());
800 if (type
->isArrayType()) {
801 const ArrayType
*atype
;
802 type
= type
->getCanonicalTypeInternal().getTypePtr();
803 atype
= cast
<ArrayType
>(type
);
804 return 1 + array_depth(atype
->getElementType().getTypePtr());
809 /* Return the element type of the given array type.
811 static QualType
base_type(QualType qt
)
813 const Type
*type
= qt
.getTypePtr();
815 if (type
->isPointerType())
816 return base_type(type
->getPointeeType());
817 if (type
->isArrayType()) {
818 const ArrayType
*atype
;
819 type
= type
->getCanonicalTypeInternal().getTypePtr();
820 atype
= cast
<ArrayType
>(type
);
821 return base_type(atype
->getElementType());
826 /* Extract an access relation from a reference to a variable.
827 * If the variable has name "A" and its type corresponds to an
828 * array of depth d, then the returned access relation is of the
831 * { [] -> A[i_1,...,i_d] }
833 __isl_give isl_map
*PetScan::extract_access(DeclRefExpr
*expr
)
835 ValueDecl
*decl
= expr
->getDecl();
836 int depth
= array_depth(decl
->getType().getTypePtr());
837 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
838 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, depth
);
841 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
843 access_rel
= isl_map_universe(dim
);
848 /* Extract an access relation from an integer contant.
849 * If the value of the constant is "v", then the returned access relation
854 __isl_give isl_map
*PetScan::extract_access(IntegerLiteral
*expr
)
856 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr
)));
859 /* Try and extract an access relation from the given Expr.
860 * Return NULL if it doesn't work out.
862 __isl_give isl_map
*PetScan::extract_access(Expr
*expr
)
864 switch (expr
->getStmtClass()) {
865 case Stmt::ImplicitCastExprClass
:
866 return extract_access(cast
<ImplicitCastExpr
>(expr
));
867 case Stmt::DeclRefExprClass
:
868 return extract_access(cast
<DeclRefExpr
>(expr
));
869 case Stmt::ArraySubscriptExprClass
:
870 return extract_access(cast
<ArraySubscriptExpr
>(expr
));
877 /* Assign the affine expression "index" to the output dimension "pos" of "map"
878 * and return the result.
880 __isl_give isl_map
*set_index(__isl_take isl_map
*map
, int pos
,
881 __isl_take isl_pw_aff
*index
)
884 int len
= isl_map_dim(map
, isl_dim_out
);
887 index_map
= isl_map_from_range(isl_set_from_pw_aff(index
));
888 index_map
= isl_map_insert_dims(index_map
, isl_dim_out
, 0, pos
);
889 index_map
= isl_map_add_dims(index_map
, isl_dim_out
, len
- pos
- 1);
890 id
= isl_map_get_tuple_id(map
, isl_dim_out
);
891 index_map
= isl_map_set_tuple_id(index_map
, isl_dim_out
, id
);
893 map
= isl_map_intersect(map
, index_map
);
898 /* Extract an access relation from the given array subscript expression.
899 * If nesting is allowed in general, then we turn it on while
900 * examining the index expression.
902 * We first extract an access relation from the base.
903 * This will result in an access relation with a range that corresponds
904 * to the array being accessed and with earlier indices filled in already.
905 * We then extract the current index and fill that in as well.
906 * The position of the current index is based on the type of base.
907 * If base is the actual array variable, then the depth of this type
908 * will be the same as the depth of the array and we will fill in
909 * the first array index.
910 * Otherwise, the depth of the base type will be smaller and we will fill
913 __isl_give isl_map
*PetScan::extract_access(ArraySubscriptExpr
*expr
)
915 Expr
*base
= expr
->getBase();
916 Expr
*idx
= expr
->getIdx();
918 isl_map
*base_access
;
920 int depth
= array_depth(base
->getType().getTypePtr());
922 bool save_nesting
= nesting_enabled
;
924 nesting_enabled
= allow_nested
;
926 base_access
= extract_access(base
);
927 index
= extract_affine(idx
);
929 nesting_enabled
= save_nesting
;
931 pos
= isl_map_dim(base_access
, isl_dim_out
) - depth
;
932 access
= set_index(base_access
, pos
, index
);
937 /* Check if "expr" calls function "minmax" with two arguments and if so
938 * make lhs and rhs refer to these two arguments.
940 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
946 if (expr
->getStmtClass() != Stmt::CallExprClass
)
949 call
= cast
<CallExpr
>(expr
);
950 fd
= call
->getDirectCallee();
954 if (call
->getNumArgs() != 2)
957 name
= fd
->getDeclName().getAsString();
961 lhs
= call
->getArg(0);
962 rhs
= call
->getArg(1);
967 /* Check if "expr" is of the form min(lhs, rhs) and if so make
968 * lhs and rhs refer to the two arguments.
970 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
972 return is_minmax(expr
, "min", lhs
, rhs
);
975 /* Check if "expr" is of the form max(lhs, rhs) and if so make
976 * lhs and rhs refer to the two arguments.
978 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
980 return is_minmax(expr
, "max", lhs
, rhs
);
983 /* Return "lhs && rhs", defined on the shared definition domain.
985 static __isl_give isl_pw_aff
*pw_aff_and(__isl_take isl_pw_aff
*lhs
,
986 __isl_take isl_pw_aff
*rhs
)
991 dom
= isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs
)),
992 isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
993 cond
= isl_set_intersect(isl_pw_aff_non_zero_set(lhs
),
994 isl_pw_aff_non_zero_set(rhs
));
995 return indicator_function(cond
, dom
);
998 /* Return "lhs && rhs", with shortcut semantics.
999 * That is, if lhs is false, then the result is defined even if rhs is not.
1000 * In practice, we compute lhs ? rhs : lhs.
1002 static __isl_give isl_pw_aff
*pw_aff_and_then(__isl_take isl_pw_aff
*lhs
,
1003 __isl_take isl_pw_aff
*rhs
)
1005 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), rhs
, lhs
);
1008 /* Return "lhs || rhs", with shortcut semantics.
1009 * That is, if lhs is true, then the result is defined even if rhs is not.
1010 * In practice, we compute lhs ? lhs : rhs.
1012 static __isl_give isl_pw_aff
*pw_aff_or_else(__isl_take isl_pw_aff
*lhs
,
1013 __isl_take isl_pw_aff
*rhs
)
1015 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), lhs
, rhs
);
1018 /* Extract an affine expressions representing the comparison "LHS op RHS"
1019 * "comp" is the original statement that "LHS op RHS" is derived from
1020 * and is used for diagnostics.
1022 * If the comparison is of the form
1026 * then the expression is constructed as the conjunction of
1031 * A similar optimization is performed for max(a,b) <= c.
1032 * We do this because that will lead to simpler representations
1033 * of the expression.
1034 * If isl is ever enhanced to explicitly deal with min and max expressions,
1035 * this optimization can be removed.
1037 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
1038 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
1047 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
1049 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
1051 if (op
== BO_LT
|| op
== BO_LE
) {
1052 Expr
*expr1
, *expr2
;
1053 if (is_min(RHS
, expr1
, expr2
)) {
1054 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
1055 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
1056 return pw_aff_and(lhs
, rhs
);
1058 if (is_max(LHS
, expr1
, expr2
)) {
1059 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
1060 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
1061 return pw_aff_and(lhs
, rhs
);
1065 lhs
= extract_affine(LHS
);
1066 rhs
= extract_affine(RHS
);
1068 dom
= isl_pw_aff_domain(isl_pw_aff_copy(lhs
));
1069 dom
= isl_set_intersect(dom
, isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1073 cond
= isl_pw_aff_lt_set(lhs
, rhs
);
1076 cond
= isl_pw_aff_le_set(lhs
, rhs
);
1079 cond
= isl_pw_aff_eq_set(lhs
, rhs
);
1082 cond
= isl_pw_aff_ne_set(lhs
, rhs
);
1085 isl_pw_aff_free(lhs
);
1086 isl_pw_aff_free(rhs
);
1092 cond
= isl_set_coalesce(cond
);
1093 res
= indicator_function(cond
, dom
);
1098 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
1100 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1101 comp
->getRHS(), comp
);
1104 /* Extract an affine expression representing the negation (logical not)
1105 * of a subexpression.
1107 __isl_give isl_pw_aff
*PetScan::extract_boolean(UnaryOperator
*op
)
1109 isl_set
*set_cond
, *dom
;
1110 isl_pw_aff
*cond
, *res
;
1112 cond
= extract_condition(op
->getSubExpr());
1114 dom
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
1116 set_cond
= isl_pw_aff_zero_set(cond
);
1118 res
= indicator_function(set_cond
, dom
);
1123 /* Extract an affine expression representing the disjunction (logical or)
1124 * or conjunction (logical and) of two subexpressions.
1126 __isl_give isl_pw_aff
*PetScan::extract_boolean(BinaryOperator
*comp
)
1128 isl_pw_aff
*lhs
, *rhs
;
1130 lhs
= extract_condition(comp
->getLHS());
1131 rhs
= extract_condition(comp
->getRHS());
1133 switch (comp
->getOpcode()) {
1135 return pw_aff_and_then(lhs
, rhs
);
1137 return pw_aff_or_else(lhs
, rhs
);
1139 isl_pw_aff_free(lhs
);
1140 isl_pw_aff_free(rhs
);
1147 __isl_give isl_pw_aff
*PetScan::extract_condition(UnaryOperator
*expr
)
1149 switch (expr
->getOpcode()) {
1151 return extract_boolean(expr
);
1158 /* Extract the affine expression "expr != 0 ? 1 : 0".
1160 __isl_give isl_pw_aff
*PetScan::extract_implicit_condition(Expr
*expr
)
1165 res
= extract_affine(expr
);
1167 dom
= isl_pw_aff_domain(isl_pw_aff_copy(res
));
1168 set
= isl_pw_aff_non_zero_set(res
);
1170 res
= indicator_function(set
, dom
);
1175 /* Extract an affine expression from a boolean expression.
1176 * In particular, return the expression "expr ? 1 : 0".
1178 * If the expression doesn't look like a condition, we assume it
1179 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1181 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
1183 BinaryOperator
*comp
;
1186 isl_set
*u
= isl_set_universe(isl_space_params_alloc(ctx
, 0));
1187 return indicator_function(u
, isl_set_copy(u
));
1190 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1191 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1193 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1194 return extract_condition(cast
<UnaryOperator
>(expr
));
1196 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1197 return extract_implicit_condition(expr
);
1199 comp
= cast
<BinaryOperator
>(expr
);
1200 switch (comp
->getOpcode()) {
1207 return extract_comparison(comp
);
1210 return extract_boolean(comp
);
1212 return extract_implicit_condition(expr
);
1216 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
1220 return pet_op_minus
;
1226 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
1230 return pet_op_add_assign
;
1232 return pet_op_sub_assign
;
1234 return pet_op_mul_assign
;
1236 return pet_op_div_assign
;
1238 return pet_op_assign
;
1260 /* Construct a pet_expr representing a unary operator expression.
1262 struct pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1264 struct pet_expr
*arg
;
1265 enum pet_op_type op
;
1267 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1268 if (op
== pet_op_last
) {
1273 arg
= extract_expr(expr
->getSubExpr());
1275 return pet_expr_new_unary(ctx
, op
, arg
);
1278 /* Mark the given access pet_expr as a write.
1279 * If a scalar is being accessed, then mark its value
1280 * as unknown in assigned_value.
1282 void PetScan::mark_write(struct pet_expr
*access
)
1287 access
->acc
.write
= 1;
1288 access
->acc
.read
= 0;
1290 if (isl_map_dim(access
->acc
.access
, isl_dim_out
) != 0)
1293 id
= isl_map_get_tuple_id(access
->acc
.access
, isl_dim_out
);
1294 decl
= (ValueDecl
*) isl_id_get_user(id
);
1295 clear_assignment(assigned_value
, decl
);
1299 /* Construct a pet_expr representing a binary operator expression.
1301 * If the top level operator is an assignment and the LHS is an access,
1302 * then we mark that access as a write. If the operator is a compound
1303 * assignment, the access is marked as both a read and a write.
1305 * If "expr" assigns something to a scalar variable, then we mark
1306 * the variable as having been assigned. If, furthermore, the expression
1307 * is affine, then keep track of this value in assigned_value
1308 * so that we can plug it in when we later come across the same variable.
1310 struct pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1312 struct pet_expr
*lhs
, *rhs
;
1313 enum pet_op_type op
;
1315 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1316 if (op
== pet_op_last
) {
1321 lhs
= extract_expr(expr
->getLHS());
1322 rhs
= extract_expr(expr
->getRHS());
1324 if (expr
->isAssignmentOp() && lhs
&& lhs
->type
== pet_expr_access
) {
1326 if (expr
->isCompoundAssignmentOp())
1330 if (expr
->getOpcode() == BO_Assign
&&
1331 lhs
&& lhs
->type
== pet_expr_access
&&
1332 isl_map_dim(lhs
->acc
.access
, isl_dim_out
) == 0) {
1333 isl_id
*id
= isl_map_get_tuple_id(lhs
->acc
.access
, isl_dim_out
);
1334 ValueDecl
*decl
= (ValueDecl
*) isl_id_get_user(id
);
1335 Expr
*rhs
= expr
->getRHS();
1336 isl_pw_aff
*pa
= try_extract_affine(rhs
);
1337 clear_assignment(assigned_value
, decl
);
1339 assigned_value
[decl
] = pa
;
1340 insert_expression(pa
);
1345 return pet_expr_new_binary(ctx
, op
, lhs
, rhs
);
1348 /* Construct a pet_expr representing a conditional operation.
1350 struct pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1352 struct pet_expr
*cond
, *lhs
, *rhs
;
1354 cond
= extract_expr(expr
->getCond());
1355 lhs
= extract_expr(expr
->getTrueExpr());
1356 rhs
= extract_expr(expr
->getFalseExpr());
1358 return pet_expr_new_ternary(ctx
, cond
, lhs
, rhs
);
1361 struct pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1363 return extract_expr(expr
->getSubExpr());
1366 /* Construct a pet_expr representing a floating point value.
1368 struct pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1370 return pet_expr_new_double(ctx
, expr
->getValueAsApproximateDouble());
1373 /* Extract an access relation from "expr" and then convert it into
1376 struct pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1379 struct pet_expr
*pe
;
1381 switch (expr
->getStmtClass()) {
1382 case Stmt::ArraySubscriptExprClass
:
1383 access
= extract_access(cast
<ArraySubscriptExpr
>(expr
));
1385 case Stmt::DeclRefExprClass
:
1386 access
= extract_access(cast
<DeclRefExpr
>(expr
));
1388 case Stmt::IntegerLiteralClass
:
1389 access
= extract_access(cast
<IntegerLiteral
>(expr
));
1396 pe
= pet_expr_from_access(access
);
1401 struct pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1403 return extract_expr(expr
->getSubExpr());
1406 /* Construct a pet_expr representing a function call.
1408 * If we are passing along a pointer to an array element
1409 * or an entire row or even higher dimensional slice of an array,
1410 * then the function being called may write into the array.
1412 * We assume here that if the function is declared to take a pointer
1413 * to a const type, then the function will perform a read
1414 * and that otherwise, it will perform a write.
1416 struct pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1418 struct pet_expr
*res
= NULL
;
1422 fd
= expr
->getDirectCallee();
1428 name
= fd
->getDeclName().getAsString();
1429 res
= pet_expr_new_call(ctx
, name
.c_str(), expr
->getNumArgs());
1433 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
1434 Expr
*arg
= expr
->getArg(i
);
1438 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1439 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(arg
);
1440 arg
= ice
->getSubExpr();
1442 if (arg
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1443 UnaryOperator
*op
= cast
<UnaryOperator
>(arg
);
1444 if (op
->getOpcode() == UO_AddrOf
) {
1446 arg
= op
->getSubExpr();
1449 res
->args
[i
] = PetScan::extract_expr(arg
);
1450 main_arg
= res
->args
[i
];
1452 res
->args
[i
] = pet_expr_new_unary(ctx
,
1453 pet_op_address_of
, res
->args
[i
]);
1456 if (arg
->getStmtClass() == Stmt::ArraySubscriptExprClass
&&
1457 array_depth(arg
->getType().getTypePtr()) > 0)
1459 if (is_addr
&& main_arg
->type
== pet_expr_access
) {
1461 if (!fd
->hasPrototype()) {
1462 unsupported(expr
, "prototype required");
1465 parm
= fd
->getParamDecl(i
);
1466 if (!const_base(parm
->getType()))
1467 mark_write(main_arg
);
1477 /* Try and onstruct a pet_expr representing "expr".
1479 struct pet_expr
*PetScan::extract_expr(Expr
*expr
)
1481 switch (expr
->getStmtClass()) {
1482 case Stmt::UnaryOperatorClass
:
1483 return extract_expr(cast
<UnaryOperator
>(expr
));
1484 case Stmt::CompoundAssignOperatorClass
:
1485 case Stmt::BinaryOperatorClass
:
1486 return extract_expr(cast
<BinaryOperator
>(expr
));
1487 case Stmt::ImplicitCastExprClass
:
1488 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1489 case Stmt::ArraySubscriptExprClass
:
1490 case Stmt::DeclRefExprClass
:
1491 case Stmt::IntegerLiteralClass
:
1492 return extract_access_expr(expr
);
1493 case Stmt::FloatingLiteralClass
:
1494 return extract_expr(cast
<FloatingLiteral
>(expr
));
1495 case Stmt::ParenExprClass
:
1496 return extract_expr(cast
<ParenExpr
>(expr
));
1497 case Stmt::ConditionalOperatorClass
:
1498 return extract_expr(cast
<ConditionalOperator
>(expr
));
1499 case Stmt::CallExprClass
:
1500 return extract_expr(cast
<CallExpr
>(expr
));
1507 /* Check if the given initialization statement is an assignment.
1508 * If so, return that assignment. Otherwise return NULL.
1510 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1512 BinaryOperator
*ass
;
1514 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1517 ass
= cast
<BinaryOperator
>(init
);
1518 if (ass
->getOpcode() != BO_Assign
)
1524 /* Check if the given initialization statement is a declaration
1525 * of a single variable.
1526 * If so, return that declaration. Otherwise return NULL.
1528 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1532 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1535 decl
= cast
<DeclStmt
>(init
);
1537 if (!decl
->isSingleDecl())
1540 return decl
->getSingleDecl();
1543 /* Given the assignment operator in the initialization of a for loop,
1544 * extract the induction variable, i.e., the (integer)variable being
1547 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1554 lhs
= init
->getLHS();
1555 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1560 ref
= cast
<DeclRefExpr
>(lhs
);
1561 decl
= ref
->getDecl();
1562 type
= decl
->getType().getTypePtr();
1564 if (!type
->isIntegerType()) {
1572 /* Given the initialization statement of a for loop and the single
1573 * declaration in this initialization statement,
1574 * extract the induction variable, i.e., the (integer) variable being
1577 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1581 vd
= cast
<VarDecl
>(decl
);
1583 const QualType type
= vd
->getType();
1584 if (!type
->isIntegerType()) {
1589 if (!vd
->getInit()) {
1597 /* Check that op is of the form iv++ or iv--.
1598 * "inc" is accordingly set to 1 or -1.
1600 bool PetScan::check_unary_increment(UnaryOperator
*op
, clang::ValueDecl
*iv
,
1606 if (!op
->isIncrementDecrementOp()) {
1611 if (op
->isIncrementOp())
1612 isl_int_set_si(inc
, 1);
1614 isl_int_set_si(inc
, -1);
1616 sub
= op
->getSubExpr();
1617 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1622 ref
= cast
<DeclRefExpr
>(sub
);
1623 if (ref
->getDecl() != iv
) {
1631 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1632 * has a single constant expression on a universe domain, then
1633 * put this constant in *user.
1635 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
1638 isl_int
*inc
= (isl_int
*)user
;
1641 if (!isl_set_plain_is_universe(set
) || !isl_aff_is_cst(aff
))
1644 isl_aff_get_constant(aff
, inc
);
1652 /* Check if op is of the form
1656 * with inc a constant and set "inc" accordingly.
1658 * We extract an affine expression from the RHS and the subtract iv.
1659 * The result should be a constant.
1661 bool PetScan::check_binary_increment(BinaryOperator
*op
, clang::ValueDecl
*iv
,
1671 if (op
->getOpcode() != BO_Assign
) {
1677 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1682 ref
= cast
<DeclRefExpr
>(lhs
);
1683 if (ref
->getDecl() != iv
) {
1688 val
= extract_affine(op
->getRHS());
1690 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1692 dim
= isl_space_params_alloc(ctx
, 1);
1693 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1694 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1695 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1697 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
1699 if (isl_pw_aff_foreach_piece(val
, &extract_cst
, &inc
) < 0) {
1700 isl_pw_aff_free(val
);
1705 isl_pw_aff_free(val
);
1710 /* Check that op is of the form iv += cst or iv -= cst.
1711 * "inc" is set to cst or -cst accordingly.
1713 bool PetScan::check_compound_increment(CompoundAssignOperator
*op
,
1714 clang::ValueDecl
*iv
, isl_int
&inc
)
1720 BinaryOperatorKind opcode
;
1722 opcode
= op
->getOpcode();
1723 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1727 if (opcode
== BO_SubAssign
)
1731 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1736 ref
= cast
<DeclRefExpr
>(lhs
);
1737 if (ref
->getDecl() != iv
) {
1744 if (rhs
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1745 UnaryOperator
*op
= cast
<UnaryOperator
>(rhs
);
1746 if (op
->getOpcode() != UO_Minus
) {
1753 rhs
= op
->getSubExpr();
1756 if (rhs
->getStmtClass() != Stmt::IntegerLiteralClass
) {
1761 extract_int(cast
<IntegerLiteral
>(rhs
), &inc
);
1763 isl_int_neg(inc
, inc
);
1768 /* Check that the increment of the given for loop increments
1769 * (or decrements) the induction variable "iv".
1770 * "up" is set to true if the induction variable is incremented.
1772 bool PetScan::check_increment(ForStmt
*stmt
, ValueDecl
*iv
, isl_int
&v
)
1774 Stmt
*inc
= stmt
->getInc();
1781 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1782 return check_unary_increment(cast
<UnaryOperator
>(inc
), iv
, v
);
1783 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1784 return check_compound_increment(
1785 cast
<CompoundAssignOperator
>(inc
), iv
, v
);
1786 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1787 return check_binary_increment(cast
<BinaryOperator
>(inc
), iv
, v
);
1793 /* Embed the given iteration domain in an extra outer loop
1794 * with induction variable "var".
1795 * If this variable appeared as a parameter in the constraints,
1796 * it is replaced by the new outermost dimension.
1798 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1799 __isl_take isl_id
*var
)
1803 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1804 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1806 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1807 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1814 /* Construct a pet_scop for an infinite loop around the given body.
1816 * We extract a pet_scop for the body and then embed it in a loop with
1825 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
1831 struct pet_scop
*scop
;
1833 scop
= extract(body
);
1837 id
= isl_id_alloc(ctx
, "t", NULL
);
1838 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
1839 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
1840 dim
= isl_space_from_domain(isl_set_get_space(domain
));
1841 dim
= isl_space_add_dims(dim
, isl_dim_out
, 1);
1842 sched
= isl_map_universe(dim
);
1843 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
1844 scop
= pet_scop_embed(scop
, domain
, sched
, id
);
1849 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1855 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
1857 return extract_infinite_loop(stmt
->getBody());
1860 /* Check if the while loop is of the form
1865 * If so, construct a scop for an infinite loop around body.
1868 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
1874 cond
= stmt
->getCond();
1880 set
= isl_pw_aff_non_zero_set(extract_condition(cond
));
1881 is_universe
= isl_set_plain_is_universe(set
);
1889 return extract_infinite_loop(stmt
->getBody());
1892 /* Check whether "cond" expresses a simple loop bound
1893 * on the only set dimension.
1894 * In particular, if "up" is set then "cond" should contain only
1895 * upper bounds on the set dimension.
1896 * Otherwise, it should contain only lower bounds.
1898 static bool is_simple_bound(__isl_keep isl_set
*cond
, isl_int inc
)
1900 if (isl_int_is_pos(inc
))
1901 return !isl_set_dim_has_lower_bound(cond
, isl_dim_set
, 0);
1903 return !isl_set_dim_has_upper_bound(cond
, isl_dim_set
, 0);
1906 /* Extend a condition on a given iteration of a loop to one that
1907 * imposes the same condition on all previous iterations.
1908 * "domain" expresses the lower [upper] bound on the iterations
1909 * when inc is positive [negative].
1911 * In particular, we construct the condition (when inc is positive)
1913 * forall i' : (domain(i') and i' <= i) => cond(i')
1915 * which is equivalent to
1917 * not exists i' : domain(i') and i' <= i and not cond(i')
1919 * We construct this set by negating cond, applying a map
1921 * { [i'] -> [i] : domain(i') and i' <= i }
1923 * and then negating the result again.
1925 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
1926 __isl_take isl_set
*domain
, isl_int inc
)
1928 isl_map
*previous_to_this
;
1930 if (isl_int_is_pos(inc
))
1931 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
1933 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
1935 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
1937 cond
= isl_set_complement(cond
);
1938 cond
= isl_set_apply(cond
, previous_to_this
);
1939 cond
= isl_set_complement(cond
);
1944 /* Construct a domain of the form
1946 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
1948 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
1949 __isl_take isl_pw_aff
*init
, isl_int inc
)
1955 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
1956 dim
= isl_pw_aff_get_domain_space(init
);
1957 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1958 aff
= isl_aff_add_coefficient(aff
, isl_dim_in
, 0, inc
);
1959 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
1961 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
1962 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1963 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1964 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1966 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
1968 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
1970 return isl_set_params(set
);
1973 /* Assuming "cond" represents a bound on a loop where the loop
1974 * iterator "iv" is incremented (or decremented) by one, check if wrapping
1977 * Under the given assumptions, wrapping is only possible if "cond" allows
1978 * for the last value before wrapping, i.e., 2^width - 1 in case of an
1979 * increasing iterator and 0 in case of a decreasing iterator.
1981 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
, isl_int inc
)
1987 test
= isl_set_copy(cond
);
1989 isl_int_init(limit
);
1990 if (isl_int_is_neg(inc
))
1991 isl_int_set_si(limit
, 0);
1993 isl_int_set_si(limit
, 1);
1994 isl_int_mul_2exp(limit
, limit
, get_type_size(iv
));
1995 isl_int_sub_ui(limit
, limit
, 1);
1998 test
= isl_set_fix(cond
, isl_dim_set
, 0, limit
);
1999 cw
= !isl_set_is_empty(test
);
2002 isl_int_clear(limit
);
2007 /* Given a one-dimensional space, construct the following mapping on this
2010 * { [v] -> [v mod 2^width] }
2012 * where width is the number of bits used to represent the values
2013 * of the unsigned variable "iv".
2015 static __isl_give isl_map
*compute_wrapping(__isl_take isl_space
*dim
,
2023 isl_int_set_si(mod
, 1);
2024 isl_int_mul_2exp(mod
, mod
, get_type_size(iv
));
2026 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2027 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2028 aff
= isl_aff_mod(aff
, mod
);
2032 return isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2033 map
= isl_map_reverse(map
);
2036 /* Construct a pet_scop for a for statement.
2037 * The for loop is required to be of the form
2039 * for (i = init; condition; ++i)
2043 * for (i = init; condition; --i)
2045 * The initialization of the for loop should either be an assignment
2046 * to an integer variable, or a declaration of such a variable with
2049 * The condition is allowed to contain nested accesses, provided
2050 * they are not being written to inside the body of the loop.
2052 * We extract a pet_scop for the body and then embed it in a loop with
2053 * iteration domain and schedule
2055 * { [i] : i >= init and condition' }
2060 * { [i] : i <= init and condition' }
2063 * Where condition' is equal to condition if the latter is
2064 * a simple upper [lower] bound and a condition that is extended
2065 * to apply to all previous iterations otherwise.
2067 * If the stride of the loop is not 1, then "i >= init" is replaced by
2069 * (exists a: i = init + stride * a and a >= 0)
2071 * If the loop iterator i is unsigned, then wrapping may occur.
2072 * During the computation, we work with a virtual iterator that
2073 * does not wrap. However, the condition in the code applies
2074 * to the wrapped value, so we need to change condition(i)
2075 * into condition([i % 2^width]).
2076 * After computing the virtual domain and schedule, we apply
2077 * the function { [v] -> [v % 2^width] } to the domain and the domain
2078 * of the schedule. In order not to lose any information, we also
2079 * need to intersect the domain of the schedule with the virtual domain
2080 * first, since some iterations in the wrapped domain may be scheduled
2081 * several times, typically an infinite number of times.
2082 * Note that there is no need to perform this final wrapping
2083 * if the loop condition (after wrapping) is simple.
2085 * Wrapping on unsigned iterators can be avoided entirely if
2086 * loop condition is simple, the loop iterator is incremented
2087 * [decremented] by one and the last value before wrapping cannot
2088 * possibly satisfy the loop condition.
2090 * Before extracting a pet_scop from the body we remove all
2091 * assignments in assigned_value to variables that are assigned
2092 * somewhere in the body of the loop.
2094 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2096 BinaryOperator
*ass
;
2104 isl_set
*cond
= NULL
;
2106 struct pet_scop
*scop
;
2107 assigned_value_cache
cache(assigned_value
);
2113 isl_map
*wrap
= NULL
;
2116 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2117 return extract_infinite_for(stmt
);
2119 init
= stmt
->getInit();
2124 if ((ass
= initialization_assignment(init
)) != NULL
) {
2125 iv
= extract_induction_variable(ass
);
2128 lhs
= ass
->getLHS();
2129 rhs
= ass
->getRHS();
2130 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2131 VarDecl
*var
= extract_induction_variable(init
, decl
);
2135 rhs
= var
->getInit();
2136 lhs
= create_DeclRefExpr(var
);
2138 unsupported(stmt
->getInit());
2143 if (!check_increment(stmt
, iv
, inc
)) {
2148 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2150 assigned_value
.erase(iv
);
2151 clear_assignments
clear(assigned_value
);
2152 clear
.TraverseStmt(stmt
->getBody());
2154 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
2156 scop
= extract(stmt
->getBody());
2158 pa
= try_extract_nested_condition(stmt
->getCond());
2159 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2160 isl_pw_aff_free(pa
);
2165 pa
= extract_condition(stmt
->getCond());
2166 cond
= isl_pw_aff_non_zero_set(pa
);
2167 cond
= embed(cond
, isl_id_copy(id
));
2168 is_one
= isl_int_is_one(inc
) || isl_int_is_negone(inc
);
2169 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2171 if (is_one
&& !is_virtual
) {
2172 pa
= extract_comparison(isl_int_is_pos(inc
) ? BO_GE
: BO_LE
,
2174 domain
= isl_pw_aff_non_zero_set(pa
);
2176 isl_pw_aff
*lb
= extract_affine(rhs
);
2177 domain
= strided_domain(isl_id_copy(id
), lb
, inc
);
2180 domain
= embed(domain
, isl_id_copy(id
));
2182 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2183 cond
= isl_set_apply(cond
, isl_map_reverse(isl_map_copy(wrap
)));
2185 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2186 is_simple
= is_simple_bound(cond
, inc
);
2188 cond
= valid_for_each_iteration(cond
,
2189 isl_set_copy(domain
), inc
);
2190 domain
= isl_set_intersect(domain
, cond
);
2191 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2192 dim
= isl_space_from_domain(isl_set_get_space(domain
));
2193 dim
= isl_space_add_dims(dim
, isl_dim_out
, 1);
2194 sched
= isl_map_universe(dim
);
2195 if (isl_int_is_pos(inc
))
2196 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2198 sched
= isl_map_oppose(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2200 if (is_virtual
&& !is_simple
) {
2201 wrap
= isl_map_set_dim_id(wrap
,
2202 isl_dim_out
, 0, isl_id_copy(id
));
2203 sched
= isl_map_intersect_domain(sched
, isl_set_copy(domain
));
2204 domain
= isl_set_apply(domain
, isl_map_copy(wrap
));
2205 sched
= isl_map_apply_domain(sched
, wrap
);
2209 scop
= pet_scop_embed(scop
, domain
, sched
, id
);
2210 scop
= resolve_nested(scop
);
2211 clear_assignment(assigned_value
, iv
);
2217 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
)
2219 return extract(stmt
->children());
2222 /* Does "id" refer to a nested access?
2224 static bool is_nested_parameter(__isl_keep isl_id
*id
)
2226 return id
&& isl_id_get_user(id
) && !isl_id_get_name(id
);
2229 /* Does parameter "pos" of "space" refer to a nested access?
2231 static bool is_nested_parameter(__isl_keep isl_space
*space
, int pos
)
2236 id
= isl_space_get_dim_id(space
, isl_dim_param
, pos
);
2237 nested
= is_nested_parameter(id
);
2243 /* Does parameter "pos" of "map" refer to a nested access?
2245 static bool is_nested_parameter(__isl_keep isl_map
*map
, int pos
)
2250 id
= isl_map_get_dim_id(map
, isl_dim_param
, pos
);
2251 nested
= is_nested_parameter(id
);
2257 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2259 static int n_nested_parameter(__isl_keep isl_space
*space
)
2264 nparam
= isl_space_dim(space
, isl_dim_param
);
2265 for (int i
= 0; i
< nparam
; ++i
)
2266 if (is_nested_parameter(space
, i
))
2272 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2274 static int n_nested_parameter(__isl_keep isl_map
*map
)
2279 space
= isl_map_get_space(map
);
2280 n
= n_nested_parameter(space
);
2281 isl_space_free(space
);
2286 /* For each nested access parameter in "space",
2287 * construct a corresponding pet_expr, place it in args and
2288 * record its position in "param2pos".
2289 * "n_arg" is the number of elements that are already in args.
2290 * The position recorded in "param2pos" takes this number into account.
2291 * If the pet_expr corresponding to a parameter is identical to
2292 * the pet_expr corresponding to an earlier parameter, then these two
2293 * parameters are made to refer to the same element in args.
2295 * Return the final number of elements in args or -1 if an error has occurred.
2297 int PetScan::extract_nested(__isl_keep isl_space
*space
,
2298 int n_arg
, struct pet_expr
**args
, std::map
<int,int> ¶m2pos
)
2302 nparam
= isl_space_dim(space
, isl_dim_param
);
2303 for (int i
= 0; i
< nparam
; ++i
) {
2305 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2308 if (!is_nested_parameter(id
)) {
2313 nested
= (Expr
*) isl_id_get_user(id
);
2314 args
[n_arg
] = extract_expr(nested
);
2318 for (j
= 0; j
< n_arg
; ++j
)
2319 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
2323 pet_expr_free(args
[n_arg
]);
2327 param2pos
[i
] = n_arg
++;
2335 /* For each nested access parameter in the access relations in "expr",
2336 * construct a corresponding pet_expr, place it in expr->args and
2337 * record its position in "param2pos".
2338 * n is the number of nested access parameters.
2340 struct pet_expr
*PetScan::extract_nested(struct pet_expr
*expr
, int n
,
2341 std::map
<int,int> ¶m2pos
)
2345 expr
->args
= isl_calloc_array(ctx
, struct pet_expr
*, n
);
2350 space
= isl_map_get_space(expr
->acc
.access
);
2351 n
= extract_nested(space
, 0, expr
->args
, param2pos
);
2352 isl_space_free(space
);
2360 pet_expr_free(expr
);
2364 /* Look for parameters in any access relation in "expr" that
2365 * refer to nested accesses. In particular, these are
2366 * parameters with no name.
2368 * If there are any such parameters, then the domain of the access
2369 * relation, which is still [] at this point, is replaced by
2370 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2371 * (after identifying identical nested accesses).
2372 * The parameters are then equated to the corresponding t dimensions
2373 * and subsequently projected out.
2374 * param2pos maps the position of the parameter to the position
2375 * of the corresponding t dimension.
2377 struct pet_expr
*PetScan::resolve_nested(struct pet_expr
*expr
)
2384 std::map
<int,int> param2pos
;
2389 for (int i
= 0; i
< expr
->n_arg
; ++i
) {
2390 expr
->args
[i
] = resolve_nested(expr
->args
[i
]);
2391 if (!expr
->args
[i
]) {
2392 pet_expr_free(expr
);
2397 if (expr
->type
!= pet_expr_access
)
2400 n
= n_nested_parameter(expr
->acc
.access
);
2404 expr
= extract_nested(expr
, n
, param2pos
);
2409 nparam
= isl_map_dim(expr
->acc
.access
, isl_dim_param
);
2410 n_in
= isl_map_dim(expr
->acc
.access
, isl_dim_in
);
2411 dim
= isl_map_get_space(expr
->acc
.access
);
2412 dim
= isl_space_domain(dim
);
2413 dim
= isl_space_from_domain(dim
);
2414 dim
= isl_space_add_dims(dim
, isl_dim_out
, n
);
2415 map
= isl_map_universe(dim
);
2416 map
= isl_map_domain_map(map
);
2417 map
= isl_map_reverse(map
);
2418 expr
->acc
.access
= isl_map_apply_domain(expr
->acc
.access
, map
);
2420 for (int i
= nparam
- 1; i
>= 0; --i
) {
2421 isl_id
*id
= isl_map_get_dim_id(expr
->acc
.access
,
2423 if (!is_nested_parameter(id
)) {
2428 expr
->acc
.access
= isl_map_equate(expr
->acc
.access
,
2429 isl_dim_param
, i
, isl_dim_in
,
2430 n_in
+ param2pos
[i
]);
2431 expr
->acc
.access
= isl_map_project_out(expr
->acc
.access
,
2432 isl_dim_param
, i
, 1);
2439 pet_expr_free(expr
);
2443 /* Convert a top-level pet_expr to a pet_scop with one statement.
2444 * This mainly involves resolving nested expression parameters
2445 * and setting the name of the iteration space.
2446 * The name is given by "label" if it is non-NULL. Otherwise,
2447 * it is of the form S_<n_stmt>.
2449 struct pet_scop
*PetScan::extract(Stmt
*stmt
, struct pet_expr
*expr
,
2450 __isl_take isl_id
*label
)
2452 struct pet_stmt
*ps
;
2453 SourceLocation loc
= stmt
->getLocStart();
2454 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
2456 expr
= resolve_nested(expr
);
2457 ps
= pet_stmt_from_pet_expr(ctx
, line
, label
, n_stmt
++, expr
);
2458 return pet_scop_from_pet_stmt(ctx
, ps
);
2461 /* Check if we can extract an affine expression from "expr".
2462 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2463 * We turn on autodetection so that we won't generate any warnings
2464 * and turn off nesting, so that we won't accept any non-affine constructs.
2466 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
2469 int save_autodetect
= autodetect
;
2470 bool save_nesting
= nesting_enabled
;
2473 nesting_enabled
= false;
2475 pwaff
= extract_affine(expr
);
2477 autodetect
= save_autodetect
;
2478 nesting_enabled
= save_nesting
;
2483 /* Check whether "expr" is an affine expression.
2485 bool PetScan::is_affine(Expr
*expr
)
2489 pwaff
= try_extract_affine(expr
);
2490 isl_pw_aff_free(pwaff
);
2492 return pwaff
!= NULL
;
2495 /* Check whether "expr" is an affine constraint.
2496 * We turn on autodetection so that we won't generate any warnings
2497 * and turn off nesting, so that we won't accept any non-affine constructs.
2499 bool PetScan::is_affine_condition(Expr
*expr
)
2502 int save_autodetect
= autodetect
;
2503 bool save_nesting
= nesting_enabled
;
2506 nesting_enabled
= false;
2508 cond
= extract_condition(expr
);
2509 isl_pw_aff_free(cond
);
2511 autodetect
= save_autodetect
;
2512 nesting_enabled
= save_nesting
;
2514 return cond
!= NULL
;
2517 /* Check if we can extract a condition from "expr".
2518 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
2519 * If allow_nested is set, then the condition may involve parameters
2520 * corresponding to nested accesses.
2521 * We turn on autodetection so that we won't generate any warnings.
2523 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
2526 int save_autodetect
= autodetect
;
2527 bool save_nesting
= nesting_enabled
;
2530 nesting_enabled
= allow_nested
;
2531 cond
= extract_condition(expr
);
2533 autodetect
= save_autodetect
;
2534 nesting_enabled
= save_nesting
;
2539 /* If the top-level expression of "stmt" is an assignment, then
2540 * return that assignment as a BinaryOperator.
2541 * Otherwise return NULL.
2543 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
2545 BinaryOperator
*ass
;
2549 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
2552 ass
= cast
<BinaryOperator
>(stmt
);
2553 if(ass
->getOpcode() != BO_Assign
)
2559 /* Check if the given if statement is a conditional assignement
2560 * with a non-affine condition. If so, construct a pet_scop
2561 * corresponding to this conditional assignment. Otherwise return NULL.
2563 * In particular we check if "stmt" is of the form
2570 * where a is some array or scalar access.
2571 * The constructed pet_scop then corresponds to the expression
2573 * a = condition ? f(...) : g(...)
2575 * All access relations in f(...) are intersected with condition
2576 * while all access relation in g(...) are intersected with the complement.
2578 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
2580 BinaryOperator
*ass_then
, *ass_else
;
2581 isl_map
*write_then
, *write_else
;
2582 isl_set
*cond
, *comp
;
2583 isl_map
*map
, *map_true
, *map_false
;
2585 struct pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
2586 bool save_nesting
= nesting_enabled
;
2588 ass_then
= top_assignment_or_null(stmt
->getThen());
2589 ass_else
= top_assignment_or_null(stmt
->getElse());
2591 if (!ass_then
|| !ass_else
)
2594 if (is_affine_condition(stmt
->getCond()))
2597 write_then
= extract_access(ass_then
->getLHS());
2598 write_else
= extract_access(ass_else
->getLHS());
2600 equal
= isl_map_is_equal(write_then
, write_else
);
2601 isl_map_free(write_else
);
2602 if (equal
< 0 || !equal
) {
2603 isl_map_free(write_then
);
2607 nesting_enabled
= allow_nested
;
2608 cond
= isl_pw_aff_non_zero_set(extract_condition(stmt
->getCond()));
2609 nesting_enabled
= save_nesting
;
2610 comp
= isl_set_complement(isl_set_copy(cond
));
2611 map_true
= isl_map_from_domain(isl_set_from_params(isl_set_copy(cond
)));
2612 map_true
= isl_map_add_dims(map_true
, isl_dim_out
, 1);
2613 map_true
= isl_map_fix_si(map_true
, isl_dim_out
, 0, 1);
2614 map_false
= isl_map_from_domain(isl_set_from_params(isl_set_copy(comp
)));
2615 map_false
= isl_map_add_dims(map_false
, isl_dim_out
, 1);
2616 map_false
= isl_map_fix_si(map_false
, isl_dim_out
, 0, 0);
2617 map
= isl_map_union_disjoint(map_true
, map_false
);
2619 pe_cond
= pet_expr_from_access(map
);
2621 pe_then
= extract_expr(ass_then
->getRHS());
2622 pe_then
= pet_expr_restrict(pe_then
, cond
);
2623 pe_else
= extract_expr(ass_else
->getRHS());
2624 pe_else
= pet_expr_restrict(pe_else
, comp
);
2626 pe
= pet_expr_new_ternary(ctx
, pe_cond
, pe_then
, pe_else
);
2627 pe_write
= pet_expr_from_access(write_then
);
2629 pe_write
->acc
.write
= 1;
2630 pe_write
->acc
.read
= 0;
2632 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, pe_write
, pe
);
2633 return extract(stmt
, pe
);
2636 /* Create an access to a virtual array representing the result
2638 * Unlike other accessed data, the id of the array is NULL as
2639 * there is no ValueDecl in the program corresponding to the virtual
2641 * The array starts out as a scalar, but grows along with the
2642 * statement writing to the array in pet_scop_embed.
2644 static __isl_give isl_map
*create_test_access(isl_ctx
*ctx
, int test_nr
)
2646 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, 0);
2650 snprintf(name
, sizeof(name
), "__pet_test_%d", test_nr
);
2651 id
= isl_id_alloc(ctx
, name
, NULL
);
2652 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
2653 return isl_map_universe(dim
);
2656 /* Create a pet_scop with a single statement evaluating "cond"
2657 * and writing the result to a virtual scalar, as expressed by
2660 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
,
2661 __isl_take isl_map
*access
)
2663 struct pet_expr
*expr
, *write
;
2664 struct pet_stmt
*ps
;
2665 SourceLocation loc
= cond
->getLocStart();
2666 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
2668 write
= pet_expr_from_access(access
);
2670 write
->acc
.write
= 1;
2671 write
->acc
.read
= 0;
2673 expr
= extract_expr(cond
);
2674 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, write
, expr
);
2675 ps
= pet_stmt_from_pet_expr(ctx
, line
, NULL
, n_stmt
++, expr
);
2676 return pet_scop_from_pet_stmt(ctx
, ps
);
2679 /* Add an array with the given extent ("access") to the list
2680 * of arrays in "scop" and return the extended pet_scop.
2681 * The array is marked as attaining values 0 and 1 only.
2683 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2684 __isl_keep isl_map
*access
, clang::ASTContext
&ast_ctx
)
2686 isl_ctx
*ctx
= isl_map_get_ctx(access
);
2688 struct pet_array
**arrays
;
2689 struct pet_array
*array
;
2696 arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
2700 scop
->arrays
= arrays
;
2702 array
= isl_calloc_type(ctx
, struct pet_array
);
2706 array
->extent
= isl_map_range(isl_map_copy(access
));
2707 dim
= isl_space_params_alloc(ctx
, 0);
2708 array
->context
= isl_set_universe(dim
);
2709 dim
= isl_space_set_alloc(ctx
, 0, 1);
2710 array
->value_bounds
= isl_set_universe(dim
);
2711 array
->value_bounds
= isl_set_lower_bound_si(array
->value_bounds
,
2713 array
->value_bounds
= isl_set_upper_bound_si(array
->value_bounds
,
2715 array
->element_type
= strdup("int");
2716 array
->element_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
2718 scop
->arrays
[scop
->n_array
] = array
;
2721 if (!array
->extent
|| !array
->context
)
2726 pet_scop_free(scop
);
2731 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
,
2735 /* Apply the map pointed to by "user" to the domain of the access
2736 * relation, thereby embedding it in the range of the map.
2737 * The domain of both relations is the zero-dimensional domain.
2739 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
, void *user
)
2741 isl_map
*map
= (isl_map
*) user
;
2743 return isl_map_apply_domain(access
, isl_map_copy(map
));
2746 /* Apply "map" to all access relations in "expr".
2748 static struct pet_expr
*embed(struct pet_expr
*expr
, __isl_keep isl_map
*map
)
2750 return pet_expr_foreach_access(expr
, &embed_access
, map
);
2753 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2755 static int n_nested_parameter(__isl_keep isl_set
*set
)
2760 space
= isl_set_get_space(set
);
2761 n
= n_nested_parameter(space
);
2762 isl_space_free(space
);
2767 /* Remove all parameters from "map" that refer to nested accesses.
2769 static __isl_give isl_map
*remove_nested_parameters(__isl_take isl_map
*map
)
2774 space
= isl_map_get_space(map
);
2775 nparam
= isl_space_dim(space
, isl_dim_param
);
2776 for (int i
= nparam
- 1; i
>= 0; --i
)
2777 if (is_nested_parameter(space
, i
))
2778 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
2779 isl_space_free(space
);
2785 static __isl_give isl_map
*access_remove_nested_parameters(
2786 __isl_take isl_map
*access
, void *user
);
2789 static __isl_give isl_map
*access_remove_nested_parameters(
2790 __isl_take isl_map
*access
, void *user
)
2792 return remove_nested_parameters(access
);
2795 /* Remove all nested access parameters from the schedule and all
2796 * accesses of "stmt".
2797 * There is no need to remove them from the domain as these parameters
2798 * have already been removed from the domain when this function is called.
2800 static struct pet_stmt
*remove_nested_parameters(struct pet_stmt
*stmt
)
2804 stmt
->schedule
= remove_nested_parameters(stmt
->schedule
);
2805 stmt
->body
= pet_expr_foreach_access(stmt
->body
,
2806 &access_remove_nested_parameters
, NULL
);
2807 if (!stmt
->schedule
|| !stmt
->body
)
2809 for (int i
= 0; i
< stmt
->n_arg
; ++i
) {
2810 stmt
->args
[i
] = pet_expr_foreach_access(stmt
->args
[i
],
2811 &access_remove_nested_parameters
, NULL
);
2818 pet_stmt_free(stmt
);
2822 /* For each nested access parameter in the domain of "stmt",
2823 * construct a corresponding pet_expr, place it in stmt->args and
2824 * record its position in "param2pos".
2825 * n is the number of nested access parameters.
2827 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
2828 std::map
<int,int> ¶m2pos
)
2832 struct pet_expr
**args
;
2834 n_arg
= stmt
->n_arg
;
2835 args
= isl_realloc_array(ctx
, stmt
->args
, struct pet_expr
*, n_arg
+ n
);
2841 space
= isl_set_get_space(stmt
->domain
);
2842 n
= extract_nested(space
, n_arg
, stmt
->args
, param2pos
);
2843 isl_space_free(space
);
2851 pet_stmt_free(stmt
);
2855 /* Look for parameters in the iteration domain of "stmt" that
2856 * refer to nested accesses. In particular, these are
2857 * parameters with no name.
2859 * If there are any such parameters, then as many extra variables
2860 * (after identifying identical nested accesses) are added to the
2861 * range of the map wrapped inside the domain.
2862 * If the original domain is not a wrapped map, then a new wrapped
2863 * map is created with zero output dimensions.
2864 * The parameters are then equated to the corresponding output dimensions
2865 * and subsequently projected out, from the iteration domain,
2866 * the schedule and the access relations.
2867 * For each of the output dimensions, a corresponding argument
2868 * expression is added. Initially they are created with
2869 * a zero-dimensional domain, so they have to be embedded
2870 * in the current iteration domain.
2871 * param2pos maps the position of the parameter to the position
2872 * of the corresponding output dimension in the wrapped map.
2874 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
2880 std::map
<int,int> param2pos
;
2885 n
= n_nested_parameter(stmt
->domain
);
2889 n_arg
= stmt
->n_arg
;
2890 stmt
= extract_nested(stmt
, n
, param2pos
);
2894 n
= stmt
->n_arg
- n_arg
;
2895 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
2896 if (isl_set_is_wrapping(stmt
->domain
))
2897 map
= isl_set_unwrap(stmt
->domain
);
2899 map
= isl_map_from_domain(stmt
->domain
);
2900 map
= isl_map_add_dims(map
, isl_dim_out
, n
);
2902 for (int i
= nparam
- 1; i
>= 0; --i
) {
2905 if (!is_nested_parameter(map
, i
))
2908 id
= isl_map_get_tuple_id(stmt
->args
[param2pos
[i
]]->acc
.access
,
2910 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
2911 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
2913 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
2916 stmt
->domain
= isl_map_wrap(map
);
2918 map
= isl_set_unwrap(isl_set_copy(stmt
->domain
));
2919 map
= isl_map_from_range(isl_map_domain(map
));
2920 for (int pos
= n_arg
; pos
< stmt
->n_arg
; ++pos
)
2921 stmt
->args
[pos
] = embed(stmt
->args
[pos
], map
);
2924 stmt
= remove_nested_parameters(stmt
);
2928 pet_stmt_free(stmt
);
2932 /* For each statement in "scop", move the parameters that correspond
2933 * to nested access into the ranges of the domains and create
2934 * corresponding argument expressions.
2936 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
2941 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
2942 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
2943 if (!scop
->stmts
[i
])
2949 pet_scop_free(scop
);
2953 /* Does "space" involve any parameters that refer to nested
2954 * accesses, i.e., parameters with no name?
2956 static bool has_nested(__isl_keep isl_space
*space
)
2960 nparam
= isl_space_dim(space
, isl_dim_param
);
2961 for (int i
= 0; i
< nparam
; ++i
)
2962 if (is_nested_parameter(space
, i
))
2968 /* Does "pa" involve any parameters that refer to nested
2969 * accesses, i.e., parameters with no name?
2971 static bool has_nested(__isl_keep isl_pw_aff
*pa
)
2976 space
= isl_pw_aff_get_space(pa
);
2977 nested
= has_nested(space
);
2978 isl_space_free(space
);
2983 /* Given an access expression "expr", is the variable accessed by
2984 * "expr" assigned anywhere inside "scop"?
2986 static bool is_assigned(pet_expr
*expr
, pet_scop
*scop
)
2988 bool assigned
= false;
2991 id
= isl_map_get_tuple_id(expr
->acc
.access
, isl_dim_out
);
2992 assigned
= pet_scop_writes(scop
, id
);
2998 /* Are all nested access parameters in "pa" allowed given "scop".
2999 * In particular, is none of them written by anywhere inside "scop".
3001 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3005 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3006 for (int i
= 0; i
< nparam
; ++i
) {
3008 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3012 if (!is_nested_parameter(id
)) {
3017 nested
= (Expr
*) isl_id_get_user(id
);
3018 expr
= extract_expr(nested
);
3019 allowed
= expr
&& expr
->type
== pet_expr_access
&&
3020 !is_assigned(expr
, scop
);
3022 pet_expr_free(expr
);
3032 /* Construct a pet_scop for an if statement.
3034 * If the condition fits the pattern of a conditional assignment,
3035 * then it is handled by extract_conditional_assignment.
3036 * Otherwise, we do the following.
3038 * If the condition is affine, then the condition is added
3039 * to the iteration domains of the then branch, while the
3040 * opposite of the condition in added to the iteration domains
3041 * of the else branch, if any.
3042 * We allow the condition to be dynamic, i.e., to refer to
3043 * scalars or array elements that may be written to outside
3044 * of the given if statement. These nested accesses are then represented
3045 * as output dimensions in the wrapping iteration domain.
3046 * If it also written _inside_ the then or else branch, then
3047 * we treat the condition as non-affine.
3048 * As explained below, this will introduce an extra statement.
3049 * For aesthetic reasons, we want this statement to have a statement
3050 * number that is lower than those of the then and else branches.
3051 * In order to evaluate if will need such a statement, however, we
3052 * first construct scops for the then and else branches.
3053 * We therefore reserve a statement number if we might have to
3054 * introduce such an extra statement.
3056 * If the condition is not affine, then we create a separate
3057 * statement that writes the result of the condition to a virtual scalar.
3058 * A constraint requiring the value of this virtual scalar to be one
3059 * is added to the iteration domains of the then branch.
3060 * Similarly, a constraint requiring the value of this virtual scalar
3061 * to be zero is added to the iteration domains of the else branch, if any.
3062 * We adjust the schedules to ensure that the virtual scalar is written
3063 * before it is read.
3065 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
3067 struct pet_scop
*scop_then
, *scop_else
, *scop
;
3068 assigned_value_cache
cache(assigned_value
);
3069 isl_map
*test_access
= NULL
;
3073 scop
= extract_conditional_assignment(stmt
);
3077 cond
= try_extract_nested_condition(stmt
->getCond());
3078 if (allow_nested
&& (!cond
|| has_nested(cond
)))
3081 scop_then
= extract(stmt
->getThen());
3083 if (stmt
->getElse()) {
3084 scop_else
= extract(stmt
->getElse());
3086 if (scop_then
&& !scop_else
) {
3088 isl_pw_aff_free(cond
);
3091 if (!scop_then
&& scop_else
) {
3093 isl_pw_aff_free(cond
);
3100 (!is_nested_allowed(cond
, scop_then
) ||
3101 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
3102 isl_pw_aff_free(cond
);
3105 if (allow_nested
&& !cond
) {
3106 int save_n_stmt
= n_stmt
;
3107 test_access
= create_test_access(ctx
, n_test
++);
3109 scop
= extract_non_affine_condition(stmt
->getCond(),
3110 isl_map_copy(test_access
));
3111 n_stmt
= save_n_stmt
;
3112 scop
= scop_add_array(scop
, test_access
, ast_context
);
3114 pet_scop_free(scop_then
);
3115 pet_scop_free(scop_else
);
3116 isl_map_free(test_access
);
3125 cond
= extract_condition(stmt
->getCond());
3126 set
= isl_pw_aff_non_zero_set(cond
);
3127 scop
= pet_scop_restrict(scop_then
, isl_set_copy(set
));
3129 if (stmt
->getElse()) {
3130 set
= isl_set_complement(set
);
3131 scop_else
= pet_scop_restrict(scop_else
, set
);
3132 scop
= pet_scop_add(ctx
, scop
, scop_else
);
3135 scop
= resolve_nested(scop
);
3137 scop
= pet_scop_prefix(scop
, 0);
3138 scop_then
= pet_scop_prefix(scop_then
, 1);
3139 scop_then
= pet_scop_filter(scop_then
,
3140 isl_map_copy(test_access
), 1);
3141 scop
= pet_scop_add(ctx
, scop
, scop_then
);
3142 if (stmt
->getElse()) {
3143 scop_else
= pet_scop_prefix(scop_else
, 1);
3144 scop_else
= pet_scop_filter(scop_else
, test_access
, 0);
3145 scop
= pet_scop_add(ctx
, scop
, scop_else
);
3147 isl_map_free(test_access
);
3153 /* Try and construct a pet_scop for a label statement.
3154 * We currently only allow labels on expression statements.
3156 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
3161 sub
= stmt
->getSubStmt();
3162 if (!isa
<Expr
>(sub
)) {
3167 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
3169 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
3172 /* Try and construct a pet_scop corresponding to "stmt".
3174 struct pet_scop
*PetScan::extract(Stmt
*stmt
)
3176 if (isa
<Expr
>(stmt
))
3177 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
3179 switch (stmt
->getStmtClass()) {
3180 case Stmt::WhileStmtClass
:
3181 return extract(cast
<WhileStmt
>(stmt
));
3182 case Stmt::ForStmtClass
:
3183 return extract_for(cast
<ForStmt
>(stmt
));
3184 case Stmt::IfStmtClass
:
3185 return extract(cast
<IfStmt
>(stmt
));
3186 case Stmt::CompoundStmtClass
:
3187 return extract(cast
<CompoundStmt
>(stmt
));
3188 case Stmt::LabelStmtClass
:
3189 return extract(cast
<LabelStmt
>(stmt
));
3197 /* Try and construct a pet_scop corresponding to (part of)
3198 * a sequence of statements.
3200 struct pet_scop
*PetScan::extract(StmtRange stmt_range
)
3205 bool partial_range
= false;
3207 scop
= pet_scop_empty(ctx
);
3208 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
3210 struct pet_scop
*scop_i
;
3211 scop_i
= extract(child
);
3212 if (scop
&& partial
) {
3213 pet_scop_free(scop_i
);
3216 scop_i
= pet_scop_prefix(scop_i
, j
);
3219 scop
= pet_scop_add(ctx
, scop
, scop_i
);
3221 partial_range
= true;
3222 if (scop
->n_stmt
!= 0 && !scop_i
)
3225 scop
= pet_scop_add(ctx
, scop
, scop_i
);
3231 if (scop
&& partial_range
)
3237 /* Check if the scop marked by the user is exactly this Stmt
3238 * or part of this Stmt.
3239 * If so, return a pet_scop corresponding to the marked region.
3240 * Otherwise, return NULL.
3242 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
3244 SourceManager
&SM
= PP
.getSourceManager();
3245 unsigned start_off
, end_off
;
3247 start_off
= SM
.getFileOffset(stmt
->getLocStart());
3248 end_off
= SM
.getFileOffset(stmt
->getLocEnd());
3250 if (start_off
> loc
.end
)
3252 if (end_off
< loc
.start
)
3254 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
3255 return extract(stmt
);
3259 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
3260 Stmt
*child
= *start
;
3263 start_off
= SM
.getFileOffset(child
->getLocStart());
3264 end_off
= SM
.getFileOffset(child
->getLocEnd());
3265 if (start_off
< loc
.start
&& end_off
> loc
.end
)
3267 if (start_off
>= loc
.start
)
3272 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
3274 start_off
= SM
.getFileOffset(child
->getLocStart());
3275 if (start_off
>= loc
.end
)
3279 return extract(StmtRange(start
, end
));
3282 /* Set the size of index "pos" of "array" to "size".
3283 * In particular, add a constraint of the form
3287 * to array->extent and a constraint of the form
3291 * to array->context.
3293 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
3294 __isl_take isl_pw_aff
*size
)
3304 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
3305 array
->context
= isl_set_intersect(array
->context
, valid
);
3307 dim
= isl_set_get_space(array
->extent
);
3308 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
3309 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
3310 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
3311 index
= isl_pw_aff_alloc(univ
, aff
);
3313 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
3314 isl_set_dim(array
->extent
, isl_dim_set
));
3315 id
= isl_set_get_tuple_id(array
->extent
);
3316 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
3317 bound
= isl_pw_aff_lt_set(index
, size
);
3319 array
->extent
= isl_set_intersect(array
->extent
, bound
);
3321 if (!array
->context
|| !array
->extent
)
3326 pet_array_free(array
);
3330 /* Figure out the size of the array at position "pos" and all
3331 * subsequent positions from "type" and update "array" accordingly.
3333 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
3334 const Type
*type
, int pos
)
3336 const ArrayType
*atype
;
3342 if (type
->isPointerType()) {
3343 type
= type
->getPointeeType().getTypePtr();
3344 return set_upper_bounds(array
, type
, pos
+ 1);
3346 if (!type
->isArrayType())
3349 type
= type
->getCanonicalTypeInternal().getTypePtr();
3350 atype
= cast
<ArrayType
>(type
);
3352 if (type
->isConstantArrayType()) {
3353 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
3354 size
= extract_affine(ca
->getSize());
3355 array
= update_size(array
, pos
, size
);
3356 } else if (type
->isVariableArrayType()) {
3357 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
3358 size
= extract_affine(vla
->getSizeExpr());
3359 array
= update_size(array
, pos
, size
);
3362 type
= atype
->getElementType().getTypePtr();
3364 return set_upper_bounds(array
, type
, pos
+ 1);
3367 /* Construct and return a pet_array corresponding to the variable "decl".
3368 * In particular, initialize array->extent to
3370 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3372 * and then call set_upper_bounds to set the upper bounds on the indices
3373 * based on the type of the variable.
3375 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
)
3377 struct pet_array
*array
;
3378 QualType qt
= decl
->getType();
3379 const Type
*type
= qt
.getTypePtr();
3380 int depth
= array_depth(type
);
3381 QualType base
= base_type(qt
);
3386 array
= isl_calloc_type(ctx
, struct pet_array
);
3390 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
3391 dim
= isl_space_set_alloc(ctx
, 0, depth
);
3392 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
3394 array
->extent
= isl_set_nat_universe(dim
);
3396 dim
= isl_space_params_alloc(ctx
, 0);
3397 array
->context
= isl_set_universe(dim
);
3399 array
= set_upper_bounds(array
, type
, 0);
3403 name
= base
.getAsString();
3404 array
->element_type
= strdup(name
.c_str());
3405 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
3410 /* Construct a list of pet_arrays, one for each array (or scalar)
3411 * accessed inside "scop" add this list to "scop" and return the result.
3413 * The context of "scop" is updated with the intesection of
3414 * the contexts of all arrays, i.e., constraints on the parameters
3415 * that ensure that the arrays have a valid (non-negative) size.
3417 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
3420 set
<ValueDecl
*> arrays
;
3421 set
<ValueDecl
*>::iterator it
;
3423 struct pet_array
**scop_arrays
;
3428 pet_scop_collect_arrays(scop
, arrays
);
3429 if (arrays
.size() == 0)
3432 n_array
= scop
->n_array
;
3434 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
3435 n_array
+ arrays
.size());
3438 scop
->arrays
= scop_arrays
;
3440 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
3441 struct pet_array
*array
;
3442 scop
->arrays
[n_array
+ i
] = array
= extract_array(ctx
, *it
);
3443 if (!scop
->arrays
[n_array
+ i
])
3446 scop
->context
= isl_set_intersect(scop
->context
,
3447 isl_set_copy(array
->context
));
3454 pet_scop_free(scop
);
3458 /* Bound all parameters in scop->context to the possible values
3459 * of the corresponding C variable.
3461 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
3468 n
= isl_set_dim(scop
->context
, isl_dim_param
);
3469 for (int i
= 0; i
< n
; ++i
) {
3473 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
3474 decl
= (ValueDecl
*) isl_id_get_user(id
);
3477 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
3485 pet_scop_free(scop
);
3489 /* Construct a pet_scop from the given function.
3491 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
3496 stmt
= fd
->getBody();
3499 scop
= extract(stmt
);
3502 scop
= pet_scop_detect_parameter_accesses(scop
);
3503 scop
= scan_arrays(scop
);
3504 scop
= add_parameter_bounds(scop
);
3505 scop
= pet_scop_gist(scop
, value_bounds
);