2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012 Ecole Normale Superieure. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
38 #include <clang/AST/ASTDiagnostic.h>
39 #include <clang/AST/Expr.h>
40 #include <clang/AST/RecursiveASTVisitor.h>
43 #include <isl/space.h>
49 #include "scop_plus.h"
54 using namespace clang
;
56 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
57 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
59 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
60 SourceLocation(), var
, false, var
->getInnerLocStart(),
61 var
->getType(), VK_LValue
);
63 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
64 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
66 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
67 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
71 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
73 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
74 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
78 /* Check if the element type corresponding to the given array type
79 * has a const qualifier.
81 static bool const_base(QualType qt
)
83 const Type
*type
= qt
.getTypePtr();
85 if (type
->isPointerType())
86 return const_base(type
->getPointeeType());
87 if (type
->isArrayType()) {
88 const ArrayType
*atype
;
89 type
= type
->getCanonicalTypeInternal().getTypePtr();
90 atype
= cast
<ArrayType
>(type
);
91 return const_base(atype
->getElementType());
94 return qt
.isConstQualified();
97 /* Mark "decl" as having an unknown value in "assigned_value".
99 * If no (known or unknown) value was assigned to "decl" before,
100 * then it may have been treated as a parameter before and may
101 * therefore appear in a value assigned to another variable.
102 * If so, this assignment needs to be turned into an unknown value too.
104 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
107 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
109 it
= assigned_value
.find(decl
);
111 assigned_value
[decl
] = NULL
;
113 if (it
== assigned_value
.end())
116 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
117 isl_pw_aff
*pa
= it
->second
;
118 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
120 for (int i
= 0; i
< nparam
; ++i
) {
123 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
125 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
126 if (isl_id_get_user(id
) == decl
)
133 /* Look for any assignments to scalar variables in part of the parse
134 * tree and set assigned_value to NULL for each of them.
135 * Also reset assigned_value if the address of a scalar variable
136 * is being taken. As an exception, if the address is passed to a function
137 * that is declared to receive a const pointer, then assigned_value is
140 * This ensures that we won't use any previously stored value
141 * in the current subtree and its parents.
143 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
144 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
145 set
<UnaryOperator
*> skip
;
147 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
148 assigned_value(assigned_value
) {}
150 /* Check for "address of" operators whose value is passed
151 * to a const pointer argument and add them to "skip", so that
152 * we can skip them in VisitUnaryOperator.
154 bool VisitCallExpr(CallExpr
*expr
) {
156 fd
= expr
->getDirectCallee();
159 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
160 Expr
*arg
= expr
->getArg(i
);
162 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
163 ImplicitCastExpr
*ice
;
164 ice
= cast
<ImplicitCastExpr
>(arg
);
165 arg
= ice
->getSubExpr();
167 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
169 op
= cast
<UnaryOperator
>(arg
);
170 if (op
->getOpcode() != UO_AddrOf
)
172 if (const_base(fd
->getParamDecl(i
)->getType()))
178 bool VisitUnaryOperator(UnaryOperator
*expr
) {
183 if (expr
->getOpcode() != UO_AddrOf
)
185 if (skip
.find(expr
) != skip
.end())
188 arg
= expr
->getSubExpr();
189 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
191 ref
= cast
<DeclRefExpr
>(arg
);
192 decl
= ref
->getDecl();
193 clear_assignment(assigned_value
, decl
);
197 bool VisitBinaryOperator(BinaryOperator
*expr
) {
202 if (!expr
->isAssignmentOp())
204 lhs
= expr
->getLHS();
205 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
207 ref
= cast
<DeclRefExpr
>(lhs
);
208 decl
= ref
->getDecl();
209 clear_assignment(assigned_value
, decl
);
214 /* Keep a copy of the currently assigned values.
216 * Any variable that is assigned a value inside the current scope
217 * is removed again when we leave the scope (either because it wasn't
218 * stored in the cache or because it has a different value in the cache).
220 struct assigned_value_cache
{
221 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
222 map
<ValueDecl
*, isl_pw_aff
*> cache
;
224 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
225 assigned_value(assigned_value
), cache(assigned_value
) {}
226 ~assigned_value_cache() {
227 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
228 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
231 (cache
.find(it
->first
) != cache
.end() &&
232 cache
[it
->first
] != it
->second
))
233 cache
[it
->first
] = NULL
;
235 assigned_value
= cache
;
239 /* Insert an expression into the collection of expressions,
240 * provided it is not already in there.
241 * The isl_pw_affs are freed in the destructor.
243 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
245 std::set
<isl_pw_aff
*>::iterator it
;
247 if (expressions
.find(expr
) == expressions
.end())
248 expressions
.insert(expr
);
250 isl_pw_aff_free(expr
);
255 std::set
<isl_pw_aff
*>::iterator it
;
257 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
258 isl_pw_aff_free(*it
);
260 isl_union_map_free(value_bounds
);
263 /* Called if we found something we (currently) cannot handle.
264 * We'll provide more informative warnings later.
266 * We only actually complain if autodetect is false.
268 void PetScan::unsupported(Stmt
*stmt
, const char *msg
)
273 SourceLocation loc
= stmt
->getLocStart();
274 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
275 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
276 msg
? msg
: "unsupported");
277 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
280 /* Extract an integer from "expr" and store it in "v".
282 int PetScan::extract_int(IntegerLiteral
*expr
, isl_int
*v
)
284 const Type
*type
= expr
->getType().getTypePtr();
285 int is_signed
= type
->hasSignedIntegerRepresentation();
288 int64_t i
= expr
->getValue().getSExtValue();
289 isl_int_set_si(*v
, i
);
291 uint64_t i
= expr
->getValue().getZExtValue();
292 isl_int_set_ui(*v
, i
);
298 /* Extract an integer from "expr" and store it in "v".
299 * Return -1 if "expr" does not (obviously) represent an integer.
301 int PetScan::extract_int(clang::ParenExpr
*expr
, isl_int
*v
)
303 return extract_int(expr
->getSubExpr(), v
);
306 /* Extract an integer from "expr" and store it in "v".
307 * Return -1 if "expr" does not (obviously) represent an integer.
309 int PetScan::extract_int(clang::Expr
*expr
, isl_int
*v
)
311 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
312 return extract_int(cast
<IntegerLiteral
>(expr
), v
);
313 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
314 return extract_int(cast
<ParenExpr
>(expr
), v
);
320 /* Extract an affine expression from the IntegerLiteral "expr".
322 __isl_give isl_pw_aff
*PetScan::extract_affine(IntegerLiteral
*expr
)
324 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
325 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
326 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
327 isl_set
*dom
= isl_set_universe(dim
);
331 extract_int(expr
, &v
);
332 aff
= isl_aff_add_constant(aff
, v
);
335 return isl_pw_aff_alloc(dom
, aff
);
338 /* Extract an affine expression from the APInt "val".
340 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
342 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
343 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
344 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
345 isl_set
*dom
= isl_set_universe(dim
);
349 isl_int_set_ui(v
, val
.getZExtValue());
350 aff
= isl_aff_add_constant(aff
, v
);
353 return isl_pw_aff_alloc(dom
, aff
);
356 __isl_give isl_pw_aff
*PetScan::extract_affine(ImplicitCastExpr
*expr
)
358 return extract_affine(expr
->getSubExpr());
361 static unsigned get_type_size(ValueDecl
*decl
)
363 return decl
->getASTContext().getIntWidth(decl
->getType());
366 /* Bound parameter "pos" of "set" to the possible values of "decl".
368 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
369 unsigned pos
, ValueDecl
*decl
)
376 width
= get_type_size(decl
);
377 if (decl
->getType()->isUnsignedIntegerType()) {
378 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
379 isl_int_set_si(v
, 1);
380 isl_int_mul_2exp(v
, v
, width
);
381 isl_int_sub_ui(v
, v
, 1);
382 set
= isl_set_upper_bound(set
, isl_dim_param
, pos
, v
);
384 isl_int_set_si(v
, 1);
385 isl_int_mul_2exp(v
, v
, width
- 1);
386 isl_int_sub_ui(v
, v
, 1);
387 set
= isl_set_upper_bound(set
, isl_dim_param
, pos
, v
);
389 isl_int_sub_ui(v
, v
, 1);
390 set
= isl_set_lower_bound(set
, isl_dim_param
, pos
, v
);
398 /* Extract an affine expression from the DeclRefExpr "expr".
400 * If the variable has been assigned a value, then we check whether
401 * we know what (affine) value was assigned.
402 * If so, we return this value. Otherwise we convert "expr"
403 * to an extra parameter (provided nesting_enabled is set).
405 * Otherwise, we simply return an expression that is equal
406 * to a parameter corresponding to the referenced variable.
408 __isl_give isl_pw_aff
*PetScan::extract_affine(DeclRefExpr
*expr
)
410 ValueDecl
*decl
= expr
->getDecl();
411 const Type
*type
= decl
->getType().getTypePtr();
417 if (!type
->isIntegerType()) {
422 if (assigned_value
.find(decl
) != assigned_value
.end()) {
423 if (assigned_value
[decl
])
424 return isl_pw_aff_copy(assigned_value
[decl
]);
426 return nested_access(expr
);
429 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
430 dim
= isl_space_params_alloc(ctx
, 1);
432 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
434 dom
= isl_set_universe(isl_space_copy(dim
));
435 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
436 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
438 return isl_pw_aff_alloc(dom
, aff
);
441 /* Extract an affine expression from an integer division operation.
442 * In particular, if "expr" is lhs/rhs, then return
444 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
446 * The second argument (rhs) is required to be a (positive) integer constant.
448 __isl_give isl_pw_aff
*PetScan::extract_affine_div(BinaryOperator
*expr
)
451 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
456 rhs_expr
= expr
->getRHS();
458 if (extract_int(rhs_expr
, &v
) < 0) {
463 lhs
= extract_affine(expr
->getLHS());
464 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
466 lhs
= isl_pw_aff_scale_down(lhs
, v
);
469 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(lhs
));
470 lhs_c
= isl_pw_aff_ceil(lhs
);
471 res
= isl_pw_aff_cond(isl_set_indicator_function(cond
), lhs_f
, lhs_c
);
476 /* Extract an affine expression from a modulo operation.
477 * In particular, if "expr" is lhs/rhs, then return
479 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
481 * The second argument (rhs) is required to be a (positive) integer constant.
483 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
486 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
491 rhs_expr
= expr
->getRHS();
492 if (rhs_expr
->getStmtClass() != Stmt::IntegerLiteralClass
) {
497 lhs
= extract_affine(expr
->getLHS());
498 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
501 extract_int(cast
<IntegerLiteral
>(rhs_expr
), &v
);
502 res
= isl_pw_aff_scale_down(isl_pw_aff_copy(lhs
), v
);
504 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(res
));
505 lhs_c
= isl_pw_aff_ceil(res
);
506 res
= isl_pw_aff_cond(isl_set_indicator_function(cond
), lhs_f
, lhs_c
);
508 res
= isl_pw_aff_scale(res
, v
);
511 res
= isl_pw_aff_sub(lhs
, res
);
516 /* Extract an affine expression from a multiplication operation.
517 * This is only allowed if at least one of the two arguments
518 * is a (piecewise) constant.
520 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
525 lhs
= extract_affine(expr
->getLHS());
526 rhs
= extract_affine(expr
->getRHS());
528 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
529 isl_pw_aff_free(lhs
);
530 isl_pw_aff_free(rhs
);
535 return isl_pw_aff_mul(lhs
, rhs
);
538 /* Extract an affine expression from an addition or subtraction operation.
540 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
545 lhs
= extract_affine(expr
->getLHS());
546 rhs
= extract_affine(expr
->getRHS());
548 switch (expr
->getOpcode()) {
550 return isl_pw_aff_add(lhs
, rhs
);
552 return isl_pw_aff_sub(lhs
, rhs
);
554 isl_pw_aff_free(lhs
);
555 isl_pw_aff_free(rhs
);
565 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
571 isl_int_set_si(mod
, 1);
572 isl_int_mul_2exp(mod
, mod
, width
);
574 pwaff
= isl_pw_aff_mod(pwaff
, mod
);
581 /* Limit the domain of "pwaff" to those elements where the function
584 * 2^{width-1} <= pwaff < 2^{width-1}
586 static __isl_give isl_pw_aff
*avoid_overflow(__isl_take isl_pw_aff
*pwaff
,
590 isl_space
*space
= isl_pw_aff_get_domain_space(pwaff
);
591 isl_local_space
*ls
= isl_local_space_from_space(space
);
597 isl_int_set_si(v
, 1);
598 isl_int_mul_2exp(v
, v
, width
- 1);
600 bound
= isl_aff_zero_on_domain(ls
);
601 bound
= isl_aff_add_constant(bound
, v
);
602 b
= isl_pw_aff_from_aff(bound
);
604 dom
= isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff
), isl_pw_aff_copy(b
));
605 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
607 b
= isl_pw_aff_neg(b
);
608 dom
= isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff
), b
);
609 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
616 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
618 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
619 __isl_take isl_set
*dom
)
622 pa
= isl_set_indicator_function(set
);
623 pa
= isl_pw_aff_intersect_domain(pa
, dom
);
627 /* Extract an affine expression from some binary operations.
628 * If the result of the expression is unsigned, then we wrap it
629 * based on the size of the type. Otherwise, we ensure that
630 * no overflow occurs.
632 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
637 switch (expr
->getOpcode()) {
640 res
= extract_affine_add(expr
);
643 res
= extract_affine_div(expr
);
646 res
= extract_affine_mod(expr
);
649 res
= extract_affine_mul(expr
);
659 return extract_condition(expr
);
665 width
= ast_context
.getIntWidth(expr
->getType());
666 if (expr
->getType()->isUnsignedIntegerType())
667 res
= wrap(res
, width
);
669 res
= avoid_overflow(res
, width
);
674 /* Extract an affine expression from a negation operation.
676 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
678 if (expr
->getOpcode() == UO_Minus
)
679 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
680 if (expr
->getOpcode() == UO_LNot
)
681 return extract_condition(expr
);
687 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
689 return extract_affine(expr
->getSubExpr());
692 /* Extract an affine expression from some special function calls.
693 * In particular, we handle "min", "max", "ceild" and "floord".
694 * In case of the latter two, the second argument needs to be
695 * a (positive) integer constant.
697 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
701 isl_pw_aff
*aff1
, *aff2
;
703 fd
= expr
->getDirectCallee();
709 name
= fd
->getDeclName().getAsString();
710 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
711 !(expr
->getNumArgs() == 2 && name
== "max") &&
712 !(expr
->getNumArgs() == 2 && name
== "floord") &&
713 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
718 if (name
== "min" || name
== "max") {
719 aff1
= extract_affine(expr
->getArg(0));
720 aff2
= extract_affine(expr
->getArg(1));
723 aff1
= isl_pw_aff_min(aff1
, aff2
);
725 aff1
= isl_pw_aff_max(aff1
, aff2
);
726 } else if (name
== "floord" || name
== "ceild") {
728 Expr
*arg2
= expr
->getArg(1);
730 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
734 aff1
= extract_affine(expr
->getArg(0));
736 extract_int(cast
<IntegerLiteral
>(arg2
), &v
);
737 aff1
= isl_pw_aff_scale_down(aff1
, v
);
739 if (name
== "floord")
740 aff1
= isl_pw_aff_floor(aff1
);
742 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 * The new parameter is resolved in resolve_nested.
759 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
766 if (!nesting_enabled
) {
771 id
= isl_id_alloc(ctx
, NULL
, expr
);
772 dim
= isl_space_params_alloc(ctx
, 1);
774 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
776 dom
= isl_set_universe(isl_space_copy(dim
));
777 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
778 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
780 return isl_pw_aff_alloc(dom
, aff
);
783 /* Affine expressions are not supposed to contain array accesses,
784 * but if nesting is allowed, we return a parameter corresponding
785 * to the array access.
787 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
789 return nested_access(expr
);
792 /* Extract an affine expression from a conditional operation.
794 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
796 isl_pw_aff
*cond
, *lhs
, *rhs
, *res
;
798 cond
= extract_condition(expr
->getCond());
799 lhs
= extract_affine(expr
->getTrueExpr());
800 rhs
= extract_affine(expr
->getFalseExpr());
802 return isl_pw_aff_cond(cond
, lhs
, rhs
);
805 /* Extract an affine expression, if possible, from "expr".
806 * Otherwise return NULL.
808 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
810 switch (expr
->getStmtClass()) {
811 case Stmt::ImplicitCastExprClass
:
812 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
813 case Stmt::IntegerLiteralClass
:
814 return extract_affine(cast
<IntegerLiteral
>(expr
));
815 case Stmt::DeclRefExprClass
:
816 return extract_affine(cast
<DeclRefExpr
>(expr
));
817 case Stmt::BinaryOperatorClass
:
818 return extract_affine(cast
<BinaryOperator
>(expr
));
819 case Stmt::UnaryOperatorClass
:
820 return extract_affine(cast
<UnaryOperator
>(expr
));
821 case Stmt::ParenExprClass
:
822 return extract_affine(cast
<ParenExpr
>(expr
));
823 case Stmt::CallExprClass
:
824 return extract_affine(cast
<CallExpr
>(expr
));
825 case Stmt::ArraySubscriptExprClass
:
826 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
827 case Stmt::ConditionalOperatorClass
:
828 return extract_affine(cast
<ConditionalOperator
>(expr
));
835 __isl_give isl_map
*PetScan::extract_access(ImplicitCastExpr
*expr
)
837 return extract_access(expr
->getSubExpr());
840 /* Return the depth of an array of the given type.
842 static int array_depth(const Type
*type
)
844 if (type
->isPointerType())
845 return 1 + array_depth(type
->getPointeeType().getTypePtr());
846 if (type
->isArrayType()) {
847 const ArrayType
*atype
;
848 type
= type
->getCanonicalTypeInternal().getTypePtr();
849 atype
= cast
<ArrayType
>(type
);
850 return 1 + array_depth(atype
->getElementType().getTypePtr());
855 /* Return the element type of the given array type.
857 static QualType
base_type(QualType qt
)
859 const Type
*type
= qt
.getTypePtr();
861 if (type
->isPointerType())
862 return base_type(type
->getPointeeType());
863 if (type
->isArrayType()) {
864 const ArrayType
*atype
;
865 type
= type
->getCanonicalTypeInternal().getTypePtr();
866 atype
= cast
<ArrayType
>(type
);
867 return base_type(atype
->getElementType());
872 /* Extract an access relation from a reference to a variable.
873 * If the variable has name "A" and its type corresponds to an
874 * array of depth d, then the returned access relation is of the
877 * { [] -> A[i_1,...,i_d] }
879 __isl_give isl_map
*PetScan::extract_access(DeclRefExpr
*expr
)
881 ValueDecl
*decl
= expr
->getDecl();
882 int depth
= array_depth(decl
->getType().getTypePtr());
883 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
884 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, depth
);
887 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
889 access_rel
= isl_map_universe(dim
);
894 /* Extract an access relation from an integer contant.
895 * If the value of the constant is "v", then the returned access relation
900 __isl_give isl_map
*PetScan::extract_access(IntegerLiteral
*expr
)
902 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr
)));
905 /* Try and extract an access relation from the given Expr.
906 * Return NULL if it doesn't work out.
908 __isl_give isl_map
*PetScan::extract_access(Expr
*expr
)
910 switch (expr
->getStmtClass()) {
911 case Stmt::ImplicitCastExprClass
:
912 return extract_access(cast
<ImplicitCastExpr
>(expr
));
913 case Stmt::DeclRefExprClass
:
914 return extract_access(cast
<DeclRefExpr
>(expr
));
915 case Stmt::ArraySubscriptExprClass
:
916 return extract_access(cast
<ArraySubscriptExpr
>(expr
));
923 /* Assign the affine expression "index" to the output dimension "pos" of "map"
924 * and return the result.
926 __isl_give isl_map
*set_index(__isl_take isl_map
*map
, int pos
,
927 __isl_take isl_pw_aff
*index
)
930 int len
= isl_map_dim(map
, isl_dim_out
);
933 index_map
= isl_map_from_range(isl_set_from_pw_aff(index
));
934 index_map
= isl_map_insert_dims(index_map
, isl_dim_out
, 0, pos
);
935 index_map
= isl_map_add_dims(index_map
, isl_dim_out
, len
- pos
- 1);
936 id
= isl_map_get_tuple_id(map
, isl_dim_out
);
937 index_map
= isl_map_set_tuple_id(index_map
, isl_dim_out
, id
);
939 map
= isl_map_intersect(map
, index_map
);
944 /* Extract an access relation from the given array subscript expression.
945 * If nesting is allowed in general, then we turn it on while
946 * examining the index expression.
948 * We first extract an access relation from the base.
949 * This will result in an access relation with a range that corresponds
950 * to the array being accessed and with earlier indices filled in already.
951 * We then extract the current index and fill that in as well.
952 * The position of the current index is based on the type of base.
953 * If base is the actual array variable, then the depth of this type
954 * will be the same as the depth of the array and we will fill in
955 * the first array index.
956 * Otherwise, the depth of the base type will be smaller and we will fill
959 __isl_give isl_map
*PetScan::extract_access(ArraySubscriptExpr
*expr
)
961 Expr
*base
= expr
->getBase();
962 Expr
*idx
= expr
->getIdx();
964 isl_map
*base_access
;
966 int depth
= array_depth(base
->getType().getTypePtr());
968 bool save_nesting
= nesting_enabled
;
970 nesting_enabled
= allow_nested
;
972 base_access
= extract_access(base
);
973 index
= extract_affine(idx
);
975 nesting_enabled
= save_nesting
;
977 pos
= isl_map_dim(base_access
, isl_dim_out
) - depth
;
978 access
= set_index(base_access
, pos
, index
);
983 /* Check if "expr" calls function "minmax" with two arguments and if so
984 * make lhs and rhs refer to these two arguments.
986 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
992 if (expr
->getStmtClass() != Stmt::CallExprClass
)
995 call
= cast
<CallExpr
>(expr
);
996 fd
= call
->getDirectCallee();
1000 if (call
->getNumArgs() != 2)
1003 name
= fd
->getDeclName().getAsString();
1007 lhs
= call
->getArg(0);
1008 rhs
= call
->getArg(1);
1013 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1014 * lhs and rhs refer to the two arguments.
1016 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1018 return is_minmax(expr
, "min", lhs
, rhs
);
1021 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1022 * lhs and rhs refer to the two arguments.
1024 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1026 return is_minmax(expr
, "max", lhs
, rhs
);
1029 /* Return "lhs && rhs", defined on the shared definition domain.
1031 static __isl_give isl_pw_aff
*pw_aff_and(__isl_take isl_pw_aff
*lhs
,
1032 __isl_take isl_pw_aff
*rhs
)
1037 dom
= isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs
)),
1038 isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1039 cond
= isl_set_intersect(isl_pw_aff_non_zero_set(lhs
),
1040 isl_pw_aff_non_zero_set(rhs
));
1041 return indicator_function(cond
, dom
);
1044 /* Return "lhs && rhs", with shortcut semantics.
1045 * That is, if lhs is false, then the result is defined even if rhs is not.
1046 * In practice, we compute lhs ? rhs : lhs.
1048 static __isl_give isl_pw_aff
*pw_aff_and_then(__isl_take isl_pw_aff
*lhs
,
1049 __isl_take isl_pw_aff
*rhs
)
1051 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), rhs
, lhs
);
1054 /* Return "lhs || rhs", with shortcut semantics.
1055 * That is, if lhs is true, then the result is defined even if rhs is not.
1056 * In practice, we compute lhs ? lhs : rhs.
1058 static __isl_give isl_pw_aff
*pw_aff_or_else(__isl_take isl_pw_aff
*lhs
,
1059 __isl_take isl_pw_aff
*rhs
)
1061 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), lhs
, rhs
);
1064 /* Extract an affine expressions representing the comparison "LHS op RHS"
1065 * "comp" is the original statement that "LHS op RHS" is derived from
1066 * and is used for diagnostics.
1068 * If the comparison is of the form
1072 * then the expression is constructed as the conjunction of
1077 * A similar optimization is performed for max(a,b) <= c.
1078 * We do this because that will lead to simpler representations
1079 * of the expression.
1080 * If isl is ever enhanced to explicitly deal with min and max expressions,
1081 * this optimization can be removed.
1083 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
1084 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
1093 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
1095 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
1097 if (op
== BO_LT
|| op
== BO_LE
) {
1098 Expr
*expr1
, *expr2
;
1099 if (is_min(RHS
, expr1
, expr2
)) {
1100 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
1101 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
1102 return pw_aff_and(lhs
, rhs
);
1104 if (is_max(LHS
, expr1
, expr2
)) {
1105 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
1106 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
1107 return pw_aff_and(lhs
, rhs
);
1111 lhs
= extract_affine(LHS
);
1112 rhs
= extract_affine(RHS
);
1114 dom
= isl_pw_aff_domain(isl_pw_aff_copy(lhs
));
1115 dom
= isl_set_intersect(dom
, isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1119 cond
= isl_pw_aff_lt_set(lhs
, rhs
);
1122 cond
= isl_pw_aff_le_set(lhs
, rhs
);
1125 cond
= isl_pw_aff_eq_set(lhs
, rhs
);
1128 cond
= isl_pw_aff_ne_set(lhs
, rhs
);
1131 isl_pw_aff_free(lhs
);
1132 isl_pw_aff_free(rhs
);
1138 cond
= isl_set_coalesce(cond
);
1139 res
= indicator_function(cond
, dom
);
1144 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
1146 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1147 comp
->getRHS(), comp
);
1150 /* Extract an affine expression representing the negation (logical not)
1151 * of a subexpression.
1153 __isl_give isl_pw_aff
*PetScan::extract_boolean(UnaryOperator
*op
)
1155 isl_set
*set_cond
, *dom
;
1156 isl_pw_aff
*cond
, *res
;
1158 cond
= extract_condition(op
->getSubExpr());
1160 dom
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
1162 set_cond
= isl_pw_aff_zero_set(cond
);
1164 res
= indicator_function(set_cond
, dom
);
1169 /* Extract an affine expression representing the disjunction (logical or)
1170 * or conjunction (logical and) of two subexpressions.
1172 __isl_give isl_pw_aff
*PetScan::extract_boolean(BinaryOperator
*comp
)
1174 isl_pw_aff
*lhs
, *rhs
;
1176 lhs
= extract_condition(comp
->getLHS());
1177 rhs
= extract_condition(comp
->getRHS());
1179 switch (comp
->getOpcode()) {
1181 return pw_aff_and_then(lhs
, rhs
);
1183 return pw_aff_or_else(lhs
, rhs
);
1185 isl_pw_aff_free(lhs
);
1186 isl_pw_aff_free(rhs
);
1193 __isl_give isl_pw_aff
*PetScan::extract_condition(UnaryOperator
*expr
)
1195 switch (expr
->getOpcode()) {
1197 return extract_boolean(expr
);
1204 /* Extract the affine expression "expr != 0 ? 1 : 0".
1206 __isl_give isl_pw_aff
*PetScan::extract_implicit_condition(Expr
*expr
)
1211 res
= extract_affine(expr
);
1213 dom
= isl_pw_aff_domain(isl_pw_aff_copy(res
));
1214 set
= isl_pw_aff_non_zero_set(res
);
1216 res
= indicator_function(set
, dom
);
1221 /* Extract an affine expression from a boolean expression.
1222 * In particular, return the expression "expr ? 1 : 0".
1224 * If the expression doesn't look like a condition, we assume it
1225 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1227 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
1229 BinaryOperator
*comp
;
1232 isl_set
*u
= isl_set_universe(isl_space_params_alloc(ctx
, 0));
1233 return indicator_function(u
, isl_set_copy(u
));
1236 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1237 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1239 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1240 return extract_condition(cast
<UnaryOperator
>(expr
));
1242 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1243 return extract_implicit_condition(expr
);
1245 comp
= cast
<BinaryOperator
>(expr
);
1246 switch (comp
->getOpcode()) {
1253 return extract_comparison(comp
);
1256 return extract_boolean(comp
);
1258 return extract_implicit_condition(expr
);
1262 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
1266 return pet_op_minus
;
1272 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
1276 return pet_op_add_assign
;
1278 return pet_op_sub_assign
;
1280 return pet_op_mul_assign
;
1282 return pet_op_div_assign
;
1284 return pet_op_assign
;
1306 /* Construct a pet_expr representing a unary operator expression.
1308 struct pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1310 struct pet_expr
*arg
;
1311 enum pet_op_type op
;
1313 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1314 if (op
== pet_op_last
) {
1319 arg
= extract_expr(expr
->getSubExpr());
1321 return pet_expr_new_unary(ctx
, op
, arg
);
1324 /* Mark the given access pet_expr as a write.
1325 * If a scalar is being accessed, then mark its value
1326 * as unknown in assigned_value.
1328 void PetScan::mark_write(struct pet_expr
*access
)
1333 access
->acc
.write
= 1;
1334 access
->acc
.read
= 0;
1336 if (isl_map_dim(access
->acc
.access
, isl_dim_out
) != 0)
1339 id
= isl_map_get_tuple_id(access
->acc
.access
, isl_dim_out
);
1340 decl
= (ValueDecl
*) isl_id_get_user(id
);
1341 clear_assignment(assigned_value
, decl
);
1345 /* Construct a pet_expr representing a binary operator expression.
1347 * If the top level operator is an assignment and the LHS is an access,
1348 * then we mark that access as a write. If the operator is a compound
1349 * assignment, the access is marked as both a read and a write.
1351 * If "expr" assigns something to a scalar variable, then we mark
1352 * the variable as having been assigned. If, furthermore, the expression
1353 * is affine, then keep track of this value in assigned_value
1354 * so that we can plug it in when we later come across the same variable.
1356 struct pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1358 struct pet_expr
*lhs
, *rhs
;
1359 enum pet_op_type op
;
1361 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1362 if (op
== pet_op_last
) {
1367 lhs
= extract_expr(expr
->getLHS());
1368 rhs
= extract_expr(expr
->getRHS());
1370 if (expr
->isAssignmentOp() && lhs
&& lhs
->type
== pet_expr_access
) {
1372 if (expr
->isCompoundAssignmentOp())
1376 if (expr
->getOpcode() == BO_Assign
&&
1377 lhs
&& lhs
->type
== pet_expr_access
&&
1378 isl_map_dim(lhs
->acc
.access
, isl_dim_out
) == 0) {
1379 isl_id
*id
= isl_map_get_tuple_id(lhs
->acc
.access
, isl_dim_out
);
1380 ValueDecl
*decl
= (ValueDecl
*) isl_id_get_user(id
);
1381 Expr
*rhs
= expr
->getRHS();
1382 isl_pw_aff
*pa
= try_extract_affine(rhs
);
1383 clear_assignment(assigned_value
, decl
);
1385 assigned_value
[decl
] = pa
;
1386 insert_expression(pa
);
1391 return pet_expr_new_binary(ctx
, op
, lhs
, rhs
);
1394 /* Construct a pet_expr representing a conditional operation.
1396 * We first try to extract the condition as an affine expression.
1397 * If that fails, we construct a pet_expr tree representing the condition.
1399 struct pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1401 struct pet_expr
*cond
, *lhs
, *rhs
;
1404 pa
= try_extract_affine(expr
->getCond());
1406 isl_set
*test
= isl_set_from_pw_aff(pa
);
1407 cond
= pet_expr_from_access(isl_map_from_range(test
));
1409 cond
= extract_expr(expr
->getCond());
1410 lhs
= extract_expr(expr
->getTrueExpr());
1411 rhs
= extract_expr(expr
->getFalseExpr());
1413 return pet_expr_new_ternary(ctx
, cond
, lhs
, rhs
);
1416 struct pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1418 return extract_expr(expr
->getSubExpr());
1421 /* Construct a pet_expr representing a floating point value.
1423 struct pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1425 return pet_expr_new_double(ctx
, expr
->getValueAsApproximateDouble());
1428 /* Extract an access relation from "expr" and then convert it into
1431 struct pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1434 struct pet_expr
*pe
;
1436 switch (expr
->getStmtClass()) {
1437 case Stmt::ArraySubscriptExprClass
:
1438 access
= extract_access(cast
<ArraySubscriptExpr
>(expr
));
1440 case Stmt::DeclRefExprClass
:
1441 access
= extract_access(cast
<DeclRefExpr
>(expr
));
1443 case Stmt::IntegerLiteralClass
:
1444 access
= extract_access(cast
<IntegerLiteral
>(expr
));
1451 pe
= pet_expr_from_access(access
);
1456 struct pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1458 return extract_expr(expr
->getSubExpr());
1461 /* Construct a pet_expr representing a function call.
1463 * If we are passing along a pointer to an array element
1464 * or an entire row or even higher dimensional slice of an array,
1465 * then the function being called may write into the array.
1467 * We assume here that if the function is declared to take a pointer
1468 * to a const type, then the function will perform a read
1469 * and that otherwise, it will perform a write.
1471 struct pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1473 struct pet_expr
*res
= NULL
;
1477 fd
= expr
->getDirectCallee();
1483 name
= fd
->getDeclName().getAsString();
1484 res
= pet_expr_new_call(ctx
, name
.c_str(), expr
->getNumArgs());
1488 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
1489 Expr
*arg
= expr
->getArg(i
);
1493 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1494 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(arg
);
1495 arg
= ice
->getSubExpr();
1497 if (arg
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1498 UnaryOperator
*op
= cast
<UnaryOperator
>(arg
);
1499 if (op
->getOpcode() == UO_AddrOf
) {
1501 arg
= op
->getSubExpr();
1504 res
->args
[i
] = PetScan::extract_expr(arg
);
1505 main_arg
= res
->args
[i
];
1507 res
->args
[i
] = pet_expr_new_unary(ctx
,
1508 pet_op_address_of
, res
->args
[i
]);
1511 if (arg
->getStmtClass() == Stmt::ArraySubscriptExprClass
&&
1512 array_depth(arg
->getType().getTypePtr()) > 0)
1514 if (is_addr
&& main_arg
->type
== pet_expr_access
) {
1516 if (!fd
->hasPrototype()) {
1517 unsupported(expr
, "prototype required");
1520 parm
= fd
->getParamDecl(i
);
1521 if (!const_base(parm
->getType()))
1522 mark_write(main_arg
);
1532 /* Try and onstruct a pet_expr representing "expr".
1534 struct pet_expr
*PetScan::extract_expr(Expr
*expr
)
1536 switch (expr
->getStmtClass()) {
1537 case Stmt::UnaryOperatorClass
:
1538 return extract_expr(cast
<UnaryOperator
>(expr
));
1539 case Stmt::CompoundAssignOperatorClass
:
1540 case Stmt::BinaryOperatorClass
:
1541 return extract_expr(cast
<BinaryOperator
>(expr
));
1542 case Stmt::ImplicitCastExprClass
:
1543 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1544 case Stmt::ArraySubscriptExprClass
:
1545 case Stmt::DeclRefExprClass
:
1546 case Stmt::IntegerLiteralClass
:
1547 return extract_access_expr(expr
);
1548 case Stmt::FloatingLiteralClass
:
1549 return extract_expr(cast
<FloatingLiteral
>(expr
));
1550 case Stmt::ParenExprClass
:
1551 return extract_expr(cast
<ParenExpr
>(expr
));
1552 case Stmt::ConditionalOperatorClass
:
1553 return extract_expr(cast
<ConditionalOperator
>(expr
));
1554 case Stmt::CallExprClass
:
1555 return extract_expr(cast
<CallExpr
>(expr
));
1562 /* Check if the given initialization statement is an assignment.
1563 * If so, return that assignment. Otherwise return NULL.
1565 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1567 BinaryOperator
*ass
;
1569 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1572 ass
= cast
<BinaryOperator
>(init
);
1573 if (ass
->getOpcode() != BO_Assign
)
1579 /* Check if the given initialization statement is a declaration
1580 * of a single variable.
1581 * If so, return that declaration. Otherwise return NULL.
1583 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1587 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1590 decl
= cast
<DeclStmt
>(init
);
1592 if (!decl
->isSingleDecl())
1595 return decl
->getSingleDecl();
1598 /* Given the assignment operator in the initialization of a for loop,
1599 * extract the induction variable, i.e., the (integer)variable being
1602 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1609 lhs
= init
->getLHS();
1610 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1615 ref
= cast
<DeclRefExpr
>(lhs
);
1616 decl
= ref
->getDecl();
1617 type
= decl
->getType().getTypePtr();
1619 if (!type
->isIntegerType()) {
1627 /* Given the initialization statement of a for loop and the single
1628 * declaration in this initialization statement,
1629 * extract the induction variable, i.e., the (integer) variable being
1632 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1636 vd
= cast
<VarDecl
>(decl
);
1638 const QualType type
= vd
->getType();
1639 if (!type
->isIntegerType()) {
1644 if (!vd
->getInit()) {
1652 /* Check that op is of the form iv++ or iv--.
1653 * Return an affine expression "1" or "-1" accordingly.
1655 __isl_give isl_pw_aff
*PetScan::extract_unary_increment(
1656 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1663 if (!op
->isIncrementDecrementOp()) {
1668 sub
= op
->getSubExpr();
1669 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1674 ref
= cast
<DeclRefExpr
>(sub
);
1675 if (ref
->getDecl() != iv
) {
1680 space
= isl_space_params_alloc(ctx
, 0);
1681 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
1683 if (op
->isIncrementOp())
1684 aff
= isl_aff_add_constant_si(aff
, 1);
1686 aff
= isl_aff_add_constant_si(aff
, -1);
1688 return isl_pw_aff_from_aff(aff
);
1691 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1692 * has a single constant expression, then put this constant in *user.
1693 * The caller is assumed to have checked that this function will
1694 * be called exactly once.
1696 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
1699 isl_int
*inc
= (isl_int
*)user
;
1702 if (isl_aff_is_cst(aff
))
1703 isl_aff_get_constant(aff
, inc
);
1713 /* Check if op is of the form
1717 * and return inc as an affine expression.
1719 * We extract an affine expression from the RHS, subtract iv and return
1722 __isl_give isl_pw_aff
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1723 clang::ValueDecl
*iv
)
1732 if (op
->getOpcode() != BO_Assign
) {
1738 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1743 ref
= cast
<DeclRefExpr
>(lhs
);
1744 if (ref
->getDecl() != iv
) {
1749 val
= extract_affine(op
->getRHS());
1751 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1753 dim
= isl_space_params_alloc(ctx
, 1);
1754 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1755 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1756 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1758 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
1763 /* Check that op is of the form iv += cst or iv -= cst
1764 * and return an affine expression corresponding oto cst or -cst accordingly.
1766 __isl_give isl_pw_aff
*PetScan::extract_compound_increment(
1767 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1773 BinaryOperatorKind opcode
;
1775 opcode
= op
->getOpcode();
1776 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1780 if (opcode
== BO_SubAssign
)
1784 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1789 ref
= cast
<DeclRefExpr
>(lhs
);
1790 if (ref
->getDecl() != iv
) {
1795 val
= extract_affine(op
->getRHS());
1797 val
= isl_pw_aff_neg(val
);
1802 /* Check that the increment of the given for loop increments
1803 * (or decrements) the induction variable "iv" and return
1804 * the increment as an affine expression if successful.
1806 __isl_give isl_pw_aff
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1809 Stmt
*inc
= stmt
->getInc();
1816 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1817 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1818 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1819 return extract_compound_increment(
1820 cast
<CompoundAssignOperator
>(inc
), iv
);
1821 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1822 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1828 /* Embed the given iteration domain in an extra outer loop
1829 * with induction variable "var".
1830 * If this variable appeared as a parameter in the constraints,
1831 * it is replaced by the new outermost dimension.
1833 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1834 __isl_take isl_id
*var
)
1838 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1839 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1841 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1842 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1849 /* Construct a pet_scop for an infinite loop around the given body.
1851 * We extract a pet_scop for the body and then embed it in a loop with
1860 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
1866 struct pet_scop
*scop
;
1868 scop
= extract(body
);
1872 id
= isl_id_alloc(ctx
, "t", NULL
);
1873 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
1874 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
1875 dim
= isl_space_from_domain(isl_set_get_space(domain
));
1876 dim
= isl_space_add_dims(dim
, isl_dim_out
, 1);
1877 sched
= isl_map_universe(dim
);
1878 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
1879 scop
= pet_scop_embed(scop
, domain
, sched
, id
);
1884 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1890 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
1892 return extract_infinite_loop(stmt
->getBody());
1895 /* Check if the while loop is of the form
1900 * If so, construct a scop for an infinite loop around body.
1903 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
1909 cond
= stmt
->getCond();
1915 set
= isl_pw_aff_non_zero_set(extract_condition(cond
));
1916 is_universe
= isl_set_plain_is_universe(set
);
1924 return extract_infinite_loop(stmt
->getBody());
1927 /* Check whether "cond" expresses a simple loop bound
1928 * on the only set dimension.
1929 * In particular, if "up" is set then "cond" should contain only
1930 * upper bounds on the set dimension.
1931 * Otherwise, it should contain only lower bounds.
1933 static bool is_simple_bound(__isl_keep isl_set
*cond
, isl_int inc
)
1935 if (isl_int_is_pos(inc
))
1936 return !isl_set_dim_has_lower_bound(cond
, isl_dim_set
, 0);
1938 return !isl_set_dim_has_upper_bound(cond
, isl_dim_set
, 0);
1941 /* Extend a condition on a given iteration of a loop to one that
1942 * imposes the same condition on all previous iterations.
1943 * "domain" expresses the lower [upper] bound on the iterations
1944 * when inc is positive [negative].
1946 * In particular, we construct the condition (when inc is positive)
1948 * forall i' : (domain(i') and i' <= i) => cond(i')
1950 * which is equivalent to
1952 * not exists i' : domain(i') and i' <= i and not cond(i')
1954 * We construct this set by negating cond, applying a map
1956 * { [i'] -> [i] : domain(i') and i' <= i }
1958 * and then negating the result again.
1960 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
1961 __isl_take isl_set
*domain
, isl_int inc
)
1963 isl_map
*previous_to_this
;
1965 if (isl_int_is_pos(inc
))
1966 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
1968 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
1970 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
1972 cond
= isl_set_complement(cond
);
1973 cond
= isl_set_apply(cond
, previous_to_this
);
1974 cond
= isl_set_complement(cond
);
1979 /* Construct a domain of the form
1981 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
1983 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
1984 __isl_take isl_pw_aff
*init
, isl_int inc
)
1990 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
1991 dim
= isl_pw_aff_get_domain_space(init
);
1992 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1993 aff
= isl_aff_add_coefficient(aff
, isl_dim_in
, 0, inc
);
1994 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
1996 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
1997 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1998 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1999 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2001 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2003 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2005 return isl_set_params(set
);
2008 /* Assuming "cond" represents a bound on a loop where the loop
2009 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2012 * Under the given assumptions, wrapping is only possible if "cond" allows
2013 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2014 * increasing iterator and 0 in case of a decreasing iterator.
2016 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
, isl_int inc
)
2022 test
= isl_set_copy(cond
);
2024 isl_int_init(limit
);
2025 if (isl_int_is_neg(inc
))
2026 isl_int_set_si(limit
, 0);
2028 isl_int_set_si(limit
, 1);
2029 isl_int_mul_2exp(limit
, limit
, get_type_size(iv
));
2030 isl_int_sub_ui(limit
, limit
, 1);
2033 test
= isl_set_fix(cond
, isl_dim_set
, 0, limit
);
2034 cw
= !isl_set_is_empty(test
);
2037 isl_int_clear(limit
);
2042 /* Given a one-dimensional space, construct the following mapping on this
2045 * { [v] -> [v mod 2^width] }
2047 * where width is the number of bits used to represent the values
2048 * of the unsigned variable "iv".
2050 static __isl_give isl_map
*compute_wrapping(__isl_take isl_space
*dim
,
2058 isl_int_set_si(mod
, 1);
2059 isl_int_mul_2exp(mod
, mod
, get_type_size(iv
));
2061 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2062 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2063 aff
= isl_aff_mod(aff
, mod
);
2067 return isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2068 map
= isl_map_reverse(map
);
2071 /* Project out the parameter "id" from "set".
2073 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2074 __isl_keep isl_id
*id
)
2078 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2080 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2085 /* Compute the set of parameters for which "set1" is a subset of "set2".
2087 * set1 is a subset of set2 if
2089 * forall i in set1 : i in set2
2093 * not exists i in set1 and i not in set2
2097 * not exists i in set1 \ set2
2099 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2100 __isl_take isl_set
*set2
)
2102 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2105 /* Compute the set of parameter values for which "cond" holds
2106 * on the next iteration for each element of "dom".
2108 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2109 * and then compute the set of parameters for which the result is a subset
2112 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2113 __isl_take isl_set
*dom
, isl_int inc
)
2119 space
= isl_set_get_space(dom
);
2120 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2121 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2122 aff
= isl_aff_add_constant(aff
, inc
);
2123 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2125 dom
= isl_set_apply(dom
, next
);
2127 return enforce_subset(dom
, cond
);
2130 /* Construct a pet_scop for a for statement.
2131 * The for loop is required to be of the form
2133 * for (i = init; condition; ++i)
2137 * for (i = init; condition; --i)
2139 * The initialization of the for loop should either be an assignment
2140 * to an integer variable, or a declaration of such a variable with
2143 * The condition is allowed to contain nested accesses, provided
2144 * they are not being written to inside the body of the loop.
2146 * We extract a pet_scop for the body and then embed it in a loop with
2147 * iteration domain and schedule
2149 * { [i] : i >= init and condition' }
2154 * { [i] : i <= init and condition' }
2157 * Where condition' is equal to condition if the latter is
2158 * a simple upper [lower] bound and a condition that is extended
2159 * to apply to all previous iterations otherwise.
2161 * If the stride of the loop is not 1, then "i >= init" is replaced by
2163 * (exists a: i = init + stride * a and a >= 0)
2165 * If the loop iterator i is unsigned, then wrapping may occur.
2166 * During the computation, we work with a virtual iterator that
2167 * does not wrap. However, the condition in the code applies
2168 * to the wrapped value, so we need to change condition(i)
2169 * into condition([i % 2^width]).
2170 * After computing the virtual domain and schedule, we apply
2171 * the function { [v] -> [v % 2^width] } to the domain and the domain
2172 * of the schedule. In order not to lose any information, we also
2173 * need to intersect the domain of the schedule with the virtual domain
2174 * first, since some iterations in the wrapped domain may be scheduled
2175 * several times, typically an infinite number of times.
2176 * Note that there is no need to perform this final wrapping
2177 * if the loop condition (after wrapping) is simple.
2179 * Wrapping on unsigned iterators can be avoided entirely if
2180 * loop condition is simple, the loop iterator is incremented
2181 * [decremented] by one and the last value before wrapping cannot
2182 * possibly satisfy the loop condition.
2184 * Before extracting a pet_scop from the body we remove all
2185 * assignments in assigned_value to variables that are assigned
2186 * somewhere in the body of the loop.
2188 * Valid parameters for a for loop are those for which the initial
2189 * value itself, the increment on each domain iteration and
2190 * the condition on both the initial value and
2191 * the result of incrementing the iterator for each iteration of the domain
2194 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2196 BinaryOperator
*ass
;
2204 isl_set
*cond
= NULL
;
2206 struct pet_scop
*scop
;
2207 assigned_value_cache
cache(assigned_value
);
2213 isl_map
*wrap
= NULL
;
2214 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2215 isl_set
*valid_init
;
2216 isl_set
*valid_cond
;
2217 isl_set
*valid_cond_init
;
2218 isl_set
*valid_cond_next
;
2221 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2222 return extract_infinite_for(stmt
);
2224 init
= stmt
->getInit();
2229 if ((ass
= initialization_assignment(init
)) != NULL
) {
2230 iv
= extract_induction_variable(ass
);
2233 lhs
= ass
->getLHS();
2234 rhs
= ass
->getRHS();
2235 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2236 VarDecl
*var
= extract_induction_variable(init
, decl
);
2240 rhs
= var
->getInit();
2241 lhs
= create_DeclRefExpr(var
);
2243 unsupported(stmt
->getInit());
2247 pa_inc
= extract_increment(stmt
, iv
);
2252 if (isl_pw_aff_n_piece(pa_inc
) != 1 ||
2253 isl_pw_aff_foreach_piece(pa_inc
, &extract_cst
, &inc
) < 0) {
2254 isl_pw_aff_free(pa_inc
);
2255 unsupported(stmt
->getInc());
2259 valid_inc
= isl_pw_aff_domain(pa_inc
);
2261 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2263 assigned_value
.erase(iv
);
2264 clear_assignments
clear(assigned_value
);
2265 clear
.TraverseStmt(stmt
->getBody());
2267 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
2269 scop
= extract(stmt
->getBody());
2271 pa
= try_extract_nested_condition(stmt
->getCond());
2272 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2273 isl_pw_aff_free(pa
);
2278 pa
= extract_condition(stmt
->getCond());
2279 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2280 cond
= isl_pw_aff_non_zero_set(pa
);
2281 cond
= embed(cond
, isl_id_copy(id
));
2282 valid_cond
= isl_set_coalesce(valid_cond
);
2283 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
2284 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
2285 is_one
= isl_int_is_one(inc
) || isl_int_is_negone(inc
);
2286 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2288 init_val
= extract_affine(rhs
);
2289 valid_cond_init
= enforce_subset(
2290 isl_set_from_pw_aff(isl_pw_aff_copy(init_val
)),
2291 isl_set_copy(valid_cond
));
2292 if (is_one
&& !is_virtual
) {
2293 isl_pw_aff_free(init_val
);
2294 pa
= extract_comparison(isl_int_is_pos(inc
) ? BO_GE
: BO_LE
,
2296 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2297 valid_init
= set_project_out_by_id(valid_init
, id
);
2298 domain
= isl_pw_aff_non_zero_set(pa
);
2300 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
2301 domain
= strided_domain(isl_id_copy(id
), init_val
, inc
);
2304 domain
= embed(domain
, isl_id_copy(id
));
2307 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2308 rev_wrap
= isl_map_reverse(isl_map_copy(wrap
));
2309 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
2310 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
2311 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
2313 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2314 is_simple
= is_simple_bound(cond
, inc
);
2316 cond
= valid_for_each_iteration(cond
,
2317 isl_set_copy(domain
), inc
);
2318 domain
= isl_set_intersect(domain
, cond
);
2319 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2320 dim
= isl_space_from_domain(isl_set_get_space(domain
));
2321 dim
= isl_space_add_dims(dim
, isl_dim_out
, 1);
2322 sched
= isl_map_universe(dim
);
2323 if (isl_int_is_pos(inc
))
2324 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2326 sched
= isl_map_oppose(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2328 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
), inc
);
2329 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
2331 if (is_virtual
&& !is_simple
) {
2332 wrap
= isl_map_set_dim_id(wrap
,
2333 isl_dim_out
, 0, isl_id_copy(id
));
2334 sched
= isl_map_intersect_domain(sched
, isl_set_copy(domain
));
2335 domain
= isl_set_apply(domain
, isl_map_copy(wrap
));
2336 sched
= isl_map_apply_domain(sched
, wrap
);
2340 scop
= pet_scop_embed(scop
, domain
, sched
, id
);
2341 scop
= resolve_nested(scop
);
2342 clear_assignment(assigned_value
, iv
);
2346 scop
= pet_scop_restrict_context(scop
, valid_init
);
2347 scop
= pet_scop_restrict_context(scop
, valid_inc
);
2348 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
2349 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
2354 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
)
2356 return extract(stmt
->children());
2359 /* Does "id" refer to a nested access?
2361 static bool is_nested_parameter(__isl_keep isl_id
*id
)
2363 return id
&& isl_id_get_user(id
) && !isl_id_get_name(id
);
2366 /* Does parameter "pos" of "space" refer to a nested access?
2368 static bool is_nested_parameter(__isl_keep isl_space
*space
, int pos
)
2373 id
= isl_space_get_dim_id(space
, isl_dim_param
, pos
);
2374 nested
= is_nested_parameter(id
);
2380 /* Does parameter "pos" of "map" refer to a nested access?
2382 static bool is_nested_parameter(__isl_keep isl_map
*map
, int pos
)
2387 id
= isl_map_get_dim_id(map
, isl_dim_param
, pos
);
2388 nested
= is_nested_parameter(id
);
2394 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2396 static int n_nested_parameter(__isl_keep isl_space
*space
)
2401 nparam
= isl_space_dim(space
, isl_dim_param
);
2402 for (int i
= 0; i
< nparam
; ++i
)
2403 if (is_nested_parameter(space
, i
))
2409 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2411 static int n_nested_parameter(__isl_keep isl_map
*map
)
2416 space
= isl_map_get_space(map
);
2417 n
= n_nested_parameter(space
);
2418 isl_space_free(space
);
2423 /* For each nested access parameter in "space",
2424 * construct a corresponding pet_expr, place it in args and
2425 * record its position in "param2pos".
2426 * "n_arg" is the number of elements that are already in args.
2427 * The position recorded in "param2pos" takes this number into account.
2428 * If the pet_expr corresponding to a parameter is identical to
2429 * the pet_expr corresponding to an earlier parameter, then these two
2430 * parameters are made to refer to the same element in args.
2432 * Return the final number of elements in args or -1 if an error has occurred.
2434 int PetScan::extract_nested(__isl_keep isl_space
*space
,
2435 int n_arg
, struct pet_expr
**args
, std::map
<int,int> ¶m2pos
)
2439 nparam
= isl_space_dim(space
, isl_dim_param
);
2440 for (int i
= 0; i
< nparam
; ++i
) {
2442 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2445 if (!is_nested_parameter(id
)) {
2450 nested
= (Expr
*) isl_id_get_user(id
);
2451 args
[n_arg
] = extract_expr(nested
);
2455 for (j
= 0; j
< n_arg
; ++j
)
2456 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
2460 pet_expr_free(args
[n_arg
]);
2464 param2pos
[i
] = n_arg
++;
2472 /* For each nested access parameter in the access relations in "expr",
2473 * construct a corresponding pet_expr, place it in expr->args and
2474 * record its position in "param2pos".
2475 * n is the number of nested access parameters.
2477 struct pet_expr
*PetScan::extract_nested(struct pet_expr
*expr
, int n
,
2478 std::map
<int,int> ¶m2pos
)
2482 expr
->args
= isl_calloc_array(ctx
, struct pet_expr
*, n
);
2487 space
= isl_map_get_space(expr
->acc
.access
);
2488 n
= extract_nested(space
, 0, expr
->args
, param2pos
);
2489 isl_space_free(space
);
2497 pet_expr_free(expr
);
2501 /* Look for parameters in any access relation in "expr" that
2502 * refer to nested accesses. In particular, these are
2503 * parameters with no name.
2505 * If there are any such parameters, then the domain of the access
2506 * relation, which is still [] at this point, is replaced by
2507 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2508 * (after identifying identical nested accesses).
2509 * The parameters are then equated to the corresponding t dimensions
2510 * and subsequently projected out.
2511 * param2pos maps the position of the parameter to the position
2512 * of the corresponding t dimension.
2514 struct pet_expr
*PetScan::resolve_nested(struct pet_expr
*expr
)
2521 std::map
<int,int> param2pos
;
2526 for (int i
= 0; i
< expr
->n_arg
; ++i
) {
2527 expr
->args
[i
] = resolve_nested(expr
->args
[i
]);
2528 if (!expr
->args
[i
]) {
2529 pet_expr_free(expr
);
2534 if (expr
->type
!= pet_expr_access
)
2537 n
= n_nested_parameter(expr
->acc
.access
);
2541 expr
= extract_nested(expr
, n
, param2pos
);
2546 nparam
= isl_map_dim(expr
->acc
.access
, isl_dim_param
);
2547 n_in
= isl_map_dim(expr
->acc
.access
, isl_dim_in
);
2548 dim
= isl_map_get_space(expr
->acc
.access
);
2549 dim
= isl_space_domain(dim
);
2550 dim
= isl_space_from_domain(dim
);
2551 dim
= isl_space_add_dims(dim
, isl_dim_out
, n
);
2552 map
= isl_map_universe(dim
);
2553 map
= isl_map_domain_map(map
);
2554 map
= isl_map_reverse(map
);
2555 expr
->acc
.access
= isl_map_apply_domain(expr
->acc
.access
, map
);
2557 for (int i
= nparam
- 1; i
>= 0; --i
) {
2558 isl_id
*id
= isl_map_get_dim_id(expr
->acc
.access
,
2560 if (!is_nested_parameter(id
)) {
2565 expr
->acc
.access
= isl_map_equate(expr
->acc
.access
,
2566 isl_dim_param
, i
, isl_dim_in
,
2567 n_in
+ param2pos
[i
]);
2568 expr
->acc
.access
= isl_map_project_out(expr
->acc
.access
,
2569 isl_dim_param
, i
, 1);
2576 pet_expr_free(expr
);
2580 /* Convert a top-level pet_expr to a pet_scop with one statement.
2581 * This mainly involves resolving nested expression parameters
2582 * and setting the name of the iteration space.
2583 * The name is given by "label" if it is non-NULL. Otherwise,
2584 * it is of the form S_<n_stmt>.
2586 struct pet_scop
*PetScan::extract(Stmt
*stmt
, struct pet_expr
*expr
,
2587 __isl_take isl_id
*label
)
2589 struct pet_stmt
*ps
;
2590 SourceLocation loc
= stmt
->getLocStart();
2591 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
2593 expr
= resolve_nested(expr
);
2594 ps
= pet_stmt_from_pet_expr(ctx
, line
, label
, n_stmt
++, expr
);
2595 return pet_scop_from_pet_stmt(ctx
, ps
);
2598 /* Check if we can extract an affine expression from "expr".
2599 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2600 * We turn on autodetection so that we won't generate any warnings
2601 * and turn off nesting, so that we won't accept any non-affine constructs.
2603 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
2606 int save_autodetect
= autodetect
;
2607 bool save_nesting
= nesting_enabled
;
2610 nesting_enabled
= false;
2612 pwaff
= extract_affine(expr
);
2614 autodetect
= save_autodetect
;
2615 nesting_enabled
= save_nesting
;
2620 /* Check whether "expr" is an affine expression.
2622 bool PetScan::is_affine(Expr
*expr
)
2626 pwaff
= try_extract_affine(expr
);
2627 isl_pw_aff_free(pwaff
);
2629 return pwaff
!= NULL
;
2632 /* Check whether "expr" is an affine constraint.
2633 * We turn on autodetection so that we won't generate any warnings
2634 * and turn off nesting, so that we won't accept any non-affine constructs.
2636 bool PetScan::is_affine_condition(Expr
*expr
)
2639 int save_autodetect
= autodetect
;
2640 bool save_nesting
= nesting_enabled
;
2643 nesting_enabled
= false;
2645 cond
= extract_condition(expr
);
2646 isl_pw_aff_free(cond
);
2648 autodetect
= save_autodetect
;
2649 nesting_enabled
= save_nesting
;
2651 return cond
!= NULL
;
2654 /* Check if we can extract a condition from "expr".
2655 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
2656 * If allow_nested is set, then the condition may involve parameters
2657 * corresponding to nested accesses.
2658 * We turn on autodetection so that we won't generate any warnings.
2660 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
2663 int save_autodetect
= autodetect
;
2664 bool save_nesting
= nesting_enabled
;
2667 nesting_enabled
= allow_nested
;
2668 cond
= extract_condition(expr
);
2670 autodetect
= save_autodetect
;
2671 nesting_enabled
= save_nesting
;
2676 /* If the top-level expression of "stmt" is an assignment, then
2677 * return that assignment as a BinaryOperator.
2678 * Otherwise return NULL.
2680 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
2682 BinaryOperator
*ass
;
2686 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
2689 ass
= cast
<BinaryOperator
>(stmt
);
2690 if(ass
->getOpcode() != BO_Assign
)
2696 /* Check if the given if statement is a conditional assignement
2697 * with a non-affine condition. If so, construct a pet_scop
2698 * corresponding to this conditional assignment. Otherwise return NULL.
2700 * In particular we check if "stmt" is of the form
2707 * where a is some array or scalar access.
2708 * The constructed pet_scop then corresponds to the expression
2710 * a = condition ? f(...) : g(...)
2712 * All access relations in f(...) are intersected with condition
2713 * while all access relation in g(...) are intersected with the complement.
2715 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
2717 BinaryOperator
*ass_then
, *ass_else
;
2718 isl_map
*write_then
, *write_else
;
2719 isl_set
*cond
, *comp
;
2723 struct pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
2724 bool save_nesting
= nesting_enabled
;
2726 ass_then
= top_assignment_or_null(stmt
->getThen());
2727 ass_else
= top_assignment_or_null(stmt
->getElse());
2729 if (!ass_then
|| !ass_else
)
2732 if (is_affine_condition(stmt
->getCond()))
2735 write_then
= extract_access(ass_then
->getLHS());
2736 write_else
= extract_access(ass_else
->getLHS());
2738 equal
= isl_map_is_equal(write_then
, write_else
);
2739 isl_map_free(write_else
);
2740 if (equal
< 0 || !equal
) {
2741 isl_map_free(write_then
);
2745 nesting_enabled
= allow_nested
;
2746 pa
= extract_condition(stmt
->getCond());
2747 nesting_enabled
= save_nesting
;
2748 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
2749 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
2750 map
= isl_map_from_range(isl_set_from_pw_aff(pa
));
2752 pe_cond
= pet_expr_from_access(map
);
2754 pe_then
= extract_expr(ass_then
->getRHS());
2755 pe_then
= pet_expr_restrict(pe_then
, cond
);
2756 pe_else
= extract_expr(ass_else
->getRHS());
2757 pe_else
= pet_expr_restrict(pe_else
, comp
);
2759 pe
= pet_expr_new_ternary(ctx
, pe_cond
, pe_then
, pe_else
);
2760 pe_write
= pet_expr_from_access(write_then
);
2762 pe_write
->acc
.write
= 1;
2763 pe_write
->acc
.read
= 0;
2765 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, pe_write
, pe
);
2766 return extract(stmt
, pe
);
2769 /* Create an access to a virtual array representing the result
2771 * Unlike other accessed data, the id of the array is NULL as
2772 * there is no ValueDecl in the program corresponding to the virtual
2774 * The array starts out as a scalar, but grows along with the
2775 * statement writing to the array in pet_scop_embed.
2777 static __isl_give isl_map
*create_test_access(isl_ctx
*ctx
, int test_nr
)
2779 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, 0);
2783 snprintf(name
, sizeof(name
), "__pet_test_%d", test_nr
);
2784 id
= isl_id_alloc(ctx
, name
, NULL
);
2785 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
2786 return isl_map_universe(dim
);
2789 /* Create a pet_scop with a single statement evaluating "cond"
2790 * and writing the result to a virtual scalar, as expressed by
2793 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
,
2794 __isl_take isl_map
*access
)
2796 struct pet_expr
*expr
, *write
;
2797 struct pet_stmt
*ps
;
2798 SourceLocation loc
= cond
->getLocStart();
2799 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
2801 write
= pet_expr_from_access(access
);
2803 write
->acc
.write
= 1;
2804 write
->acc
.read
= 0;
2806 expr
= extract_expr(cond
);
2807 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, write
, expr
);
2808 ps
= pet_stmt_from_pet_expr(ctx
, line
, NULL
, n_stmt
++, expr
);
2809 return pet_scop_from_pet_stmt(ctx
, ps
);
2812 /* Add an array with the given extent ("access") to the list
2813 * of arrays in "scop" and return the extended pet_scop.
2814 * The array is marked as attaining values 0 and 1 only.
2816 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2817 __isl_keep isl_map
*access
, clang::ASTContext
&ast_ctx
)
2819 isl_ctx
*ctx
= isl_map_get_ctx(access
);
2821 struct pet_array
**arrays
;
2822 struct pet_array
*array
;
2829 arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
2833 scop
->arrays
= arrays
;
2835 array
= isl_calloc_type(ctx
, struct pet_array
);
2839 array
->extent
= isl_map_range(isl_map_copy(access
));
2840 dim
= isl_space_params_alloc(ctx
, 0);
2841 array
->context
= isl_set_universe(dim
);
2842 dim
= isl_space_set_alloc(ctx
, 0, 1);
2843 array
->value_bounds
= isl_set_universe(dim
);
2844 array
->value_bounds
= isl_set_lower_bound_si(array
->value_bounds
,
2846 array
->value_bounds
= isl_set_upper_bound_si(array
->value_bounds
,
2848 array
->element_type
= strdup("int");
2849 array
->element_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
2851 scop
->arrays
[scop
->n_array
] = array
;
2854 if (!array
->extent
|| !array
->context
)
2859 pet_scop_free(scop
);
2864 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
,
2868 /* Apply the map pointed to by "user" to the domain of the access
2869 * relation, thereby embedding it in the range of the map.
2870 * The domain of both relations is the zero-dimensional domain.
2872 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
, void *user
)
2874 isl_map
*map
= (isl_map
*) user
;
2876 return isl_map_apply_domain(access
, isl_map_copy(map
));
2879 /* Apply "map" to all access relations in "expr".
2881 static struct pet_expr
*embed(struct pet_expr
*expr
, __isl_keep isl_map
*map
)
2883 return pet_expr_foreach_access(expr
, &embed_access
, map
);
2886 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2888 static int n_nested_parameter(__isl_keep isl_set
*set
)
2893 space
= isl_set_get_space(set
);
2894 n
= n_nested_parameter(space
);
2895 isl_space_free(space
);
2900 /* Remove all parameters from "map" that refer to nested accesses.
2902 static __isl_give isl_map
*remove_nested_parameters(__isl_take isl_map
*map
)
2907 space
= isl_map_get_space(map
);
2908 nparam
= isl_space_dim(space
, isl_dim_param
);
2909 for (int i
= nparam
- 1; i
>= 0; --i
)
2910 if (is_nested_parameter(space
, i
))
2911 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
2912 isl_space_free(space
);
2918 static __isl_give isl_map
*access_remove_nested_parameters(
2919 __isl_take isl_map
*access
, void *user
);
2922 static __isl_give isl_map
*access_remove_nested_parameters(
2923 __isl_take isl_map
*access
, void *user
)
2925 return remove_nested_parameters(access
);
2928 /* Remove all nested access parameters from the schedule and all
2929 * accesses of "stmt".
2930 * There is no need to remove them from the domain as these parameters
2931 * have already been removed from the domain when this function is called.
2933 static struct pet_stmt
*remove_nested_parameters(struct pet_stmt
*stmt
)
2937 stmt
->schedule
= remove_nested_parameters(stmt
->schedule
);
2938 stmt
->body
= pet_expr_foreach_access(stmt
->body
,
2939 &access_remove_nested_parameters
, NULL
);
2940 if (!stmt
->schedule
|| !stmt
->body
)
2942 for (int i
= 0; i
< stmt
->n_arg
; ++i
) {
2943 stmt
->args
[i
] = pet_expr_foreach_access(stmt
->args
[i
],
2944 &access_remove_nested_parameters
, NULL
);
2951 pet_stmt_free(stmt
);
2955 /* For each nested access parameter in the domain of "stmt",
2956 * construct a corresponding pet_expr, place it in stmt->args and
2957 * record its position in "param2pos".
2958 * n is the number of nested access parameters.
2960 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
2961 std::map
<int,int> ¶m2pos
)
2965 struct pet_expr
**args
;
2967 n_arg
= stmt
->n_arg
;
2968 args
= isl_realloc_array(ctx
, stmt
->args
, struct pet_expr
*, n_arg
+ n
);
2974 space
= isl_set_get_space(stmt
->domain
);
2975 n
= extract_nested(space
, n_arg
, stmt
->args
, param2pos
);
2976 isl_space_free(space
);
2984 pet_stmt_free(stmt
);
2988 /* Look for parameters in the iteration domain of "stmt" that
2989 * refer to nested accesses. In particular, these are
2990 * parameters with no name.
2992 * If there are any such parameters, then as many extra variables
2993 * (after identifying identical nested accesses) are added to the
2994 * range of the map wrapped inside the domain.
2995 * If the original domain is not a wrapped map, then a new wrapped
2996 * map is created with zero output dimensions.
2997 * The parameters are then equated to the corresponding output dimensions
2998 * and subsequently projected out, from the iteration domain,
2999 * the schedule and the access relations.
3000 * For each of the output dimensions, a corresponding argument
3001 * expression is added. Initially they are created with
3002 * a zero-dimensional domain, so they have to be embedded
3003 * in the current iteration domain.
3004 * param2pos maps the position of the parameter to the position
3005 * of the corresponding output dimension in the wrapped map.
3007 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3013 std::map
<int,int> param2pos
;
3018 n
= n_nested_parameter(stmt
->domain
);
3022 n_arg
= stmt
->n_arg
;
3023 stmt
= extract_nested(stmt
, n
, param2pos
);
3027 n
= stmt
->n_arg
- n_arg
;
3028 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3029 if (isl_set_is_wrapping(stmt
->domain
))
3030 map
= isl_set_unwrap(stmt
->domain
);
3032 map
= isl_map_from_domain(stmt
->domain
);
3033 map
= isl_map_add_dims(map
, isl_dim_out
, n
);
3035 for (int i
= nparam
- 1; i
>= 0; --i
) {
3038 if (!is_nested_parameter(map
, i
))
3041 id
= isl_map_get_tuple_id(stmt
->args
[param2pos
[i
]]->acc
.access
,
3043 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3044 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3046 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3049 stmt
->domain
= isl_map_wrap(map
);
3051 map
= isl_set_unwrap(isl_set_copy(stmt
->domain
));
3052 map
= isl_map_from_range(isl_map_domain(map
));
3053 for (int pos
= n_arg
; pos
< stmt
->n_arg
; ++pos
)
3054 stmt
->args
[pos
] = embed(stmt
->args
[pos
], map
);
3057 stmt
= remove_nested_parameters(stmt
);
3061 pet_stmt_free(stmt
);
3065 /* For each statement in "scop", move the parameters that correspond
3066 * to nested access into the ranges of the domains and create
3067 * corresponding argument expressions.
3069 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3074 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3075 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3076 if (!scop
->stmts
[i
])
3082 pet_scop_free(scop
);
3086 /* Does "space" involve any parameters that refer to nested
3087 * accesses, i.e., parameters with no name?
3089 static bool has_nested(__isl_keep isl_space
*space
)
3093 nparam
= isl_space_dim(space
, isl_dim_param
);
3094 for (int i
= 0; i
< nparam
; ++i
)
3095 if (is_nested_parameter(space
, i
))
3101 /* Does "pa" involve any parameters that refer to nested
3102 * accesses, i.e., parameters with no name?
3104 static bool has_nested(__isl_keep isl_pw_aff
*pa
)
3109 space
= isl_pw_aff_get_space(pa
);
3110 nested
= has_nested(space
);
3111 isl_space_free(space
);
3116 /* Given an access expression "expr", is the variable accessed by
3117 * "expr" assigned anywhere inside "scop"?
3119 static bool is_assigned(pet_expr
*expr
, pet_scop
*scop
)
3121 bool assigned
= false;
3124 id
= isl_map_get_tuple_id(expr
->acc
.access
, isl_dim_out
);
3125 assigned
= pet_scop_writes(scop
, id
);
3131 /* Are all nested access parameters in "pa" allowed given "scop".
3132 * In particular, is none of them written by anywhere inside "scop".
3134 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3138 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3139 for (int i
= 0; i
< nparam
; ++i
) {
3141 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3145 if (!is_nested_parameter(id
)) {
3150 nested
= (Expr
*) isl_id_get_user(id
);
3151 expr
= extract_expr(nested
);
3152 allowed
= expr
&& expr
->type
== pet_expr_access
&&
3153 !is_assigned(expr
, scop
);
3155 pet_expr_free(expr
);
3165 /* Construct a pet_scop for an if statement.
3167 * If the condition fits the pattern of a conditional assignment,
3168 * then it is handled by extract_conditional_assignment.
3169 * Otherwise, we do the following.
3171 * If the condition is affine, then the condition is added
3172 * to the iteration domains of the then branch, while the
3173 * opposite of the condition in added to the iteration domains
3174 * of the else branch, if any.
3175 * We allow the condition to be dynamic, i.e., to refer to
3176 * scalars or array elements that may be written to outside
3177 * of the given if statement. These nested accesses are then represented
3178 * as output dimensions in the wrapping iteration domain.
3179 * If it also written _inside_ the then or else branch, then
3180 * we treat the condition as non-affine.
3181 * As explained below, this will introduce an extra statement.
3182 * For aesthetic reasons, we want this statement to have a statement
3183 * number that is lower than those of the then and else branches.
3184 * In order to evaluate if will need such a statement, however, we
3185 * first construct scops for the then and else branches.
3186 * We therefore reserve a statement number if we might have to
3187 * introduce such an extra statement.
3189 * If the condition is not affine, then we create a separate
3190 * statement that writes the result of the condition to a virtual scalar.
3191 * A constraint requiring the value of this virtual scalar to be one
3192 * is added to the iteration domains of the then branch.
3193 * Similarly, a constraint requiring the value of this virtual scalar
3194 * to be zero is added to the iteration domains of the else branch, if any.
3195 * We adjust the schedules to ensure that the virtual scalar is written
3196 * before it is read.
3198 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
3200 struct pet_scop
*scop_then
, *scop_else
, *scop
;
3201 assigned_value_cache
cache(assigned_value
);
3202 isl_map
*test_access
= NULL
;
3206 scop
= extract_conditional_assignment(stmt
);
3210 cond
= try_extract_nested_condition(stmt
->getCond());
3211 if (allow_nested
&& (!cond
|| has_nested(cond
)))
3214 scop_then
= extract(stmt
->getThen());
3216 if (stmt
->getElse()) {
3217 scop_else
= extract(stmt
->getElse());
3219 if (scop_then
&& !scop_else
) {
3221 isl_pw_aff_free(cond
);
3224 if (!scop_then
&& scop_else
) {
3226 isl_pw_aff_free(cond
);
3233 (!is_nested_allowed(cond
, scop_then
) ||
3234 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
3235 isl_pw_aff_free(cond
);
3238 if (allow_nested
&& !cond
) {
3239 int save_n_stmt
= n_stmt
;
3240 test_access
= create_test_access(ctx
, n_test
++);
3242 scop
= extract_non_affine_condition(stmt
->getCond(),
3243 isl_map_copy(test_access
));
3244 n_stmt
= save_n_stmt
;
3245 scop
= scop_add_array(scop
, test_access
, ast_context
);
3247 pet_scop_free(scop_then
);
3248 pet_scop_free(scop_else
);
3249 isl_map_free(test_access
);
3259 cond
= extract_condition(stmt
->getCond());
3260 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
3261 set
= isl_pw_aff_non_zero_set(cond
);
3262 scop
= pet_scop_restrict(scop_then
, isl_set_copy(set
));
3264 if (stmt
->getElse()) {
3265 set
= isl_set_subtract(isl_set_copy(valid
), set
);
3266 scop_else
= pet_scop_restrict(scop_else
, set
);
3267 scop
= pet_scop_add(ctx
, scop
, scop_else
);
3270 scop
= resolve_nested(scop
);
3271 scop
= pet_scop_restrict_context(scop
, valid
);
3273 scop
= pet_scop_prefix(scop
, 0);
3274 scop_then
= pet_scop_prefix(scop_then
, 1);
3275 scop_then
= pet_scop_filter(scop_then
,
3276 isl_map_copy(test_access
), 1);
3277 scop
= pet_scop_add(ctx
, scop
, scop_then
);
3278 if (stmt
->getElse()) {
3279 scop_else
= pet_scop_prefix(scop_else
, 1);
3280 scop_else
= pet_scop_filter(scop_else
, test_access
, 0);
3281 scop
= pet_scop_add(ctx
, scop
, scop_else
);
3283 isl_map_free(test_access
);
3289 /* Try and construct a pet_scop for a label statement.
3290 * We currently only allow labels on expression statements.
3292 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
3297 sub
= stmt
->getSubStmt();
3298 if (!isa
<Expr
>(sub
)) {
3303 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
3305 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
3308 /* Try and construct a pet_scop corresponding to "stmt".
3310 struct pet_scop
*PetScan::extract(Stmt
*stmt
)
3312 if (isa
<Expr
>(stmt
))
3313 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
3315 switch (stmt
->getStmtClass()) {
3316 case Stmt::WhileStmtClass
:
3317 return extract(cast
<WhileStmt
>(stmt
));
3318 case Stmt::ForStmtClass
:
3319 return extract_for(cast
<ForStmt
>(stmt
));
3320 case Stmt::IfStmtClass
:
3321 return extract(cast
<IfStmt
>(stmt
));
3322 case Stmt::CompoundStmtClass
:
3323 return extract(cast
<CompoundStmt
>(stmt
));
3324 case Stmt::LabelStmtClass
:
3325 return extract(cast
<LabelStmt
>(stmt
));
3333 /* Try and construct a pet_scop corresponding to (part of)
3334 * a sequence of statements.
3336 struct pet_scop
*PetScan::extract(StmtRange stmt_range
)
3341 bool partial_range
= false;
3343 scop
= pet_scop_empty(ctx
);
3344 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
3346 struct pet_scop
*scop_i
;
3347 scop_i
= extract(child
);
3348 if (scop
&& partial
) {
3349 pet_scop_free(scop_i
);
3352 scop_i
= pet_scop_prefix(scop_i
, j
);
3355 scop
= pet_scop_add(ctx
, scop
, scop_i
);
3357 partial_range
= true;
3358 if (scop
->n_stmt
!= 0 && !scop_i
)
3361 scop
= pet_scop_add(ctx
, scop
, scop_i
);
3367 if (scop
&& partial_range
)
3373 /* Check if the scop marked by the user is exactly this Stmt
3374 * or part of this Stmt.
3375 * If so, return a pet_scop corresponding to the marked region.
3376 * Otherwise, return NULL.
3378 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
3380 SourceManager
&SM
= PP
.getSourceManager();
3381 unsigned start_off
, end_off
;
3383 start_off
= SM
.getFileOffset(stmt
->getLocStart());
3384 end_off
= SM
.getFileOffset(stmt
->getLocEnd());
3386 if (start_off
> loc
.end
)
3388 if (end_off
< loc
.start
)
3390 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
3391 return extract(stmt
);
3395 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
3396 Stmt
*child
= *start
;
3399 start_off
= SM
.getFileOffset(child
->getLocStart());
3400 end_off
= SM
.getFileOffset(child
->getLocEnd());
3401 if (start_off
< loc
.start
&& end_off
> loc
.end
)
3403 if (start_off
>= loc
.start
)
3408 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
3410 start_off
= SM
.getFileOffset(child
->getLocStart());
3411 if (start_off
>= loc
.end
)
3415 return extract(StmtRange(start
, end
));
3418 /* Set the size of index "pos" of "array" to "size".
3419 * In particular, add a constraint of the form
3423 * to array->extent and a constraint of the form
3427 * to array->context.
3429 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
3430 __isl_take isl_pw_aff
*size
)
3440 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
3441 array
->context
= isl_set_intersect(array
->context
, valid
);
3443 dim
= isl_set_get_space(array
->extent
);
3444 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
3445 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
3446 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
3447 index
= isl_pw_aff_alloc(univ
, aff
);
3449 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
3450 isl_set_dim(array
->extent
, isl_dim_set
));
3451 id
= isl_set_get_tuple_id(array
->extent
);
3452 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
3453 bound
= isl_pw_aff_lt_set(index
, size
);
3455 array
->extent
= isl_set_intersect(array
->extent
, bound
);
3457 if (!array
->context
|| !array
->extent
)
3462 pet_array_free(array
);
3466 /* Figure out the size of the array at position "pos" and all
3467 * subsequent positions from "type" and update "array" accordingly.
3469 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
3470 const Type
*type
, int pos
)
3472 const ArrayType
*atype
;
3478 if (type
->isPointerType()) {
3479 type
= type
->getPointeeType().getTypePtr();
3480 return set_upper_bounds(array
, type
, pos
+ 1);
3482 if (!type
->isArrayType())
3485 type
= type
->getCanonicalTypeInternal().getTypePtr();
3486 atype
= cast
<ArrayType
>(type
);
3488 if (type
->isConstantArrayType()) {
3489 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
3490 size
= extract_affine(ca
->getSize());
3491 array
= update_size(array
, pos
, size
);
3492 } else if (type
->isVariableArrayType()) {
3493 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
3494 size
= extract_affine(vla
->getSizeExpr());
3495 array
= update_size(array
, pos
, size
);
3498 type
= atype
->getElementType().getTypePtr();
3500 return set_upper_bounds(array
, type
, pos
+ 1);
3503 /* Construct and return a pet_array corresponding to the variable "decl".
3504 * In particular, initialize array->extent to
3506 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3508 * and then call set_upper_bounds to set the upper bounds on the indices
3509 * based on the type of the variable.
3511 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
)
3513 struct pet_array
*array
;
3514 QualType qt
= decl
->getType();
3515 const Type
*type
= qt
.getTypePtr();
3516 int depth
= array_depth(type
);
3517 QualType base
= base_type(qt
);
3522 array
= isl_calloc_type(ctx
, struct pet_array
);
3526 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
3527 dim
= isl_space_set_alloc(ctx
, 0, depth
);
3528 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
3530 array
->extent
= isl_set_nat_universe(dim
);
3532 dim
= isl_space_params_alloc(ctx
, 0);
3533 array
->context
= isl_set_universe(dim
);
3535 array
= set_upper_bounds(array
, type
, 0);
3539 name
= base
.getAsString();
3540 array
->element_type
= strdup(name
.c_str());
3541 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
3546 /* Construct a list of pet_arrays, one for each array (or scalar)
3547 * accessed inside "scop" add this list to "scop" and return the result.
3549 * The context of "scop" is updated with the intesection of
3550 * the contexts of all arrays, i.e., constraints on the parameters
3551 * that ensure that the arrays have a valid (non-negative) size.
3553 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
3556 set
<ValueDecl
*> arrays
;
3557 set
<ValueDecl
*>::iterator it
;
3559 struct pet_array
**scop_arrays
;
3564 pet_scop_collect_arrays(scop
, arrays
);
3565 if (arrays
.size() == 0)
3568 n_array
= scop
->n_array
;
3570 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
3571 n_array
+ arrays
.size());
3574 scop
->arrays
= scop_arrays
;
3576 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
3577 struct pet_array
*array
;
3578 scop
->arrays
[n_array
+ i
] = array
= extract_array(ctx
, *it
);
3579 if (!scop
->arrays
[n_array
+ i
])
3582 scop
->context
= isl_set_intersect(scop
->context
,
3583 isl_set_copy(array
->context
));
3590 pet_scop_free(scop
);
3594 /* Bound all parameters in scop->context to the possible values
3595 * of the corresponding C variable.
3597 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
3604 n
= isl_set_dim(scop
->context
, isl_dim_param
);
3605 for (int i
= 0; i
< n
; ++i
) {
3609 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
3610 decl
= (ValueDecl
*) isl_id_get_user(id
);
3613 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
3621 pet_scop_free(scop
);
3625 /* Construct a pet_scop from the given function.
3627 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
3632 stmt
= fd
->getBody();
3635 scop
= extract(stmt
);
3638 scop
= pet_scop_detect_parameter_accesses(scop
);
3639 scop
= scan_arrays(scop
);
3640 scop
= add_parameter_bounds(scop
);
3641 scop
= pet_scop_gist(scop
, value_bounds
);