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
*lhs
, *lhs_f
, *lhs_c
;
458 rhs_expr
= expr
->getRHS();
460 if (extract_int(rhs_expr
, &v
) < 0) {
465 lhs
= extract_affine(expr
->getLHS());
466 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
468 lhs
= isl_pw_aff_scale_down(lhs
, v
);
471 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(lhs
));
472 lhs_c
= isl_pw_aff_ceil(lhs
);
473 res
= isl_pw_aff_cond(isl_set_indicator_function(cond
), lhs_f
, lhs_c
);
478 /* Extract an affine expression from a modulo operation.
479 * In particular, if "expr" is lhs/rhs, then return
481 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
483 * The second argument (rhs) is required to be a (positive) integer constant.
485 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
488 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
493 rhs_expr
= expr
->getRHS();
494 if (rhs_expr
->getStmtClass() != Stmt::IntegerLiteralClass
) {
499 lhs
= extract_affine(expr
->getLHS());
500 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
503 extract_int(cast
<IntegerLiteral
>(rhs_expr
), &v
);
504 res
= isl_pw_aff_scale_down(isl_pw_aff_copy(lhs
), v
);
506 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(res
));
507 lhs_c
= isl_pw_aff_ceil(res
);
508 res
= isl_pw_aff_cond(isl_set_indicator_function(cond
), lhs_f
, lhs_c
);
510 res
= isl_pw_aff_scale(res
, v
);
513 res
= isl_pw_aff_sub(lhs
, res
);
518 /* Extract an affine expression from a multiplication operation.
519 * This is only allowed if at least one of the two arguments
520 * is a (piecewise) constant.
522 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
527 lhs
= extract_affine(expr
->getLHS());
528 rhs
= extract_affine(expr
->getRHS());
530 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
531 isl_pw_aff_free(lhs
);
532 isl_pw_aff_free(rhs
);
537 return isl_pw_aff_mul(lhs
, rhs
);
540 /* Extract an affine expression from an addition or subtraction operation.
542 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
547 lhs
= extract_affine(expr
->getLHS());
548 rhs
= extract_affine(expr
->getRHS());
550 switch (expr
->getOpcode()) {
552 return isl_pw_aff_add(lhs
, rhs
);
554 return isl_pw_aff_sub(lhs
, rhs
);
556 isl_pw_aff_free(lhs
);
557 isl_pw_aff_free(rhs
);
567 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
573 isl_int_set_si(mod
, 1);
574 isl_int_mul_2exp(mod
, mod
, width
);
576 pwaff
= isl_pw_aff_mod(pwaff
, mod
);
583 /* Limit the domain of "pwaff" to those elements where the function
586 * 2^{width-1} <= pwaff < 2^{width-1}
588 static __isl_give isl_pw_aff
*avoid_overflow(__isl_take isl_pw_aff
*pwaff
,
592 isl_space
*space
= isl_pw_aff_get_domain_space(pwaff
);
593 isl_local_space
*ls
= isl_local_space_from_space(space
);
599 isl_int_set_si(v
, 1);
600 isl_int_mul_2exp(v
, v
, width
- 1);
602 bound
= isl_aff_zero_on_domain(ls
);
603 bound
= isl_aff_add_constant(bound
, v
);
604 b
= isl_pw_aff_from_aff(bound
);
606 dom
= isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff
), isl_pw_aff_copy(b
));
607 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
609 b
= isl_pw_aff_neg(b
);
610 dom
= isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff
), b
);
611 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
618 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
620 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
621 __isl_take isl_set
*dom
)
624 pa
= isl_set_indicator_function(set
);
625 pa
= isl_pw_aff_intersect_domain(pa
, dom
);
629 /* Extract an affine expression from some binary operations.
630 * If the result of the expression is unsigned, then we wrap it
631 * based on the size of the type. Otherwise, we ensure that
632 * no overflow occurs.
634 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
639 switch (expr
->getOpcode()) {
642 res
= extract_affine_add(expr
);
645 res
= extract_affine_div(expr
);
648 res
= extract_affine_mod(expr
);
651 res
= extract_affine_mul(expr
);
661 return extract_condition(expr
);
667 width
= ast_context
.getIntWidth(expr
->getType());
668 if (expr
->getType()->isUnsignedIntegerType())
669 res
= wrap(res
, width
);
671 res
= avoid_overflow(res
, width
);
676 /* Extract an affine expression from a negation operation.
678 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
680 if (expr
->getOpcode() == UO_Minus
)
681 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
682 if (expr
->getOpcode() == UO_LNot
)
683 return extract_condition(expr
);
689 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
691 return extract_affine(expr
->getSubExpr());
694 /* Extract an affine expression from some special function calls.
695 * In particular, we handle "min", "max", "ceild" and "floord".
696 * In case of the latter two, the second argument needs to be
697 * a (positive) integer constant.
699 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
703 isl_pw_aff
*aff1
, *aff2
;
705 fd
= expr
->getDirectCallee();
711 name
= fd
->getDeclName().getAsString();
712 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
713 !(expr
->getNumArgs() == 2 && name
== "max") &&
714 !(expr
->getNumArgs() == 2 && name
== "floord") &&
715 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
720 if (name
== "min" || name
== "max") {
721 aff1
= extract_affine(expr
->getArg(0));
722 aff2
= extract_affine(expr
->getArg(1));
725 aff1
= isl_pw_aff_min(aff1
, aff2
);
727 aff1
= isl_pw_aff_max(aff1
, aff2
);
728 } else if (name
== "floord" || name
== "ceild") {
730 Expr
*arg2
= expr
->getArg(1);
732 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
736 aff1
= extract_affine(expr
->getArg(0));
738 extract_int(cast
<IntegerLiteral
>(arg2
), &v
);
739 aff1
= isl_pw_aff_scale_down(aff1
, v
);
741 if (name
== "floord")
742 aff1
= isl_pw_aff_floor(aff1
);
744 aff1
= isl_pw_aff_ceil(aff1
);
753 /* This method is called when we come across an access that is
754 * nested in what is supposed to be an affine expression.
755 * If nesting is allowed, we return a new parameter that corresponds
756 * to this nested access. Otherwise, we simply complain.
758 * Note that we currently don't allow nested accesses themselves
759 * to contain any nested accesses, so we check if we can extract
760 * the access without any nesting and complain if we can't.
762 * The new parameter is resolved in resolve_nested.
764 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
772 if (!nesting_enabled
) {
777 allow_nested
= false;
778 access
= extract_access(expr
);
784 isl_map_free(access
);
786 id
= isl_id_alloc(ctx
, NULL
, expr
);
787 dim
= isl_space_params_alloc(ctx
, 1);
789 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
791 dom
= isl_set_universe(isl_space_copy(dim
));
792 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
793 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
795 return isl_pw_aff_alloc(dom
, aff
);
798 /* Affine expressions are not supposed to contain array accesses,
799 * but if nesting is allowed, we return a parameter corresponding
800 * to the array access.
802 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
804 return nested_access(expr
);
807 /* Extract an affine expression from a conditional operation.
809 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
811 isl_pw_aff
*cond
, *lhs
, *rhs
, *res
;
813 cond
= extract_condition(expr
->getCond());
814 lhs
= extract_affine(expr
->getTrueExpr());
815 rhs
= extract_affine(expr
->getFalseExpr());
817 return isl_pw_aff_cond(cond
, lhs
, rhs
);
820 /* Extract an affine expression, if possible, from "expr".
821 * Otherwise return NULL.
823 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
825 switch (expr
->getStmtClass()) {
826 case Stmt::ImplicitCastExprClass
:
827 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
828 case Stmt::IntegerLiteralClass
:
829 return extract_affine(cast
<IntegerLiteral
>(expr
));
830 case Stmt::DeclRefExprClass
:
831 return extract_affine(cast
<DeclRefExpr
>(expr
));
832 case Stmt::BinaryOperatorClass
:
833 return extract_affine(cast
<BinaryOperator
>(expr
));
834 case Stmt::UnaryOperatorClass
:
835 return extract_affine(cast
<UnaryOperator
>(expr
));
836 case Stmt::ParenExprClass
:
837 return extract_affine(cast
<ParenExpr
>(expr
));
838 case Stmt::CallExprClass
:
839 return extract_affine(cast
<CallExpr
>(expr
));
840 case Stmt::ArraySubscriptExprClass
:
841 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
842 case Stmt::ConditionalOperatorClass
:
843 return extract_affine(cast
<ConditionalOperator
>(expr
));
850 __isl_give isl_map
*PetScan::extract_access(ImplicitCastExpr
*expr
)
852 return extract_access(expr
->getSubExpr());
855 /* Return the depth of an array of the given type.
857 static int array_depth(const Type
*type
)
859 if (type
->isPointerType())
860 return 1 + array_depth(type
->getPointeeType().getTypePtr());
861 if (type
->isArrayType()) {
862 const ArrayType
*atype
;
863 type
= type
->getCanonicalTypeInternal().getTypePtr();
864 atype
= cast
<ArrayType
>(type
);
865 return 1 + array_depth(atype
->getElementType().getTypePtr());
870 /* Return the element type of the given array type.
872 static QualType
base_type(QualType qt
)
874 const Type
*type
= qt
.getTypePtr();
876 if (type
->isPointerType())
877 return base_type(type
->getPointeeType());
878 if (type
->isArrayType()) {
879 const ArrayType
*atype
;
880 type
= type
->getCanonicalTypeInternal().getTypePtr();
881 atype
= cast
<ArrayType
>(type
);
882 return base_type(atype
->getElementType());
887 /* Extract an access relation from a reference to a variable.
888 * If the variable has name "A" and its type corresponds to an
889 * array of depth d, then the returned access relation is of the
892 * { [] -> A[i_1,...,i_d] }
894 __isl_give isl_map
*PetScan::extract_access(DeclRefExpr
*expr
)
896 ValueDecl
*decl
= expr
->getDecl();
897 int depth
= array_depth(decl
->getType().getTypePtr());
898 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
899 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, depth
);
902 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
904 access_rel
= isl_map_universe(dim
);
909 /* Extract an access relation from an integer contant.
910 * If the value of the constant is "v", then the returned access relation
915 __isl_give isl_map
*PetScan::extract_access(IntegerLiteral
*expr
)
917 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr
)));
920 /* Try and extract an access relation from the given Expr.
921 * Return NULL if it doesn't work out.
923 __isl_give isl_map
*PetScan::extract_access(Expr
*expr
)
925 switch (expr
->getStmtClass()) {
926 case Stmt::ImplicitCastExprClass
:
927 return extract_access(cast
<ImplicitCastExpr
>(expr
));
928 case Stmt::DeclRefExprClass
:
929 return extract_access(cast
<DeclRefExpr
>(expr
));
930 case Stmt::ArraySubscriptExprClass
:
931 return extract_access(cast
<ArraySubscriptExpr
>(expr
));
932 case Stmt::IntegerLiteralClass
:
933 return extract_access(cast
<IntegerLiteral
>(expr
));
940 /* Assign the affine expression "index" to the output dimension "pos" of "map",
941 * restrict the domain to those values that result in a non-negative index
942 * and return the result.
944 __isl_give isl_map
*set_index(__isl_take isl_map
*map
, int pos
,
945 __isl_take isl_pw_aff
*index
)
948 int len
= isl_map_dim(map
, isl_dim_out
);
952 domain
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(index
));
953 index
= isl_pw_aff_intersect_domain(index
, domain
);
954 index_map
= isl_map_from_range(isl_set_from_pw_aff(index
));
955 index_map
= isl_map_insert_dims(index_map
, isl_dim_out
, 0, pos
);
956 index_map
= isl_map_add_dims(index_map
, isl_dim_out
, len
- pos
- 1);
957 id
= isl_map_get_tuple_id(map
, isl_dim_out
);
958 index_map
= isl_map_set_tuple_id(index_map
, isl_dim_out
, id
);
960 map
= isl_map_intersect(map
, index_map
);
965 /* Extract an access relation from the given array subscript expression.
966 * If nesting is allowed in general, then we turn it on while
967 * examining the index expression.
969 * We first extract an access relation from the base.
970 * This will result in an access relation with a range that corresponds
971 * to the array being accessed and with earlier indices filled in already.
972 * We then extract the current index and fill that in as well.
973 * The position of the current index is based on the type of base.
974 * If base is the actual array variable, then the depth of this type
975 * will be the same as the depth of the array and we will fill in
976 * the first array index.
977 * Otherwise, the depth of the base type will be smaller and we will fill
980 __isl_give isl_map
*PetScan::extract_access(ArraySubscriptExpr
*expr
)
982 Expr
*base
= expr
->getBase();
983 Expr
*idx
= expr
->getIdx();
985 isl_map
*base_access
;
987 int depth
= array_depth(base
->getType().getTypePtr());
989 bool save_nesting
= nesting_enabled
;
991 nesting_enabled
= allow_nested
;
993 base_access
= extract_access(base
);
994 index
= extract_affine(idx
);
996 nesting_enabled
= save_nesting
;
998 pos
= isl_map_dim(base_access
, isl_dim_out
) - depth
;
999 access
= set_index(base_access
, pos
, index
);
1004 /* Check if "expr" calls function "minmax" with two arguments and if so
1005 * make lhs and rhs refer to these two arguments.
1007 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
1013 if (expr
->getStmtClass() != Stmt::CallExprClass
)
1016 call
= cast
<CallExpr
>(expr
);
1017 fd
= call
->getDirectCallee();
1021 if (call
->getNumArgs() != 2)
1024 name
= fd
->getDeclName().getAsString();
1028 lhs
= call
->getArg(0);
1029 rhs
= call
->getArg(1);
1034 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1035 * lhs and rhs refer to the two arguments.
1037 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1039 return is_minmax(expr
, "min", lhs
, rhs
);
1042 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1043 * lhs and rhs refer to the two arguments.
1045 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1047 return is_minmax(expr
, "max", lhs
, rhs
);
1050 /* Return "lhs && rhs", defined on the shared definition domain.
1052 static __isl_give isl_pw_aff
*pw_aff_and(__isl_take isl_pw_aff
*lhs
,
1053 __isl_take isl_pw_aff
*rhs
)
1058 dom
= isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs
)),
1059 isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1060 cond
= isl_set_intersect(isl_pw_aff_non_zero_set(lhs
),
1061 isl_pw_aff_non_zero_set(rhs
));
1062 return indicator_function(cond
, dom
);
1065 /* Return "lhs && rhs", with shortcut semantics.
1066 * That is, if lhs is false, then the result is defined even if rhs is not.
1067 * In practice, we compute lhs ? rhs : lhs.
1069 static __isl_give isl_pw_aff
*pw_aff_and_then(__isl_take isl_pw_aff
*lhs
,
1070 __isl_take isl_pw_aff
*rhs
)
1072 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), rhs
, lhs
);
1075 /* Return "lhs || rhs", with shortcut semantics.
1076 * That is, if lhs is true, then the result is defined even if rhs is not.
1077 * In practice, we compute lhs ? lhs : rhs.
1079 static __isl_give isl_pw_aff
*pw_aff_or_else(__isl_take isl_pw_aff
*lhs
,
1080 __isl_take isl_pw_aff
*rhs
)
1082 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), lhs
, rhs
);
1085 /* Extract an affine expressions representing the comparison "LHS op RHS"
1086 * "comp" is the original statement that "LHS op RHS" is derived from
1087 * and is used for diagnostics.
1089 * If the comparison is of the form
1093 * then the expression is constructed as the conjunction of
1098 * A similar optimization is performed for max(a,b) <= c.
1099 * We do this because that will lead to simpler representations
1100 * of the expression.
1101 * If isl is ever enhanced to explicitly deal with min and max expressions,
1102 * this optimization can be removed.
1104 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
1105 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
1114 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
1116 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
1118 if (op
== BO_LT
|| op
== BO_LE
) {
1119 Expr
*expr1
, *expr2
;
1120 if (is_min(RHS
, expr1
, expr2
)) {
1121 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
1122 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
1123 return pw_aff_and(lhs
, rhs
);
1125 if (is_max(LHS
, expr1
, expr2
)) {
1126 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
1127 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
1128 return pw_aff_and(lhs
, rhs
);
1132 lhs
= extract_affine(LHS
);
1133 rhs
= extract_affine(RHS
);
1135 dom
= isl_pw_aff_domain(isl_pw_aff_copy(lhs
));
1136 dom
= isl_set_intersect(dom
, isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1140 cond
= isl_pw_aff_lt_set(lhs
, rhs
);
1143 cond
= isl_pw_aff_le_set(lhs
, rhs
);
1146 cond
= isl_pw_aff_eq_set(lhs
, rhs
);
1149 cond
= isl_pw_aff_ne_set(lhs
, rhs
);
1152 isl_pw_aff_free(lhs
);
1153 isl_pw_aff_free(rhs
);
1159 cond
= isl_set_coalesce(cond
);
1160 res
= indicator_function(cond
, dom
);
1165 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
1167 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1168 comp
->getRHS(), comp
);
1171 /* Extract an affine expression representing the negation (logical not)
1172 * of a subexpression.
1174 __isl_give isl_pw_aff
*PetScan::extract_boolean(UnaryOperator
*op
)
1176 isl_set
*set_cond
, *dom
;
1177 isl_pw_aff
*cond
, *res
;
1179 cond
= extract_condition(op
->getSubExpr());
1181 dom
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
1183 set_cond
= isl_pw_aff_zero_set(cond
);
1185 res
= indicator_function(set_cond
, dom
);
1190 /* Extract an affine expression representing the disjunction (logical or)
1191 * or conjunction (logical and) of two subexpressions.
1193 __isl_give isl_pw_aff
*PetScan::extract_boolean(BinaryOperator
*comp
)
1195 isl_pw_aff
*lhs
, *rhs
;
1197 lhs
= extract_condition(comp
->getLHS());
1198 rhs
= extract_condition(comp
->getRHS());
1200 switch (comp
->getOpcode()) {
1202 return pw_aff_and_then(lhs
, rhs
);
1204 return pw_aff_or_else(lhs
, rhs
);
1206 isl_pw_aff_free(lhs
);
1207 isl_pw_aff_free(rhs
);
1214 __isl_give isl_pw_aff
*PetScan::extract_condition(UnaryOperator
*expr
)
1216 switch (expr
->getOpcode()) {
1218 return extract_boolean(expr
);
1225 /* Extract the affine expression "expr != 0 ? 1 : 0".
1227 __isl_give isl_pw_aff
*PetScan::extract_implicit_condition(Expr
*expr
)
1232 res
= extract_affine(expr
);
1234 dom
= isl_pw_aff_domain(isl_pw_aff_copy(res
));
1235 set
= isl_pw_aff_non_zero_set(res
);
1237 res
= indicator_function(set
, dom
);
1242 /* Extract an affine expression from a boolean expression.
1243 * In particular, return the expression "expr ? 1 : 0".
1245 * If the expression doesn't look like a condition, we assume it
1246 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1248 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
1250 BinaryOperator
*comp
;
1253 isl_set
*u
= isl_set_universe(isl_space_params_alloc(ctx
, 0));
1254 return indicator_function(u
, isl_set_copy(u
));
1257 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1258 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1260 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1261 return extract_condition(cast
<UnaryOperator
>(expr
));
1263 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1264 return extract_implicit_condition(expr
);
1266 comp
= cast
<BinaryOperator
>(expr
);
1267 switch (comp
->getOpcode()) {
1274 return extract_comparison(comp
);
1277 return extract_boolean(comp
);
1279 return extract_implicit_condition(expr
);
1283 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
1287 return pet_op_minus
;
1289 return pet_op_post_inc
;
1291 return pet_op_post_dec
;
1293 return pet_op_pre_inc
;
1295 return pet_op_pre_dec
;
1301 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
1305 return pet_op_add_assign
;
1307 return pet_op_sub_assign
;
1309 return pet_op_mul_assign
;
1311 return pet_op_div_assign
;
1313 return pet_op_assign
;
1335 /* Construct a pet_expr representing a unary operator expression.
1337 struct pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1339 struct pet_expr
*arg
;
1340 enum pet_op_type op
;
1342 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1343 if (op
== pet_op_last
) {
1348 arg
= extract_expr(expr
->getSubExpr());
1350 if (expr
->isIncrementDecrementOp() &&
1351 arg
&& arg
->type
== pet_expr_access
) {
1356 return pet_expr_new_unary(ctx
, op
, arg
);
1359 /* Mark the given access pet_expr as a write.
1360 * If a scalar is being accessed, then mark its value
1361 * as unknown in assigned_value.
1363 void PetScan::mark_write(struct pet_expr
*access
)
1368 access
->acc
.write
= 1;
1369 access
->acc
.read
= 0;
1371 if (isl_map_dim(access
->acc
.access
, isl_dim_out
) != 0)
1374 id
= isl_map_get_tuple_id(access
->acc
.access
, isl_dim_out
);
1375 decl
= (ValueDecl
*) isl_id_get_user(id
);
1376 clear_assignment(assigned_value
, decl
);
1380 /* Construct a pet_expr representing a binary operator expression.
1382 * If the top level operator is an assignment and the LHS is an access,
1383 * then we mark that access as a write. If the operator is a compound
1384 * assignment, the access is marked as both a read and a write.
1386 * If "expr" assigns something to a scalar variable, then we mark
1387 * the variable as having been assigned. If, furthermore, the expression
1388 * is affine, then keep track of this value in assigned_value
1389 * so that we can plug it in when we later come across the same variable.
1391 struct pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1393 struct pet_expr
*lhs
, *rhs
;
1394 enum pet_op_type op
;
1396 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1397 if (op
== pet_op_last
) {
1402 lhs
= extract_expr(expr
->getLHS());
1403 rhs
= extract_expr(expr
->getRHS());
1405 if (expr
->isAssignmentOp() && lhs
&& lhs
->type
== pet_expr_access
) {
1407 if (expr
->isCompoundAssignmentOp())
1411 if (expr
->getOpcode() == BO_Assign
&&
1412 lhs
&& lhs
->type
== pet_expr_access
&&
1413 isl_map_dim(lhs
->acc
.access
, isl_dim_out
) == 0) {
1414 isl_id
*id
= isl_map_get_tuple_id(lhs
->acc
.access
, isl_dim_out
);
1415 ValueDecl
*decl
= (ValueDecl
*) isl_id_get_user(id
);
1416 Expr
*rhs
= expr
->getRHS();
1417 isl_pw_aff
*pa
= try_extract_affine(rhs
);
1418 clear_assignment(assigned_value
, decl
);
1420 assigned_value
[decl
] = pa
;
1421 insert_expression(pa
);
1426 return pet_expr_new_binary(ctx
, op
, lhs
, rhs
);
1429 /* Construct a pet_expr representing a conditional operation.
1431 * We first try to extract the condition as an affine expression.
1432 * If that fails, we construct a pet_expr tree representing the condition.
1434 struct pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1436 struct pet_expr
*cond
, *lhs
, *rhs
;
1439 pa
= try_extract_affine(expr
->getCond());
1441 isl_set
*test
= isl_set_from_pw_aff(pa
);
1442 cond
= pet_expr_from_access(isl_map_from_range(test
));
1444 cond
= extract_expr(expr
->getCond());
1445 lhs
= extract_expr(expr
->getTrueExpr());
1446 rhs
= extract_expr(expr
->getFalseExpr());
1448 return pet_expr_new_ternary(ctx
, cond
, lhs
, rhs
);
1451 struct pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1453 return extract_expr(expr
->getSubExpr());
1456 /* Construct a pet_expr representing a floating point value.
1458 struct pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1460 return pet_expr_new_double(ctx
, expr
->getValueAsApproximateDouble());
1463 /* Extract an access relation from "expr" and then convert it into
1466 struct pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1469 struct pet_expr
*pe
;
1471 access
= extract_access(expr
);
1473 pe
= pet_expr_from_access(access
);
1478 struct pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1480 return extract_expr(expr
->getSubExpr());
1483 /* Construct a pet_expr representing a function call.
1485 * If we are passing along a pointer to an array element
1486 * or an entire row or even higher dimensional slice of an array,
1487 * then the function being called may write into the array.
1489 * We assume here that if the function is declared to take a pointer
1490 * to a const type, then the function will perform a read
1491 * and that otherwise, it will perform a write.
1493 struct pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1495 struct pet_expr
*res
= NULL
;
1499 fd
= expr
->getDirectCallee();
1505 name
= fd
->getDeclName().getAsString();
1506 res
= pet_expr_new_call(ctx
, name
.c_str(), expr
->getNumArgs());
1510 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
1511 Expr
*arg
= expr
->getArg(i
);
1515 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1516 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(arg
);
1517 arg
= ice
->getSubExpr();
1519 if (arg
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1520 UnaryOperator
*op
= cast
<UnaryOperator
>(arg
);
1521 if (op
->getOpcode() == UO_AddrOf
) {
1523 arg
= op
->getSubExpr();
1526 res
->args
[i
] = PetScan::extract_expr(arg
);
1527 main_arg
= res
->args
[i
];
1529 res
->args
[i
] = pet_expr_new_unary(ctx
,
1530 pet_op_address_of
, res
->args
[i
]);
1533 if (arg
->getStmtClass() == Stmt::ArraySubscriptExprClass
&&
1534 array_depth(arg
->getType().getTypePtr()) > 0)
1536 if (is_addr
&& main_arg
->type
== pet_expr_access
) {
1538 if (!fd
->hasPrototype()) {
1539 unsupported(expr
, "prototype required");
1542 parm
= fd
->getParamDecl(i
);
1543 if (!const_base(parm
->getType()))
1544 mark_write(main_arg
);
1554 /* Try and onstruct a pet_expr representing "expr".
1556 struct pet_expr
*PetScan::extract_expr(Expr
*expr
)
1558 switch (expr
->getStmtClass()) {
1559 case Stmt::UnaryOperatorClass
:
1560 return extract_expr(cast
<UnaryOperator
>(expr
));
1561 case Stmt::CompoundAssignOperatorClass
:
1562 case Stmt::BinaryOperatorClass
:
1563 return extract_expr(cast
<BinaryOperator
>(expr
));
1564 case Stmt::ImplicitCastExprClass
:
1565 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1566 case Stmt::ArraySubscriptExprClass
:
1567 case Stmt::DeclRefExprClass
:
1568 case Stmt::IntegerLiteralClass
:
1569 return extract_access_expr(expr
);
1570 case Stmt::FloatingLiteralClass
:
1571 return extract_expr(cast
<FloatingLiteral
>(expr
));
1572 case Stmt::ParenExprClass
:
1573 return extract_expr(cast
<ParenExpr
>(expr
));
1574 case Stmt::ConditionalOperatorClass
:
1575 return extract_expr(cast
<ConditionalOperator
>(expr
));
1576 case Stmt::CallExprClass
:
1577 return extract_expr(cast
<CallExpr
>(expr
));
1584 /* Check if the given initialization statement is an assignment.
1585 * If so, return that assignment. Otherwise return NULL.
1587 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1589 BinaryOperator
*ass
;
1591 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1594 ass
= cast
<BinaryOperator
>(init
);
1595 if (ass
->getOpcode() != BO_Assign
)
1601 /* Check if the given initialization statement is a declaration
1602 * of a single variable.
1603 * If so, return that declaration. Otherwise return NULL.
1605 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1609 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1612 decl
= cast
<DeclStmt
>(init
);
1614 if (!decl
->isSingleDecl())
1617 return decl
->getSingleDecl();
1620 /* Given the assignment operator in the initialization of a for loop,
1621 * extract the induction variable, i.e., the (integer)variable being
1624 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1631 lhs
= init
->getLHS();
1632 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1637 ref
= cast
<DeclRefExpr
>(lhs
);
1638 decl
= ref
->getDecl();
1639 type
= decl
->getType().getTypePtr();
1641 if (!type
->isIntegerType()) {
1649 /* Given the initialization statement of a for loop and the single
1650 * declaration in this initialization statement,
1651 * extract the induction variable, i.e., the (integer) variable being
1654 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1658 vd
= cast
<VarDecl
>(decl
);
1660 const QualType type
= vd
->getType();
1661 if (!type
->isIntegerType()) {
1666 if (!vd
->getInit()) {
1674 /* Check that op is of the form iv++ or iv--.
1675 * Return an affine expression "1" or "-1" accordingly.
1677 __isl_give isl_pw_aff
*PetScan::extract_unary_increment(
1678 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1685 if (!op
->isIncrementDecrementOp()) {
1690 sub
= op
->getSubExpr();
1691 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1696 ref
= cast
<DeclRefExpr
>(sub
);
1697 if (ref
->getDecl() != iv
) {
1702 space
= isl_space_params_alloc(ctx
, 0);
1703 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
1705 if (op
->isIncrementOp())
1706 aff
= isl_aff_add_constant_si(aff
, 1);
1708 aff
= isl_aff_add_constant_si(aff
, -1);
1710 return isl_pw_aff_from_aff(aff
);
1713 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1714 * has a single constant expression, then put this constant in *user.
1715 * The caller is assumed to have checked that this function will
1716 * be called exactly once.
1718 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
1721 isl_int
*inc
= (isl_int
*)user
;
1724 if (isl_aff_is_cst(aff
))
1725 isl_aff_get_constant(aff
, inc
);
1735 /* Check if op is of the form
1739 * and return inc as an affine expression.
1741 * We extract an affine expression from the RHS, subtract iv and return
1744 __isl_give isl_pw_aff
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1745 clang::ValueDecl
*iv
)
1754 if (op
->getOpcode() != BO_Assign
) {
1760 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1765 ref
= cast
<DeclRefExpr
>(lhs
);
1766 if (ref
->getDecl() != iv
) {
1771 val
= extract_affine(op
->getRHS());
1773 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1775 dim
= isl_space_params_alloc(ctx
, 1);
1776 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1777 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1778 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1780 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
1785 /* Check that op is of the form iv += cst or iv -= cst
1786 * and return an affine expression corresponding oto cst or -cst accordingly.
1788 __isl_give isl_pw_aff
*PetScan::extract_compound_increment(
1789 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1795 BinaryOperatorKind opcode
;
1797 opcode
= op
->getOpcode();
1798 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1802 if (opcode
== BO_SubAssign
)
1806 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1811 ref
= cast
<DeclRefExpr
>(lhs
);
1812 if (ref
->getDecl() != iv
) {
1817 val
= extract_affine(op
->getRHS());
1819 val
= isl_pw_aff_neg(val
);
1824 /* Check that the increment of the given for loop increments
1825 * (or decrements) the induction variable "iv" and return
1826 * the increment as an affine expression if successful.
1828 __isl_give isl_pw_aff
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1831 Stmt
*inc
= stmt
->getInc();
1838 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1839 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1840 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1841 return extract_compound_increment(
1842 cast
<CompoundAssignOperator
>(inc
), iv
);
1843 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1844 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1850 /* Embed the given iteration domain in an extra outer loop
1851 * with induction variable "var".
1852 * If this variable appeared as a parameter in the constraints,
1853 * it is replaced by the new outermost dimension.
1855 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1856 __isl_take isl_id
*var
)
1860 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1861 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1863 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1864 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1871 /* Return those elements in the space of "cond" that come after
1872 * (based on "sign") an element in "cond".
1874 static __isl_give isl_set
*after(__isl_take isl_set
*cond
, int sign
)
1876 isl_map
*previous_to_this
;
1879 previous_to_this
= isl_map_lex_lt(isl_set_get_space(cond
));
1881 previous_to_this
= isl_map_lex_gt(isl_set_get_space(cond
));
1883 cond
= isl_set_apply(cond
, previous_to_this
);
1888 /* Create the infinite iteration domain
1890 * { [id] : id >= 0 }
1892 * If "scop" has an affine skip of type pet_skip_later,
1893 * then remove those iterations i that have an earlier iteration
1894 * where the skip condition is satisfied, meaning that iteration i
1896 * Since we are dealing with a loop without loop iterator,
1897 * the skip condition cannot refer to the current loop iterator and
1898 * so effectively, the returned set is of the form
1900 * { [0]; [id] : id >= 1 and not skip }
1902 static __isl_give isl_set
*infinite_domain(__isl_take isl_id
*id
,
1903 struct pet_scop
*scop
)
1905 isl_ctx
*ctx
= isl_id_get_ctx(id
);
1909 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
1910 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, id
);
1912 if (!pet_scop_has_affine_skip(scop
, pet_skip_later
))
1915 skip
= pet_scop_get_skip(scop
, pet_skip_later
);
1916 skip
= isl_set_fix_si(skip
, isl_dim_set
, 0, 1);
1917 skip
= isl_set_params(skip
);
1918 skip
= embed(skip
, isl_id_copy(id
));
1919 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
1920 domain
= isl_set_subtract(domain
, after(skip
, 1));
1925 /* Create an identity mapping on the space containing "domain".
1927 static __isl_give isl_map
*identity_map(__isl_keep isl_set
*domain
)
1932 space
= isl_space_map_from_set(isl_set_get_space(domain
));
1933 id
= isl_map_identity(space
);
1938 /* Add a filter to "scop" that imposes that it is only executed
1939 * when "break_access" has a zero value for all previous iterations
1942 * The input "break_access" has a zero-dimensional domain and range.
1944 static struct pet_scop
*scop_add_break(struct pet_scop
*scop
,
1945 __isl_take isl_map
*break_access
, __isl_take isl_set
*domain
, int sign
)
1947 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
1951 id_test
= isl_map_get_tuple_id(break_access
, isl_dim_out
);
1952 break_access
= isl_map_add_dims(break_access
, isl_dim_in
, 1);
1953 break_access
= isl_map_add_dims(break_access
, isl_dim_out
, 1);
1954 break_access
= isl_map_intersect_range(break_access
, domain
);
1955 break_access
= isl_map_set_tuple_id(break_access
, isl_dim_out
, id_test
);
1957 prev
= isl_map_lex_gt_first(isl_map_get_space(break_access
), 1);
1959 prev
= isl_map_lex_lt_first(isl_map_get_space(break_access
), 1);
1960 break_access
= isl_map_intersect(break_access
, prev
);
1961 scop
= pet_scop_filter(scop
, break_access
, 0);
1962 scop
= pet_scop_merge_filters(scop
);
1967 /* Construct a pet_scop for an infinite loop around the given body.
1969 * We extract a pet_scop for the body and then embed it in a loop with
1978 * If the body contains any break, then it is taken into
1979 * account in infinite_domain (if the skip condition is affine)
1980 * or in scop_add_break (if the skip condition is not affine).
1982 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
1988 struct pet_scop
*scop
;
1991 scop
= extract(body
);
1995 id
= isl_id_alloc(ctx
, "t", NULL
);
1996 domain
= infinite_domain(isl_id_copy(id
), scop
);
1997 ident
= identity_map(domain
);
1999 has_var_break
= pet_scop_has_var_skip(scop
, pet_skip_later
);
2001 access
= pet_scop_get_skip_map(scop
, pet_skip_later
);
2003 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
2004 isl_map_copy(ident
), ident
, id
);
2006 scop
= scop_add_break(scop
, access
, domain
, 1);
2008 isl_set_free(domain
);
2013 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2019 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
2021 return extract_infinite_loop(stmt
->getBody());
2024 /* Create an access to a virtual array representing the result
2026 * Unlike other accessed data, the id of the array is NULL as
2027 * there is no ValueDecl in the program corresponding to the virtual
2029 * The array starts out as a scalar, but grows along with the
2030 * statement writing to the array in pet_scop_embed.
2032 static __isl_give isl_map
*create_test_access(isl_ctx
*ctx
, int test_nr
)
2034 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, 0);
2038 snprintf(name
, sizeof(name
), "__pet_test_%d", test_nr
);
2039 id
= isl_id_alloc(ctx
, name
, NULL
);
2040 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
2041 return isl_map_universe(dim
);
2044 /* Add an array with the given extent ("access") to the list
2045 * of arrays in "scop" and return the extended pet_scop.
2046 * The array is marked as attaining values 0 and 1 only and
2047 * as each element being assigned at most once.
2049 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2050 __isl_keep isl_map
*access
, clang::ASTContext
&ast_ctx
)
2052 isl_ctx
*ctx
= isl_map_get_ctx(access
);
2054 struct pet_array
**arrays
;
2055 struct pet_array
*array
;
2062 arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
2066 scop
->arrays
= arrays
;
2068 array
= isl_calloc_type(ctx
, struct pet_array
);
2072 array
->extent
= isl_map_range(isl_map_copy(access
));
2073 dim
= isl_space_params_alloc(ctx
, 0);
2074 array
->context
= isl_set_universe(dim
);
2075 dim
= isl_space_set_alloc(ctx
, 0, 1);
2076 array
->value_bounds
= isl_set_universe(dim
);
2077 array
->value_bounds
= isl_set_lower_bound_si(array
->value_bounds
,
2079 array
->value_bounds
= isl_set_upper_bound_si(array
->value_bounds
,
2081 array
->element_type
= strdup("int");
2082 array
->element_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
2083 array
->uniquely_defined
= 1;
2085 scop
->arrays
[scop
->n_array
] = array
;
2088 if (!array
->extent
|| !array
->context
)
2093 pet_scop_free(scop
);
2097 /* Construct a pet_scop for a while loop of the form
2102 * In particular, construct a scop for an infinite loop around body and
2103 * intersect the domain with the affine expression.
2104 * Note that this intersection may result in an empty loop.
2106 struct pet_scop
*PetScan::extract_affine_while(__isl_take isl_pw_aff
*pa
,
2109 struct pet_scop
*scop
;
2113 valid
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2114 dom
= isl_pw_aff_non_zero_set(pa
);
2115 scop
= extract_infinite_loop(body
);
2116 scop
= pet_scop_restrict(scop
, dom
);
2117 scop
= pet_scop_restrict_context(scop
, valid
);
2122 /* Construct a scop for a while, given the scops for the condition
2123 * and the body, the filter access and the iteration domain of
2126 * In particular, the scop for the condition is filtered to depend
2127 * on "test_access" evaluating to true for all previous iterations
2128 * of the loop, while the scop for the body is filtered to depend
2129 * on "test_access" evaluating to true for all iterations up to the
2130 * current iteration.
2132 * These filtered scops are then combined into a single scop.
2134 * "sign" is positive if the iterator increases and negative
2137 static struct pet_scop
*scop_add_while(struct pet_scop
*scop_cond
,
2138 struct pet_scop
*scop_body
, __isl_take isl_map
*test_access
,
2139 __isl_take isl_set
*domain
, int sign
)
2141 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
2145 id_test
= isl_map_get_tuple_id(test_access
, isl_dim_out
);
2146 test_access
= isl_map_add_dims(test_access
, isl_dim_in
, 1);
2147 test_access
= isl_map_add_dims(test_access
, isl_dim_out
, 1);
2148 test_access
= isl_map_intersect_range(test_access
, domain
);
2149 test_access
= isl_map_set_tuple_id(test_access
, isl_dim_out
, id_test
);
2151 prev
= isl_map_lex_ge_first(isl_map_get_space(test_access
), 1);
2153 prev
= isl_map_lex_le_first(isl_map_get_space(test_access
), 1);
2154 test_access
= isl_map_intersect(test_access
, prev
);
2155 scop_body
= pet_scop_filter(scop_body
, isl_map_copy(test_access
), 1);
2157 prev
= isl_map_lex_gt_first(isl_map_get_space(test_access
), 1);
2159 prev
= isl_map_lex_lt_first(isl_map_get_space(test_access
), 1);
2160 test_access
= isl_map_intersect(test_access
, prev
);
2161 scop_cond
= pet_scop_filter(scop_cond
, test_access
, 1);
2163 return pet_scop_add_seq(ctx
, scop_cond
, scop_body
);
2166 /* Check if the while loop is of the form
2168 * while (affine expression)
2171 * If so, call extract_affine_while to construct a scop.
2173 * Otherwise, construct a generic while scop, with iteration domain
2174 * { [t] : t >= 0 }. The scop consists of two parts, one for
2175 * evaluating the condition and one for the body.
2176 * The schedule is adjusted to reflect that the condition is evaluated
2177 * before the body is executed and the body is filtered to depend
2178 * on the result of the condition evaluating to true on all iterations
2179 * up to the current iteration, while the evaluation the condition itself
2180 * is filtered to depend on the result of the condition evaluating to true
2181 * on all previous iterations.
2182 * The context of the scop representing the body is dropped
2183 * because we don't know how many times the body will be executed,
2186 * If the body contains any break, then it is taken into
2187 * account in infinite_domain (if the skip condition is affine)
2188 * or in scop_add_break (if the skip condition is not affine).
2190 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
2194 isl_map
*test_access
;
2198 struct pet_scop
*scop
, *scop_body
;
2200 isl_map
*break_access
;
2202 cond
= stmt
->getCond();
2208 pa
= try_extract_affine_condition(cond
);
2210 return extract_affine_while(pa
, stmt
->getBody());
2212 if (!allow_nested
) {
2217 test_access
= create_test_access(ctx
, n_test
++);
2218 scop
= extract_non_affine_condition(cond
, isl_map_copy(test_access
));
2219 scop
= scop_add_array(scop
, test_access
, ast_context
);
2220 scop_body
= extract(stmt
->getBody());
2222 id
= isl_id_alloc(ctx
, "t", NULL
);
2223 domain
= infinite_domain(isl_id_copy(id
), scop_body
);
2224 ident
= identity_map(domain
);
2226 has_var_break
= pet_scop_has_var_skip(scop_body
, pet_skip_later
);
2228 break_access
= pet_scop_get_skip_map(scop_body
, pet_skip_later
);
2230 scop
= pet_scop_prefix(scop
, 0);
2231 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), isl_map_copy(ident
),
2232 isl_map_copy(ident
), isl_id_copy(id
));
2233 scop_body
= pet_scop_reset_context(scop_body
);
2234 scop_body
= pet_scop_prefix(scop_body
, 1);
2235 scop_body
= pet_scop_embed(scop_body
, isl_set_copy(domain
),
2236 isl_map_copy(ident
), ident
, id
);
2238 if (has_var_break
) {
2239 scop
= scop_add_break(scop
, isl_map_copy(break_access
),
2240 isl_set_copy(domain
), 1);
2241 scop_body
= scop_add_break(scop_body
, break_access
,
2242 isl_set_copy(domain
), 1);
2244 scop
= scop_add_while(scop
, scop_body
, test_access
, domain
, 1);
2249 /* Check whether "cond" expresses a simple loop bound
2250 * on the only set dimension.
2251 * In particular, if "up" is set then "cond" should contain only
2252 * upper bounds on the set dimension.
2253 * Otherwise, it should contain only lower bounds.
2255 static bool is_simple_bound(__isl_keep isl_set
*cond
, isl_int inc
)
2257 if (isl_int_is_pos(inc
))
2258 return !isl_set_dim_has_lower_bound(cond
, isl_dim_set
, 0);
2260 return !isl_set_dim_has_upper_bound(cond
, isl_dim_set
, 0);
2263 /* Extend a condition on a given iteration of a loop to one that
2264 * imposes the same condition on all previous iterations.
2265 * "domain" expresses the lower [upper] bound on the iterations
2266 * when inc is positive [negative].
2268 * In particular, we construct the condition (when inc is positive)
2270 * forall i' : (domain(i') and i' <= i) => cond(i')
2272 * which is equivalent to
2274 * not exists i' : domain(i') and i' <= i and not cond(i')
2276 * We construct this set by negating cond, applying a map
2278 * { [i'] -> [i] : domain(i') and i' <= i }
2280 * and then negating the result again.
2282 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
2283 __isl_take isl_set
*domain
, isl_int inc
)
2285 isl_map
*previous_to_this
;
2287 if (isl_int_is_pos(inc
))
2288 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
2290 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
2292 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
2294 cond
= isl_set_complement(cond
);
2295 cond
= isl_set_apply(cond
, previous_to_this
);
2296 cond
= isl_set_complement(cond
);
2301 /* Construct a domain of the form
2303 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2305 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
2306 __isl_take isl_pw_aff
*init
, isl_int inc
)
2312 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
2313 dim
= isl_pw_aff_get_domain_space(init
);
2314 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2315 aff
= isl_aff_add_coefficient(aff
, isl_dim_in
, 0, inc
);
2316 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2318 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2319 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2320 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2321 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2323 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2325 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2327 return isl_set_params(set
);
2330 /* Assuming "cond" represents a bound on a loop where the loop
2331 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2334 * Under the given assumptions, wrapping is only possible if "cond" allows
2335 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2336 * increasing iterator and 0 in case of a decreasing iterator.
2338 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
, isl_int inc
)
2344 test
= isl_set_copy(cond
);
2346 isl_int_init(limit
);
2347 if (isl_int_is_neg(inc
))
2348 isl_int_set_si(limit
, 0);
2350 isl_int_set_si(limit
, 1);
2351 isl_int_mul_2exp(limit
, limit
, get_type_size(iv
));
2352 isl_int_sub_ui(limit
, limit
, 1);
2355 test
= isl_set_fix(cond
, isl_dim_set
, 0, limit
);
2356 cw
= !isl_set_is_empty(test
);
2359 isl_int_clear(limit
);
2364 /* Given a one-dimensional space, construct the following mapping on this
2367 * { [v] -> [v mod 2^width] }
2369 * where width is the number of bits used to represent the values
2370 * of the unsigned variable "iv".
2372 static __isl_give isl_map
*compute_wrapping(__isl_take isl_space
*dim
,
2380 isl_int_set_si(mod
, 1);
2381 isl_int_mul_2exp(mod
, mod
, get_type_size(iv
));
2383 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2384 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2385 aff
= isl_aff_mod(aff
, mod
);
2389 return isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2390 map
= isl_map_reverse(map
);
2393 /* Project out the parameter "id" from "set".
2395 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2396 __isl_keep isl_id
*id
)
2400 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2402 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2407 /* Compute the set of parameters for which "set1" is a subset of "set2".
2409 * set1 is a subset of set2 if
2411 * forall i in set1 : i in set2
2415 * not exists i in set1 and i not in set2
2419 * not exists i in set1 \ set2
2421 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2422 __isl_take isl_set
*set2
)
2424 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2427 /* Compute the set of parameter values for which "cond" holds
2428 * on the next iteration for each element of "dom".
2430 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2431 * and then compute the set of parameters for which the result is a subset
2434 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2435 __isl_take isl_set
*dom
, isl_int inc
)
2441 space
= isl_set_get_space(dom
);
2442 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2443 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2444 aff
= isl_aff_add_constant(aff
, inc
);
2445 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2447 dom
= isl_set_apply(dom
, next
);
2449 return enforce_subset(dom
, cond
);
2452 /* Does "id" refer to a nested access?
2454 static bool is_nested_parameter(__isl_keep isl_id
*id
)
2456 return id
&& isl_id_get_user(id
) && !isl_id_get_name(id
);
2459 /* Does parameter "pos" of "space" refer to a nested access?
2461 static bool is_nested_parameter(__isl_keep isl_space
*space
, int pos
)
2466 id
= isl_space_get_dim_id(space
, isl_dim_param
, pos
);
2467 nested
= is_nested_parameter(id
);
2473 /* Does "space" involve any parameters that refer to nested
2474 * accesses, i.e., parameters with no name?
2476 static bool has_nested(__isl_keep isl_space
*space
)
2480 nparam
= isl_space_dim(space
, isl_dim_param
);
2481 for (int i
= 0; i
< nparam
; ++i
)
2482 if (is_nested_parameter(space
, i
))
2488 /* Does "pa" involve any parameters that refer to nested
2489 * accesses, i.e., parameters with no name?
2491 static bool has_nested(__isl_keep isl_pw_aff
*pa
)
2496 space
= isl_pw_aff_get_space(pa
);
2497 nested
= has_nested(space
);
2498 isl_space_free(space
);
2503 /* Construct a pet_scop for a for statement.
2504 * The for loop is required to be of the form
2506 * for (i = init; condition; ++i)
2510 * for (i = init; condition; --i)
2512 * The initialization of the for loop should either be an assignment
2513 * to an integer variable, or a declaration of such a variable with
2516 * The condition is allowed to contain nested accesses, provided
2517 * they are not being written to inside the body of the loop.
2518 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2519 * essentially treated as a while loop, with iteration domain
2520 * { [i] : i >= init }.
2522 * We extract a pet_scop for the body and then embed it in a loop with
2523 * iteration domain and schedule
2525 * { [i] : i >= init and condition' }
2530 * { [i] : i <= init and condition' }
2533 * Where condition' is equal to condition if the latter is
2534 * a simple upper [lower] bound and a condition that is extended
2535 * to apply to all previous iterations otherwise.
2537 * If the condition is non-affine, then we drop the condition from the
2538 * iteration domain and instead create a separate statement
2539 * for evaluating the condition. The body is then filtered to depend
2540 * on the result of the condition evaluating to true on all iterations
2541 * up to the current iteration, while the evaluation the condition itself
2542 * is filtered to depend on the result of the condition evaluating to true
2543 * on all previous iterations.
2544 * The context of the scop representing the body is dropped
2545 * because we don't know how many times the body will be executed,
2548 * If the stride of the loop is not 1, then "i >= init" is replaced by
2550 * (exists a: i = init + stride * a and a >= 0)
2552 * If the loop iterator i is unsigned, then wrapping may occur.
2553 * During the computation, we work with a virtual iterator that
2554 * does not wrap. However, the condition in the code applies
2555 * to the wrapped value, so we need to change condition(i)
2556 * into condition([i % 2^width]).
2557 * After computing the virtual domain and schedule, we apply
2558 * the function { [v] -> [v % 2^width] } to the domain and the domain
2559 * of the schedule. In order not to lose any information, we also
2560 * need to intersect the domain of the schedule with the virtual domain
2561 * first, since some iterations in the wrapped domain may be scheduled
2562 * several times, typically an infinite number of times.
2563 * Note that there may be no need to perform this final wrapping
2564 * if the loop condition (after wrapping) satisfies certain conditions.
2565 * However, the is_simple_bound condition is not enough since it doesn't
2566 * check if there even is an upper bound.
2568 * If the loop condition is non-affine, then we keep the virtual
2569 * iterator in the iteration domain and instead replace all accesses
2570 * to the original iterator by the wrapping of the virtual iterator.
2572 * Wrapping on unsigned iterators can be avoided entirely if
2573 * loop condition is simple, the loop iterator is incremented
2574 * [decremented] by one and the last value before wrapping cannot
2575 * possibly satisfy the loop condition.
2577 * Before extracting a pet_scop from the body we remove all
2578 * assignments in assigned_value to variables that are assigned
2579 * somewhere in the body of the loop.
2581 * Valid parameters for a for loop are those for which the initial
2582 * value itself, the increment on each domain iteration and
2583 * the condition on both the initial value and
2584 * the result of incrementing the iterator for each iteration of the domain
2586 * If the loop condition is non-affine, then we only consider validity
2587 * of the initial value.
2589 * If the body contains any break, then we keep track of it in "skip"
2590 * (if the skip condition is affine) or it is handled in scop_add_break
2591 * (if the skip condition is not affine).
2592 * Note that the affine break condition needs to be considered with
2593 * respect to previous iterations in the virtual domain (if any)
2594 * and that the domain needs to be kept virtual if there is a non-affine
2597 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2599 BinaryOperator
*ass
;
2607 isl_set
*cond
= NULL
;
2608 isl_set
*skip
= NULL
;
2610 struct pet_scop
*scop
, *scop_cond
= NULL
;
2611 assigned_value_cache
cache(assigned_value
);
2617 bool keep_virtual
= false;
2618 bool has_affine_break
;
2620 isl_map
*wrap
= NULL
;
2621 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2622 isl_set
*valid_init
;
2623 isl_set
*valid_cond
;
2624 isl_set
*valid_cond_init
;
2625 isl_set
*valid_cond_next
;
2627 isl_map
*test_access
= NULL
, *break_access
= NULL
;
2630 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2631 return extract_infinite_for(stmt
);
2633 init
= stmt
->getInit();
2638 if ((ass
= initialization_assignment(init
)) != NULL
) {
2639 iv
= extract_induction_variable(ass
);
2642 lhs
= ass
->getLHS();
2643 rhs
= ass
->getRHS();
2644 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2645 VarDecl
*var
= extract_induction_variable(init
, decl
);
2649 rhs
= var
->getInit();
2650 lhs
= create_DeclRefExpr(var
);
2652 unsupported(stmt
->getInit());
2656 pa_inc
= extract_increment(stmt
, iv
);
2661 if (isl_pw_aff_n_piece(pa_inc
) != 1 ||
2662 isl_pw_aff_foreach_piece(pa_inc
, &extract_cst
, &inc
) < 0) {
2663 isl_pw_aff_free(pa_inc
);
2664 unsupported(stmt
->getInc());
2668 valid_inc
= isl_pw_aff_domain(pa_inc
);
2670 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2672 assigned_value
.erase(iv
);
2673 clear_assignments
clear(assigned_value
);
2674 clear
.TraverseStmt(stmt
->getBody());
2676 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
2678 pa
= try_extract_nested_condition(stmt
->getCond());
2679 if (allow_nested
&& (!pa
|| has_nested(pa
)))
2682 scop
= extract(stmt
->getBody());
2684 has_affine_break
= scop
&&
2685 pet_scop_has_affine_skip(scop
, pet_skip_later
);
2686 if (has_affine_break
) {
2687 skip
= pet_scop_get_skip(scop
, pet_skip_later
);
2688 skip
= isl_set_fix_si(skip
, isl_dim_set
, 0, 1);
2689 skip
= isl_set_params(skip
);
2691 has_var_break
= scop
&& pet_scop_has_var_skip(scop
, pet_skip_later
);
2692 if (has_var_break
) {
2693 break_access
= pet_scop_get_skip_map(scop
, pet_skip_later
);
2694 keep_virtual
= true;
2697 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2698 isl_pw_aff_free(pa
);
2702 if (!allow_nested
&& !pa
)
2703 pa
= try_extract_affine_condition(stmt
->getCond());
2704 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2705 cond
= isl_pw_aff_non_zero_set(pa
);
2706 if (allow_nested
&& !cond
) {
2707 int save_n_stmt
= n_stmt
;
2708 test_access
= create_test_access(ctx
, n_test
++);
2710 scop_cond
= extract_non_affine_condition(stmt
->getCond(),
2711 isl_map_copy(test_access
));
2712 n_stmt
= save_n_stmt
;
2713 scop_cond
= scop_add_array(scop_cond
, test_access
, ast_context
);
2714 scop_cond
= pet_scop_prefix(scop_cond
, 0);
2715 scop
= pet_scop_reset_context(scop
);
2716 scop
= pet_scop_prefix(scop
, 1);
2717 keep_virtual
= true;
2718 cond
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2721 cond
= embed(cond
, isl_id_copy(id
));
2722 skip
= embed(skip
, isl_id_copy(id
));
2723 valid_cond
= isl_set_coalesce(valid_cond
);
2724 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
2725 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
2726 is_one
= isl_int_is_one(inc
) || isl_int_is_negone(inc
);
2727 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2729 init_val
= extract_affine(rhs
);
2730 valid_cond_init
= enforce_subset(
2731 isl_set_from_pw_aff(isl_pw_aff_copy(init_val
)),
2732 isl_set_copy(valid_cond
));
2733 if (is_one
&& !is_virtual
) {
2734 isl_pw_aff_free(init_val
);
2735 pa
= extract_comparison(isl_int_is_pos(inc
) ? BO_GE
: BO_LE
,
2737 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2738 valid_init
= set_project_out_by_id(valid_init
, id
);
2739 domain
= isl_pw_aff_non_zero_set(pa
);
2741 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
2742 domain
= strided_domain(isl_id_copy(id
), init_val
, inc
);
2745 domain
= embed(domain
, isl_id_copy(id
));
2748 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2749 rev_wrap
= isl_map_reverse(isl_map_copy(wrap
));
2750 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
2751 skip
= isl_set_apply(skip
, isl_map_copy(rev_wrap
));
2752 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
2753 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
2755 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2756 is_simple
= is_simple_bound(cond
, inc
);
2758 cond
= valid_for_each_iteration(cond
,
2759 isl_set_copy(domain
), inc
);
2760 domain
= isl_set_intersect(domain
, cond
);
2761 if (has_affine_break
) {
2762 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2763 skip
= after(skip
, isl_int_sgn(inc
));
2764 domain
= isl_set_subtract(domain
, skip
);
2766 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2767 space
= isl_space_from_domain(isl_set_get_space(domain
));
2768 space
= isl_space_add_dims(space
, isl_dim_out
, 1);
2769 sched
= isl_map_universe(space
);
2770 if (isl_int_is_pos(inc
))
2771 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2773 sched
= isl_map_oppose(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2775 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
), inc
);
2776 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
2778 if (is_virtual
&& !keep_virtual
) {
2779 wrap
= isl_map_set_dim_id(wrap
,
2780 isl_dim_out
, 0, isl_id_copy(id
));
2781 sched
= isl_map_intersect_domain(sched
, isl_set_copy(domain
));
2782 domain
= isl_set_apply(domain
, isl_map_copy(wrap
));
2783 sched
= isl_map_apply_domain(sched
, wrap
);
2785 if (!(is_virtual
&& keep_virtual
)) {
2786 space
= isl_set_get_space(domain
);
2787 wrap
= isl_map_identity(isl_space_map_from_set(space
));
2790 scop_cond
= pet_scop_embed(scop_cond
, isl_set_copy(domain
),
2791 isl_map_copy(sched
), isl_map_copy(wrap
), isl_id_copy(id
));
2792 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), sched
, wrap
, id
);
2793 scop
= resolve_nested(scop
);
2795 scop
= scop_add_break(scop
, break_access
, isl_set_copy(domain
),
2798 scop
= scop_add_while(scop_cond
, scop
, test_access
, domain
,
2800 isl_set_free(valid_inc
);
2802 scop
= pet_scop_restrict_context(scop
, valid_inc
);
2803 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
2804 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
2805 isl_set_free(domain
);
2807 clear_assignment(assigned_value
, iv
);
2811 scop
= pet_scop_restrict_context(scop
, valid_init
);
2816 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
)
2818 return extract(stmt
->children());
2821 /* Does parameter "pos" of "map" refer to a nested access?
2823 static bool is_nested_parameter(__isl_keep isl_map
*map
, int pos
)
2828 id
= isl_map_get_dim_id(map
, isl_dim_param
, pos
);
2829 nested
= is_nested_parameter(id
);
2835 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2837 static int n_nested_parameter(__isl_keep isl_space
*space
)
2842 nparam
= isl_space_dim(space
, isl_dim_param
);
2843 for (int i
= 0; i
< nparam
; ++i
)
2844 if (is_nested_parameter(space
, i
))
2850 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2852 static int n_nested_parameter(__isl_keep isl_map
*map
)
2857 space
= isl_map_get_space(map
);
2858 n
= n_nested_parameter(space
);
2859 isl_space_free(space
);
2864 /* For each nested access parameter in "space",
2865 * construct a corresponding pet_expr, place it in args and
2866 * record its position in "param2pos".
2867 * "n_arg" is the number of elements that are already in args.
2868 * The position recorded in "param2pos" takes this number into account.
2869 * If the pet_expr corresponding to a parameter is identical to
2870 * the pet_expr corresponding to an earlier parameter, then these two
2871 * parameters are made to refer to the same element in args.
2873 * Return the final number of elements in args or -1 if an error has occurred.
2875 int PetScan::extract_nested(__isl_keep isl_space
*space
,
2876 int n_arg
, struct pet_expr
**args
, std::map
<int,int> ¶m2pos
)
2880 nparam
= isl_space_dim(space
, isl_dim_param
);
2881 for (int i
= 0; i
< nparam
; ++i
) {
2883 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2886 if (!is_nested_parameter(id
)) {
2891 nested
= (Expr
*) isl_id_get_user(id
);
2892 args
[n_arg
] = extract_expr(nested
);
2896 for (j
= 0; j
< n_arg
; ++j
)
2897 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
2901 pet_expr_free(args
[n_arg
]);
2905 param2pos
[i
] = n_arg
++;
2913 /* For each nested access parameter in the access relations in "expr",
2914 * construct a corresponding pet_expr, place it in expr->args and
2915 * record its position in "param2pos".
2916 * n is the number of nested access parameters.
2918 struct pet_expr
*PetScan::extract_nested(struct pet_expr
*expr
, int n
,
2919 std::map
<int,int> ¶m2pos
)
2923 expr
->args
= isl_calloc_array(ctx
, struct pet_expr
*, n
);
2928 space
= isl_map_get_space(expr
->acc
.access
);
2929 n
= extract_nested(space
, 0, expr
->args
, param2pos
);
2930 isl_space_free(space
);
2938 pet_expr_free(expr
);
2942 /* Look for parameters in any access relation in "expr" that
2943 * refer to nested accesses. In particular, these are
2944 * parameters with no name.
2946 * If there are any such parameters, then the domain of the access
2947 * relation, which is still [] at this point, is replaced by
2948 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2949 * (after identifying identical nested accesses).
2950 * The parameters are then equated to the corresponding t dimensions
2951 * and subsequently projected out.
2952 * param2pos maps the position of the parameter to the position
2953 * of the corresponding t dimension.
2955 struct pet_expr
*PetScan::resolve_nested(struct pet_expr
*expr
)
2962 std::map
<int,int> param2pos
;
2967 for (int i
= 0; i
< expr
->n_arg
; ++i
) {
2968 expr
->args
[i
] = resolve_nested(expr
->args
[i
]);
2969 if (!expr
->args
[i
]) {
2970 pet_expr_free(expr
);
2975 if (expr
->type
!= pet_expr_access
)
2978 n
= n_nested_parameter(expr
->acc
.access
);
2982 expr
= extract_nested(expr
, n
, param2pos
);
2987 nparam
= isl_map_dim(expr
->acc
.access
, isl_dim_param
);
2988 n_in
= isl_map_dim(expr
->acc
.access
, isl_dim_in
);
2989 dim
= isl_map_get_space(expr
->acc
.access
);
2990 dim
= isl_space_domain(dim
);
2991 dim
= isl_space_from_domain(dim
);
2992 dim
= isl_space_add_dims(dim
, isl_dim_out
, n
);
2993 map
= isl_map_universe(dim
);
2994 map
= isl_map_domain_map(map
);
2995 map
= isl_map_reverse(map
);
2996 expr
->acc
.access
= isl_map_apply_domain(expr
->acc
.access
, map
);
2998 for (int i
= nparam
- 1; i
>= 0; --i
) {
2999 isl_id
*id
= isl_map_get_dim_id(expr
->acc
.access
,
3001 if (!is_nested_parameter(id
)) {
3006 expr
->acc
.access
= isl_map_equate(expr
->acc
.access
,
3007 isl_dim_param
, i
, isl_dim_in
,
3008 n_in
+ param2pos
[i
]);
3009 expr
->acc
.access
= isl_map_project_out(expr
->acc
.access
,
3010 isl_dim_param
, i
, 1);
3017 pet_expr_free(expr
);
3021 /* Convert a top-level pet_expr to a pet_scop with one statement.
3022 * This mainly involves resolving nested expression parameters
3023 * and setting the name of the iteration space.
3024 * The name is given by "label" if it is non-NULL. Otherwise,
3025 * it is of the form S_<n_stmt>.
3027 struct pet_scop
*PetScan::extract(Stmt
*stmt
, struct pet_expr
*expr
,
3028 __isl_take isl_id
*label
)
3030 struct pet_stmt
*ps
;
3031 SourceLocation loc
= stmt
->getLocStart();
3032 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3034 expr
= resolve_nested(expr
);
3035 ps
= pet_stmt_from_pet_expr(ctx
, line
, label
, n_stmt
++, expr
);
3036 return pet_scop_from_pet_stmt(ctx
, ps
);
3039 /* Check if we can extract an affine expression from "expr".
3040 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3041 * We turn on autodetection so that we won't generate any warnings
3042 * and turn off nesting, so that we won't accept any non-affine constructs.
3044 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
3047 int save_autodetect
= options
->autodetect
;
3048 bool save_nesting
= nesting_enabled
;
3050 options
->autodetect
= 1;
3051 nesting_enabled
= false;
3053 pwaff
= extract_affine(expr
);
3055 options
->autodetect
= save_autodetect
;
3056 nesting_enabled
= save_nesting
;
3061 /* Check whether "expr" is an affine expression.
3063 bool PetScan::is_affine(Expr
*expr
)
3067 pwaff
= try_extract_affine(expr
);
3068 isl_pw_aff_free(pwaff
);
3070 return pwaff
!= NULL
;
3073 /* Check if we can extract an affine constraint from "expr".
3074 * Return the constraint as an isl_set if we can and NULL otherwise.
3075 * We turn on autodetection so that we won't generate any warnings
3076 * and turn off nesting, so that we won't accept any non-affine constructs.
3078 __isl_give isl_pw_aff
*PetScan::try_extract_affine_condition(Expr
*expr
)
3081 int save_autodetect
= options
->autodetect
;
3082 bool save_nesting
= nesting_enabled
;
3084 options
->autodetect
= 1;
3085 nesting_enabled
= false;
3087 cond
= extract_condition(expr
);
3089 options
->autodetect
= save_autodetect
;
3090 nesting_enabled
= save_nesting
;
3095 /* Check whether "expr" is an affine constraint.
3097 bool PetScan::is_affine_condition(Expr
*expr
)
3101 cond
= try_extract_affine_condition(expr
);
3102 isl_pw_aff_free(cond
);
3104 return cond
!= NULL
;
3107 /* Check if we can extract a condition from "expr".
3108 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3109 * If allow_nested is set, then the condition may involve parameters
3110 * corresponding to nested accesses.
3111 * We turn on autodetection so that we won't generate any warnings.
3113 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
3116 int save_autodetect
= options
->autodetect
;
3117 bool save_nesting
= nesting_enabled
;
3119 options
->autodetect
= 1;
3120 nesting_enabled
= allow_nested
;
3121 cond
= extract_condition(expr
);
3123 options
->autodetect
= save_autodetect
;
3124 nesting_enabled
= save_nesting
;
3129 /* If the top-level expression of "stmt" is an assignment, then
3130 * return that assignment as a BinaryOperator.
3131 * Otherwise return NULL.
3133 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
3135 BinaryOperator
*ass
;
3139 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
3142 ass
= cast
<BinaryOperator
>(stmt
);
3143 if(ass
->getOpcode() != BO_Assign
)
3149 /* Check if the given if statement is a conditional assignement
3150 * with a non-affine condition. If so, construct a pet_scop
3151 * corresponding to this conditional assignment. Otherwise return NULL.
3153 * In particular we check if "stmt" is of the form
3160 * where a is some array or scalar access.
3161 * The constructed pet_scop then corresponds to the expression
3163 * a = condition ? f(...) : g(...)
3165 * All access relations in f(...) are intersected with condition
3166 * while all access relation in g(...) are intersected with the complement.
3168 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
3170 BinaryOperator
*ass_then
, *ass_else
;
3171 isl_map
*write_then
, *write_else
;
3172 isl_set
*cond
, *comp
;
3176 struct pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
3177 bool save_nesting
= nesting_enabled
;
3179 if (!options
->detect_conditional_assignment
)
3182 ass_then
= top_assignment_or_null(stmt
->getThen());
3183 ass_else
= top_assignment_or_null(stmt
->getElse());
3185 if (!ass_then
|| !ass_else
)
3188 if (is_affine_condition(stmt
->getCond()))
3191 write_then
= extract_access(ass_then
->getLHS());
3192 write_else
= extract_access(ass_else
->getLHS());
3194 equal
= isl_map_is_equal(write_then
, write_else
);
3195 isl_map_free(write_else
);
3196 if (equal
< 0 || !equal
) {
3197 isl_map_free(write_then
);
3201 nesting_enabled
= allow_nested
;
3202 pa
= extract_condition(stmt
->getCond());
3203 nesting_enabled
= save_nesting
;
3204 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
3205 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
3206 map
= isl_map_from_range(isl_set_from_pw_aff(pa
));
3208 pe_cond
= pet_expr_from_access(map
);
3210 pe_then
= extract_expr(ass_then
->getRHS());
3211 pe_then
= pet_expr_restrict(pe_then
, cond
);
3212 pe_else
= extract_expr(ass_else
->getRHS());
3213 pe_else
= pet_expr_restrict(pe_else
, comp
);
3215 pe
= pet_expr_new_ternary(ctx
, pe_cond
, pe_then
, pe_else
);
3216 pe_write
= pet_expr_from_access(write_then
);
3218 pe_write
->acc
.write
= 1;
3219 pe_write
->acc
.read
= 0;
3221 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, pe_write
, pe
);
3222 return extract(stmt
, pe
);
3225 /* Create a pet_scop with a single statement evaluating "cond"
3226 * and writing the result to a virtual scalar, as expressed by
3229 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
,
3230 __isl_take isl_map
*access
)
3232 struct pet_expr
*expr
, *write
;
3233 struct pet_stmt
*ps
;
3234 struct pet_scop
*scop
;
3235 SourceLocation loc
= cond
->getLocStart();
3236 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3238 write
= pet_expr_from_access(access
);
3240 write
->acc
.write
= 1;
3241 write
->acc
.read
= 0;
3243 expr
= extract_expr(cond
);
3244 expr
= resolve_nested(expr
);
3245 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, write
, expr
);
3246 ps
= pet_stmt_from_pet_expr(ctx
, line
, NULL
, n_stmt
++, expr
);
3247 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3248 scop
= resolve_nested(scop
);
3254 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
,
3258 /* Apply the map pointed to by "user" to the domain of the access
3259 * relation, thereby embedding it in the range of the map.
3260 * The domain of both relations is the zero-dimensional domain.
3262 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
, void *user
)
3264 isl_map
*map
= (isl_map
*) user
;
3266 return isl_map_apply_domain(access
, isl_map_copy(map
));
3269 /* Apply "map" to all access relations in "expr".
3271 static struct pet_expr
*embed(struct pet_expr
*expr
, __isl_keep isl_map
*map
)
3273 return pet_expr_foreach_access(expr
, &embed_access
, map
);
3276 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3278 static int n_nested_parameter(__isl_keep isl_set
*set
)
3283 space
= isl_set_get_space(set
);
3284 n
= n_nested_parameter(space
);
3285 isl_space_free(space
);
3290 /* Remove all parameters from "map" that refer to nested accesses.
3292 static __isl_give isl_map
*remove_nested_parameters(__isl_take isl_map
*map
)
3297 space
= isl_map_get_space(map
);
3298 nparam
= isl_space_dim(space
, isl_dim_param
);
3299 for (int i
= nparam
- 1; i
>= 0; --i
)
3300 if (is_nested_parameter(space
, i
))
3301 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3302 isl_space_free(space
);
3308 static __isl_give isl_map
*access_remove_nested_parameters(
3309 __isl_take isl_map
*access
, void *user
);
3312 static __isl_give isl_map
*access_remove_nested_parameters(
3313 __isl_take isl_map
*access
, void *user
)
3315 return remove_nested_parameters(access
);
3318 /* Remove all nested access parameters from the schedule and all
3319 * accesses of "stmt".
3320 * There is no need to remove them from the domain as these parameters
3321 * have already been removed from the domain when this function is called.
3323 static struct pet_stmt
*remove_nested_parameters(struct pet_stmt
*stmt
)
3327 stmt
->schedule
= remove_nested_parameters(stmt
->schedule
);
3328 stmt
->body
= pet_expr_foreach_access(stmt
->body
,
3329 &access_remove_nested_parameters
, NULL
);
3330 if (!stmt
->schedule
|| !stmt
->body
)
3332 for (int i
= 0; i
< stmt
->n_arg
; ++i
) {
3333 stmt
->args
[i
] = pet_expr_foreach_access(stmt
->args
[i
],
3334 &access_remove_nested_parameters
, NULL
);
3341 pet_stmt_free(stmt
);
3345 /* For each nested access parameter in the domain of "stmt",
3346 * construct a corresponding pet_expr, place it before the original
3347 * elements in stmt->args and record its position in "param2pos".
3348 * n is the number of nested access parameters.
3350 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
3351 std::map
<int,int> ¶m2pos
)
3356 struct pet_expr
**args
;
3358 n_arg
= stmt
->n_arg
;
3359 args
= isl_calloc_array(ctx
, struct pet_expr
*, n
+ n_arg
);
3363 space
= isl_set_get_space(stmt
->domain
);
3364 n_arg
= extract_nested(space
, 0, args
, param2pos
);
3365 isl_space_free(space
);
3370 for (i
= 0; i
< stmt
->n_arg
; ++i
)
3371 args
[n_arg
+ i
] = stmt
->args
[i
];
3374 stmt
->n_arg
+= n_arg
;
3379 for (i
= 0; i
< n
; ++i
)
3380 pet_expr_free(args
[i
]);
3383 pet_stmt_free(stmt
);
3387 /* Check whether any of the arguments i of "stmt" starting at position "n"
3388 * is equal to one of the first "n" arguments j.
3389 * If so, combine the constraints on arguments i and j and remove
3392 static struct pet_stmt
*remove_duplicate_arguments(struct pet_stmt
*stmt
, int n
)
3401 if (n
== stmt
->n_arg
)
3404 map
= isl_set_unwrap(stmt
->domain
);
3406 for (i
= stmt
->n_arg
- 1; i
>= n
; --i
) {
3407 for (j
= 0; j
< n
; ++j
)
3408 if (pet_expr_is_equal(stmt
->args
[i
], stmt
->args
[j
]))
3413 map
= isl_map_equate(map
, isl_dim_out
, i
, isl_dim_out
, j
);
3414 map
= isl_map_project_out(map
, isl_dim_out
, i
, 1);
3416 pet_expr_free(stmt
->args
[i
]);
3417 for (j
= i
; j
+ 1 < stmt
->n_arg
; ++j
)
3418 stmt
->args
[j
] = stmt
->args
[j
+ 1];
3422 stmt
->domain
= isl_map_wrap(map
);
3427 pet_stmt_free(stmt
);
3431 /* Look for parameters in the iteration domain of "stmt" that
3432 * refer to nested accesses. In particular, these are
3433 * parameters with no name.
3435 * If there are any such parameters, then as many extra variables
3436 * (after identifying identical nested accesses) are inserted in the
3437 * range of the map wrapped inside the domain, before the original variables.
3438 * If the original domain is not a wrapped map, then a new wrapped
3439 * map is created with zero output dimensions.
3440 * The parameters are then equated to the corresponding output dimensions
3441 * and subsequently projected out, from the iteration domain,
3442 * the schedule and the access relations.
3443 * For each of the output dimensions, a corresponding argument
3444 * expression is inserted. Initially they are created with
3445 * a zero-dimensional domain, so they have to be embedded
3446 * in the current iteration domain.
3447 * param2pos maps the position of the parameter to the position
3448 * of the corresponding output dimension in the wrapped map.
3450 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3456 std::map
<int,int> param2pos
;
3461 n
= n_nested_parameter(stmt
->domain
);
3465 n_arg
= stmt
->n_arg
;
3466 stmt
= extract_nested(stmt
, n
, param2pos
);
3470 n
= stmt
->n_arg
- n_arg
;
3471 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3472 if (isl_set_is_wrapping(stmt
->domain
))
3473 map
= isl_set_unwrap(stmt
->domain
);
3475 map
= isl_map_from_domain(stmt
->domain
);
3476 map
= isl_map_insert_dims(map
, isl_dim_out
, 0, n
);
3478 for (int i
= nparam
- 1; i
>= 0; --i
) {
3481 if (!is_nested_parameter(map
, i
))
3484 id
= isl_map_get_tuple_id(stmt
->args
[param2pos
[i
]]->acc
.access
,
3486 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3487 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3489 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3492 stmt
->domain
= isl_map_wrap(map
);
3494 map
= isl_set_unwrap(isl_set_copy(stmt
->domain
));
3495 map
= isl_map_from_range(isl_map_domain(map
));
3496 for (int pos
= 0; pos
< n
; ++pos
)
3497 stmt
->args
[pos
] = embed(stmt
->args
[pos
], map
);
3500 stmt
= remove_nested_parameters(stmt
);
3501 stmt
= remove_duplicate_arguments(stmt
, n
);
3505 pet_stmt_free(stmt
);
3509 /* For each statement in "scop", move the parameters that correspond
3510 * to nested access into the ranges of the domains and create
3511 * corresponding argument expressions.
3513 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3518 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3519 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3520 if (!scop
->stmts
[i
])
3526 pet_scop_free(scop
);
3530 /* Given an access expression "expr", is the variable accessed by
3531 * "expr" assigned anywhere inside "scop"?
3533 static bool is_assigned(pet_expr
*expr
, pet_scop
*scop
)
3535 bool assigned
= false;
3538 id
= isl_map_get_tuple_id(expr
->acc
.access
, isl_dim_out
);
3539 assigned
= pet_scop_writes(scop
, id
);
3545 /* Are all nested access parameters in "pa" allowed given "scop".
3546 * In particular, is none of them written by anywhere inside "scop".
3548 * If "scop" has any skip conditions, then no nested access parameters
3549 * are allowed. In particular, if there is any nested access in a guard
3550 * for a piece of code containing a "continue", then we want to introduce
3551 * a separate statement for evaluating this guard so that we can express
3552 * that the result is false for all previous iterations.
3554 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3561 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3562 for (int i
= 0; i
< nparam
; ++i
) {
3564 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3568 if (!is_nested_parameter(id
)) {
3573 if (pet_scop_has_skip(scop
, pet_skip_now
)) {
3578 nested
= (Expr
*) isl_id_get_user(id
);
3579 expr
= extract_expr(nested
);
3580 allowed
= expr
&& expr
->type
== pet_expr_access
&&
3581 !is_assigned(expr
, scop
);
3583 pet_expr_free(expr
);
3593 /* Do we need to construct a skip condition of the given type
3594 * on an if statement, given that the if condition is non-affine?
3596 * pet_scop_filter_skip can only handle the case where the if condition
3597 * holds (the then branch) and the skip condition is universal.
3598 * In any other case, we need to construct a new skip condition.
3600 static bool need_skip(struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3601 bool have_else
, enum pet_skip type
)
3603 if (have_else
&& scop_else
&& pet_scop_has_skip(scop_else
, type
))
3605 if (scop_then
&& pet_scop_has_skip(scop_then
, type
) &&
3606 !pet_scop_has_universal_skip(scop_then
, type
))
3611 /* Do we need to construct a skip condition of the given type
3612 * on an if statement, given that the if condition is affine?
3614 * There is no need to construct a new skip condition if all
3615 * the skip conditions are affine.
3617 static bool need_skip_aff(struct pet_scop
*scop_then
,
3618 struct pet_scop
*scop_else
, bool have_else
, enum pet_skip type
)
3620 if (scop_then
&& pet_scop_has_var_skip(scop_then
, type
))
3622 if (have_else
&& scop_else
&& pet_scop_has_var_skip(scop_else
, type
))
3627 /* Do we need to construct a skip condition of the given type
3628 * on an if statement?
3630 static bool need_skip(struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3631 bool have_else
, enum pet_skip type
, bool affine
)
3634 return need_skip_aff(scop_then
, scop_else
, have_else
, type
);
3636 return need_skip(scop_then
, scop_else
, have_else
, type
);
3639 /* Construct an affine expression pet_expr that is evaluates
3640 * to the constant "val".
3642 static struct pet_expr
*universally(isl_ctx
*ctx
, int val
)
3647 space
= isl_space_alloc(ctx
, 0, 0, 1);
3648 map
= isl_map_universe(space
);
3649 map
= isl_map_fix_si(map
, isl_dim_out
, 0, val
);
3651 return pet_expr_from_access(map
);
3654 /* Construct an affine expression pet_expr that is evaluates
3655 * to the constant 1.
3657 static struct pet_expr
*universally_true(isl_ctx
*ctx
)
3659 return universally(ctx
, 1);
3662 /* Construct an affine expression pet_expr that is evaluates
3663 * to the constant 0.
3665 static struct pet_expr
*universally_false(isl_ctx
*ctx
)
3667 return universally(ctx
, 0);
3670 /* Given an access relation "test_access" for the if condition,
3671 * an access relation "skip_access" for the skip condition and
3672 * scops for the then and else branches, construct a scop for
3673 * computing "skip_access".
3675 * The computed scop contains a single statement that essentially does
3677 * skip_cond = test_cond ? skip_cond_then : skip_cond_else
3679 * If the skip conditions of the then and/or else branch are not affine,
3680 * then they need to be filtered by test_access.
3681 * If they are missing, then this means the skip condition is false.
3683 * Since we are constructing a skip condition for the if statement,
3684 * the skip conditions on the then and else branches are removed.
3686 static struct pet_scop
*extract_skip(PetScan
*scan
,
3687 __isl_take isl_map
*test_access
, __isl_take isl_map
*skip_access
,
3688 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
, bool have_else
,
3691 struct pet_expr
*expr_then
, *expr_else
, *expr
, *expr_skip
;
3692 struct pet_stmt
*stmt
;
3693 struct pet_scop
*scop
;
3694 isl_ctx
*ctx
= scan
->ctx
;
3698 if (have_else
&& !scop_else
)
3701 if (pet_scop_has_skip(scop_then
, type
)) {
3702 expr_then
= pet_scop_get_skip_expr(scop_then
, type
);
3703 pet_scop_reset_skip(scop_then
, type
);
3704 if (!pet_expr_is_affine(expr_then
))
3705 expr_then
= pet_expr_filter(expr_then
,
3706 isl_map_copy(test_access
), 1);
3708 expr_then
= universally_false(ctx
);
3710 if (have_else
&& pet_scop_has_skip(scop_else
, type
)) {
3711 expr_else
= pet_scop_get_skip_expr(scop_else
, type
);
3712 pet_scop_reset_skip(scop_else
, type
);
3713 if (!pet_expr_is_affine(expr_else
))
3714 expr_else
= pet_expr_filter(expr_else
,
3715 isl_map_copy(test_access
), 0);
3717 expr_else
= universally_false(ctx
);
3719 expr
= pet_expr_from_access(test_access
);
3720 expr
= pet_expr_new_ternary(ctx
, expr
, expr_then
, expr_else
);
3721 expr_skip
= pet_expr_from_access(isl_map_copy(skip_access
));
3723 expr_skip
->acc
.write
= 1;
3724 expr_skip
->acc
.read
= 0;
3726 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, expr_skip
, expr
);
3727 stmt
= pet_stmt_from_pet_expr(ctx
, -1, NULL
, scan
->n_stmt
++, expr
);
3729 scop
= pet_scop_from_pet_stmt(ctx
, stmt
);
3730 scop
= scop_add_array(scop
, skip_access
, scan
->ast_context
);
3731 isl_map_free(skip_access
);
3735 isl_map_free(test_access
);
3736 isl_map_free(skip_access
);
3740 /* Is scop's skip_now condition equal to its skip_later condition?
3741 * In particular, this means that it either has no skip_now condition
3742 * or both a skip_now and a skip_later condition (that are equal to each other).
3744 static bool skip_equals_skip_later(struct pet_scop
*scop
)
3746 int has_skip_now
, has_skip_later
;
3748 isl_set
*skip_now
, *skip_later
;
3752 has_skip_now
= pet_scop_has_skip(scop
, pet_skip_now
);
3753 has_skip_later
= pet_scop_has_skip(scop
, pet_skip_later
);
3754 if (has_skip_now
!= has_skip_later
)
3759 skip_now
= pet_scop_get_skip(scop
, pet_skip_now
);
3760 skip_later
= pet_scop_get_skip(scop
, pet_skip_later
);
3761 equal
= isl_set_is_equal(skip_now
, skip_later
);
3762 isl_set_free(skip_now
);
3763 isl_set_free(skip_later
);
3768 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
3770 static void drop_skip_later(struct pet_scop
*scop1
, struct pet_scop
*scop2
)
3772 pet_scop_reset_skip(scop1
, pet_skip_later
);
3773 pet_scop_reset_skip(scop2
, pet_skip_later
);
3776 /* Structure that handles the construction of skip conditions.
3778 * scop_then and scop_else represent the then and else branches
3779 * of the if statement
3781 * skip[type] is true if we need to construct a skip condition of that type
3782 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
3783 * are equal to each other
3784 * access[type] is the virtual array representing the skip condition
3785 * scop[type] is a scop for computing the skip condition
3787 struct pet_skip_info
{
3793 struct pet_scop
*scop
[2];
3795 pet_skip_info(isl_ctx
*ctx
) : ctx(ctx
) {}
3797 operator bool() { return skip
[pet_skip_now
] || skip
[pet_skip_later
]; }
3800 /* Structure that handles the construction of skip conditions on if statements.
3802 * scop_then and scop_else represent the then and else branches
3803 * of the if statement
3805 struct pet_skip_info_if
: public pet_skip_info
{
3806 struct pet_scop
*scop_then
, *scop_else
;
3809 pet_skip_info_if(isl_ctx
*ctx
, struct pet_scop
*scop_then
,
3810 struct pet_scop
*scop_else
, bool have_else
, bool affine
);
3811 void extract(PetScan
*scan
, __isl_keep isl_map
*access
,
3812 enum pet_skip type
);
3813 void extract(PetScan
*scan
, __isl_keep isl_map
*access
);
3814 void extract(PetScan
*scan
, __isl_keep isl_pw_aff
*cond
);
3815 struct pet_scop
*add(struct pet_scop
*scop
, enum pet_skip type
,
3817 struct pet_scop
*add(struct pet_scop
*scop
, int offset
);
3820 /* Initialize a pet_skip_info_if structure based on the then and else branches
3821 * and based on whether the if condition is affine or not.
3823 pet_skip_info_if::pet_skip_info_if(isl_ctx
*ctx
, struct pet_scop
*scop_then
,
3824 struct pet_scop
*scop_else
, bool have_else
, bool affine
) :
3825 pet_skip_info(ctx
), scop_then(scop_then
), scop_else(scop_else
),
3826 have_else(have_else
)
3828 skip
[pet_skip_now
] =
3829 need_skip(scop_then
, scop_else
, have_else
, pet_skip_now
, affine
);
3830 equal
= skip
[pet_skip_now
] && skip_equals_skip_later(scop_then
) &&
3831 (!have_else
|| skip_equals_skip_later(scop_else
));
3832 skip
[pet_skip_later
] = skip
[pet_skip_now
] && !equal
&&
3833 need_skip(scop_then
, scop_else
, have_else
, pet_skip_later
, affine
);
3836 /* If we need to construct a skip condition of the given type,
3839 * "map" represents the if condition.
3841 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_map
*map
,
3847 access
[type
] = create_test_access(isl_map_get_ctx(map
), scan
->n_test
++);
3848 scop
[type
] = extract_skip(scan
, isl_map_copy(map
),
3849 isl_map_copy(access
[type
]),
3850 scop_then
, scop_else
, have_else
, type
);
3853 /* Construct the required skip conditions, given the if condition "map".
3855 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_map
*map
)
3857 extract(scan
, map
, pet_skip_now
);
3858 extract(scan
, map
, pet_skip_later
);
3860 drop_skip_later(scop_then
, scop_else
);
3863 /* Construct the required skip conditions, given the if condition "cond".
3865 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_pw_aff
*cond
)
3870 if (!skip
[pet_skip_now
] && !skip
[pet_skip_later
])
3873 test_set
= isl_set_from_pw_aff(isl_pw_aff_copy(cond
));
3874 test
= isl_map_from_range(test_set
);
3875 extract(scan
, test
);
3879 /* Add the computed skip condition of the give type to "main" and
3880 * add the scop for computing the condition at the given offset.
3882 * If equal is set, then we only computed a skip condition for pet_skip_now,
3883 * but we also need to set it as main's pet_skip_later.
3885 struct pet_scop
*pet_skip_info_if::add(struct pet_scop
*main
,
3886 enum pet_skip type
, int offset
)
3893 skip_set
= isl_map_range(access
[type
]);
3894 access
[type
] = NULL
;
3895 scop
[type
] = pet_scop_prefix(scop
[type
], offset
);
3896 main
= pet_scop_add_par(ctx
, main
, scop
[type
]);
3900 main
= pet_scop_set_skip(main
, pet_skip_later
,
3901 isl_set_copy(skip_set
));
3903 main
= pet_scop_set_skip(main
, type
, skip_set
);
3908 /* Add the computed skip conditions to "main" and
3909 * add the scops for computing the conditions at the given offset.
3911 struct pet_scop
*pet_skip_info_if::add(struct pet_scop
*scop
, int offset
)
3913 scop
= add(scop
, pet_skip_now
, offset
);
3914 scop
= add(scop
, pet_skip_later
, offset
);
3919 /* Construct a pet_scop for a non-affine if statement.
3921 * We create a separate statement that writes the result
3922 * of the non-affine condition to a virtual scalar.
3923 * A constraint requiring the value of this virtual scalar to be one
3924 * is added to the iteration domains of the then branch.
3925 * Similarly, a constraint requiring the value of this virtual scalar
3926 * to be zero is added to the iteration domains of the else branch, if any.
3927 * We adjust the schedules to ensure that the virtual scalar is written
3928 * before it is read.
3930 * If there are any breaks or continues in the then and/or else
3931 * branches, then we may have to compute a new skip condition.
3932 * This is handled using a pet_skip_info_if object.
3933 * On initialization, the object checks if skip conditions need
3934 * to be computed. If so, it does so in "extract" and adds them in "add".
3936 struct pet_scop
*PetScan::extract_non_affine_if(Expr
*cond
,
3937 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3938 bool have_else
, int stmt_id
)
3940 struct pet_scop
*scop
;
3941 isl_map
*test_access
;
3942 int save_n_stmt
= n_stmt
;
3944 test_access
= create_test_access(ctx
, n_test
++);
3946 scop
= extract_non_affine_condition(cond
, isl_map_copy(test_access
));
3947 n_stmt
= save_n_stmt
;
3948 scop
= scop_add_array(scop
, test_access
, ast_context
);
3950 pet_skip_info_if
skip(ctx
, scop_then
, scop_else
, have_else
, false);
3951 skip
.extract(this, test_access
);
3953 scop
= pet_scop_prefix(scop
, 0);
3954 scop_then
= pet_scop_prefix(scop_then
, 1);
3955 scop_then
= pet_scop_filter(scop_then
, isl_map_copy(test_access
), 1);
3957 scop_else
= pet_scop_prefix(scop_else
, 1);
3958 scop_else
= pet_scop_filter(scop_else
, test_access
, 0);
3959 scop_then
= pet_scop_add_par(ctx
, scop_then
, scop_else
);
3961 isl_map_free(test_access
);
3963 scop
= pet_scop_add_seq(ctx
, scop
, scop_then
);
3965 scop
= skip
.add(scop
, 2);
3970 /* Construct a pet_scop for an if statement.
3972 * If the condition fits the pattern of a conditional assignment,
3973 * then it is handled by extract_conditional_assignment.
3974 * Otherwise, we do the following.
3976 * If the condition is affine, then the condition is added
3977 * to the iteration domains of the then branch, while the
3978 * opposite of the condition in added to the iteration domains
3979 * of the else branch, if any.
3980 * We allow the condition to be dynamic, i.e., to refer to
3981 * scalars or array elements that may be written to outside
3982 * of the given if statement. These nested accesses are then represented
3983 * as output dimensions in the wrapping iteration domain.
3984 * If it also written _inside_ the then or else branch, then
3985 * we treat the condition as non-affine.
3986 * As explained in extract_non_affine_if, this will introduce
3987 * an extra statement.
3988 * For aesthetic reasons, we want this statement to have a statement
3989 * number that is lower than those of the then and else branches.
3990 * In order to evaluate if will need such a statement, however, we
3991 * first construct scops for the then and else branches.
3992 * We therefore reserve a statement number if we might have to
3993 * introduce such an extra statement.
3995 * If the condition is not affine, then the scop is created in
3996 * extract_non_affine_if.
3998 * If there are any breaks or continues in the then and/or else
3999 * branches, then we may have to compute a new skip condition.
4000 * This is handled using a pet_skip_info_if object.
4001 * On initialization, the object checks if skip conditions need
4002 * to be computed. If so, it does so in "extract" and adds them in "add".
4004 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
4006 struct pet_scop
*scop_then
, *scop_else
= NULL
, *scop
;
4012 scop
= extract_conditional_assignment(stmt
);
4016 cond
= try_extract_nested_condition(stmt
->getCond());
4017 if (allow_nested
&& (!cond
|| has_nested(cond
)))
4021 assigned_value_cache
cache(assigned_value
);
4022 scop_then
= extract(stmt
->getThen());
4025 if (stmt
->getElse()) {
4026 assigned_value_cache
cache(assigned_value
);
4027 scop_else
= extract(stmt
->getElse());
4028 if (options
->autodetect
) {
4029 if (scop_then
&& !scop_else
) {
4031 isl_pw_aff_free(cond
);
4034 if (!scop_then
&& scop_else
) {
4036 isl_pw_aff_free(cond
);
4043 (!is_nested_allowed(cond
, scop_then
) ||
4044 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
4045 isl_pw_aff_free(cond
);
4048 if (allow_nested
&& !cond
)
4049 return extract_non_affine_if(stmt
->getCond(), scop_then
,
4050 scop_else
, stmt
->getElse(), stmt_id
);
4053 cond
= extract_condition(stmt
->getCond());
4055 pet_skip_info_if
skip(ctx
, scop_then
, scop_else
, stmt
->getElse(), true);
4056 skip
.extract(this, cond
);
4058 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
4059 set
= isl_pw_aff_non_zero_set(cond
);
4060 scop
= pet_scop_restrict(scop_then
, isl_set_copy(set
));
4062 if (stmt
->getElse()) {
4063 set
= isl_set_subtract(isl_set_copy(valid
), set
);
4064 scop_else
= pet_scop_restrict(scop_else
, set
);
4065 scop
= pet_scop_add_par(ctx
, scop
, scop_else
);
4068 scop
= resolve_nested(scop
);
4069 scop
= pet_scop_restrict_context(scop
, valid
);
4072 scop
= pet_scop_prefix(scop
, 0);
4073 scop
= skip
.add(scop
, 1);
4078 /* Try and construct a pet_scop for a label statement.
4079 * We currently only allow labels on expression statements.
4081 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
4086 sub
= stmt
->getSubStmt();
4087 if (!isa
<Expr
>(sub
)) {
4092 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
4094 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
4097 /* Construct a pet_scop for a continue statement.
4099 * We simply create an empty scop with a universal pet_skip_now
4100 * skip condition. This skip condition will then be taken into
4101 * account by the enclosing loop construct, possibly after
4102 * being incorporated into outer skip conditions.
4104 struct pet_scop
*PetScan::extract(ContinueStmt
*stmt
)
4110 scop
= pet_scop_empty(ctx
);
4114 space
= isl_space_set_alloc(ctx
, 0, 1);
4115 set
= isl_set_universe(space
);
4116 set
= isl_set_fix_si(set
, isl_dim_set
, 0, 1);
4117 scop
= pet_scop_set_skip(scop
, pet_skip_now
, set
);
4122 /* Construct a pet_scop for a break statement.
4124 * We simply create an empty scop with both a universal pet_skip_now
4125 * skip condition and a universal pet_skip_later skip condition.
4126 * These skip conditions will then be taken into
4127 * account by the enclosing loop construct, possibly after
4128 * being incorporated into outer skip conditions.
4130 struct pet_scop
*PetScan::extract(BreakStmt
*stmt
)
4136 scop
= pet_scop_empty(ctx
);
4140 space
= isl_space_set_alloc(ctx
, 0, 1);
4141 set
= isl_set_universe(space
);
4142 set
= isl_set_fix_si(set
, isl_dim_set
, 0, 1);
4143 scop
= pet_scop_set_skip(scop
, pet_skip_now
, isl_set_copy(set
));
4144 scop
= pet_scop_set_skip(scop
, pet_skip_later
, set
);
4149 /* Try and construct a pet_scop corresponding to "stmt".
4151 struct pet_scop
*PetScan::extract(Stmt
*stmt
)
4153 if (isa
<Expr
>(stmt
))
4154 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
4156 switch (stmt
->getStmtClass()) {
4157 case Stmt::WhileStmtClass
:
4158 return extract(cast
<WhileStmt
>(stmt
));
4159 case Stmt::ForStmtClass
:
4160 return extract_for(cast
<ForStmt
>(stmt
));
4161 case Stmt::IfStmtClass
:
4162 return extract(cast
<IfStmt
>(stmt
));
4163 case Stmt::CompoundStmtClass
:
4164 return extract(cast
<CompoundStmt
>(stmt
));
4165 case Stmt::LabelStmtClass
:
4166 return extract(cast
<LabelStmt
>(stmt
));
4167 case Stmt::ContinueStmtClass
:
4168 return extract(cast
<ContinueStmt
>(stmt
));
4169 case Stmt::BreakStmtClass
:
4170 return extract(cast
<BreakStmt
>(stmt
));
4178 /* Do we need to construct a skip condition of the given type
4179 * on a sequence of statements?
4181 * There is no need to construct a new skip condition if only
4182 * only of the two statements has a skip condition or if both
4183 * of their skip conditions are affine.
4185 * In principle we also don't need a new continuation variable if
4186 * the continuation of scop2 is affine, but then we would need
4187 * to allow more complicated forms of continuations.
4189 static bool need_skip_seq(struct pet_scop
*scop1
, struct pet_scop
*scop2
,
4192 if (!scop1
|| !pet_scop_has_skip(scop1
, type
))
4194 if (!scop2
|| !pet_scop_has_skip(scop2
, type
))
4196 if (pet_scop_has_affine_skip(scop1
, type
) &&
4197 pet_scop_has_affine_skip(scop2
, type
))
4202 /* Construct a scop for computing the skip condition of the given type and
4203 * with access relation "skip_access" for a sequence of two scops "scop1"
4206 * The computed scop contains a single statement that essentially does
4208 * skip_cond = skip_cond_1 ? 1 : skip_cond_2
4210 * or, in other words, skip_cond1 || skip_cond2.
4211 * In this expression, skip_cond_2 is filtered to reflect that it is
4212 * only evaluated when skip_cond_1 is false.
4214 * The skip condition on scop1 is not removed because it still needs
4215 * to be applied to scop2 when these two scops are combined.
4217 static struct pet_scop
*extract_skip_seq(PetScan
*ps
,
4218 __isl_take isl_map
*skip_access
,
4219 struct pet_scop
*scop1
, struct pet_scop
*scop2
, enum pet_skip type
)
4222 struct pet_expr
*expr1
, *expr2
, *expr
, *expr_skip
;
4223 struct pet_stmt
*stmt
;
4224 struct pet_scop
*scop
;
4225 isl_ctx
*ctx
= ps
->ctx
;
4227 if (!scop1
|| !scop2
)
4230 expr1
= pet_scop_get_skip_expr(scop1
, type
);
4231 expr2
= pet_scop_get_skip_expr(scop2
, type
);
4232 pet_scop_reset_skip(scop2
, type
);
4234 expr2
= pet_expr_filter(expr2
, isl_map_copy(expr1
->acc
.access
), 0);
4236 expr
= universally_true(ctx
);
4237 expr
= pet_expr_new_ternary(ctx
, expr1
, expr
, expr2
);
4238 expr_skip
= pet_expr_from_access(isl_map_copy(skip_access
));
4240 expr_skip
->acc
.write
= 1;
4241 expr_skip
->acc
.read
= 0;
4243 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, expr_skip
, expr
);
4244 stmt
= pet_stmt_from_pet_expr(ctx
, -1, NULL
, ps
->n_stmt
++, expr
);
4246 scop
= pet_scop_from_pet_stmt(ctx
, stmt
);
4247 scop
= scop_add_array(scop
, skip_access
, ps
->ast_context
);
4248 isl_map_free(skip_access
);
4252 isl_map_free(skip_access
);
4256 /* Structure that handles the construction of skip conditions
4257 * on sequences of statements.
4259 * scop1 and scop2 represent the two statements that are combined
4261 struct pet_skip_info_seq
: public pet_skip_info
{
4262 struct pet_scop
*scop1
, *scop2
;
4264 pet_skip_info_seq(isl_ctx
*ctx
, struct pet_scop
*scop1
,
4265 struct pet_scop
*scop2
);
4266 void extract(PetScan
*scan
, enum pet_skip type
);
4267 void extract(PetScan
*scan
);
4268 struct pet_scop
*add(struct pet_scop
*scop
, enum pet_skip type
,
4270 struct pet_scop
*add(struct pet_scop
*scop
, int offset
);
4273 /* Initialize a pet_skip_info_seq structure based on
4274 * on the two statements that are going to be combined.
4276 pet_skip_info_seq::pet_skip_info_seq(isl_ctx
*ctx
, struct pet_scop
*scop1
,
4277 struct pet_scop
*scop2
) : pet_skip_info(ctx
), scop1(scop1
), scop2(scop2
)
4279 skip
[pet_skip_now
] = need_skip_seq(scop1
, scop2
, pet_skip_now
);
4280 equal
= skip
[pet_skip_now
] && skip_equals_skip_later(scop1
) &&
4281 skip_equals_skip_later(scop2
);
4282 skip
[pet_skip_later
] = skip
[pet_skip_now
] && !equal
&&
4283 need_skip_seq(scop1
, scop2
, pet_skip_later
);
4286 /* If we need to construct a skip condition of the given type,
4289 void pet_skip_info_seq::extract(PetScan
*scan
, enum pet_skip type
)
4294 access
[type
] = create_test_access(ctx
, scan
->n_test
++);
4295 scop
[type
] = extract_skip_seq(scan
, isl_map_copy(access
[type
]),
4296 scop1
, scop2
, type
);
4299 /* Construct the required skip conditions.
4301 void pet_skip_info_seq::extract(PetScan
*scan
)
4303 extract(scan
, pet_skip_now
);
4304 extract(scan
, pet_skip_later
);
4306 drop_skip_later(scop1
, scop2
);
4309 /* Add the computed skip condition of the give type to "main" and
4310 * add the scop for computing the condition at the given offset (the statement
4311 * number). Within this offset, the condition is computed at position 1
4312 * to ensure that it is computed after the corresponding statement.
4314 * If equal is set, then we only computed a skip condition for pet_skip_now,
4315 * but we also need to set it as main's pet_skip_later.
4317 struct pet_scop
*pet_skip_info_seq::add(struct pet_scop
*main
,
4318 enum pet_skip type
, int offset
)
4325 skip_set
= isl_map_range(access
[type
]);
4326 access
[type
] = NULL
;
4327 scop
[type
] = pet_scop_prefix(scop
[type
], 1);
4328 scop
[type
] = pet_scop_prefix(scop
[type
], offset
);
4329 main
= pet_scop_add_par(ctx
, main
, scop
[type
]);
4333 main
= pet_scop_set_skip(main
, pet_skip_later
,
4334 isl_set_copy(skip_set
));
4336 main
= pet_scop_set_skip(main
, type
, skip_set
);
4341 /* Add the computed skip conditions to "main" and
4342 * add the scops for computing the conditions at the given offset.
4344 struct pet_scop
*pet_skip_info_seq::add(struct pet_scop
*scop
, int offset
)
4346 scop
= add(scop
, pet_skip_now
, offset
);
4347 scop
= add(scop
, pet_skip_later
, offset
);
4352 /* Try and construct a pet_scop corresponding to (part of)
4353 * a sequence of statements.
4355 * If there are any breaks or continues in the individual statements,
4356 * then we may have to compute a new skip condition.
4357 * This is handled using a pet_skip_info_seq object.
4358 * On initialization, the object checks if skip conditions need
4359 * to be computed. If so, it does so in "extract" and adds them in "add".
4361 struct pet_scop
*PetScan::extract(StmtRange stmt_range
)
4366 bool partial_range
= false;
4368 scop
= pet_scop_empty(ctx
);
4369 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
4371 struct pet_scop
*scop_i
;
4373 scop_i
= extract(child
);
4374 if (scop
&& partial
) {
4375 pet_scop_free(scop_i
);
4378 pet_skip_info_seq
skip(ctx
, scop
, scop_i
);
4381 scop_i
= pet_scop_prefix(scop_i
, 0);
4382 scop_i
= pet_scop_prefix(scop_i
, j
);
4383 if (options
->autodetect
) {
4385 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4387 partial_range
= true;
4388 if (scop
->n_stmt
!= 0 && !scop_i
)
4391 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4394 scop
= skip
.add(scop
, j
);
4400 if (scop
&& partial_range
)
4406 /* Check if the scop marked by the user is exactly this Stmt
4407 * or part of this Stmt.
4408 * If so, return a pet_scop corresponding to the marked region.
4409 * Otherwise, return NULL.
4411 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
4413 SourceManager
&SM
= PP
.getSourceManager();
4414 unsigned start_off
, end_off
;
4416 start_off
= SM
.getFileOffset(stmt
->getLocStart());
4417 end_off
= SM
.getFileOffset(stmt
->getLocEnd());
4419 if (start_off
> loc
.end
)
4421 if (end_off
< loc
.start
)
4423 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
4424 return extract(stmt
);
4428 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
4429 Stmt
*child
= *start
;
4432 start_off
= SM
.getFileOffset(child
->getLocStart());
4433 end_off
= SM
.getFileOffset(child
->getLocEnd());
4434 if (start_off
< loc
.start
&& end_off
> loc
.end
)
4436 if (start_off
>= loc
.start
)
4441 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
4443 start_off
= SM
.getFileOffset(child
->getLocStart());
4444 if (start_off
>= loc
.end
)
4448 return extract(StmtRange(start
, end
));
4451 /* Set the size of index "pos" of "array" to "size".
4452 * In particular, add a constraint of the form
4456 * to array->extent and a constraint of the form
4460 * to array->context.
4462 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
4463 __isl_take isl_pw_aff
*size
)
4473 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
4474 array
->context
= isl_set_intersect(array
->context
, valid
);
4476 dim
= isl_set_get_space(array
->extent
);
4477 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
4478 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
4479 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
4480 index
= isl_pw_aff_alloc(univ
, aff
);
4482 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
4483 isl_set_dim(array
->extent
, isl_dim_set
));
4484 id
= isl_set_get_tuple_id(array
->extent
);
4485 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
4486 bound
= isl_pw_aff_lt_set(index
, size
);
4488 array
->extent
= isl_set_intersect(array
->extent
, bound
);
4490 if (!array
->context
|| !array
->extent
)
4495 pet_array_free(array
);
4499 /* Figure out the size of the array at position "pos" and all
4500 * subsequent positions from "type" and update "array" accordingly.
4502 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
4503 const Type
*type
, int pos
)
4505 const ArrayType
*atype
;
4511 if (type
->isPointerType()) {
4512 type
= type
->getPointeeType().getTypePtr();
4513 return set_upper_bounds(array
, type
, pos
+ 1);
4515 if (!type
->isArrayType())
4518 type
= type
->getCanonicalTypeInternal().getTypePtr();
4519 atype
= cast
<ArrayType
>(type
);
4521 if (type
->isConstantArrayType()) {
4522 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
4523 size
= extract_affine(ca
->getSize());
4524 array
= update_size(array
, pos
, size
);
4525 } else if (type
->isVariableArrayType()) {
4526 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
4527 size
= extract_affine(vla
->getSizeExpr());
4528 array
= update_size(array
, pos
, size
);
4531 type
= atype
->getElementType().getTypePtr();
4533 return set_upper_bounds(array
, type
, pos
+ 1);
4536 /* Construct and return a pet_array corresponding to the variable "decl".
4537 * In particular, initialize array->extent to
4539 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4541 * and then call set_upper_bounds to set the upper bounds on the indices
4542 * based on the type of the variable.
4544 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
)
4546 struct pet_array
*array
;
4547 QualType qt
= decl
->getType();
4548 const Type
*type
= qt
.getTypePtr();
4549 int depth
= array_depth(type
);
4550 QualType base
= base_type(qt
);
4555 array
= isl_calloc_type(ctx
, struct pet_array
);
4559 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
4560 dim
= isl_space_set_alloc(ctx
, 0, depth
);
4561 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
4563 array
->extent
= isl_set_nat_universe(dim
);
4565 dim
= isl_space_params_alloc(ctx
, 0);
4566 array
->context
= isl_set_universe(dim
);
4568 array
= set_upper_bounds(array
, type
, 0);
4572 name
= base
.getAsString();
4573 array
->element_type
= strdup(name
.c_str());
4574 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
4579 /* Construct a list of pet_arrays, one for each array (or scalar)
4580 * accessed inside "scop", add this list to "scop" and return the result.
4582 * The context of "scop" is updated with the intersection of
4583 * the contexts of all arrays, i.e., constraints on the parameters
4584 * that ensure that the arrays have a valid (non-negative) size.
4586 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
4589 set
<ValueDecl
*> arrays
;
4590 set
<ValueDecl
*>::iterator it
;
4592 struct pet_array
**scop_arrays
;
4597 pet_scop_collect_arrays(scop
, arrays
);
4598 if (arrays
.size() == 0)
4601 n_array
= scop
->n_array
;
4603 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
4604 n_array
+ arrays
.size());
4607 scop
->arrays
= scop_arrays
;
4609 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
4610 struct pet_array
*array
;
4611 scop
->arrays
[n_array
+ i
] = array
= extract_array(ctx
, *it
);
4612 if (!scop
->arrays
[n_array
+ i
])
4615 scop
->context
= isl_set_intersect(scop
->context
,
4616 isl_set_copy(array
->context
));
4623 pet_scop_free(scop
);
4627 /* Bound all parameters in scop->context to the possible values
4628 * of the corresponding C variable.
4630 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
4637 n
= isl_set_dim(scop
->context
, isl_dim_param
);
4638 for (int i
= 0; i
< n
; ++i
) {
4642 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
4643 if (is_nested_parameter(id
)) {
4645 isl_die(isl_set_get_ctx(scop
->context
),
4647 "unresolved nested parameter", goto error
);
4649 decl
= (ValueDecl
*) isl_id_get_user(id
);
4652 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
4660 pet_scop_free(scop
);
4664 /* Construct a pet_scop from the given function.
4666 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
4671 stmt
= fd
->getBody();
4673 if (options
->autodetect
)
4674 scop
= extract(stmt
);
4677 scop
= pet_scop_detect_parameter_accesses(scop
);
4678 scop
= scan_arrays(scop
);
4679 scop
= add_parameter_bounds(scop
);
4680 scop
= pet_scop_gist(scop
, value_bounds
);