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
);
752 /* This method is called when we come across an access that is
753 * nested in what is supposed to be an affine expression.
754 * If nesting is allowed, we return a new parameter that corresponds
755 * to this nested access. Otherwise, we simply complain.
757 * Note that we currently don't allow nested accesses themselves
758 * to contain any nested accesses, so we check if we can extract
759 * the access without any nesting and complain if we can't.
761 * The new parameter is resolved in resolve_nested.
763 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
771 if (!nesting_enabled
) {
776 allow_nested
= false;
777 access
= extract_access(expr
);
783 isl_map_free(access
);
785 id
= isl_id_alloc(ctx
, NULL
, expr
);
786 dim
= isl_space_params_alloc(ctx
, 1);
788 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
790 dom
= isl_set_universe(isl_space_copy(dim
));
791 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
792 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
794 return isl_pw_aff_alloc(dom
, aff
);
797 /* Affine expressions are not supposed to contain array accesses,
798 * but if nesting is allowed, we return a parameter corresponding
799 * to the array access.
801 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
803 return nested_access(expr
);
806 /* Extract an affine expression from a conditional operation.
808 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
810 isl_pw_aff
*cond
, *lhs
, *rhs
, *res
;
812 cond
= extract_condition(expr
->getCond());
813 lhs
= extract_affine(expr
->getTrueExpr());
814 rhs
= extract_affine(expr
->getFalseExpr());
816 return isl_pw_aff_cond(cond
, lhs
, rhs
);
819 /* Extract an affine expression, if possible, from "expr".
820 * Otherwise return NULL.
822 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
824 switch (expr
->getStmtClass()) {
825 case Stmt::ImplicitCastExprClass
:
826 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
827 case Stmt::IntegerLiteralClass
:
828 return extract_affine(cast
<IntegerLiteral
>(expr
));
829 case Stmt::DeclRefExprClass
:
830 return extract_affine(cast
<DeclRefExpr
>(expr
));
831 case Stmt::BinaryOperatorClass
:
832 return extract_affine(cast
<BinaryOperator
>(expr
));
833 case Stmt::UnaryOperatorClass
:
834 return extract_affine(cast
<UnaryOperator
>(expr
));
835 case Stmt::ParenExprClass
:
836 return extract_affine(cast
<ParenExpr
>(expr
));
837 case Stmt::CallExprClass
:
838 return extract_affine(cast
<CallExpr
>(expr
));
839 case Stmt::ArraySubscriptExprClass
:
840 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
841 case Stmt::ConditionalOperatorClass
:
842 return extract_affine(cast
<ConditionalOperator
>(expr
));
849 __isl_give isl_map
*PetScan::extract_access(ImplicitCastExpr
*expr
)
851 return extract_access(expr
->getSubExpr());
854 /* Return the depth of an array of the given type.
856 static int array_depth(const Type
*type
)
858 if (type
->isPointerType())
859 return 1 + array_depth(type
->getPointeeType().getTypePtr());
860 if (type
->isArrayType()) {
861 const ArrayType
*atype
;
862 type
= type
->getCanonicalTypeInternal().getTypePtr();
863 atype
= cast
<ArrayType
>(type
);
864 return 1 + array_depth(atype
->getElementType().getTypePtr());
869 /* Return the element type of the given array type.
871 static QualType
base_type(QualType qt
)
873 const Type
*type
= qt
.getTypePtr();
875 if (type
->isPointerType())
876 return base_type(type
->getPointeeType());
877 if (type
->isArrayType()) {
878 const ArrayType
*atype
;
879 type
= type
->getCanonicalTypeInternal().getTypePtr();
880 atype
= cast
<ArrayType
>(type
);
881 return base_type(atype
->getElementType());
886 /* Extract an access relation from a reference to a variable.
887 * If the variable has name "A" and its type corresponds to an
888 * array of depth d, then the returned access relation is of the
891 * { [] -> A[i_1,...,i_d] }
893 __isl_give isl_map
*PetScan::extract_access(DeclRefExpr
*expr
)
895 ValueDecl
*decl
= expr
->getDecl();
896 int depth
= array_depth(decl
->getType().getTypePtr());
897 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
898 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, depth
);
901 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
903 access_rel
= isl_map_universe(dim
);
908 /* Extract an access relation from an integer contant.
909 * If the value of the constant is "v", then the returned access relation
914 __isl_give isl_map
*PetScan::extract_access(IntegerLiteral
*expr
)
916 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr
)));
919 /* Try and extract an access relation from the given Expr.
920 * Return NULL if it doesn't work out.
922 __isl_give isl_map
*PetScan::extract_access(Expr
*expr
)
924 switch (expr
->getStmtClass()) {
925 case Stmt::ImplicitCastExprClass
:
926 return extract_access(cast
<ImplicitCastExpr
>(expr
));
927 case Stmt::DeclRefExprClass
:
928 return extract_access(cast
<DeclRefExpr
>(expr
));
929 case Stmt::ArraySubscriptExprClass
:
930 return extract_access(cast
<ArraySubscriptExpr
>(expr
));
931 case Stmt::IntegerLiteralClass
:
932 return extract_access(cast
<IntegerLiteral
>(expr
));
939 /* Assign the affine expression "index" to the output dimension "pos" of "map",
940 * restrict the domain to those values that result in a non-negative index
941 * and return the result.
943 __isl_give isl_map
*set_index(__isl_take isl_map
*map
, int pos
,
944 __isl_take isl_pw_aff
*index
)
947 int len
= isl_map_dim(map
, isl_dim_out
);
951 domain
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(index
));
952 index
= isl_pw_aff_intersect_domain(index
, domain
);
953 index_map
= isl_map_from_range(isl_set_from_pw_aff(index
));
954 index_map
= isl_map_insert_dims(index_map
, isl_dim_out
, 0, pos
);
955 index_map
= isl_map_add_dims(index_map
, isl_dim_out
, len
- pos
- 1);
956 id
= isl_map_get_tuple_id(map
, isl_dim_out
);
957 index_map
= isl_map_set_tuple_id(index_map
, isl_dim_out
, id
);
959 map
= isl_map_intersect(map
, index_map
);
964 /* Extract an access relation from the given array subscript expression.
965 * If nesting is allowed in general, then we turn it on while
966 * examining the index expression.
968 * We first extract an access relation from the base.
969 * This will result in an access relation with a range that corresponds
970 * to the array being accessed and with earlier indices filled in already.
971 * We then extract the current index and fill that in as well.
972 * The position of the current index is based on the type of base.
973 * If base is the actual array variable, then the depth of this type
974 * will be the same as the depth of the array and we will fill in
975 * the first array index.
976 * Otherwise, the depth of the base type will be smaller and we will fill
979 __isl_give isl_map
*PetScan::extract_access(ArraySubscriptExpr
*expr
)
981 Expr
*base
= expr
->getBase();
982 Expr
*idx
= expr
->getIdx();
984 isl_map
*base_access
;
986 int depth
= array_depth(base
->getType().getTypePtr());
988 bool save_nesting
= nesting_enabled
;
990 nesting_enabled
= allow_nested
;
992 base_access
= extract_access(base
);
993 index
= extract_affine(idx
);
995 nesting_enabled
= save_nesting
;
997 pos
= isl_map_dim(base_access
, isl_dim_out
) - depth
;
998 access
= set_index(base_access
, pos
, index
);
1003 /* Check if "expr" calls function "minmax" with two arguments and if so
1004 * make lhs and rhs refer to these two arguments.
1006 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
1012 if (expr
->getStmtClass() != Stmt::CallExprClass
)
1015 call
= cast
<CallExpr
>(expr
);
1016 fd
= call
->getDirectCallee();
1020 if (call
->getNumArgs() != 2)
1023 name
= fd
->getDeclName().getAsString();
1027 lhs
= call
->getArg(0);
1028 rhs
= call
->getArg(1);
1033 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1034 * lhs and rhs refer to the two arguments.
1036 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1038 return is_minmax(expr
, "min", lhs
, rhs
);
1041 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1042 * lhs and rhs refer to the two arguments.
1044 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1046 return is_minmax(expr
, "max", lhs
, rhs
);
1049 /* Return "lhs && rhs", defined on the shared definition domain.
1051 static __isl_give isl_pw_aff
*pw_aff_and(__isl_take isl_pw_aff
*lhs
,
1052 __isl_take isl_pw_aff
*rhs
)
1057 dom
= isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs
)),
1058 isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1059 cond
= isl_set_intersect(isl_pw_aff_non_zero_set(lhs
),
1060 isl_pw_aff_non_zero_set(rhs
));
1061 return indicator_function(cond
, dom
);
1064 /* Return "lhs && rhs", with shortcut semantics.
1065 * That is, if lhs is false, then the result is defined even if rhs is not.
1066 * In practice, we compute lhs ? rhs : lhs.
1068 static __isl_give isl_pw_aff
*pw_aff_and_then(__isl_take isl_pw_aff
*lhs
,
1069 __isl_take isl_pw_aff
*rhs
)
1071 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), rhs
, lhs
);
1074 /* Return "lhs || rhs", with shortcut semantics.
1075 * That is, if lhs is true, then the result is defined even if rhs is not.
1076 * In practice, we compute lhs ? lhs : rhs.
1078 static __isl_give isl_pw_aff
*pw_aff_or_else(__isl_take isl_pw_aff
*lhs
,
1079 __isl_take isl_pw_aff
*rhs
)
1081 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), lhs
, rhs
);
1084 /* Extract an affine expressions representing the comparison "LHS op RHS"
1085 * "comp" is the original statement that "LHS op RHS" is derived from
1086 * and is used for diagnostics.
1088 * If the comparison is of the form
1092 * then the expression is constructed as the conjunction of
1097 * A similar optimization is performed for max(a,b) <= c.
1098 * We do this because that will lead to simpler representations
1099 * of the expression.
1100 * If isl is ever enhanced to explicitly deal with min and max expressions,
1101 * this optimization can be removed.
1103 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
1104 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
1113 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
1115 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
1117 if (op
== BO_LT
|| op
== BO_LE
) {
1118 Expr
*expr1
, *expr2
;
1119 if (is_min(RHS
, expr1
, expr2
)) {
1120 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
1121 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
1122 return pw_aff_and(lhs
, rhs
);
1124 if (is_max(LHS
, expr1
, expr2
)) {
1125 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
1126 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
1127 return pw_aff_and(lhs
, rhs
);
1131 lhs
= extract_affine(LHS
);
1132 rhs
= extract_affine(RHS
);
1134 dom
= isl_pw_aff_domain(isl_pw_aff_copy(lhs
));
1135 dom
= isl_set_intersect(dom
, isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1139 cond
= isl_pw_aff_lt_set(lhs
, rhs
);
1142 cond
= isl_pw_aff_le_set(lhs
, rhs
);
1145 cond
= isl_pw_aff_eq_set(lhs
, rhs
);
1148 cond
= isl_pw_aff_ne_set(lhs
, rhs
);
1151 isl_pw_aff_free(lhs
);
1152 isl_pw_aff_free(rhs
);
1158 cond
= isl_set_coalesce(cond
);
1159 res
= indicator_function(cond
, dom
);
1164 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
1166 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1167 comp
->getRHS(), comp
);
1170 /* Extract an affine expression representing the negation (logical not)
1171 * of a subexpression.
1173 __isl_give isl_pw_aff
*PetScan::extract_boolean(UnaryOperator
*op
)
1175 isl_set
*set_cond
, *dom
;
1176 isl_pw_aff
*cond
, *res
;
1178 cond
= extract_condition(op
->getSubExpr());
1180 dom
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
1182 set_cond
= isl_pw_aff_zero_set(cond
);
1184 res
= indicator_function(set_cond
, dom
);
1189 /* Extract an affine expression representing the disjunction (logical or)
1190 * or conjunction (logical and) of two subexpressions.
1192 __isl_give isl_pw_aff
*PetScan::extract_boolean(BinaryOperator
*comp
)
1194 isl_pw_aff
*lhs
, *rhs
;
1196 lhs
= extract_condition(comp
->getLHS());
1197 rhs
= extract_condition(comp
->getRHS());
1199 switch (comp
->getOpcode()) {
1201 return pw_aff_and_then(lhs
, rhs
);
1203 return pw_aff_or_else(lhs
, rhs
);
1205 isl_pw_aff_free(lhs
);
1206 isl_pw_aff_free(rhs
);
1213 __isl_give isl_pw_aff
*PetScan::extract_condition(UnaryOperator
*expr
)
1215 switch (expr
->getOpcode()) {
1217 return extract_boolean(expr
);
1224 /* Extract the affine expression "expr != 0 ? 1 : 0".
1226 __isl_give isl_pw_aff
*PetScan::extract_implicit_condition(Expr
*expr
)
1231 res
= extract_affine(expr
);
1233 dom
= isl_pw_aff_domain(isl_pw_aff_copy(res
));
1234 set
= isl_pw_aff_non_zero_set(res
);
1236 res
= indicator_function(set
, dom
);
1241 /* Extract an affine expression from a boolean expression.
1242 * In particular, return the expression "expr ? 1 : 0".
1244 * If the expression doesn't look like a condition, we assume it
1245 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1247 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
1249 BinaryOperator
*comp
;
1252 isl_set
*u
= isl_set_universe(isl_space_params_alloc(ctx
, 0));
1253 return indicator_function(u
, isl_set_copy(u
));
1256 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1257 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1259 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1260 return extract_condition(cast
<UnaryOperator
>(expr
));
1262 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1263 return extract_implicit_condition(expr
);
1265 comp
= cast
<BinaryOperator
>(expr
);
1266 switch (comp
->getOpcode()) {
1273 return extract_comparison(comp
);
1276 return extract_boolean(comp
);
1278 return extract_implicit_condition(expr
);
1282 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
1286 return pet_op_minus
;
1288 return pet_op_post_inc
;
1290 return pet_op_post_dec
;
1292 return pet_op_pre_inc
;
1294 return pet_op_pre_dec
;
1300 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
1304 return pet_op_add_assign
;
1306 return pet_op_sub_assign
;
1308 return pet_op_mul_assign
;
1310 return pet_op_div_assign
;
1312 return pet_op_assign
;
1334 /* Construct a pet_expr representing a unary operator expression.
1336 struct pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1338 struct pet_expr
*arg
;
1339 enum pet_op_type op
;
1341 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1342 if (op
== pet_op_last
) {
1347 arg
= extract_expr(expr
->getSubExpr());
1349 if (expr
->isIncrementDecrementOp() &&
1350 arg
&& arg
->type
== pet_expr_access
) {
1355 return pet_expr_new_unary(ctx
, op
, arg
);
1358 /* Mark the given access pet_expr as a write.
1359 * If a scalar is being accessed, then mark its value
1360 * as unknown in assigned_value.
1362 void PetScan::mark_write(struct pet_expr
*access
)
1367 access
->acc
.write
= 1;
1368 access
->acc
.read
= 0;
1370 if (isl_map_dim(access
->acc
.access
, isl_dim_out
) != 0)
1373 id
= isl_map_get_tuple_id(access
->acc
.access
, isl_dim_out
);
1374 decl
= (ValueDecl
*) isl_id_get_user(id
);
1375 clear_assignment(assigned_value
, decl
);
1379 /* Construct a pet_expr representing a binary operator expression.
1381 * If the top level operator is an assignment and the LHS is an access,
1382 * then we mark that access as a write. If the operator is a compound
1383 * assignment, the access is marked as both a read and a write.
1385 * If "expr" assigns something to a scalar variable, then we mark
1386 * the variable as having been assigned. If, furthermore, the expression
1387 * is affine, then keep track of this value in assigned_value
1388 * so that we can plug it in when we later come across the same variable.
1390 struct pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1392 struct pet_expr
*lhs
, *rhs
;
1393 enum pet_op_type op
;
1395 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1396 if (op
== pet_op_last
) {
1401 lhs
= extract_expr(expr
->getLHS());
1402 rhs
= extract_expr(expr
->getRHS());
1404 if (expr
->isAssignmentOp() && lhs
&& lhs
->type
== pet_expr_access
) {
1406 if (expr
->isCompoundAssignmentOp())
1410 if (expr
->getOpcode() == BO_Assign
&&
1411 lhs
&& lhs
->type
== pet_expr_access
&&
1412 isl_map_dim(lhs
->acc
.access
, isl_dim_out
) == 0) {
1413 isl_id
*id
= isl_map_get_tuple_id(lhs
->acc
.access
, isl_dim_out
);
1414 ValueDecl
*decl
= (ValueDecl
*) isl_id_get_user(id
);
1415 Expr
*rhs
= expr
->getRHS();
1416 isl_pw_aff
*pa
= try_extract_affine(rhs
);
1417 clear_assignment(assigned_value
, decl
);
1419 assigned_value
[decl
] = pa
;
1420 insert_expression(pa
);
1425 return pet_expr_new_binary(ctx
, op
, lhs
, rhs
);
1428 /* Construct a pet_expr representing a conditional operation.
1430 * We first try to extract the condition as an affine expression.
1431 * If that fails, we construct a pet_expr tree representing the condition.
1433 struct pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1435 struct pet_expr
*cond
, *lhs
, *rhs
;
1438 pa
= try_extract_affine(expr
->getCond());
1440 isl_set
*test
= isl_set_from_pw_aff(pa
);
1441 cond
= pet_expr_from_access(isl_map_from_range(test
));
1443 cond
= extract_expr(expr
->getCond());
1444 lhs
= extract_expr(expr
->getTrueExpr());
1445 rhs
= extract_expr(expr
->getFalseExpr());
1447 return pet_expr_new_ternary(ctx
, cond
, lhs
, rhs
);
1450 struct pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1452 return extract_expr(expr
->getSubExpr());
1455 /* Construct a pet_expr representing a floating point value.
1457 struct pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1459 return pet_expr_new_double(ctx
, expr
->getValueAsApproximateDouble());
1462 /* Extract an access relation from "expr" and then convert it into
1465 struct pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1468 struct pet_expr
*pe
;
1470 access
= extract_access(expr
);
1472 pe
= pet_expr_from_access(access
);
1477 struct pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1479 return extract_expr(expr
->getSubExpr());
1482 /* Construct a pet_expr representing a function call.
1484 * If we are passing along a pointer to an array element
1485 * or an entire row or even higher dimensional slice of an array,
1486 * then the function being called may write into the array.
1488 * We assume here that if the function is declared to take a pointer
1489 * to a const type, then the function will perform a read
1490 * and that otherwise, it will perform a write.
1492 struct pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1494 struct pet_expr
*res
= NULL
;
1498 fd
= expr
->getDirectCallee();
1504 name
= fd
->getDeclName().getAsString();
1505 res
= pet_expr_new_call(ctx
, name
.c_str(), expr
->getNumArgs());
1509 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
1510 Expr
*arg
= expr
->getArg(i
);
1514 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1515 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(arg
);
1516 arg
= ice
->getSubExpr();
1518 if (arg
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1519 UnaryOperator
*op
= cast
<UnaryOperator
>(arg
);
1520 if (op
->getOpcode() == UO_AddrOf
) {
1522 arg
= op
->getSubExpr();
1525 res
->args
[i
] = PetScan::extract_expr(arg
);
1526 main_arg
= res
->args
[i
];
1528 res
->args
[i
] = pet_expr_new_unary(ctx
,
1529 pet_op_address_of
, res
->args
[i
]);
1532 if (arg
->getStmtClass() == Stmt::ArraySubscriptExprClass
&&
1533 array_depth(arg
->getType().getTypePtr()) > 0)
1535 if (is_addr
&& main_arg
->type
== pet_expr_access
) {
1537 if (!fd
->hasPrototype()) {
1538 unsupported(expr
, "prototype required");
1541 parm
= fd
->getParamDecl(i
);
1542 if (!const_base(parm
->getType()))
1543 mark_write(main_arg
);
1553 /* Try and onstruct a pet_expr representing "expr".
1555 struct pet_expr
*PetScan::extract_expr(Expr
*expr
)
1557 switch (expr
->getStmtClass()) {
1558 case Stmt::UnaryOperatorClass
:
1559 return extract_expr(cast
<UnaryOperator
>(expr
));
1560 case Stmt::CompoundAssignOperatorClass
:
1561 case Stmt::BinaryOperatorClass
:
1562 return extract_expr(cast
<BinaryOperator
>(expr
));
1563 case Stmt::ImplicitCastExprClass
:
1564 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1565 case Stmt::ArraySubscriptExprClass
:
1566 case Stmt::DeclRefExprClass
:
1567 case Stmt::IntegerLiteralClass
:
1568 return extract_access_expr(expr
);
1569 case Stmt::FloatingLiteralClass
:
1570 return extract_expr(cast
<FloatingLiteral
>(expr
));
1571 case Stmt::ParenExprClass
:
1572 return extract_expr(cast
<ParenExpr
>(expr
));
1573 case Stmt::ConditionalOperatorClass
:
1574 return extract_expr(cast
<ConditionalOperator
>(expr
));
1575 case Stmt::CallExprClass
:
1576 return extract_expr(cast
<CallExpr
>(expr
));
1583 /* Check if the given initialization statement is an assignment.
1584 * If so, return that assignment. Otherwise return NULL.
1586 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1588 BinaryOperator
*ass
;
1590 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1593 ass
= cast
<BinaryOperator
>(init
);
1594 if (ass
->getOpcode() != BO_Assign
)
1600 /* Check if the given initialization statement is a declaration
1601 * of a single variable.
1602 * If so, return that declaration. Otherwise return NULL.
1604 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1608 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1611 decl
= cast
<DeclStmt
>(init
);
1613 if (!decl
->isSingleDecl())
1616 return decl
->getSingleDecl();
1619 /* Given the assignment operator in the initialization of a for loop,
1620 * extract the induction variable, i.e., the (integer)variable being
1623 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1630 lhs
= init
->getLHS();
1631 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1636 ref
= cast
<DeclRefExpr
>(lhs
);
1637 decl
= ref
->getDecl();
1638 type
= decl
->getType().getTypePtr();
1640 if (!type
->isIntegerType()) {
1648 /* Given the initialization statement of a for loop and the single
1649 * declaration in this initialization statement,
1650 * extract the induction variable, i.e., the (integer) variable being
1653 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1657 vd
= cast
<VarDecl
>(decl
);
1659 const QualType type
= vd
->getType();
1660 if (!type
->isIntegerType()) {
1665 if (!vd
->getInit()) {
1673 /* Check that op is of the form iv++ or iv--.
1674 * Return an affine expression "1" or "-1" accordingly.
1676 __isl_give isl_pw_aff
*PetScan::extract_unary_increment(
1677 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1684 if (!op
->isIncrementDecrementOp()) {
1689 sub
= op
->getSubExpr();
1690 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1695 ref
= cast
<DeclRefExpr
>(sub
);
1696 if (ref
->getDecl() != iv
) {
1701 space
= isl_space_params_alloc(ctx
, 0);
1702 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
1704 if (op
->isIncrementOp())
1705 aff
= isl_aff_add_constant_si(aff
, 1);
1707 aff
= isl_aff_add_constant_si(aff
, -1);
1709 return isl_pw_aff_from_aff(aff
);
1712 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1713 * has a single constant expression, then put this constant in *user.
1714 * The caller is assumed to have checked that this function will
1715 * be called exactly once.
1717 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
1720 isl_int
*inc
= (isl_int
*)user
;
1723 if (isl_aff_is_cst(aff
))
1724 isl_aff_get_constant(aff
, inc
);
1734 /* Check if op is of the form
1738 * and return inc as an affine expression.
1740 * We extract an affine expression from the RHS, subtract iv and return
1743 __isl_give isl_pw_aff
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1744 clang::ValueDecl
*iv
)
1753 if (op
->getOpcode() != BO_Assign
) {
1759 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1764 ref
= cast
<DeclRefExpr
>(lhs
);
1765 if (ref
->getDecl() != iv
) {
1770 val
= extract_affine(op
->getRHS());
1772 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1774 dim
= isl_space_params_alloc(ctx
, 1);
1775 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1776 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1777 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1779 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
1784 /* Check that op is of the form iv += cst or iv -= cst
1785 * and return an affine expression corresponding oto cst or -cst accordingly.
1787 __isl_give isl_pw_aff
*PetScan::extract_compound_increment(
1788 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1794 BinaryOperatorKind opcode
;
1796 opcode
= op
->getOpcode();
1797 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1801 if (opcode
== BO_SubAssign
)
1805 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1810 ref
= cast
<DeclRefExpr
>(lhs
);
1811 if (ref
->getDecl() != iv
) {
1816 val
= extract_affine(op
->getRHS());
1818 val
= isl_pw_aff_neg(val
);
1823 /* Check that the increment of the given for loop increments
1824 * (or decrements) the induction variable "iv" and return
1825 * the increment as an affine expression if successful.
1827 __isl_give isl_pw_aff
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1830 Stmt
*inc
= stmt
->getInc();
1837 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1838 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1839 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1840 return extract_compound_increment(
1841 cast
<CompoundAssignOperator
>(inc
), iv
);
1842 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1843 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1849 /* Embed the given iteration domain in an extra outer loop
1850 * with induction variable "var".
1851 * If this variable appeared as a parameter in the constraints,
1852 * it is replaced by the new outermost dimension.
1854 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1855 __isl_take isl_id
*var
)
1859 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1860 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1862 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1863 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1870 /* Create the infinite iteration domain
1872 * { [id] : id >= 0 }
1875 static __isl_give isl_set
*infinite_domain(__isl_take isl_id
*id
)
1877 isl_ctx
*ctx
= isl_id_get_ctx(id
);
1880 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
1881 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, id
);
1886 /* Create an identity mapping on the space containing "domain".
1888 static __isl_give isl_map
*identity_map(__isl_keep isl_set
*domain
)
1893 space
= isl_space_map_from_set(isl_set_get_space(domain
));
1894 id
= isl_map_identity(space
);
1899 /* Construct a pet_scop for an infinite loop around the given body.
1901 * We extract a pet_scop for the body and then embed it in a loop with
1910 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
1915 struct pet_scop
*scop
;
1917 scop
= extract(body
);
1921 id
= isl_id_alloc(ctx
, "t", NULL
);
1922 domain
= infinite_domain(isl_id_copy(id
));
1923 ident
= identity_map(domain
);
1924 scop
= pet_scop_embed(scop
, domain
, isl_map_copy(ident
), ident
, id
);
1929 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1935 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
1937 return extract_infinite_loop(stmt
->getBody());
1940 /* Create an access to a virtual array representing the result
1942 * Unlike other accessed data, the id of the array is NULL as
1943 * there is no ValueDecl in the program corresponding to the virtual
1945 * The array starts out as a scalar, but grows along with the
1946 * statement writing to the array in pet_scop_embed.
1948 static __isl_give isl_map
*create_test_access(isl_ctx
*ctx
, int test_nr
)
1950 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, 0);
1954 snprintf(name
, sizeof(name
), "__pet_test_%d", test_nr
);
1955 id
= isl_id_alloc(ctx
, name
, NULL
);
1956 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
1957 return isl_map_universe(dim
);
1960 /* Add an array with the given extent ("access") to the list
1961 * of arrays in "scop" and return the extended pet_scop.
1962 * The array is marked as attaining values 0 and 1 only and
1963 * as each element being assigned at most once.
1965 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
1966 __isl_keep isl_map
*access
, clang::ASTContext
&ast_ctx
)
1968 isl_ctx
*ctx
= isl_map_get_ctx(access
);
1970 struct pet_array
**arrays
;
1971 struct pet_array
*array
;
1978 arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
1982 scop
->arrays
= arrays
;
1984 array
= isl_calloc_type(ctx
, struct pet_array
);
1988 array
->extent
= isl_map_range(isl_map_copy(access
));
1989 dim
= isl_space_params_alloc(ctx
, 0);
1990 array
->context
= isl_set_universe(dim
);
1991 dim
= isl_space_set_alloc(ctx
, 0, 1);
1992 array
->value_bounds
= isl_set_universe(dim
);
1993 array
->value_bounds
= isl_set_lower_bound_si(array
->value_bounds
,
1995 array
->value_bounds
= isl_set_upper_bound_si(array
->value_bounds
,
1997 array
->element_type
= strdup("int");
1998 array
->element_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
1999 array
->uniquely_defined
= 1;
2001 scop
->arrays
[scop
->n_array
] = array
;
2004 if (!array
->extent
|| !array
->context
)
2009 pet_scop_free(scop
);
2013 /* Construct a pet_scop for a while loop of the form
2018 * In particular, construct a scop for an infinite loop around body and
2019 * intersect the domain with the affine expression.
2020 * Note that this intersection may result in an empty loop.
2022 struct pet_scop
*PetScan::extract_affine_while(__isl_take isl_pw_aff
*pa
,
2025 struct pet_scop
*scop
;
2029 valid
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2030 dom
= isl_pw_aff_non_zero_set(pa
);
2031 scop
= extract_infinite_loop(body
);
2032 scop
= pet_scop_restrict(scop
, dom
);
2033 scop
= pet_scop_restrict_context(scop
, valid
);
2038 /* Construct a scop for a while, given the scops for the condition
2039 * and the body, the filter access and the iteration domain of
2042 * In particular, the scop for the condition is filtered to depend
2043 * on "test_access" evaluating to true for all previous iterations
2044 * of the loop, while the scop for the body is filtered to depend
2045 * on "test_access" evaluating to true for all iterations up to the
2046 * current iteration.
2048 * These filtered scops are then combined into a single scop.
2050 * "sign" is positive if the iterator increases and negative
2053 static struct pet_scop
*scop_add_while(struct pet_scop
*scop_cond
,
2054 struct pet_scop
*scop_body
, __isl_take isl_map
*test_access
,
2055 __isl_take isl_set
*domain
, int sign
)
2057 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
2061 id_test
= isl_map_get_tuple_id(test_access
, isl_dim_out
);
2062 test_access
= isl_map_add_dims(test_access
, isl_dim_in
, 1);
2063 test_access
= isl_map_add_dims(test_access
, isl_dim_out
, 1);
2064 test_access
= isl_map_intersect_range(test_access
, domain
);
2065 test_access
= isl_map_set_tuple_id(test_access
, isl_dim_out
, id_test
);
2067 prev
= isl_map_lex_ge_first(isl_map_get_space(test_access
), 1);
2069 prev
= isl_map_lex_le_first(isl_map_get_space(test_access
), 1);
2070 test_access
= isl_map_intersect(test_access
, prev
);
2071 scop_body
= pet_scop_filter(scop_body
, isl_map_copy(test_access
), 1);
2073 prev
= isl_map_lex_gt_first(isl_map_get_space(test_access
), 1);
2075 prev
= isl_map_lex_lt_first(isl_map_get_space(test_access
), 1);
2076 test_access
= isl_map_intersect(test_access
, prev
);
2077 scop_cond
= pet_scop_filter(scop_cond
, test_access
, 1);
2079 return pet_scop_add(ctx
, scop_cond
, scop_body
);
2082 /* Check if the while loop is of the form
2084 * while (affine expression)
2087 * If so, call extract_affine_while to construct a scop.
2089 * Otherwise, construct a generic while scop, with iteration domain
2090 * { [t] : t >= 0 }. The scop consists of two parts, one for
2091 * evaluating the condition and one for the body.
2092 * The schedule is adjusted to reflect that the condition is evaluated
2093 * before the body is executed and the body is filtered to depend
2094 * on the result of the condition evaluating to true on all iterations
2095 * up to the current iteration, while the evaluation the condition itself
2096 * is filtered to depend on the result of the condition evaluating to true
2097 * on all previous iterations.
2098 * The context of the scop representing the body is dropped
2099 * because we don't know how many times the body will be executed,
2102 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
2106 isl_map
*test_access
;
2110 struct pet_scop
*scop
, *scop_body
;
2112 cond
= stmt
->getCond();
2118 pa
= try_extract_affine_condition(cond
);
2120 return extract_affine_while(pa
, stmt
->getBody());
2122 if (!allow_nested
) {
2127 id
= isl_id_alloc(ctx
, "t", NULL
);
2128 domain
= infinite_domain(isl_id_copy(id
));
2129 ident
= identity_map(domain
);
2131 test_access
= create_test_access(ctx
, n_test
++);
2132 scop
= extract_non_affine_condition(cond
, isl_map_copy(test_access
));
2133 scop
= scop_add_array(scop
, test_access
, ast_context
);
2134 scop
= pet_scop_prefix(scop
, 0);
2135 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), isl_map_copy(ident
),
2136 isl_map_copy(ident
), isl_id_copy(id
));
2137 scop_body
= extract(stmt
->getBody());
2138 scop_body
= pet_scop_reset_context(scop_body
);
2139 scop_body
= pet_scop_prefix(scop_body
, 1);
2140 scop_body
= pet_scop_embed(scop_body
, isl_set_copy(domain
),
2141 isl_map_copy(ident
), ident
, id
);
2143 scop
= scop_add_while(scop
, scop_body
, test_access
, domain
, 1);
2148 /* Check whether "cond" expresses a simple loop bound
2149 * on the only set dimension.
2150 * In particular, if "up" is set then "cond" should contain only
2151 * upper bounds on the set dimension.
2152 * Otherwise, it should contain only lower bounds.
2154 static bool is_simple_bound(__isl_keep isl_set
*cond
, isl_int inc
)
2156 if (isl_int_is_pos(inc
))
2157 return !isl_set_dim_has_lower_bound(cond
, isl_dim_set
, 0);
2159 return !isl_set_dim_has_upper_bound(cond
, isl_dim_set
, 0);
2162 /* Extend a condition on a given iteration of a loop to one that
2163 * imposes the same condition on all previous iterations.
2164 * "domain" expresses the lower [upper] bound on the iterations
2165 * when inc is positive [negative].
2167 * In particular, we construct the condition (when inc is positive)
2169 * forall i' : (domain(i') and i' <= i) => cond(i')
2171 * which is equivalent to
2173 * not exists i' : domain(i') and i' <= i and not cond(i')
2175 * We construct this set by negating cond, applying a map
2177 * { [i'] -> [i] : domain(i') and i' <= i }
2179 * and then negating the result again.
2181 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
2182 __isl_take isl_set
*domain
, isl_int inc
)
2184 isl_map
*previous_to_this
;
2186 if (isl_int_is_pos(inc
))
2187 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
2189 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
2191 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
2193 cond
= isl_set_complement(cond
);
2194 cond
= isl_set_apply(cond
, previous_to_this
);
2195 cond
= isl_set_complement(cond
);
2200 /* Construct a domain of the form
2202 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2204 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
2205 __isl_take isl_pw_aff
*init
, isl_int inc
)
2211 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
2212 dim
= isl_pw_aff_get_domain_space(init
);
2213 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2214 aff
= isl_aff_add_coefficient(aff
, isl_dim_in
, 0, inc
);
2215 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2217 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2218 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2219 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2220 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2222 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2224 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2226 return isl_set_params(set
);
2229 /* Assuming "cond" represents a bound on a loop where the loop
2230 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2233 * Under the given assumptions, wrapping is only possible if "cond" allows
2234 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2235 * increasing iterator and 0 in case of a decreasing iterator.
2237 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
, isl_int inc
)
2243 test
= isl_set_copy(cond
);
2245 isl_int_init(limit
);
2246 if (isl_int_is_neg(inc
))
2247 isl_int_set_si(limit
, 0);
2249 isl_int_set_si(limit
, 1);
2250 isl_int_mul_2exp(limit
, limit
, get_type_size(iv
));
2251 isl_int_sub_ui(limit
, limit
, 1);
2254 test
= isl_set_fix(cond
, isl_dim_set
, 0, limit
);
2255 cw
= !isl_set_is_empty(test
);
2258 isl_int_clear(limit
);
2263 /* Given a one-dimensional space, construct the following mapping on this
2266 * { [v] -> [v mod 2^width] }
2268 * where width is the number of bits used to represent the values
2269 * of the unsigned variable "iv".
2271 static __isl_give isl_map
*compute_wrapping(__isl_take isl_space
*dim
,
2279 isl_int_set_si(mod
, 1);
2280 isl_int_mul_2exp(mod
, mod
, get_type_size(iv
));
2282 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2283 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2284 aff
= isl_aff_mod(aff
, mod
);
2288 return isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2289 map
= isl_map_reverse(map
);
2292 /* Project out the parameter "id" from "set".
2294 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2295 __isl_keep isl_id
*id
)
2299 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2301 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2306 /* Compute the set of parameters for which "set1" is a subset of "set2".
2308 * set1 is a subset of set2 if
2310 * forall i in set1 : i in set2
2314 * not exists i in set1 and i not in set2
2318 * not exists i in set1 \ set2
2320 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2321 __isl_take isl_set
*set2
)
2323 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2326 /* Compute the set of parameter values for which "cond" holds
2327 * on the next iteration for each element of "dom".
2329 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2330 * and then compute the set of parameters for which the result is a subset
2333 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2334 __isl_take isl_set
*dom
, isl_int inc
)
2340 space
= isl_set_get_space(dom
);
2341 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2342 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2343 aff
= isl_aff_add_constant(aff
, inc
);
2344 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2346 dom
= isl_set_apply(dom
, next
);
2348 return enforce_subset(dom
, cond
);
2351 /* Does "id" refer to a nested access?
2353 static bool is_nested_parameter(__isl_keep isl_id
*id
)
2355 return id
&& isl_id_get_user(id
) && !isl_id_get_name(id
);
2358 /* Does parameter "pos" of "space" refer to a nested access?
2360 static bool is_nested_parameter(__isl_keep isl_space
*space
, int pos
)
2365 id
= isl_space_get_dim_id(space
, isl_dim_param
, pos
);
2366 nested
= is_nested_parameter(id
);
2372 /* Does "space" involve any parameters that refer to nested
2373 * accesses, i.e., parameters with no name?
2375 static bool has_nested(__isl_keep isl_space
*space
)
2379 nparam
= isl_space_dim(space
, isl_dim_param
);
2380 for (int i
= 0; i
< nparam
; ++i
)
2381 if (is_nested_parameter(space
, i
))
2387 /* Does "pa" involve any parameters that refer to nested
2388 * accesses, i.e., parameters with no name?
2390 static bool has_nested(__isl_keep isl_pw_aff
*pa
)
2395 space
= isl_pw_aff_get_space(pa
);
2396 nested
= has_nested(space
);
2397 isl_space_free(space
);
2402 /* Construct a pet_scop for a for statement.
2403 * The for loop is required to be of the form
2405 * for (i = init; condition; ++i)
2409 * for (i = init; condition; --i)
2411 * The initialization of the for loop should either be an assignment
2412 * to an integer variable, or a declaration of such a variable with
2415 * The condition is allowed to contain nested accesses, provided
2416 * they are not being written to inside the body of the loop.
2417 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2418 * essentially treated as a while loop, with iteration domain
2419 * { [i] : i >= init }.
2421 * We extract a pet_scop for the body and then embed it in a loop with
2422 * iteration domain and schedule
2424 * { [i] : i >= init and condition' }
2429 * { [i] : i <= init and condition' }
2432 * Where condition' is equal to condition if the latter is
2433 * a simple upper [lower] bound and a condition that is extended
2434 * to apply to all previous iterations otherwise.
2436 * If the condition is non-affine, then we drop the condition from the
2437 * iteration domain and instead create a separate statement
2438 * for evaluating the condition. The body is then filtered to depend
2439 * on the result of the condition evaluating to true on all iterations
2440 * up to the current iteration, while the evaluation the condition itself
2441 * is filtered to depend on the result of the condition evaluating to true
2442 * on all previous iterations.
2443 * The context of the scop representing the body is dropped
2444 * because we don't know how many times the body will be executed,
2447 * If the stride of the loop is not 1, then "i >= init" is replaced by
2449 * (exists a: i = init + stride * a and a >= 0)
2451 * If the loop iterator i is unsigned, then wrapping may occur.
2452 * During the computation, we work with a virtual iterator that
2453 * does not wrap. However, the condition in the code applies
2454 * to the wrapped value, so we need to change condition(i)
2455 * into condition([i % 2^width]).
2456 * After computing the virtual domain and schedule, we apply
2457 * the function { [v] -> [v % 2^width] } to the domain and the domain
2458 * of the schedule. In order not to lose any information, we also
2459 * need to intersect the domain of the schedule with the virtual domain
2460 * first, since some iterations in the wrapped domain may be scheduled
2461 * several times, typically an infinite number of times.
2462 * Note that there may be no need to perform this final wrapping
2463 * if the loop condition (after wrapping) satisfies certain conditions.
2464 * However, the is_simple_bound condition is not enough since it doesn't
2465 * check if there even is an upper bound.
2467 * If the loop condition is non-affine, then we keep the virtual
2468 * iterator in the iteration domain and instead replace all accesses
2469 * to the original iterator by the wrapping of the virtual iterator.
2471 * Wrapping on unsigned iterators can be avoided entirely if
2472 * loop condition is simple, the loop iterator is incremented
2473 * [decremented] by one and the last value before wrapping cannot
2474 * possibly satisfy the loop condition.
2476 * Before extracting a pet_scop from the body we remove all
2477 * assignments in assigned_value to variables that are assigned
2478 * somewhere in the body of the loop.
2480 * Valid parameters for a for loop are those for which the initial
2481 * value itself, the increment on each domain iteration and
2482 * the condition on both the initial value and
2483 * the result of incrementing the iterator for each iteration of the domain
2485 * If the loop condition is non-affine, then we only consider validity
2486 * of the initial value.
2488 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2490 BinaryOperator
*ass
;
2498 isl_set
*cond
= NULL
;
2500 struct pet_scop
*scop
, *scop_cond
= NULL
;
2501 assigned_value_cache
cache(assigned_value
);
2507 bool keep_virtual
= false;
2508 isl_map
*wrap
= NULL
;
2509 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2510 isl_set
*valid_init
;
2511 isl_set
*valid_cond
;
2512 isl_set
*valid_cond_init
;
2513 isl_set
*valid_cond_next
;
2515 isl_map
*test_access
= NULL
;
2518 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2519 return extract_infinite_for(stmt
);
2521 init
= stmt
->getInit();
2526 if ((ass
= initialization_assignment(init
)) != NULL
) {
2527 iv
= extract_induction_variable(ass
);
2530 lhs
= ass
->getLHS();
2531 rhs
= ass
->getRHS();
2532 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2533 VarDecl
*var
= extract_induction_variable(init
, decl
);
2537 rhs
= var
->getInit();
2538 lhs
= create_DeclRefExpr(var
);
2540 unsupported(stmt
->getInit());
2544 pa_inc
= extract_increment(stmt
, iv
);
2549 if (isl_pw_aff_n_piece(pa_inc
) != 1 ||
2550 isl_pw_aff_foreach_piece(pa_inc
, &extract_cst
, &inc
) < 0) {
2551 isl_pw_aff_free(pa_inc
);
2552 unsupported(stmt
->getInc());
2556 valid_inc
= isl_pw_aff_domain(pa_inc
);
2558 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2560 assigned_value
.erase(iv
);
2561 clear_assignments
clear(assigned_value
);
2562 clear
.TraverseStmt(stmt
->getBody());
2564 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
2566 pa
= try_extract_nested_condition(stmt
->getCond());
2567 if (allow_nested
&& (!pa
|| has_nested(pa
)))
2570 scop
= extract(stmt
->getBody());
2572 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2573 isl_pw_aff_free(pa
);
2577 if (!allow_nested
&& !pa
)
2578 pa
= try_extract_affine_condition(stmt
->getCond());
2579 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2580 cond
= isl_pw_aff_non_zero_set(pa
);
2581 if (allow_nested
&& !cond
) {
2582 int save_n_stmt
= n_stmt
;
2583 test_access
= create_test_access(ctx
, n_test
++);
2585 scop_cond
= extract_non_affine_condition(stmt
->getCond(),
2586 isl_map_copy(test_access
));
2587 n_stmt
= save_n_stmt
;
2588 scop_cond
= scop_add_array(scop_cond
, test_access
, ast_context
);
2589 scop_cond
= pet_scop_prefix(scop_cond
, 0);
2590 scop
= pet_scop_reset_context(scop
);
2591 scop
= pet_scop_prefix(scop
, 1);
2592 keep_virtual
= true;
2593 cond
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2596 cond
= embed(cond
, isl_id_copy(id
));
2597 valid_cond
= isl_set_coalesce(valid_cond
);
2598 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
2599 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
2600 is_one
= isl_int_is_one(inc
) || isl_int_is_negone(inc
);
2601 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2603 init_val
= extract_affine(rhs
);
2604 valid_cond_init
= enforce_subset(
2605 isl_set_from_pw_aff(isl_pw_aff_copy(init_val
)),
2606 isl_set_copy(valid_cond
));
2607 if (is_one
&& !is_virtual
) {
2608 isl_pw_aff_free(init_val
);
2609 pa
= extract_comparison(isl_int_is_pos(inc
) ? BO_GE
: BO_LE
,
2611 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2612 valid_init
= set_project_out_by_id(valid_init
, id
);
2613 domain
= isl_pw_aff_non_zero_set(pa
);
2615 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
2616 domain
= strided_domain(isl_id_copy(id
), init_val
, inc
);
2619 domain
= embed(domain
, isl_id_copy(id
));
2622 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2623 rev_wrap
= isl_map_reverse(isl_map_copy(wrap
));
2624 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
2625 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
2626 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
2628 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2629 is_simple
= is_simple_bound(cond
, inc
);
2631 cond
= valid_for_each_iteration(cond
,
2632 isl_set_copy(domain
), inc
);
2633 domain
= isl_set_intersect(domain
, cond
);
2634 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2635 space
= isl_space_from_domain(isl_set_get_space(domain
));
2636 space
= isl_space_add_dims(space
, isl_dim_out
, 1);
2637 sched
= isl_map_universe(space
);
2638 if (isl_int_is_pos(inc
))
2639 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2641 sched
= isl_map_oppose(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2643 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
), inc
);
2644 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
2646 if (is_virtual
&& !keep_virtual
) {
2647 wrap
= isl_map_set_dim_id(wrap
,
2648 isl_dim_out
, 0, isl_id_copy(id
));
2649 sched
= isl_map_intersect_domain(sched
, isl_set_copy(domain
));
2650 domain
= isl_set_apply(domain
, isl_map_copy(wrap
));
2651 sched
= isl_map_apply_domain(sched
, wrap
);
2653 if (!(is_virtual
&& keep_virtual
)) {
2654 space
= isl_set_get_space(domain
);
2655 wrap
= isl_map_identity(isl_space_map_from_set(space
));
2658 scop_cond
= pet_scop_embed(scop_cond
, isl_set_copy(domain
),
2659 isl_map_copy(sched
), isl_map_copy(wrap
), isl_id_copy(id
));
2660 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), sched
, wrap
, id
);
2661 scop
= resolve_nested(scop
);
2663 scop
= scop_add_while(scop_cond
, scop
, test_access
, domain
,
2665 isl_set_free(valid_inc
);
2667 scop
= pet_scop_restrict_context(scop
, valid_inc
);
2668 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
2669 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
2670 isl_set_free(domain
);
2672 clear_assignment(assigned_value
, iv
);
2676 scop
= pet_scop_restrict_context(scop
, valid_init
);
2681 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
)
2683 return extract(stmt
->children());
2686 /* Does parameter "pos" of "map" refer to a nested access?
2688 static bool is_nested_parameter(__isl_keep isl_map
*map
, int pos
)
2693 id
= isl_map_get_dim_id(map
, isl_dim_param
, pos
);
2694 nested
= is_nested_parameter(id
);
2700 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2702 static int n_nested_parameter(__isl_keep isl_space
*space
)
2707 nparam
= isl_space_dim(space
, isl_dim_param
);
2708 for (int i
= 0; i
< nparam
; ++i
)
2709 if (is_nested_parameter(space
, i
))
2715 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2717 static int n_nested_parameter(__isl_keep isl_map
*map
)
2722 space
= isl_map_get_space(map
);
2723 n
= n_nested_parameter(space
);
2724 isl_space_free(space
);
2729 /* For each nested access parameter in "space",
2730 * construct a corresponding pet_expr, place it in args and
2731 * record its position in "param2pos".
2732 * "n_arg" is the number of elements that are already in args.
2733 * The position recorded in "param2pos" takes this number into account.
2734 * If the pet_expr corresponding to a parameter is identical to
2735 * the pet_expr corresponding to an earlier parameter, then these two
2736 * parameters are made to refer to the same element in args.
2738 * Return the final number of elements in args or -1 if an error has occurred.
2740 int PetScan::extract_nested(__isl_keep isl_space
*space
,
2741 int n_arg
, struct pet_expr
**args
, std::map
<int,int> ¶m2pos
)
2745 nparam
= isl_space_dim(space
, isl_dim_param
);
2746 for (int i
= 0; i
< nparam
; ++i
) {
2748 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2751 if (!is_nested_parameter(id
)) {
2756 nested
= (Expr
*) isl_id_get_user(id
);
2757 args
[n_arg
] = extract_expr(nested
);
2761 for (j
= 0; j
< n_arg
; ++j
)
2762 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
2766 pet_expr_free(args
[n_arg
]);
2770 param2pos
[i
] = n_arg
++;
2778 /* For each nested access parameter in the access relations in "expr",
2779 * construct a corresponding pet_expr, place it in expr->args and
2780 * record its position in "param2pos".
2781 * n is the number of nested access parameters.
2783 struct pet_expr
*PetScan::extract_nested(struct pet_expr
*expr
, int n
,
2784 std::map
<int,int> ¶m2pos
)
2788 expr
->args
= isl_calloc_array(ctx
, struct pet_expr
*, n
);
2793 space
= isl_map_get_space(expr
->acc
.access
);
2794 n
= extract_nested(space
, 0, expr
->args
, param2pos
);
2795 isl_space_free(space
);
2803 pet_expr_free(expr
);
2807 /* Look for parameters in any access relation in "expr" that
2808 * refer to nested accesses. In particular, these are
2809 * parameters with no name.
2811 * If there are any such parameters, then the domain of the access
2812 * relation, which is still [] at this point, is replaced by
2813 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2814 * (after identifying identical nested accesses).
2815 * The parameters are then equated to the corresponding t dimensions
2816 * and subsequently projected out.
2817 * param2pos maps the position of the parameter to the position
2818 * of the corresponding t dimension.
2820 struct pet_expr
*PetScan::resolve_nested(struct pet_expr
*expr
)
2827 std::map
<int,int> param2pos
;
2832 for (int i
= 0; i
< expr
->n_arg
; ++i
) {
2833 expr
->args
[i
] = resolve_nested(expr
->args
[i
]);
2834 if (!expr
->args
[i
]) {
2835 pet_expr_free(expr
);
2840 if (expr
->type
!= pet_expr_access
)
2843 n
= n_nested_parameter(expr
->acc
.access
);
2847 expr
= extract_nested(expr
, n
, param2pos
);
2852 nparam
= isl_map_dim(expr
->acc
.access
, isl_dim_param
);
2853 n_in
= isl_map_dim(expr
->acc
.access
, isl_dim_in
);
2854 dim
= isl_map_get_space(expr
->acc
.access
);
2855 dim
= isl_space_domain(dim
);
2856 dim
= isl_space_from_domain(dim
);
2857 dim
= isl_space_add_dims(dim
, isl_dim_out
, n
);
2858 map
= isl_map_universe(dim
);
2859 map
= isl_map_domain_map(map
);
2860 map
= isl_map_reverse(map
);
2861 expr
->acc
.access
= isl_map_apply_domain(expr
->acc
.access
, map
);
2863 for (int i
= nparam
- 1; i
>= 0; --i
) {
2864 isl_id
*id
= isl_map_get_dim_id(expr
->acc
.access
,
2866 if (!is_nested_parameter(id
)) {
2871 expr
->acc
.access
= isl_map_equate(expr
->acc
.access
,
2872 isl_dim_param
, i
, isl_dim_in
,
2873 n_in
+ param2pos
[i
]);
2874 expr
->acc
.access
= isl_map_project_out(expr
->acc
.access
,
2875 isl_dim_param
, i
, 1);
2882 pet_expr_free(expr
);
2886 /* Convert a top-level pet_expr to a pet_scop with one statement.
2887 * This mainly involves resolving nested expression parameters
2888 * and setting the name of the iteration space.
2889 * The name is given by "label" if it is non-NULL. Otherwise,
2890 * it is of the form S_<n_stmt>.
2892 struct pet_scop
*PetScan::extract(Stmt
*stmt
, struct pet_expr
*expr
,
2893 __isl_take isl_id
*label
)
2895 struct pet_stmt
*ps
;
2896 SourceLocation loc
= stmt
->getLocStart();
2897 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
2899 expr
= resolve_nested(expr
);
2900 ps
= pet_stmt_from_pet_expr(ctx
, line
, label
, n_stmt
++, expr
);
2901 return pet_scop_from_pet_stmt(ctx
, ps
);
2904 /* Check if we can extract an affine expression from "expr".
2905 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2906 * We turn on autodetection so that we won't generate any warnings
2907 * and turn off nesting, so that we won't accept any non-affine constructs.
2909 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
2912 int save_autodetect
= options
->autodetect
;
2913 bool save_nesting
= nesting_enabled
;
2915 options
->autodetect
= 1;
2916 nesting_enabled
= false;
2918 pwaff
= extract_affine(expr
);
2920 options
->autodetect
= save_autodetect
;
2921 nesting_enabled
= save_nesting
;
2926 /* Check whether "expr" is an affine expression.
2928 bool PetScan::is_affine(Expr
*expr
)
2932 pwaff
= try_extract_affine(expr
);
2933 isl_pw_aff_free(pwaff
);
2935 return pwaff
!= NULL
;
2938 /* Check if we can extract an affine constraint from "expr".
2939 * Return the constraint as an isl_set if we can and NULL otherwise.
2940 * We turn on autodetection so that we won't generate any warnings
2941 * and turn off nesting, so that we won't accept any non-affine constructs.
2943 __isl_give isl_pw_aff
*PetScan::try_extract_affine_condition(Expr
*expr
)
2946 int save_autodetect
= options
->autodetect
;
2947 bool save_nesting
= nesting_enabled
;
2949 options
->autodetect
= 1;
2950 nesting_enabled
= false;
2952 cond
= extract_condition(expr
);
2954 options
->autodetect
= save_autodetect
;
2955 nesting_enabled
= save_nesting
;
2960 /* Check whether "expr" is an affine constraint.
2962 bool PetScan::is_affine_condition(Expr
*expr
)
2966 cond
= try_extract_affine_condition(expr
);
2967 isl_pw_aff_free(cond
);
2969 return cond
!= NULL
;
2972 /* Check if we can extract a condition from "expr".
2973 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
2974 * If allow_nested is set, then the condition may involve parameters
2975 * corresponding to nested accesses.
2976 * We turn on autodetection so that we won't generate any warnings.
2978 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
2981 int save_autodetect
= options
->autodetect
;
2982 bool save_nesting
= nesting_enabled
;
2984 options
->autodetect
= 1;
2985 nesting_enabled
= allow_nested
;
2986 cond
= extract_condition(expr
);
2988 options
->autodetect
= save_autodetect
;
2989 nesting_enabled
= save_nesting
;
2994 /* If the top-level expression of "stmt" is an assignment, then
2995 * return that assignment as a BinaryOperator.
2996 * Otherwise return NULL.
2998 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
3000 BinaryOperator
*ass
;
3004 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
3007 ass
= cast
<BinaryOperator
>(stmt
);
3008 if(ass
->getOpcode() != BO_Assign
)
3014 /* Check if the given if statement is a conditional assignement
3015 * with a non-affine condition. If so, construct a pet_scop
3016 * corresponding to this conditional assignment. Otherwise return NULL.
3018 * In particular we check if "stmt" is of the form
3025 * where a is some array or scalar access.
3026 * The constructed pet_scop then corresponds to the expression
3028 * a = condition ? f(...) : g(...)
3030 * All access relations in f(...) are intersected with condition
3031 * while all access relation in g(...) are intersected with the complement.
3033 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
3035 BinaryOperator
*ass_then
, *ass_else
;
3036 isl_map
*write_then
, *write_else
;
3037 isl_set
*cond
, *comp
;
3041 struct pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
3042 bool save_nesting
= nesting_enabled
;
3044 if (!options
->detect_conditional_assignment
)
3047 ass_then
= top_assignment_or_null(stmt
->getThen());
3048 ass_else
= top_assignment_or_null(stmt
->getElse());
3050 if (!ass_then
|| !ass_else
)
3053 if (is_affine_condition(stmt
->getCond()))
3056 write_then
= extract_access(ass_then
->getLHS());
3057 write_else
= extract_access(ass_else
->getLHS());
3059 equal
= isl_map_is_equal(write_then
, write_else
);
3060 isl_map_free(write_else
);
3061 if (equal
< 0 || !equal
) {
3062 isl_map_free(write_then
);
3066 nesting_enabled
= allow_nested
;
3067 pa
= extract_condition(stmt
->getCond());
3068 nesting_enabled
= save_nesting
;
3069 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
3070 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
3071 map
= isl_map_from_range(isl_set_from_pw_aff(pa
));
3073 pe_cond
= pet_expr_from_access(map
);
3075 pe_then
= extract_expr(ass_then
->getRHS());
3076 pe_then
= pet_expr_restrict(pe_then
, cond
);
3077 pe_else
= extract_expr(ass_else
->getRHS());
3078 pe_else
= pet_expr_restrict(pe_else
, comp
);
3080 pe
= pet_expr_new_ternary(ctx
, pe_cond
, pe_then
, pe_else
);
3081 pe_write
= pet_expr_from_access(write_then
);
3083 pe_write
->acc
.write
= 1;
3084 pe_write
->acc
.read
= 0;
3086 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, pe_write
, pe
);
3087 return extract(stmt
, pe
);
3090 /* Create a pet_scop with a single statement evaluating "cond"
3091 * and writing the result to a virtual scalar, as expressed by
3094 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
,
3095 __isl_take isl_map
*access
)
3097 struct pet_expr
*expr
, *write
;
3098 struct pet_stmt
*ps
;
3099 struct pet_scop
*scop
;
3100 SourceLocation loc
= cond
->getLocStart();
3101 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3103 write
= pet_expr_from_access(access
);
3105 write
->acc
.write
= 1;
3106 write
->acc
.read
= 0;
3108 expr
= extract_expr(cond
);
3109 expr
= resolve_nested(expr
);
3110 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, write
, expr
);
3111 ps
= pet_stmt_from_pet_expr(ctx
, line
, NULL
, n_stmt
++, expr
);
3112 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3113 scop
= resolve_nested(scop
);
3119 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
,
3123 /* Apply the map pointed to by "user" to the domain of the access
3124 * relation, thereby embedding it in the range of the map.
3125 * The domain of both relations is the zero-dimensional domain.
3127 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
, void *user
)
3129 isl_map
*map
= (isl_map
*) user
;
3131 return isl_map_apply_domain(access
, isl_map_copy(map
));
3134 /* Apply "map" to all access relations in "expr".
3136 static struct pet_expr
*embed(struct pet_expr
*expr
, __isl_keep isl_map
*map
)
3138 return pet_expr_foreach_access(expr
, &embed_access
, map
);
3141 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3143 static int n_nested_parameter(__isl_keep isl_set
*set
)
3148 space
= isl_set_get_space(set
);
3149 n
= n_nested_parameter(space
);
3150 isl_space_free(space
);
3155 /* Remove all parameters from "map" that refer to nested accesses.
3157 static __isl_give isl_map
*remove_nested_parameters(__isl_take isl_map
*map
)
3162 space
= isl_map_get_space(map
);
3163 nparam
= isl_space_dim(space
, isl_dim_param
);
3164 for (int i
= nparam
- 1; i
>= 0; --i
)
3165 if (is_nested_parameter(space
, i
))
3166 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3167 isl_space_free(space
);
3173 static __isl_give isl_map
*access_remove_nested_parameters(
3174 __isl_take isl_map
*access
, void *user
);
3177 static __isl_give isl_map
*access_remove_nested_parameters(
3178 __isl_take isl_map
*access
, void *user
)
3180 return remove_nested_parameters(access
);
3183 /* Remove all nested access parameters from the schedule and all
3184 * accesses of "stmt".
3185 * There is no need to remove them from the domain as these parameters
3186 * have already been removed from the domain when this function is called.
3188 static struct pet_stmt
*remove_nested_parameters(struct pet_stmt
*stmt
)
3192 stmt
->schedule
= remove_nested_parameters(stmt
->schedule
);
3193 stmt
->body
= pet_expr_foreach_access(stmt
->body
,
3194 &access_remove_nested_parameters
, NULL
);
3195 if (!stmt
->schedule
|| !stmt
->body
)
3197 for (int i
= 0; i
< stmt
->n_arg
; ++i
) {
3198 stmt
->args
[i
] = pet_expr_foreach_access(stmt
->args
[i
],
3199 &access_remove_nested_parameters
, NULL
);
3206 pet_stmt_free(stmt
);
3210 /* For each nested access parameter in the domain of "stmt",
3211 * construct a corresponding pet_expr, place it before the original
3212 * elements in stmt->args and record its position in "param2pos".
3213 * n is the number of nested access parameters.
3215 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
3216 std::map
<int,int> ¶m2pos
)
3221 struct pet_expr
**args
;
3223 n_arg
= stmt
->n_arg
;
3224 args
= isl_calloc_array(ctx
, struct pet_expr
*, n
+ n_arg
);
3228 space
= isl_set_get_space(stmt
->domain
);
3229 n_arg
= extract_nested(space
, 0, args
, param2pos
);
3230 isl_space_free(space
);
3235 for (i
= 0; i
< stmt
->n_arg
; ++i
)
3236 args
[n_arg
+ i
] = stmt
->args
[i
];
3239 stmt
->n_arg
+= n_arg
;
3244 for (i
= 0; i
< n
; ++i
)
3245 pet_expr_free(args
[i
]);
3248 pet_stmt_free(stmt
);
3252 /* Check whether any of the arguments i of "stmt" starting at position "n"
3253 * is equal to one of the first "n" arguments j.
3254 * If so, combine the constraints on arguments i and j and remove
3257 static struct pet_stmt
*remove_duplicate_arguments(struct pet_stmt
*stmt
, int n
)
3266 if (n
== stmt
->n_arg
)
3269 map
= isl_set_unwrap(stmt
->domain
);
3271 for (i
= stmt
->n_arg
- 1; i
>= n
; --i
) {
3272 for (j
= 0; j
< n
; ++j
)
3273 if (pet_expr_is_equal(stmt
->args
[i
], stmt
->args
[j
]))
3278 map
= isl_map_equate(map
, isl_dim_out
, i
, isl_dim_out
, j
);
3279 map
= isl_map_project_out(map
, isl_dim_out
, i
, 1);
3281 pet_expr_free(stmt
->args
[i
]);
3282 for (j
= i
; j
+ 1 < stmt
->n_arg
; ++j
)
3283 stmt
->args
[j
] = stmt
->args
[j
+ 1];
3287 stmt
->domain
= isl_map_wrap(map
);
3292 pet_stmt_free(stmt
);
3296 /* Look for parameters in the iteration domain of "stmt" that
3297 * refer to nested accesses. In particular, these are
3298 * parameters with no name.
3300 * If there are any such parameters, then as many extra variables
3301 * (after identifying identical nested accesses) are inserted in the
3302 * range of the map wrapped inside the domain, before the original variables.
3303 * If the original domain is not a wrapped map, then a new wrapped
3304 * map is created with zero output dimensions.
3305 * The parameters are then equated to the corresponding output dimensions
3306 * and subsequently projected out, from the iteration domain,
3307 * the schedule and the access relations.
3308 * For each of the output dimensions, a corresponding argument
3309 * expression is inserted. Initially they are created with
3310 * a zero-dimensional domain, so they have to be embedded
3311 * in the current iteration domain.
3312 * param2pos maps the position of the parameter to the position
3313 * of the corresponding output dimension in the wrapped map.
3315 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3321 std::map
<int,int> param2pos
;
3326 n
= n_nested_parameter(stmt
->domain
);
3330 n_arg
= stmt
->n_arg
;
3331 stmt
= extract_nested(stmt
, n
, param2pos
);
3335 n
= stmt
->n_arg
- n_arg
;
3336 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3337 if (isl_set_is_wrapping(stmt
->domain
))
3338 map
= isl_set_unwrap(stmt
->domain
);
3340 map
= isl_map_from_domain(stmt
->domain
);
3341 map
= isl_map_insert_dims(map
, isl_dim_out
, 0, n
);
3343 for (int i
= nparam
- 1; i
>= 0; --i
) {
3346 if (!is_nested_parameter(map
, i
))
3349 id
= isl_map_get_tuple_id(stmt
->args
[param2pos
[i
]]->acc
.access
,
3351 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3352 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3354 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3357 stmt
->domain
= isl_map_wrap(map
);
3359 map
= isl_set_unwrap(isl_set_copy(stmt
->domain
));
3360 map
= isl_map_from_range(isl_map_domain(map
));
3361 for (int pos
= 0; pos
< n
; ++pos
)
3362 stmt
->args
[pos
] = embed(stmt
->args
[pos
], map
);
3365 stmt
= remove_nested_parameters(stmt
);
3366 stmt
= remove_duplicate_arguments(stmt
, n
);
3370 pet_stmt_free(stmt
);
3374 /* For each statement in "scop", move the parameters that correspond
3375 * to nested access into the ranges of the domains and create
3376 * corresponding argument expressions.
3378 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3383 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3384 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3385 if (!scop
->stmts
[i
])
3391 pet_scop_free(scop
);
3395 /* Given an access expression "expr", is the variable accessed by
3396 * "expr" assigned anywhere inside "scop"?
3398 static bool is_assigned(pet_expr
*expr
, pet_scop
*scop
)
3400 bool assigned
= false;
3403 id
= isl_map_get_tuple_id(expr
->acc
.access
, isl_dim_out
);
3404 assigned
= pet_scop_writes(scop
, id
);
3410 /* Are all nested access parameters in "pa" allowed given "scop".
3411 * In particular, is none of them written by anywhere inside "scop".
3413 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3417 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3418 for (int i
= 0; i
< nparam
; ++i
) {
3420 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3424 if (!is_nested_parameter(id
)) {
3429 nested
= (Expr
*) isl_id_get_user(id
);
3430 expr
= extract_expr(nested
);
3431 allowed
= expr
&& expr
->type
== pet_expr_access
&&
3432 !is_assigned(expr
, scop
);
3434 pet_expr_free(expr
);
3444 /* Construct a pet_scop for a non-affine if statement.
3446 * We create a separate statement that writes the result
3447 * of the non-affine condition to a virtual scalar.
3448 * A constraint requiring the value of this virtual scalar to be one
3449 * is added to the iteration domains of the then branch.
3450 * Similarly, a constraint requiring the value of this virtual scalar
3451 * to be zero is added to the iteration domains of the else branch, if any.
3452 * We adjust the schedules to ensure that the virtual scalar is written
3453 * before it is read.
3455 struct pet_scop
*PetScan::extract_non_affine_if(Expr
*cond
,
3456 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3457 bool have_else
, int stmt_id
)
3459 struct pet_scop
*scop
;
3460 isl_map
*test_access
;
3461 int save_n_stmt
= n_stmt
;
3463 test_access
= create_test_access(ctx
, n_test
++);
3465 scop
= extract_non_affine_condition(cond
, isl_map_copy(test_access
));
3466 n_stmt
= save_n_stmt
;
3467 scop
= scop_add_array(scop
, test_access
, ast_context
);
3469 scop
= pet_scop_prefix(scop
, 0);
3470 scop_then
= pet_scop_prefix(scop_then
, 1);
3471 scop_then
= pet_scop_filter(scop_then
, isl_map_copy(test_access
), 1);
3473 scop_else
= pet_scop_prefix(scop_else
, 1);
3474 scop_else
= pet_scop_filter(scop_else
, test_access
, 0);
3475 scop_then
= pet_scop_add(ctx
, scop_then
, scop_else
);
3477 isl_map_free(test_access
);
3479 scop
= pet_scop_add(ctx
, scop
, scop_then
);
3484 /* Construct a pet_scop for an if statement.
3486 * If the condition fits the pattern of a conditional assignment,
3487 * then it is handled by extract_conditional_assignment.
3488 * Otherwise, we do the following.
3490 * If the condition is affine, then the condition is added
3491 * to the iteration domains of the then branch, while the
3492 * opposite of the condition in added to the iteration domains
3493 * of the else branch, if any.
3494 * We allow the condition to be dynamic, i.e., to refer to
3495 * scalars or array elements that may be written to outside
3496 * of the given if statement. These nested accesses are then represented
3497 * as output dimensions in the wrapping iteration domain.
3498 * If it also written _inside_ the then or else branch, then
3499 * we treat the condition as non-affine.
3500 * As explained in extract_non_affine_if, this will introduce
3501 * an extra statement.
3502 * For aesthetic reasons, we want this statement to have a statement
3503 * number that is lower than those of the then and else branches.
3504 * In order to evaluate if will need such a statement, however, we
3505 * first construct scops for the then and else branches.
3506 * We therefore reserve a statement number if we might have to
3507 * introduce such an extra statement.
3509 * If the condition is not affine, then the scop is created in
3510 * extract_non_affine_if.
3512 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
3514 struct pet_scop
*scop_then
, *scop_else
, *scop
;
3520 scop
= extract_conditional_assignment(stmt
);
3524 cond
= try_extract_nested_condition(stmt
->getCond());
3525 if (allow_nested
&& (!cond
|| has_nested(cond
)))
3529 assigned_value_cache
cache(assigned_value
);
3530 scop_then
= extract(stmt
->getThen());
3533 if (stmt
->getElse()) {
3534 assigned_value_cache
cache(assigned_value
);
3535 scop_else
= extract(stmt
->getElse());
3536 if (options
->autodetect
) {
3537 if (scop_then
&& !scop_else
) {
3539 isl_pw_aff_free(cond
);
3542 if (!scop_then
&& scop_else
) {
3544 isl_pw_aff_free(cond
);
3551 (!is_nested_allowed(cond
, scop_then
) ||
3552 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
3553 isl_pw_aff_free(cond
);
3556 if (allow_nested
&& !cond
)
3557 return extract_non_affine_if(stmt
->getCond(), scop_then
,
3558 scop_else
, stmt
->getElse(), stmt_id
);
3561 cond
= extract_condition(stmt
->getCond());
3562 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
3563 set
= isl_pw_aff_non_zero_set(cond
);
3564 scop
= pet_scop_restrict(scop_then
, isl_set_copy(set
));
3566 if (stmt
->getElse()) {
3567 set
= isl_set_subtract(isl_set_copy(valid
), set
);
3568 scop_else
= pet_scop_restrict(scop_else
, set
);
3569 scop
= pet_scop_add(ctx
, scop
, scop_else
);
3572 scop
= resolve_nested(scop
);
3573 scop
= pet_scop_restrict_context(scop
, valid
);
3578 /* Try and construct a pet_scop for a label statement.
3579 * We currently only allow labels on expression statements.
3581 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
3586 sub
= stmt
->getSubStmt();
3587 if (!isa
<Expr
>(sub
)) {
3592 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
3594 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
3597 /* Try and construct a pet_scop corresponding to "stmt".
3599 struct pet_scop
*PetScan::extract(Stmt
*stmt
)
3601 if (isa
<Expr
>(stmt
))
3602 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
3604 switch (stmt
->getStmtClass()) {
3605 case Stmt::WhileStmtClass
:
3606 return extract(cast
<WhileStmt
>(stmt
));
3607 case Stmt::ForStmtClass
:
3608 return extract_for(cast
<ForStmt
>(stmt
));
3609 case Stmt::IfStmtClass
:
3610 return extract(cast
<IfStmt
>(stmt
));
3611 case Stmt::CompoundStmtClass
:
3612 return extract(cast
<CompoundStmt
>(stmt
));
3613 case Stmt::LabelStmtClass
:
3614 return extract(cast
<LabelStmt
>(stmt
));
3622 /* Try and construct a pet_scop corresponding to (part of)
3623 * a sequence of statements.
3625 struct pet_scop
*PetScan::extract(StmtRange stmt_range
)
3630 bool partial_range
= false;
3632 scop
= pet_scop_empty(ctx
);
3633 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
3635 struct pet_scop
*scop_i
;
3636 scop_i
= extract(child
);
3637 if (scop
&& partial
) {
3638 pet_scop_free(scop_i
);
3641 scop_i
= pet_scop_prefix(scop_i
, j
);
3642 if (options
->autodetect
) {
3644 scop
= pet_scop_add(ctx
, scop
, scop_i
);
3646 partial_range
= true;
3647 if (scop
->n_stmt
!= 0 && !scop_i
)
3650 scop
= pet_scop_add(ctx
, scop
, scop_i
);
3656 if (scop
&& partial_range
)
3662 /* Check if the scop marked by the user is exactly this Stmt
3663 * or part of this Stmt.
3664 * If so, return a pet_scop corresponding to the marked region.
3665 * Otherwise, return NULL.
3667 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
3669 SourceManager
&SM
= PP
.getSourceManager();
3670 unsigned start_off
, end_off
;
3672 start_off
= SM
.getFileOffset(stmt
->getLocStart());
3673 end_off
= SM
.getFileOffset(stmt
->getLocEnd());
3675 if (start_off
> loc
.end
)
3677 if (end_off
< loc
.start
)
3679 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
3680 return extract(stmt
);
3684 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
3685 Stmt
*child
= *start
;
3688 start_off
= SM
.getFileOffset(child
->getLocStart());
3689 end_off
= SM
.getFileOffset(child
->getLocEnd());
3690 if (start_off
< loc
.start
&& end_off
> loc
.end
)
3692 if (start_off
>= loc
.start
)
3697 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
3699 start_off
= SM
.getFileOffset(child
->getLocStart());
3700 if (start_off
>= loc
.end
)
3704 return extract(StmtRange(start
, end
));
3707 /* Set the size of index "pos" of "array" to "size".
3708 * In particular, add a constraint of the form
3712 * to array->extent and a constraint of the form
3716 * to array->context.
3718 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
3719 __isl_take isl_pw_aff
*size
)
3729 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
3730 array
->context
= isl_set_intersect(array
->context
, valid
);
3732 dim
= isl_set_get_space(array
->extent
);
3733 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
3734 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
3735 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
3736 index
= isl_pw_aff_alloc(univ
, aff
);
3738 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
3739 isl_set_dim(array
->extent
, isl_dim_set
));
3740 id
= isl_set_get_tuple_id(array
->extent
);
3741 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
3742 bound
= isl_pw_aff_lt_set(index
, size
);
3744 array
->extent
= isl_set_intersect(array
->extent
, bound
);
3746 if (!array
->context
|| !array
->extent
)
3751 pet_array_free(array
);
3755 /* Figure out the size of the array at position "pos" and all
3756 * subsequent positions from "type" and update "array" accordingly.
3758 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
3759 const Type
*type
, int pos
)
3761 const ArrayType
*atype
;
3767 if (type
->isPointerType()) {
3768 type
= type
->getPointeeType().getTypePtr();
3769 return set_upper_bounds(array
, type
, pos
+ 1);
3771 if (!type
->isArrayType())
3774 type
= type
->getCanonicalTypeInternal().getTypePtr();
3775 atype
= cast
<ArrayType
>(type
);
3777 if (type
->isConstantArrayType()) {
3778 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
3779 size
= extract_affine(ca
->getSize());
3780 array
= update_size(array
, pos
, size
);
3781 } else if (type
->isVariableArrayType()) {
3782 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
3783 size
= extract_affine(vla
->getSizeExpr());
3784 array
= update_size(array
, pos
, size
);
3787 type
= atype
->getElementType().getTypePtr();
3789 return set_upper_bounds(array
, type
, pos
+ 1);
3792 /* Construct and return a pet_array corresponding to the variable "decl".
3793 * In particular, initialize array->extent to
3795 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3797 * and then call set_upper_bounds to set the upper bounds on the indices
3798 * based on the type of the variable.
3800 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
)
3802 struct pet_array
*array
;
3803 QualType qt
= decl
->getType();
3804 const Type
*type
= qt
.getTypePtr();
3805 int depth
= array_depth(type
);
3806 QualType base
= base_type(qt
);
3811 array
= isl_calloc_type(ctx
, struct pet_array
);
3815 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
3816 dim
= isl_space_set_alloc(ctx
, 0, depth
);
3817 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
3819 array
->extent
= isl_set_nat_universe(dim
);
3821 dim
= isl_space_params_alloc(ctx
, 0);
3822 array
->context
= isl_set_universe(dim
);
3824 array
= set_upper_bounds(array
, type
, 0);
3828 name
= base
.getAsString();
3829 array
->element_type
= strdup(name
.c_str());
3830 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
3835 /* Construct a list of pet_arrays, one for each array (or scalar)
3836 * accessed inside "scop", add this list to "scop" and return the result.
3838 * The context of "scop" is updated with the intersection of
3839 * the contexts of all arrays, i.e., constraints on the parameters
3840 * that ensure that the arrays have a valid (non-negative) size.
3842 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
3845 set
<ValueDecl
*> arrays
;
3846 set
<ValueDecl
*>::iterator it
;
3848 struct pet_array
**scop_arrays
;
3853 pet_scop_collect_arrays(scop
, arrays
);
3854 if (arrays
.size() == 0)
3857 n_array
= scop
->n_array
;
3859 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
3860 n_array
+ arrays
.size());
3863 scop
->arrays
= scop_arrays
;
3865 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
3866 struct pet_array
*array
;
3867 scop
->arrays
[n_array
+ i
] = array
= extract_array(ctx
, *it
);
3868 if (!scop
->arrays
[n_array
+ i
])
3871 scop
->context
= isl_set_intersect(scop
->context
,
3872 isl_set_copy(array
->context
));
3879 pet_scop_free(scop
);
3883 /* Bound all parameters in scop->context to the possible values
3884 * of the corresponding C variable.
3886 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
3893 n
= isl_set_dim(scop
->context
, isl_dim_param
);
3894 for (int i
= 0; i
< n
; ++i
) {
3898 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
3899 if (is_nested_parameter(id
)) {
3901 isl_die(isl_set_get_ctx(scop
->context
),
3903 "unresolved nested parameter", goto error
);
3905 decl
= (ValueDecl
*) isl_id_get_user(id
);
3908 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
3916 pet_scop_free(scop
);
3920 /* Construct a pet_scop from the given function.
3922 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
3927 stmt
= fd
->getBody();
3929 if (options
->autodetect
)
3930 scop
= extract(stmt
);
3933 scop
= pet_scop_detect_parameter_accesses(scop
);
3934 scop
= scan_arrays(scop
);
3935 scop
= add_parameter_bounds(scop
);
3936 scop
= pet_scop_gist(scop
, value_bounds
);