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>
50 #include "scop_plus.h"
55 using namespace clang
;
57 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
58 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
60 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
61 SourceLocation(), var
, false, var
->getInnerLocStart(),
62 var
->getType(), VK_LValue
);
64 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
65 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
67 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
68 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
72 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
74 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
75 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
79 /* Check if the element type corresponding to the given array type
80 * has a const qualifier.
82 static bool const_base(QualType qt
)
84 const Type
*type
= qt
.getTypePtr();
86 if (type
->isPointerType())
87 return const_base(type
->getPointeeType());
88 if (type
->isArrayType()) {
89 const ArrayType
*atype
;
90 type
= type
->getCanonicalTypeInternal().getTypePtr();
91 atype
= cast
<ArrayType
>(type
);
92 return const_base(atype
->getElementType());
95 return qt
.isConstQualified();
98 /* Mark "decl" as having an unknown value in "assigned_value".
100 * If no (known or unknown) value was assigned to "decl" before,
101 * then it may have been treated as a parameter before and may
102 * therefore appear in a value assigned to another variable.
103 * If so, this assignment needs to be turned into an unknown value too.
105 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
108 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
110 it
= assigned_value
.find(decl
);
112 assigned_value
[decl
] = NULL
;
114 if (it
== assigned_value
.end())
117 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
118 isl_pw_aff
*pa
= it
->second
;
119 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
121 for (int i
= 0; i
< nparam
; ++i
) {
124 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
126 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
127 if (isl_id_get_user(id
) == decl
)
134 /* Look for any assignments to scalar variables in part of the parse
135 * tree and set assigned_value to NULL for each of them.
136 * Also reset assigned_value if the address of a scalar variable
137 * is being taken. As an exception, if the address is passed to a function
138 * that is declared to receive a const pointer, then assigned_value is
141 * This ensures that we won't use any previously stored value
142 * in the current subtree and its parents.
144 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
145 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
146 set
<UnaryOperator
*> skip
;
148 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
149 assigned_value(assigned_value
) {}
151 /* Check for "address of" operators whose value is passed
152 * to a const pointer argument and add them to "skip", so that
153 * we can skip them in VisitUnaryOperator.
155 bool VisitCallExpr(CallExpr
*expr
) {
157 fd
= expr
->getDirectCallee();
160 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
161 Expr
*arg
= expr
->getArg(i
);
163 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
164 ImplicitCastExpr
*ice
;
165 ice
= cast
<ImplicitCastExpr
>(arg
);
166 arg
= ice
->getSubExpr();
168 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
170 op
= cast
<UnaryOperator
>(arg
);
171 if (op
->getOpcode() != UO_AddrOf
)
173 if (const_base(fd
->getParamDecl(i
)->getType()))
179 bool VisitUnaryOperator(UnaryOperator
*expr
) {
184 if (expr
->getOpcode() != UO_AddrOf
)
186 if (skip
.find(expr
) != skip
.end())
189 arg
= expr
->getSubExpr();
190 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
192 ref
= cast
<DeclRefExpr
>(arg
);
193 decl
= ref
->getDecl();
194 clear_assignment(assigned_value
, decl
);
198 bool VisitBinaryOperator(BinaryOperator
*expr
) {
203 if (!expr
->isAssignmentOp())
205 lhs
= expr
->getLHS();
206 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
208 ref
= cast
<DeclRefExpr
>(lhs
);
209 decl
= ref
->getDecl();
210 clear_assignment(assigned_value
, decl
);
215 /* Keep a copy of the currently assigned values.
217 * Any variable that is assigned a value inside the current scope
218 * is removed again when we leave the scope (either because it wasn't
219 * stored in the cache or because it has a different value in the cache).
221 struct assigned_value_cache
{
222 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
223 map
<ValueDecl
*, isl_pw_aff
*> cache
;
225 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
226 assigned_value(assigned_value
), cache(assigned_value
) {}
227 ~assigned_value_cache() {
228 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
229 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
232 (cache
.find(it
->first
) != cache
.end() &&
233 cache
[it
->first
] != it
->second
))
234 cache
[it
->first
] = NULL
;
236 assigned_value
= cache
;
240 /* Insert an expression into the collection of expressions,
241 * provided it is not already in there.
242 * The isl_pw_affs are freed in the destructor.
244 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
246 std::set
<isl_pw_aff
*>::iterator it
;
248 if (expressions
.find(expr
) == expressions
.end())
249 expressions
.insert(expr
);
251 isl_pw_aff_free(expr
);
256 std::set
<isl_pw_aff
*>::iterator it
;
258 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
259 isl_pw_aff_free(*it
);
261 isl_union_map_free(value_bounds
);
264 /* Called if we found something we (currently) cannot handle.
265 * We'll provide more informative warnings later.
267 * We only actually complain if autodetect is false.
269 void PetScan::unsupported(Stmt
*stmt
, const char *msg
)
271 if (options
->autodetect
)
274 SourceLocation loc
= stmt
->getLocStart();
275 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
276 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
277 msg
? msg
: "unsupported");
278 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
281 /* Extract an integer from "expr" and store it in "v".
283 int PetScan::extract_int(IntegerLiteral
*expr
, isl_int
*v
)
285 const Type
*type
= expr
->getType().getTypePtr();
286 int is_signed
= type
->hasSignedIntegerRepresentation();
289 int64_t i
= expr
->getValue().getSExtValue();
290 isl_int_set_si(*v
, i
);
292 uint64_t i
= expr
->getValue().getZExtValue();
293 isl_int_set_ui(*v
, i
);
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::ParenExpr
*expr
, isl_int
*v
)
304 return extract_int(expr
->getSubExpr(), v
);
307 /* Extract an integer from "expr" and store it in "v".
308 * Return -1 if "expr" does not (obviously) represent an integer.
310 int PetScan::extract_int(clang::Expr
*expr
, isl_int
*v
)
312 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
313 return extract_int(cast
<IntegerLiteral
>(expr
), v
);
314 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
315 return extract_int(cast
<ParenExpr
>(expr
), v
);
321 /* Extract an affine expression from the IntegerLiteral "expr".
323 __isl_give isl_pw_aff
*PetScan::extract_affine(IntegerLiteral
*expr
)
325 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
326 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
327 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
328 isl_set
*dom
= isl_set_universe(dim
);
332 extract_int(expr
, &v
);
333 aff
= isl_aff_add_constant(aff
, v
);
336 return isl_pw_aff_alloc(dom
, aff
);
339 /* Extract an affine expression from the APInt "val".
341 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
343 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
344 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
345 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
346 isl_set
*dom
= isl_set_universe(dim
);
350 isl_int_set_ui(v
, val
.getZExtValue());
351 aff
= isl_aff_add_constant(aff
, v
);
354 return isl_pw_aff_alloc(dom
, aff
);
357 __isl_give isl_pw_aff
*PetScan::extract_affine(ImplicitCastExpr
*expr
)
359 return extract_affine(expr
->getSubExpr());
362 static unsigned get_type_size(ValueDecl
*decl
)
364 return decl
->getASTContext().getIntWidth(decl
->getType());
367 /* Bound parameter "pos" of "set" to the possible values of "decl".
369 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
370 unsigned pos
, ValueDecl
*decl
)
377 width
= get_type_size(decl
);
378 if (decl
->getType()->isUnsignedIntegerType()) {
379 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
380 isl_int_set_si(v
, 1);
381 isl_int_mul_2exp(v
, v
, width
);
382 isl_int_sub_ui(v
, v
, 1);
383 set
= isl_set_upper_bound(set
, isl_dim_param
, pos
, v
);
385 isl_int_set_si(v
, 1);
386 isl_int_mul_2exp(v
, v
, width
- 1);
387 isl_int_sub_ui(v
, v
, 1);
388 set
= isl_set_upper_bound(set
, isl_dim_param
, pos
, v
);
390 isl_int_sub_ui(v
, v
, 1);
391 set
= isl_set_lower_bound(set
, isl_dim_param
, pos
, v
);
399 /* Extract an affine expression from the DeclRefExpr "expr".
401 * If the variable has been assigned a value, then we check whether
402 * we know what (affine) value was assigned.
403 * If so, we return this value. Otherwise we convert "expr"
404 * to an extra parameter (provided nesting_enabled is set).
406 * Otherwise, we simply return an expression that is equal
407 * to a parameter corresponding to the referenced variable.
409 __isl_give isl_pw_aff
*PetScan::extract_affine(DeclRefExpr
*expr
)
411 ValueDecl
*decl
= expr
->getDecl();
412 const Type
*type
= decl
->getType().getTypePtr();
418 if (!type
->isIntegerType()) {
423 if (assigned_value
.find(decl
) != assigned_value
.end()) {
424 if (assigned_value
[decl
])
425 return isl_pw_aff_copy(assigned_value
[decl
]);
427 return nested_access(expr
);
430 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
431 dim
= isl_space_params_alloc(ctx
, 1);
433 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
435 dom
= isl_set_universe(isl_space_copy(dim
));
436 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
437 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
439 return isl_pw_aff_alloc(dom
, aff
);
442 /* Extract an affine expression from an integer division operation.
443 * In particular, if "expr" is lhs/rhs, then return
445 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
447 * The second argument (rhs) is required to be a (positive) integer constant.
449 __isl_give isl_pw_aff
*PetScan::extract_affine_div(BinaryOperator
*expr
)
452 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
457 rhs_expr
= expr
->getRHS();
459 if (extract_int(rhs_expr
, &v
) < 0) {
464 lhs
= extract_affine(expr
->getLHS());
465 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
467 lhs
= isl_pw_aff_scale_down(lhs
, v
);
470 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(lhs
));
471 lhs_c
= isl_pw_aff_ceil(lhs
);
472 res
= isl_pw_aff_cond(isl_set_indicator_function(cond
), lhs_f
, lhs_c
);
477 /* Extract an affine expression from a modulo operation.
478 * In particular, if "expr" is lhs/rhs, then return
480 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
482 * The second argument (rhs) is required to be a (positive) integer constant.
484 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
487 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
492 rhs_expr
= expr
->getRHS();
493 if (rhs_expr
->getStmtClass() != Stmt::IntegerLiteralClass
) {
498 lhs
= extract_affine(expr
->getLHS());
499 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
502 extract_int(cast
<IntegerLiteral
>(rhs_expr
), &v
);
503 res
= isl_pw_aff_scale_down(isl_pw_aff_copy(lhs
), v
);
505 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(res
));
506 lhs_c
= isl_pw_aff_ceil(res
);
507 res
= isl_pw_aff_cond(isl_set_indicator_function(cond
), lhs_f
, lhs_c
);
509 res
= isl_pw_aff_scale(res
, v
);
512 res
= isl_pw_aff_sub(lhs
, res
);
517 /* Extract an affine expression from a multiplication operation.
518 * This is only allowed if at least one of the two arguments
519 * is a (piecewise) constant.
521 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
526 lhs
= extract_affine(expr
->getLHS());
527 rhs
= extract_affine(expr
->getRHS());
529 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
530 isl_pw_aff_free(lhs
);
531 isl_pw_aff_free(rhs
);
536 return isl_pw_aff_mul(lhs
, rhs
);
539 /* Extract an affine expression from an addition or subtraction operation.
541 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
546 lhs
= extract_affine(expr
->getLHS());
547 rhs
= extract_affine(expr
->getRHS());
549 switch (expr
->getOpcode()) {
551 return isl_pw_aff_add(lhs
, rhs
);
553 return isl_pw_aff_sub(lhs
, rhs
);
555 isl_pw_aff_free(lhs
);
556 isl_pw_aff_free(rhs
);
566 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
572 isl_int_set_si(mod
, 1);
573 isl_int_mul_2exp(mod
, mod
, width
);
575 pwaff
= isl_pw_aff_mod(pwaff
, mod
);
582 /* Limit the domain of "pwaff" to those elements where the function
585 * 2^{width-1} <= pwaff < 2^{width-1}
587 static __isl_give isl_pw_aff
*avoid_overflow(__isl_take isl_pw_aff
*pwaff
,
591 isl_space
*space
= isl_pw_aff_get_domain_space(pwaff
);
592 isl_local_space
*ls
= isl_local_space_from_space(space
);
598 isl_int_set_si(v
, 1);
599 isl_int_mul_2exp(v
, v
, width
- 1);
601 bound
= isl_aff_zero_on_domain(ls
);
602 bound
= isl_aff_add_constant(bound
, v
);
603 b
= isl_pw_aff_from_aff(bound
);
605 dom
= isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff
), isl_pw_aff_copy(b
));
606 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
608 b
= isl_pw_aff_neg(b
);
609 dom
= isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff
), b
);
610 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
617 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
619 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
620 __isl_take isl_set
*dom
)
623 pa
= isl_set_indicator_function(set
);
624 pa
= isl_pw_aff_intersect_domain(pa
, dom
);
628 /* Extract an affine expression from some binary operations.
629 * If the result of the expression is unsigned, then we wrap it
630 * based on the size of the type. Otherwise, we ensure that
631 * no overflow occurs.
633 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
638 switch (expr
->getOpcode()) {
641 res
= extract_affine_add(expr
);
644 res
= extract_affine_div(expr
);
647 res
= extract_affine_mod(expr
);
650 res
= extract_affine_mul(expr
);
660 return extract_condition(expr
);
666 width
= ast_context
.getIntWidth(expr
->getType());
667 if (expr
->getType()->isUnsignedIntegerType())
668 res
= wrap(res
, width
);
670 res
= avoid_overflow(res
, width
);
675 /* Extract an affine expression from a negation operation.
677 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
679 if (expr
->getOpcode() == UO_Minus
)
680 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
681 if (expr
->getOpcode() == UO_LNot
)
682 return extract_condition(expr
);
688 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
690 return extract_affine(expr
->getSubExpr());
693 /* Extract an affine expression from some special function calls.
694 * In particular, we handle "min", "max", "ceild" and "floord".
695 * In case of the latter two, the second argument needs to be
696 * a (positive) integer constant.
698 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
702 isl_pw_aff
*aff1
, *aff2
;
704 fd
= expr
->getDirectCallee();
710 name
= fd
->getDeclName().getAsString();
711 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
712 !(expr
->getNumArgs() == 2 && name
== "max") &&
713 !(expr
->getNumArgs() == 2 && name
== "floord") &&
714 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
719 if (name
== "min" || name
== "max") {
720 aff1
= extract_affine(expr
->getArg(0));
721 aff2
= extract_affine(expr
->getArg(1));
724 aff1
= isl_pw_aff_min(aff1
, aff2
);
726 aff1
= isl_pw_aff_max(aff1
, aff2
);
727 } else if (name
== "floord" || name
== "ceild") {
729 Expr
*arg2
= expr
->getArg(1);
731 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
735 aff1
= extract_affine(expr
->getArg(0));
737 extract_int(cast
<IntegerLiteral
>(arg2
), &v
);
738 aff1
= isl_pw_aff_scale_down(aff1
, v
);
740 if (name
== "floord")
741 aff1
= isl_pw_aff_floor(aff1
);
743 aff1
= isl_pw_aff_ceil(aff1
);
753 /* This method is called when we come across an access that is
754 * nested in what is supposed to be an affine expression.
755 * If nesting is allowed, we return a new parameter that corresponds
756 * to this nested access. Otherwise, we simply complain.
758 * The new parameter is resolved in resolve_nested.
760 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
767 if (!nesting_enabled
) {
772 id
= isl_id_alloc(ctx
, NULL
, expr
);
773 dim
= isl_space_params_alloc(ctx
, 1);
775 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
777 dom
= isl_set_universe(isl_space_copy(dim
));
778 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
779 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
781 return isl_pw_aff_alloc(dom
, aff
);
784 /* Affine expressions are not supposed to contain array accesses,
785 * but if nesting is allowed, we return a parameter corresponding
786 * to the array access.
788 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
790 return nested_access(expr
);
793 /* Extract an affine expression from a conditional operation.
795 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
797 isl_pw_aff
*cond
, *lhs
, *rhs
, *res
;
799 cond
= extract_condition(expr
->getCond());
800 lhs
= extract_affine(expr
->getTrueExpr());
801 rhs
= extract_affine(expr
->getFalseExpr());
803 return isl_pw_aff_cond(cond
, lhs
, rhs
);
806 /* Extract an affine expression, if possible, from "expr".
807 * Otherwise return NULL.
809 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
811 switch (expr
->getStmtClass()) {
812 case Stmt::ImplicitCastExprClass
:
813 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
814 case Stmt::IntegerLiteralClass
:
815 return extract_affine(cast
<IntegerLiteral
>(expr
));
816 case Stmt::DeclRefExprClass
:
817 return extract_affine(cast
<DeclRefExpr
>(expr
));
818 case Stmt::BinaryOperatorClass
:
819 return extract_affine(cast
<BinaryOperator
>(expr
));
820 case Stmt::UnaryOperatorClass
:
821 return extract_affine(cast
<UnaryOperator
>(expr
));
822 case Stmt::ParenExprClass
:
823 return extract_affine(cast
<ParenExpr
>(expr
));
824 case Stmt::CallExprClass
:
825 return extract_affine(cast
<CallExpr
>(expr
));
826 case Stmt::ArraySubscriptExprClass
:
827 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
828 case Stmt::ConditionalOperatorClass
:
829 return extract_affine(cast
<ConditionalOperator
>(expr
));
836 __isl_give isl_map
*PetScan::extract_access(ImplicitCastExpr
*expr
)
838 return extract_access(expr
->getSubExpr());
841 /* Return the depth of an array of the given type.
843 static int array_depth(const Type
*type
)
845 if (type
->isPointerType())
846 return 1 + array_depth(type
->getPointeeType().getTypePtr());
847 if (type
->isArrayType()) {
848 const ArrayType
*atype
;
849 type
= type
->getCanonicalTypeInternal().getTypePtr();
850 atype
= cast
<ArrayType
>(type
);
851 return 1 + array_depth(atype
->getElementType().getTypePtr());
856 /* Return the element type of the given array type.
858 static QualType
base_type(QualType qt
)
860 const Type
*type
= qt
.getTypePtr();
862 if (type
->isPointerType())
863 return base_type(type
->getPointeeType());
864 if (type
->isArrayType()) {
865 const ArrayType
*atype
;
866 type
= type
->getCanonicalTypeInternal().getTypePtr();
867 atype
= cast
<ArrayType
>(type
);
868 return base_type(atype
->getElementType());
873 /* Extract an access relation from a reference to a variable.
874 * If the variable has name "A" and its type corresponds to an
875 * array of depth d, then the returned access relation is of the
878 * { [] -> A[i_1,...,i_d] }
880 __isl_give isl_map
*PetScan::extract_access(DeclRefExpr
*expr
)
882 ValueDecl
*decl
= expr
->getDecl();
883 int depth
= array_depth(decl
->getType().getTypePtr());
884 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
885 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, depth
);
888 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
890 access_rel
= isl_map_universe(dim
);
895 /* Extract an access relation from an integer contant.
896 * If the value of the constant is "v", then the returned access relation
901 __isl_give isl_map
*PetScan::extract_access(IntegerLiteral
*expr
)
903 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr
)));
906 /* Try and extract an access relation from the given Expr.
907 * Return NULL if it doesn't work out.
909 __isl_give isl_map
*PetScan::extract_access(Expr
*expr
)
911 switch (expr
->getStmtClass()) {
912 case Stmt::ImplicitCastExprClass
:
913 return extract_access(cast
<ImplicitCastExpr
>(expr
));
914 case Stmt::DeclRefExprClass
:
915 return extract_access(cast
<DeclRefExpr
>(expr
));
916 case Stmt::ArraySubscriptExprClass
:
917 return extract_access(cast
<ArraySubscriptExpr
>(expr
));
924 /* Assign the affine expression "index" to the output dimension "pos" of "map",
925 * restrict the domain to those values that result in a non-negative index
926 * and return the result.
928 __isl_give isl_map
*set_index(__isl_take isl_map
*map
, int pos
,
929 __isl_take isl_pw_aff
*index
)
932 int len
= isl_map_dim(map
, isl_dim_out
);
936 domain
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(index
));
937 index
= isl_pw_aff_intersect_domain(index
, domain
);
938 index_map
= isl_map_from_range(isl_set_from_pw_aff(index
));
939 index_map
= isl_map_insert_dims(index_map
, isl_dim_out
, 0, pos
);
940 index_map
= isl_map_add_dims(index_map
, isl_dim_out
, len
- pos
- 1);
941 id
= isl_map_get_tuple_id(map
, isl_dim_out
);
942 index_map
= isl_map_set_tuple_id(index_map
, isl_dim_out
, id
);
944 map
= isl_map_intersect(map
, index_map
);
949 /* Extract an access relation from the given array subscript expression.
950 * If nesting is allowed in general, then we turn it on while
951 * examining the index expression.
953 * We first extract an access relation from the base.
954 * This will result in an access relation with a range that corresponds
955 * to the array being accessed and with earlier indices filled in already.
956 * We then extract the current index and fill that in as well.
957 * The position of the current index is based on the type of base.
958 * If base is the actual array variable, then the depth of this type
959 * will be the same as the depth of the array and we will fill in
960 * the first array index.
961 * Otherwise, the depth of the base type will be smaller and we will fill
964 __isl_give isl_map
*PetScan::extract_access(ArraySubscriptExpr
*expr
)
966 Expr
*base
= expr
->getBase();
967 Expr
*idx
= expr
->getIdx();
969 isl_map
*base_access
;
971 int depth
= array_depth(base
->getType().getTypePtr());
973 bool save_nesting
= nesting_enabled
;
975 nesting_enabled
= allow_nested
;
977 base_access
= extract_access(base
);
978 index
= extract_affine(idx
);
980 nesting_enabled
= save_nesting
;
982 pos
= isl_map_dim(base_access
, isl_dim_out
) - depth
;
983 access
= set_index(base_access
, pos
, index
);
988 /* Check if "expr" calls function "minmax" with two arguments and if so
989 * make lhs and rhs refer to these two arguments.
991 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
997 if (expr
->getStmtClass() != Stmt::CallExprClass
)
1000 call
= cast
<CallExpr
>(expr
);
1001 fd
= call
->getDirectCallee();
1005 if (call
->getNumArgs() != 2)
1008 name
= fd
->getDeclName().getAsString();
1012 lhs
= call
->getArg(0);
1013 rhs
= call
->getArg(1);
1018 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1019 * lhs and rhs refer to the two arguments.
1021 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1023 return is_minmax(expr
, "min", lhs
, rhs
);
1026 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1027 * lhs and rhs refer to the two arguments.
1029 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1031 return is_minmax(expr
, "max", lhs
, rhs
);
1034 /* Return "lhs && rhs", defined on the shared definition domain.
1036 static __isl_give isl_pw_aff
*pw_aff_and(__isl_take isl_pw_aff
*lhs
,
1037 __isl_take isl_pw_aff
*rhs
)
1042 dom
= isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs
)),
1043 isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1044 cond
= isl_set_intersect(isl_pw_aff_non_zero_set(lhs
),
1045 isl_pw_aff_non_zero_set(rhs
));
1046 return indicator_function(cond
, dom
);
1049 /* Return "lhs && rhs", with shortcut semantics.
1050 * That is, if lhs is false, then the result is defined even if rhs is not.
1051 * In practice, we compute lhs ? rhs : lhs.
1053 static __isl_give isl_pw_aff
*pw_aff_and_then(__isl_take isl_pw_aff
*lhs
,
1054 __isl_take isl_pw_aff
*rhs
)
1056 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), rhs
, lhs
);
1059 /* Return "lhs || rhs", with shortcut semantics.
1060 * That is, if lhs is true, then the result is defined even if rhs is not.
1061 * In practice, we compute lhs ? lhs : rhs.
1063 static __isl_give isl_pw_aff
*pw_aff_or_else(__isl_take isl_pw_aff
*lhs
,
1064 __isl_take isl_pw_aff
*rhs
)
1066 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), lhs
, rhs
);
1069 /* Extract an affine expressions representing the comparison "LHS op RHS"
1070 * "comp" is the original statement that "LHS op RHS" is derived from
1071 * and is used for diagnostics.
1073 * If the comparison is of the form
1077 * then the expression is constructed as the conjunction of
1082 * A similar optimization is performed for max(a,b) <= c.
1083 * We do this because that will lead to simpler representations
1084 * of the expression.
1085 * If isl is ever enhanced to explicitly deal with min and max expressions,
1086 * this optimization can be removed.
1088 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
1089 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
1098 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
1100 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
1102 if (op
== BO_LT
|| op
== BO_LE
) {
1103 Expr
*expr1
, *expr2
;
1104 if (is_min(RHS
, expr1
, expr2
)) {
1105 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
1106 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
1107 return pw_aff_and(lhs
, rhs
);
1109 if (is_max(LHS
, expr1
, expr2
)) {
1110 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
1111 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
1112 return pw_aff_and(lhs
, rhs
);
1116 lhs
= extract_affine(LHS
);
1117 rhs
= extract_affine(RHS
);
1119 dom
= isl_pw_aff_domain(isl_pw_aff_copy(lhs
));
1120 dom
= isl_set_intersect(dom
, isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1124 cond
= isl_pw_aff_lt_set(lhs
, rhs
);
1127 cond
= isl_pw_aff_le_set(lhs
, rhs
);
1130 cond
= isl_pw_aff_eq_set(lhs
, rhs
);
1133 cond
= isl_pw_aff_ne_set(lhs
, rhs
);
1136 isl_pw_aff_free(lhs
);
1137 isl_pw_aff_free(rhs
);
1143 cond
= isl_set_coalesce(cond
);
1144 res
= indicator_function(cond
, dom
);
1149 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
1151 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1152 comp
->getRHS(), comp
);
1155 /* Extract an affine expression representing the negation (logical not)
1156 * of a subexpression.
1158 __isl_give isl_pw_aff
*PetScan::extract_boolean(UnaryOperator
*op
)
1160 isl_set
*set_cond
, *dom
;
1161 isl_pw_aff
*cond
, *res
;
1163 cond
= extract_condition(op
->getSubExpr());
1165 dom
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
1167 set_cond
= isl_pw_aff_zero_set(cond
);
1169 res
= indicator_function(set_cond
, dom
);
1174 /* Extract an affine expression representing the disjunction (logical or)
1175 * or conjunction (logical and) of two subexpressions.
1177 __isl_give isl_pw_aff
*PetScan::extract_boolean(BinaryOperator
*comp
)
1179 isl_pw_aff
*lhs
, *rhs
;
1181 lhs
= extract_condition(comp
->getLHS());
1182 rhs
= extract_condition(comp
->getRHS());
1184 switch (comp
->getOpcode()) {
1186 return pw_aff_and_then(lhs
, rhs
);
1188 return pw_aff_or_else(lhs
, rhs
);
1190 isl_pw_aff_free(lhs
);
1191 isl_pw_aff_free(rhs
);
1198 __isl_give isl_pw_aff
*PetScan::extract_condition(UnaryOperator
*expr
)
1200 switch (expr
->getOpcode()) {
1202 return extract_boolean(expr
);
1209 /* Extract the affine expression "expr != 0 ? 1 : 0".
1211 __isl_give isl_pw_aff
*PetScan::extract_implicit_condition(Expr
*expr
)
1216 res
= extract_affine(expr
);
1218 dom
= isl_pw_aff_domain(isl_pw_aff_copy(res
));
1219 set
= isl_pw_aff_non_zero_set(res
);
1221 res
= indicator_function(set
, dom
);
1226 /* Extract an affine expression from a boolean expression.
1227 * In particular, return the expression "expr ? 1 : 0".
1229 * If the expression doesn't look like a condition, we assume it
1230 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1232 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
1234 BinaryOperator
*comp
;
1237 isl_set
*u
= isl_set_universe(isl_space_params_alloc(ctx
, 0));
1238 return indicator_function(u
, isl_set_copy(u
));
1241 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1242 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1244 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1245 return extract_condition(cast
<UnaryOperator
>(expr
));
1247 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1248 return extract_implicit_condition(expr
);
1250 comp
= cast
<BinaryOperator
>(expr
);
1251 switch (comp
->getOpcode()) {
1258 return extract_comparison(comp
);
1261 return extract_boolean(comp
);
1263 return extract_implicit_condition(expr
);
1267 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
1271 return pet_op_minus
;
1277 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
1281 return pet_op_add_assign
;
1283 return pet_op_sub_assign
;
1285 return pet_op_mul_assign
;
1287 return pet_op_div_assign
;
1289 return pet_op_assign
;
1311 /* Construct a pet_expr representing a unary operator expression.
1313 struct pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1315 struct pet_expr
*arg
;
1316 enum pet_op_type op
;
1318 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1319 if (op
== pet_op_last
) {
1324 arg
= extract_expr(expr
->getSubExpr());
1326 return pet_expr_new_unary(ctx
, op
, arg
);
1329 /* Mark the given access pet_expr as a write.
1330 * If a scalar is being accessed, then mark its value
1331 * as unknown in assigned_value.
1333 void PetScan::mark_write(struct pet_expr
*access
)
1338 access
->acc
.write
= 1;
1339 access
->acc
.read
= 0;
1341 if (isl_map_dim(access
->acc
.access
, isl_dim_out
) != 0)
1344 id
= isl_map_get_tuple_id(access
->acc
.access
, isl_dim_out
);
1345 decl
= (ValueDecl
*) isl_id_get_user(id
);
1346 clear_assignment(assigned_value
, decl
);
1350 /* Construct a pet_expr representing a binary operator expression.
1352 * If the top level operator is an assignment and the LHS is an access,
1353 * then we mark that access as a write. If the operator is a compound
1354 * assignment, the access is marked as both a read and a write.
1356 * If "expr" assigns something to a scalar variable, then we mark
1357 * the variable as having been assigned. If, furthermore, the expression
1358 * is affine, then keep track of this value in assigned_value
1359 * so that we can plug it in when we later come across the same variable.
1361 struct pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1363 struct pet_expr
*lhs
, *rhs
;
1364 enum pet_op_type op
;
1366 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1367 if (op
== pet_op_last
) {
1372 lhs
= extract_expr(expr
->getLHS());
1373 rhs
= extract_expr(expr
->getRHS());
1375 if (expr
->isAssignmentOp() && lhs
&& lhs
->type
== pet_expr_access
) {
1377 if (expr
->isCompoundAssignmentOp())
1381 if (expr
->getOpcode() == BO_Assign
&&
1382 lhs
&& lhs
->type
== pet_expr_access
&&
1383 isl_map_dim(lhs
->acc
.access
, isl_dim_out
) == 0) {
1384 isl_id
*id
= isl_map_get_tuple_id(lhs
->acc
.access
, isl_dim_out
);
1385 ValueDecl
*decl
= (ValueDecl
*) isl_id_get_user(id
);
1386 Expr
*rhs
= expr
->getRHS();
1387 isl_pw_aff
*pa
= try_extract_affine(rhs
);
1388 clear_assignment(assigned_value
, decl
);
1390 assigned_value
[decl
] = pa
;
1391 insert_expression(pa
);
1396 return pet_expr_new_binary(ctx
, op
, lhs
, rhs
);
1399 /* Construct a pet_expr representing a conditional operation.
1401 * We first try to extract the condition as an affine expression.
1402 * If that fails, we construct a pet_expr tree representing the condition.
1404 struct pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1406 struct pet_expr
*cond
, *lhs
, *rhs
;
1409 pa
= try_extract_affine(expr
->getCond());
1411 isl_set
*test
= isl_set_from_pw_aff(pa
);
1412 cond
= pet_expr_from_access(isl_map_from_range(test
));
1414 cond
= extract_expr(expr
->getCond());
1415 lhs
= extract_expr(expr
->getTrueExpr());
1416 rhs
= extract_expr(expr
->getFalseExpr());
1418 return pet_expr_new_ternary(ctx
, cond
, lhs
, rhs
);
1421 struct pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1423 return extract_expr(expr
->getSubExpr());
1426 /* Construct a pet_expr representing a floating point value.
1428 struct pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1430 return pet_expr_new_double(ctx
, expr
->getValueAsApproximateDouble());
1433 /* Extract an access relation from "expr" and then convert it into
1436 struct pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1439 struct pet_expr
*pe
;
1441 switch (expr
->getStmtClass()) {
1442 case Stmt::ArraySubscriptExprClass
:
1443 access
= extract_access(cast
<ArraySubscriptExpr
>(expr
));
1445 case Stmt::DeclRefExprClass
:
1446 access
= extract_access(cast
<DeclRefExpr
>(expr
));
1448 case Stmt::IntegerLiteralClass
:
1449 access
= extract_access(cast
<IntegerLiteral
>(expr
));
1456 pe
= pet_expr_from_access(access
);
1461 struct pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1463 return extract_expr(expr
->getSubExpr());
1466 /* Construct a pet_expr representing a function call.
1468 * If we are passing along a pointer to an array element
1469 * or an entire row or even higher dimensional slice of an array,
1470 * then the function being called may write into the array.
1472 * We assume here that if the function is declared to take a pointer
1473 * to a const type, then the function will perform a read
1474 * and that otherwise, it will perform a write.
1476 struct pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1478 struct pet_expr
*res
= NULL
;
1482 fd
= expr
->getDirectCallee();
1488 name
= fd
->getDeclName().getAsString();
1489 res
= pet_expr_new_call(ctx
, name
.c_str(), expr
->getNumArgs());
1493 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
1494 Expr
*arg
= expr
->getArg(i
);
1498 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1499 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(arg
);
1500 arg
= ice
->getSubExpr();
1502 if (arg
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1503 UnaryOperator
*op
= cast
<UnaryOperator
>(arg
);
1504 if (op
->getOpcode() == UO_AddrOf
) {
1506 arg
= op
->getSubExpr();
1509 res
->args
[i
] = PetScan::extract_expr(arg
);
1510 main_arg
= res
->args
[i
];
1512 res
->args
[i
] = pet_expr_new_unary(ctx
,
1513 pet_op_address_of
, res
->args
[i
]);
1516 if (arg
->getStmtClass() == Stmt::ArraySubscriptExprClass
&&
1517 array_depth(arg
->getType().getTypePtr()) > 0)
1519 if (is_addr
&& main_arg
->type
== pet_expr_access
) {
1521 if (!fd
->hasPrototype()) {
1522 unsupported(expr
, "prototype required");
1525 parm
= fd
->getParamDecl(i
);
1526 if (!const_base(parm
->getType()))
1527 mark_write(main_arg
);
1537 /* Try and onstruct a pet_expr representing "expr".
1539 struct pet_expr
*PetScan::extract_expr(Expr
*expr
)
1541 switch (expr
->getStmtClass()) {
1542 case Stmt::UnaryOperatorClass
:
1543 return extract_expr(cast
<UnaryOperator
>(expr
));
1544 case Stmt::CompoundAssignOperatorClass
:
1545 case Stmt::BinaryOperatorClass
:
1546 return extract_expr(cast
<BinaryOperator
>(expr
));
1547 case Stmt::ImplicitCastExprClass
:
1548 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1549 case Stmt::ArraySubscriptExprClass
:
1550 case Stmt::DeclRefExprClass
:
1551 case Stmt::IntegerLiteralClass
:
1552 return extract_access_expr(expr
);
1553 case Stmt::FloatingLiteralClass
:
1554 return extract_expr(cast
<FloatingLiteral
>(expr
));
1555 case Stmt::ParenExprClass
:
1556 return extract_expr(cast
<ParenExpr
>(expr
));
1557 case Stmt::ConditionalOperatorClass
:
1558 return extract_expr(cast
<ConditionalOperator
>(expr
));
1559 case Stmt::CallExprClass
:
1560 return extract_expr(cast
<CallExpr
>(expr
));
1567 /* Check if the given initialization statement is an assignment.
1568 * If so, return that assignment. Otherwise return NULL.
1570 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1572 BinaryOperator
*ass
;
1574 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1577 ass
= cast
<BinaryOperator
>(init
);
1578 if (ass
->getOpcode() != BO_Assign
)
1584 /* Check if the given initialization statement is a declaration
1585 * of a single variable.
1586 * If so, return that declaration. Otherwise return NULL.
1588 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1592 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1595 decl
= cast
<DeclStmt
>(init
);
1597 if (!decl
->isSingleDecl())
1600 return decl
->getSingleDecl();
1603 /* Given the assignment operator in the initialization of a for loop,
1604 * extract the induction variable, i.e., the (integer)variable being
1607 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1614 lhs
= init
->getLHS();
1615 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1620 ref
= cast
<DeclRefExpr
>(lhs
);
1621 decl
= ref
->getDecl();
1622 type
= decl
->getType().getTypePtr();
1624 if (!type
->isIntegerType()) {
1632 /* Given the initialization statement of a for loop and the single
1633 * declaration in this initialization statement,
1634 * extract the induction variable, i.e., the (integer) variable being
1637 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1641 vd
= cast
<VarDecl
>(decl
);
1643 const QualType type
= vd
->getType();
1644 if (!type
->isIntegerType()) {
1649 if (!vd
->getInit()) {
1657 /* Check that op is of the form iv++ or iv--.
1658 * Return an affine expression "1" or "-1" accordingly.
1660 __isl_give isl_pw_aff
*PetScan::extract_unary_increment(
1661 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1668 if (!op
->isIncrementDecrementOp()) {
1673 sub
= op
->getSubExpr();
1674 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1679 ref
= cast
<DeclRefExpr
>(sub
);
1680 if (ref
->getDecl() != iv
) {
1685 space
= isl_space_params_alloc(ctx
, 0);
1686 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
1688 if (op
->isIncrementOp())
1689 aff
= isl_aff_add_constant_si(aff
, 1);
1691 aff
= isl_aff_add_constant_si(aff
, -1);
1693 return isl_pw_aff_from_aff(aff
);
1696 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1697 * has a single constant expression, then put this constant in *user.
1698 * The caller is assumed to have checked that this function will
1699 * be called exactly once.
1701 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
1704 isl_int
*inc
= (isl_int
*)user
;
1707 if (isl_aff_is_cst(aff
))
1708 isl_aff_get_constant(aff
, inc
);
1718 /* Check if op is of the form
1722 * and return inc as an affine expression.
1724 * We extract an affine expression from the RHS, subtract iv and return
1727 __isl_give isl_pw_aff
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1728 clang::ValueDecl
*iv
)
1737 if (op
->getOpcode() != BO_Assign
) {
1743 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1748 ref
= cast
<DeclRefExpr
>(lhs
);
1749 if (ref
->getDecl() != iv
) {
1754 val
= extract_affine(op
->getRHS());
1756 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1758 dim
= isl_space_params_alloc(ctx
, 1);
1759 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1760 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1761 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1763 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
1768 /* Check that op is of the form iv += cst or iv -= cst
1769 * and return an affine expression corresponding oto cst or -cst accordingly.
1771 __isl_give isl_pw_aff
*PetScan::extract_compound_increment(
1772 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1778 BinaryOperatorKind opcode
;
1780 opcode
= op
->getOpcode();
1781 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1785 if (opcode
== BO_SubAssign
)
1789 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1794 ref
= cast
<DeclRefExpr
>(lhs
);
1795 if (ref
->getDecl() != iv
) {
1800 val
= extract_affine(op
->getRHS());
1802 val
= isl_pw_aff_neg(val
);
1807 /* Check that the increment of the given for loop increments
1808 * (or decrements) the induction variable "iv" and return
1809 * the increment as an affine expression if successful.
1811 __isl_give isl_pw_aff
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1814 Stmt
*inc
= stmt
->getInc();
1821 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1822 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1823 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1824 return extract_compound_increment(
1825 cast
<CompoundAssignOperator
>(inc
), iv
);
1826 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1827 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1833 /* Embed the given iteration domain in an extra outer loop
1834 * with induction variable "var".
1835 * If this variable appeared as a parameter in the constraints,
1836 * it is replaced by the new outermost dimension.
1838 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1839 __isl_take isl_id
*var
)
1843 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1844 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1846 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1847 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1854 /* Construct a pet_scop for an infinite loop around the given body.
1856 * We extract a pet_scop for the body and then embed it in a loop with
1865 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
1871 struct pet_scop
*scop
;
1873 scop
= extract(body
);
1877 id
= isl_id_alloc(ctx
, "t", NULL
);
1878 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
1879 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
1880 dim
= isl_space_from_domain(isl_set_get_space(domain
));
1881 dim
= isl_space_add_dims(dim
, isl_dim_out
, 1);
1882 sched
= isl_map_universe(dim
);
1883 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
1884 scop
= pet_scop_embed(scop
, domain
, sched
, id
);
1889 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1895 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
1897 return extract_infinite_loop(stmt
->getBody());
1900 /* Check if the while loop is of the form
1905 * If so, construct a scop for an infinite loop around body.
1908 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
1914 cond
= stmt
->getCond();
1920 set
= isl_pw_aff_non_zero_set(extract_condition(cond
));
1921 is_universe
= isl_set_plain_is_universe(set
);
1929 return extract_infinite_loop(stmt
->getBody());
1932 /* Check whether "cond" expresses a simple loop bound
1933 * on the only set dimension.
1934 * In particular, if "up" is set then "cond" should contain only
1935 * upper bounds on the set dimension.
1936 * Otherwise, it should contain only lower bounds.
1938 static bool is_simple_bound(__isl_keep isl_set
*cond
, isl_int inc
)
1940 if (isl_int_is_pos(inc
))
1941 return !isl_set_dim_has_lower_bound(cond
, isl_dim_set
, 0);
1943 return !isl_set_dim_has_upper_bound(cond
, isl_dim_set
, 0);
1946 /* Extend a condition on a given iteration of a loop to one that
1947 * imposes the same condition on all previous iterations.
1948 * "domain" expresses the lower [upper] bound on the iterations
1949 * when inc is positive [negative].
1951 * In particular, we construct the condition (when inc is positive)
1953 * forall i' : (domain(i') and i' <= i) => cond(i')
1955 * which is equivalent to
1957 * not exists i' : domain(i') and i' <= i and not cond(i')
1959 * We construct this set by negating cond, applying a map
1961 * { [i'] -> [i] : domain(i') and i' <= i }
1963 * and then negating the result again.
1965 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
1966 __isl_take isl_set
*domain
, isl_int inc
)
1968 isl_map
*previous_to_this
;
1970 if (isl_int_is_pos(inc
))
1971 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
1973 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
1975 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
1977 cond
= isl_set_complement(cond
);
1978 cond
= isl_set_apply(cond
, previous_to_this
);
1979 cond
= isl_set_complement(cond
);
1984 /* Construct a domain of the form
1986 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
1988 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
1989 __isl_take isl_pw_aff
*init
, isl_int inc
)
1995 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
1996 dim
= isl_pw_aff_get_domain_space(init
);
1997 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1998 aff
= isl_aff_add_coefficient(aff
, isl_dim_in
, 0, inc
);
1999 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2001 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2002 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2003 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2004 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2006 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2008 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2010 return isl_set_params(set
);
2013 /* Assuming "cond" represents a bound on a loop where the loop
2014 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2017 * Under the given assumptions, wrapping is only possible if "cond" allows
2018 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2019 * increasing iterator and 0 in case of a decreasing iterator.
2021 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
, isl_int inc
)
2027 test
= isl_set_copy(cond
);
2029 isl_int_init(limit
);
2030 if (isl_int_is_neg(inc
))
2031 isl_int_set_si(limit
, 0);
2033 isl_int_set_si(limit
, 1);
2034 isl_int_mul_2exp(limit
, limit
, get_type_size(iv
));
2035 isl_int_sub_ui(limit
, limit
, 1);
2038 test
= isl_set_fix(cond
, isl_dim_set
, 0, limit
);
2039 cw
= !isl_set_is_empty(test
);
2042 isl_int_clear(limit
);
2047 /* Given a one-dimensional space, construct the following mapping on this
2050 * { [v] -> [v mod 2^width] }
2052 * where width is the number of bits used to represent the values
2053 * of the unsigned variable "iv".
2055 static __isl_give isl_map
*compute_wrapping(__isl_take isl_space
*dim
,
2063 isl_int_set_si(mod
, 1);
2064 isl_int_mul_2exp(mod
, mod
, get_type_size(iv
));
2066 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2067 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2068 aff
= isl_aff_mod(aff
, mod
);
2072 return isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2073 map
= isl_map_reverse(map
);
2076 /* Project out the parameter "id" from "set".
2078 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2079 __isl_keep isl_id
*id
)
2083 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2085 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2090 /* Compute the set of parameters for which "set1" is a subset of "set2".
2092 * set1 is a subset of set2 if
2094 * forall i in set1 : i in set2
2098 * not exists i in set1 and i not in set2
2102 * not exists i in set1 \ set2
2104 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2105 __isl_take isl_set
*set2
)
2107 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2110 /* Compute the set of parameter values for which "cond" holds
2111 * on the next iteration for each element of "dom".
2113 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2114 * and then compute the set of parameters for which the result is a subset
2117 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2118 __isl_take isl_set
*dom
, isl_int inc
)
2124 space
= isl_set_get_space(dom
);
2125 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2126 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2127 aff
= isl_aff_add_constant(aff
, inc
);
2128 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2130 dom
= isl_set_apply(dom
, next
);
2132 return enforce_subset(dom
, cond
);
2135 /* Construct a pet_scop for a for statement.
2136 * The for loop is required to be of the form
2138 * for (i = init; condition; ++i)
2142 * for (i = init; condition; --i)
2144 * The initialization of the for loop should either be an assignment
2145 * to an integer variable, or a declaration of such a variable with
2148 * The condition is allowed to contain nested accesses, provided
2149 * they are not being written to inside the body of the loop.
2151 * We extract a pet_scop for the body and then embed it in a loop with
2152 * iteration domain and schedule
2154 * { [i] : i >= init and condition' }
2159 * { [i] : i <= init and condition' }
2162 * Where condition' is equal to condition if the latter is
2163 * a simple upper [lower] bound and a condition that is extended
2164 * to apply to all previous iterations otherwise.
2166 * If the stride of the loop is not 1, then "i >= init" is replaced by
2168 * (exists a: i = init + stride * a and a >= 0)
2170 * If the loop iterator i is unsigned, then wrapping may occur.
2171 * During the computation, we work with a virtual iterator that
2172 * does not wrap. However, the condition in the code applies
2173 * to the wrapped value, so we need to change condition(i)
2174 * into condition([i % 2^width]).
2175 * After computing the virtual domain and schedule, we apply
2176 * the function { [v] -> [v % 2^width] } to the domain and the domain
2177 * of the schedule. In order not to lose any information, we also
2178 * need to intersect the domain of the schedule with the virtual domain
2179 * first, since some iterations in the wrapped domain may be scheduled
2180 * several times, typically an infinite number of times.
2181 * Note that there is no need to perform this final wrapping
2182 * if the loop condition (after wrapping) is simple.
2184 * Wrapping on unsigned iterators can be avoided entirely if
2185 * loop condition is simple, the loop iterator is incremented
2186 * [decremented] by one and the last value before wrapping cannot
2187 * possibly satisfy the loop condition.
2189 * Before extracting a pet_scop from the body we remove all
2190 * assignments in assigned_value to variables that are assigned
2191 * somewhere in the body of the loop.
2193 * Valid parameters for a for loop are those for which the initial
2194 * value itself, the increment on each domain iteration and
2195 * the condition on both the initial value and
2196 * the result of incrementing the iterator for each iteration of the domain
2199 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2201 BinaryOperator
*ass
;
2209 isl_set
*cond
= NULL
;
2211 struct pet_scop
*scop
;
2212 assigned_value_cache
cache(assigned_value
);
2218 isl_map
*wrap
= NULL
;
2219 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2220 isl_set
*valid_init
;
2221 isl_set
*valid_cond
;
2222 isl_set
*valid_cond_init
;
2223 isl_set
*valid_cond_next
;
2226 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2227 return extract_infinite_for(stmt
);
2229 init
= stmt
->getInit();
2234 if ((ass
= initialization_assignment(init
)) != NULL
) {
2235 iv
= extract_induction_variable(ass
);
2238 lhs
= ass
->getLHS();
2239 rhs
= ass
->getRHS();
2240 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2241 VarDecl
*var
= extract_induction_variable(init
, decl
);
2245 rhs
= var
->getInit();
2246 lhs
= create_DeclRefExpr(var
);
2248 unsupported(stmt
->getInit());
2252 pa_inc
= extract_increment(stmt
, iv
);
2257 if (isl_pw_aff_n_piece(pa_inc
) != 1 ||
2258 isl_pw_aff_foreach_piece(pa_inc
, &extract_cst
, &inc
) < 0) {
2259 isl_pw_aff_free(pa_inc
);
2260 unsupported(stmt
->getInc());
2264 valid_inc
= isl_pw_aff_domain(pa_inc
);
2266 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2268 assigned_value
.erase(iv
);
2269 clear_assignments
clear(assigned_value
);
2270 clear
.TraverseStmt(stmt
->getBody());
2272 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
2274 scop
= extract(stmt
->getBody());
2276 pa
= try_extract_nested_condition(stmt
->getCond());
2277 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2278 isl_pw_aff_free(pa
);
2283 pa
= extract_condition(stmt
->getCond());
2284 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2285 cond
= isl_pw_aff_non_zero_set(pa
);
2286 cond
= embed(cond
, isl_id_copy(id
));
2287 valid_cond
= isl_set_coalesce(valid_cond
);
2288 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
2289 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
2290 is_one
= isl_int_is_one(inc
) || isl_int_is_negone(inc
);
2291 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2293 init_val
= extract_affine(rhs
);
2294 valid_cond_init
= enforce_subset(
2295 isl_set_from_pw_aff(isl_pw_aff_copy(init_val
)),
2296 isl_set_copy(valid_cond
));
2297 if (is_one
&& !is_virtual
) {
2298 isl_pw_aff_free(init_val
);
2299 pa
= extract_comparison(isl_int_is_pos(inc
) ? BO_GE
: BO_LE
,
2301 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2302 valid_init
= set_project_out_by_id(valid_init
, id
);
2303 domain
= isl_pw_aff_non_zero_set(pa
);
2305 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
2306 domain
= strided_domain(isl_id_copy(id
), init_val
, inc
);
2309 domain
= embed(domain
, isl_id_copy(id
));
2312 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2313 rev_wrap
= isl_map_reverse(isl_map_copy(wrap
));
2314 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
2315 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
2316 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
2318 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2319 is_simple
= is_simple_bound(cond
, inc
);
2321 cond
= valid_for_each_iteration(cond
,
2322 isl_set_copy(domain
), inc
);
2323 domain
= isl_set_intersect(domain
, cond
);
2324 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2325 dim
= isl_space_from_domain(isl_set_get_space(domain
));
2326 dim
= isl_space_add_dims(dim
, isl_dim_out
, 1);
2327 sched
= isl_map_universe(dim
);
2328 if (isl_int_is_pos(inc
))
2329 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2331 sched
= isl_map_oppose(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2333 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
), inc
);
2334 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
2336 if (is_virtual
&& !is_simple
) {
2337 wrap
= isl_map_set_dim_id(wrap
,
2338 isl_dim_out
, 0, isl_id_copy(id
));
2339 sched
= isl_map_intersect_domain(sched
, isl_set_copy(domain
));
2340 domain
= isl_set_apply(domain
, isl_map_copy(wrap
));
2341 sched
= isl_map_apply_domain(sched
, wrap
);
2345 scop
= pet_scop_embed(scop
, domain
, sched
, id
);
2346 scop
= resolve_nested(scop
);
2347 clear_assignment(assigned_value
, iv
);
2351 scop
= pet_scop_restrict_context(scop
, valid_init
);
2352 scop
= pet_scop_restrict_context(scop
, valid_inc
);
2353 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
2354 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
2359 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
)
2361 return extract(stmt
->children());
2364 /* Does "id" refer to a nested access?
2366 static bool is_nested_parameter(__isl_keep isl_id
*id
)
2368 return id
&& isl_id_get_user(id
) && !isl_id_get_name(id
);
2371 /* Does parameter "pos" of "space" refer to a nested access?
2373 static bool is_nested_parameter(__isl_keep isl_space
*space
, int pos
)
2378 id
= isl_space_get_dim_id(space
, isl_dim_param
, pos
);
2379 nested
= is_nested_parameter(id
);
2385 /* Does parameter "pos" of "map" refer to a nested access?
2387 static bool is_nested_parameter(__isl_keep isl_map
*map
, int pos
)
2392 id
= isl_map_get_dim_id(map
, isl_dim_param
, pos
);
2393 nested
= is_nested_parameter(id
);
2399 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2401 static int n_nested_parameter(__isl_keep isl_space
*space
)
2406 nparam
= isl_space_dim(space
, isl_dim_param
);
2407 for (int i
= 0; i
< nparam
; ++i
)
2408 if (is_nested_parameter(space
, i
))
2414 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2416 static int n_nested_parameter(__isl_keep isl_map
*map
)
2421 space
= isl_map_get_space(map
);
2422 n
= n_nested_parameter(space
);
2423 isl_space_free(space
);
2428 /* For each nested access parameter in "space",
2429 * construct a corresponding pet_expr, place it in args and
2430 * record its position in "param2pos".
2431 * "n_arg" is the number of elements that are already in args.
2432 * The position recorded in "param2pos" takes this number into account.
2433 * If the pet_expr corresponding to a parameter is identical to
2434 * the pet_expr corresponding to an earlier parameter, then these two
2435 * parameters are made to refer to the same element in args.
2437 * Return the final number of elements in args or -1 if an error has occurred.
2439 int PetScan::extract_nested(__isl_keep isl_space
*space
,
2440 int n_arg
, struct pet_expr
**args
, std::map
<int,int> ¶m2pos
)
2444 nparam
= isl_space_dim(space
, isl_dim_param
);
2445 for (int i
= 0; i
< nparam
; ++i
) {
2447 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2450 if (!is_nested_parameter(id
)) {
2455 nested
= (Expr
*) isl_id_get_user(id
);
2456 args
[n_arg
] = extract_expr(nested
);
2460 for (j
= 0; j
< n_arg
; ++j
)
2461 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
2465 pet_expr_free(args
[n_arg
]);
2469 param2pos
[i
] = n_arg
++;
2477 /* For each nested access parameter in the access relations in "expr",
2478 * construct a corresponding pet_expr, place it in expr->args and
2479 * record its position in "param2pos".
2480 * n is the number of nested access parameters.
2482 struct pet_expr
*PetScan::extract_nested(struct pet_expr
*expr
, int n
,
2483 std::map
<int,int> ¶m2pos
)
2487 expr
->args
= isl_calloc_array(ctx
, struct pet_expr
*, n
);
2492 space
= isl_map_get_space(expr
->acc
.access
);
2493 n
= extract_nested(space
, 0, expr
->args
, param2pos
);
2494 isl_space_free(space
);
2502 pet_expr_free(expr
);
2506 /* Look for parameters in any access relation in "expr" that
2507 * refer to nested accesses. In particular, these are
2508 * parameters with no name.
2510 * If there are any such parameters, then the domain of the access
2511 * relation, which is still [] at this point, is replaced by
2512 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2513 * (after identifying identical nested accesses).
2514 * The parameters are then equated to the corresponding t dimensions
2515 * and subsequently projected out.
2516 * param2pos maps the position of the parameter to the position
2517 * of the corresponding t dimension.
2519 struct pet_expr
*PetScan::resolve_nested(struct pet_expr
*expr
)
2526 std::map
<int,int> param2pos
;
2531 for (int i
= 0; i
< expr
->n_arg
; ++i
) {
2532 expr
->args
[i
] = resolve_nested(expr
->args
[i
]);
2533 if (!expr
->args
[i
]) {
2534 pet_expr_free(expr
);
2539 if (expr
->type
!= pet_expr_access
)
2542 n
= n_nested_parameter(expr
->acc
.access
);
2546 expr
= extract_nested(expr
, n
, param2pos
);
2551 nparam
= isl_map_dim(expr
->acc
.access
, isl_dim_param
);
2552 n_in
= isl_map_dim(expr
->acc
.access
, isl_dim_in
);
2553 dim
= isl_map_get_space(expr
->acc
.access
);
2554 dim
= isl_space_domain(dim
);
2555 dim
= isl_space_from_domain(dim
);
2556 dim
= isl_space_add_dims(dim
, isl_dim_out
, n
);
2557 map
= isl_map_universe(dim
);
2558 map
= isl_map_domain_map(map
);
2559 map
= isl_map_reverse(map
);
2560 expr
->acc
.access
= isl_map_apply_domain(expr
->acc
.access
, map
);
2562 for (int i
= nparam
- 1; i
>= 0; --i
) {
2563 isl_id
*id
= isl_map_get_dim_id(expr
->acc
.access
,
2565 if (!is_nested_parameter(id
)) {
2570 expr
->acc
.access
= isl_map_equate(expr
->acc
.access
,
2571 isl_dim_param
, i
, isl_dim_in
,
2572 n_in
+ param2pos
[i
]);
2573 expr
->acc
.access
= isl_map_project_out(expr
->acc
.access
,
2574 isl_dim_param
, i
, 1);
2581 pet_expr_free(expr
);
2585 /* Convert a top-level pet_expr to a pet_scop with one statement.
2586 * This mainly involves resolving nested expression parameters
2587 * and setting the name of the iteration space.
2588 * The name is given by "label" if it is non-NULL. Otherwise,
2589 * it is of the form S_<n_stmt>.
2591 struct pet_scop
*PetScan::extract(Stmt
*stmt
, struct pet_expr
*expr
,
2592 __isl_take isl_id
*label
)
2594 struct pet_stmt
*ps
;
2595 SourceLocation loc
= stmt
->getLocStart();
2596 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
2598 expr
= resolve_nested(expr
);
2599 ps
= pet_stmt_from_pet_expr(ctx
, line
, label
, n_stmt
++, expr
);
2600 return pet_scop_from_pet_stmt(ctx
, ps
);
2603 /* Check if we can extract an affine expression from "expr".
2604 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2605 * We turn on autodetection so that we won't generate any warnings
2606 * and turn off nesting, so that we won't accept any non-affine constructs.
2608 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
2611 int save_autodetect
= options
->autodetect
;
2612 bool save_nesting
= nesting_enabled
;
2614 options
->autodetect
= 1;
2615 nesting_enabled
= false;
2617 pwaff
= extract_affine(expr
);
2619 options
->autodetect
= save_autodetect
;
2620 nesting_enabled
= save_nesting
;
2625 /* Check whether "expr" is an affine expression.
2627 bool PetScan::is_affine(Expr
*expr
)
2631 pwaff
= try_extract_affine(expr
);
2632 isl_pw_aff_free(pwaff
);
2634 return pwaff
!= NULL
;
2637 /* Check whether "expr" is an affine constraint.
2638 * We turn on autodetection so that we won't generate any warnings
2639 * and turn off nesting, so that we won't accept any non-affine constructs.
2641 bool PetScan::is_affine_condition(Expr
*expr
)
2644 int save_autodetect
= options
->autodetect
;
2645 bool save_nesting
= nesting_enabled
;
2647 options
->autodetect
= 1;
2648 nesting_enabled
= false;
2650 cond
= extract_condition(expr
);
2651 isl_pw_aff_free(cond
);
2653 options
->autodetect
= save_autodetect
;
2654 nesting_enabled
= save_nesting
;
2656 return cond
!= NULL
;
2659 /* Check if we can extract a condition from "expr".
2660 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
2661 * If allow_nested is set, then the condition may involve parameters
2662 * corresponding to nested accesses.
2663 * We turn on autodetection so that we won't generate any warnings.
2665 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
2668 int save_autodetect
= options
->autodetect
;
2669 bool save_nesting
= nesting_enabled
;
2671 options
->autodetect
= 1;
2672 nesting_enabled
= allow_nested
;
2673 cond
= extract_condition(expr
);
2675 options
->autodetect
= save_autodetect
;
2676 nesting_enabled
= save_nesting
;
2681 /* If the top-level expression of "stmt" is an assignment, then
2682 * return that assignment as a BinaryOperator.
2683 * Otherwise return NULL.
2685 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
2687 BinaryOperator
*ass
;
2691 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
2694 ass
= cast
<BinaryOperator
>(stmt
);
2695 if(ass
->getOpcode() != BO_Assign
)
2701 /* Check if the given if statement is a conditional assignement
2702 * with a non-affine condition. If so, construct a pet_scop
2703 * corresponding to this conditional assignment. Otherwise return NULL.
2705 * In particular we check if "stmt" is of the form
2712 * where a is some array or scalar access.
2713 * The constructed pet_scop then corresponds to the expression
2715 * a = condition ? f(...) : g(...)
2717 * All access relations in f(...) are intersected with condition
2718 * while all access relation in g(...) are intersected with the complement.
2720 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
2722 BinaryOperator
*ass_then
, *ass_else
;
2723 isl_map
*write_then
, *write_else
;
2724 isl_set
*cond
, *comp
;
2728 struct pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
2729 bool save_nesting
= nesting_enabled
;
2731 if (!options
->detect_conditional_assignment
)
2734 ass_then
= top_assignment_or_null(stmt
->getThen());
2735 ass_else
= top_assignment_or_null(stmt
->getElse());
2737 if (!ass_then
|| !ass_else
)
2740 if (is_affine_condition(stmt
->getCond()))
2743 write_then
= extract_access(ass_then
->getLHS());
2744 write_else
= extract_access(ass_else
->getLHS());
2746 equal
= isl_map_is_equal(write_then
, write_else
);
2747 isl_map_free(write_else
);
2748 if (equal
< 0 || !equal
) {
2749 isl_map_free(write_then
);
2753 nesting_enabled
= allow_nested
;
2754 pa
= extract_condition(stmt
->getCond());
2755 nesting_enabled
= save_nesting
;
2756 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
2757 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
2758 map
= isl_map_from_range(isl_set_from_pw_aff(pa
));
2760 pe_cond
= pet_expr_from_access(map
);
2762 pe_then
= extract_expr(ass_then
->getRHS());
2763 pe_then
= pet_expr_restrict(pe_then
, cond
);
2764 pe_else
= extract_expr(ass_else
->getRHS());
2765 pe_else
= pet_expr_restrict(pe_else
, comp
);
2767 pe
= pet_expr_new_ternary(ctx
, pe_cond
, pe_then
, pe_else
);
2768 pe_write
= pet_expr_from_access(write_then
);
2770 pe_write
->acc
.write
= 1;
2771 pe_write
->acc
.read
= 0;
2773 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, pe_write
, pe
);
2774 return extract(stmt
, pe
);
2777 /* Create an access to a virtual array representing the result
2779 * Unlike other accessed data, the id of the array is NULL as
2780 * there is no ValueDecl in the program corresponding to the virtual
2782 * The array starts out as a scalar, but grows along with the
2783 * statement writing to the array in pet_scop_embed.
2785 static __isl_give isl_map
*create_test_access(isl_ctx
*ctx
, int test_nr
)
2787 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, 0);
2791 snprintf(name
, sizeof(name
), "__pet_test_%d", test_nr
);
2792 id
= isl_id_alloc(ctx
, name
, NULL
);
2793 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
2794 return isl_map_universe(dim
);
2797 /* Create a pet_scop with a single statement evaluating "cond"
2798 * and writing the result to a virtual scalar, as expressed by
2801 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
,
2802 __isl_take isl_map
*access
)
2804 struct pet_expr
*expr
, *write
;
2805 struct pet_stmt
*ps
;
2806 SourceLocation loc
= cond
->getLocStart();
2807 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
2809 write
= pet_expr_from_access(access
);
2811 write
->acc
.write
= 1;
2812 write
->acc
.read
= 0;
2814 expr
= extract_expr(cond
);
2815 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, write
, expr
);
2816 ps
= pet_stmt_from_pet_expr(ctx
, line
, NULL
, n_stmt
++, expr
);
2817 return pet_scop_from_pet_stmt(ctx
, ps
);
2820 /* Add an array with the given extent ("access") to the list
2821 * of arrays in "scop" and return the extended pet_scop.
2822 * The array is marked as attaining values 0 and 1 only.
2824 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2825 __isl_keep isl_map
*access
, clang::ASTContext
&ast_ctx
)
2827 isl_ctx
*ctx
= isl_map_get_ctx(access
);
2829 struct pet_array
**arrays
;
2830 struct pet_array
*array
;
2837 arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
2841 scop
->arrays
= arrays
;
2843 array
= isl_calloc_type(ctx
, struct pet_array
);
2847 array
->extent
= isl_map_range(isl_map_copy(access
));
2848 dim
= isl_space_params_alloc(ctx
, 0);
2849 array
->context
= isl_set_universe(dim
);
2850 dim
= isl_space_set_alloc(ctx
, 0, 1);
2851 array
->value_bounds
= isl_set_universe(dim
);
2852 array
->value_bounds
= isl_set_lower_bound_si(array
->value_bounds
,
2854 array
->value_bounds
= isl_set_upper_bound_si(array
->value_bounds
,
2856 array
->element_type
= strdup("int");
2857 array
->element_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
2859 scop
->arrays
[scop
->n_array
] = array
;
2862 if (!array
->extent
|| !array
->context
)
2867 pet_scop_free(scop
);
2872 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
,
2876 /* Apply the map pointed to by "user" to the domain of the access
2877 * relation, thereby embedding it in the range of the map.
2878 * The domain of both relations is the zero-dimensional domain.
2880 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
, void *user
)
2882 isl_map
*map
= (isl_map
*) user
;
2884 return isl_map_apply_domain(access
, isl_map_copy(map
));
2887 /* Apply "map" to all access relations in "expr".
2889 static struct pet_expr
*embed(struct pet_expr
*expr
, __isl_keep isl_map
*map
)
2891 return pet_expr_foreach_access(expr
, &embed_access
, map
);
2894 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2896 static int n_nested_parameter(__isl_keep isl_set
*set
)
2901 space
= isl_set_get_space(set
);
2902 n
= n_nested_parameter(space
);
2903 isl_space_free(space
);
2908 /* Remove all parameters from "map" that refer to nested accesses.
2910 static __isl_give isl_map
*remove_nested_parameters(__isl_take isl_map
*map
)
2915 space
= isl_map_get_space(map
);
2916 nparam
= isl_space_dim(space
, isl_dim_param
);
2917 for (int i
= nparam
- 1; i
>= 0; --i
)
2918 if (is_nested_parameter(space
, i
))
2919 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
2920 isl_space_free(space
);
2926 static __isl_give isl_map
*access_remove_nested_parameters(
2927 __isl_take isl_map
*access
, void *user
);
2930 static __isl_give isl_map
*access_remove_nested_parameters(
2931 __isl_take isl_map
*access
, void *user
)
2933 return remove_nested_parameters(access
);
2936 /* Remove all nested access parameters from the schedule and all
2937 * accesses of "stmt".
2938 * There is no need to remove them from the domain as these parameters
2939 * have already been removed from the domain when this function is called.
2941 static struct pet_stmt
*remove_nested_parameters(struct pet_stmt
*stmt
)
2945 stmt
->schedule
= remove_nested_parameters(stmt
->schedule
);
2946 stmt
->body
= pet_expr_foreach_access(stmt
->body
,
2947 &access_remove_nested_parameters
, NULL
);
2948 if (!stmt
->schedule
|| !stmt
->body
)
2950 for (int i
= 0; i
< stmt
->n_arg
; ++i
) {
2951 stmt
->args
[i
] = pet_expr_foreach_access(stmt
->args
[i
],
2952 &access_remove_nested_parameters
, NULL
);
2959 pet_stmt_free(stmt
);
2963 /* For each nested access parameter in the domain of "stmt",
2964 * construct a corresponding pet_expr, place it in stmt->args and
2965 * record its position in "param2pos".
2966 * n is the number of nested access parameters.
2968 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
2969 std::map
<int,int> ¶m2pos
)
2973 struct pet_expr
**args
;
2975 n_arg
= stmt
->n_arg
;
2976 args
= isl_realloc_array(ctx
, stmt
->args
, struct pet_expr
*, n_arg
+ n
);
2982 space
= isl_set_get_space(stmt
->domain
);
2983 n
= extract_nested(space
, n_arg
, stmt
->args
, param2pos
);
2984 isl_space_free(space
);
2992 pet_stmt_free(stmt
);
2996 /* Look for parameters in the iteration domain of "stmt" that
2997 * refer to nested accesses. In particular, these are
2998 * parameters with no name.
3000 * If there are any such parameters, then as many extra variables
3001 * (after identifying identical nested accesses) are added to the
3002 * range of the map wrapped inside the domain.
3003 * If the original domain is not a wrapped map, then a new wrapped
3004 * map is created with zero output dimensions.
3005 * The parameters are then equated to the corresponding output dimensions
3006 * and subsequently projected out, from the iteration domain,
3007 * the schedule and the access relations.
3008 * For each of the output dimensions, a corresponding argument
3009 * expression is added. Initially they are created with
3010 * a zero-dimensional domain, so they have to be embedded
3011 * in the current iteration domain.
3012 * param2pos maps the position of the parameter to the position
3013 * of the corresponding output dimension in the wrapped map.
3015 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3021 std::map
<int,int> param2pos
;
3026 n
= n_nested_parameter(stmt
->domain
);
3030 n_arg
= stmt
->n_arg
;
3031 stmt
= extract_nested(stmt
, n
, param2pos
);
3035 n
= stmt
->n_arg
- n_arg
;
3036 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3037 if (isl_set_is_wrapping(stmt
->domain
))
3038 map
= isl_set_unwrap(stmt
->domain
);
3040 map
= isl_map_from_domain(stmt
->domain
);
3041 map
= isl_map_add_dims(map
, isl_dim_out
, n
);
3043 for (int i
= nparam
- 1; i
>= 0; --i
) {
3046 if (!is_nested_parameter(map
, i
))
3049 id
= isl_map_get_tuple_id(stmt
->args
[param2pos
[i
]]->acc
.access
,
3051 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3052 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3054 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3057 stmt
->domain
= isl_map_wrap(map
);
3059 map
= isl_set_unwrap(isl_set_copy(stmt
->domain
));
3060 map
= isl_map_from_range(isl_map_domain(map
));
3061 for (int pos
= n_arg
; pos
< stmt
->n_arg
; ++pos
)
3062 stmt
->args
[pos
] = embed(stmt
->args
[pos
], map
);
3065 stmt
= remove_nested_parameters(stmt
);
3069 pet_stmt_free(stmt
);
3073 /* For each statement in "scop", move the parameters that correspond
3074 * to nested access into the ranges of the domains and create
3075 * corresponding argument expressions.
3077 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3082 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3083 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3084 if (!scop
->stmts
[i
])
3090 pet_scop_free(scop
);
3094 /* Does "space" involve any parameters that refer to nested
3095 * accesses, i.e., parameters with no name?
3097 static bool has_nested(__isl_keep isl_space
*space
)
3101 nparam
= isl_space_dim(space
, isl_dim_param
);
3102 for (int i
= 0; i
< nparam
; ++i
)
3103 if (is_nested_parameter(space
, i
))
3109 /* Does "pa" involve any parameters that refer to nested
3110 * accesses, i.e., parameters with no name?
3112 static bool has_nested(__isl_keep isl_pw_aff
*pa
)
3117 space
= isl_pw_aff_get_space(pa
);
3118 nested
= has_nested(space
);
3119 isl_space_free(space
);
3124 /* Given an access expression "expr", is the variable accessed by
3125 * "expr" assigned anywhere inside "scop"?
3127 static bool is_assigned(pet_expr
*expr
, pet_scop
*scop
)
3129 bool assigned
= false;
3132 id
= isl_map_get_tuple_id(expr
->acc
.access
, isl_dim_out
);
3133 assigned
= pet_scop_writes(scop
, id
);
3139 /* Are all nested access parameters in "pa" allowed given "scop".
3140 * In particular, is none of them written by anywhere inside "scop".
3142 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3146 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3147 for (int i
= 0; i
< nparam
; ++i
) {
3149 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3153 if (!is_nested_parameter(id
)) {
3158 nested
= (Expr
*) isl_id_get_user(id
);
3159 expr
= extract_expr(nested
);
3160 allowed
= expr
&& expr
->type
== pet_expr_access
&&
3161 !is_assigned(expr
, scop
);
3163 pet_expr_free(expr
);
3173 /* Construct a pet_scop for an if statement.
3175 * If the condition fits the pattern of a conditional assignment,
3176 * then it is handled by extract_conditional_assignment.
3177 * Otherwise, we do the following.
3179 * If the condition is affine, then the condition is added
3180 * to the iteration domains of the then branch, while the
3181 * opposite of the condition in added to the iteration domains
3182 * of the else branch, if any.
3183 * We allow the condition to be dynamic, i.e., to refer to
3184 * scalars or array elements that may be written to outside
3185 * of the given if statement. These nested accesses are then represented
3186 * as output dimensions in the wrapping iteration domain.
3187 * If it also written _inside_ the then or else branch, then
3188 * we treat the condition as non-affine.
3189 * As explained below, this will introduce an extra statement.
3190 * For aesthetic reasons, we want this statement to have a statement
3191 * number that is lower than those of the then and else branches.
3192 * In order to evaluate if will need such a statement, however, we
3193 * first construct scops for the then and else branches.
3194 * We therefore reserve a statement number if we might have to
3195 * introduce such an extra statement.
3197 * If the condition is not affine, then we create a separate
3198 * statement that writes the result of the condition to a virtual scalar.
3199 * A constraint requiring the value of this virtual scalar to be one
3200 * is added to the iteration domains of the then branch.
3201 * Similarly, a constraint requiring the value of this virtual scalar
3202 * to be zero is added to the iteration domains of the else branch, if any.
3203 * We adjust the schedules to ensure that the virtual scalar is written
3204 * before it is read.
3206 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
3208 struct pet_scop
*scop_then
, *scop_else
, *scop
;
3209 assigned_value_cache
cache(assigned_value
);
3210 isl_map
*test_access
= NULL
;
3214 scop
= extract_conditional_assignment(stmt
);
3218 cond
= try_extract_nested_condition(stmt
->getCond());
3219 if (allow_nested
&& (!cond
|| has_nested(cond
)))
3222 scop_then
= extract(stmt
->getThen());
3224 if (stmt
->getElse()) {
3225 scop_else
= extract(stmt
->getElse());
3226 if (options
->autodetect
) {
3227 if (scop_then
&& !scop_else
) {
3229 isl_pw_aff_free(cond
);
3232 if (!scop_then
&& scop_else
) {
3234 isl_pw_aff_free(cond
);
3241 (!is_nested_allowed(cond
, scop_then
) ||
3242 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
3243 isl_pw_aff_free(cond
);
3246 if (allow_nested
&& !cond
) {
3247 int save_n_stmt
= n_stmt
;
3248 test_access
= create_test_access(ctx
, n_test
++);
3250 scop
= extract_non_affine_condition(stmt
->getCond(),
3251 isl_map_copy(test_access
));
3252 n_stmt
= save_n_stmt
;
3253 scop
= scop_add_array(scop
, test_access
, ast_context
);
3255 pet_scop_free(scop_then
);
3256 pet_scop_free(scop_else
);
3257 isl_map_free(test_access
);
3267 cond
= extract_condition(stmt
->getCond());
3268 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
3269 set
= isl_pw_aff_non_zero_set(cond
);
3270 scop
= pet_scop_restrict(scop_then
, isl_set_copy(set
));
3272 if (stmt
->getElse()) {
3273 set
= isl_set_subtract(isl_set_copy(valid
), set
);
3274 scop_else
= pet_scop_restrict(scop_else
, set
);
3275 scop
= pet_scop_add(ctx
, scop
, scop_else
);
3278 scop
= resolve_nested(scop
);
3279 scop
= pet_scop_restrict_context(scop
, valid
);
3281 scop
= pet_scop_prefix(scop
, 0);
3282 scop_then
= pet_scop_prefix(scop_then
, 1);
3283 scop_then
= pet_scop_filter(scop_then
,
3284 isl_map_copy(test_access
), 1);
3285 scop
= pet_scop_add(ctx
, scop
, scop_then
);
3286 if (stmt
->getElse()) {
3287 scop_else
= pet_scop_prefix(scop_else
, 1);
3288 scop_else
= pet_scop_filter(scop_else
, test_access
, 0);
3289 scop
= pet_scop_add(ctx
, scop
, scop_else
);
3291 isl_map_free(test_access
);
3297 /* Try and construct a pet_scop for a label statement.
3298 * We currently only allow labels on expression statements.
3300 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
3305 sub
= stmt
->getSubStmt();
3306 if (!isa
<Expr
>(sub
)) {
3311 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
3313 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
3316 /* Try and construct a pet_scop corresponding to "stmt".
3318 struct pet_scop
*PetScan::extract(Stmt
*stmt
)
3320 if (isa
<Expr
>(stmt
))
3321 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
3323 switch (stmt
->getStmtClass()) {
3324 case Stmt::WhileStmtClass
:
3325 return extract(cast
<WhileStmt
>(stmt
));
3326 case Stmt::ForStmtClass
:
3327 return extract_for(cast
<ForStmt
>(stmt
));
3328 case Stmt::IfStmtClass
:
3329 return extract(cast
<IfStmt
>(stmt
));
3330 case Stmt::CompoundStmtClass
:
3331 return extract(cast
<CompoundStmt
>(stmt
));
3332 case Stmt::LabelStmtClass
:
3333 return extract(cast
<LabelStmt
>(stmt
));
3341 /* Try and construct a pet_scop corresponding to (part of)
3342 * a sequence of statements.
3344 struct pet_scop
*PetScan::extract(StmtRange stmt_range
)
3349 bool partial_range
= false;
3351 scop
= pet_scop_empty(ctx
);
3352 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
3354 struct pet_scop
*scop_i
;
3355 scop_i
= extract(child
);
3356 if (scop
&& partial
) {
3357 pet_scop_free(scop_i
);
3360 scop_i
= pet_scop_prefix(scop_i
, j
);
3361 if (options
->autodetect
) {
3363 scop
= pet_scop_add(ctx
, scop
, scop_i
);
3365 partial_range
= true;
3366 if (scop
->n_stmt
!= 0 && !scop_i
)
3369 scop
= pet_scop_add(ctx
, scop
, scop_i
);
3375 if (scop
&& partial_range
)
3381 /* Check if the scop marked by the user is exactly this Stmt
3382 * or part of this Stmt.
3383 * If so, return a pet_scop corresponding to the marked region.
3384 * Otherwise, return NULL.
3386 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
3388 SourceManager
&SM
= PP
.getSourceManager();
3389 unsigned start_off
, end_off
;
3391 start_off
= SM
.getFileOffset(stmt
->getLocStart());
3392 end_off
= SM
.getFileOffset(stmt
->getLocEnd());
3394 if (start_off
> loc
.end
)
3396 if (end_off
< loc
.start
)
3398 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
3399 return extract(stmt
);
3403 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
3404 Stmt
*child
= *start
;
3407 start_off
= SM
.getFileOffset(child
->getLocStart());
3408 end_off
= SM
.getFileOffset(child
->getLocEnd());
3409 if (start_off
< loc
.start
&& end_off
> loc
.end
)
3411 if (start_off
>= loc
.start
)
3416 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
3418 start_off
= SM
.getFileOffset(child
->getLocStart());
3419 if (start_off
>= loc
.end
)
3423 return extract(StmtRange(start
, end
));
3426 /* Set the size of index "pos" of "array" to "size".
3427 * In particular, add a constraint of the form
3431 * to array->extent and a constraint of the form
3435 * to array->context.
3437 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
3438 __isl_take isl_pw_aff
*size
)
3448 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
3449 array
->context
= isl_set_intersect(array
->context
, valid
);
3451 dim
= isl_set_get_space(array
->extent
);
3452 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
3453 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
3454 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
3455 index
= isl_pw_aff_alloc(univ
, aff
);
3457 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
3458 isl_set_dim(array
->extent
, isl_dim_set
));
3459 id
= isl_set_get_tuple_id(array
->extent
);
3460 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
3461 bound
= isl_pw_aff_lt_set(index
, size
);
3463 array
->extent
= isl_set_intersect(array
->extent
, bound
);
3465 if (!array
->context
|| !array
->extent
)
3470 pet_array_free(array
);
3474 /* Figure out the size of the array at position "pos" and all
3475 * subsequent positions from "type" and update "array" accordingly.
3477 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
3478 const Type
*type
, int pos
)
3480 const ArrayType
*atype
;
3486 if (type
->isPointerType()) {
3487 type
= type
->getPointeeType().getTypePtr();
3488 return set_upper_bounds(array
, type
, pos
+ 1);
3490 if (!type
->isArrayType())
3493 type
= type
->getCanonicalTypeInternal().getTypePtr();
3494 atype
= cast
<ArrayType
>(type
);
3496 if (type
->isConstantArrayType()) {
3497 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
3498 size
= extract_affine(ca
->getSize());
3499 array
= update_size(array
, pos
, size
);
3500 } else if (type
->isVariableArrayType()) {
3501 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
3502 size
= extract_affine(vla
->getSizeExpr());
3503 array
= update_size(array
, pos
, size
);
3506 type
= atype
->getElementType().getTypePtr();
3508 return set_upper_bounds(array
, type
, pos
+ 1);
3511 /* Construct and return a pet_array corresponding to the variable "decl".
3512 * In particular, initialize array->extent to
3514 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3516 * and then call set_upper_bounds to set the upper bounds on the indices
3517 * based on the type of the variable.
3519 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
)
3521 struct pet_array
*array
;
3522 QualType qt
= decl
->getType();
3523 const Type
*type
= qt
.getTypePtr();
3524 int depth
= array_depth(type
);
3525 QualType base
= base_type(qt
);
3530 array
= isl_calloc_type(ctx
, struct pet_array
);
3534 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
3535 dim
= isl_space_set_alloc(ctx
, 0, depth
);
3536 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
3538 array
->extent
= isl_set_nat_universe(dim
);
3540 dim
= isl_space_params_alloc(ctx
, 0);
3541 array
->context
= isl_set_universe(dim
);
3543 array
= set_upper_bounds(array
, type
, 0);
3547 name
= base
.getAsString();
3548 array
->element_type
= strdup(name
.c_str());
3549 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
3554 /* Construct a list of pet_arrays, one for each array (or scalar)
3555 * accessed inside "scop" add this list to "scop" and return the result.
3557 * The context of "scop" is updated with the intesection of
3558 * the contexts of all arrays, i.e., constraints on the parameters
3559 * that ensure that the arrays have a valid (non-negative) size.
3561 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
3564 set
<ValueDecl
*> arrays
;
3565 set
<ValueDecl
*>::iterator it
;
3567 struct pet_array
**scop_arrays
;
3572 pet_scop_collect_arrays(scop
, arrays
);
3573 if (arrays
.size() == 0)
3576 n_array
= scop
->n_array
;
3578 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
3579 n_array
+ arrays
.size());
3582 scop
->arrays
= scop_arrays
;
3584 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
3585 struct pet_array
*array
;
3586 scop
->arrays
[n_array
+ i
] = array
= extract_array(ctx
, *it
);
3587 if (!scop
->arrays
[n_array
+ i
])
3590 scop
->context
= isl_set_intersect(scop
->context
,
3591 isl_set_copy(array
->context
));
3598 pet_scop_free(scop
);
3602 /* Bound all parameters in scop->context to the possible values
3603 * of the corresponding C variable.
3605 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
3612 n
= isl_set_dim(scop
->context
, isl_dim_param
);
3613 for (int i
= 0; i
< n
; ++i
) {
3617 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
3618 decl
= (ValueDecl
*) isl_id_get_user(id
);
3621 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
3629 pet_scop_free(scop
);
3633 /* Construct a pet_scop from the given function.
3635 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
3640 stmt
= fd
->getBody();
3642 if (options
->autodetect
)
3643 scop
= extract(stmt
);
3646 scop
= pet_scop_detect_parameter_accesses(scop
);
3647 scop
= scan_arrays(scop
);
3648 scop
= add_parameter_bounds(scop
);
3649 scop
= pet_scop_gist(scop
, value_bounds
);