2 * Copyright 2011 Leiden University. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following
13 * disclaimer in the documentation and/or other materials provided
14 * with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
20 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 * The views and conclusions contained in the software and documentation
29 * are those of the authors and should not be interpreted as
30 * representing official policies, either expressed or implied, of
37 #include <clang/AST/ASTDiagnostic.h>
38 #include <clang/AST/Expr.h>
39 #include <clang/AST/RecursiveASTVisitor.h>
42 #include <isl/space.h>
48 #include "scop_plus.h"
53 using namespace clang
;
55 #ifdef DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION
56 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
58 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
59 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
63 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
65 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
66 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
70 /* Check if the element type corresponding to the given array type
71 * has a const qualifier.
73 static bool const_base(QualType qt
)
75 const Type
*type
= qt
.getTypePtr();
77 if (type
->isPointerType())
78 return const_base(type
->getPointeeType());
79 if (type
->isArrayType()) {
80 const ArrayType
*atype
;
81 type
= type
->getCanonicalTypeInternal().getTypePtr();
82 atype
= cast
<ArrayType
>(type
);
83 return const_base(atype
->getElementType());
86 return qt
.isConstQualified();
89 /* Mark "decl" as having an unknown value in "assigned_value".
91 * If no (known or unknown) value was assigned to "decl" before,
92 * then it may have been treated as a parameter before and may
93 * therefore appear in a value assigned to another variable.
94 * If so, this assignment needs to be turned into an unknown value too.
96 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
99 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
101 it
= assigned_value
.find(decl
);
103 assigned_value
[decl
] = NULL
;
105 if (it
== assigned_value
.end())
108 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
109 isl_pw_aff
*pa
= it
->second
;
110 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
112 for (int i
= 0; i
< nparam
; ++i
) {
115 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
117 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
118 if (isl_id_get_user(id
) == decl
)
125 /* Look for any assignments to scalar variables in part of the parse
126 * tree and set assigned_value to NULL for each of them.
127 * Also reset assigned_value if the address of a scalar variable
128 * is being taken. As an exception, if the address is passed to a function
129 * that is declared to receive a const pointer, then assigned_value is
132 * This ensures that we won't use any previously stored value
133 * in the current subtree and its parents.
135 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
136 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
137 set
<UnaryOperator
*> skip
;
139 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
140 assigned_value(assigned_value
) {}
142 /* Check for "address of" operators whose value is passed
143 * to a const pointer argument and add them to "skip", so that
144 * we can skip them in VisitUnaryOperator.
146 bool VisitCallExpr(CallExpr
*expr
) {
148 fd
= expr
->getDirectCallee();
151 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
152 Expr
*arg
= expr
->getArg(i
);
154 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
155 ImplicitCastExpr
*ice
;
156 ice
= cast
<ImplicitCastExpr
>(arg
);
157 arg
= ice
->getSubExpr();
159 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
161 op
= cast
<UnaryOperator
>(arg
);
162 if (op
->getOpcode() != UO_AddrOf
)
164 if (const_base(fd
->getParamDecl(i
)->getType()))
170 bool VisitUnaryOperator(UnaryOperator
*expr
) {
175 if (expr
->getOpcode() != UO_AddrOf
)
177 if (skip
.find(expr
) != skip
.end())
180 arg
= expr
->getSubExpr();
181 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
183 ref
= cast
<DeclRefExpr
>(arg
);
184 decl
= ref
->getDecl();
185 clear_assignment(assigned_value
, decl
);
189 bool VisitBinaryOperator(BinaryOperator
*expr
) {
194 if (!expr
->isAssignmentOp())
196 lhs
= expr
->getLHS();
197 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
199 ref
= cast
<DeclRefExpr
>(lhs
);
200 decl
= ref
->getDecl();
201 clear_assignment(assigned_value
, decl
);
206 /* Keep a copy of the currently assigned values.
208 * Any variable that is assigned a value inside the current scope
209 * is removed again when we leave the scope (either because it wasn't
210 * stored in the cache or because it has a different value in the cache).
212 struct assigned_value_cache
{
213 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
214 map
<ValueDecl
*, isl_pw_aff
*> cache
;
216 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
217 assigned_value(assigned_value
), cache(assigned_value
) {}
218 ~assigned_value_cache() {
219 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
220 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
223 (cache
.find(it
->first
) != cache
.end() &&
224 cache
[it
->first
] != it
->second
))
225 cache
[it
->first
] = NULL
;
227 assigned_value
= cache
;
231 /* Insert an expression into the collection of expressions,
232 * provided it is not already in there.
233 * The isl_pw_affs are freed in the destructor.
235 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
237 std::set
<isl_pw_aff
*>::iterator it
;
239 if (expressions
.find(expr
) == expressions
.end())
240 expressions
.insert(expr
);
242 isl_pw_aff_free(expr
);
247 std::set
<isl_pw_aff
*>::iterator it
;
249 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
250 isl_pw_aff_free(*it
);
253 /* Called if we found something we (currently) cannot handle.
254 * We'll provide more informative warnings later.
256 * We only actually complain if autodetect is false.
258 void PetScan::unsupported(Stmt
*stmt
, const char *msg
)
263 SourceLocation loc
= stmt
->getLocStart();
264 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
265 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
266 msg
? msg
: "unsupported");
267 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
270 /* Extract an integer from "expr" and store it in "v".
272 int PetScan::extract_int(IntegerLiteral
*expr
, isl_int
*v
)
274 const Type
*type
= expr
->getType().getTypePtr();
275 int is_signed
= type
->hasSignedIntegerRepresentation();
278 int64_t i
= expr
->getValue().getSExtValue();
279 isl_int_set_si(*v
, i
);
281 uint64_t i
= expr
->getValue().getZExtValue();
282 isl_int_set_ui(*v
, i
);
288 /* Extract an integer from "expr" and store it in "v".
289 * Return -1 if "expr" does not (obviously) represent an integer.
291 int PetScan::extract_int(clang::ParenExpr
*expr
, isl_int
*v
)
293 return extract_int(expr
->getSubExpr(), v
);
296 /* Extract an integer from "expr" and store it in "v".
297 * Return -1 if "expr" does not (obviously) represent an integer.
299 int PetScan::extract_int(clang::Expr
*expr
, isl_int
*v
)
301 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
302 return extract_int(cast
<IntegerLiteral
>(expr
), v
);
303 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
304 return extract_int(cast
<ParenExpr
>(expr
), v
);
310 /* Extract an affine expression from the IntegerLiteral "expr".
312 __isl_give isl_pw_aff
*PetScan::extract_affine(IntegerLiteral
*expr
)
314 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
315 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
316 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
317 isl_set
*dom
= isl_set_universe(dim
);
321 extract_int(expr
, &v
);
322 aff
= isl_aff_add_constant(aff
, v
);
325 return isl_pw_aff_alloc(dom
, aff
);
328 /* Extract an affine expression from the APInt "val".
330 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
332 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
333 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
334 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
335 isl_set
*dom
= isl_set_universe(dim
);
339 isl_int_set_ui(v
, val
.getZExtValue());
340 aff
= isl_aff_add_constant(aff
, v
);
343 return isl_pw_aff_alloc(dom
, aff
);
346 __isl_give isl_pw_aff
*PetScan::extract_affine(ImplicitCastExpr
*expr
)
348 return extract_affine(expr
->getSubExpr());
351 /* Extract an affine expression from the DeclRefExpr "expr".
353 * If the variable has been assigned a value, then we check whether
354 * we know what (affine) value was assigned.
355 * If so, we return this value. Otherwise we convert "expr"
356 * to an extra parameter (provided nesting_enabled is set).
358 * Otherwise, we simply return an expression that is equal
359 * to a parameter corresponding to the referenced variable.
361 __isl_give isl_pw_aff
*PetScan::extract_affine(DeclRefExpr
*expr
)
363 ValueDecl
*decl
= expr
->getDecl();
364 const Type
*type
= decl
->getType().getTypePtr();
370 if (!type
->isIntegerType()) {
375 if (assigned_value
.find(decl
) != assigned_value
.end()) {
376 if (assigned_value
[decl
])
377 return isl_pw_aff_copy(assigned_value
[decl
]);
379 return nested_access(expr
);
382 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
383 dim
= isl_space_params_alloc(ctx
, 1);
385 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
387 dom
= isl_set_universe(isl_space_copy(dim
));
388 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
389 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
391 return isl_pw_aff_alloc(dom
, aff
);
394 /* Extract an affine expression from an integer division operation.
395 * In particular, if "expr" is lhs/rhs, then return
397 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
399 * The second argument (rhs) is required to be a (positive) integer constant.
401 __isl_give isl_pw_aff
*PetScan::extract_affine_div(BinaryOperator
*expr
)
404 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
409 rhs_expr
= expr
->getRHS();
411 if (extract_int(rhs_expr
, &v
) < 0) {
416 lhs
= extract_affine(expr
->getLHS());
417 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
419 lhs
= isl_pw_aff_scale_down(lhs
, v
);
422 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(lhs
));
423 lhs_c
= isl_pw_aff_ceil(lhs
);
424 res
= isl_pw_aff_cond(cond
, lhs_f
, lhs_c
);
429 /* Extract an affine expression from a modulo operation.
430 * In particular, if "expr" is lhs/rhs, then return
432 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
434 * The second argument (rhs) is required to be a (positive) integer constant.
436 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
439 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
444 rhs_expr
= expr
->getRHS();
445 if (rhs_expr
->getStmtClass() != Stmt::IntegerLiteralClass
) {
450 lhs
= extract_affine(expr
->getLHS());
451 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
454 extract_int(cast
<IntegerLiteral
>(rhs_expr
), &v
);
455 res
= isl_pw_aff_scale_down(isl_pw_aff_copy(lhs
), v
);
457 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(res
));
458 lhs_c
= isl_pw_aff_ceil(res
);
459 res
= isl_pw_aff_cond(cond
, lhs_f
, lhs_c
);
461 res
= isl_pw_aff_scale(res
, v
);
464 res
= isl_pw_aff_sub(lhs
, res
);
469 /* Extract an affine expression from a multiplication operation.
470 * This is only allowed if at least one of the two arguments
471 * is a (piecewise) constant.
473 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
478 lhs
= extract_affine(expr
->getLHS());
479 rhs
= extract_affine(expr
->getRHS());
481 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
482 isl_pw_aff_free(lhs
);
483 isl_pw_aff_free(rhs
);
488 return isl_pw_aff_mul(lhs
, rhs
);
491 /* Extract an affine expression from an addition or subtraction operation.
493 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
498 lhs
= extract_affine(expr
->getLHS());
499 rhs
= extract_affine(expr
->getRHS());
501 switch (expr
->getOpcode()) {
503 return isl_pw_aff_add(lhs
, rhs
);
505 return isl_pw_aff_sub(lhs
, rhs
);
507 isl_pw_aff_free(lhs
);
508 isl_pw_aff_free(rhs
);
518 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
524 isl_int_set_si(mod
, 1);
525 isl_int_mul_2exp(mod
, mod
, width
);
527 pwaff
= isl_pw_aff_mod(pwaff
, mod
);
534 /* Extract an affine expression from a boolean expression.
535 * In particular, return the expression "expr ? 1 : 0".
537 __isl_give isl_pw_aff
*PetScan::extract_implicit_affine(Expr
*expr
)
539 isl_set
*cond
= extract_condition(expr
);
540 isl_space
*space
= isl_set_get_space(cond
);
541 isl_local_space
*ls
= isl_local_space_from_space(space
);
542 isl_aff
*zero
= isl_aff_zero_on_domain(isl_local_space_copy(ls
));
543 isl_aff
*one
= isl_aff_zero_on_domain(ls
);
544 one
= isl_aff_add_constant_si(one
, 1);
545 return isl_pw_aff_cond(cond
, isl_pw_aff_from_aff(one
),
546 isl_pw_aff_from_aff(zero
));
549 /* Extract an affine expression from some binary operations.
550 * If the result of the expression is unsigned, then we wrap it
551 * based on the size of the type.
553 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
557 switch (expr
->getOpcode()) {
560 res
= extract_affine_add(expr
);
563 res
= extract_affine_div(expr
);
566 res
= extract_affine_mod(expr
);
569 res
= extract_affine_mul(expr
);
579 res
= extract_implicit_affine(expr
);
586 if (expr
->getType()->isUnsignedIntegerType())
587 res
= wrap(res
, ast_context
.getIntWidth(expr
->getType()));
592 /* Extract an affine expression from a negation operation.
594 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
596 if (expr
->getOpcode() == UO_Minus
)
597 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
598 if (expr
->getOpcode() == UO_LNot
)
599 return extract_implicit_affine(expr
);
605 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
607 return extract_affine(expr
->getSubExpr());
610 /* Extract an affine expression from some special function calls.
611 * In particular, we handle "min", "max", "ceild" and "floord".
612 * In case of the latter two, the second argument needs to be
613 * a (positive) integer constant.
615 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
619 isl_pw_aff
*aff1
, *aff2
;
621 fd
= expr
->getDirectCallee();
627 name
= fd
->getDeclName().getAsString();
628 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
629 !(expr
->getNumArgs() == 2 && name
== "max") &&
630 !(expr
->getNumArgs() == 2 && name
== "floord") &&
631 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
636 if (name
== "min" || name
== "max") {
637 aff1
= extract_affine(expr
->getArg(0));
638 aff2
= extract_affine(expr
->getArg(1));
641 aff1
= isl_pw_aff_min(aff1
, aff2
);
643 aff1
= isl_pw_aff_max(aff1
, aff2
);
644 } else if (name
== "floord" || name
== "ceild") {
646 Expr
*arg2
= expr
->getArg(1);
648 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
652 aff1
= extract_affine(expr
->getArg(0));
654 extract_int(cast
<IntegerLiteral
>(arg2
), &v
);
655 aff1
= isl_pw_aff_scale_down(aff1
, v
);
657 if (name
== "floord")
658 aff1
= isl_pw_aff_floor(aff1
);
660 aff1
= isl_pw_aff_ceil(aff1
);
670 /* This method is called when we come across an access that is
671 * nested in what is supposed to be an affine expression.
672 * If nesting is allowed, we return a new parameter that corresponds
673 * to this nested access. Otherwise, we simply complain.
675 * The new parameter is resolved in resolve_nested.
677 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
684 if (!nesting_enabled
) {
689 id
= isl_id_alloc(ctx
, NULL
, expr
);
690 dim
= isl_space_params_alloc(ctx
, 1);
692 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
694 dom
= isl_set_universe(isl_space_copy(dim
));
695 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
696 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
698 return isl_pw_aff_alloc(dom
, aff
);
701 /* Affine expressions are not supposed to contain array accesses,
702 * but if nesting is allowed, we return a parameter corresponding
703 * to the array access.
705 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
707 return nested_access(expr
);
710 /* Extract an affine expression from a conditional operation.
712 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
715 isl_pw_aff
*lhs
, *rhs
;
717 cond
= extract_condition(expr
->getCond());
718 lhs
= extract_affine(expr
->getTrueExpr());
719 rhs
= extract_affine(expr
->getFalseExpr());
721 return isl_pw_aff_cond(cond
, lhs
, rhs
);
724 /* Extract an affine expression, if possible, from "expr".
725 * Otherwise return NULL.
727 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
729 switch (expr
->getStmtClass()) {
730 case Stmt::ImplicitCastExprClass
:
731 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
732 case Stmt::IntegerLiteralClass
:
733 return extract_affine(cast
<IntegerLiteral
>(expr
));
734 case Stmt::DeclRefExprClass
:
735 return extract_affine(cast
<DeclRefExpr
>(expr
));
736 case Stmt::BinaryOperatorClass
:
737 return extract_affine(cast
<BinaryOperator
>(expr
));
738 case Stmt::UnaryOperatorClass
:
739 return extract_affine(cast
<UnaryOperator
>(expr
));
740 case Stmt::ParenExprClass
:
741 return extract_affine(cast
<ParenExpr
>(expr
));
742 case Stmt::CallExprClass
:
743 return extract_affine(cast
<CallExpr
>(expr
));
744 case Stmt::ArraySubscriptExprClass
:
745 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
746 case Stmt::ConditionalOperatorClass
:
747 return extract_affine(cast
<ConditionalOperator
>(expr
));
754 __isl_give isl_map
*PetScan::extract_access(ImplicitCastExpr
*expr
)
756 return extract_access(expr
->getSubExpr());
759 /* Return the depth of an array of the given type.
761 static int array_depth(const Type
*type
)
763 if (type
->isPointerType())
764 return 1 + array_depth(type
->getPointeeType().getTypePtr());
765 if (type
->isArrayType()) {
766 const ArrayType
*atype
;
767 type
= type
->getCanonicalTypeInternal().getTypePtr();
768 atype
= cast
<ArrayType
>(type
);
769 return 1 + array_depth(atype
->getElementType().getTypePtr());
774 /* Return the element type of the given array type.
776 static QualType
base_type(QualType qt
)
778 const Type
*type
= qt
.getTypePtr();
780 if (type
->isPointerType())
781 return base_type(type
->getPointeeType());
782 if (type
->isArrayType()) {
783 const ArrayType
*atype
;
784 type
= type
->getCanonicalTypeInternal().getTypePtr();
785 atype
= cast
<ArrayType
>(type
);
786 return base_type(atype
->getElementType());
791 /* Extract an access relation from a reference to a variable.
792 * If the variable has name "A" and its type corresponds to an
793 * array of depth d, then the returned access relation is of the
796 * { [] -> A[i_1,...,i_d] }
798 __isl_give isl_map
*PetScan::extract_access(DeclRefExpr
*expr
)
800 ValueDecl
*decl
= expr
->getDecl();
801 int depth
= array_depth(decl
->getType().getTypePtr());
802 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
803 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, depth
);
806 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
808 access_rel
= isl_map_universe(dim
);
813 /* Extract an access relation from an integer contant.
814 * If the value of the constant is "v", then the returned access relation
819 __isl_give isl_map
*PetScan::extract_access(IntegerLiteral
*expr
)
821 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr
)));
824 /* Try and extract an access relation from the given Expr.
825 * Return NULL if it doesn't work out.
827 __isl_give isl_map
*PetScan::extract_access(Expr
*expr
)
829 switch (expr
->getStmtClass()) {
830 case Stmt::ImplicitCastExprClass
:
831 return extract_access(cast
<ImplicitCastExpr
>(expr
));
832 case Stmt::DeclRefExprClass
:
833 return extract_access(cast
<DeclRefExpr
>(expr
));
834 case Stmt::ArraySubscriptExprClass
:
835 return extract_access(cast
<ArraySubscriptExpr
>(expr
));
842 /* Assign the affine expression "index" to the output dimension "pos" of "map"
843 * and return the result.
845 __isl_give isl_map
*set_index(__isl_take isl_map
*map
, int pos
,
846 __isl_take isl_pw_aff
*index
)
849 int len
= isl_map_dim(map
, isl_dim_out
);
852 index_map
= isl_map_from_range(isl_set_from_pw_aff(index
));
853 index_map
= isl_map_insert_dims(index_map
, isl_dim_out
, 0, pos
);
854 index_map
= isl_map_add_dims(index_map
, isl_dim_out
, len
- pos
- 1);
855 id
= isl_map_get_tuple_id(map
, isl_dim_out
);
856 index_map
= isl_map_set_tuple_id(index_map
, isl_dim_out
, id
);
858 map
= isl_map_intersect(map
, index_map
);
863 /* Extract an access relation from the given array subscript expression.
864 * If nesting is allowed in general, then we turn it on while
865 * examining the index expression.
867 * We first extract an access relation from the base.
868 * This will result in an access relation with a range that corresponds
869 * to the array being accessed and with earlier indices filled in already.
870 * We then extract the current index and fill that in as well.
871 * The position of the current index is based on the type of base.
872 * If base is the actual array variable, then the depth of this type
873 * will be the same as the depth of the array and we will fill in
874 * the first array index.
875 * Otherwise, the depth of the base type will be smaller and we will fill
878 __isl_give isl_map
*PetScan::extract_access(ArraySubscriptExpr
*expr
)
880 Expr
*base
= expr
->getBase();
881 Expr
*idx
= expr
->getIdx();
883 isl_map
*base_access
;
885 int depth
= array_depth(base
->getType().getTypePtr());
887 bool save_nesting
= nesting_enabled
;
889 nesting_enabled
= allow_nested
;
891 base_access
= extract_access(base
);
892 index
= extract_affine(idx
);
894 nesting_enabled
= save_nesting
;
896 pos
= isl_map_dim(base_access
, isl_dim_out
) - depth
;
897 access
= set_index(base_access
, pos
, index
);
902 /* Check if "expr" calls function "minmax" with two arguments and if so
903 * make lhs and rhs refer to these two arguments.
905 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
911 if (expr
->getStmtClass() != Stmt::CallExprClass
)
914 call
= cast
<CallExpr
>(expr
);
915 fd
= call
->getDirectCallee();
919 if (call
->getNumArgs() != 2)
922 name
= fd
->getDeclName().getAsString();
926 lhs
= call
->getArg(0);
927 rhs
= call
->getArg(1);
932 /* Check if "expr" is of the form min(lhs, rhs) and if so make
933 * lhs and rhs refer to the two arguments.
935 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
937 return is_minmax(expr
, "min", lhs
, rhs
);
940 /* Check if "expr" is of the form max(lhs, rhs) and if so make
941 * lhs and rhs refer to the two arguments.
943 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
945 return is_minmax(expr
, "max", lhs
, rhs
);
948 /* Extract a set of values satisfying the comparison "LHS op RHS"
949 * "comp" is the original statement that "LHS op RHS" is derived from
950 * and is used for diagnostics.
952 * If the comparison is of the form
956 * then the set is constructed as the intersection of the set corresponding
961 * A similar optimization is performed for max(a,b) <= c.
962 * We do this because that will lead to simpler representations of the set.
963 * If isl is ever enhanced to explicitly deal with min and max expressions,
964 * this optimization can be removed.
966 __isl_give isl_set
*PetScan::extract_comparison(BinaryOperatorKind op
,
967 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
974 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
976 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
978 if (op
== BO_LT
|| op
== BO_LE
) {
980 isl_set
*set1
, *set2
;
981 if (is_min(RHS
, expr1
, expr2
)) {
982 set1
= extract_comparison(op
, LHS
, expr1
, comp
);
983 set2
= extract_comparison(op
, LHS
, expr2
, comp
);
984 return isl_set_intersect(set1
, set2
);
986 if (is_max(LHS
, expr1
, expr2
)) {
987 set1
= extract_comparison(op
, expr1
, RHS
, comp
);
988 set2
= extract_comparison(op
, expr2
, RHS
, comp
);
989 return isl_set_intersect(set1
, set2
);
993 lhs
= extract_affine(LHS
);
994 rhs
= extract_affine(RHS
);
998 cond
= isl_pw_aff_lt_set(lhs
, rhs
);
1001 cond
= isl_pw_aff_le_set(lhs
, rhs
);
1004 cond
= isl_pw_aff_eq_set(lhs
, rhs
);
1007 cond
= isl_pw_aff_ne_set(lhs
, rhs
);
1010 isl_pw_aff_free(lhs
);
1011 isl_pw_aff_free(rhs
);
1016 cond
= isl_set_coalesce(cond
);
1021 __isl_give isl_set
*PetScan::extract_comparison(BinaryOperator
*comp
)
1023 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1024 comp
->getRHS(), comp
);
1027 /* Extract a set of values satisfying the negation (logical not)
1028 * of a subexpression.
1030 __isl_give isl_set
*PetScan::extract_boolean(UnaryOperator
*op
)
1034 cond
= extract_condition(op
->getSubExpr());
1036 return isl_set_complement(cond
);
1039 /* Extract a set of values satisfying the union (logical or)
1040 * or intersection (logical and) of two subexpressions.
1042 __isl_give isl_set
*PetScan::extract_boolean(BinaryOperator
*comp
)
1048 lhs
= extract_condition(comp
->getLHS());
1049 rhs
= extract_condition(comp
->getRHS());
1051 switch (comp
->getOpcode()) {
1053 cond
= isl_set_intersect(lhs
, rhs
);
1056 cond
= isl_set_union(lhs
, rhs
);
1068 __isl_give isl_set
*PetScan::extract_condition(UnaryOperator
*expr
)
1070 switch (expr
->getOpcode()) {
1072 return extract_boolean(expr
);
1079 /* Extract a set of values satisfying the condition "expr != 0".
1081 __isl_give isl_set
*PetScan::extract_implicit_condition(Expr
*expr
)
1083 return isl_pw_aff_non_zero_set(extract_affine(expr
));
1086 /* Extract a set of values satisfying the condition expressed by "expr".
1088 * If the expression doesn't look like a condition, we assume it
1089 * is an affine expression and return the condition "expr != 0".
1091 __isl_give isl_set
*PetScan::extract_condition(Expr
*expr
)
1093 BinaryOperator
*comp
;
1096 return isl_set_universe(isl_space_params_alloc(ctx
, 0));
1098 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1099 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1101 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1102 return extract_condition(cast
<UnaryOperator
>(expr
));
1104 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1105 return extract_implicit_condition(expr
);
1107 comp
= cast
<BinaryOperator
>(expr
);
1108 switch (comp
->getOpcode()) {
1115 return extract_comparison(comp
);
1118 return extract_boolean(comp
);
1120 return extract_implicit_condition(expr
);
1124 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
1128 return pet_op_minus
;
1134 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
1138 return pet_op_add_assign
;
1140 return pet_op_sub_assign
;
1142 return pet_op_mul_assign
;
1144 return pet_op_div_assign
;
1146 return pet_op_assign
;
1168 /* Construct a pet_expr representing a unary operator expression.
1170 struct pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1172 struct pet_expr
*arg
;
1173 enum pet_op_type op
;
1175 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1176 if (op
== pet_op_last
) {
1181 arg
= extract_expr(expr
->getSubExpr());
1183 return pet_expr_new_unary(ctx
, op
, arg
);
1186 /* Mark the given access pet_expr as a write.
1187 * If a scalar is being accessed, then mark its value
1188 * as unknown in assigned_value.
1190 void PetScan::mark_write(struct pet_expr
*access
)
1195 access
->acc
.write
= 1;
1196 access
->acc
.read
= 0;
1198 if (isl_map_dim(access
->acc
.access
, isl_dim_out
) != 0)
1201 id
= isl_map_get_tuple_id(access
->acc
.access
, isl_dim_out
);
1202 decl
= (ValueDecl
*) isl_id_get_user(id
);
1203 clear_assignment(assigned_value
, decl
);
1207 /* Construct a pet_expr representing a binary operator expression.
1209 * If the top level operator is an assignment and the LHS is an access,
1210 * then we mark that access as a write. If the operator is a compound
1211 * assignment, the access is marked as both a read and a write.
1213 * If "expr" assigns something to a scalar variable, then we mark
1214 * the variable as having been assigned. If, furthermore, the expression
1215 * is affine, then keep track of this value in assigned_value
1216 * so that we can plug it in when we later come across the same variable.
1218 struct pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1220 struct pet_expr
*lhs
, *rhs
;
1221 enum pet_op_type op
;
1223 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1224 if (op
== pet_op_last
) {
1229 lhs
= extract_expr(expr
->getLHS());
1230 rhs
= extract_expr(expr
->getRHS());
1232 if (expr
->isAssignmentOp() && lhs
&& lhs
->type
== pet_expr_access
) {
1234 if (expr
->isCompoundAssignmentOp())
1238 if (expr
->getOpcode() == BO_Assign
&&
1239 lhs
&& lhs
->type
== pet_expr_access
&&
1240 isl_map_dim(lhs
->acc
.access
, isl_dim_out
) == 0) {
1241 isl_id
*id
= isl_map_get_tuple_id(lhs
->acc
.access
, isl_dim_out
);
1242 ValueDecl
*decl
= (ValueDecl
*) isl_id_get_user(id
);
1243 Expr
*rhs
= expr
->getRHS();
1244 isl_pw_aff
*pa
= try_extract_affine(rhs
);
1245 clear_assignment(assigned_value
, decl
);
1247 assigned_value
[decl
] = pa
;
1248 insert_expression(pa
);
1253 return pet_expr_new_binary(ctx
, op
, lhs
, rhs
);
1256 /* Construct a pet_expr representing a conditional operation.
1258 struct pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1260 struct pet_expr
*cond
, *lhs
, *rhs
;
1262 cond
= extract_expr(expr
->getCond());
1263 lhs
= extract_expr(expr
->getTrueExpr());
1264 rhs
= extract_expr(expr
->getFalseExpr());
1266 return pet_expr_new_ternary(ctx
, cond
, lhs
, rhs
);
1269 struct pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1271 return extract_expr(expr
->getSubExpr());
1274 /* Construct a pet_expr representing a floating point value.
1276 struct pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1278 return pet_expr_new_double(ctx
, expr
->getValueAsApproximateDouble());
1281 /* Extract an access relation from "expr" and then convert it into
1284 struct pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1287 struct pet_expr
*pe
;
1289 switch (expr
->getStmtClass()) {
1290 case Stmt::ArraySubscriptExprClass
:
1291 access
= extract_access(cast
<ArraySubscriptExpr
>(expr
));
1293 case Stmt::DeclRefExprClass
:
1294 access
= extract_access(cast
<DeclRefExpr
>(expr
));
1296 case Stmt::IntegerLiteralClass
:
1297 access
= extract_access(cast
<IntegerLiteral
>(expr
));
1304 pe
= pet_expr_from_access(access
);
1309 struct pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1311 return extract_expr(expr
->getSubExpr());
1314 /* Construct a pet_expr representing a function call.
1316 * If we are passing along a pointer to an array element
1317 * or an entire row or even higher dimensional slice of an array,
1318 * then the function being called may write into the array.
1320 * We assume here that if the function is declared to take a pointer
1321 * to a const type, then the function will perform a read
1322 * and that otherwise, it will perform a write.
1324 struct pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1326 struct pet_expr
*res
= NULL
;
1330 fd
= expr
->getDirectCallee();
1336 name
= fd
->getDeclName().getAsString();
1337 res
= pet_expr_new_call(ctx
, name
.c_str(), expr
->getNumArgs());
1341 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
1342 Expr
*arg
= expr
->getArg(i
);
1346 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1347 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(arg
);
1348 arg
= ice
->getSubExpr();
1350 if (arg
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1351 UnaryOperator
*op
= cast
<UnaryOperator
>(arg
);
1352 if (op
->getOpcode() == UO_AddrOf
) {
1354 arg
= op
->getSubExpr();
1357 res
->args
[i
] = PetScan::extract_expr(arg
);
1358 main_arg
= res
->args
[i
];
1360 res
->args
[i
] = pet_expr_new_unary(ctx
,
1361 pet_op_address_of
, res
->args
[i
]);
1364 if (arg
->getStmtClass() == Stmt::ArraySubscriptExprClass
&&
1365 array_depth(arg
->getType().getTypePtr()) > 0)
1367 if (is_addr
&& main_arg
->type
== pet_expr_access
) {
1369 if (!fd
->hasPrototype()) {
1370 unsupported(expr
, "prototype required");
1373 parm
= fd
->getParamDecl(i
);
1374 if (!const_base(parm
->getType()))
1375 mark_write(main_arg
);
1385 /* Try and onstruct a pet_expr representing "expr".
1387 struct pet_expr
*PetScan::extract_expr(Expr
*expr
)
1389 switch (expr
->getStmtClass()) {
1390 case Stmt::UnaryOperatorClass
:
1391 return extract_expr(cast
<UnaryOperator
>(expr
));
1392 case Stmt::CompoundAssignOperatorClass
:
1393 case Stmt::BinaryOperatorClass
:
1394 return extract_expr(cast
<BinaryOperator
>(expr
));
1395 case Stmt::ImplicitCastExprClass
:
1396 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1397 case Stmt::ArraySubscriptExprClass
:
1398 case Stmt::DeclRefExprClass
:
1399 case Stmt::IntegerLiteralClass
:
1400 return extract_access_expr(expr
);
1401 case Stmt::FloatingLiteralClass
:
1402 return extract_expr(cast
<FloatingLiteral
>(expr
));
1403 case Stmt::ParenExprClass
:
1404 return extract_expr(cast
<ParenExpr
>(expr
));
1405 case Stmt::ConditionalOperatorClass
:
1406 return extract_expr(cast
<ConditionalOperator
>(expr
));
1407 case Stmt::CallExprClass
:
1408 return extract_expr(cast
<CallExpr
>(expr
));
1415 /* Check if the given initialization statement is an assignment.
1416 * If so, return that assignment. Otherwise return NULL.
1418 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1420 BinaryOperator
*ass
;
1422 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1425 ass
= cast
<BinaryOperator
>(init
);
1426 if (ass
->getOpcode() != BO_Assign
)
1432 /* Check if the given initialization statement is a declaration
1433 * of a single variable.
1434 * If so, return that declaration. Otherwise return NULL.
1436 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1440 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1443 decl
= cast
<DeclStmt
>(init
);
1445 if (!decl
->isSingleDecl())
1448 return decl
->getSingleDecl();
1451 /* Given the assignment operator in the initialization of a for loop,
1452 * extract the induction variable, i.e., the (integer)variable being
1455 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1462 lhs
= init
->getLHS();
1463 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1468 ref
= cast
<DeclRefExpr
>(lhs
);
1469 decl
= ref
->getDecl();
1470 type
= decl
->getType().getTypePtr();
1472 if (!type
->isIntegerType()) {
1480 /* Given the initialization statement of a for loop and the single
1481 * declaration in this initialization statement,
1482 * extract the induction variable, i.e., the (integer) variable being
1485 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1489 vd
= cast
<VarDecl
>(decl
);
1491 const QualType type
= vd
->getType();
1492 if (!type
->isIntegerType()) {
1497 if (!vd
->getInit()) {
1505 /* Check that op is of the form iv++ or iv--.
1506 * "inc" is accordingly set to 1 or -1.
1508 bool PetScan::check_unary_increment(UnaryOperator
*op
, clang::ValueDecl
*iv
,
1514 if (!op
->isIncrementDecrementOp()) {
1519 if (op
->isIncrementOp())
1520 isl_int_set_si(inc
, 1);
1522 isl_int_set_si(inc
, -1);
1524 sub
= op
->getSubExpr();
1525 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1530 ref
= cast
<DeclRefExpr
>(sub
);
1531 if (ref
->getDecl() != iv
) {
1539 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1540 * has a single constant expression on a universe domain, then
1541 * put this constant in *user.
1543 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
1546 isl_int
*inc
= (isl_int
*)user
;
1549 if (!isl_set_plain_is_universe(set
) || !isl_aff_is_cst(aff
))
1552 isl_aff_get_constant(aff
, inc
);
1560 /* Check if op is of the form
1564 * with inc a constant and set "inc" accordingly.
1566 * We extract an affine expression from the RHS and the subtract iv.
1567 * The result should be a constant.
1569 bool PetScan::check_binary_increment(BinaryOperator
*op
, clang::ValueDecl
*iv
,
1579 if (op
->getOpcode() != BO_Assign
) {
1585 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1590 ref
= cast
<DeclRefExpr
>(lhs
);
1591 if (ref
->getDecl() != iv
) {
1596 val
= extract_affine(op
->getRHS());
1598 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1600 dim
= isl_space_params_alloc(ctx
, 1);
1601 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1602 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1603 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1605 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
1607 if (isl_pw_aff_foreach_piece(val
, &extract_cst
, &inc
) < 0) {
1608 isl_pw_aff_free(val
);
1613 isl_pw_aff_free(val
);
1618 /* Check that op is of the form iv += cst or iv -= cst.
1619 * "inc" is set to cst or -cst accordingly.
1621 bool PetScan::check_compound_increment(CompoundAssignOperator
*op
,
1622 clang::ValueDecl
*iv
, isl_int
&inc
)
1628 BinaryOperatorKind opcode
;
1630 opcode
= op
->getOpcode();
1631 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1635 if (opcode
== BO_SubAssign
)
1639 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1644 ref
= cast
<DeclRefExpr
>(lhs
);
1645 if (ref
->getDecl() != iv
) {
1652 if (rhs
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1653 UnaryOperator
*op
= cast
<UnaryOperator
>(rhs
);
1654 if (op
->getOpcode() != UO_Minus
) {
1661 rhs
= op
->getSubExpr();
1664 if (rhs
->getStmtClass() != Stmt::IntegerLiteralClass
) {
1669 extract_int(cast
<IntegerLiteral
>(rhs
), &inc
);
1671 isl_int_neg(inc
, inc
);
1676 /* Check that the increment of the given for loop increments
1677 * (or decrements) the induction variable "iv".
1678 * "up" is set to true if the induction variable is incremented.
1680 bool PetScan::check_increment(ForStmt
*stmt
, ValueDecl
*iv
, isl_int
&v
)
1682 Stmt
*inc
= stmt
->getInc();
1689 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1690 return check_unary_increment(cast
<UnaryOperator
>(inc
), iv
, v
);
1691 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1692 return check_compound_increment(
1693 cast
<CompoundAssignOperator
>(inc
), iv
, v
);
1694 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1695 return check_binary_increment(cast
<BinaryOperator
>(inc
), iv
, v
);
1701 /* Embed the given iteration domain in an extra outer loop
1702 * with induction variable "var".
1703 * If this variable appeared as a parameter in the constraints,
1704 * it is replaced by the new outermost dimension.
1706 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1707 __isl_take isl_id
*var
)
1711 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1712 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1714 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1715 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1722 /* Construct a pet_scop for an infinite loop around the given body.
1724 * We extract a pet_scop for the body and then embed it in a loop with
1733 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
1739 struct pet_scop
*scop
;
1741 scop
= extract(body
);
1745 id
= isl_id_alloc(ctx
, "t", NULL
);
1746 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
1747 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
1748 dim
= isl_space_from_domain(isl_set_get_space(domain
));
1749 dim
= isl_space_add_dims(dim
, isl_dim_out
, 1);
1750 sched
= isl_map_universe(dim
);
1751 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
1752 scop
= pet_scop_embed(scop
, domain
, sched
, id
);
1757 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1763 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
1765 return extract_infinite_loop(stmt
->getBody());
1768 /* Check if the while loop is of the form
1773 * If so, construct a scop for an infinite loop around body.
1776 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
1782 cond
= stmt
->getCond();
1788 set
= extract_condition(cond
);
1789 is_universe
= isl_set_plain_is_universe(set
);
1797 return extract_infinite_loop(stmt
->getBody());
1800 /* Check whether "cond" expresses a simple loop bound
1801 * on the only set dimension.
1802 * In particular, if "up" is set then "cond" should contain only
1803 * upper bounds on the set dimension.
1804 * Otherwise, it should contain only lower bounds.
1806 static bool is_simple_bound(__isl_keep isl_set
*cond
, isl_int inc
)
1808 if (isl_int_is_pos(inc
))
1809 return !isl_set_dim_has_lower_bound(cond
, isl_dim_set
, 0);
1811 return !isl_set_dim_has_upper_bound(cond
, isl_dim_set
, 0);
1814 /* Extend a condition on a given iteration of a loop to one that
1815 * imposes the same condition on all previous iterations.
1816 * "domain" expresses the lower [upper] bound on the iterations
1817 * when inc is positive [negative].
1819 * In particular, we construct the condition (when inc is positive)
1821 * forall i' : (domain(i') and i' <= i) => cond(i')
1823 * which is equivalent to
1825 * not exists i' : domain(i') and i' <= i and not cond(i')
1827 * We construct this set by negating cond, applying a map
1829 * { [i'] -> [i] : domain(i') and i' <= i }
1831 * and then negating the result again.
1833 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
1834 __isl_take isl_set
*domain
, isl_int inc
)
1836 isl_map
*previous_to_this
;
1838 if (isl_int_is_pos(inc
))
1839 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
1841 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
1843 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
1845 cond
= isl_set_complement(cond
);
1846 cond
= isl_set_apply(cond
, previous_to_this
);
1847 cond
= isl_set_complement(cond
);
1852 /* Construct a domain of the form
1854 * [id] -> { [] : exists a: id = init + a * inc and a >= 0 }
1856 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
1857 __isl_take isl_pw_aff
*init
, isl_int inc
)
1863 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
1864 dim
= isl_pw_aff_get_domain_space(init
);
1865 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1866 aff
= isl_aff_add_coefficient(aff
, isl_dim_in
, 0, inc
);
1867 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
1869 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
1870 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1871 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1872 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1874 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
1876 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
1878 return isl_set_project_out(set
, isl_dim_set
, 0, 1);
1881 static unsigned get_type_size(ValueDecl
*decl
)
1883 return decl
->getASTContext().getIntWidth(decl
->getType());
1886 /* Assuming "cond" represents a simple bound on a loop where the loop
1887 * iterator "iv" is incremented (or decremented) by one, check if wrapping
1890 * Under the given assumptions, wrapping is only possible if "cond" allows
1891 * for the last value before wrapping, i.e., 2^width - 1 in case of an
1892 * increasing iterator and 0 in case of a decreasing iterator.
1894 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
, isl_int inc
)
1900 test
= isl_set_copy(cond
);
1902 isl_int_init(limit
);
1903 if (isl_int_is_neg(inc
))
1904 isl_int_set_si(limit
, 0);
1906 isl_int_set_si(limit
, 1);
1907 isl_int_mul_2exp(limit
, limit
, get_type_size(iv
));
1908 isl_int_sub_ui(limit
, limit
, 1);
1911 test
= isl_set_fix(cond
, isl_dim_set
, 0, limit
);
1912 cw
= !isl_set_is_empty(test
);
1915 isl_int_clear(limit
);
1920 /* Given a one-dimensional space, construct the following mapping on this
1923 * { [v] -> [v mod 2^width] }
1925 * where width is the number of bits used to represent the values
1926 * of the unsigned variable "iv".
1928 static __isl_give isl_map
*compute_wrapping(__isl_take isl_space
*dim
,
1936 isl_int_set_si(mod
, 1);
1937 isl_int_mul_2exp(mod
, mod
, get_type_size(iv
));
1939 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1940 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
1941 aff
= isl_aff_mod(aff
, mod
);
1945 return isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
1946 map
= isl_map_reverse(map
);
1949 /* Construct a pet_scop for a for statement.
1950 * The for loop is required to be of the form
1952 * for (i = init; condition; ++i)
1956 * for (i = init; condition; --i)
1958 * The initialization of the for loop should either be an assignment
1959 * to an integer variable, or a declaration of such a variable with
1962 * The condition is allowed to contain nested accesses, provided
1963 * they are not being written to inside the body of the loop.
1965 * We extract a pet_scop for the body and then embed it in a loop with
1966 * iteration domain and schedule
1968 * { [i] : i >= init and condition' }
1973 * { [i] : i <= init and condition' }
1976 * Where condition' is equal to condition if the latter is
1977 * a simple upper [lower] bound and a condition that is extended
1978 * to apply to all previous iterations otherwise.
1980 * If the stride of the loop is not 1, then "i >= init" is replaced by
1982 * (exists a: i = init + stride * a and a >= 0)
1984 * If the loop iterator i is unsigned, then wrapping may occur.
1985 * During the computation, we work with a virtual iterator that
1986 * does not wrap. However, the condition in the code applies
1987 * to the wrapped value, so we need to change condition(i)
1988 * into condition([i % 2^width]).
1989 * After computing the virtual domain and schedule, we apply
1990 * the function { [v] -> [v % 2^width] } to the domain and the domain
1991 * of the schedule. In order not to lose any information, we also
1992 * need to intersect the domain of the schedule with the virtual domain
1993 * first, since some iterations in the wrapped domain may be scheduled
1994 * several times, typically an infinite number of times.
1995 * Note that there is no need to perform this final wrapping
1996 * if the loop condition (after wrapping) is simple.
1998 * Wrapping on unsigned iterators can be avoided entirely if
1999 * loop condition is simple, the loop iterator is incremented
2000 * [decremented] by one and the last value before wrapping cannot
2001 * possibly satisfy the loop condition.
2003 * Before extracting a pet_scop from the body we remove all
2004 * assignments in assigned_value to variables that are assigned
2005 * somewhere in the body of the loop.
2007 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2009 BinaryOperator
*ass
;
2017 isl_set
*cond
= NULL
;
2019 struct pet_scop
*scop
;
2020 assigned_value_cache
cache(assigned_value
);
2025 isl_map
*wrap
= NULL
;
2027 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2028 return extract_infinite_for(stmt
);
2030 init
= stmt
->getInit();
2035 if ((ass
= initialization_assignment(init
)) != NULL
) {
2036 iv
= extract_induction_variable(ass
);
2039 lhs
= ass
->getLHS();
2040 rhs
= ass
->getRHS();
2041 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2042 VarDecl
*var
= extract_induction_variable(init
, decl
);
2046 rhs
= var
->getInit();
2047 lhs
= create_DeclRefExpr(var
);
2049 unsupported(stmt
->getInit());
2054 if (!check_increment(stmt
, iv
, inc
)) {
2059 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2061 assigned_value
.erase(iv
);
2062 clear_assignments
clear(assigned_value
);
2063 clear
.TraverseStmt(stmt
->getBody());
2065 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
2067 is_one
= isl_int_is_one(inc
) || isl_int_is_negone(inc
);
2069 domain
= extract_comparison(isl_int_is_pos(inc
) ? BO_GE
: BO_LE
,
2072 isl_pw_aff
*lb
= extract_affine(rhs
);
2073 domain
= strided_domain(isl_id_copy(id
), lb
, inc
);
2076 scop
= extract(stmt
->getBody());
2078 cond
= try_extract_nested_condition(stmt
->getCond());
2079 if (cond
&& !is_nested_allowed(cond
, scop
)) {
2085 cond
= extract_condition(stmt
->getCond());
2086 cond
= embed(cond
, isl_id_copy(id
));
2087 domain
= embed(domain
, isl_id_copy(id
));
2088 is_simple
= is_simple_bound(cond
, inc
);
2090 (!is_simple
|| !is_one
|| can_wrap(cond
, iv
, inc
))) {
2091 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2092 cond
= isl_set_apply(cond
, isl_map_reverse(isl_map_copy(wrap
)));
2093 is_simple
= is_simple
&& is_simple_bound(cond
, inc
);
2096 cond
= valid_for_each_iteration(cond
,
2097 isl_set_copy(domain
), inc
);
2098 domain
= isl_set_intersect(domain
, cond
);
2099 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2100 dim
= isl_space_from_domain(isl_set_get_space(domain
));
2101 dim
= isl_space_add_dims(dim
, isl_dim_out
, 1);
2102 sched
= isl_map_universe(dim
);
2103 if (isl_int_is_pos(inc
))
2104 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2106 sched
= isl_map_oppose(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2108 if (is_unsigned
&& !is_simple
) {
2109 wrap
= isl_map_set_dim_id(wrap
,
2110 isl_dim_out
, 0, isl_id_copy(id
));
2111 sched
= isl_map_intersect_domain(sched
, isl_set_copy(domain
));
2112 domain
= isl_set_apply(domain
, isl_map_copy(wrap
));
2113 sched
= isl_map_apply_domain(sched
, wrap
);
2117 scop
= pet_scop_embed(scop
, domain
, sched
, id
);
2118 scop
= resolve_nested(scop
);
2119 clear_assignment(assigned_value
, iv
);
2125 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
)
2127 return extract(stmt
->children());
2130 /* Does "id" refer to a nested access?
2132 static bool is_nested_parameter(__isl_keep isl_id
*id
)
2134 return id
&& isl_id_get_user(id
) && !isl_id_get_name(id
);
2137 /* Does parameter "pos" of "space" refer to a nested access?
2139 static bool is_nested_parameter(__isl_keep isl_space
*space
, int pos
)
2144 id
= isl_space_get_dim_id(space
, isl_dim_param
, pos
);
2145 nested
= is_nested_parameter(id
);
2151 /* Does parameter "pos" of "map" refer to a nested access?
2153 static bool is_nested_parameter(__isl_keep isl_map
*map
, int pos
)
2158 id
= isl_map_get_dim_id(map
, isl_dim_param
, pos
);
2159 nested
= is_nested_parameter(id
);
2165 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2167 static int n_nested_parameter(__isl_keep isl_space
*space
)
2172 nparam
= isl_space_dim(space
, isl_dim_param
);
2173 for (int i
= 0; i
< nparam
; ++i
)
2174 if (is_nested_parameter(space
, i
))
2180 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2182 static int n_nested_parameter(__isl_keep isl_map
*map
)
2187 space
= isl_map_get_space(map
);
2188 n
= n_nested_parameter(space
);
2189 isl_space_free(space
);
2194 /* For each nested access parameter in "space",
2195 * construct a corresponding pet_expr, place it in args and
2196 * record its position in "param2pos".
2197 * "n_arg" is the number of elements that are already in args.
2198 * The position recorded in "param2pos" takes this number into account.
2199 * If the pet_expr corresponding to a parameter is identical to
2200 * the pet_expr corresponding to an earlier parameter, then these two
2201 * parameters are made to refer to the same element in args.
2203 * Return the final number of elements in args or -1 if an error has occurred.
2205 int PetScan::extract_nested(__isl_keep isl_space
*space
,
2206 int n_arg
, struct pet_expr
**args
, std::map
<int,int> ¶m2pos
)
2210 nparam
= isl_space_dim(space
, isl_dim_param
);
2211 for (int i
= 0; i
< nparam
; ++i
) {
2213 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2216 if (!is_nested_parameter(id
)) {
2221 nested
= (Expr
*) isl_id_get_user(id
);
2222 args
[n_arg
] = extract_expr(nested
);
2226 for (j
= 0; j
< n_arg
; ++j
)
2227 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
2231 pet_expr_free(args
[n_arg
]);
2235 param2pos
[i
] = n_arg
++;
2243 /* For each nested access parameter in the access relations in "expr",
2244 * construct a corresponding pet_expr, place it in expr->args and
2245 * record its position in "param2pos".
2246 * n is the number of nested access parameters.
2248 struct pet_expr
*PetScan::extract_nested(struct pet_expr
*expr
, int n
,
2249 std::map
<int,int> ¶m2pos
)
2253 expr
->args
= isl_calloc_array(ctx
, struct pet_expr
*, n
);
2258 space
= isl_map_get_space(expr
->acc
.access
);
2259 n
= extract_nested(space
, 0, expr
->args
, param2pos
);
2260 isl_space_free(space
);
2268 pet_expr_free(expr
);
2272 /* Look for parameters in any access relation in "expr" that
2273 * refer to nested accesses. In particular, these are
2274 * parameters with no name.
2276 * If there are any such parameters, then the domain of the access
2277 * relation, which is still [] at this point, is replaced by
2278 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2279 * (after identifying identical nested accesses).
2280 * The parameters are then equated to the corresponding t dimensions
2281 * and subsequently projected out.
2282 * param2pos maps the position of the parameter to the position
2283 * of the corresponding t dimension.
2285 struct pet_expr
*PetScan::resolve_nested(struct pet_expr
*expr
)
2292 std::map
<int,int> param2pos
;
2297 for (int i
= 0; i
< expr
->n_arg
; ++i
) {
2298 expr
->args
[i
] = resolve_nested(expr
->args
[i
]);
2299 if (!expr
->args
[i
]) {
2300 pet_expr_free(expr
);
2305 if (expr
->type
!= pet_expr_access
)
2308 n
= n_nested_parameter(expr
->acc
.access
);
2312 expr
= extract_nested(expr
, n
, param2pos
);
2317 nparam
= isl_map_dim(expr
->acc
.access
, isl_dim_param
);
2318 n_in
= isl_map_dim(expr
->acc
.access
, isl_dim_in
);
2319 dim
= isl_map_get_space(expr
->acc
.access
);
2320 dim
= isl_space_domain(dim
);
2321 dim
= isl_space_from_domain(dim
);
2322 dim
= isl_space_add_dims(dim
, isl_dim_out
, n
);
2323 map
= isl_map_universe(dim
);
2324 map
= isl_map_domain_map(map
);
2325 map
= isl_map_reverse(map
);
2326 expr
->acc
.access
= isl_map_apply_domain(expr
->acc
.access
, map
);
2328 for (int i
= nparam
- 1; i
>= 0; --i
) {
2329 isl_id
*id
= isl_map_get_dim_id(expr
->acc
.access
,
2331 if (!is_nested_parameter(id
)) {
2336 expr
->acc
.access
= isl_map_equate(expr
->acc
.access
,
2337 isl_dim_param
, i
, isl_dim_in
,
2338 n_in
+ param2pos
[i
]);
2339 expr
->acc
.access
= isl_map_project_out(expr
->acc
.access
,
2340 isl_dim_param
, i
, 1);
2347 pet_expr_free(expr
);
2351 /* Convert a top-level pet_expr to a pet_scop with one statement.
2352 * This mainly involves resolving nested expression parameters
2353 * and setting the name of the iteration space.
2354 * The name is given by "label" if it is non-NULL. Otherwise,
2355 * it is of the form S_<n_stmt>.
2357 struct pet_scop
*PetScan::extract(Stmt
*stmt
, struct pet_expr
*expr
,
2358 __isl_take isl_id
*label
)
2360 struct pet_stmt
*ps
;
2361 SourceLocation loc
= stmt
->getLocStart();
2362 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
2364 expr
= resolve_nested(expr
);
2365 ps
= pet_stmt_from_pet_expr(ctx
, line
, label
, n_stmt
++, expr
);
2366 return pet_scop_from_pet_stmt(ctx
, ps
);
2369 /* Check if we can extract an affine expression from "expr".
2370 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2371 * We turn on autodetection so that we won't generate any warnings
2372 * and turn off nesting, so that we won't accept any non-affine constructs.
2374 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
2377 int save_autodetect
= autodetect
;
2378 bool save_nesting
= nesting_enabled
;
2381 nesting_enabled
= false;
2383 pwaff
= extract_affine(expr
);
2385 autodetect
= save_autodetect
;
2386 nesting_enabled
= save_nesting
;
2391 /* Check whether "expr" is an affine expression.
2393 bool PetScan::is_affine(Expr
*expr
)
2397 pwaff
= try_extract_affine(expr
);
2398 isl_pw_aff_free(pwaff
);
2400 return pwaff
!= NULL
;
2403 /* Check whether "expr" is an affine constraint.
2404 * We turn on autodetection so that we won't generate any warnings
2405 * and turn off nesting, so that we won't accept any non-affine constructs.
2407 bool PetScan::is_affine_condition(Expr
*expr
)
2410 int save_autodetect
= autodetect
;
2411 bool save_nesting
= nesting_enabled
;
2414 nesting_enabled
= false;
2416 set
= extract_condition(expr
);
2419 autodetect
= save_autodetect
;
2420 nesting_enabled
= save_nesting
;
2425 /* Check if we can extract a condition from "expr".
2426 * Return the condition as an isl_set if we can and NULL otherwise.
2427 * If allow_nested is set, then the condition may involve parameters
2428 * corresponding to nested accesses.
2429 * We turn on autodetection so that we won't generate any warnings.
2431 __isl_give isl_set
*PetScan::try_extract_nested_condition(Expr
*expr
)
2434 int save_autodetect
= autodetect
;
2435 bool save_nesting
= nesting_enabled
;
2438 nesting_enabled
= allow_nested
;
2439 set
= extract_condition(expr
);
2441 autodetect
= save_autodetect
;
2442 nesting_enabled
= save_nesting
;
2447 /* If the top-level expression of "stmt" is an assignment, then
2448 * return that assignment as a BinaryOperator.
2449 * Otherwise return NULL.
2451 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
2453 BinaryOperator
*ass
;
2457 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
2460 ass
= cast
<BinaryOperator
>(stmt
);
2461 if(ass
->getOpcode() != BO_Assign
)
2467 /* Check if the given if statement is a conditional assignement
2468 * with a non-affine condition. If so, construct a pet_scop
2469 * corresponding to this conditional assignment. Otherwise return NULL.
2471 * In particular we check if "stmt" is of the form
2478 * where a is some array or scalar access.
2479 * The constructed pet_scop then corresponds to the expression
2481 * a = condition ? f(...) : g(...)
2483 * All access relations in f(...) are intersected with condition
2484 * while all access relation in g(...) are intersected with the complement.
2486 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
2488 BinaryOperator
*ass_then
, *ass_else
;
2489 isl_map
*write_then
, *write_else
;
2490 isl_set
*cond
, *comp
;
2491 isl_map
*map
, *map_true
, *map_false
;
2493 struct pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
2494 bool save_nesting
= nesting_enabled
;
2496 ass_then
= top_assignment_or_null(stmt
->getThen());
2497 ass_else
= top_assignment_or_null(stmt
->getElse());
2499 if (!ass_then
|| !ass_else
)
2502 if (is_affine_condition(stmt
->getCond()))
2505 write_then
= extract_access(ass_then
->getLHS());
2506 write_else
= extract_access(ass_else
->getLHS());
2508 equal
= isl_map_is_equal(write_then
, write_else
);
2509 isl_map_free(write_else
);
2510 if (equal
< 0 || !equal
) {
2511 isl_map_free(write_then
);
2515 nesting_enabled
= allow_nested
;
2516 cond
= extract_condition(stmt
->getCond());
2517 nesting_enabled
= save_nesting
;
2518 comp
= isl_set_complement(isl_set_copy(cond
));
2519 map_true
= isl_map_from_domain(isl_set_from_params(isl_set_copy(cond
)));
2520 map_true
= isl_map_add_dims(map_true
, isl_dim_out
, 1);
2521 map_true
= isl_map_fix_si(map_true
, isl_dim_out
, 0, 1);
2522 map_false
= isl_map_from_domain(isl_set_from_params(isl_set_copy(comp
)));
2523 map_false
= isl_map_add_dims(map_false
, isl_dim_out
, 1);
2524 map_false
= isl_map_fix_si(map_false
, isl_dim_out
, 0, 0);
2525 map
= isl_map_union_disjoint(map_true
, map_false
);
2527 pe_cond
= pet_expr_from_access(map
);
2529 pe_then
= extract_expr(ass_then
->getRHS());
2530 pe_then
= pet_expr_restrict(pe_then
, cond
);
2531 pe_else
= extract_expr(ass_else
->getRHS());
2532 pe_else
= pet_expr_restrict(pe_else
, comp
);
2534 pe
= pet_expr_new_ternary(ctx
, pe_cond
, pe_then
, pe_else
);
2535 pe_write
= pet_expr_from_access(write_then
);
2537 pe_write
->acc
.write
= 1;
2538 pe_write
->acc
.read
= 0;
2540 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, pe_write
, pe
);
2541 return extract(stmt
, pe
);
2544 /* Create an access to a virtual array representing the result
2546 * Unlike other accessed data, the id of the array is NULL as
2547 * there is no ValueDecl in the program corresponding to the virtual
2549 * The array starts out as a scalar, but grows along with the
2550 * statement writing to the array in pet_scop_embed.
2552 static __isl_give isl_map
*create_test_access(isl_ctx
*ctx
, int test_nr
)
2554 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, 0);
2558 snprintf(name
, sizeof(name
), "__pet_test_%d", test_nr
);
2559 id
= isl_id_alloc(ctx
, name
, NULL
);
2560 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
2561 return isl_map_universe(dim
);
2564 /* Create a pet_scop with a single statement evaluating "cond"
2565 * and writing the result to a virtual scalar, as expressed by
2568 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
,
2569 __isl_take isl_map
*access
)
2571 struct pet_expr
*expr
, *write
;
2572 struct pet_stmt
*ps
;
2573 SourceLocation loc
= cond
->getLocStart();
2574 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
2576 write
= pet_expr_from_access(access
);
2578 write
->acc
.write
= 1;
2579 write
->acc
.read
= 0;
2581 expr
= extract_expr(cond
);
2582 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, write
, expr
);
2583 ps
= pet_stmt_from_pet_expr(ctx
, line
, NULL
, n_stmt
++, expr
);
2584 return pet_scop_from_pet_stmt(ctx
, ps
);
2587 /* Add an array with the given extent ("access") to the list
2588 * of arrays in "scop" and return the extended pet_scop.
2589 * The array is marked as attaining values 0 and 1 only.
2591 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2592 __isl_keep isl_map
*access
)
2594 isl_ctx
*ctx
= isl_map_get_ctx(access
);
2596 struct pet_array
**arrays
;
2597 struct pet_array
*array
;
2604 arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
2608 scop
->arrays
= arrays
;
2610 array
= isl_calloc_type(ctx
, struct pet_array
);
2614 array
->extent
= isl_map_range(isl_map_copy(access
));
2615 dim
= isl_space_params_alloc(ctx
, 0);
2616 array
->context
= isl_set_universe(dim
);
2617 dim
= isl_space_set_alloc(ctx
, 0, 1);
2618 array
->value_bounds
= isl_set_universe(dim
);
2619 array
->value_bounds
= isl_set_lower_bound_si(array
->value_bounds
,
2621 array
->value_bounds
= isl_set_upper_bound_si(array
->value_bounds
,
2623 array
->element_type
= strdup("int");
2625 scop
->arrays
[scop
->n_array
] = array
;
2628 if (!array
->extent
|| !array
->context
)
2633 pet_scop_free(scop
);
2638 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
,
2642 /* Apply the map pointed to by "user" to the domain of the access
2643 * relation, thereby embedding it in the range of the map.
2644 * The domain of both relations is the zero-dimensional domain.
2646 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
, void *user
)
2648 isl_map
*map
= (isl_map
*) user
;
2650 return isl_map_apply_domain(access
, isl_map_copy(map
));
2653 /* Apply "map" to all access relations in "expr".
2655 static struct pet_expr
*embed(struct pet_expr
*expr
, __isl_keep isl_map
*map
)
2657 return pet_expr_foreach_access(expr
, &embed_access
, map
);
2660 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2662 static int n_nested_parameter(__isl_keep isl_set
*set
)
2667 space
= isl_set_get_space(set
);
2668 n
= n_nested_parameter(space
);
2669 isl_space_free(space
);
2674 /* Remove all parameters from "map" that refer to nested accesses.
2676 static __isl_give isl_map
*remove_nested_parameters(__isl_take isl_map
*map
)
2681 space
= isl_map_get_space(map
);
2682 nparam
= isl_space_dim(space
, isl_dim_param
);
2683 for (int i
= nparam
- 1; i
>= 0; --i
)
2684 if (is_nested_parameter(space
, i
))
2685 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
2686 isl_space_free(space
);
2692 static __isl_give isl_map
*access_remove_nested_parameters(
2693 __isl_take isl_map
*access
, void *user
);
2696 static __isl_give isl_map
*access_remove_nested_parameters(
2697 __isl_take isl_map
*access
, void *user
)
2699 return remove_nested_parameters(access
);
2702 /* Remove all nested access parameters from the schedule and all
2703 * accesses of "stmt".
2704 * There is no need to remove them from the domain as these parameters
2705 * have already been removed from the domain when this function is called.
2707 static struct pet_stmt
*remove_nested_parameters(struct pet_stmt
*stmt
)
2711 stmt
->schedule
= remove_nested_parameters(stmt
->schedule
);
2712 stmt
->body
= pet_expr_foreach_access(stmt
->body
,
2713 &access_remove_nested_parameters
, NULL
);
2714 if (!stmt
->schedule
|| !stmt
->body
)
2716 for (int i
= 0; i
< stmt
->n_arg
; ++i
) {
2717 stmt
->args
[i
] = pet_expr_foreach_access(stmt
->args
[i
],
2718 &access_remove_nested_parameters
, NULL
);
2725 pet_stmt_free(stmt
);
2729 /* For each nested access parameter in the domain of "stmt",
2730 * construct a corresponding pet_expr, place it in stmt->args and
2731 * record its position in "param2pos".
2732 * n is the number of nested access parameters.
2734 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
2735 std::map
<int,int> ¶m2pos
)
2739 struct pet_expr
**args
;
2741 n_arg
= stmt
->n_arg
;
2742 args
= isl_realloc_array(ctx
, stmt
->args
, struct pet_expr
*, n_arg
+ n
);
2748 space
= isl_set_get_space(stmt
->domain
);
2749 n
= extract_nested(space
, n_arg
, stmt
->args
, param2pos
);
2750 isl_space_free(space
);
2758 pet_stmt_free(stmt
);
2762 /* Look for parameters in the iteration domain of "stmt" that
2763 * refer to nested accesses. In particular, these are
2764 * parameters with no name.
2766 * If there are any such parameters, then as many extra variables
2767 * (after identifying identical nested accesses) are added to the
2768 * range of the map wrapped inside the domain.
2769 * If the original domain is not a wrapped map, then a new wrapped
2770 * map is created with zero output dimensions.
2771 * The parameters are then equated to the corresponding output dimensions
2772 * and subsequently projected out, from the iteration domain,
2773 * the schedule and the access relations.
2774 * For each of the output dimensions, a corresponding argument
2775 * expression is added. Initially they are created with
2776 * a zero-dimensional domain, so they have to be embedded
2777 * in the current iteration domain.
2778 * param2pos maps the position of the parameter to the position
2779 * of the corresponding output dimension in the wrapped map.
2781 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
2787 std::map
<int,int> param2pos
;
2792 n
= n_nested_parameter(stmt
->domain
);
2796 n_arg
= stmt
->n_arg
;
2797 stmt
= extract_nested(stmt
, n
, param2pos
);
2801 n
= stmt
->n_arg
- n_arg
;
2802 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
2803 if (isl_set_is_wrapping(stmt
->domain
))
2804 map
= isl_set_unwrap(stmt
->domain
);
2806 map
= isl_map_from_domain(stmt
->domain
);
2807 map
= isl_map_add_dims(map
, isl_dim_out
, n
);
2809 for (int i
= nparam
- 1; i
>= 0; --i
) {
2812 if (!is_nested_parameter(map
, i
))
2815 id
= isl_map_get_tuple_id(stmt
->args
[param2pos
[i
]]->acc
.access
,
2817 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
2818 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
2820 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
2823 stmt
->domain
= isl_map_wrap(map
);
2825 map
= isl_set_unwrap(isl_set_copy(stmt
->domain
));
2826 map
= isl_map_from_range(isl_map_domain(map
));
2827 for (int pos
= n_arg
; pos
< stmt
->n_arg
; ++pos
)
2828 stmt
->args
[pos
] = embed(stmt
->args
[pos
], map
);
2831 stmt
= remove_nested_parameters(stmt
);
2835 pet_stmt_free(stmt
);
2839 /* For each statement in "scop", move the parameters that correspond
2840 * to nested access into the ranges of the domains and create
2841 * corresponding argument expressions.
2843 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
2848 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
2849 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
2850 if (!scop
->stmts
[i
])
2856 pet_scop_free(scop
);
2860 /* Does "space" involve any parameters that refer to nested
2861 * accesses, i.e., parameters with no name?
2863 static bool has_nested(__isl_keep isl_space
*space
)
2867 nparam
= isl_space_dim(space
, isl_dim_param
);
2868 for (int i
= 0; i
< nparam
; ++i
)
2869 if (is_nested_parameter(space
, i
))
2875 /* Does "set" involve any parameters that refer to nested
2876 * accesses, i.e., parameters with no name?
2878 static bool has_nested(__isl_keep isl_set
*set
)
2883 space
= isl_set_get_space(set
);
2884 nested
= has_nested(space
);
2885 isl_space_free(space
);
2890 /* Given an access expression "expr", is the variable accessed by
2891 * "expr" assigned anywhere inside "scop"?
2893 static bool is_assigned(pet_expr
*expr
, pet_scop
*scop
)
2895 bool assigned
= false;
2898 id
= isl_map_get_tuple_id(expr
->acc
.access
, isl_dim_out
);
2899 assigned
= pet_scop_writes(scop
, id
);
2905 /* Are all nested access parameters in "set" allowed given "scop".
2906 * In particular, is none of them written by anywhere inside "scop".
2908 bool PetScan::is_nested_allowed(__isl_keep isl_set
*set
, pet_scop
*scop
)
2912 nparam
= isl_set_dim(set
, isl_dim_param
);
2913 for (int i
= 0; i
< nparam
; ++i
) {
2915 isl_id
*id
= isl_set_get_dim_id(set
, isl_dim_param
, i
);
2919 if (!is_nested_parameter(id
)) {
2924 nested
= (Expr
*) isl_id_get_user(id
);
2925 expr
= extract_expr(nested
);
2926 allowed
= expr
&& expr
->type
== pet_expr_access
&&
2927 !is_assigned(expr
, scop
);
2929 pet_expr_free(expr
);
2939 /* Construct a pet_scop for an if statement.
2941 * If the condition fits the pattern of a conditional assignment,
2942 * then it is handled by extract_conditional_assignment.
2943 * Otherwise, we do the following.
2945 * If the condition is affine, then the condition is added
2946 * to the iteration domains of the then branch, while the
2947 * opposite of the condition in added to the iteration domains
2948 * of the else branch, if any.
2949 * We allow the condition to be dynamic, i.e., to refer to
2950 * scalars or array elements that may be written to outside
2951 * of the given if statement. These nested accesses are then represented
2952 * as output dimensions in the wrapping iteration domain.
2953 * If it also written _inside_ the then or else branch, then
2954 * we treat the condition as non-affine.
2955 * As explained below, this will introduce an extra statement.
2956 * For aesthetic reasons, we want this statement to have a statement
2957 * number that is lower than those of the then and else branches.
2958 * In order to evaluate if will need such a statement, however, we
2959 * first construct scops for the then and else branches.
2960 * We therefore reserve a statement number if we might have to
2961 * introduce such an extra statement.
2963 * If the condition is not affine, then we create a separate
2964 * statement that writes the result of the condition to a virtual scalar.
2965 * A constraint requiring the value of this virtual scalar to be one
2966 * is added to the iteration domains of the then branch.
2967 * Similarly, a constraint requiring the value of this virtual scalar
2968 * to be zero is added to the iteration domains of the else branch, if any.
2969 * We adjust the schedules to ensure that the virtual scalar is written
2970 * before it is read.
2972 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
2974 struct pet_scop
*scop_then
, *scop_else
, *scop
;
2975 assigned_value_cache
cache(assigned_value
);
2976 isl_map
*test_access
= NULL
;
2980 scop
= extract_conditional_assignment(stmt
);
2984 cond
= try_extract_nested_condition(stmt
->getCond());
2985 if (allow_nested
&& (!cond
|| has_nested(cond
)))
2988 scop_then
= extract(stmt
->getThen());
2990 if (stmt
->getElse()) {
2991 scop_else
= extract(stmt
->getElse());
2993 if (scop_then
&& !scop_else
) {
2998 if (!scop_then
&& scop_else
) {
3007 (!is_nested_allowed(cond
, scop_then
) ||
3008 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
3012 if (allow_nested
&& !cond
) {
3013 int save_n_stmt
= n_stmt
;
3014 test_access
= create_test_access(ctx
, n_test
++);
3016 scop
= extract_non_affine_condition(stmt
->getCond(),
3017 isl_map_copy(test_access
));
3018 n_stmt
= save_n_stmt
;
3019 scop
= scop_add_array(scop
, test_access
);
3021 pet_scop_free(scop_then
);
3022 pet_scop_free(scop_else
);
3023 isl_map_free(test_access
);
3030 cond
= extract_condition(stmt
->getCond());
3031 scop
= pet_scop_restrict(scop_then
, isl_set_copy(cond
));
3033 if (stmt
->getElse()) {
3034 cond
= isl_set_complement(cond
);
3035 scop_else
= pet_scop_restrict(scop_else
, cond
);
3036 scop
= pet_scop_add(ctx
, scop
, scop_else
);
3039 scop
= resolve_nested(scop
);
3041 scop
= pet_scop_prefix(scop
, 0);
3042 scop_then
= pet_scop_prefix(scop_then
, 1);
3043 scop_then
= pet_scop_filter(scop_then
,
3044 isl_map_copy(test_access
), 1);
3045 scop
= pet_scop_add(ctx
, scop
, scop_then
);
3046 if (stmt
->getElse()) {
3047 scop_else
= pet_scop_prefix(scop_else
, 1);
3048 scop_else
= pet_scop_filter(scop_else
, test_access
, 0);
3049 scop
= pet_scop_add(ctx
, scop
, scop_else
);
3051 isl_map_free(test_access
);
3057 /* Try and construct a pet_scop for a label statement.
3058 * We currently only allow labels on expression statements.
3060 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
3065 sub
= stmt
->getSubStmt();
3066 if (!isa
<Expr
>(sub
)) {
3071 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
3073 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
3076 /* Try and construct a pet_scop corresponding to "stmt".
3078 struct pet_scop
*PetScan::extract(Stmt
*stmt
)
3080 if (isa
<Expr
>(stmt
))
3081 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
3083 switch (stmt
->getStmtClass()) {
3084 case Stmt::WhileStmtClass
:
3085 return extract(cast
<WhileStmt
>(stmt
));
3086 case Stmt::ForStmtClass
:
3087 return extract_for(cast
<ForStmt
>(stmt
));
3088 case Stmt::IfStmtClass
:
3089 return extract(cast
<IfStmt
>(stmt
));
3090 case Stmt::CompoundStmtClass
:
3091 return extract(cast
<CompoundStmt
>(stmt
));
3092 case Stmt::LabelStmtClass
:
3093 return extract(cast
<LabelStmt
>(stmt
));
3101 /* Try and construct a pet_scop corresponding to (part of)
3102 * a sequence of statements.
3104 struct pet_scop
*PetScan::extract(StmtRange stmt_range
)
3109 bool partial_range
= false;
3111 scop
= pet_scop_empty(ctx
);
3112 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
3114 struct pet_scop
*scop_i
;
3115 scop_i
= extract(child
);
3116 if (scop
&& partial
) {
3117 pet_scop_free(scop_i
);
3120 scop_i
= pet_scop_prefix(scop_i
, j
);
3123 scop
= pet_scop_add(ctx
, scop
, scop_i
);
3125 partial_range
= true;
3126 if (scop
->n_stmt
!= 0 && !scop_i
)
3129 scop
= pet_scop_add(ctx
, scop
, scop_i
);
3135 if (scop
&& partial_range
)
3141 /* Check if the scop marked by the user is exactly this Stmt
3142 * or part of this Stmt.
3143 * If so, return a pet_scop corresponding to the marked region.
3144 * Otherwise, return NULL.
3146 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
3148 SourceManager
&SM
= PP
.getSourceManager();
3149 unsigned start_off
, end_off
;
3151 start_off
= SM
.getFileOffset(stmt
->getLocStart());
3152 end_off
= SM
.getFileOffset(stmt
->getLocEnd());
3154 if (start_off
> loc
.end
)
3156 if (end_off
< loc
.start
)
3158 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
3159 return extract(stmt
);
3163 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
3164 Stmt
*child
= *start
;
3167 start_off
= SM
.getFileOffset(child
->getLocStart());
3168 end_off
= SM
.getFileOffset(child
->getLocEnd());
3169 if (start_off
< loc
.start
&& end_off
> loc
.end
)
3171 if (start_off
>= loc
.start
)
3176 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
3178 start_off
= SM
.getFileOffset(child
->getLocStart());
3179 if (start_off
>= loc
.end
)
3183 return extract(StmtRange(start
, end
));
3186 /* Set the size of index "pos" of "array" to "size".
3187 * In particular, add a constraint of the form
3191 * to array->extent and a constraint of the form
3195 * to array->context.
3197 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
3198 __isl_take isl_pw_aff
*size
)
3208 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
3209 array
->context
= isl_set_intersect(array
->context
, valid
);
3211 dim
= isl_set_get_space(array
->extent
);
3212 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
3213 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
3214 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
3215 index
= isl_pw_aff_alloc(univ
, aff
);
3217 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
3218 isl_set_dim(array
->extent
, isl_dim_set
));
3219 id
= isl_set_get_tuple_id(array
->extent
);
3220 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
3221 bound
= isl_pw_aff_lt_set(index
, size
);
3223 array
->extent
= isl_set_intersect(array
->extent
, bound
);
3225 if (!array
->context
|| !array
->extent
)
3230 pet_array_free(array
);
3234 /* Figure out the size of the array at position "pos" and all
3235 * subsequent positions from "type" and update "array" accordingly.
3237 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
3238 const Type
*type
, int pos
)
3240 const ArrayType
*atype
;
3246 if (type
->isPointerType()) {
3247 type
= type
->getPointeeType().getTypePtr();
3248 return set_upper_bounds(array
, type
, pos
+ 1);
3250 if (!type
->isArrayType())
3253 type
= type
->getCanonicalTypeInternal().getTypePtr();
3254 atype
= cast
<ArrayType
>(type
);
3256 if (type
->isConstantArrayType()) {
3257 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
3258 size
= extract_affine(ca
->getSize());
3259 array
= update_size(array
, pos
, size
);
3260 } else if (type
->isVariableArrayType()) {
3261 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
3262 size
= extract_affine(vla
->getSizeExpr());
3263 array
= update_size(array
, pos
, size
);
3266 type
= atype
->getElementType().getTypePtr();
3268 return set_upper_bounds(array
, type
, pos
+ 1);
3271 /* Construct and return a pet_array corresponding to the variable "decl".
3272 * In particular, initialize array->extent to
3274 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3276 * and then call set_upper_bounds to set the upper bounds on the indices
3277 * based on the type of the variable.
3279 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
)
3281 struct pet_array
*array
;
3282 QualType qt
= decl
->getType();
3283 const Type
*type
= qt
.getTypePtr();
3284 int depth
= array_depth(type
);
3285 QualType base
= base_type(qt
);
3290 array
= isl_calloc_type(ctx
, struct pet_array
);
3294 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
3295 dim
= isl_space_set_alloc(ctx
, 0, depth
);
3296 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
3298 array
->extent
= isl_set_nat_universe(dim
);
3300 dim
= isl_space_params_alloc(ctx
, 0);
3301 array
->context
= isl_set_universe(dim
);
3303 array
= set_upper_bounds(array
, type
, 0);
3307 name
= base
.getAsString();
3308 array
->element_type
= strdup(name
.c_str());
3313 /* Construct a list of pet_arrays, one for each array (or scalar)
3314 * accessed inside "scop" add this list to "scop" and return the result.
3316 * The context of "scop" is updated with the intesection of
3317 * the contexts of all arrays, i.e., constraints on the parameters
3318 * that ensure that the arrays have a valid (non-negative) size.
3320 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
3323 set
<ValueDecl
*> arrays
;
3324 set
<ValueDecl
*>::iterator it
;
3326 struct pet_array
**scop_arrays
;
3331 pet_scop_collect_arrays(scop
, arrays
);
3332 if (arrays
.size() == 0)
3335 n_array
= scop
->n_array
;
3337 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
3338 n_array
+ arrays
.size());
3341 scop
->arrays
= scop_arrays
;
3343 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
3344 struct pet_array
*array
;
3345 scop
->arrays
[n_array
+ i
] = array
= extract_array(ctx
, *it
);
3346 if (!scop
->arrays
[n_array
+ i
])
3349 scop
->context
= isl_set_intersect(scop
->context
,
3350 isl_set_copy(array
->context
));
3357 pet_scop_free(scop
);
3361 /* Construct a pet_scop from the given function.
3363 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
3368 stmt
= fd
->getBody();
3371 scop
= extract(stmt
);
3374 scop
= pet_scop_detect_parameter_accesses(scop
);
3375 scop
= scan_arrays(scop
);