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/ASTContext.h>
39 #include <clang/AST/ASTDiagnostic.h>
40 #include <clang/AST/Expr.h>
41 #include <clang/AST/RecursiveASTVisitor.h>
44 #include <isl/space.h>
51 #include "scop_plus.h"
56 using namespace clang
;
58 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
59 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
61 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
62 SourceLocation(), var
, false, var
->getInnerLocStart(),
63 var
->getType(), VK_LValue
);
65 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
66 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
68 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
69 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
73 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
75 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
76 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
80 /* Check if the element type corresponding to the given array type
81 * has a const qualifier.
83 static bool const_base(QualType qt
)
85 const Type
*type
= qt
.getTypePtr();
87 if (type
->isPointerType())
88 return const_base(type
->getPointeeType());
89 if (type
->isArrayType()) {
90 const ArrayType
*atype
;
91 type
= type
->getCanonicalTypeInternal().getTypePtr();
92 atype
= cast
<ArrayType
>(type
);
93 return const_base(atype
->getElementType());
96 return qt
.isConstQualified();
99 /* Mark "decl" as having an unknown value in "assigned_value".
101 * If no (known or unknown) value was assigned to "decl" before,
102 * then it may have been treated as a parameter before and may
103 * therefore appear in a value assigned to another variable.
104 * If so, this assignment needs to be turned into an unknown value too.
106 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
109 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
111 it
= assigned_value
.find(decl
);
113 assigned_value
[decl
] = NULL
;
115 if (it
== assigned_value
.end())
118 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
119 isl_pw_aff
*pa
= it
->second
;
120 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
122 for (int i
= 0; i
< nparam
; ++i
) {
125 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
127 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
128 if (isl_id_get_user(id
) == decl
)
135 /* Look for any assignments to scalar variables in part of the parse
136 * tree and set assigned_value to NULL for each of them.
137 * Also reset assigned_value if the address of a scalar variable
138 * is being taken. As an exception, if the address is passed to a function
139 * that is declared to receive a const pointer, then assigned_value is
142 * This ensures that we won't use any previously stored value
143 * in the current subtree and its parents.
145 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
146 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
147 set
<UnaryOperator
*> skip
;
149 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
150 assigned_value(assigned_value
) {}
152 /* Check for "address of" operators whose value is passed
153 * to a const pointer argument and add them to "skip", so that
154 * we can skip them in VisitUnaryOperator.
156 bool VisitCallExpr(CallExpr
*expr
) {
158 fd
= expr
->getDirectCallee();
161 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
162 Expr
*arg
= expr
->getArg(i
);
164 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
165 ImplicitCastExpr
*ice
;
166 ice
= cast
<ImplicitCastExpr
>(arg
);
167 arg
= ice
->getSubExpr();
169 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
171 op
= cast
<UnaryOperator
>(arg
);
172 if (op
->getOpcode() != UO_AddrOf
)
174 if (const_base(fd
->getParamDecl(i
)->getType()))
180 bool VisitUnaryOperator(UnaryOperator
*expr
) {
185 if (expr
->getOpcode() != UO_AddrOf
)
187 if (skip
.find(expr
) != skip
.end())
190 arg
= expr
->getSubExpr();
191 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
193 ref
= cast
<DeclRefExpr
>(arg
);
194 decl
= ref
->getDecl();
195 clear_assignment(assigned_value
, decl
);
199 bool VisitBinaryOperator(BinaryOperator
*expr
) {
204 if (!expr
->isAssignmentOp())
206 lhs
= expr
->getLHS();
207 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
209 ref
= cast
<DeclRefExpr
>(lhs
);
210 decl
= ref
->getDecl();
211 clear_assignment(assigned_value
, decl
);
216 /* Keep a copy of the currently assigned values.
218 * Any variable that is assigned a value inside the current scope
219 * is removed again when we leave the scope (either because it wasn't
220 * stored in the cache or because it has a different value in the cache).
222 struct assigned_value_cache
{
223 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
224 map
<ValueDecl
*, isl_pw_aff
*> cache
;
226 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
227 assigned_value(assigned_value
), cache(assigned_value
) {}
228 ~assigned_value_cache() {
229 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
230 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
233 (cache
.find(it
->first
) != cache
.end() &&
234 cache
[it
->first
] != it
->second
))
235 cache
[it
->first
] = NULL
;
237 assigned_value
= cache
;
241 /* Insert an expression into the collection of expressions,
242 * provided it is not already in there.
243 * The isl_pw_affs are freed in the destructor.
245 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
247 std::set
<isl_pw_aff
*>::iterator it
;
249 if (expressions
.find(expr
) == expressions
.end())
250 expressions
.insert(expr
);
252 isl_pw_aff_free(expr
);
257 std::set
<isl_pw_aff
*>::iterator it
;
259 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
260 isl_pw_aff_free(*it
);
262 isl_union_map_free(value_bounds
);
265 /* Called if we found something we (currently) cannot handle.
266 * We'll provide more informative warnings later.
268 * We only actually complain if autodetect is false.
270 void PetScan::unsupported(Stmt
*stmt
, const char *msg
)
272 if (options
->autodetect
)
275 SourceLocation loc
= stmt
->getLocStart();
276 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
277 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
278 msg
? msg
: "unsupported");
279 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
282 /* Extract an integer from "expr" and store it in "v".
284 int PetScan::extract_int(IntegerLiteral
*expr
, isl_int
*v
)
286 const Type
*type
= expr
->getType().getTypePtr();
287 int is_signed
= type
->hasSignedIntegerRepresentation();
290 int64_t i
= expr
->getValue().getSExtValue();
291 isl_int_set_si(*v
, i
);
293 uint64_t i
= expr
->getValue().getZExtValue();
294 isl_int_set_ui(*v
, i
);
300 /* Extract an integer from "expr" and store it in "v".
301 * Return -1 if "expr" does not (obviously) represent an integer.
303 int PetScan::extract_int(clang::ParenExpr
*expr
, isl_int
*v
)
305 return extract_int(expr
->getSubExpr(), v
);
308 /* Extract an integer from "expr" and store it in "v".
309 * Return -1 if "expr" does not (obviously) represent an integer.
311 int PetScan::extract_int(clang::Expr
*expr
, isl_int
*v
)
313 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
314 return extract_int(cast
<IntegerLiteral
>(expr
), v
);
315 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
316 return extract_int(cast
<ParenExpr
>(expr
), v
);
322 /* Extract an affine expression from the IntegerLiteral "expr".
324 __isl_give isl_pw_aff
*PetScan::extract_affine(IntegerLiteral
*expr
)
326 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
327 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
328 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
329 isl_set
*dom
= isl_set_universe(dim
);
333 extract_int(expr
, &v
);
334 aff
= isl_aff_add_constant(aff
, v
);
337 return isl_pw_aff_alloc(dom
, aff
);
340 /* Extract an affine expression from the APInt "val".
342 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
344 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
345 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
346 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
347 isl_set
*dom
= isl_set_universe(dim
);
351 isl_int_set_ui(v
, val
.getZExtValue());
352 aff
= isl_aff_add_constant(aff
, v
);
355 return isl_pw_aff_alloc(dom
, aff
);
358 __isl_give isl_pw_aff
*PetScan::extract_affine(ImplicitCastExpr
*expr
)
360 return extract_affine(expr
->getSubExpr());
363 static unsigned get_type_size(ValueDecl
*decl
)
365 return decl
->getASTContext().getIntWidth(decl
->getType());
368 /* Bound parameter "pos" of "set" to the possible values of "decl".
370 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
371 unsigned pos
, ValueDecl
*decl
)
378 width
= get_type_size(decl
);
379 if (decl
->getType()->isUnsignedIntegerType()) {
380 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
381 isl_int_set_si(v
, 1);
382 isl_int_mul_2exp(v
, v
, width
);
383 isl_int_sub_ui(v
, v
, 1);
384 set
= isl_set_upper_bound(set
, isl_dim_param
, pos
, v
);
386 isl_int_set_si(v
, 1);
387 isl_int_mul_2exp(v
, v
, width
- 1);
388 isl_int_sub_ui(v
, v
, 1);
389 set
= isl_set_upper_bound(set
, isl_dim_param
, pos
, v
);
391 isl_int_sub_ui(v
, v
, 1);
392 set
= isl_set_lower_bound(set
, isl_dim_param
, pos
, v
);
400 /* Extract an affine expression from the DeclRefExpr "expr".
402 * If the variable has been assigned a value, then we check whether
403 * we know what (affine) value was assigned.
404 * If so, we return this value. Otherwise we convert "expr"
405 * to an extra parameter (provided nesting_enabled is set).
407 * Otherwise, we simply return an expression that is equal
408 * to a parameter corresponding to the referenced variable.
410 __isl_give isl_pw_aff
*PetScan::extract_affine(DeclRefExpr
*expr
)
412 ValueDecl
*decl
= expr
->getDecl();
413 const Type
*type
= decl
->getType().getTypePtr();
419 if (!type
->isIntegerType()) {
424 if (assigned_value
.find(decl
) != assigned_value
.end()) {
425 if (assigned_value
[decl
])
426 return isl_pw_aff_copy(assigned_value
[decl
]);
428 return nested_access(expr
);
431 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
432 dim
= isl_space_params_alloc(ctx
, 1);
434 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
436 dom
= isl_set_universe(isl_space_copy(dim
));
437 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
438 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
440 return isl_pw_aff_alloc(dom
, aff
);
443 /* Extract an affine expression from an integer division operation.
444 * In particular, if "expr" is lhs/rhs, then return
446 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
448 * The second argument (rhs) is required to be a (positive) integer constant.
450 __isl_give isl_pw_aff
*PetScan::extract_affine_div(BinaryOperator
*expr
)
453 isl_pw_aff
*rhs
, *lhs
;
455 rhs
= extract_affine(expr
->getRHS());
456 is_cst
= isl_pw_aff_is_cst(rhs
);
457 if (is_cst
< 0 || !is_cst
) {
458 isl_pw_aff_free(rhs
);
464 lhs
= extract_affine(expr
->getLHS());
466 return isl_pw_aff_tdiv_q(lhs
, rhs
);
469 /* Extract an affine expression from a modulo operation.
470 * In particular, if "expr" is lhs/rhs, then return
472 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
474 * The second argument (rhs) is required to be a (positive) integer constant.
476 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
479 isl_pw_aff
*rhs
, *lhs
;
481 rhs
= extract_affine(expr
->getRHS());
482 is_cst
= isl_pw_aff_is_cst(rhs
);
483 if (is_cst
< 0 || !is_cst
) {
484 isl_pw_aff_free(rhs
);
490 lhs
= extract_affine(expr
->getLHS());
492 return isl_pw_aff_tdiv_r(lhs
, rhs
);
495 /* Extract an affine expression from a multiplication operation.
496 * This is only allowed if at least one of the two arguments
497 * is a (piecewise) constant.
499 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
504 lhs
= extract_affine(expr
->getLHS());
505 rhs
= extract_affine(expr
->getRHS());
507 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
508 isl_pw_aff_free(lhs
);
509 isl_pw_aff_free(rhs
);
514 return isl_pw_aff_mul(lhs
, rhs
);
517 /* Extract an affine expression from an addition or subtraction operation.
519 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
524 lhs
= extract_affine(expr
->getLHS());
525 rhs
= extract_affine(expr
->getRHS());
527 switch (expr
->getOpcode()) {
529 return isl_pw_aff_add(lhs
, rhs
);
531 return isl_pw_aff_sub(lhs
, rhs
);
533 isl_pw_aff_free(lhs
);
534 isl_pw_aff_free(rhs
);
544 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
550 isl_int_set_si(mod
, 1);
551 isl_int_mul_2exp(mod
, mod
, width
);
553 pwaff
= isl_pw_aff_mod(pwaff
, mod
);
560 /* Limit the domain of "pwaff" to those elements where the function
563 * 2^{width-1} <= pwaff < 2^{width-1}
565 static __isl_give isl_pw_aff
*avoid_overflow(__isl_take isl_pw_aff
*pwaff
,
569 isl_space
*space
= isl_pw_aff_get_domain_space(pwaff
);
570 isl_local_space
*ls
= isl_local_space_from_space(space
);
576 isl_int_set_si(v
, 1);
577 isl_int_mul_2exp(v
, v
, width
- 1);
579 bound
= isl_aff_zero_on_domain(ls
);
580 bound
= isl_aff_add_constant(bound
, v
);
581 b
= isl_pw_aff_from_aff(bound
);
583 dom
= isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff
), isl_pw_aff_copy(b
));
584 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
586 b
= isl_pw_aff_neg(b
);
587 dom
= isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff
), b
);
588 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
595 /* Handle potential overflows on signed computations.
597 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
598 * the we adjust the domain of "pa" to avoid overflows.
600 __isl_give isl_pw_aff
*PetScan::signed_overflow(__isl_take isl_pw_aff
*pa
,
603 if (options
->signed_overflow
== PET_OVERFLOW_AVOID
)
604 pa
= avoid_overflow(pa
, width
);
609 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
611 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
612 __isl_take isl_set
*dom
)
615 pa
= isl_set_indicator_function(set
);
616 pa
= isl_pw_aff_intersect_domain(pa
, dom
);
620 /* Extract an affine expression from some binary operations.
621 * If the result of the expression is unsigned, then we wrap it
622 * based on the size of the type. Otherwise, we ensure that
623 * no overflow occurs.
625 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
630 switch (expr
->getOpcode()) {
633 res
= extract_affine_add(expr
);
636 res
= extract_affine_div(expr
);
639 res
= extract_affine_mod(expr
);
642 res
= extract_affine_mul(expr
);
652 return extract_condition(expr
);
658 width
= ast_context
.getIntWidth(expr
->getType());
659 if (expr
->getType()->isUnsignedIntegerType())
660 res
= wrap(res
, width
);
662 res
= signed_overflow(res
, width
);
667 /* Extract an affine expression from a negation operation.
669 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
671 if (expr
->getOpcode() == UO_Minus
)
672 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
673 if (expr
->getOpcode() == UO_LNot
)
674 return extract_condition(expr
);
680 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
682 return extract_affine(expr
->getSubExpr());
685 /* Extract an affine expression from some special function calls.
686 * In particular, we handle "min", "max", "ceild" and "floord".
687 * In case of the latter two, the second argument needs to be
688 * a (positive) integer constant.
690 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
694 isl_pw_aff
*aff1
, *aff2
;
696 fd
= expr
->getDirectCallee();
702 name
= fd
->getDeclName().getAsString();
703 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
704 !(expr
->getNumArgs() == 2 && name
== "max") &&
705 !(expr
->getNumArgs() == 2 && name
== "floord") &&
706 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
711 if (name
== "min" || name
== "max") {
712 aff1
= extract_affine(expr
->getArg(0));
713 aff2
= extract_affine(expr
->getArg(1));
716 aff1
= isl_pw_aff_min(aff1
, aff2
);
718 aff1
= isl_pw_aff_max(aff1
, aff2
);
719 } else if (name
== "floord" || name
== "ceild") {
721 Expr
*arg2
= expr
->getArg(1);
723 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
727 aff1
= extract_affine(expr
->getArg(0));
729 extract_int(cast
<IntegerLiteral
>(arg2
), &v
);
730 aff1
= isl_pw_aff_scale_down(aff1
, v
);
732 if (name
== "floord")
733 aff1
= isl_pw_aff_floor(aff1
);
735 aff1
= isl_pw_aff_ceil(aff1
);
744 /* This method is called when we come across an access that is
745 * nested in what is supposed to be an affine expression.
746 * If nesting is allowed, we return a new parameter that corresponds
747 * to this nested access. Otherwise, we simply complain.
749 * Note that we currently don't allow nested accesses themselves
750 * to contain any nested accesses, so we check if we can extract
751 * the access without any nesting and complain if we can't.
753 * The new parameter is resolved in resolve_nested.
755 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
763 if (!nesting_enabled
) {
768 allow_nested
= false;
769 access
= extract_access(expr
);
775 isl_map_free(access
);
777 id
= isl_id_alloc(ctx
, NULL
, expr
);
778 dim
= isl_space_params_alloc(ctx
, 1);
780 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
782 dom
= isl_set_universe(isl_space_copy(dim
));
783 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
784 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
786 return isl_pw_aff_alloc(dom
, aff
);
789 /* Affine expressions are not supposed to contain array accesses,
790 * but if nesting is allowed, we return a parameter corresponding
791 * to the array access.
793 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
795 return nested_access(expr
);
798 /* Extract an affine expression from a conditional operation.
800 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
802 isl_pw_aff
*cond
, *lhs
, *rhs
, *res
;
804 cond
= extract_condition(expr
->getCond());
805 lhs
= extract_affine(expr
->getTrueExpr());
806 rhs
= extract_affine(expr
->getFalseExpr());
808 return isl_pw_aff_cond(cond
, lhs
, rhs
);
811 /* Extract an affine expression, if possible, from "expr".
812 * Otherwise return NULL.
814 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
816 switch (expr
->getStmtClass()) {
817 case Stmt::ImplicitCastExprClass
:
818 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
819 case Stmt::IntegerLiteralClass
:
820 return extract_affine(cast
<IntegerLiteral
>(expr
));
821 case Stmt::DeclRefExprClass
:
822 return extract_affine(cast
<DeclRefExpr
>(expr
));
823 case Stmt::BinaryOperatorClass
:
824 return extract_affine(cast
<BinaryOperator
>(expr
));
825 case Stmt::UnaryOperatorClass
:
826 return extract_affine(cast
<UnaryOperator
>(expr
));
827 case Stmt::ParenExprClass
:
828 return extract_affine(cast
<ParenExpr
>(expr
));
829 case Stmt::CallExprClass
:
830 return extract_affine(cast
<CallExpr
>(expr
));
831 case Stmt::ArraySubscriptExprClass
:
832 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
833 case Stmt::ConditionalOperatorClass
:
834 return extract_affine(cast
<ConditionalOperator
>(expr
));
841 __isl_give isl_map
*PetScan::extract_access(ImplicitCastExpr
*expr
)
843 return extract_access(expr
->getSubExpr());
846 /* Return the depth of an array of the given type.
848 static int array_depth(const Type
*type
)
850 if (type
->isPointerType())
851 return 1 + array_depth(type
->getPointeeType().getTypePtr());
852 if (type
->isArrayType()) {
853 const ArrayType
*atype
;
854 type
= type
->getCanonicalTypeInternal().getTypePtr();
855 atype
= cast
<ArrayType
>(type
);
856 return 1 + array_depth(atype
->getElementType().getTypePtr());
861 /* Return the element type of the given array type.
863 static QualType
base_type(QualType qt
)
865 const Type
*type
= qt
.getTypePtr();
867 if (type
->isPointerType())
868 return base_type(type
->getPointeeType());
869 if (type
->isArrayType()) {
870 const ArrayType
*atype
;
871 type
= type
->getCanonicalTypeInternal().getTypePtr();
872 atype
= cast
<ArrayType
>(type
);
873 return base_type(atype
->getElementType());
878 /* Extract an access relation from a reference to a variable.
879 * If the variable has name "A" and its type corresponds to an
880 * array of depth d, then the returned access relation is of the
883 * { [] -> A[i_1,...,i_d] }
885 __isl_give isl_map
*PetScan::extract_access(DeclRefExpr
*expr
)
887 ValueDecl
*decl
= expr
->getDecl();
888 int depth
= array_depth(decl
->getType().getTypePtr());
889 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
890 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, depth
);
893 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
895 access_rel
= isl_map_universe(dim
);
900 /* Extract an access relation from an integer contant.
901 * If the value of the constant is "v", then the returned access relation
906 __isl_give isl_map
*PetScan::extract_access(IntegerLiteral
*expr
)
908 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr
)));
911 /* Try and extract an access relation from the given Expr.
912 * Return NULL if it doesn't work out.
914 __isl_give isl_map
*PetScan::extract_access(Expr
*expr
)
916 switch (expr
->getStmtClass()) {
917 case Stmt::ImplicitCastExprClass
:
918 return extract_access(cast
<ImplicitCastExpr
>(expr
));
919 case Stmt::DeclRefExprClass
:
920 return extract_access(cast
<DeclRefExpr
>(expr
));
921 case Stmt::ArraySubscriptExprClass
:
922 return extract_access(cast
<ArraySubscriptExpr
>(expr
));
923 case Stmt::IntegerLiteralClass
:
924 return extract_access(cast
<IntegerLiteral
>(expr
));
931 /* Assign the affine expression "index" to the output dimension "pos" of "map",
932 * restrict the domain to those values that result in a non-negative index
933 * and return the result.
935 __isl_give isl_map
*set_index(__isl_take isl_map
*map
, int pos
,
936 __isl_take isl_pw_aff
*index
)
939 int len
= isl_map_dim(map
, isl_dim_out
);
943 domain
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(index
));
944 index
= isl_pw_aff_intersect_domain(index
, domain
);
945 index_map
= isl_map_from_range(isl_set_from_pw_aff(index
));
946 index_map
= isl_map_insert_dims(index_map
, isl_dim_out
, 0, pos
);
947 index_map
= isl_map_add_dims(index_map
, isl_dim_out
, len
- pos
- 1);
948 id
= isl_map_get_tuple_id(map
, isl_dim_out
);
949 index_map
= isl_map_set_tuple_id(index_map
, isl_dim_out
, id
);
951 map
= isl_map_intersect(map
, index_map
);
956 /* Extract an access relation from the given array subscript expression.
957 * If nesting is allowed in general, then we turn it on while
958 * examining the index expression.
960 * We first extract an access relation from the base.
961 * This will result in an access relation with a range that corresponds
962 * to the array being accessed and with earlier indices filled in already.
963 * We then extract the current index and fill that in as well.
964 * The position of the current index is based on the type of base.
965 * If base is the actual array variable, then the depth of this type
966 * will be the same as the depth of the array and we will fill in
967 * the first array index.
968 * Otherwise, the depth of the base type will be smaller and we will fill
971 __isl_give isl_map
*PetScan::extract_access(ArraySubscriptExpr
*expr
)
973 Expr
*base
= expr
->getBase();
974 Expr
*idx
= expr
->getIdx();
976 isl_map
*base_access
;
978 int depth
= array_depth(base
->getType().getTypePtr());
980 bool save_nesting
= nesting_enabled
;
982 nesting_enabled
= allow_nested
;
984 base_access
= extract_access(base
);
985 index
= extract_affine(idx
);
987 nesting_enabled
= save_nesting
;
989 pos
= isl_map_dim(base_access
, isl_dim_out
) - depth
;
990 access
= set_index(base_access
, pos
, index
);
995 /* Check if "expr" calls function "minmax" with two arguments and if so
996 * make lhs and rhs refer to these two arguments.
998 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
1004 if (expr
->getStmtClass() != Stmt::CallExprClass
)
1007 call
= cast
<CallExpr
>(expr
);
1008 fd
= call
->getDirectCallee();
1012 if (call
->getNumArgs() != 2)
1015 name
= fd
->getDeclName().getAsString();
1019 lhs
= call
->getArg(0);
1020 rhs
= call
->getArg(1);
1025 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1026 * lhs and rhs refer to the two arguments.
1028 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1030 return is_minmax(expr
, "min", lhs
, rhs
);
1033 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1034 * lhs and rhs refer to the two arguments.
1036 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1038 return is_minmax(expr
, "max", lhs
, rhs
);
1041 /* Return "lhs && rhs", defined on the shared definition domain.
1043 static __isl_give isl_pw_aff
*pw_aff_and(__isl_take isl_pw_aff
*lhs
,
1044 __isl_take isl_pw_aff
*rhs
)
1049 dom
= isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs
)),
1050 isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1051 cond
= isl_set_intersect(isl_pw_aff_non_zero_set(lhs
),
1052 isl_pw_aff_non_zero_set(rhs
));
1053 return indicator_function(cond
, dom
);
1056 /* Return "lhs && rhs", with shortcut semantics.
1057 * That is, if lhs is false, then the result is defined even if rhs is not.
1058 * In practice, we compute lhs ? rhs : lhs.
1060 static __isl_give isl_pw_aff
*pw_aff_and_then(__isl_take isl_pw_aff
*lhs
,
1061 __isl_take isl_pw_aff
*rhs
)
1063 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), rhs
, lhs
);
1066 /* Return "lhs || rhs", with shortcut semantics.
1067 * That is, if lhs is true, then the result is defined even if rhs is not.
1068 * In practice, we compute lhs ? lhs : rhs.
1070 static __isl_give isl_pw_aff
*pw_aff_or_else(__isl_take isl_pw_aff
*lhs
,
1071 __isl_take isl_pw_aff
*rhs
)
1073 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), lhs
, rhs
);
1076 /* Extract an affine expressions representing the comparison "LHS op RHS"
1077 * "comp" is the original statement that "LHS op RHS" is derived from
1078 * and is used for diagnostics.
1080 * If the comparison is of the form
1084 * then the expression is constructed as the conjunction of
1089 * A similar optimization is performed for max(a,b) <= c.
1090 * We do this because that will lead to simpler representations
1091 * of the expression.
1092 * If isl is ever enhanced to explicitly deal with min and max expressions,
1093 * this optimization can be removed.
1095 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
1096 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
1105 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
1107 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
1109 if (op
== BO_LT
|| op
== BO_LE
) {
1110 Expr
*expr1
, *expr2
;
1111 if (is_min(RHS
, expr1
, expr2
)) {
1112 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
1113 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
1114 return pw_aff_and(lhs
, rhs
);
1116 if (is_max(LHS
, expr1
, expr2
)) {
1117 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
1118 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
1119 return pw_aff_and(lhs
, rhs
);
1123 lhs
= extract_affine(LHS
);
1124 rhs
= extract_affine(RHS
);
1126 dom
= isl_pw_aff_domain(isl_pw_aff_copy(lhs
));
1127 dom
= isl_set_intersect(dom
, isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1131 cond
= isl_pw_aff_lt_set(lhs
, rhs
);
1134 cond
= isl_pw_aff_le_set(lhs
, rhs
);
1137 cond
= isl_pw_aff_eq_set(lhs
, rhs
);
1140 cond
= isl_pw_aff_ne_set(lhs
, rhs
);
1143 isl_pw_aff_free(lhs
);
1144 isl_pw_aff_free(rhs
);
1150 cond
= isl_set_coalesce(cond
);
1151 res
= indicator_function(cond
, dom
);
1156 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
1158 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1159 comp
->getRHS(), comp
);
1162 /* Extract an affine expression representing the negation (logical not)
1163 * of a subexpression.
1165 __isl_give isl_pw_aff
*PetScan::extract_boolean(UnaryOperator
*op
)
1167 isl_set
*set_cond
, *dom
;
1168 isl_pw_aff
*cond
, *res
;
1170 cond
= extract_condition(op
->getSubExpr());
1172 dom
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
1174 set_cond
= isl_pw_aff_zero_set(cond
);
1176 res
= indicator_function(set_cond
, dom
);
1181 /* Extract an affine expression representing the disjunction (logical or)
1182 * or conjunction (logical and) of two subexpressions.
1184 __isl_give isl_pw_aff
*PetScan::extract_boolean(BinaryOperator
*comp
)
1186 isl_pw_aff
*lhs
, *rhs
;
1188 lhs
= extract_condition(comp
->getLHS());
1189 rhs
= extract_condition(comp
->getRHS());
1191 switch (comp
->getOpcode()) {
1193 return pw_aff_and_then(lhs
, rhs
);
1195 return pw_aff_or_else(lhs
, rhs
);
1197 isl_pw_aff_free(lhs
);
1198 isl_pw_aff_free(rhs
);
1205 __isl_give isl_pw_aff
*PetScan::extract_condition(UnaryOperator
*expr
)
1207 switch (expr
->getOpcode()) {
1209 return extract_boolean(expr
);
1216 /* Extract the affine expression "expr != 0 ? 1 : 0".
1218 __isl_give isl_pw_aff
*PetScan::extract_implicit_condition(Expr
*expr
)
1223 res
= extract_affine(expr
);
1225 dom
= isl_pw_aff_domain(isl_pw_aff_copy(res
));
1226 set
= isl_pw_aff_non_zero_set(res
);
1228 res
= indicator_function(set
, dom
);
1233 /* Extract an affine expression from a boolean expression.
1234 * In particular, return the expression "expr ? 1 : 0".
1236 * If the expression doesn't look like a condition, we assume it
1237 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1239 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
1241 BinaryOperator
*comp
;
1244 isl_set
*u
= isl_set_universe(isl_space_params_alloc(ctx
, 0));
1245 return indicator_function(u
, isl_set_copy(u
));
1248 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1249 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1251 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1252 return extract_condition(cast
<UnaryOperator
>(expr
));
1254 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1255 return extract_implicit_condition(expr
);
1257 comp
= cast
<BinaryOperator
>(expr
);
1258 switch (comp
->getOpcode()) {
1265 return extract_comparison(comp
);
1268 return extract_boolean(comp
);
1270 return extract_implicit_condition(expr
);
1274 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
1278 return pet_op_minus
;
1280 return pet_op_post_inc
;
1282 return pet_op_post_dec
;
1284 return pet_op_pre_inc
;
1286 return pet_op_pre_dec
;
1292 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
1296 return pet_op_add_assign
;
1298 return pet_op_sub_assign
;
1300 return pet_op_mul_assign
;
1302 return pet_op_div_assign
;
1304 return pet_op_assign
;
1328 /* Construct a pet_expr representing a unary operator expression.
1330 struct pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1332 struct pet_expr
*arg
;
1333 enum pet_op_type op
;
1335 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1336 if (op
== pet_op_last
) {
1341 arg
= extract_expr(expr
->getSubExpr());
1343 if (expr
->isIncrementDecrementOp() &&
1344 arg
&& arg
->type
== pet_expr_access
) {
1349 return pet_expr_new_unary(ctx
, op
, arg
);
1352 /* Mark the given access pet_expr as a write.
1353 * If a scalar is being accessed, then mark its value
1354 * as unknown in assigned_value.
1356 void PetScan::mark_write(struct pet_expr
*access
)
1361 access
->acc
.write
= 1;
1362 access
->acc
.read
= 0;
1364 if (isl_map_dim(access
->acc
.access
, isl_dim_out
) != 0)
1367 id
= isl_map_get_tuple_id(access
->acc
.access
, isl_dim_out
);
1368 decl
= (ValueDecl
*) isl_id_get_user(id
);
1369 clear_assignment(assigned_value
, decl
);
1373 /* Construct a pet_expr representing a binary operator expression.
1375 * If the top level operator is an assignment and the LHS is an access,
1376 * then we mark that access as a write. If the operator is a compound
1377 * assignment, the access is marked as both a read and a write.
1379 * If "expr" assigns something to a scalar variable, then we mark
1380 * the variable as having been assigned. If, furthermore, the expression
1381 * is affine, then keep track of this value in assigned_value
1382 * so that we can plug it in when we later come across the same variable.
1384 struct pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1386 struct pet_expr
*lhs
, *rhs
;
1387 enum pet_op_type op
;
1389 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1390 if (op
== pet_op_last
) {
1395 lhs
= extract_expr(expr
->getLHS());
1396 rhs
= extract_expr(expr
->getRHS());
1398 if (expr
->isAssignmentOp() && lhs
&& lhs
->type
== pet_expr_access
) {
1400 if (expr
->isCompoundAssignmentOp())
1404 if (expr
->getOpcode() == BO_Assign
&&
1405 lhs
&& lhs
->type
== pet_expr_access
&&
1406 isl_map_dim(lhs
->acc
.access
, isl_dim_out
) == 0) {
1407 isl_id
*id
= isl_map_get_tuple_id(lhs
->acc
.access
, isl_dim_out
);
1408 ValueDecl
*decl
= (ValueDecl
*) isl_id_get_user(id
);
1409 Expr
*rhs
= expr
->getRHS();
1410 isl_pw_aff
*pa
= try_extract_affine(rhs
);
1411 clear_assignment(assigned_value
, decl
);
1413 assigned_value
[decl
] = pa
;
1414 insert_expression(pa
);
1419 return pet_expr_new_binary(ctx
, op
, lhs
, rhs
);
1422 /* Construct a pet_expr representing a conditional operation.
1424 * We first try to extract the condition as an affine expression.
1425 * If that fails, we construct a pet_expr tree representing the condition.
1427 struct pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1429 struct pet_expr
*cond
, *lhs
, *rhs
;
1432 pa
= try_extract_affine(expr
->getCond());
1434 isl_set
*test
= isl_set_from_pw_aff(pa
);
1435 cond
= pet_expr_from_access(isl_map_from_range(test
));
1437 cond
= extract_expr(expr
->getCond());
1438 lhs
= extract_expr(expr
->getTrueExpr());
1439 rhs
= extract_expr(expr
->getFalseExpr());
1441 return pet_expr_new_ternary(ctx
, cond
, lhs
, rhs
);
1444 struct pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1446 return extract_expr(expr
->getSubExpr());
1449 /* Construct a pet_expr representing a floating point value.
1451 struct pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1453 return pet_expr_new_double(ctx
, expr
->getValueAsApproximateDouble());
1456 /* Extract an access relation from "expr" and then convert it into
1459 struct pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1462 struct pet_expr
*pe
;
1464 access
= extract_access(expr
);
1466 pe
= pet_expr_from_access(access
);
1471 struct pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1473 return extract_expr(expr
->getSubExpr());
1476 /* Construct a pet_expr representing a function call.
1478 * If we are passing along a pointer to an array element
1479 * or an entire row or even higher dimensional slice of an array,
1480 * then the function being called may write into the array.
1482 * We assume here that if the function is declared to take a pointer
1483 * to a const type, then the function will perform a read
1484 * and that otherwise, it will perform a write.
1486 struct pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1488 struct pet_expr
*res
= NULL
;
1492 fd
= expr
->getDirectCallee();
1498 name
= fd
->getDeclName().getAsString();
1499 res
= pet_expr_new_call(ctx
, name
.c_str(), expr
->getNumArgs());
1503 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
1504 Expr
*arg
= expr
->getArg(i
);
1508 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1509 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(arg
);
1510 arg
= ice
->getSubExpr();
1512 if (arg
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1513 UnaryOperator
*op
= cast
<UnaryOperator
>(arg
);
1514 if (op
->getOpcode() == UO_AddrOf
) {
1516 arg
= op
->getSubExpr();
1519 res
->args
[i
] = PetScan::extract_expr(arg
);
1520 main_arg
= res
->args
[i
];
1522 res
->args
[i
] = pet_expr_new_unary(ctx
,
1523 pet_op_address_of
, res
->args
[i
]);
1526 if (arg
->getStmtClass() == Stmt::ArraySubscriptExprClass
&&
1527 array_depth(arg
->getType().getTypePtr()) > 0)
1529 if (is_addr
&& main_arg
->type
== pet_expr_access
) {
1531 if (!fd
->hasPrototype()) {
1532 unsupported(expr
, "prototype required");
1535 parm
= fd
->getParamDecl(i
);
1536 if (!const_base(parm
->getType()))
1537 mark_write(main_arg
);
1547 /* Try and onstruct a pet_expr representing "expr".
1549 struct pet_expr
*PetScan::extract_expr(Expr
*expr
)
1551 switch (expr
->getStmtClass()) {
1552 case Stmt::UnaryOperatorClass
:
1553 return extract_expr(cast
<UnaryOperator
>(expr
));
1554 case Stmt::CompoundAssignOperatorClass
:
1555 case Stmt::BinaryOperatorClass
:
1556 return extract_expr(cast
<BinaryOperator
>(expr
));
1557 case Stmt::ImplicitCastExprClass
:
1558 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1559 case Stmt::ArraySubscriptExprClass
:
1560 case Stmt::DeclRefExprClass
:
1561 case Stmt::IntegerLiteralClass
:
1562 return extract_access_expr(expr
);
1563 case Stmt::FloatingLiteralClass
:
1564 return extract_expr(cast
<FloatingLiteral
>(expr
));
1565 case Stmt::ParenExprClass
:
1566 return extract_expr(cast
<ParenExpr
>(expr
));
1567 case Stmt::ConditionalOperatorClass
:
1568 return extract_expr(cast
<ConditionalOperator
>(expr
));
1569 case Stmt::CallExprClass
:
1570 return extract_expr(cast
<CallExpr
>(expr
));
1577 /* Check if the given initialization statement is an assignment.
1578 * If so, return that assignment. Otherwise return NULL.
1580 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1582 BinaryOperator
*ass
;
1584 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1587 ass
= cast
<BinaryOperator
>(init
);
1588 if (ass
->getOpcode() != BO_Assign
)
1594 /* Check if the given initialization statement is a declaration
1595 * of a single variable.
1596 * If so, return that declaration. Otherwise return NULL.
1598 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1602 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1605 decl
= cast
<DeclStmt
>(init
);
1607 if (!decl
->isSingleDecl())
1610 return decl
->getSingleDecl();
1613 /* Given the assignment operator in the initialization of a for loop,
1614 * extract the induction variable, i.e., the (integer)variable being
1617 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1624 lhs
= init
->getLHS();
1625 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1630 ref
= cast
<DeclRefExpr
>(lhs
);
1631 decl
= ref
->getDecl();
1632 type
= decl
->getType().getTypePtr();
1634 if (!type
->isIntegerType()) {
1642 /* Given the initialization statement of a for loop and the single
1643 * declaration in this initialization statement,
1644 * extract the induction variable, i.e., the (integer) variable being
1647 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1651 vd
= cast
<VarDecl
>(decl
);
1653 const QualType type
= vd
->getType();
1654 if (!type
->isIntegerType()) {
1659 if (!vd
->getInit()) {
1667 /* Check that op is of the form iv++ or iv--.
1668 * Return an affine expression "1" or "-1" accordingly.
1670 __isl_give isl_pw_aff
*PetScan::extract_unary_increment(
1671 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1678 if (!op
->isIncrementDecrementOp()) {
1683 sub
= op
->getSubExpr();
1684 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1689 ref
= cast
<DeclRefExpr
>(sub
);
1690 if (ref
->getDecl() != iv
) {
1695 space
= isl_space_params_alloc(ctx
, 0);
1696 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
1698 if (op
->isIncrementOp())
1699 aff
= isl_aff_add_constant_si(aff
, 1);
1701 aff
= isl_aff_add_constant_si(aff
, -1);
1703 return isl_pw_aff_from_aff(aff
);
1706 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1707 * has a single constant expression, then put this constant in *user.
1708 * The caller is assumed to have checked that this function will
1709 * be called exactly once.
1711 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
1714 isl_int
*inc
= (isl_int
*)user
;
1717 if (isl_aff_is_cst(aff
))
1718 isl_aff_get_constant(aff
, inc
);
1728 /* Check if op is of the form
1732 * and return inc as an affine expression.
1734 * We extract an affine expression from the RHS, subtract iv and return
1737 __isl_give isl_pw_aff
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1738 clang::ValueDecl
*iv
)
1747 if (op
->getOpcode() != BO_Assign
) {
1753 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1758 ref
= cast
<DeclRefExpr
>(lhs
);
1759 if (ref
->getDecl() != iv
) {
1764 val
= extract_affine(op
->getRHS());
1766 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1768 dim
= isl_space_params_alloc(ctx
, 1);
1769 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1770 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1771 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1773 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
1778 /* Check that op is of the form iv += cst or iv -= cst
1779 * and return an affine expression corresponding oto cst or -cst accordingly.
1781 __isl_give isl_pw_aff
*PetScan::extract_compound_increment(
1782 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1788 BinaryOperatorKind opcode
;
1790 opcode
= op
->getOpcode();
1791 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1795 if (opcode
== BO_SubAssign
)
1799 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1804 ref
= cast
<DeclRefExpr
>(lhs
);
1805 if (ref
->getDecl() != iv
) {
1810 val
= extract_affine(op
->getRHS());
1812 val
= isl_pw_aff_neg(val
);
1817 /* Check that the increment of the given for loop increments
1818 * (or decrements) the induction variable "iv" and return
1819 * the increment as an affine expression if successful.
1821 __isl_give isl_pw_aff
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1824 Stmt
*inc
= stmt
->getInc();
1831 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1832 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1833 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1834 return extract_compound_increment(
1835 cast
<CompoundAssignOperator
>(inc
), iv
);
1836 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1837 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1843 /* Embed the given iteration domain in an extra outer loop
1844 * with induction variable "var".
1845 * If this variable appeared as a parameter in the constraints,
1846 * it is replaced by the new outermost dimension.
1848 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1849 __isl_take isl_id
*var
)
1853 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1854 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1856 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1857 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1864 /* Return those elements in the space of "cond" that come after
1865 * (based on "sign") an element in "cond".
1867 static __isl_give isl_set
*after(__isl_take isl_set
*cond
, int sign
)
1869 isl_map
*previous_to_this
;
1872 previous_to_this
= isl_map_lex_lt(isl_set_get_space(cond
));
1874 previous_to_this
= isl_map_lex_gt(isl_set_get_space(cond
));
1876 cond
= isl_set_apply(cond
, previous_to_this
);
1881 /* Create the infinite iteration domain
1883 * { [id] : id >= 0 }
1885 * If "scop" has an affine skip of type pet_skip_later,
1886 * then remove those iterations i that have an earlier iteration
1887 * where the skip condition is satisfied, meaning that iteration i
1889 * Since we are dealing with a loop without loop iterator,
1890 * the skip condition cannot refer to the current loop iterator and
1891 * so effectively, the returned set is of the form
1893 * { [0]; [id] : id >= 1 and not skip }
1895 static __isl_give isl_set
*infinite_domain(__isl_take isl_id
*id
,
1896 struct pet_scop
*scop
)
1898 isl_ctx
*ctx
= isl_id_get_ctx(id
);
1902 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
1903 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, id
);
1905 if (!pet_scop_has_affine_skip(scop
, pet_skip_later
))
1908 skip
= pet_scop_get_skip(scop
, pet_skip_later
);
1909 skip
= isl_set_fix_si(skip
, isl_dim_set
, 0, 1);
1910 skip
= isl_set_params(skip
);
1911 skip
= embed(skip
, isl_id_copy(id
));
1912 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
1913 domain
= isl_set_subtract(domain
, after(skip
, 1));
1918 /* Create an identity mapping on the space containing "domain".
1920 static __isl_give isl_map
*identity_map(__isl_keep isl_set
*domain
)
1925 space
= isl_space_map_from_set(isl_set_get_space(domain
));
1926 id
= isl_map_identity(space
);
1931 /* Add a filter to "scop" that imposes that it is only executed
1932 * when "break_access" has a zero value for all previous iterations
1935 * The input "break_access" has a zero-dimensional domain and range.
1937 static struct pet_scop
*scop_add_break(struct pet_scop
*scop
,
1938 __isl_take isl_map
*break_access
, __isl_take isl_set
*domain
, int sign
)
1940 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
1944 id_test
= isl_map_get_tuple_id(break_access
, isl_dim_out
);
1945 break_access
= isl_map_add_dims(break_access
, isl_dim_in
, 1);
1946 break_access
= isl_map_add_dims(break_access
, isl_dim_out
, 1);
1947 break_access
= isl_map_intersect_range(break_access
, domain
);
1948 break_access
= isl_map_set_tuple_id(break_access
, isl_dim_out
, id_test
);
1950 prev
= isl_map_lex_gt_first(isl_map_get_space(break_access
), 1);
1952 prev
= isl_map_lex_lt_first(isl_map_get_space(break_access
), 1);
1953 break_access
= isl_map_intersect(break_access
, prev
);
1954 scop
= pet_scop_filter(scop
, break_access
, 0);
1955 scop
= pet_scop_merge_filters(scop
);
1960 /* Construct a pet_scop for an infinite loop around the given body.
1962 * We extract a pet_scop for the body and then embed it in a loop with
1971 * If the body contains any break, then it is taken into
1972 * account in infinite_domain (if the skip condition is affine)
1973 * or in scop_add_break (if the skip condition is not affine).
1975 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
1981 struct pet_scop
*scop
;
1984 scop
= extract(body
);
1988 id
= isl_id_alloc(ctx
, "t", NULL
);
1989 domain
= infinite_domain(isl_id_copy(id
), scop
);
1990 ident
= identity_map(domain
);
1992 has_var_break
= pet_scop_has_var_skip(scop
, pet_skip_later
);
1994 access
= pet_scop_get_skip_map(scop
, pet_skip_later
);
1996 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
1997 isl_map_copy(ident
), ident
, id
);
1999 scop
= scop_add_break(scop
, access
, domain
, 1);
2001 isl_set_free(domain
);
2006 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2012 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
2014 return extract_infinite_loop(stmt
->getBody());
2017 /* Create an access to a virtual array representing the result
2019 * Unlike other accessed data, the id of the array is NULL as
2020 * there is no ValueDecl in the program corresponding to the virtual
2022 * The array starts out as a scalar, but grows along with the
2023 * statement writing to the array in pet_scop_embed.
2025 static __isl_give isl_map
*create_test_access(isl_ctx
*ctx
, int test_nr
)
2027 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, 0);
2031 snprintf(name
, sizeof(name
), "__pet_test_%d", test_nr
);
2032 id
= isl_id_alloc(ctx
, name
, NULL
);
2033 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
2034 return isl_map_universe(dim
);
2037 /* Add an array with the given extent ("access") to the list
2038 * of arrays in "scop" and return the extended pet_scop.
2039 * The array is marked as attaining values 0 and 1 only and
2040 * as each element being assigned at most once.
2042 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2043 __isl_keep isl_map
*access
, clang::ASTContext
&ast_ctx
)
2045 isl_ctx
*ctx
= isl_map_get_ctx(access
);
2047 struct pet_array
**arrays
;
2048 struct pet_array
*array
;
2055 arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
2059 scop
->arrays
= arrays
;
2061 array
= isl_calloc_type(ctx
, struct pet_array
);
2065 array
->extent
= isl_map_range(isl_map_copy(access
));
2066 dim
= isl_space_params_alloc(ctx
, 0);
2067 array
->context
= isl_set_universe(dim
);
2068 dim
= isl_space_set_alloc(ctx
, 0, 1);
2069 array
->value_bounds
= isl_set_universe(dim
);
2070 array
->value_bounds
= isl_set_lower_bound_si(array
->value_bounds
,
2072 array
->value_bounds
= isl_set_upper_bound_si(array
->value_bounds
,
2074 array
->element_type
= strdup("int");
2075 array
->element_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
2076 array
->uniquely_defined
= 1;
2078 scop
->arrays
[scop
->n_array
] = array
;
2081 if (!array
->extent
|| !array
->context
)
2086 pet_scop_free(scop
);
2090 /* Construct a pet_scop for a while loop of the form
2095 * In particular, construct a scop for an infinite loop around body and
2096 * intersect the domain with the affine expression.
2097 * Note that this intersection may result in an empty loop.
2099 struct pet_scop
*PetScan::extract_affine_while(__isl_take isl_pw_aff
*pa
,
2102 struct pet_scop
*scop
;
2106 valid
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2107 dom
= isl_pw_aff_non_zero_set(pa
);
2108 scop
= extract_infinite_loop(body
);
2109 scop
= pet_scop_restrict(scop
, dom
);
2110 scop
= pet_scop_restrict_context(scop
, valid
);
2115 /* Construct a scop for a while, given the scops for the condition
2116 * and the body, the filter access and the iteration domain of
2119 * In particular, the scop for the condition is filtered to depend
2120 * on "test_access" evaluating to true for all previous iterations
2121 * of the loop, while the scop for the body is filtered to depend
2122 * on "test_access" evaluating to true for all iterations up to the
2123 * current iteration.
2125 * These filtered scops are then combined into a single scop.
2127 * "sign" is positive if the iterator increases and negative
2130 static struct pet_scop
*scop_add_while(struct pet_scop
*scop_cond
,
2131 struct pet_scop
*scop_body
, __isl_take isl_map
*test_access
,
2132 __isl_take isl_set
*domain
, int sign
)
2134 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
2138 id_test
= isl_map_get_tuple_id(test_access
, isl_dim_out
);
2139 test_access
= isl_map_add_dims(test_access
, isl_dim_in
, 1);
2140 test_access
= isl_map_add_dims(test_access
, isl_dim_out
, 1);
2141 test_access
= isl_map_intersect_range(test_access
, domain
);
2142 test_access
= isl_map_set_tuple_id(test_access
, isl_dim_out
, id_test
);
2144 prev
= isl_map_lex_ge_first(isl_map_get_space(test_access
), 1);
2146 prev
= isl_map_lex_le_first(isl_map_get_space(test_access
), 1);
2147 test_access
= isl_map_intersect(test_access
, prev
);
2148 scop_body
= pet_scop_filter(scop_body
, isl_map_copy(test_access
), 1);
2150 prev
= isl_map_lex_gt_first(isl_map_get_space(test_access
), 1);
2152 prev
= isl_map_lex_lt_first(isl_map_get_space(test_access
), 1);
2153 test_access
= isl_map_intersect(test_access
, prev
);
2154 scop_cond
= pet_scop_filter(scop_cond
, test_access
, 1);
2156 return pet_scop_add_seq(ctx
, scop_cond
, scop_body
);
2159 /* Check if the while loop is of the form
2161 * while (affine expression)
2164 * If so, call extract_affine_while to construct a scop.
2166 * Otherwise, construct a generic while scop, with iteration domain
2167 * { [t] : t >= 0 }. The scop consists of two parts, one for
2168 * evaluating the condition and one for the body.
2169 * The schedule is adjusted to reflect that the condition is evaluated
2170 * before the body is executed and the body is filtered to depend
2171 * on the result of the condition evaluating to true on all iterations
2172 * up to the current iteration, while the evaluation the condition itself
2173 * is filtered to depend on the result of the condition evaluating to true
2174 * on all previous iterations.
2175 * The context of the scop representing the body is dropped
2176 * because we don't know how many times the body will be executed,
2179 * If the body contains any break, then it is taken into
2180 * account in infinite_domain (if the skip condition is affine)
2181 * or in scop_add_break (if the skip condition is not affine).
2183 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
2187 isl_map
*test_access
;
2191 struct pet_scop
*scop
, *scop_body
;
2193 isl_map
*break_access
;
2195 cond
= stmt
->getCond();
2201 pa
= try_extract_affine_condition(cond
);
2203 return extract_affine_while(pa
, stmt
->getBody());
2205 if (!allow_nested
) {
2210 test_access
= create_test_access(ctx
, n_test
++);
2211 scop
= extract_non_affine_condition(cond
, isl_map_copy(test_access
));
2212 scop
= scop_add_array(scop
, test_access
, ast_context
);
2213 scop_body
= extract(stmt
->getBody());
2215 id
= isl_id_alloc(ctx
, "t", NULL
);
2216 domain
= infinite_domain(isl_id_copy(id
), scop_body
);
2217 ident
= identity_map(domain
);
2219 has_var_break
= pet_scop_has_var_skip(scop_body
, pet_skip_later
);
2221 break_access
= pet_scop_get_skip_map(scop_body
, pet_skip_later
);
2223 scop
= pet_scop_prefix(scop
, 0);
2224 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), isl_map_copy(ident
),
2225 isl_map_copy(ident
), isl_id_copy(id
));
2226 scop_body
= pet_scop_reset_context(scop_body
);
2227 scop_body
= pet_scop_prefix(scop_body
, 1);
2228 scop_body
= pet_scop_embed(scop_body
, isl_set_copy(domain
),
2229 isl_map_copy(ident
), ident
, id
);
2231 if (has_var_break
) {
2232 scop
= scop_add_break(scop
, isl_map_copy(break_access
),
2233 isl_set_copy(domain
), 1);
2234 scop_body
= scop_add_break(scop_body
, break_access
,
2235 isl_set_copy(domain
), 1);
2237 scop
= scop_add_while(scop
, scop_body
, test_access
, domain
, 1);
2242 /* Check whether "cond" expresses a simple loop bound
2243 * on the only set dimension.
2244 * In particular, if "up" is set then "cond" should contain only
2245 * upper bounds on the set dimension.
2246 * Otherwise, it should contain only lower bounds.
2248 static bool is_simple_bound(__isl_keep isl_set
*cond
, isl_int inc
)
2250 if (isl_int_is_pos(inc
))
2251 return !isl_set_dim_has_any_lower_bound(cond
, isl_dim_set
, 0);
2253 return !isl_set_dim_has_any_upper_bound(cond
, isl_dim_set
, 0);
2256 /* Extend a condition on a given iteration of a loop to one that
2257 * imposes the same condition on all previous iterations.
2258 * "domain" expresses the lower [upper] bound on the iterations
2259 * when inc is positive [negative].
2261 * In particular, we construct the condition (when inc is positive)
2263 * forall i' : (domain(i') and i' <= i) => cond(i')
2265 * which is equivalent to
2267 * not exists i' : domain(i') and i' <= i and not cond(i')
2269 * We construct this set by negating cond, applying a map
2271 * { [i'] -> [i] : domain(i') and i' <= i }
2273 * and then negating the result again.
2275 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
2276 __isl_take isl_set
*domain
, isl_int inc
)
2278 isl_map
*previous_to_this
;
2280 if (isl_int_is_pos(inc
))
2281 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
2283 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
2285 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
2287 cond
= isl_set_complement(cond
);
2288 cond
= isl_set_apply(cond
, previous_to_this
);
2289 cond
= isl_set_complement(cond
);
2294 /* Construct a domain of the form
2296 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2298 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
2299 __isl_take isl_pw_aff
*init
, isl_int inc
)
2305 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
2306 dim
= isl_pw_aff_get_domain_space(init
);
2307 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2308 aff
= isl_aff_add_coefficient(aff
, isl_dim_in
, 0, inc
);
2309 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2311 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2312 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2313 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2314 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2316 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2318 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2320 return isl_set_params(set
);
2323 /* Assuming "cond" represents a bound on a loop where the loop
2324 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2327 * Under the given assumptions, wrapping is only possible if "cond" allows
2328 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2329 * increasing iterator and 0 in case of a decreasing iterator.
2331 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
, isl_int inc
)
2337 test
= isl_set_copy(cond
);
2339 isl_int_init(limit
);
2340 if (isl_int_is_neg(inc
))
2341 isl_int_set_si(limit
, 0);
2343 isl_int_set_si(limit
, 1);
2344 isl_int_mul_2exp(limit
, limit
, get_type_size(iv
));
2345 isl_int_sub_ui(limit
, limit
, 1);
2348 test
= isl_set_fix(cond
, isl_dim_set
, 0, limit
);
2349 cw
= !isl_set_is_empty(test
);
2352 isl_int_clear(limit
);
2357 /* Given a one-dimensional space, construct the following mapping on this
2360 * { [v] -> [v mod 2^width] }
2362 * where width is the number of bits used to represent the values
2363 * of the unsigned variable "iv".
2365 static __isl_give isl_map
*compute_wrapping(__isl_take isl_space
*dim
,
2373 isl_int_set_si(mod
, 1);
2374 isl_int_mul_2exp(mod
, mod
, get_type_size(iv
));
2376 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2377 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2378 aff
= isl_aff_mod(aff
, mod
);
2382 return isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2383 map
= isl_map_reverse(map
);
2386 /* Project out the parameter "id" from "set".
2388 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2389 __isl_keep isl_id
*id
)
2393 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2395 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2400 /* Compute the set of parameters for which "set1" is a subset of "set2".
2402 * set1 is a subset of set2 if
2404 * forall i in set1 : i in set2
2408 * not exists i in set1 and i not in set2
2412 * not exists i in set1 \ set2
2414 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2415 __isl_take isl_set
*set2
)
2417 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2420 /* Compute the set of parameter values for which "cond" holds
2421 * on the next iteration for each element of "dom".
2423 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2424 * and then compute the set of parameters for which the result is a subset
2427 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2428 __isl_take isl_set
*dom
, isl_int inc
)
2434 space
= isl_set_get_space(dom
);
2435 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2436 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2437 aff
= isl_aff_add_constant(aff
, inc
);
2438 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2440 dom
= isl_set_apply(dom
, next
);
2442 return enforce_subset(dom
, cond
);
2445 /* Does "id" refer to a nested access?
2447 static bool is_nested_parameter(__isl_keep isl_id
*id
)
2449 return id
&& isl_id_get_user(id
) && !isl_id_get_name(id
);
2452 /* Does parameter "pos" of "space" refer to a nested access?
2454 static bool is_nested_parameter(__isl_keep isl_space
*space
, int pos
)
2459 id
= isl_space_get_dim_id(space
, isl_dim_param
, pos
);
2460 nested
= is_nested_parameter(id
);
2466 /* Does "space" involve any parameters that refer to nested
2467 * accesses, i.e., parameters with no name?
2469 static bool has_nested(__isl_keep isl_space
*space
)
2473 nparam
= isl_space_dim(space
, isl_dim_param
);
2474 for (int i
= 0; i
< nparam
; ++i
)
2475 if (is_nested_parameter(space
, i
))
2481 /* Does "pa" involve any parameters that refer to nested
2482 * accesses, i.e., parameters with no name?
2484 static bool has_nested(__isl_keep isl_pw_aff
*pa
)
2489 space
= isl_pw_aff_get_space(pa
);
2490 nested
= has_nested(space
);
2491 isl_space_free(space
);
2496 /* Construct a pet_scop for a for statement.
2497 * The for loop is required to be of the form
2499 * for (i = init; condition; ++i)
2503 * for (i = init; condition; --i)
2505 * The initialization of the for loop should either be an assignment
2506 * to an integer variable, or a declaration of such a variable with
2509 * The condition is allowed to contain nested accesses, provided
2510 * they are not being written to inside the body of the loop.
2511 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2512 * essentially treated as a while loop, with iteration domain
2513 * { [i] : i >= init }.
2515 * We extract a pet_scop for the body and then embed it in a loop with
2516 * iteration domain and schedule
2518 * { [i] : i >= init and condition' }
2523 * { [i] : i <= init and condition' }
2526 * Where condition' is equal to condition if the latter is
2527 * a simple upper [lower] bound and a condition that is extended
2528 * to apply to all previous iterations otherwise.
2530 * If the condition is non-affine, then we drop the condition from the
2531 * iteration domain and instead create a separate statement
2532 * for evaluating the condition. The body is then filtered to depend
2533 * on the result of the condition evaluating to true on all iterations
2534 * up to the current iteration, while the evaluation the condition itself
2535 * is filtered to depend on the result of the condition evaluating to true
2536 * on all previous iterations.
2537 * The context of the scop representing the body is dropped
2538 * because we don't know how many times the body will be executed,
2541 * If the stride of the loop is not 1, then "i >= init" is replaced by
2543 * (exists a: i = init + stride * a and a >= 0)
2545 * If the loop iterator i is unsigned, then wrapping may occur.
2546 * During the computation, we work with a virtual iterator that
2547 * does not wrap. However, the condition in the code applies
2548 * to the wrapped value, so we need to change condition(i)
2549 * into condition([i % 2^width]).
2550 * After computing the virtual domain and schedule, we apply
2551 * the function { [v] -> [v % 2^width] } to the domain and the domain
2552 * of the schedule. In order not to lose any information, we also
2553 * need to intersect the domain of the schedule with the virtual domain
2554 * first, since some iterations in the wrapped domain may be scheduled
2555 * several times, typically an infinite number of times.
2556 * Note that there may be no need to perform this final wrapping
2557 * if the loop condition (after wrapping) satisfies certain conditions.
2558 * However, the is_simple_bound condition is not enough since it doesn't
2559 * check if there even is an upper bound.
2561 * If the loop condition is non-affine, then we keep the virtual
2562 * iterator in the iteration domain and instead replace all accesses
2563 * to the original iterator by the wrapping of the virtual iterator.
2565 * Wrapping on unsigned iterators can be avoided entirely if
2566 * loop condition is simple, the loop iterator is incremented
2567 * [decremented] by one and the last value before wrapping cannot
2568 * possibly satisfy the loop condition.
2570 * Before extracting a pet_scop from the body we remove all
2571 * assignments in assigned_value to variables that are assigned
2572 * somewhere in the body of the loop.
2574 * Valid parameters for a for loop are those for which the initial
2575 * value itself, the increment on each domain iteration and
2576 * the condition on both the initial value and
2577 * the result of incrementing the iterator for each iteration of the domain
2579 * If the loop condition is non-affine, then we only consider validity
2580 * of the initial value.
2582 * If the body contains any break, then we keep track of it in "skip"
2583 * (if the skip condition is affine) or it is handled in scop_add_break
2584 * (if the skip condition is not affine).
2585 * Note that the affine break condition needs to be considered with
2586 * respect to previous iterations in the virtual domain (if any)
2587 * and that the domain needs to be kept virtual if there is a non-affine
2590 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2592 BinaryOperator
*ass
;
2600 isl_set
*cond
= NULL
;
2601 isl_set
*skip
= NULL
;
2603 struct pet_scop
*scop
, *scop_cond
= NULL
;
2604 assigned_value_cache
cache(assigned_value
);
2610 bool keep_virtual
= false;
2611 bool has_affine_break
;
2613 isl_map
*wrap
= NULL
;
2614 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2615 isl_set
*valid_init
;
2616 isl_set
*valid_cond
;
2617 isl_set
*valid_cond_init
;
2618 isl_set
*valid_cond_next
;
2620 isl_map
*test_access
= NULL
, *break_access
= NULL
;
2623 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2624 return extract_infinite_for(stmt
);
2626 init
= stmt
->getInit();
2631 if ((ass
= initialization_assignment(init
)) != NULL
) {
2632 iv
= extract_induction_variable(ass
);
2635 lhs
= ass
->getLHS();
2636 rhs
= ass
->getRHS();
2637 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2638 VarDecl
*var
= extract_induction_variable(init
, decl
);
2642 rhs
= var
->getInit();
2643 lhs
= create_DeclRefExpr(var
);
2645 unsupported(stmt
->getInit());
2649 pa_inc
= extract_increment(stmt
, iv
);
2654 if (isl_pw_aff_n_piece(pa_inc
) != 1 ||
2655 isl_pw_aff_foreach_piece(pa_inc
, &extract_cst
, &inc
) < 0) {
2656 isl_pw_aff_free(pa_inc
);
2657 unsupported(stmt
->getInc());
2661 valid_inc
= isl_pw_aff_domain(pa_inc
);
2663 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2665 assigned_value
.erase(iv
);
2666 clear_assignments
clear(assigned_value
);
2667 clear
.TraverseStmt(stmt
->getBody());
2669 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
2671 pa
= try_extract_nested_condition(stmt
->getCond());
2672 if (allow_nested
&& (!pa
|| has_nested(pa
)))
2675 scop
= extract(stmt
->getBody());
2677 has_affine_break
= scop
&&
2678 pet_scop_has_affine_skip(scop
, pet_skip_later
);
2679 if (has_affine_break
) {
2680 skip
= pet_scop_get_skip(scop
, pet_skip_later
);
2681 skip
= isl_set_fix_si(skip
, isl_dim_set
, 0, 1);
2682 skip
= isl_set_params(skip
);
2684 has_var_break
= scop
&& pet_scop_has_var_skip(scop
, pet_skip_later
);
2685 if (has_var_break
) {
2686 break_access
= pet_scop_get_skip_map(scop
, pet_skip_later
);
2687 keep_virtual
= true;
2690 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2691 isl_pw_aff_free(pa
);
2695 if (!allow_nested
&& !pa
)
2696 pa
= try_extract_affine_condition(stmt
->getCond());
2697 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2698 cond
= isl_pw_aff_non_zero_set(pa
);
2699 if (allow_nested
&& !cond
) {
2700 int save_n_stmt
= n_stmt
;
2701 test_access
= create_test_access(ctx
, n_test
++);
2703 scop_cond
= extract_non_affine_condition(stmt
->getCond(),
2704 isl_map_copy(test_access
));
2705 n_stmt
= save_n_stmt
;
2706 scop_cond
= scop_add_array(scop_cond
, test_access
, ast_context
);
2707 scop_cond
= pet_scop_prefix(scop_cond
, 0);
2708 scop
= pet_scop_reset_context(scop
);
2709 scop
= pet_scop_prefix(scop
, 1);
2710 keep_virtual
= true;
2711 cond
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2714 cond
= embed(cond
, isl_id_copy(id
));
2715 skip
= embed(skip
, isl_id_copy(id
));
2716 valid_cond
= isl_set_coalesce(valid_cond
);
2717 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
2718 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
2719 is_one
= isl_int_is_one(inc
) || isl_int_is_negone(inc
);
2720 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2722 init_val
= extract_affine(rhs
);
2723 valid_cond_init
= enforce_subset(
2724 isl_set_from_pw_aff(isl_pw_aff_copy(init_val
)),
2725 isl_set_copy(valid_cond
));
2726 if (is_one
&& !is_virtual
) {
2727 isl_pw_aff_free(init_val
);
2728 pa
= extract_comparison(isl_int_is_pos(inc
) ? BO_GE
: BO_LE
,
2730 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2731 valid_init
= set_project_out_by_id(valid_init
, id
);
2732 domain
= isl_pw_aff_non_zero_set(pa
);
2734 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
2735 domain
= strided_domain(isl_id_copy(id
), init_val
, inc
);
2738 domain
= embed(domain
, isl_id_copy(id
));
2741 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2742 rev_wrap
= isl_map_reverse(isl_map_copy(wrap
));
2743 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
2744 skip
= isl_set_apply(skip
, isl_map_copy(rev_wrap
));
2745 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
2746 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
2748 is_simple
= is_simple_bound(cond
, inc
);
2750 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2751 is_simple
= is_simple_bound(cond
, inc
);
2754 cond
= valid_for_each_iteration(cond
,
2755 isl_set_copy(domain
), inc
);
2756 domain
= isl_set_intersect(domain
, cond
);
2757 if (has_affine_break
) {
2758 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2759 skip
= after(skip
, isl_int_sgn(inc
));
2760 domain
= isl_set_subtract(domain
, skip
);
2762 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2763 space
= isl_space_from_domain(isl_set_get_space(domain
));
2764 space
= isl_space_add_dims(space
, isl_dim_out
, 1);
2765 sched
= isl_map_universe(space
);
2766 if (isl_int_is_pos(inc
))
2767 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2769 sched
= isl_map_oppose(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2771 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
), inc
);
2772 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
2774 if (is_virtual
&& !keep_virtual
) {
2775 wrap
= isl_map_set_dim_id(wrap
,
2776 isl_dim_out
, 0, isl_id_copy(id
));
2777 sched
= isl_map_intersect_domain(sched
, isl_set_copy(domain
));
2778 domain
= isl_set_apply(domain
, isl_map_copy(wrap
));
2779 sched
= isl_map_apply_domain(sched
, wrap
);
2781 if (!(is_virtual
&& keep_virtual
)) {
2782 space
= isl_set_get_space(domain
);
2783 wrap
= isl_map_identity(isl_space_map_from_set(space
));
2786 scop_cond
= pet_scop_embed(scop_cond
, isl_set_copy(domain
),
2787 isl_map_copy(sched
), isl_map_copy(wrap
), isl_id_copy(id
));
2788 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), sched
, wrap
, id
);
2789 scop
= resolve_nested(scop
);
2791 scop
= scop_add_break(scop
, break_access
, isl_set_copy(domain
),
2794 scop
= scop_add_while(scop_cond
, scop
, test_access
, domain
,
2796 isl_set_free(valid_inc
);
2798 scop
= pet_scop_restrict_context(scop
, valid_inc
);
2799 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
2800 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
2801 isl_set_free(domain
);
2803 clear_assignment(assigned_value
, iv
);
2807 scop
= pet_scop_restrict_context(scop
, valid_init
);
2812 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
)
2814 return extract(stmt
->children());
2817 /* Does parameter "pos" of "map" refer to a nested access?
2819 static bool is_nested_parameter(__isl_keep isl_map
*map
, int pos
)
2824 id
= isl_map_get_dim_id(map
, isl_dim_param
, pos
);
2825 nested
= is_nested_parameter(id
);
2831 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2833 static int n_nested_parameter(__isl_keep isl_space
*space
)
2838 nparam
= isl_space_dim(space
, isl_dim_param
);
2839 for (int i
= 0; i
< nparam
; ++i
)
2840 if (is_nested_parameter(space
, i
))
2846 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2848 static int n_nested_parameter(__isl_keep isl_map
*map
)
2853 space
= isl_map_get_space(map
);
2854 n
= n_nested_parameter(space
);
2855 isl_space_free(space
);
2860 /* For each nested access parameter in "space",
2861 * construct a corresponding pet_expr, place it in args and
2862 * record its position in "param2pos".
2863 * "n_arg" is the number of elements that are already in args.
2864 * The position recorded in "param2pos" takes this number into account.
2865 * If the pet_expr corresponding to a parameter is identical to
2866 * the pet_expr corresponding to an earlier parameter, then these two
2867 * parameters are made to refer to the same element in args.
2869 * Return the final number of elements in args or -1 if an error has occurred.
2871 int PetScan::extract_nested(__isl_keep isl_space
*space
,
2872 int n_arg
, struct pet_expr
**args
, std::map
<int,int> ¶m2pos
)
2876 nparam
= isl_space_dim(space
, isl_dim_param
);
2877 for (int i
= 0; i
< nparam
; ++i
) {
2879 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2882 if (!is_nested_parameter(id
)) {
2887 nested
= (Expr
*) isl_id_get_user(id
);
2888 args
[n_arg
] = extract_expr(nested
);
2892 for (j
= 0; j
< n_arg
; ++j
)
2893 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
2897 pet_expr_free(args
[n_arg
]);
2901 param2pos
[i
] = n_arg
++;
2909 /* For each nested access parameter in the access relations in "expr",
2910 * construct a corresponding pet_expr, place it in expr->args and
2911 * record its position in "param2pos".
2912 * n is the number of nested access parameters.
2914 struct pet_expr
*PetScan::extract_nested(struct pet_expr
*expr
, int n
,
2915 std::map
<int,int> ¶m2pos
)
2919 expr
->args
= isl_calloc_array(ctx
, struct pet_expr
*, n
);
2924 space
= isl_map_get_space(expr
->acc
.access
);
2925 n
= extract_nested(space
, 0, expr
->args
, param2pos
);
2926 isl_space_free(space
);
2934 pet_expr_free(expr
);
2938 /* Look for parameters in any access relation in "expr" that
2939 * refer to nested accesses. In particular, these are
2940 * parameters with no name.
2942 * If there are any such parameters, then the domain of the access
2943 * relation, which is still [] at this point, is replaced by
2944 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2945 * (after identifying identical nested accesses).
2946 * The parameters are then equated to the corresponding t dimensions
2947 * and subsequently projected out.
2948 * param2pos maps the position of the parameter to the position
2949 * of the corresponding t dimension.
2951 struct pet_expr
*PetScan::resolve_nested(struct pet_expr
*expr
)
2958 std::map
<int,int> param2pos
;
2963 for (int i
= 0; i
< expr
->n_arg
; ++i
) {
2964 expr
->args
[i
] = resolve_nested(expr
->args
[i
]);
2965 if (!expr
->args
[i
]) {
2966 pet_expr_free(expr
);
2971 if (expr
->type
!= pet_expr_access
)
2974 n
= n_nested_parameter(expr
->acc
.access
);
2978 expr
= extract_nested(expr
, n
, param2pos
);
2983 nparam
= isl_map_dim(expr
->acc
.access
, isl_dim_param
);
2984 n_in
= isl_map_dim(expr
->acc
.access
, isl_dim_in
);
2985 dim
= isl_map_get_space(expr
->acc
.access
);
2986 dim
= isl_space_domain(dim
);
2987 dim
= isl_space_from_domain(dim
);
2988 dim
= isl_space_add_dims(dim
, isl_dim_out
, n
);
2989 map
= isl_map_universe(dim
);
2990 map
= isl_map_domain_map(map
);
2991 map
= isl_map_reverse(map
);
2992 expr
->acc
.access
= isl_map_apply_domain(expr
->acc
.access
, map
);
2994 for (int i
= nparam
- 1; i
>= 0; --i
) {
2995 isl_id
*id
= isl_map_get_dim_id(expr
->acc
.access
,
2997 if (!is_nested_parameter(id
)) {
3002 expr
->acc
.access
= isl_map_equate(expr
->acc
.access
,
3003 isl_dim_param
, i
, isl_dim_in
,
3004 n_in
+ param2pos
[i
]);
3005 expr
->acc
.access
= isl_map_project_out(expr
->acc
.access
,
3006 isl_dim_param
, i
, 1);
3013 pet_expr_free(expr
);
3017 /* Convert a top-level pet_expr to a pet_scop with one statement.
3018 * This mainly involves resolving nested expression parameters
3019 * and setting the name of the iteration space.
3020 * The name is given by "label" if it is non-NULL. Otherwise,
3021 * it is of the form S_<n_stmt>.
3023 struct pet_scop
*PetScan::extract(Stmt
*stmt
, struct pet_expr
*expr
,
3024 __isl_take isl_id
*label
)
3026 struct pet_stmt
*ps
;
3027 SourceLocation loc
= stmt
->getLocStart();
3028 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3030 expr
= resolve_nested(expr
);
3031 ps
= pet_stmt_from_pet_expr(ctx
, line
, label
, n_stmt
++, expr
);
3032 return pet_scop_from_pet_stmt(ctx
, ps
);
3035 /* Check if we can extract an affine expression from "expr".
3036 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3037 * We turn on autodetection so that we won't generate any warnings
3038 * and turn off nesting, so that we won't accept any non-affine constructs.
3040 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
3043 int save_autodetect
= options
->autodetect
;
3044 bool save_nesting
= nesting_enabled
;
3046 options
->autodetect
= 1;
3047 nesting_enabled
= false;
3049 pwaff
= extract_affine(expr
);
3051 options
->autodetect
= save_autodetect
;
3052 nesting_enabled
= save_nesting
;
3057 /* Check whether "expr" is an affine expression.
3059 bool PetScan::is_affine(Expr
*expr
)
3063 pwaff
= try_extract_affine(expr
);
3064 isl_pw_aff_free(pwaff
);
3066 return pwaff
!= NULL
;
3069 /* Check if we can extract an affine constraint from "expr".
3070 * Return the constraint as an isl_set if we can and NULL otherwise.
3071 * We turn on autodetection so that we won't generate any warnings
3072 * and turn off nesting, so that we won't accept any non-affine constructs.
3074 __isl_give isl_pw_aff
*PetScan::try_extract_affine_condition(Expr
*expr
)
3077 int save_autodetect
= options
->autodetect
;
3078 bool save_nesting
= nesting_enabled
;
3080 options
->autodetect
= 1;
3081 nesting_enabled
= false;
3083 cond
= extract_condition(expr
);
3085 options
->autodetect
= save_autodetect
;
3086 nesting_enabled
= save_nesting
;
3091 /* Check whether "expr" is an affine constraint.
3093 bool PetScan::is_affine_condition(Expr
*expr
)
3097 cond
= try_extract_affine_condition(expr
);
3098 isl_pw_aff_free(cond
);
3100 return cond
!= NULL
;
3103 /* Check if we can extract a condition from "expr".
3104 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3105 * If allow_nested is set, then the condition may involve parameters
3106 * corresponding to nested accesses.
3107 * We turn on autodetection so that we won't generate any warnings.
3109 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
3112 int save_autodetect
= options
->autodetect
;
3113 bool save_nesting
= nesting_enabled
;
3115 options
->autodetect
= 1;
3116 nesting_enabled
= allow_nested
;
3117 cond
= extract_condition(expr
);
3119 options
->autodetect
= save_autodetect
;
3120 nesting_enabled
= save_nesting
;
3125 /* If the top-level expression of "stmt" is an assignment, then
3126 * return that assignment as a BinaryOperator.
3127 * Otherwise return NULL.
3129 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
3131 BinaryOperator
*ass
;
3135 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
3138 ass
= cast
<BinaryOperator
>(stmt
);
3139 if(ass
->getOpcode() != BO_Assign
)
3145 /* Check if the given if statement is a conditional assignement
3146 * with a non-affine condition. If so, construct a pet_scop
3147 * corresponding to this conditional assignment. Otherwise return NULL.
3149 * In particular we check if "stmt" is of the form
3156 * where a is some array or scalar access.
3157 * The constructed pet_scop then corresponds to the expression
3159 * a = condition ? f(...) : g(...)
3161 * All access relations in f(...) are intersected with condition
3162 * while all access relation in g(...) are intersected with the complement.
3164 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
3166 BinaryOperator
*ass_then
, *ass_else
;
3167 isl_map
*write_then
, *write_else
;
3168 isl_set
*cond
, *comp
;
3172 struct pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
3173 bool save_nesting
= nesting_enabled
;
3175 if (!options
->detect_conditional_assignment
)
3178 ass_then
= top_assignment_or_null(stmt
->getThen());
3179 ass_else
= top_assignment_or_null(stmt
->getElse());
3181 if (!ass_then
|| !ass_else
)
3184 if (is_affine_condition(stmt
->getCond()))
3187 write_then
= extract_access(ass_then
->getLHS());
3188 write_else
= extract_access(ass_else
->getLHS());
3190 equal
= isl_map_is_equal(write_then
, write_else
);
3191 isl_map_free(write_else
);
3192 if (equal
< 0 || !equal
) {
3193 isl_map_free(write_then
);
3197 nesting_enabled
= allow_nested
;
3198 pa
= extract_condition(stmt
->getCond());
3199 nesting_enabled
= save_nesting
;
3200 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
3201 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
3202 map
= isl_map_from_range(isl_set_from_pw_aff(pa
));
3204 pe_cond
= pet_expr_from_access(map
);
3206 pe_then
= extract_expr(ass_then
->getRHS());
3207 pe_then
= pet_expr_restrict(pe_then
, cond
);
3208 pe_else
= extract_expr(ass_else
->getRHS());
3209 pe_else
= pet_expr_restrict(pe_else
, comp
);
3211 pe
= pet_expr_new_ternary(ctx
, pe_cond
, pe_then
, pe_else
);
3212 pe_write
= pet_expr_from_access(write_then
);
3214 pe_write
->acc
.write
= 1;
3215 pe_write
->acc
.read
= 0;
3217 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, pe_write
, pe
);
3218 return extract(stmt
, pe
);
3221 /* Create a pet_scop with a single statement evaluating "cond"
3222 * and writing the result to a virtual scalar, as expressed by
3225 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
,
3226 __isl_take isl_map
*access
)
3228 struct pet_expr
*expr
, *write
;
3229 struct pet_stmt
*ps
;
3230 struct pet_scop
*scop
;
3231 SourceLocation loc
= cond
->getLocStart();
3232 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3234 write
= pet_expr_from_access(access
);
3236 write
->acc
.write
= 1;
3237 write
->acc
.read
= 0;
3239 expr
= extract_expr(cond
);
3240 expr
= resolve_nested(expr
);
3241 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, write
, expr
);
3242 ps
= pet_stmt_from_pet_expr(ctx
, line
, NULL
, n_stmt
++, expr
);
3243 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3244 scop
= resolve_nested(scop
);
3250 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
,
3254 /* Apply the map pointed to by "user" to the domain of the access
3255 * relation, thereby embedding it in the range of the map.
3256 * The domain of both relations is the zero-dimensional domain.
3258 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
, void *user
)
3260 isl_map
*map
= (isl_map
*) user
;
3262 return isl_map_apply_domain(access
, isl_map_copy(map
));
3265 /* Apply "map" to all access relations in "expr".
3267 static struct pet_expr
*embed(struct pet_expr
*expr
, __isl_keep isl_map
*map
)
3269 return pet_expr_foreach_access(expr
, &embed_access
, map
);
3272 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3274 static int n_nested_parameter(__isl_keep isl_set
*set
)
3279 space
= isl_set_get_space(set
);
3280 n
= n_nested_parameter(space
);
3281 isl_space_free(space
);
3286 /* Remove all parameters from "map" that refer to nested accesses.
3288 static __isl_give isl_map
*remove_nested_parameters(__isl_take isl_map
*map
)
3293 space
= isl_map_get_space(map
);
3294 nparam
= isl_space_dim(space
, isl_dim_param
);
3295 for (int i
= nparam
- 1; i
>= 0; --i
)
3296 if (is_nested_parameter(space
, i
))
3297 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3298 isl_space_free(space
);
3304 static __isl_give isl_map
*access_remove_nested_parameters(
3305 __isl_take isl_map
*access
, void *user
);
3308 static __isl_give isl_map
*access_remove_nested_parameters(
3309 __isl_take isl_map
*access
, void *user
)
3311 return remove_nested_parameters(access
);
3314 /* Remove all nested access parameters from the schedule and all
3315 * accesses of "stmt".
3316 * There is no need to remove them from the domain as these parameters
3317 * have already been removed from the domain when this function is called.
3319 static struct pet_stmt
*remove_nested_parameters(struct pet_stmt
*stmt
)
3323 stmt
->schedule
= remove_nested_parameters(stmt
->schedule
);
3324 stmt
->body
= pet_expr_foreach_access(stmt
->body
,
3325 &access_remove_nested_parameters
, NULL
);
3326 if (!stmt
->schedule
|| !stmt
->body
)
3328 for (int i
= 0; i
< stmt
->n_arg
; ++i
) {
3329 stmt
->args
[i
] = pet_expr_foreach_access(stmt
->args
[i
],
3330 &access_remove_nested_parameters
, NULL
);
3337 pet_stmt_free(stmt
);
3341 /* For each nested access parameter in the domain of "stmt",
3342 * construct a corresponding pet_expr, place it before the original
3343 * elements in stmt->args and record its position in "param2pos".
3344 * n is the number of nested access parameters.
3346 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
3347 std::map
<int,int> ¶m2pos
)
3352 struct pet_expr
**args
;
3354 n_arg
= stmt
->n_arg
;
3355 args
= isl_calloc_array(ctx
, struct pet_expr
*, n
+ n_arg
);
3359 space
= isl_set_get_space(stmt
->domain
);
3360 n_arg
= extract_nested(space
, 0, args
, param2pos
);
3361 isl_space_free(space
);
3366 for (i
= 0; i
< stmt
->n_arg
; ++i
)
3367 args
[n_arg
+ i
] = stmt
->args
[i
];
3370 stmt
->n_arg
+= n_arg
;
3375 for (i
= 0; i
< n
; ++i
)
3376 pet_expr_free(args
[i
]);
3379 pet_stmt_free(stmt
);
3383 /* Check whether any of the arguments i of "stmt" starting at position "n"
3384 * is equal to one of the first "n" arguments j.
3385 * If so, combine the constraints on arguments i and j and remove
3388 static struct pet_stmt
*remove_duplicate_arguments(struct pet_stmt
*stmt
, int n
)
3397 if (n
== stmt
->n_arg
)
3400 map
= isl_set_unwrap(stmt
->domain
);
3402 for (i
= stmt
->n_arg
- 1; i
>= n
; --i
) {
3403 for (j
= 0; j
< n
; ++j
)
3404 if (pet_expr_is_equal(stmt
->args
[i
], stmt
->args
[j
]))
3409 map
= isl_map_equate(map
, isl_dim_out
, i
, isl_dim_out
, j
);
3410 map
= isl_map_project_out(map
, isl_dim_out
, i
, 1);
3412 pet_expr_free(stmt
->args
[i
]);
3413 for (j
= i
; j
+ 1 < stmt
->n_arg
; ++j
)
3414 stmt
->args
[j
] = stmt
->args
[j
+ 1];
3418 stmt
->domain
= isl_map_wrap(map
);
3423 pet_stmt_free(stmt
);
3427 /* Look for parameters in the iteration domain of "stmt" that
3428 * refer to nested accesses. In particular, these are
3429 * parameters with no name.
3431 * If there are any such parameters, then as many extra variables
3432 * (after identifying identical nested accesses) are inserted in the
3433 * range of the map wrapped inside the domain, before the original variables.
3434 * If the original domain is not a wrapped map, then a new wrapped
3435 * map is created with zero output dimensions.
3436 * The parameters are then equated to the corresponding output dimensions
3437 * and subsequently projected out, from the iteration domain,
3438 * the schedule and the access relations.
3439 * For each of the output dimensions, a corresponding argument
3440 * expression is inserted. Initially they are created with
3441 * a zero-dimensional domain, so they have to be embedded
3442 * in the current iteration domain.
3443 * param2pos maps the position of the parameter to the position
3444 * of the corresponding output dimension in the wrapped map.
3446 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3452 std::map
<int,int> param2pos
;
3457 n
= n_nested_parameter(stmt
->domain
);
3461 n_arg
= stmt
->n_arg
;
3462 stmt
= extract_nested(stmt
, n
, param2pos
);
3466 n
= stmt
->n_arg
- n_arg
;
3467 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3468 if (isl_set_is_wrapping(stmt
->domain
))
3469 map
= isl_set_unwrap(stmt
->domain
);
3471 map
= isl_map_from_domain(stmt
->domain
);
3472 map
= isl_map_insert_dims(map
, isl_dim_out
, 0, n
);
3474 for (int i
= nparam
- 1; i
>= 0; --i
) {
3477 if (!is_nested_parameter(map
, i
))
3480 id
= isl_map_get_tuple_id(stmt
->args
[param2pos
[i
]]->acc
.access
,
3482 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3483 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3485 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3488 stmt
->domain
= isl_map_wrap(map
);
3490 map
= isl_set_unwrap(isl_set_copy(stmt
->domain
));
3491 map
= isl_map_from_range(isl_map_domain(map
));
3492 for (int pos
= 0; pos
< n
; ++pos
)
3493 stmt
->args
[pos
] = embed(stmt
->args
[pos
], map
);
3496 stmt
= remove_nested_parameters(stmt
);
3497 stmt
= remove_duplicate_arguments(stmt
, n
);
3501 pet_stmt_free(stmt
);
3505 /* For each statement in "scop", move the parameters that correspond
3506 * to nested access into the ranges of the domains and create
3507 * corresponding argument expressions.
3509 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3514 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3515 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3516 if (!scop
->stmts
[i
])
3522 pet_scop_free(scop
);
3526 /* Given an access expression "expr", is the variable accessed by
3527 * "expr" assigned anywhere inside "scop"?
3529 static bool is_assigned(pet_expr
*expr
, pet_scop
*scop
)
3531 bool assigned
= false;
3534 id
= isl_map_get_tuple_id(expr
->acc
.access
, isl_dim_out
);
3535 assigned
= pet_scop_writes(scop
, id
);
3541 /* Are all nested access parameters in "pa" allowed given "scop".
3542 * In particular, is none of them written by anywhere inside "scop".
3544 * If "scop" has any skip conditions, then no nested access parameters
3545 * are allowed. In particular, if there is any nested access in a guard
3546 * for a piece of code containing a "continue", then we want to introduce
3547 * a separate statement for evaluating this guard so that we can express
3548 * that the result is false for all previous iterations.
3550 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3557 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3558 for (int i
= 0; i
< nparam
; ++i
) {
3560 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3564 if (!is_nested_parameter(id
)) {
3569 if (pet_scop_has_skip(scop
, pet_skip_now
)) {
3574 nested
= (Expr
*) isl_id_get_user(id
);
3575 expr
= extract_expr(nested
);
3576 allowed
= expr
&& expr
->type
== pet_expr_access
&&
3577 !is_assigned(expr
, scop
);
3579 pet_expr_free(expr
);
3589 /* Do we need to construct a skip condition of the given type
3590 * on an if statement, given that the if condition is non-affine?
3592 * pet_scop_filter_skip can only handle the case where the if condition
3593 * holds (the then branch) and the skip condition is universal.
3594 * In any other case, we need to construct a new skip condition.
3596 static bool need_skip(struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3597 bool have_else
, enum pet_skip type
)
3599 if (have_else
&& scop_else
&& pet_scop_has_skip(scop_else
, type
))
3601 if (scop_then
&& pet_scop_has_skip(scop_then
, type
) &&
3602 !pet_scop_has_universal_skip(scop_then
, type
))
3607 /* Do we need to construct a skip condition of the given type
3608 * on an if statement, given that the if condition is affine?
3610 * There is no need to construct a new skip condition if all
3611 * the skip conditions are affine.
3613 static bool need_skip_aff(struct pet_scop
*scop_then
,
3614 struct pet_scop
*scop_else
, bool have_else
, enum pet_skip type
)
3616 if (scop_then
&& pet_scop_has_var_skip(scop_then
, type
))
3618 if (have_else
&& scop_else
&& pet_scop_has_var_skip(scop_else
, type
))
3623 /* Do we need to construct a skip condition of the given type
3624 * on an if statement?
3626 static bool need_skip(struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3627 bool have_else
, enum pet_skip type
, bool affine
)
3630 return need_skip_aff(scop_then
, scop_else
, have_else
, type
);
3632 return need_skip(scop_then
, scop_else
, have_else
, type
);
3635 /* Construct an affine expression pet_expr that is evaluates
3636 * to the constant "val".
3638 static struct pet_expr
*universally(isl_ctx
*ctx
, int val
)
3643 space
= isl_space_alloc(ctx
, 0, 0, 1);
3644 map
= isl_map_universe(space
);
3645 map
= isl_map_fix_si(map
, isl_dim_out
, 0, val
);
3647 return pet_expr_from_access(map
);
3650 /* Construct an affine expression pet_expr that is evaluates
3651 * to the constant 1.
3653 static struct pet_expr
*universally_true(isl_ctx
*ctx
)
3655 return universally(ctx
, 1);
3658 /* Construct an affine expression pet_expr that is evaluates
3659 * to the constant 0.
3661 static struct pet_expr
*universally_false(isl_ctx
*ctx
)
3663 return universally(ctx
, 0);
3666 /* Given an access relation "test_access" for the if condition,
3667 * an access relation "skip_access" for the skip condition and
3668 * scops for the then and else branches, construct a scop for
3669 * computing "skip_access".
3671 * The computed scop contains a single statement that essentially does
3673 * skip_cond = test_cond ? skip_cond_then : skip_cond_else
3675 * If the skip conditions of the then and/or else branch are not affine,
3676 * then they need to be filtered by test_access.
3677 * If they are missing, then this means the skip condition is false.
3679 * Since we are constructing a skip condition for the if statement,
3680 * the skip conditions on the then and else branches are removed.
3682 static struct pet_scop
*extract_skip(PetScan
*scan
,
3683 __isl_take isl_map
*test_access
, __isl_take isl_map
*skip_access
,
3684 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
, bool have_else
,
3687 struct pet_expr
*expr_then
, *expr_else
, *expr
, *expr_skip
;
3688 struct pet_stmt
*stmt
;
3689 struct pet_scop
*scop
;
3690 isl_ctx
*ctx
= scan
->ctx
;
3694 if (have_else
&& !scop_else
)
3697 if (pet_scop_has_skip(scop_then
, type
)) {
3698 expr_then
= pet_scop_get_skip_expr(scop_then
, type
);
3699 pet_scop_reset_skip(scop_then
, type
);
3700 if (!pet_expr_is_affine(expr_then
))
3701 expr_then
= pet_expr_filter(expr_then
,
3702 isl_map_copy(test_access
), 1);
3704 expr_then
= universally_false(ctx
);
3706 if (have_else
&& pet_scop_has_skip(scop_else
, type
)) {
3707 expr_else
= pet_scop_get_skip_expr(scop_else
, type
);
3708 pet_scop_reset_skip(scop_else
, type
);
3709 if (!pet_expr_is_affine(expr_else
))
3710 expr_else
= pet_expr_filter(expr_else
,
3711 isl_map_copy(test_access
), 0);
3713 expr_else
= universally_false(ctx
);
3715 expr
= pet_expr_from_access(test_access
);
3716 expr
= pet_expr_new_ternary(ctx
, expr
, expr_then
, expr_else
);
3717 expr_skip
= pet_expr_from_access(isl_map_copy(skip_access
));
3719 expr_skip
->acc
.write
= 1;
3720 expr_skip
->acc
.read
= 0;
3722 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, expr_skip
, expr
);
3723 stmt
= pet_stmt_from_pet_expr(ctx
, -1, NULL
, scan
->n_stmt
++, expr
);
3725 scop
= pet_scop_from_pet_stmt(ctx
, stmt
);
3726 scop
= scop_add_array(scop
, skip_access
, scan
->ast_context
);
3727 isl_map_free(skip_access
);
3731 isl_map_free(test_access
);
3732 isl_map_free(skip_access
);
3736 /* Is scop's skip_now condition equal to its skip_later condition?
3737 * In particular, this means that it either has no skip_now condition
3738 * or both a skip_now and a skip_later condition (that are equal to each other).
3740 static bool skip_equals_skip_later(struct pet_scop
*scop
)
3742 int has_skip_now
, has_skip_later
;
3744 isl_set
*skip_now
, *skip_later
;
3748 has_skip_now
= pet_scop_has_skip(scop
, pet_skip_now
);
3749 has_skip_later
= pet_scop_has_skip(scop
, pet_skip_later
);
3750 if (has_skip_now
!= has_skip_later
)
3755 skip_now
= pet_scop_get_skip(scop
, pet_skip_now
);
3756 skip_later
= pet_scop_get_skip(scop
, pet_skip_later
);
3757 equal
= isl_set_is_equal(skip_now
, skip_later
);
3758 isl_set_free(skip_now
);
3759 isl_set_free(skip_later
);
3764 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
3766 static void drop_skip_later(struct pet_scop
*scop1
, struct pet_scop
*scop2
)
3768 pet_scop_reset_skip(scop1
, pet_skip_later
);
3769 pet_scop_reset_skip(scop2
, pet_skip_later
);
3772 /* Structure that handles the construction of skip conditions.
3774 * scop_then and scop_else represent the then and else branches
3775 * of the if statement
3777 * skip[type] is true if we need to construct a skip condition of that type
3778 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
3779 * are equal to each other
3780 * access[type] is the virtual array representing the skip condition
3781 * scop[type] is a scop for computing the skip condition
3783 struct pet_skip_info
{
3789 struct pet_scop
*scop
[2];
3791 pet_skip_info(isl_ctx
*ctx
) : ctx(ctx
) {}
3793 operator bool() { return skip
[pet_skip_now
] || skip
[pet_skip_later
]; }
3796 /* Structure that handles the construction of skip conditions on if statements.
3798 * scop_then and scop_else represent the then and else branches
3799 * of the if statement
3801 struct pet_skip_info_if
: public pet_skip_info
{
3802 struct pet_scop
*scop_then
, *scop_else
;
3805 pet_skip_info_if(isl_ctx
*ctx
, struct pet_scop
*scop_then
,
3806 struct pet_scop
*scop_else
, bool have_else
, bool affine
);
3807 void extract(PetScan
*scan
, __isl_keep isl_map
*access
,
3808 enum pet_skip type
);
3809 void extract(PetScan
*scan
, __isl_keep isl_map
*access
);
3810 void extract(PetScan
*scan
, __isl_keep isl_pw_aff
*cond
);
3811 struct pet_scop
*add(struct pet_scop
*scop
, enum pet_skip type
,
3813 struct pet_scop
*add(struct pet_scop
*scop
, int offset
);
3816 /* Initialize a pet_skip_info_if structure based on the then and else branches
3817 * and based on whether the if condition is affine or not.
3819 pet_skip_info_if::pet_skip_info_if(isl_ctx
*ctx
, struct pet_scop
*scop_then
,
3820 struct pet_scop
*scop_else
, bool have_else
, bool affine
) :
3821 pet_skip_info(ctx
), scop_then(scop_then
), scop_else(scop_else
),
3822 have_else(have_else
)
3824 skip
[pet_skip_now
] =
3825 need_skip(scop_then
, scop_else
, have_else
, pet_skip_now
, affine
);
3826 equal
= skip
[pet_skip_now
] && skip_equals_skip_later(scop_then
) &&
3827 (!have_else
|| skip_equals_skip_later(scop_else
));
3828 skip
[pet_skip_later
] = skip
[pet_skip_now
] && !equal
&&
3829 need_skip(scop_then
, scop_else
, have_else
, pet_skip_later
, affine
);
3832 /* If we need to construct a skip condition of the given type,
3835 * "map" represents the if condition.
3837 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_map
*map
,
3843 access
[type
] = create_test_access(isl_map_get_ctx(map
), scan
->n_test
++);
3844 scop
[type
] = extract_skip(scan
, isl_map_copy(map
),
3845 isl_map_copy(access
[type
]),
3846 scop_then
, scop_else
, have_else
, type
);
3849 /* Construct the required skip conditions, given the if condition "map".
3851 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_map
*map
)
3853 extract(scan
, map
, pet_skip_now
);
3854 extract(scan
, map
, pet_skip_later
);
3856 drop_skip_later(scop_then
, scop_else
);
3859 /* Construct the required skip conditions, given the if condition "cond".
3861 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_pw_aff
*cond
)
3866 if (!skip
[pet_skip_now
] && !skip
[pet_skip_later
])
3869 test_set
= isl_set_from_pw_aff(isl_pw_aff_copy(cond
));
3870 test
= isl_map_from_range(test_set
);
3871 extract(scan
, test
);
3875 /* Add the computed skip condition of the give type to "main" and
3876 * add the scop for computing the condition at the given offset.
3878 * If equal is set, then we only computed a skip condition for pet_skip_now,
3879 * but we also need to set it as main's pet_skip_later.
3881 struct pet_scop
*pet_skip_info_if::add(struct pet_scop
*main
,
3882 enum pet_skip type
, int offset
)
3889 skip_set
= isl_map_range(access
[type
]);
3890 access
[type
] = NULL
;
3891 scop
[type
] = pet_scop_prefix(scop
[type
], offset
);
3892 main
= pet_scop_add_par(ctx
, main
, scop
[type
]);
3896 main
= pet_scop_set_skip(main
, pet_skip_later
,
3897 isl_set_copy(skip_set
));
3899 main
= pet_scop_set_skip(main
, type
, skip_set
);
3904 /* Add the computed skip conditions to "main" and
3905 * add the scops for computing the conditions at the given offset.
3907 struct pet_scop
*pet_skip_info_if::add(struct pet_scop
*scop
, int offset
)
3909 scop
= add(scop
, pet_skip_now
, offset
);
3910 scop
= add(scop
, pet_skip_later
, offset
);
3915 /* Construct a pet_scop for a non-affine if statement.
3917 * We create a separate statement that writes the result
3918 * of the non-affine condition to a virtual scalar.
3919 * A constraint requiring the value of this virtual scalar to be one
3920 * is added to the iteration domains of the then branch.
3921 * Similarly, a constraint requiring the value of this virtual scalar
3922 * to be zero is added to the iteration domains of the else branch, if any.
3923 * We adjust the schedules to ensure that the virtual scalar is written
3924 * before it is read.
3926 * If there are any breaks or continues in the then and/or else
3927 * branches, then we may have to compute a new skip condition.
3928 * This is handled using a pet_skip_info_if object.
3929 * On initialization, the object checks if skip conditions need
3930 * to be computed. If so, it does so in "extract" and adds them in "add".
3932 struct pet_scop
*PetScan::extract_non_affine_if(Expr
*cond
,
3933 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3934 bool have_else
, int stmt_id
)
3936 struct pet_scop
*scop
;
3937 isl_map
*test_access
;
3938 int save_n_stmt
= n_stmt
;
3940 test_access
= create_test_access(ctx
, n_test
++);
3942 scop
= extract_non_affine_condition(cond
, isl_map_copy(test_access
));
3943 n_stmt
= save_n_stmt
;
3944 scop
= scop_add_array(scop
, test_access
, ast_context
);
3946 pet_skip_info_if
skip(ctx
, scop_then
, scop_else
, have_else
, false);
3947 skip
.extract(this, test_access
);
3949 scop
= pet_scop_prefix(scop
, 0);
3950 scop_then
= pet_scop_prefix(scop_then
, 1);
3951 scop_then
= pet_scop_filter(scop_then
, isl_map_copy(test_access
), 1);
3953 scop_else
= pet_scop_prefix(scop_else
, 1);
3954 scop_else
= pet_scop_filter(scop_else
, test_access
, 0);
3955 scop_then
= pet_scop_add_par(ctx
, scop_then
, scop_else
);
3957 isl_map_free(test_access
);
3959 scop
= pet_scop_add_seq(ctx
, scop
, scop_then
);
3961 scop
= skip
.add(scop
, 2);
3966 /* Construct a pet_scop for an if statement.
3968 * If the condition fits the pattern of a conditional assignment,
3969 * then it is handled by extract_conditional_assignment.
3970 * Otherwise, we do the following.
3972 * If the condition is affine, then the condition is added
3973 * to the iteration domains of the then branch, while the
3974 * opposite of the condition in added to the iteration domains
3975 * of the else branch, if any.
3976 * We allow the condition to be dynamic, i.e., to refer to
3977 * scalars or array elements that may be written to outside
3978 * of the given if statement. These nested accesses are then represented
3979 * as output dimensions in the wrapping iteration domain.
3980 * If it also written _inside_ the then or else branch, then
3981 * we treat the condition as non-affine.
3982 * As explained in extract_non_affine_if, this will introduce
3983 * an extra statement.
3984 * For aesthetic reasons, we want this statement to have a statement
3985 * number that is lower than those of the then and else branches.
3986 * In order to evaluate if will need such a statement, however, we
3987 * first construct scops for the then and else branches.
3988 * We therefore reserve a statement number if we might have to
3989 * introduce such an extra statement.
3991 * If the condition is not affine, then the scop is created in
3992 * extract_non_affine_if.
3994 * If there are any breaks or continues in the then and/or else
3995 * branches, then we may have to compute a new skip condition.
3996 * This is handled using a pet_skip_info_if object.
3997 * On initialization, the object checks if skip conditions need
3998 * to be computed. If so, it does so in "extract" and adds them in "add".
4000 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
4002 struct pet_scop
*scop_then
, *scop_else
= NULL
, *scop
;
4008 scop
= extract_conditional_assignment(stmt
);
4012 cond
= try_extract_nested_condition(stmt
->getCond());
4013 if (allow_nested
&& (!cond
|| has_nested(cond
)))
4017 assigned_value_cache
cache(assigned_value
);
4018 scop_then
= extract(stmt
->getThen());
4021 if (stmt
->getElse()) {
4022 assigned_value_cache
cache(assigned_value
);
4023 scop_else
= extract(stmt
->getElse());
4024 if (options
->autodetect
) {
4025 if (scop_then
&& !scop_else
) {
4027 isl_pw_aff_free(cond
);
4030 if (!scop_then
&& scop_else
) {
4032 isl_pw_aff_free(cond
);
4039 (!is_nested_allowed(cond
, scop_then
) ||
4040 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
4041 isl_pw_aff_free(cond
);
4044 if (allow_nested
&& !cond
)
4045 return extract_non_affine_if(stmt
->getCond(), scop_then
,
4046 scop_else
, stmt
->getElse(), stmt_id
);
4049 cond
= extract_condition(stmt
->getCond());
4051 pet_skip_info_if
skip(ctx
, scop_then
, scop_else
, stmt
->getElse(), true);
4052 skip
.extract(this, cond
);
4054 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
4055 set
= isl_pw_aff_non_zero_set(cond
);
4056 scop
= pet_scop_restrict(scop_then
, isl_set_copy(set
));
4058 if (stmt
->getElse()) {
4059 set
= isl_set_subtract(isl_set_copy(valid
), set
);
4060 scop_else
= pet_scop_restrict(scop_else
, set
);
4061 scop
= pet_scop_add_par(ctx
, scop
, scop_else
);
4064 scop
= resolve_nested(scop
);
4065 scop
= pet_scop_restrict_context(scop
, valid
);
4068 scop
= pet_scop_prefix(scop
, 0);
4069 scop
= skip
.add(scop
, 1);
4074 /* Try and construct a pet_scop for a label statement.
4075 * We currently only allow labels on expression statements.
4077 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
4082 sub
= stmt
->getSubStmt();
4083 if (!isa
<Expr
>(sub
)) {
4088 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
4090 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
4093 /* Construct a pet_scop for a continue statement.
4095 * We simply create an empty scop with a universal pet_skip_now
4096 * skip condition. This skip condition will then be taken into
4097 * account by the enclosing loop construct, possibly after
4098 * being incorporated into outer skip conditions.
4100 struct pet_scop
*PetScan::extract(ContinueStmt
*stmt
)
4106 scop
= pet_scop_empty(ctx
);
4110 space
= isl_space_set_alloc(ctx
, 0, 1);
4111 set
= isl_set_universe(space
);
4112 set
= isl_set_fix_si(set
, isl_dim_set
, 0, 1);
4113 scop
= pet_scop_set_skip(scop
, pet_skip_now
, set
);
4118 /* Construct a pet_scop for a break statement.
4120 * We simply create an empty scop with both a universal pet_skip_now
4121 * skip condition and a universal pet_skip_later skip condition.
4122 * These skip conditions will then be taken into
4123 * account by the enclosing loop construct, possibly after
4124 * being incorporated into outer skip conditions.
4126 struct pet_scop
*PetScan::extract(BreakStmt
*stmt
)
4132 scop
= pet_scop_empty(ctx
);
4136 space
= isl_space_set_alloc(ctx
, 0, 1);
4137 set
= isl_set_universe(space
);
4138 set
= isl_set_fix_si(set
, isl_dim_set
, 0, 1);
4139 scop
= pet_scop_set_skip(scop
, pet_skip_now
, isl_set_copy(set
));
4140 scop
= pet_scop_set_skip(scop
, pet_skip_later
, set
);
4145 /* Try and construct a pet_scop corresponding to "stmt".
4147 struct pet_scop
*PetScan::extract(Stmt
*stmt
)
4149 if (isa
<Expr
>(stmt
))
4150 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
4152 switch (stmt
->getStmtClass()) {
4153 case Stmt::WhileStmtClass
:
4154 return extract(cast
<WhileStmt
>(stmt
));
4155 case Stmt::ForStmtClass
:
4156 return extract_for(cast
<ForStmt
>(stmt
));
4157 case Stmt::IfStmtClass
:
4158 return extract(cast
<IfStmt
>(stmt
));
4159 case Stmt::CompoundStmtClass
:
4160 return extract(cast
<CompoundStmt
>(stmt
));
4161 case Stmt::LabelStmtClass
:
4162 return extract(cast
<LabelStmt
>(stmt
));
4163 case Stmt::ContinueStmtClass
:
4164 return extract(cast
<ContinueStmt
>(stmt
));
4165 case Stmt::BreakStmtClass
:
4166 return extract(cast
<BreakStmt
>(stmt
));
4174 /* Do we need to construct a skip condition of the given type
4175 * on a sequence of statements?
4177 * There is no need to construct a new skip condition if only
4178 * only of the two statements has a skip condition or if both
4179 * of their skip conditions are affine.
4181 * In principle we also don't need a new continuation variable if
4182 * the continuation of scop2 is affine, but then we would need
4183 * to allow more complicated forms of continuations.
4185 static bool need_skip_seq(struct pet_scop
*scop1
, struct pet_scop
*scop2
,
4188 if (!scop1
|| !pet_scop_has_skip(scop1
, type
))
4190 if (!scop2
|| !pet_scop_has_skip(scop2
, type
))
4192 if (pet_scop_has_affine_skip(scop1
, type
) &&
4193 pet_scop_has_affine_skip(scop2
, type
))
4198 /* Construct a scop for computing the skip condition of the given type and
4199 * with access relation "skip_access" for a sequence of two scops "scop1"
4202 * The computed scop contains a single statement that essentially does
4204 * skip_cond = skip_cond_1 ? 1 : skip_cond_2
4206 * or, in other words, skip_cond1 || skip_cond2.
4207 * In this expression, skip_cond_2 is filtered to reflect that it is
4208 * only evaluated when skip_cond_1 is false.
4210 * The skip condition on scop1 is not removed because it still needs
4211 * to be applied to scop2 when these two scops are combined.
4213 static struct pet_scop
*extract_skip_seq(PetScan
*ps
,
4214 __isl_take isl_map
*skip_access
,
4215 struct pet_scop
*scop1
, struct pet_scop
*scop2
, enum pet_skip type
)
4218 struct pet_expr
*expr1
, *expr2
, *expr
, *expr_skip
;
4219 struct pet_stmt
*stmt
;
4220 struct pet_scop
*scop
;
4221 isl_ctx
*ctx
= ps
->ctx
;
4223 if (!scop1
|| !scop2
)
4226 expr1
= pet_scop_get_skip_expr(scop1
, type
);
4227 expr2
= pet_scop_get_skip_expr(scop2
, type
);
4228 pet_scop_reset_skip(scop2
, type
);
4230 expr2
= pet_expr_filter(expr2
, isl_map_copy(expr1
->acc
.access
), 0);
4232 expr
= universally_true(ctx
);
4233 expr
= pet_expr_new_ternary(ctx
, expr1
, expr
, expr2
);
4234 expr_skip
= pet_expr_from_access(isl_map_copy(skip_access
));
4236 expr_skip
->acc
.write
= 1;
4237 expr_skip
->acc
.read
= 0;
4239 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, expr_skip
, expr
);
4240 stmt
= pet_stmt_from_pet_expr(ctx
, -1, NULL
, ps
->n_stmt
++, expr
);
4242 scop
= pet_scop_from_pet_stmt(ctx
, stmt
);
4243 scop
= scop_add_array(scop
, skip_access
, ps
->ast_context
);
4244 isl_map_free(skip_access
);
4248 isl_map_free(skip_access
);
4252 /* Structure that handles the construction of skip conditions
4253 * on sequences of statements.
4255 * scop1 and scop2 represent the two statements that are combined
4257 struct pet_skip_info_seq
: public pet_skip_info
{
4258 struct pet_scop
*scop1
, *scop2
;
4260 pet_skip_info_seq(isl_ctx
*ctx
, struct pet_scop
*scop1
,
4261 struct pet_scop
*scop2
);
4262 void extract(PetScan
*scan
, enum pet_skip type
);
4263 void extract(PetScan
*scan
);
4264 struct pet_scop
*add(struct pet_scop
*scop
, enum pet_skip type
,
4266 struct pet_scop
*add(struct pet_scop
*scop
, int offset
);
4269 /* Initialize a pet_skip_info_seq structure based on
4270 * on the two statements that are going to be combined.
4272 pet_skip_info_seq::pet_skip_info_seq(isl_ctx
*ctx
, struct pet_scop
*scop1
,
4273 struct pet_scop
*scop2
) : pet_skip_info(ctx
), scop1(scop1
), scop2(scop2
)
4275 skip
[pet_skip_now
] = need_skip_seq(scop1
, scop2
, pet_skip_now
);
4276 equal
= skip
[pet_skip_now
] && skip_equals_skip_later(scop1
) &&
4277 skip_equals_skip_later(scop2
);
4278 skip
[pet_skip_later
] = skip
[pet_skip_now
] && !equal
&&
4279 need_skip_seq(scop1
, scop2
, pet_skip_later
);
4282 /* If we need to construct a skip condition of the given type,
4285 void pet_skip_info_seq::extract(PetScan
*scan
, enum pet_skip type
)
4290 access
[type
] = create_test_access(ctx
, scan
->n_test
++);
4291 scop
[type
] = extract_skip_seq(scan
, isl_map_copy(access
[type
]),
4292 scop1
, scop2
, type
);
4295 /* Construct the required skip conditions.
4297 void pet_skip_info_seq::extract(PetScan
*scan
)
4299 extract(scan
, pet_skip_now
);
4300 extract(scan
, pet_skip_later
);
4302 drop_skip_later(scop1
, scop2
);
4305 /* Add the computed skip condition of the give type to "main" and
4306 * add the scop for computing the condition at the given offset (the statement
4307 * number). Within this offset, the condition is computed at position 1
4308 * to ensure that it is computed after the corresponding statement.
4310 * If equal is set, then we only computed a skip condition for pet_skip_now,
4311 * but we also need to set it as main's pet_skip_later.
4313 struct pet_scop
*pet_skip_info_seq::add(struct pet_scop
*main
,
4314 enum pet_skip type
, int offset
)
4321 skip_set
= isl_map_range(access
[type
]);
4322 access
[type
] = NULL
;
4323 scop
[type
] = pet_scop_prefix(scop
[type
], 1);
4324 scop
[type
] = pet_scop_prefix(scop
[type
], offset
);
4325 main
= pet_scop_add_par(ctx
, main
, scop
[type
]);
4329 main
= pet_scop_set_skip(main
, pet_skip_later
,
4330 isl_set_copy(skip_set
));
4332 main
= pet_scop_set_skip(main
, type
, skip_set
);
4337 /* Add the computed skip conditions to "main" and
4338 * add the scops for computing the conditions at the given offset.
4340 struct pet_scop
*pet_skip_info_seq::add(struct pet_scop
*scop
, int offset
)
4342 scop
= add(scop
, pet_skip_now
, offset
);
4343 scop
= add(scop
, pet_skip_later
, offset
);
4348 /* Try and construct a pet_scop corresponding to (part of)
4349 * a sequence of statements.
4351 * If there are any breaks or continues in the individual statements,
4352 * then we may have to compute a new skip condition.
4353 * This is handled using a pet_skip_info_seq object.
4354 * On initialization, the object checks if skip conditions need
4355 * to be computed. If so, it does so in "extract" and adds them in "add".
4357 struct pet_scop
*PetScan::extract(StmtRange stmt_range
)
4362 bool partial_range
= false;
4364 scop
= pet_scop_empty(ctx
);
4365 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
4367 struct pet_scop
*scop_i
;
4369 scop_i
= extract(child
);
4370 if (scop
&& partial
) {
4371 pet_scop_free(scop_i
);
4374 pet_skip_info_seq
skip(ctx
, scop
, scop_i
);
4377 scop_i
= pet_scop_prefix(scop_i
, 0);
4378 scop_i
= pet_scop_prefix(scop_i
, j
);
4379 if (options
->autodetect
) {
4381 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4383 partial_range
= true;
4384 if (scop
->n_stmt
!= 0 && !scop_i
)
4387 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4390 scop
= skip
.add(scop
, j
);
4396 if (scop
&& partial_range
)
4402 /* Return the file offset of the expansion location of "Loc".
4404 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
4406 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
4409 /* Check if the scop marked by the user is exactly this Stmt
4410 * or part of this Stmt.
4411 * If so, return a pet_scop corresponding to the marked region.
4412 * Otherwise, return NULL.
4414 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
4416 SourceManager
&SM
= PP
.getSourceManager();
4417 unsigned start_off
, end_off
;
4419 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
4420 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
4422 if (start_off
> loc
.end
)
4424 if (end_off
< loc
.start
)
4426 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
4427 return extract(stmt
);
4431 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
4432 Stmt
*child
= *start
;
4435 start_off
= getExpansionOffset(SM
, child
->getLocStart());
4436 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
4437 if (start_off
< loc
.start
&& end_off
> loc
.end
)
4439 if (start_off
>= loc
.start
)
4444 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
4446 start_off
= SM
.getFileOffset(child
->getLocStart());
4447 if (start_off
>= loc
.end
)
4451 return extract(StmtRange(start
, end
));
4454 /* Set the size of index "pos" of "array" to "size".
4455 * In particular, add a constraint of the form
4459 * to array->extent and a constraint of the form
4463 * to array->context.
4465 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
4466 __isl_take isl_pw_aff
*size
)
4476 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
4477 array
->context
= isl_set_intersect(array
->context
, valid
);
4479 dim
= isl_set_get_space(array
->extent
);
4480 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
4481 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
4482 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
4483 index
= isl_pw_aff_alloc(univ
, aff
);
4485 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
4486 isl_set_dim(array
->extent
, isl_dim_set
));
4487 id
= isl_set_get_tuple_id(array
->extent
);
4488 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
4489 bound
= isl_pw_aff_lt_set(index
, size
);
4491 array
->extent
= isl_set_intersect(array
->extent
, bound
);
4493 if (!array
->context
|| !array
->extent
)
4498 pet_array_free(array
);
4502 /* Figure out the size of the array at position "pos" and all
4503 * subsequent positions from "type" and update "array" accordingly.
4505 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
4506 const Type
*type
, int pos
)
4508 const ArrayType
*atype
;
4514 if (type
->isPointerType()) {
4515 type
= type
->getPointeeType().getTypePtr();
4516 return set_upper_bounds(array
, type
, pos
+ 1);
4518 if (!type
->isArrayType())
4521 type
= type
->getCanonicalTypeInternal().getTypePtr();
4522 atype
= cast
<ArrayType
>(type
);
4524 if (type
->isConstantArrayType()) {
4525 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
4526 size
= extract_affine(ca
->getSize());
4527 array
= update_size(array
, pos
, size
);
4528 } else if (type
->isVariableArrayType()) {
4529 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
4530 size
= extract_affine(vla
->getSizeExpr());
4531 array
= update_size(array
, pos
, size
);
4534 type
= atype
->getElementType().getTypePtr();
4536 return set_upper_bounds(array
, type
, pos
+ 1);
4539 /* Construct and return a pet_array corresponding to the variable "decl".
4540 * In particular, initialize array->extent to
4542 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4544 * and then call set_upper_bounds to set the upper bounds on the indices
4545 * based on the type of the variable.
4547 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
)
4549 struct pet_array
*array
;
4550 QualType qt
= decl
->getType();
4551 const Type
*type
= qt
.getTypePtr();
4552 int depth
= array_depth(type
);
4553 QualType base
= base_type(qt
);
4558 array
= isl_calloc_type(ctx
, struct pet_array
);
4562 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
4563 dim
= isl_space_set_alloc(ctx
, 0, depth
);
4564 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
4566 array
->extent
= isl_set_nat_universe(dim
);
4568 dim
= isl_space_params_alloc(ctx
, 0);
4569 array
->context
= isl_set_universe(dim
);
4571 array
= set_upper_bounds(array
, type
, 0);
4575 name
= base
.getAsString();
4576 array
->element_type
= strdup(name
.c_str());
4577 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
4582 /* Construct a list of pet_arrays, one for each array (or scalar)
4583 * accessed inside "scop", add this list to "scop" and return the result.
4585 * The context of "scop" is updated with the intersection of
4586 * the contexts of all arrays, i.e., constraints on the parameters
4587 * that ensure that the arrays have a valid (non-negative) size.
4589 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
4592 set
<ValueDecl
*> arrays
;
4593 set
<ValueDecl
*>::iterator it
;
4595 struct pet_array
**scop_arrays
;
4600 pet_scop_collect_arrays(scop
, arrays
);
4601 if (arrays
.size() == 0)
4604 n_array
= scop
->n_array
;
4606 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
4607 n_array
+ arrays
.size());
4610 scop
->arrays
= scop_arrays
;
4612 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
4613 struct pet_array
*array
;
4614 scop
->arrays
[n_array
+ i
] = array
= extract_array(ctx
, *it
);
4615 if (!scop
->arrays
[n_array
+ i
])
4618 scop
->context
= isl_set_intersect(scop
->context
,
4619 isl_set_copy(array
->context
));
4626 pet_scop_free(scop
);
4630 /* Bound all parameters in scop->context to the possible values
4631 * of the corresponding C variable.
4633 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
4640 n
= isl_set_dim(scop
->context
, isl_dim_param
);
4641 for (int i
= 0; i
< n
; ++i
) {
4645 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
4646 if (is_nested_parameter(id
)) {
4648 isl_die(isl_set_get_ctx(scop
->context
),
4650 "unresolved nested parameter", goto error
);
4652 decl
= (ValueDecl
*) isl_id_get_user(id
);
4655 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
4663 pet_scop_free(scop
);
4667 /* Construct a pet_scop from the given function.
4669 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
4674 stmt
= fd
->getBody();
4676 if (options
->autodetect
)
4677 scop
= extract(stmt
);
4680 scop
= pet_scop_detect_parameter_accesses(scop
);
4681 scop
= scan_arrays(scop
);
4682 scop
= add_parameter_bounds(scop
);
4683 scop
= pet_scop_gist(scop
, value_bounds
);