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
39 #include <llvm/Support/raw_ostream.h>
40 #include <clang/AST/ASTContext.h>
41 #include <clang/AST/ASTDiagnostic.h>
42 #include <clang/AST/Expr.h>
43 #include <clang/AST/RecursiveASTVisitor.h>
46 #include <isl/space.h>
53 #include "scop_plus.h"
58 using namespace clang
;
60 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
61 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
63 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
64 SourceLocation(), var
, false, var
->getInnerLocStart(),
65 var
->getType(), VK_LValue
);
67 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
68 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
70 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
71 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
75 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
77 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
78 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
82 /* Check if the element type corresponding to the given array type
83 * has a const qualifier.
85 static bool const_base(QualType qt
)
87 const Type
*type
= qt
.getTypePtr();
89 if (type
->isPointerType())
90 return const_base(type
->getPointeeType());
91 if (type
->isArrayType()) {
92 const ArrayType
*atype
;
93 type
= type
->getCanonicalTypeInternal().getTypePtr();
94 atype
= cast
<ArrayType
>(type
);
95 return const_base(atype
->getElementType());
98 return qt
.isConstQualified();
101 /* Mark "decl" as having an unknown value in "assigned_value".
103 * If no (known or unknown) value was assigned to "decl" before,
104 * then it may have been treated as a parameter before and may
105 * therefore appear in a value assigned to another variable.
106 * If so, this assignment needs to be turned into an unknown value too.
108 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
111 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
113 it
= assigned_value
.find(decl
);
115 assigned_value
[decl
] = NULL
;
117 if (it
== assigned_value
.end())
120 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
121 isl_pw_aff
*pa
= it
->second
;
122 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
124 for (int i
= 0; i
< nparam
; ++i
) {
127 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
129 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
130 if (isl_id_get_user(id
) == decl
)
137 /* Look for any assignments to scalar variables in part of the parse
138 * tree and set assigned_value to NULL for each of them.
139 * Also reset assigned_value if the address of a scalar variable
140 * is being taken. As an exception, if the address is passed to a function
141 * that is declared to receive a const pointer, then assigned_value is
144 * This ensures that we won't use any previously stored value
145 * in the current subtree and its parents.
147 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
148 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
149 set
<UnaryOperator
*> skip
;
151 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
152 assigned_value(assigned_value
) {}
154 /* Check for "address of" operators whose value is passed
155 * to a const pointer argument and add them to "skip", so that
156 * we can skip them in VisitUnaryOperator.
158 bool VisitCallExpr(CallExpr
*expr
) {
160 fd
= expr
->getDirectCallee();
163 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
164 Expr
*arg
= expr
->getArg(i
);
166 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
167 ImplicitCastExpr
*ice
;
168 ice
= cast
<ImplicitCastExpr
>(arg
);
169 arg
= ice
->getSubExpr();
171 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
173 op
= cast
<UnaryOperator
>(arg
);
174 if (op
->getOpcode() != UO_AddrOf
)
176 if (const_base(fd
->getParamDecl(i
)->getType()))
182 bool VisitUnaryOperator(UnaryOperator
*expr
) {
187 switch (expr
->getOpcode()) {
197 if (skip
.find(expr
) != skip
.end())
200 arg
= expr
->getSubExpr();
201 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
203 ref
= cast
<DeclRefExpr
>(arg
);
204 decl
= ref
->getDecl();
205 clear_assignment(assigned_value
, decl
);
209 bool VisitBinaryOperator(BinaryOperator
*expr
) {
214 if (!expr
->isAssignmentOp())
216 lhs
= expr
->getLHS();
217 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
219 ref
= cast
<DeclRefExpr
>(lhs
);
220 decl
= ref
->getDecl();
221 clear_assignment(assigned_value
, decl
);
226 /* Keep a copy of the currently assigned values.
228 * Any variable that is assigned a value inside the current scope
229 * is removed again when we leave the scope (either because it wasn't
230 * stored in the cache or because it has a different value in the cache).
232 struct assigned_value_cache
{
233 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
234 map
<ValueDecl
*, isl_pw_aff
*> cache
;
236 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
237 assigned_value(assigned_value
), cache(assigned_value
) {}
238 ~assigned_value_cache() {
239 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
240 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
243 (cache
.find(it
->first
) != cache
.end() &&
244 cache
[it
->first
] != it
->second
))
245 cache
[it
->first
] = NULL
;
247 assigned_value
= cache
;
251 /* Insert an expression into the collection of expressions,
252 * provided it is not already in there.
253 * The isl_pw_affs are freed in the destructor.
255 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
257 std::set
<isl_pw_aff
*>::iterator it
;
259 if (expressions
.find(expr
) == expressions
.end())
260 expressions
.insert(expr
);
262 isl_pw_aff_free(expr
);
267 std::set
<isl_pw_aff
*>::iterator it
;
269 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
270 isl_pw_aff_free(*it
);
272 isl_union_map_free(value_bounds
);
275 /* Called if we found something we (currently) cannot handle.
276 * We'll provide more informative warnings later.
278 * We only actually complain if autodetect is false.
280 void PetScan::unsupported(Stmt
*stmt
, const char *msg
)
282 if (options
->autodetect
)
285 SourceLocation loc
= stmt
->getLocStart();
286 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
287 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
288 msg
? msg
: "unsupported");
289 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
292 /* Extract an integer from "expr".
294 __isl_give isl_val
*PetScan::extract_int(isl_ctx
*ctx
, IntegerLiteral
*expr
)
296 const Type
*type
= expr
->getType().getTypePtr();
297 int is_signed
= type
->hasSignedIntegerRepresentation();
298 llvm::APInt val
= expr
->getValue();
299 int is_negative
= is_signed
&& val
.isNegative();
305 v
= extract_unsigned(ctx
, val
);
312 /* Extract an integer from "val", which assumed to be non-negative.
314 __isl_give isl_val
*PetScan::extract_unsigned(isl_ctx
*ctx
,
315 const llvm::APInt
&val
)
318 const uint64_t *data
;
320 data
= val
.getRawData();
321 n
= val
.getNumWords();
322 return isl_val_int_from_chunks(ctx
, n
, sizeof(uint64_t), data
);
325 /* Extract an integer from "expr".
326 * Return NULL if "expr" does not (obviously) represent an integer.
328 __isl_give isl_val
*PetScan::extract_int(clang::ParenExpr
*expr
)
330 return extract_int(expr
->getSubExpr());
333 /* Extract an integer from "expr".
334 * Return NULL if "expr" does not (obviously) represent an integer.
336 __isl_give isl_val
*PetScan::extract_int(clang::Expr
*expr
)
338 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
339 return extract_int(ctx
, cast
<IntegerLiteral
>(expr
));
340 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
341 return extract_int(cast
<ParenExpr
>(expr
));
347 /* Extract an affine expression from the IntegerLiteral "expr".
349 __isl_give isl_pw_aff
*PetScan::extract_affine(IntegerLiteral
*expr
)
351 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
352 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
353 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
354 isl_set
*dom
= isl_set_universe(dim
);
357 v
= extract_int(expr
);
358 aff
= isl_aff_add_constant_val(aff
, v
);
360 return isl_pw_aff_alloc(dom
, aff
);
363 /* Extract an affine expression from the APInt "val", which is assumed
364 * to be non-negative.
366 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
368 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
369 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
370 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
371 isl_set
*dom
= isl_set_universe(dim
);
374 v
= extract_unsigned(ctx
, val
);
375 aff
= isl_aff_add_constant_val(aff
, v
);
377 return isl_pw_aff_alloc(dom
, aff
);
380 __isl_give isl_pw_aff
*PetScan::extract_affine(ImplicitCastExpr
*expr
)
382 return extract_affine(expr
->getSubExpr());
385 static unsigned get_type_size(ValueDecl
*decl
)
387 return decl
->getASTContext().getIntWidth(decl
->getType());
390 /* Bound parameter "pos" of "set" to the possible values of "decl".
392 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
393 unsigned pos
, ValueDecl
*decl
)
399 ctx
= isl_set_get_ctx(set
);
400 width
= get_type_size(decl
);
401 if (decl
->getType()->isUnsignedIntegerType()) {
402 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
403 bound
= isl_val_int_from_ui(ctx
, width
);
404 bound
= isl_val_2exp(bound
);
405 bound
= isl_val_sub_ui(bound
, 1);
406 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
, bound
);
408 bound
= isl_val_int_from_ui(ctx
, width
- 1);
409 bound
= isl_val_2exp(bound
);
410 bound
= isl_val_sub_ui(bound
, 1);
411 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
,
412 isl_val_copy(bound
));
413 bound
= isl_val_neg(bound
);
414 bound
= isl_val_sub_ui(bound
, 1);
415 set
= isl_set_lower_bound_val(set
, isl_dim_param
, pos
, bound
);
421 /* Extract an affine expression from the DeclRefExpr "expr".
423 * If the variable has been assigned a value, then we check whether
424 * we know what (affine) value was assigned.
425 * If so, we return this value. Otherwise we convert "expr"
426 * to an extra parameter (provided nesting_enabled is set).
428 * Otherwise, we simply return an expression that is equal
429 * to a parameter corresponding to the referenced variable.
431 __isl_give isl_pw_aff
*PetScan::extract_affine(DeclRefExpr
*expr
)
433 ValueDecl
*decl
= expr
->getDecl();
434 const Type
*type
= decl
->getType().getTypePtr();
440 if (!type
->isIntegerType()) {
445 if (assigned_value
.find(decl
) != assigned_value
.end()) {
446 if (assigned_value
[decl
])
447 return isl_pw_aff_copy(assigned_value
[decl
]);
449 return nested_access(expr
);
452 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
453 dim
= isl_space_params_alloc(ctx
, 1);
455 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
457 dom
= isl_set_universe(isl_space_copy(dim
));
458 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
459 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
461 return isl_pw_aff_alloc(dom
, aff
);
464 /* Extract an affine expression from an integer division operation.
465 * In particular, if "expr" is lhs/rhs, then return
467 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
469 * The second argument (rhs) is required to be a (positive) integer constant.
471 __isl_give isl_pw_aff
*PetScan::extract_affine_div(BinaryOperator
*expr
)
474 isl_pw_aff
*rhs
, *lhs
;
476 rhs
= extract_affine(expr
->getRHS());
477 is_cst
= isl_pw_aff_is_cst(rhs
);
478 if (is_cst
< 0 || !is_cst
) {
479 isl_pw_aff_free(rhs
);
485 lhs
= extract_affine(expr
->getLHS());
487 return isl_pw_aff_tdiv_q(lhs
, rhs
);
490 /* Extract an affine expression from a modulo operation.
491 * In particular, if "expr" is lhs/rhs, then return
493 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
495 * The second argument (rhs) is required to be a (positive) integer constant.
497 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
500 isl_pw_aff
*rhs
, *lhs
;
502 rhs
= extract_affine(expr
->getRHS());
503 is_cst
= isl_pw_aff_is_cst(rhs
);
504 if (is_cst
< 0 || !is_cst
) {
505 isl_pw_aff_free(rhs
);
511 lhs
= extract_affine(expr
->getLHS());
513 return isl_pw_aff_tdiv_r(lhs
, rhs
);
516 /* Extract an affine expression from a multiplication operation.
517 * This is only allowed if at least one of the two arguments
518 * is a (piecewise) constant.
520 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
525 lhs
= extract_affine(expr
->getLHS());
526 rhs
= extract_affine(expr
->getRHS());
528 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
529 isl_pw_aff_free(lhs
);
530 isl_pw_aff_free(rhs
);
535 return isl_pw_aff_mul(lhs
, rhs
);
538 /* Extract an affine expression from an addition or subtraction operation.
540 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
545 lhs
= extract_affine(expr
->getLHS());
546 rhs
= extract_affine(expr
->getRHS());
548 switch (expr
->getOpcode()) {
550 return isl_pw_aff_add(lhs
, rhs
);
552 return isl_pw_aff_sub(lhs
, rhs
);
554 isl_pw_aff_free(lhs
);
555 isl_pw_aff_free(rhs
);
565 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
571 ctx
= isl_pw_aff_get_ctx(pwaff
);
572 mod
= isl_val_int_from_ui(ctx
, width
);
573 mod
= isl_val_2exp(mod
);
575 pwaff
= isl_pw_aff_mod_val(pwaff
, mod
);
580 /* Limit the domain of "pwaff" to those elements where the function
583 * 2^{width-1} <= pwaff < 2^{width-1}
585 static __isl_give isl_pw_aff
*avoid_overflow(__isl_take isl_pw_aff
*pwaff
,
590 isl_space
*space
= isl_pw_aff_get_domain_space(pwaff
);
591 isl_local_space
*ls
= isl_local_space_from_space(space
);
596 ctx
= isl_pw_aff_get_ctx(pwaff
);
597 v
= isl_val_int_from_ui(ctx
, width
- 1);
600 bound
= isl_aff_zero_on_domain(ls
);
601 bound
= isl_aff_add_constant_val(bound
, v
);
602 b
= isl_pw_aff_from_aff(bound
);
604 dom
= isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff
), isl_pw_aff_copy(b
));
605 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
607 b
= isl_pw_aff_neg(b
);
608 dom
= isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff
), b
);
609 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
614 /* Handle potential overflows on signed computations.
616 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
617 * the we adjust the domain of "pa" to avoid overflows.
619 __isl_give isl_pw_aff
*PetScan::signed_overflow(__isl_take isl_pw_aff
*pa
,
622 if (options
->signed_overflow
== PET_OVERFLOW_AVOID
)
623 pa
= avoid_overflow(pa
, width
);
628 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
630 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
631 __isl_take isl_set
*dom
)
634 pa
= isl_set_indicator_function(set
);
635 pa
= isl_pw_aff_intersect_domain(pa
, dom
);
639 /* Extract an affine expression from some binary operations.
640 * If the result of the expression is unsigned, then we wrap it
641 * based on the size of the type. Otherwise, we ensure that
642 * no overflow occurs.
644 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
649 switch (expr
->getOpcode()) {
652 res
= extract_affine_add(expr
);
655 res
= extract_affine_div(expr
);
658 res
= extract_affine_mod(expr
);
661 res
= extract_affine_mul(expr
);
671 return extract_condition(expr
);
677 width
= ast_context
.getIntWidth(expr
->getType());
678 if (expr
->getType()->isUnsignedIntegerType())
679 res
= wrap(res
, width
);
681 res
= signed_overflow(res
, width
);
686 /* Extract an affine expression from a negation operation.
688 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
690 if (expr
->getOpcode() == UO_Minus
)
691 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
692 if (expr
->getOpcode() == UO_LNot
)
693 return extract_condition(expr
);
699 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
701 return extract_affine(expr
->getSubExpr());
704 /* Extract an affine expression from some special function calls.
705 * In particular, we handle "min", "max", "ceild" and "floord".
706 * In case of the latter two, the second argument needs to be
707 * a (positive) integer constant.
709 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
713 isl_pw_aff
*aff1
, *aff2
;
715 fd
= expr
->getDirectCallee();
721 name
= fd
->getDeclName().getAsString();
722 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
723 !(expr
->getNumArgs() == 2 && name
== "max") &&
724 !(expr
->getNumArgs() == 2 && name
== "floord") &&
725 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
730 if (name
== "min" || name
== "max") {
731 aff1
= extract_affine(expr
->getArg(0));
732 aff2
= extract_affine(expr
->getArg(1));
735 aff1
= isl_pw_aff_min(aff1
, aff2
);
737 aff1
= isl_pw_aff_max(aff1
, aff2
);
738 } else if (name
== "floord" || name
== "ceild") {
740 Expr
*arg2
= expr
->getArg(1);
742 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
746 aff1
= extract_affine(expr
->getArg(0));
747 v
= extract_int(cast
<IntegerLiteral
>(arg2
));
748 aff1
= isl_pw_aff_scale_down_val(aff1
, v
);
749 if (name
== "floord")
750 aff1
= isl_pw_aff_floor(aff1
);
752 aff1
= isl_pw_aff_ceil(aff1
);
761 /* This method is called when we come across an access that is
762 * nested in what is supposed to be an affine expression.
763 * If nesting is allowed, we return a new parameter that corresponds
764 * to this nested access. Otherwise, we simply complain.
766 * Note that we currently don't allow nested accesses themselves
767 * to contain any nested accesses, so we check if we can extract
768 * the access without any nesting and complain if we can't.
770 * The new parameter is resolved in resolve_nested.
772 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
780 if (!nesting_enabled
) {
785 allow_nested
= false;
786 access
= extract_access(expr
);
792 isl_map_free(access
);
794 id
= isl_id_alloc(ctx
, NULL
, expr
);
795 dim
= isl_space_params_alloc(ctx
, 1);
797 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
799 dom
= isl_set_universe(isl_space_copy(dim
));
800 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
801 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
803 return isl_pw_aff_alloc(dom
, aff
);
806 /* Affine expressions are not supposed to contain array accesses,
807 * but if nesting is allowed, we return a parameter corresponding
808 * to the array access.
810 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
812 return nested_access(expr
);
815 /* Extract an affine expression from a conditional operation.
817 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
819 isl_pw_aff
*cond
, *lhs
, *rhs
, *res
;
821 cond
= extract_condition(expr
->getCond());
822 lhs
= extract_affine(expr
->getTrueExpr());
823 rhs
= extract_affine(expr
->getFalseExpr());
825 return isl_pw_aff_cond(cond
, lhs
, rhs
);
828 /* Extract an affine expression, if possible, from "expr".
829 * Otherwise return NULL.
831 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
833 switch (expr
->getStmtClass()) {
834 case Stmt::ImplicitCastExprClass
:
835 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
836 case Stmt::IntegerLiteralClass
:
837 return extract_affine(cast
<IntegerLiteral
>(expr
));
838 case Stmt::DeclRefExprClass
:
839 return extract_affine(cast
<DeclRefExpr
>(expr
));
840 case Stmt::BinaryOperatorClass
:
841 return extract_affine(cast
<BinaryOperator
>(expr
));
842 case Stmt::UnaryOperatorClass
:
843 return extract_affine(cast
<UnaryOperator
>(expr
));
844 case Stmt::ParenExprClass
:
845 return extract_affine(cast
<ParenExpr
>(expr
));
846 case Stmt::CallExprClass
:
847 return extract_affine(cast
<CallExpr
>(expr
));
848 case Stmt::ArraySubscriptExprClass
:
849 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
850 case Stmt::ConditionalOperatorClass
:
851 return extract_affine(cast
<ConditionalOperator
>(expr
));
858 __isl_give isl_map
*PetScan::extract_access(ImplicitCastExpr
*expr
)
860 return extract_access(expr
->getSubExpr());
863 /* Return the depth of an array of the given type.
865 static int array_depth(const Type
*type
)
867 if (type
->isPointerType())
868 return 1 + array_depth(type
->getPointeeType().getTypePtr());
869 if (type
->isArrayType()) {
870 const ArrayType
*atype
;
871 type
= type
->getCanonicalTypeInternal().getTypePtr();
872 atype
= cast
<ArrayType
>(type
);
873 return 1 + array_depth(atype
->getElementType().getTypePtr());
878 /* Return the element type of the given array type.
880 static QualType
base_type(QualType qt
)
882 const Type
*type
= qt
.getTypePtr();
884 if (type
->isPointerType())
885 return base_type(type
->getPointeeType());
886 if (type
->isArrayType()) {
887 const ArrayType
*atype
;
888 type
= type
->getCanonicalTypeInternal().getTypePtr();
889 atype
= cast
<ArrayType
>(type
);
890 return base_type(atype
->getElementType());
895 /* Extract an access relation from a reference to a variable.
896 * If the variable has name "A" and its type corresponds to an
897 * array of depth d, then the returned access relation is of the
900 * { [] -> A[i_1,...,i_d] }
902 __isl_give isl_map
*PetScan::extract_access(DeclRefExpr
*expr
)
904 return extract_access(expr
->getDecl());
907 /* Extract an access relation from a variable.
908 * If the variable has name "A" and its type corresponds to an
909 * array of depth d, then the returned access relation is of the
912 * { [] -> A[i_1,...,i_d] }
914 __isl_give isl_map
*PetScan::extract_access(ValueDecl
*decl
)
916 int depth
= array_depth(decl
->getType().getTypePtr());
917 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
918 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, depth
);
921 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
923 access_rel
= isl_map_universe(dim
);
928 /* Extract an access relation from an integer contant.
929 * If the value of the constant is "v", then the returned access relation
934 __isl_give isl_map
*PetScan::extract_access(IntegerLiteral
*expr
)
936 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr
)));
939 /* Try and extract an access relation from the given Expr.
940 * Return NULL if it doesn't work out.
942 __isl_give isl_map
*PetScan::extract_access(Expr
*expr
)
944 switch (expr
->getStmtClass()) {
945 case Stmt::ImplicitCastExprClass
:
946 return extract_access(cast
<ImplicitCastExpr
>(expr
));
947 case Stmt::DeclRefExprClass
:
948 return extract_access(cast
<DeclRefExpr
>(expr
));
949 case Stmt::ArraySubscriptExprClass
:
950 return extract_access(cast
<ArraySubscriptExpr
>(expr
));
951 case Stmt::IntegerLiteralClass
:
952 return extract_access(cast
<IntegerLiteral
>(expr
));
959 /* Assign the affine expression "index" to the output dimension "pos" of "map",
960 * restrict the domain to those values that result in a non-negative index
961 * and return the result.
963 __isl_give isl_map
*set_index(__isl_take isl_map
*map
, int pos
,
964 __isl_take isl_pw_aff
*index
)
967 int len
= isl_map_dim(map
, isl_dim_out
);
971 domain
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(index
));
972 index
= isl_pw_aff_intersect_domain(index
, domain
);
973 index_map
= isl_map_from_range(isl_set_from_pw_aff(index
));
974 index_map
= isl_map_insert_dims(index_map
, isl_dim_out
, 0, pos
);
975 index_map
= isl_map_add_dims(index_map
, isl_dim_out
, len
- pos
- 1);
976 id
= isl_map_get_tuple_id(map
, isl_dim_out
);
977 index_map
= isl_map_set_tuple_id(index_map
, isl_dim_out
, id
);
979 map
= isl_map_intersect(map
, index_map
);
984 /* Extract an access relation from the given array subscript expression.
985 * If nesting is allowed in general, then we turn it on while
986 * examining the index expression.
988 * We first extract an access relation from the base.
989 * This will result in an access relation with a range that corresponds
990 * to the array being accessed and with earlier indices filled in already.
991 * We then extract the current index and fill that in as well.
992 * The position of the current index is based on the type of base.
993 * If base is the actual array variable, then the depth of this type
994 * will be the same as the depth of the array and we will fill in
995 * the first array index.
996 * Otherwise, the depth of the base type will be smaller and we will fill
999 __isl_give isl_map
*PetScan::extract_access(ArraySubscriptExpr
*expr
)
1001 Expr
*base
= expr
->getBase();
1002 Expr
*idx
= expr
->getIdx();
1004 isl_map
*base_access
;
1006 int depth
= array_depth(base
->getType().getTypePtr());
1008 bool save_nesting
= nesting_enabled
;
1010 nesting_enabled
= allow_nested
;
1012 base_access
= extract_access(base
);
1013 index
= extract_affine(idx
);
1015 nesting_enabled
= save_nesting
;
1017 pos
= isl_map_dim(base_access
, isl_dim_out
) - depth
;
1018 access
= set_index(base_access
, pos
, index
);
1023 /* Check if "expr" calls function "minmax" with two arguments and if so
1024 * make lhs and rhs refer to these two arguments.
1026 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
1032 if (expr
->getStmtClass() != Stmt::CallExprClass
)
1035 call
= cast
<CallExpr
>(expr
);
1036 fd
= call
->getDirectCallee();
1040 if (call
->getNumArgs() != 2)
1043 name
= fd
->getDeclName().getAsString();
1047 lhs
= call
->getArg(0);
1048 rhs
= call
->getArg(1);
1053 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1054 * lhs and rhs refer to the two arguments.
1056 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1058 return is_minmax(expr
, "min", lhs
, rhs
);
1061 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1062 * lhs and rhs refer to the two arguments.
1064 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1066 return is_minmax(expr
, "max", lhs
, rhs
);
1069 /* Return "lhs && rhs", defined on the shared definition domain.
1071 static __isl_give isl_pw_aff
*pw_aff_and(__isl_take isl_pw_aff
*lhs
,
1072 __isl_take isl_pw_aff
*rhs
)
1077 dom
= isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs
)),
1078 isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1079 cond
= isl_set_intersect(isl_pw_aff_non_zero_set(lhs
),
1080 isl_pw_aff_non_zero_set(rhs
));
1081 return indicator_function(cond
, dom
);
1084 /* Return "lhs && rhs", with shortcut semantics.
1085 * That is, if lhs is false, then the result is defined even if rhs is not.
1086 * In practice, we compute lhs ? rhs : lhs.
1088 static __isl_give isl_pw_aff
*pw_aff_and_then(__isl_take isl_pw_aff
*lhs
,
1089 __isl_take isl_pw_aff
*rhs
)
1091 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), rhs
, lhs
);
1094 /* Return "lhs || rhs", with shortcut semantics.
1095 * That is, if lhs is true, then the result is defined even if rhs is not.
1096 * In practice, we compute lhs ? lhs : rhs.
1098 static __isl_give isl_pw_aff
*pw_aff_or_else(__isl_take isl_pw_aff
*lhs
,
1099 __isl_take isl_pw_aff
*rhs
)
1101 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), lhs
, rhs
);
1104 /* Extract an affine expressions representing the comparison "LHS op RHS"
1105 * "comp" is the original statement that "LHS op RHS" is derived from
1106 * and is used for diagnostics.
1108 * If the comparison is of the form
1112 * then the expression is constructed as the conjunction of
1117 * A similar optimization is performed for max(a,b) <= c.
1118 * We do this because that will lead to simpler representations
1119 * of the expression.
1120 * If isl is ever enhanced to explicitly deal with min and max expressions,
1121 * this optimization can be removed.
1123 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
1124 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
1133 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
1135 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
1137 if (op
== BO_LT
|| op
== BO_LE
) {
1138 Expr
*expr1
, *expr2
;
1139 if (is_min(RHS
, expr1
, expr2
)) {
1140 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
1141 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
1142 return pw_aff_and(lhs
, rhs
);
1144 if (is_max(LHS
, expr1
, expr2
)) {
1145 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
1146 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
1147 return pw_aff_and(lhs
, rhs
);
1151 lhs
= extract_affine(LHS
);
1152 rhs
= extract_affine(RHS
);
1154 dom
= isl_pw_aff_domain(isl_pw_aff_copy(lhs
));
1155 dom
= isl_set_intersect(dom
, isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1159 cond
= isl_pw_aff_lt_set(lhs
, rhs
);
1162 cond
= isl_pw_aff_le_set(lhs
, rhs
);
1165 cond
= isl_pw_aff_eq_set(lhs
, rhs
);
1168 cond
= isl_pw_aff_ne_set(lhs
, rhs
);
1171 isl_pw_aff_free(lhs
);
1172 isl_pw_aff_free(rhs
);
1178 cond
= isl_set_coalesce(cond
);
1179 res
= indicator_function(cond
, dom
);
1184 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
1186 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1187 comp
->getRHS(), comp
);
1190 /* Extract an affine expression representing the negation (logical not)
1191 * of a subexpression.
1193 __isl_give isl_pw_aff
*PetScan::extract_boolean(UnaryOperator
*op
)
1195 isl_set
*set_cond
, *dom
;
1196 isl_pw_aff
*cond
, *res
;
1198 cond
= extract_condition(op
->getSubExpr());
1200 dom
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
1202 set_cond
= isl_pw_aff_zero_set(cond
);
1204 res
= indicator_function(set_cond
, dom
);
1209 /* Extract an affine expression representing the disjunction (logical or)
1210 * or conjunction (logical and) of two subexpressions.
1212 __isl_give isl_pw_aff
*PetScan::extract_boolean(BinaryOperator
*comp
)
1214 isl_pw_aff
*lhs
, *rhs
;
1216 lhs
= extract_condition(comp
->getLHS());
1217 rhs
= extract_condition(comp
->getRHS());
1219 switch (comp
->getOpcode()) {
1221 return pw_aff_and_then(lhs
, rhs
);
1223 return pw_aff_or_else(lhs
, rhs
);
1225 isl_pw_aff_free(lhs
);
1226 isl_pw_aff_free(rhs
);
1233 __isl_give isl_pw_aff
*PetScan::extract_condition(UnaryOperator
*expr
)
1235 switch (expr
->getOpcode()) {
1237 return extract_boolean(expr
);
1244 /* Extract the affine expression "expr != 0 ? 1 : 0".
1246 __isl_give isl_pw_aff
*PetScan::extract_implicit_condition(Expr
*expr
)
1251 res
= extract_affine(expr
);
1253 dom
= isl_pw_aff_domain(isl_pw_aff_copy(res
));
1254 set
= isl_pw_aff_non_zero_set(res
);
1256 res
= indicator_function(set
, dom
);
1261 /* Extract an affine expression from a boolean expression.
1262 * In particular, return the expression "expr ? 1 : 0".
1264 * If the expression doesn't look like a condition, we assume it
1265 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1267 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
1269 BinaryOperator
*comp
;
1272 isl_set
*u
= isl_set_universe(isl_space_params_alloc(ctx
, 0));
1273 return indicator_function(u
, isl_set_copy(u
));
1276 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1277 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1279 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1280 return extract_condition(cast
<UnaryOperator
>(expr
));
1282 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1283 return extract_implicit_condition(expr
);
1285 comp
= cast
<BinaryOperator
>(expr
);
1286 switch (comp
->getOpcode()) {
1293 return extract_comparison(comp
);
1296 return extract_boolean(comp
);
1298 return extract_implicit_condition(expr
);
1302 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
1306 return pet_op_minus
;
1308 return pet_op_post_inc
;
1310 return pet_op_post_dec
;
1312 return pet_op_pre_inc
;
1314 return pet_op_pre_dec
;
1320 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
1324 return pet_op_add_assign
;
1326 return pet_op_sub_assign
;
1328 return pet_op_mul_assign
;
1330 return pet_op_div_assign
;
1332 return pet_op_assign
;
1356 /* Construct a pet_expr representing a unary operator expression.
1358 struct pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1360 struct pet_expr
*arg
;
1361 enum pet_op_type op
;
1363 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1364 if (op
== pet_op_last
) {
1369 arg
= extract_expr(expr
->getSubExpr());
1371 if (expr
->isIncrementDecrementOp() &&
1372 arg
&& arg
->type
== pet_expr_access
) {
1377 return pet_expr_new_unary(ctx
, op
, arg
);
1380 /* Mark the given access pet_expr as a write.
1381 * If a scalar is being accessed, then mark its value
1382 * as unknown in assigned_value.
1384 void PetScan::mark_write(struct pet_expr
*access
)
1392 access
->acc
.write
= 1;
1393 access
->acc
.read
= 0;
1395 if (!pet_expr_is_scalar_access(access
))
1398 id
= pet_expr_access_get_id(access
);
1399 decl
= (ValueDecl
*) isl_id_get_user(id
);
1400 clear_assignment(assigned_value
, decl
);
1404 /* Assign "rhs" to "lhs".
1406 * In particular, if "lhs" is a scalar variable, then mark
1407 * the variable as having been assigned. If, furthermore, "rhs"
1408 * is an affine expression, then keep track of this value in assigned_value
1409 * so that we can plug it in when we later come across the same variable.
1411 void PetScan::assign(struct pet_expr
*lhs
, Expr
*rhs
)
1419 if (!pet_expr_is_scalar_access(lhs
))
1422 id
= pet_expr_access_get_id(lhs
);
1423 decl
= (ValueDecl
*) isl_id_get_user(id
);
1426 pa
= try_extract_affine(rhs
);
1427 clear_assignment(assigned_value
, decl
);
1430 assigned_value
[decl
] = pa
;
1431 insert_expression(pa
);
1434 /* Construct a pet_expr representing a binary operator expression.
1436 * If the top level operator is an assignment and the LHS is an access,
1437 * then we mark that access as a write. If the operator is a compound
1438 * assignment, the access is marked as both a read and a write.
1440 * If "expr" assigns something to a scalar variable, then we mark
1441 * the variable as having been assigned. If, furthermore, the expression
1442 * is affine, then keep track of this value in assigned_value
1443 * so that we can plug it in when we later come across the same variable.
1445 struct pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1447 struct pet_expr
*lhs
, *rhs
;
1448 enum pet_op_type op
;
1450 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1451 if (op
== pet_op_last
) {
1456 lhs
= extract_expr(expr
->getLHS());
1457 rhs
= extract_expr(expr
->getRHS());
1459 if (expr
->isAssignmentOp() && lhs
&& lhs
->type
== pet_expr_access
) {
1461 if (expr
->isCompoundAssignmentOp())
1465 if (expr
->getOpcode() == BO_Assign
)
1466 assign(lhs
, expr
->getRHS());
1468 return pet_expr_new_binary(ctx
, op
, lhs
, rhs
);
1471 /* Construct a pet_scop with a single statement killing the entire
1474 struct pet_scop
*PetScan::kill(Stmt
*stmt
, struct pet_array
*array
)
1477 struct pet_expr
*expr
;
1481 access
= isl_map_from_range(isl_set_copy(array
->extent
));
1482 expr
= pet_expr_kill_from_access(access
);
1483 return extract(stmt
, expr
);
1486 /* Construct a pet_scop for a (single) variable declaration.
1488 * The scop contains the variable being declared (as an array)
1489 * and a statement killing the array.
1491 * If the variable is initialized in the AST, then the scop
1492 * also contains an assignment to the variable.
1494 struct pet_scop
*PetScan::extract(DeclStmt
*stmt
)
1498 struct pet_expr
*lhs
, *rhs
, *pe
;
1499 struct pet_scop
*scop_decl
, *scop
;
1500 struct pet_array
*array
;
1502 if (!stmt
->isSingleDecl()) {
1507 decl
= stmt
->getSingleDecl();
1508 vd
= cast
<VarDecl
>(decl
);
1510 array
= extract_array(ctx
, vd
);
1512 array
->declared
= 1;
1513 scop_decl
= kill(stmt
, array
);
1514 scop_decl
= pet_scop_add_array(scop_decl
, array
);
1519 lhs
= pet_expr_from_access(extract_access(vd
));
1520 rhs
= extract_expr(vd
->getInit());
1523 assign(lhs
, vd
->getInit());
1525 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, lhs
, rhs
);
1526 scop
= extract(stmt
, pe
);
1528 scop_decl
= pet_scop_prefix(scop_decl
, 0);
1529 scop
= pet_scop_prefix(scop
, 1);
1531 scop
= pet_scop_add_seq(ctx
, scop_decl
, scop
);
1536 /* Construct a pet_expr representing a conditional operation.
1538 * We first try to extract the condition as an affine expression.
1539 * If that fails, we construct a pet_expr tree representing the condition.
1541 struct pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1543 struct pet_expr
*cond
, *lhs
, *rhs
;
1546 pa
= try_extract_affine(expr
->getCond());
1548 isl_multi_pw_aff
*test
= isl_multi_pw_aff_from_pw_aff(pa
);
1549 test
= isl_multi_pw_aff_from_range(test
);
1550 cond
= pet_expr_from_index(test
);
1552 cond
= extract_expr(expr
->getCond());
1553 lhs
= extract_expr(expr
->getTrueExpr());
1554 rhs
= extract_expr(expr
->getFalseExpr());
1556 return pet_expr_new_ternary(ctx
, cond
, lhs
, rhs
);
1559 struct pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1561 return extract_expr(expr
->getSubExpr());
1564 /* Construct a pet_expr representing a floating point value.
1566 * If the floating point literal does not appear in a macro,
1567 * then we use the original representation in the source code
1568 * as the string representation. Otherwise, we use the pretty
1569 * printer to produce a string representation.
1571 struct pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1575 const LangOptions
&LO
= PP
.getLangOpts();
1576 SourceLocation loc
= expr
->getLocation();
1578 if (!loc
.isMacroID()) {
1579 SourceManager
&SM
= PP
.getSourceManager();
1580 unsigned len
= Lexer::MeasureTokenLength(loc
, SM
, LO
);
1581 s
= string(SM
.getCharacterData(loc
), len
);
1583 llvm::raw_string_ostream
S(s
);
1584 expr
->printPretty(S
, 0, PrintingPolicy(LO
));
1587 d
= expr
->getValueAsApproximateDouble();
1588 return pet_expr_new_double(ctx
, d
, s
.c_str());
1591 /* Extract an access relation from "expr" and then convert it into
1594 struct pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1597 struct pet_expr
*pe
;
1599 access
= extract_access(expr
);
1601 pe
= pet_expr_from_access(access
);
1606 struct pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1608 return extract_expr(expr
->getSubExpr());
1611 /* Construct a pet_expr representing a function call.
1613 * If we are passing along a pointer to an array element
1614 * or an entire row or even higher dimensional slice of an array,
1615 * then the function being called may write into the array.
1617 * We assume here that if the function is declared to take a pointer
1618 * to a const type, then the function will perform a read
1619 * and that otherwise, it will perform a write.
1621 struct pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1623 struct pet_expr
*res
= NULL
;
1627 fd
= expr
->getDirectCallee();
1633 name
= fd
->getDeclName().getAsString();
1634 res
= pet_expr_new_call(ctx
, name
.c_str(), expr
->getNumArgs());
1638 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
1639 Expr
*arg
= expr
->getArg(i
);
1643 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1644 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(arg
);
1645 arg
= ice
->getSubExpr();
1647 if (arg
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1648 UnaryOperator
*op
= cast
<UnaryOperator
>(arg
);
1649 if (op
->getOpcode() == UO_AddrOf
) {
1651 arg
= op
->getSubExpr();
1654 res
->args
[i
] = PetScan::extract_expr(arg
);
1655 main_arg
= res
->args
[i
];
1657 res
->args
[i
] = pet_expr_new_unary(ctx
,
1658 pet_op_address_of
, res
->args
[i
]);
1661 if (arg
->getStmtClass() == Stmt::ArraySubscriptExprClass
&&
1662 array_depth(arg
->getType().getTypePtr()) > 0)
1664 if (is_addr
&& main_arg
->type
== pet_expr_access
) {
1666 if (!fd
->hasPrototype()) {
1667 unsupported(expr
, "prototype required");
1670 parm
= fd
->getParamDecl(i
);
1671 if (!const_base(parm
->getType()))
1672 mark_write(main_arg
);
1682 /* Construct a pet_expr representing a (C style) cast.
1684 struct pet_expr
*PetScan::extract_expr(CStyleCastExpr
*expr
)
1686 struct pet_expr
*arg
;
1689 arg
= extract_expr(expr
->getSubExpr());
1693 type
= expr
->getTypeAsWritten();
1694 return pet_expr_new_cast(ctx
, type
.getAsString().c_str(), arg
);
1697 /* Try and onstruct a pet_expr representing "expr".
1699 struct pet_expr
*PetScan::extract_expr(Expr
*expr
)
1701 switch (expr
->getStmtClass()) {
1702 case Stmt::UnaryOperatorClass
:
1703 return extract_expr(cast
<UnaryOperator
>(expr
));
1704 case Stmt::CompoundAssignOperatorClass
:
1705 case Stmt::BinaryOperatorClass
:
1706 return extract_expr(cast
<BinaryOperator
>(expr
));
1707 case Stmt::ImplicitCastExprClass
:
1708 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1709 case Stmt::ArraySubscriptExprClass
:
1710 case Stmt::DeclRefExprClass
:
1711 case Stmt::IntegerLiteralClass
:
1712 return extract_access_expr(expr
);
1713 case Stmt::FloatingLiteralClass
:
1714 return extract_expr(cast
<FloatingLiteral
>(expr
));
1715 case Stmt::ParenExprClass
:
1716 return extract_expr(cast
<ParenExpr
>(expr
));
1717 case Stmt::ConditionalOperatorClass
:
1718 return extract_expr(cast
<ConditionalOperator
>(expr
));
1719 case Stmt::CallExprClass
:
1720 return extract_expr(cast
<CallExpr
>(expr
));
1721 case Stmt::CStyleCastExprClass
:
1722 return extract_expr(cast
<CStyleCastExpr
>(expr
));
1729 /* Check if the given initialization statement is an assignment.
1730 * If so, return that assignment. Otherwise return NULL.
1732 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1734 BinaryOperator
*ass
;
1736 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1739 ass
= cast
<BinaryOperator
>(init
);
1740 if (ass
->getOpcode() != BO_Assign
)
1746 /* Check if the given initialization statement is a declaration
1747 * of a single variable.
1748 * If so, return that declaration. Otherwise return NULL.
1750 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1754 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1757 decl
= cast
<DeclStmt
>(init
);
1759 if (!decl
->isSingleDecl())
1762 return decl
->getSingleDecl();
1765 /* Given the assignment operator in the initialization of a for loop,
1766 * extract the induction variable, i.e., the (integer)variable being
1769 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1776 lhs
= init
->getLHS();
1777 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1782 ref
= cast
<DeclRefExpr
>(lhs
);
1783 decl
= ref
->getDecl();
1784 type
= decl
->getType().getTypePtr();
1786 if (!type
->isIntegerType()) {
1794 /* Given the initialization statement of a for loop and the single
1795 * declaration in this initialization statement,
1796 * extract the induction variable, i.e., the (integer) variable being
1799 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1803 vd
= cast
<VarDecl
>(decl
);
1805 const QualType type
= vd
->getType();
1806 if (!type
->isIntegerType()) {
1811 if (!vd
->getInit()) {
1819 /* Check that op is of the form iv++ or iv--.
1820 * Return an affine expression "1" or "-1" accordingly.
1822 __isl_give isl_pw_aff
*PetScan::extract_unary_increment(
1823 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1830 if (!op
->isIncrementDecrementOp()) {
1835 sub
= op
->getSubExpr();
1836 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1841 ref
= cast
<DeclRefExpr
>(sub
);
1842 if (ref
->getDecl() != iv
) {
1847 space
= isl_space_params_alloc(ctx
, 0);
1848 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
1850 if (op
->isIncrementOp())
1851 aff
= isl_aff_add_constant_si(aff
, 1);
1853 aff
= isl_aff_add_constant_si(aff
, -1);
1855 return isl_pw_aff_from_aff(aff
);
1858 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1859 * has a single constant expression, then put this constant in *user.
1860 * The caller is assumed to have checked that this function will
1861 * be called exactly once.
1863 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
1866 isl_val
**inc
= (isl_val
**)user
;
1869 if (isl_aff_is_cst(aff
))
1870 *inc
= isl_aff_get_constant_val(aff
);
1880 /* Check if op is of the form
1884 * and return inc as an affine expression.
1886 * We extract an affine expression from the RHS, subtract iv and return
1889 __isl_give isl_pw_aff
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1890 clang::ValueDecl
*iv
)
1899 if (op
->getOpcode() != BO_Assign
) {
1905 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1910 ref
= cast
<DeclRefExpr
>(lhs
);
1911 if (ref
->getDecl() != iv
) {
1916 val
= extract_affine(op
->getRHS());
1918 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1920 dim
= isl_space_params_alloc(ctx
, 1);
1921 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1922 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1923 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1925 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
1930 /* Check that op is of the form iv += cst or iv -= cst
1931 * and return an affine expression corresponding oto cst or -cst accordingly.
1933 __isl_give isl_pw_aff
*PetScan::extract_compound_increment(
1934 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1940 BinaryOperatorKind opcode
;
1942 opcode
= op
->getOpcode();
1943 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1947 if (opcode
== BO_SubAssign
)
1951 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1956 ref
= cast
<DeclRefExpr
>(lhs
);
1957 if (ref
->getDecl() != iv
) {
1962 val
= extract_affine(op
->getRHS());
1964 val
= isl_pw_aff_neg(val
);
1969 /* Check that the increment of the given for loop increments
1970 * (or decrements) the induction variable "iv" and return
1971 * the increment as an affine expression if successful.
1973 __isl_give isl_pw_aff
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1976 Stmt
*inc
= stmt
->getInc();
1983 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1984 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1985 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1986 return extract_compound_increment(
1987 cast
<CompoundAssignOperator
>(inc
), iv
);
1988 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1989 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1995 /* Embed the given iteration domain in an extra outer loop
1996 * with induction variable "var".
1997 * If this variable appeared as a parameter in the constraints,
1998 * it is replaced by the new outermost dimension.
2000 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
2001 __isl_take isl_id
*var
)
2005 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
2006 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
2008 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
2009 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2016 /* Return those elements in the space of "cond" that come after
2017 * (based on "sign") an element in "cond".
2019 static __isl_give isl_set
*after(__isl_take isl_set
*cond
, int sign
)
2021 isl_map
*previous_to_this
;
2024 previous_to_this
= isl_map_lex_lt(isl_set_get_space(cond
));
2026 previous_to_this
= isl_map_lex_gt(isl_set_get_space(cond
));
2028 cond
= isl_set_apply(cond
, previous_to_this
);
2033 /* Create the infinite iteration domain
2035 * { [id] : id >= 0 }
2037 * If "scop" has an affine skip of type pet_skip_later,
2038 * then remove those iterations i that have an earlier iteration
2039 * where the skip condition is satisfied, meaning that iteration i
2041 * Since we are dealing with a loop without loop iterator,
2042 * the skip condition cannot refer to the current loop iterator and
2043 * so effectively, the returned set is of the form
2045 * { [0]; [id] : id >= 1 and not skip }
2047 static __isl_give isl_set
*infinite_domain(__isl_take isl_id
*id
,
2048 struct pet_scop
*scop
)
2050 isl_ctx
*ctx
= isl_id_get_ctx(id
);
2054 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
2055 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, id
);
2057 if (!pet_scop_has_affine_skip(scop
, pet_skip_later
))
2060 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
2061 skip
= embed(skip
, isl_id_copy(id
));
2062 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2063 domain
= isl_set_subtract(domain
, after(skip
, 1));
2068 /* Create an identity affine expression on the space containing "domain",
2069 * which is assumed to be one-dimensional.
2071 static __isl_give isl_aff
*identity_aff(__isl_keep isl_set
*domain
)
2073 isl_local_space
*ls
;
2075 ls
= isl_local_space_from_space(isl_set_get_space(domain
));
2076 return isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
2079 /* Create a map that maps elements of a single-dimensional array "id_test"
2080 * to the previous element (according to "inc"), provided this element
2081 * belongs to "domain". That is, create the map
2083 * { id[x] -> id[x - inc] : x - inc in domain }
2085 static __isl_give isl_map
*map_to_previous(__isl_take isl_id
*id_test
,
2086 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2089 isl_local_space
*ls
;
2093 space
= isl_set_get_space(domain
);
2094 ls
= isl_local_space_from_space(space
);
2095 aff
= isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
2096 aff
= isl_aff_add_constant_val(aff
, isl_val_neg(inc
));
2097 prev
= isl_map_from_aff(aff
);
2098 prev
= isl_map_intersect_range(prev
, domain
);
2099 prev
= isl_map_set_tuple_id(prev
, isl_dim_out
, id_test
);
2104 /* Add an implication to "scop" expressing that if an element of
2105 * virtual array "id_test" has value "satisfied" then all previous elements
2106 * of this array also have that value. The set of previous elements
2107 * is bounded by "domain". If "sign" is negative then iterator
2108 * is decreasing and we express that all subsequent array elements
2109 * (but still defined previously) have the same value.
2111 static struct pet_scop
*add_implication(struct pet_scop
*scop
,
2112 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
, int sign
,
2118 domain
= isl_set_set_tuple_id(domain
, id_test
);
2119 space
= isl_set_get_space(domain
);
2121 map
= isl_map_lex_ge(space
);
2123 map
= isl_map_lex_le(space
);
2124 map
= isl_map_intersect_range(map
, domain
);
2125 scop
= pet_scop_add_implication(scop
, map
, satisfied
);
2130 /* Add a filter to "scop" that imposes that it is only executed
2131 * when the variable identified by "id_test" has a zero value
2132 * for all previous iterations of "domain".
2134 * In particular, add a filter that imposes that the array
2135 * has a zero value at the previous iteration of domain and
2136 * add an implication that implies that it then has that
2137 * value for all previous iterations.
2139 static struct pet_scop
*scop_add_break(struct pet_scop
*scop
,
2140 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
,
2141 __isl_take isl_val
*inc
)
2144 int sign
= isl_val_sgn(inc
);
2146 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
2147 scop
= add_implication(scop
, id_test
, domain
, sign
, 0);
2148 scop
= pet_scop_filter(scop
, prev
, 0);
2153 /* Construct a pet_scop for an infinite loop around the given body.
2155 * We extract a pet_scop for the body and then embed it in a loop with
2164 * If the body contains any break, then it is taken into
2165 * account in infinite_domain (if the skip condition is affine)
2166 * or in scop_add_break (if the skip condition is not affine).
2168 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
2170 isl_id
*id
, *id_test
;
2173 struct pet_scop
*scop
;
2176 scop
= extract(body
);
2180 id
= isl_id_alloc(ctx
, "t", NULL
);
2181 domain
= infinite_domain(isl_id_copy(id
), scop
);
2182 ident
= identity_aff(domain
);
2184 has_var_break
= pet_scop_has_var_skip(scop
, pet_skip_later
);
2186 id_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
2188 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
2189 isl_map_from_aff(isl_aff_copy(ident
)), ident
, id
);
2191 scop
= scop_add_break(scop
, id_test
, domain
, isl_val_one(ctx
));
2193 isl_set_free(domain
);
2198 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2204 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
2206 return extract_infinite_loop(stmt
->getBody());
2209 /* Create an index expression for an access to a virtual array
2210 * representing the result of a condition.
2211 * Unlike other accessed data, the id of the array is NULL as
2212 * there is no ValueDecl in the program corresponding to the virtual
2214 * The array starts out as a scalar, but grows along with the
2215 * statement writing to the array in pet_scop_embed.
2217 static __isl_give isl_multi_pw_aff
*create_test_index(isl_ctx
*ctx
, int test_nr
)
2219 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, 0);
2223 snprintf(name
, sizeof(name
), "__pet_test_%d", test_nr
);
2224 id
= isl_id_alloc(ctx
, name
, NULL
);
2225 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
2226 return isl_multi_pw_aff_zero(dim
);
2229 /* Create an access to a virtual array representing the result
2232 static __isl_give isl_map
*create_test_access(isl_ctx
*ctx
, int test_nr
)
2234 return isl_map_from_multi_pw_aff(create_test_index(ctx
, test_nr
));
2237 /* Add an array with the given extent ("access") to the list
2238 * of arrays in "scop" and return the extended pet_scop.
2239 * The array is marked as attaining values 0 and 1 only and
2240 * as each element being assigned at most once.
2242 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2243 __isl_keep isl_map
*access
, clang::ASTContext
&ast_ctx
)
2245 isl_ctx
*ctx
= isl_map_get_ctx(access
);
2247 struct pet_array
*array
;
2254 array
= isl_calloc_type(ctx
, struct pet_array
);
2258 array
->extent
= isl_map_range(isl_map_copy(access
));
2259 dim
= isl_space_params_alloc(ctx
, 0);
2260 array
->context
= isl_set_universe(dim
);
2261 dim
= isl_space_set_alloc(ctx
, 0, 1);
2262 array
->value_bounds
= isl_set_universe(dim
);
2263 array
->value_bounds
= isl_set_lower_bound_si(array
->value_bounds
,
2265 array
->value_bounds
= isl_set_upper_bound_si(array
->value_bounds
,
2267 array
->element_type
= strdup("int");
2268 array
->element_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
2269 array
->uniquely_defined
= 1;
2271 if (!array
->extent
|| !array
->context
)
2272 array
= pet_array_free(array
);
2274 scop
= pet_scop_add_array(scop
, array
);
2278 pet_scop_free(scop
);
2282 /* Construct a pet_scop for a while loop of the form
2287 * In particular, construct a scop for an infinite loop around body and
2288 * intersect the domain with the affine expression.
2289 * Note that this intersection may result in an empty loop.
2291 struct pet_scop
*PetScan::extract_affine_while(__isl_take isl_pw_aff
*pa
,
2294 struct pet_scop
*scop
;
2298 valid
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2299 dom
= isl_pw_aff_non_zero_set(pa
);
2300 scop
= extract_infinite_loop(body
);
2301 scop
= pet_scop_restrict(scop
, dom
);
2302 scop
= pet_scop_restrict_context(scop
, valid
);
2307 /* Construct a scop for a while, given the scops for the condition
2308 * and the body, the filter identifier and the iteration domain of
2311 * In particular, the scop for the condition is filtered to depend
2312 * on "id_test" evaluating to true for all previous iterations
2313 * of the loop, while the scop for the body is filtered to depend
2314 * on "id_test" evaluating to true for all iterations up to the
2315 * current iteration.
2316 * The actual filter only imposes that this virtual array has
2317 * value one on the previous or the current iteration.
2318 * The fact that this condition also applies to the previous
2319 * iterations is enforced by an implication.
2321 * These filtered scops are then combined into a single scop.
2323 * "sign" is positive if the iterator increases and negative
2326 static struct pet_scop
*scop_add_while(struct pet_scop
*scop_cond
,
2327 struct pet_scop
*scop_body
, __isl_take isl_id
*id_test
,
2328 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2330 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
2332 isl_map
*test_access
;
2334 int sign
= isl_val_sgn(inc
);
2335 struct pet_scop
*scop
;
2337 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
2338 scop_cond
= pet_scop_filter(scop_cond
, prev
, 1);
2340 space
= isl_space_map_from_set(isl_set_get_space(domain
));
2341 test_access
= isl_map_identity(space
);
2342 test_access
= isl_map_set_tuple_id(test_access
, isl_dim_out
,
2343 isl_id_copy(id_test
));
2344 scop_body
= pet_scop_filter(scop_body
, test_access
, 1);
2346 scop
= pet_scop_add_seq(ctx
, scop_cond
, scop_body
);
2347 scop
= add_implication(scop
, id_test
, domain
, sign
, 1);
2352 /* Check if the while loop is of the form
2354 * while (affine expression)
2357 * If so, call extract_affine_while to construct a scop.
2359 * Otherwise, construct a generic while scop, with iteration domain
2360 * { [t] : t >= 0 }. The scop consists of two parts, one for
2361 * evaluating the condition and one for the body.
2362 * The schedule is adjusted to reflect that the condition is evaluated
2363 * before the body is executed and the body is filtered to depend
2364 * on the result of the condition evaluating to true on all iterations
2365 * up to the current iteration, while the evaluation the condition itself
2366 * is filtered to depend on the result of the condition evaluating to true
2367 * on all previous iterations.
2368 * The context of the scop representing the body is dropped
2369 * because we don't know how many times the body will be executed,
2372 * If the body contains any break, then it is taken into
2373 * account in infinite_domain (if the skip condition is affine)
2374 * or in scop_add_break (if the skip condition is not affine).
2376 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
2379 isl_id
*id
, *id_test
, *id_break_test
;
2380 isl_map
*test_access
;
2384 struct pet_scop
*scop
, *scop_body
;
2387 cond
= stmt
->getCond();
2393 clear_assignments
clear(assigned_value
);
2394 clear
.TraverseStmt(stmt
->getBody());
2396 pa
= try_extract_affine_condition(cond
);
2398 return extract_affine_while(pa
, stmt
->getBody());
2400 if (!allow_nested
) {
2405 test_access
= create_test_access(ctx
, n_test
++);
2406 scop
= extract_non_affine_condition(cond
, isl_map_copy(test_access
));
2407 scop
= scop_add_array(scop
, test_access
, ast_context
);
2408 id_test
= isl_map_get_tuple_id(test_access
, isl_dim_out
);
2409 isl_map_free(test_access
);
2410 scop_body
= extract(stmt
->getBody());
2412 id
= isl_id_alloc(ctx
, "t", NULL
);
2413 domain
= infinite_domain(isl_id_copy(id
), scop_body
);
2414 ident
= identity_aff(domain
);
2416 has_var_break
= pet_scop_has_var_skip(scop_body
, pet_skip_later
);
2418 id_break_test
= pet_scop_get_skip_id(scop_body
, pet_skip_later
);
2420 scop
= pet_scop_prefix(scop
, 0);
2421 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
2422 isl_map_from_aff(isl_aff_copy(ident
)),
2423 isl_aff_copy(ident
), isl_id_copy(id
));
2424 scop_body
= pet_scop_reset_context(scop_body
);
2425 scop_body
= pet_scop_prefix(scop_body
, 1);
2426 scop_body
= pet_scop_embed(scop_body
, isl_set_copy(domain
),
2427 isl_map_from_aff(isl_aff_copy(ident
)), ident
, id
);
2429 if (has_var_break
) {
2430 scop
= scop_add_break(scop
, isl_id_copy(id_break_test
),
2431 isl_set_copy(domain
), isl_val_one(ctx
));
2432 scop_body
= scop_add_break(scop_body
, id_break_test
,
2433 isl_set_copy(domain
), isl_val_one(ctx
));
2435 scop
= scop_add_while(scop
, scop_body
, id_test
, domain
,
2441 /* Check whether "cond" expresses a simple loop bound
2442 * on the only set dimension.
2443 * In particular, if "up" is set then "cond" should contain only
2444 * upper bounds on the set dimension.
2445 * Otherwise, it should contain only lower bounds.
2447 static bool is_simple_bound(__isl_keep isl_set
*cond
, __isl_keep isl_val
*inc
)
2449 if (isl_val_is_pos(inc
))
2450 return !isl_set_dim_has_any_lower_bound(cond
, isl_dim_set
, 0);
2452 return !isl_set_dim_has_any_upper_bound(cond
, isl_dim_set
, 0);
2455 /* Extend a condition on a given iteration of a loop to one that
2456 * imposes the same condition on all previous iterations.
2457 * "domain" expresses the lower [upper] bound on the iterations
2458 * when inc is positive [negative].
2460 * In particular, we construct the condition (when inc is positive)
2462 * forall i' : (domain(i') and i' <= i) => cond(i')
2464 * which is equivalent to
2466 * not exists i' : domain(i') and i' <= i and not cond(i')
2468 * We construct this set by negating cond, applying a map
2470 * { [i'] -> [i] : domain(i') and i' <= i }
2472 * and then negating the result again.
2474 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
2475 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2477 isl_map
*previous_to_this
;
2479 if (isl_val_is_pos(inc
))
2480 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
2482 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
2484 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
2486 cond
= isl_set_complement(cond
);
2487 cond
= isl_set_apply(cond
, previous_to_this
);
2488 cond
= isl_set_complement(cond
);
2495 /* Construct a domain of the form
2497 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2499 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
2500 __isl_take isl_pw_aff
*init
, __isl_take isl_val
*inc
)
2506 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
2507 dim
= isl_pw_aff_get_domain_space(init
);
2508 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2509 aff
= isl_aff_add_coefficient_val(aff
, isl_dim_in
, 0, inc
);
2510 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2512 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2513 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2514 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2515 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2517 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2519 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2521 return isl_set_params(set
);
2524 /* Assuming "cond" represents a bound on a loop where the loop
2525 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2528 * Under the given assumptions, wrapping is only possible if "cond" allows
2529 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2530 * increasing iterator and 0 in case of a decreasing iterator.
2532 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
,
2533 __isl_keep isl_val
*inc
)
2540 test
= isl_set_copy(cond
);
2542 ctx
= isl_set_get_ctx(test
);
2543 if (isl_val_is_neg(inc
))
2544 limit
= isl_val_zero(ctx
);
2546 limit
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2547 limit
= isl_val_2exp(limit
);
2548 limit
= isl_val_sub_ui(limit
, 1);
2551 test
= isl_set_fix_val(cond
, isl_dim_set
, 0, limit
);
2552 cw
= !isl_set_is_empty(test
);
2558 /* Given a one-dimensional space, construct the following affine expression
2561 * { [v] -> [v mod 2^width] }
2563 * where width is the number of bits used to represent the values
2564 * of the unsigned variable "iv".
2566 static __isl_give isl_aff
*compute_wrapping(__isl_take isl_space
*dim
,
2574 ctx
= isl_space_get_ctx(dim
);
2575 mod
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2576 mod
= isl_val_2exp(mod
);
2578 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2579 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2580 aff
= isl_aff_mod_val(aff
, mod
);
2585 /* Project out the parameter "id" from "set".
2587 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2588 __isl_keep isl_id
*id
)
2592 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2594 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2599 /* Compute the set of parameters for which "set1" is a subset of "set2".
2601 * set1 is a subset of set2 if
2603 * forall i in set1 : i in set2
2607 * not exists i in set1 and i not in set2
2611 * not exists i in set1 \ set2
2613 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2614 __isl_take isl_set
*set2
)
2616 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2619 /* Compute the set of parameter values for which "cond" holds
2620 * on the next iteration for each element of "dom".
2622 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2623 * and then compute the set of parameters for which the result is a subset
2626 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2627 __isl_take isl_set
*dom
, __isl_take isl_val
*inc
)
2633 space
= isl_set_get_space(dom
);
2634 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2635 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2636 aff
= isl_aff_add_constant_val(aff
, inc
);
2637 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2639 dom
= isl_set_apply(dom
, next
);
2641 return enforce_subset(dom
, cond
);
2644 /* Does "id" refer to a nested access?
2646 static bool is_nested_parameter(__isl_keep isl_id
*id
)
2648 return id
&& isl_id_get_user(id
) && !isl_id_get_name(id
);
2651 /* Does parameter "pos" of "space" refer to a nested access?
2653 static bool is_nested_parameter(__isl_keep isl_space
*space
, int pos
)
2658 id
= isl_space_get_dim_id(space
, isl_dim_param
, pos
);
2659 nested
= is_nested_parameter(id
);
2665 /* Does "space" involve any parameters that refer to nested
2666 * accesses, i.e., parameters with no name?
2668 static bool has_nested(__isl_keep isl_space
*space
)
2672 nparam
= isl_space_dim(space
, isl_dim_param
);
2673 for (int i
= 0; i
< nparam
; ++i
)
2674 if (is_nested_parameter(space
, i
))
2680 /* Does "pa" involve any parameters that refer to nested
2681 * accesses, i.e., parameters with no name?
2683 static bool has_nested(__isl_keep isl_pw_aff
*pa
)
2688 space
= isl_pw_aff_get_space(pa
);
2689 nested
= has_nested(space
);
2690 isl_space_free(space
);
2695 /* Construct a pet_scop for a for statement.
2696 * The for loop is required to be of the form
2698 * for (i = init; condition; ++i)
2702 * for (i = init; condition; --i)
2704 * The initialization of the for loop should either be an assignment
2705 * to an integer variable, or a declaration of such a variable with
2708 * The condition is allowed to contain nested accesses, provided
2709 * they are not being written to inside the body of the loop.
2710 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2711 * essentially treated as a while loop, with iteration domain
2712 * { [i] : i >= init }.
2714 * We extract a pet_scop for the body and then embed it in a loop with
2715 * iteration domain and schedule
2717 * { [i] : i >= init and condition' }
2722 * { [i] : i <= init and condition' }
2725 * Where condition' is equal to condition if the latter is
2726 * a simple upper [lower] bound and a condition that is extended
2727 * to apply to all previous iterations otherwise.
2729 * If the condition is non-affine, then we drop the condition from the
2730 * iteration domain and instead create a separate statement
2731 * for evaluating the condition. The body is then filtered to depend
2732 * on the result of the condition evaluating to true on all iterations
2733 * up to the current iteration, while the evaluation the condition itself
2734 * is filtered to depend on the result of the condition evaluating to true
2735 * on all previous iterations.
2736 * The context of the scop representing the body is dropped
2737 * because we don't know how many times the body will be executed,
2740 * If the stride of the loop is not 1, then "i >= init" is replaced by
2742 * (exists a: i = init + stride * a and a >= 0)
2744 * If the loop iterator i is unsigned, then wrapping may occur.
2745 * During the computation, we work with a virtual iterator that
2746 * does not wrap. However, the condition in the code applies
2747 * to the wrapped value, so we need to change condition(i)
2748 * into condition([i % 2^width]).
2749 * After computing the virtual domain and schedule, we apply
2750 * the function { [v] -> [v % 2^width] } to the domain and the domain
2751 * of the schedule. In order not to lose any information, we also
2752 * need to intersect the domain of the schedule with the virtual domain
2753 * first, since some iterations in the wrapped domain may be scheduled
2754 * several times, typically an infinite number of times.
2755 * Note that there may be no need to perform this final wrapping
2756 * if the loop condition (after wrapping) satisfies certain conditions.
2757 * However, the is_simple_bound condition is not enough since it doesn't
2758 * check if there even is an upper bound.
2760 * If the loop condition is non-affine, then we keep the virtual
2761 * iterator in the iteration domain and instead replace all accesses
2762 * to the original iterator by the wrapping of the virtual iterator.
2764 * Wrapping on unsigned iterators can be avoided entirely if
2765 * loop condition is simple, the loop iterator is incremented
2766 * [decremented] by one and the last value before wrapping cannot
2767 * possibly satisfy the loop condition.
2769 * Before extracting a pet_scop from the body we remove all
2770 * assignments in assigned_value to variables that are assigned
2771 * somewhere in the body of the loop.
2773 * Valid parameters for a for loop are those for which the initial
2774 * value itself, the increment on each domain iteration and
2775 * the condition on both the initial value and
2776 * the result of incrementing the iterator for each iteration of the domain
2778 * If the loop condition is non-affine, then we only consider validity
2779 * of the initial value.
2781 * If the body contains any break, then we keep track of it in "skip"
2782 * (if the skip condition is affine) or it is handled in scop_add_break
2783 * (if the skip condition is not affine).
2784 * Note that the affine break condition needs to be considered with
2785 * respect to previous iterations in the virtual domain (if any)
2786 * and that the domain needs to be kept virtual if there is a non-affine
2789 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2791 BinaryOperator
*ass
;
2799 isl_set
*cond
= NULL
;
2800 isl_set
*skip
= NULL
;
2801 isl_id
*id
, *id_test
= NULL
, *id_break_test
;
2802 struct pet_scop
*scop
, *scop_cond
= NULL
;
2803 assigned_value_cache
cache(assigned_value
);
2809 bool keep_virtual
= false;
2810 bool has_affine_break
;
2812 isl_aff
*wrap
= NULL
;
2813 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2814 isl_set
*valid_init
;
2815 isl_set
*valid_cond
;
2816 isl_set
*valid_cond_init
;
2817 isl_set
*valid_cond_next
;
2821 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2822 return extract_infinite_for(stmt
);
2824 init
= stmt
->getInit();
2829 if ((ass
= initialization_assignment(init
)) != NULL
) {
2830 iv
= extract_induction_variable(ass
);
2833 lhs
= ass
->getLHS();
2834 rhs
= ass
->getRHS();
2835 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2836 VarDecl
*var
= extract_induction_variable(init
, decl
);
2840 rhs
= var
->getInit();
2841 lhs
= create_DeclRefExpr(var
);
2843 unsupported(stmt
->getInit());
2847 pa_inc
= extract_increment(stmt
, iv
);
2852 if (isl_pw_aff_n_piece(pa_inc
) != 1 ||
2853 isl_pw_aff_foreach_piece(pa_inc
, &extract_cst
, &inc
) < 0) {
2854 isl_pw_aff_free(pa_inc
);
2855 unsupported(stmt
->getInc());
2859 valid_inc
= isl_pw_aff_domain(pa_inc
);
2861 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2863 assigned_value
.erase(iv
);
2864 clear_assignments
clear(assigned_value
);
2865 clear
.TraverseStmt(stmt
->getBody());
2867 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
2869 pa
= try_extract_nested_condition(stmt
->getCond());
2870 if (allow_nested
&& (!pa
|| has_nested(pa
)))
2873 scop
= extract(stmt
->getBody());
2875 has_affine_break
= scop
&&
2876 pet_scop_has_affine_skip(scop
, pet_skip_later
);
2877 if (has_affine_break
)
2878 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
2879 has_var_break
= scop
&& pet_scop_has_var_skip(scop
, pet_skip_later
);
2880 if (has_var_break
) {
2881 id_break_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
2882 keep_virtual
= true;
2885 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2886 isl_pw_aff_free(pa
);
2890 if (!allow_nested
&& !pa
)
2891 pa
= try_extract_affine_condition(stmt
->getCond());
2892 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2893 cond
= isl_pw_aff_non_zero_set(pa
);
2894 if (allow_nested
&& !cond
) {
2895 isl_map
*test_access
;
2896 int save_n_stmt
= n_stmt
;
2897 test_access
= create_test_access(ctx
, n_test
++);
2899 scop_cond
= extract_non_affine_condition(stmt
->getCond(),
2900 isl_map_copy(test_access
));
2901 n_stmt
= save_n_stmt
;
2902 scop_cond
= scop_add_array(scop_cond
, test_access
, ast_context
);
2903 id_test
= isl_map_get_tuple_id(test_access
, isl_dim_out
);
2904 isl_map_free(test_access
);
2905 scop_cond
= pet_scop_prefix(scop_cond
, 0);
2906 scop
= pet_scop_reset_context(scop
);
2907 scop
= pet_scop_prefix(scop
, 1);
2908 keep_virtual
= true;
2909 cond
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2912 cond
= embed(cond
, isl_id_copy(id
));
2913 skip
= embed(skip
, isl_id_copy(id
));
2914 valid_cond
= isl_set_coalesce(valid_cond
);
2915 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
2916 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
2917 is_one
= isl_val_is_one(inc
) || isl_val_is_negone(inc
);
2918 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2920 init_val
= extract_affine(rhs
);
2921 valid_cond_init
= enforce_subset(
2922 isl_set_from_pw_aff(isl_pw_aff_copy(init_val
)),
2923 isl_set_copy(valid_cond
));
2924 if (is_one
&& !is_virtual
) {
2925 isl_pw_aff_free(init_val
);
2926 pa
= extract_comparison(isl_val_is_pos(inc
) ? BO_GE
: BO_LE
,
2928 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2929 valid_init
= set_project_out_by_id(valid_init
, id
);
2930 domain
= isl_pw_aff_non_zero_set(pa
);
2932 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
2933 domain
= strided_domain(isl_id_copy(id
), init_val
,
2937 domain
= embed(domain
, isl_id_copy(id
));
2940 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2941 rev_wrap
= isl_map_from_aff(isl_aff_copy(wrap
));
2942 rev_wrap
= isl_map_reverse(rev_wrap
);
2943 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
2944 skip
= isl_set_apply(skip
, isl_map_copy(rev_wrap
));
2945 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
2946 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
2948 is_simple
= is_simple_bound(cond
, inc
);
2950 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2951 is_simple
= is_simple_bound(cond
, inc
);
2954 cond
= valid_for_each_iteration(cond
,
2955 isl_set_copy(domain
), isl_val_copy(inc
));
2956 domain
= isl_set_intersect(domain
, cond
);
2957 if (has_affine_break
) {
2958 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2959 skip
= after(skip
, isl_val_sgn(inc
));
2960 domain
= isl_set_subtract(domain
, skip
);
2962 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2963 space
= isl_space_from_domain(isl_set_get_space(domain
));
2964 space
= isl_space_add_dims(space
, isl_dim_out
, 1);
2965 sched
= isl_map_universe(space
);
2966 if (isl_val_is_pos(inc
))
2967 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2969 sched
= isl_map_oppose(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2971 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
),
2973 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
2975 if (is_virtual
&& !keep_virtual
) {
2976 isl_map
*wrap_map
= isl_map_from_aff(wrap
);
2977 wrap_map
= isl_map_set_dim_id(wrap_map
,
2978 isl_dim_out
, 0, isl_id_copy(id
));
2979 sched
= isl_map_intersect_domain(sched
, isl_set_copy(domain
));
2980 domain
= isl_set_apply(domain
, isl_map_copy(wrap_map
));
2981 sched
= isl_map_apply_domain(sched
, wrap_map
);
2983 if (!(is_virtual
&& keep_virtual
))
2984 wrap
= identity_aff(domain
);
2986 scop_cond
= pet_scop_embed(scop_cond
, isl_set_copy(domain
),
2987 isl_map_copy(sched
), isl_aff_copy(wrap
), isl_id_copy(id
));
2988 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), sched
, wrap
, id
);
2989 scop
= resolve_nested(scop
);
2991 scop
= scop_add_break(scop
, id_break_test
, isl_set_copy(domain
),
2994 scop
= scop_add_while(scop_cond
, scop
, id_test
, domain
,
2996 isl_set_free(valid_inc
);
2998 scop
= pet_scop_restrict_context(scop
, valid_inc
);
2999 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
3000 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
3001 isl_set_free(domain
);
3003 clear_assignment(assigned_value
, iv
);
3007 scop
= pet_scop_restrict_context(scop
, valid_init
);
3012 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
, bool skip_declarations
)
3014 return extract(stmt
->children(), true, skip_declarations
);
3017 /* Does parameter "pos" of "map" refer to a nested access?
3019 static bool is_nested_parameter(__isl_keep isl_map
*map
, int pos
)
3024 id
= isl_map_get_dim_id(map
, isl_dim_param
, pos
);
3025 nested
= is_nested_parameter(id
);
3031 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
3033 static int n_nested_parameter(__isl_keep isl_space
*space
)
3038 nparam
= isl_space_dim(space
, isl_dim_param
);
3039 for (int i
= 0; i
< nparam
; ++i
)
3040 if (is_nested_parameter(space
, i
))
3046 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
3048 static int n_nested_parameter(__isl_keep isl_map
*map
)
3053 space
= isl_map_get_space(map
);
3054 n
= n_nested_parameter(space
);
3055 isl_space_free(space
);
3060 /* For each nested access parameter in "space",
3061 * construct a corresponding pet_expr, place it in args and
3062 * record its position in "param2pos".
3063 * "n_arg" is the number of elements that are already in args.
3064 * The position recorded in "param2pos" takes this number into account.
3065 * If the pet_expr corresponding to a parameter is identical to
3066 * the pet_expr corresponding to an earlier parameter, then these two
3067 * parameters are made to refer to the same element in args.
3069 * Return the final number of elements in args or -1 if an error has occurred.
3071 int PetScan::extract_nested(__isl_keep isl_space
*space
,
3072 int n_arg
, struct pet_expr
**args
, std::map
<int,int> ¶m2pos
)
3076 nparam
= isl_space_dim(space
, isl_dim_param
);
3077 for (int i
= 0; i
< nparam
; ++i
) {
3079 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
3082 if (!is_nested_parameter(id
)) {
3087 nested
= (Expr
*) isl_id_get_user(id
);
3088 args
[n_arg
] = extract_expr(nested
);
3092 for (j
= 0; j
< n_arg
; ++j
)
3093 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
3097 pet_expr_free(args
[n_arg
]);
3101 param2pos
[i
] = n_arg
++;
3109 /* For each nested access parameter in the access relations in "expr",
3110 * construct a corresponding pet_expr, place it in expr->args and
3111 * record its position in "param2pos".
3112 * n is the number of nested access parameters.
3114 struct pet_expr
*PetScan::extract_nested(struct pet_expr
*expr
, int n
,
3115 std::map
<int,int> ¶m2pos
)
3119 expr
->args
= isl_calloc_array(ctx
, struct pet_expr
*, n
);
3124 space
= isl_map_get_space(expr
->acc
.access
);
3125 n
= extract_nested(space
, 0, expr
->args
, param2pos
);
3126 isl_space_free(space
);
3134 pet_expr_free(expr
);
3138 /* Look for parameters in any access relation in "expr" that
3139 * refer to nested accesses. In particular, these are
3140 * parameters with no name.
3142 * If there are any such parameters, then the domain of the access
3143 * relation, which is still [] at this point, is replaced by
3144 * [[] -> [t_1,...,t_n]], with n the number of these parameters
3145 * (after identifying identical nested accesses).
3146 * The parameters are then equated to the corresponding t dimensions
3147 * and subsequently projected out.
3148 * param2pos maps the position of the parameter to the position
3149 * of the corresponding t dimension.
3151 struct pet_expr
*PetScan::resolve_nested(struct pet_expr
*expr
)
3158 std::map
<int,int> param2pos
;
3163 for (int i
= 0; i
< expr
->n_arg
; ++i
) {
3164 expr
->args
[i
] = resolve_nested(expr
->args
[i
]);
3165 if (!expr
->args
[i
]) {
3166 pet_expr_free(expr
);
3171 if (expr
->type
!= pet_expr_access
)
3174 n
= n_nested_parameter(expr
->acc
.access
);
3178 expr
= extract_nested(expr
, n
, param2pos
);
3183 nparam
= isl_map_dim(expr
->acc
.access
, isl_dim_param
);
3184 n_in
= isl_map_dim(expr
->acc
.access
, isl_dim_in
);
3185 dim
= isl_map_get_space(expr
->acc
.access
);
3186 dim
= isl_space_domain(dim
);
3187 dim
= isl_space_from_domain(dim
);
3188 dim
= isl_space_add_dims(dim
, isl_dim_out
, n
);
3189 map
= isl_map_universe(dim
);
3190 map
= isl_map_domain_map(map
);
3191 map
= isl_map_reverse(map
);
3192 expr
->acc
.access
= isl_map_apply_domain(expr
->acc
.access
, map
);
3194 for (int i
= nparam
- 1; i
>= 0; --i
) {
3195 isl_id
*id
= isl_map_get_dim_id(expr
->acc
.access
,
3197 if (!is_nested_parameter(id
)) {
3202 expr
->acc
.access
= isl_map_equate(expr
->acc
.access
,
3203 isl_dim_param
, i
, isl_dim_in
,
3204 n_in
+ param2pos
[i
]);
3205 expr
->acc
.access
= isl_map_project_out(expr
->acc
.access
,
3206 isl_dim_param
, i
, 1);
3213 pet_expr_free(expr
);
3217 /* Return the file offset of the expansion location of "Loc".
3219 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
3221 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
3224 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3226 /* Return a SourceLocation for the location after the first semicolon
3227 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3228 * call it and also skip trailing spaces and newline.
3230 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3231 const LangOptions
&LO
)
3233 return Lexer::findLocationAfterToken(loc
, tok::semi
, SM
, LO
, true);
3238 /* Return a SourceLocation for the location after the first semicolon
3239 * after "loc". If Lexer::findLocationAfterToken is not available,
3240 * we look in the underlying character data for the first semicolon.
3242 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3243 const LangOptions
&LO
)
3246 const char *s
= SM
.getCharacterData(loc
);
3248 semi
= strchr(s
, ';');
3250 return SourceLocation();
3251 return loc
.getFileLocWithOffset(semi
+ 1 - s
);
3256 /* If the token at "loc" is the first token on the line, then return
3257 * a location referring to the start of the line.
3258 * Otherwise, return "loc".
3260 * This function is used to extend a scop to the start of the line
3261 * if the first token of the scop is also the first token on the line.
3263 * We look for the first token on the line. If its location is equal to "loc",
3264 * then the latter is the location of the first token on the line.
3266 static SourceLocation
move_to_start_of_line_if_first_token(SourceLocation loc
,
3267 SourceManager
&SM
, const LangOptions
&LO
)
3269 std::pair
<FileID
, unsigned> file_offset_pair
;
3270 llvm::StringRef file
;
3273 SourceLocation token_loc
, line_loc
;
3276 loc
= SM
.getExpansionLoc(loc
);
3277 col
= SM
.getExpansionColumnNumber(loc
);
3278 line_loc
= loc
.getLocWithOffset(1 - col
);
3279 file_offset_pair
= SM
.getDecomposedLoc(line_loc
);
3280 file
= SM
.getBufferData(file_offset_pair
.first
, NULL
);
3281 pos
= file
.data() + file_offset_pair
.second
;
3283 Lexer
lexer(SM
.getLocForStartOfFile(file_offset_pair
.first
), LO
,
3284 file
.begin(), pos
, file
.end());
3285 lexer
.LexFromRawLexer(tok
);
3286 token_loc
= tok
.getLocation();
3288 if (token_loc
== loc
)
3294 /* Convert a top-level pet_expr to a pet_scop with one statement.
3295 * This mainly involves resolving nested expression parameters
3296 * and setting the name of the iteration space.
3297 * The name is given by "label" if it is non-NULL. Otherwise,
3298 * it is of the form S_<n_stmt>.
3299 * start and end of the pet_scop are derived from those of "stmt".
3301 struct pet_scop
*PetScan::extract(Stmt
*stmt
, struct pet_expr
*expr
,
3302 __isl_take isl_id
*label
)
3304 struct pet_stmt
*ps
;
3305 struct pet_scop
*scop
;
3306 SourceLocation loc
= stmt
->getLocStart();
3307 SourceManager
&SM
= PP
.getSourceManager();
3308 const LangOptions
&LO
= PP
.getLangOpts();
3309 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3310 unsigned start
, end
;
3312 expr
= resolve_nested(expr
);
3313 ps
= pet_stmt_from_pet_expr(ctx
, line
, label
, n_stmt
++, expr
);
3314 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3316 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
);
3317 start
= getExpansionOffset(SM
, loc
);
3318 loc
= stmt
->getLocEnd();
3319 loc
= location_after_semi(loc
, SM
, LO
);
3320 end
= getExpansionOffset(SM
, loc
);
3322 scop
= pet_scop_update_start_end(scop
, start
, end
);
3326 /* Check if we can extract an affine expression from "expr".
3327 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3328 * We turn on autodetection so that we won't generate any warnings
3329 * and turn off nesting, so that we won't accept any non-affine constructs.
3331 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
3334 int save_autodetect
= options
->autodetect
;
3335 bool save_nesting
= nesting_enabled
;
3337 options
->autodetect
= 1;
3338 nesting_enabled
= false;
3340 pwaff
= extract_affine(expr
);
3342 options
->autodetect
= save_autodetect
;
3343 nesting_enabled
= save_nesting
;
3348 /* Check whether "expr" is an affine expression.
3350 bool PetScan::is_affine(Expr
*expr
)
3354 pwaff
= try_extract_affine(expr
);
3355 isl_pw_aff_free(pwaff
);
3357 return pwaff
!= NULL
;
3360 /* Check if we can extract an affine constraint from "expr".
3361 * Return the constraint as an isl_set if we can and NULL otherwise.
3362 * We turn on autodetection so that we won't generate any warnings
3363 * and turn off nesting, so that we won't accept any non-affine constructs.
3365 __isl_give isl_pw_aff
*PetScan::try_extract_affine_condition(Expr
*expr
)
3368 int save_autodetect
= options
->autodetect
;
3369 bool save_nesting
= nesting_enabled
;
3371 options
->autodetect
= 1;
3372 nesting_enabled
= false;
3374 cond
= extract_condition(expr
);
3376 options
->autodetect
= save_autodetect
;
3377 nesting_enabled
= save_nesting
;
3382 /* Check whether "expr" is an affine constraint.
3384 bool PetScan::is_affine_condition(Expr
*expr
)
3388 cond
= try_extract_affine_condition(expr
);
3389 isl_pw_aff_free(cond
);
3391 return cond
!= NULL
;
3394 /* Check if we can extract a condition from "expr".
3395 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3396 * If allow_nested is set, then the condition may involve parameters
3397 * corresponding to nested accesses.
3398 * We turn on autodetection so that we won't generate any warnings.
3400 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
3403 int save_autodetect
= options
->autodetect
;
3404 bool save_nesting
= nesting_enabled
;
3406 options
->autodetect
= 1;
3407 nesting_enabled
= allow_nested
;
3408 cond
= extract_condition(expr
);
3410 options
->autodetect
= save_autodetect
;
3411 nesting_enabled
= save_nesting
;
3416 /* If the top-level expression of "stmt" is an assignment, then
3417 * return that assignment as a BinaryOperator.
3418 * Otherwise return NULL.
3420 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
3422 BinaryOperator
*ass
;
3426 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
3429 ass
= cast
<BinaryOperator
>(stmt
);
3430 if(ass
->getOpcode() != BO_Assign
)
3436 /* Check if the given if statement is a conditional assignement
3437 * with a non-affine condition. If so, construct a pet_scop
3438 * corresponding to this conditional assignment. Otherwise return NULL.
3440 * In particular we check if "stmt" is of the form
3447 * where a is some array or scalar access.
3448 * The constructed pet_scop then corresponds to the expression
3450 * a = condition ? f(...) : g(...)
3452 * All access relations in f(...) are intersected with condition
3453 * while all access relation in g(...) are intersected with the complement.
3455 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
3457 BinaryOperator
*ass_then
, *ass_else
;
3458 isl_map
*write_then
, *write_else
;
3459 isl_set
*cond
, *comp
;
3463 struct pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
3464 bool save_nesting
= nesting_enabled
;
3466 if (!options
->detect_conditional_assignment
)
3469 ass_then
= top_assignment_or_null(stmt
->getThen());
3470 ass_else
= top_assignment_or_null(stmt
->getElse());
3472 if (!ass_then
|| !ass_else
)
3475 if (is_affine_condition(stmt
->getCond()))
3478 write_then
= extract_access(ass_then
->getLHS());
3479 write_else
= extract_access(ass_else
->getLHS());
3481 equal
= isl_map_is_equal(write_then
, write_else
);
3482 isl_map_free(write_else
);
3483 if (equal
< 0 || !equal
) {
3484 isl_map_free(write_then
);
3488 nesting_enabled
= allow_nested
;
3489 pa
= extract_condition(stmt
->getCond());
3490 nesting_enabled
= save_nesting
;
3491 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
3492 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
3493 map
= isl_map_from_range(isl_set_from_pw_aff(pa
));
3495 pe_cond
= pet_expr_from_access(map
);
3497 pe_then
= extract_expr(ass_then
->getRHS());
3498 pe_then
= pet_expr_restrict(pe_then
, cond
);
3499 pe_else
= extract_expr(ass_else
->getRHS());
3500 pe_else
= pet_expr_restrict(pe_else
, comp
);
3502 pe
= pet_expr_new_ternary(ctx
, pe_cond
, pe_then
, pe_else
);
3503 pe_write
= pet_expr_from_access(write_then
);
3505 pe_write
->acc
.write
= 1;
3506 pe_write
->acc
.read
= 0;
3508 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, pe_write
, pe
);
3509 return extract(stmt
, pe
);
3512 /* Create a pet_scop with a single statement evaluating "cond"
3513 * and writing the result to a virtual scalar, as expressed by
3516 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
,
3517 __isl_take isl_map
*access
)
3519 struct pet_expr
*expr
, *write
;
3520 struct pet_stmt
*ps
;
3521 struct pet_scop
*scop
;
3522 SourceLocation loc
= cond
->getLocStart();
3523 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3525 write
= pet_expr_from_access(access
);
3527 write
->acc
.write
= 1;
3528 write
->acc
.read
= 0;
3530 expr
= extract_expr(cond
);
3531 expr
= resolve_nested(expr
);
3532 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, write
, expr
);
3533 ps
= pet_stmt_from_pet_expr(ctx
, line
, NULL
, n_stmt
++, expr
);
3534 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3535 scop
= resolve_nested(scop
);
3541 static struct pet_expr
*embed_access(struct pet_expr
*expr
, void *user
);
3544 /* Apply the map pointed to by "user" to the domain of the access
3545 * relation associated to "expr", thereby embedding it in the range of the map.
3546 * The domain of both relations is the zero-dimensional domain.
3548 static struct pet_expr
*embed_access(struct pet_expr
*expr
, void *user
)
3550 isl_map
*map
= (isl_map
*) user
;
3552 expr
->acc
.access
= isl_map_apply_domain(expr
->acc
.access
,
3554 if (!expr
->acc
.access
)
3559 pet_expr_free(expr
);
3563 /* Apply "map" to all access relations in "expr".
3565 static struct pet_expr
*embed(struct pet_expr
*expr
, __isl_keep isl_map
*map
)
3567 return pet_expr_map_access(expr
, &embed_access
, map
);
3570 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3572 static int n_nested_parameter(__isl_keep isl_set
*set
)
3577 space
= isl_set_get_space(set
);
3578 n
= n_nested_parameter(space
);
3579 isl_space_free(space
);
3584 /* Remove all parameters from "map" that refer to nested accesses.
3586 static __isl_give isl_map
*remove_nested_parameters(__isl_take isl_map
*map
)
3591 space
= isl_map_get_space(map
);
3592 nparam
= isl_space_dim(space
, isl_dim_param
);
3593 for (int i
= nparam
- 1; i
>= 0; --i
)
3594 if (is_nested_parameter(space
, i
))
3595 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3596 isl_space_free(space
);
3601 /* Remove all parameters from the access relation of "expr"
3602 * that refer to nested accesses.
3604 static struct pet_expr
*remove_nested_parameters(struct pet_expr
*expr
)
3606 expr
->acc
.access
= remove_nested_parameters(expr
->acc
.access
);
3607 if (!expr
->acc
.access
)
3612 pet_expr_free(expr
);
3617 static struct pet_expr
*expr_remove_nested_parameters(
3618 struct pet_expr
*expr
, void *user
);
3621 static struct pet_expr
*expr_remove_nested_parameters(
3622 struct pet_expr
*expr
, void *user
)
3624 return remove_nested_parameters(expr
);
3627 /* Remove all nested access parameters from the schedule and all
3628 * accesses of "stmt".
3629 * There is no need to remove them from the domain as these parameters
3630 * have already been removed from the domain when this function is called.
3632 static struct pet_stmt
*remove_nested_parameters(struct pet_stmt
*stmt
)
3636 stmt
->schedule
= remove_nested_parameters(stmt
->schedule
);
3637 stmt
->body
= pet_expr_map_access(stmt
->body
,
3638 &expr_remove_nested_parameters
, NULL
);
3639 if (!stmt
->schedule
|| !stmt
->body
)
3641 for (int i
= 0; i
< stmt
->n_arg
; ++i
) {
3642 stmt
->args
[i
] = pet_expr_map_access(stmt
->args
[i
],
3643 &expr_remove_nested_parameters
, NULL
);
3650 pet_stmt_free(stmt
);
3654 /* For each nested access parameter in the domain of "stmt",
3655 * construct a corresponding pet_expr, place it before the original
3656 * elements in stmt->args and record its position in "param2pos".
3657 * n is the number of nested access parameters.
3659 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
3660 std::map
<int,int> ¶m2pos
)
3665 struct pet_expr
**args
;
3667 n_arg
= stmt
->n_arg
;
3668 args
= isl_calloc_array(ctx
, struct pet_expr
*, n
+ n_arg
);
3672 space
= isl_set_get_space(stmt
->domain
);
3673 n_arg
= extract_nested(space
, 0, args
, param2pos
);
3674 isl_space_free(space
);
3679 for (i
= 0; i
< stmt
->n_arg
; ++i
)
3680 args
[n_arg
+ i
] = stmt
->args
[i
];
3683 stmt
->n_arg
+= n_arg
;
3688 for (i
= 0; i
< n
; ++i
)
3689 pet_expr_free(args
[i
]);
3692 pet_stmt_free(stmt
);
3696 /* Check whether any of the arguments i of "stmt" starting at position "n"
3697 * is equal to one of the first "n" arguments j.
3698 * If so, combine the constraints on arguments i and j and remove
3701 static struct pet_stmt
*remove_duplicate_arguments(struct pet_stmt
*stmt
, int n
)
3710 if (n
== stmt
->n_arg
)
3713 map
= isl_set_unwrap(stmt
->domain
);
3715 for (i
= stmt
->n_arg
- 1; i
>= n
; --i
) {
3716 for (j
= 0; j
< n
; ++j
)
3717 if (pet_expr_is_equal(stmt
->args
[i
], stmt
->args
[j
]))
3722 map
= isl_map_equate(map
, isl_dim_out
, i
, isl_dim_out
, j
);
3723 map
= isl_map_project_out(map
, isl_dim_out
, i
, 1);
3725 pet_expr_free(stmt
->args
[i
]);
3726 for (j
= i
; j
+ 1 < stmt
->n_arg
; ++j
)
3727 stmt
->args
[j
] = stmt
->args
[j
+ 1];
3731 stmt
->domain
= isl_map_wrap(map
);
3736 pet_stmt_free(stmt
);
3740 /* Look for parameters in the iteration domain of "stmt" that
3741 * refer to nested accesses. In particular, these are
3742 * parameters with no name.
3744 * If there are any such parameters, then as many extra variables
3745 * (after identifying identical nested accesses) are inserted in the
3746 * range of the map wrapped inside the domain, before the original variables.
3747 * If the original domain is not a wrapped map, then a new wrapped
3748 * map is created with zero output dimensions.
3749 * The parameters are then equated to the corresponding output dimensions
3750 * and subsequently projected out, from the iteration domain,
3751 * the schedule and the access relations.
3752 * For each of the output dimensions, a corresponding argument
3753 * expression is inserted. Initially they are created with
3754 * a zero-dimensional domain, so they have to be embedded
3755 * in the current iteration domain.
3756 * param2pos maps the position of the parameter to the position
3757 * of the corresponding output dimension in the wrapped map.
3759 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3765 std::map
<int,int> param2pos
;
3770 n
= n_nested_parameter(stmt
->domain
);
3774 n_arg
= stmt
->n_arg
;
3775 stmt
= extract_nested(stmt
, n
, param2pos
);
3779 n
= stmt
->n_arg
- n_arg
;
3780 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3781 if (isl_set_is_wrapping(stmt
->domain
))
3782 map
= isl_set_unwrap(stmt
->domain
);
3784 map
= isl_map_from_domain(stmt
->domain
);
3785 map
= isl_map_insert_dims(map
, isl_dim_out
, 0, n
);
3787 for (int i
= nparam
- 1; i
>= 0; --i
) {
3790 if (!is_nested_parameter(map
, i
))
3793 id
= pet_expr_access_get_id(stmt
->args
[param2pos
[i
]]);
3794 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3795 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3797 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3800 stmt
->domain
= isl_map_wrap(map
);
3802 map
= isl_set_unwrap(isl_set_copy(stmt
->domain
));
3803 map
= isl_map_from_range(isl_map_domain(map
));
3804 for (int pos
= 0; pos
< n
; ++pos
)
3805 stmt
->args
[pos
] = embed(stmt
->args
[pos
], map
);
3808 stmt
= remove_nested_parameters(stmt
);
3809 stmt
= remove_duplicate_arguments(stmt
, n
);
3813 pet_stmt_free(stmt
);
3817 /* For each statement in "scop", move the parameters that correspond
3818 * to nested access into the ranges of the domains and create
3819 * corresponding argument expressions.
3821 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3826 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3827 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3828 if (!scop
->stmts
[i
])
3834 pet_scop_free(scop
);
3838 /* Given an access expression "expr", is the variable accessed by
3839 * "expr" assigned anywhere inside "scop"?
3841 static bool is_assigned(pet_expr
*expr
, pet_scop
*scop
)
3843 bool assigned
= false;
3846 id
= pet_expr_access_get_id(expr
);
3847 assigned
= pet_scop_writes(scop
, id
);
3853 /* Are all nested access parameters in "pa" allowed given "scop".
3854 * In particular, is none of them written by anywhere inside "scop".
3856 * If "scop" has any skip conditions, then no nested access parameters
3857 * are allowed. In particular, if there is any nested access in a guard
3858 * for a piece of code containing a "continue", then we want to introduce
3859 * a separate statement for evaluating this guard so that we can express
3860 * that the result is false for all previous iterations.
3862 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3869 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3870 for (int i
= 0; i
< nparam
; ++i
) {
3872 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3876 if (!is_nested_parameter(id
)) {
3881 if (pet_scop_has_skip(scop
, pet_skip_now
)) {
3886 nested
= (Expr
*) isl_id_get_user(id
);
3887 expr
= extract_expr(nested
);
3888 allowed
= expr
&& expr
->type
== pet_expr_access
&&
3889 !is_assigned(expr
, scop
);
3891 pet_expr_free(expr
);
3901 /* Do we need to construct a skip condition of the given type
3902 * on an if statement, given that the if condition is non-affine?
3904 * pet_scop_filter_skip can only handle the case where the if condition
3905 * holds (the then branch) and the skip condition is universal.
3906 * In any other case, we need to construct a new skip condition.
3908 static bool need_skip(struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3909 bool have_else
, enum pet_skip type
)
3911 if (have_else
&& scop_else
&& pet_scop_has_skip(scop_else
, type
))
3913 if (scop_then
&& pet_scop_has_skip(scop_then
, type
) &&
3914 !pet_scop_has_universal_skip(scop_then
, type
))
3919 /* Do we need to construct a skip condition of the given type
3920 * on an if statement, given that the if condition is affine?
3922 * There is no need to construct a new skip condition if all
3923 * the skip conditions are affine.
3925 static bool need_skip_aff(struct pet_scop
*scop_then
,
3926 struct pet_scop
*scop_else
, bool have_else
, enum pet_skip type
)
3928 if (scop_then
&& pet_scop_has_var_skip(scop_then
, type
))
3930 if (have_else
&& scop_else
&& pet_scop_has_var_skip(scop_else
, type
))
3935 /* Do we need to construct a skip condition of the given type
3936 * on an if statement?
3938 static bool need_skip(struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3939 bool have_else
, enum pet_skip type
, bool affine
)
3942 return need_skip_aff(scop_then
, scop_else
, have_else
, type
);
3944 return need_skip(scop_then
, scop_else
, have_else
, type
);
3947 /* Construct an affine expression pet_expr that evaluates
3948 * to the constant "val".
3950 static struct pet_expr
*universally(isl_ctx
*ctx
, int val
)
3955 space
= isl_space_alloc(ctx
, 0, 0, 1);
3956 map
= isl_map_universe(space
);
3957 map
= isl_map_fix_si(map
, isl_dim_out
, 0, val
);
3959 return pet_expr_from_access(map
);
3962 /* Construct an affine expression pet_expr that evaluates
3963 * to the constant 1.
3965 static struct pet_expr
*universally_true(isl_ctx
*ctx
)
3967 return universally(ctx
, 1);
3970 /* Construct an affine expression pet_expr that evaluates
3971 * to the constant 0.
3973 static struct pet_expr
*universally_false(isl_ctx
*ctx
)
3975 return universally(ctx
, 0);
3978 /* Given an access relation "test_access" for the if condition,
3979 * an access relation "skip_access" for the skip condition and
3980 * scops for the then and else branches, construct a scop for
3981 * computing "skip_access".
3983 * The computed scop contains a single statement that essentially does
3985 * skip_cond = test_cond ? skip_cond_then : skip_cond_else
3987 * If the skip conditions of the then and/or else branch are not affine,
3988 * then they need to be filtered by test_access.
3989 * If they are missing, then this means the skip condition is false.
3991 * Since we are constructing a skip condition for the if statement,
3992 * the skip conditions on the then and else branches are removed.
3994 static struct pet_scop
*extract_skip(PetScan
*scan
,
3995 __isl_take isl_map
*test_access
, __isl_take isl_map
*skip_access
,
3996 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
, bool have_else
,
3999 struct pet_expr
*expr_then
, *expr_else
, *expr
, *expr_skip
;
4000 struct pet_stmt
*stmt
;
4001 struct pet_scop
*scop
;
4002 isl_ctx
*ctx
= scan
->ctx
;
4006 if (have_else
&& !scop_else
)
4009 if (pet_scop_has_skip(scop_then
, type
)) {
4010 expr_then
= pet_scop_get_skip_expr(scop_then
, type
);
4011 pet_scop_reset_skip(scop_then
, type
);
4012 if (!pet_expr_is_affine(expr_then
))
4013 expr_then
= pet_expr_filter(expr_then
,
4014 isl_map_copy(test_access
), 1);
4016 expr_then
= universally_false(ctx
);
4018 if (have_else
&& pet_scop_has_skip(scop_else
, type
)) {
4019 expr_else
= pet_scop_get_skip_expr(scop_else
, type
);
4020 pet_scop_reset_skip(scop_else
, type
);
4021 if (!pet_expr_is_affine(expr_else
))
4022 expr_else
= pet_expr_filter(expr_else
,
4023 isl_map_copy(test_access
), 0);
4025 expr_else
= universally_false(ctx
);
4027 expr
= pet_expr_from_access(test_access
);
4028 expr
= pet_expr_new_ternary(ctx
, expr
, expr_then
, expr_else
);
4029 expr_skip
= pet_expr_from_access(isl_map_copy(skip_access
));
4031 expr_skip
->acc
.write
= 1;
4032 expr_skip
->acc
.read
= 0;
4034 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, expr_skip
, expr
);
4035 stmt
= pet_stmt_from_pet_expr(ctx
, -1, NULL
, scan
->n_stmt
++, expr
);
4037 scop
= pet_scop_from_pet_stmt(ctx
, stmt
);
4038 scop
= scop_add_array(scop
, skip_access
, scan
->ast_context
);
4039 isl_map_free(skip_access
);
4043 isl_map_free(test_access
);
4044 isl_map_free(skip_access
);
4048 /* Is scop's skip_now condition equal to its skip_later condition?
4049 * In particular, this means that it either has no skip_now condition
4050 * or both a skip_now and a skip_later condition (that are equal to each other).
4052 static bool skip_equals_skip_later(struct pet_scop
*scop
)
4054 int has_skip_now
, has_skip_later
;
4056 isl_set
*skip_now
, *skip_later
;
4060 has_skip_now
= pet_scop_has_skip(scop
, pet_skip_now
);
4061 has_skip_later
= pet_scop_has_skip(scop
, pet_skip_later
);
4062 if (has_skip_now
!= has_skip_later
)
4067 skip_now
= pet_scop_get_skip(scop
, pet_skip_now
);
4068 skip_later
= pet_scop_get_skip(scop
, pet_skip_later
);
4069 equal
= isl_set_is_equal(skip_now
, skip_later
);
4070 isl_set_free(skip_now
);
4071 isl_set_free(skip_later
);
4076 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
4078 static void drop_skip_later(struct pet_scop
*scop1
, struct pet_scop
*scop2
)
4080 pet_scop_reset_skip(scop1
, pet_skip_later
);
4081 pet_scop_reset_skip(scop2
, pet_skip_later
);
4084 /* Structure that handles the construction of skip conditions.
4086 * scop_then and scop_else represent the then and else branches
4087 * of the if statement
4089 * skip[type] is true if we need to construct a skip condition of that type
4090 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
4091 * are equal to each other
4092 * access[type] is the virtual array representing the skip condition
4093 * scop[type] is a scop for computing the skip condition
4095 struct pet_skip_info
{
4101 struct pet_scop
*scop
[2];
4103 pet_skip_info(isl_ctx
*ctx
) : ctx(ctx
) {}
4105 operator bool() { return skip
[pet_skip_now
] || skip
[pet_skip_later
]; }
4108 /* Structure that handles the construction of skip conditions on if statements.
4110 * scop_then and scop_else represent the then and else branches
4111 * of the if statement
4113 struct pet_skip_info_if
: public pet_skip_info
{
4114 struct pet_scop
*scop_then
, *scop_else
;
4117 pet_skip_info_if(isl_ctx
*ctx
, struct pet_scop
*scop_then
,
4118 struct pet_scop
*scop_else
, bool have_else
, bool affine
);
4119 void extract(PetScan
*scan
, __isl_keep isl_map
*access
,
4120 enum pet_skip type
);
4121 void extract(PetScan
*scan
, __isl_keep isl_map
*access
);
4122 void extract(PetScan
*scan
, __isl_keep isl_pw_aff
*cond
);
4123 struct pet_scop
*add(struct pet_scop
*scop
, enum pet_skip type
,
4125 struct pet_scop
*add(struct pet_scop
*scop
, int offset
);
4128 /* Initialize a pet_skip_info_if structure based on the then and else branches
4129 * and based on whether the if condition is affine or not.
4131 pet_skip_info_if::pet_skip_info_if(isl_ctx
*ctx
, struct pet_scop
*scop_then
,
4132 struct pet_scop
*scop_else
, bool have_else
, bool affine
) :
4133 pet_skip_info(ctx
), scop_then(scop_then
), scop_else(scop_else
),
4134 have_else(have_else
)
4136 skip
[pet_skip_now
] =
4137 need_skip(scop_then
, scop_else
, have_else
, pet_skip_now
, affine
);
4138 equal
= skip
[pet_skip_now
] && skip_equals_skip_later(scop_then
) &&
4139 (!have_else
|| skip_equals_skip_later(scop_else
));
4140 skip
[pet_skip_later
] = skip
[pet_skip_now
] && !equal
&&
4141 need_skip(scop_then
, scop_else
, have_else
, pet_skip_later
, affine
);
4144 /* If we need to construct a skip condition of the given type,
4147 * "map" represents the if condition.
4149 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_map
*map
,
4155 access
[type
] = create_test_access(isl_map_get_ctx(map
), scan
->n_test
++);
4156 scop
[type
] = extract_skip(scan
, isl_map_copy(map
),
4157 isl_map_copy(access
[type
]),
4158 scop_then
, scop_else
, have_else
, type
);
4161 /* Construct the required skip conditions, given the if condition "map".
4163 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_map
*map
)
4165 extract(scan
, map
, pet_skip_now
);
4166 extract(scan
, map
, pet_skip_later
);
4168 drop_skip_later(scop_then
, scop_else
);
4171 /* Construct the required skip conditions, given the if condition "cond".
4173 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_pw_aff
*cond
)
4178 if (!skip
[pet_skip_now
] && !skip
[pet_skip_later
])
4181 test_set
= isl_set_from_pw_aff(isl_pw_aff_copy(cond
));
4182 test
= isl_map_from_range(test_set
);
4183 extract(scan
, test
);
4187 /* Add the computed skip condition of the give type to "main" and
4188 * add the scop for computing the condition at the given offset.
4190 * If equal is set, then we only computed a skip condition for pet_skip_now,
4191 * but we also need to set it as main's pet_skip_later.
4193 struct pet_scop
*pet_skip_info_if::add(struct pet_scop
*main
,
4194 enum pet_skip type
, int offset
)
4201 skip_set
= isl_map_range(access
[type
]);
4202 access
[type
] = NULL
;
4203 scop
[type
] = pet_scop_prefix(scop
[type
], offset
);
4204 main
= pet_scop_add_par(ctx
, main
, scop
[type
]);
4208 main
= pet_scop_set_skip(main
, pet_skip_later
,
4209 isl_set_copy(skip_set
));
4211 main
= pet_scop_set_skip(main
, type
, skip_set
);
4216 /* Add the computed skip conditions to "main" and
4217 * add the scops for computing the conditions at the given offset.
4219 struct pet_scop
*pet_skip_info_if::add(struct pet_scop
*scop
, int offset
)
4221 scop
= add(scop
, pet_skip_now
, offset
);
4222 scop
= add(scop
, pet_skip_later
, offset
);
4227 /* Construct a pet_scop for a non-affine if statement.
4229 * We create a separate statement that writes the result
4230 * of the non-affine condition to a virtual scalar.
4231 * A constraint requiring the value of this virtual scalar to be one
4232 * is added to the iteration domains of the then branch.
4233 * Similarly, a constraint requiring the value of this virtual scalar
4234 * to be zero is added to the iteration domains of the else branch, if any.
4235 * We adjust the schedules to ensure that the virtual scalar is written
4236 * before it is read.
4238 * If there are any breaks or continues in the then and/or else
4239 * branches, then we may have to compute a new skip condition.
4240 * This is handled using a pet_skip_info_if object.
4241 * On initialization, the object checks if skip conditions need
4242 * to be computed. If so, it does so in "extract" and adds them in "add".
4244 struct pet_scop
*PetScan::extract_non_affine_if(Expr
*cond
,
4245 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
4246 bool have_else
, int stmt_id
)
4248 struct pet_scop
*scop
;
4249 isl_map
*test_access
;
4250 int save_n_stmt
= n_stmt
;
4252 test_access
= create_test_access(ctx
, n_test
++);
4254 scop
= extract_non_affine_condition(cond
, isl_map_copy(test_access
));
4255 n_stmt
= save_n_stmt
;
4256 scop
= scop_add_array(scop
, test_access
, ast_context
);
4258 pet_skip_info_if
skip(ctx
, scop_then
, scop_else
, have_else
, false);
4259 skip
.extract(this, test_access
);
4261 scop
= pet_scop_prefix(scop
, 0);
4262 scop_then
= pet_scop_prefix(scop_then
, 1);
4263 scop_then
= pet_scop_filter(scop_then
, isl_map_copy(test_access
), 1);
4265 scop_else
= pet_scop_prefix(scop_else
, 1);
4266 scop_else
= pet_scop_filter(scop_else
, test_access
, 0);
4267 scop_then
= pet_scop_add_par(ctx
, scop_then
, scop_else
);
4269 isl_map_free(test_access
);
4271 scop
= pet_scop_add_seq(ctx
, scop
, scop_then
);
4273 scop
= skip
.add(scop
, 2);
4278 /* Construct a pet_scop for an if statement.
4280 * If the condition fits the pattern of a conditional assignment,
4281 * then it is handled by extract_conditional_assignment.
4282 * Otherwise, we do the following.
4284 * If the condition is affine, then the condition is added
4285 * to the iteration domains of the then branch, while the
4286 * opposite of the condition in added to the iteration domains
4287 * of the else branch, if any.
4288 * We allow the condition to be dynamic, i.e., to refer to
4289 * scalars or array elements that may be written to outside
4290 * of the given if statement. These nested accesses are then represented
4291 * as output dimensions in the wrapping iteration domain.
4292 * If it also written _inside_ the then or else branch, then
4293 * we treat the condition as non-affine.
4294 * As explained in extract_non_affine_if, this will introduce
4295 * an extra statement.
4296 * For aesthetic reasons, we want this statement to have a statement
4297 * number that is lower than those of the then and else branches.
4298 * In order to evaluate if will need such a statement, however, we
4299 * first construct scops for the then and else branches.
4300 * We therefore reserve a statement number if we might have to
4301 * introduce such an extra statement.
4303 * If the condition is not affine, then the scop is created in
4304 * extract_non_affine_if.
4306 * If there are any breaks or continues in the then and/or else
4307 * branches, then we may have to compute a new skip condition.
4308 * This is handled using a pet_skip_info_if object.
4309 * On initialization, the object checks if skip conditions need
4310 * to be computed. If so, it does so in "extract" and adds them in "add".
4312 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
4314 struct pet_scop
*scop_then
, *scop_else
= NULL
, *scop
;
4320 scop
= extract_conditional_assignment(stmt
);
4324 cond
= try_extract_nested_condition(stmt
->getCond());
4325 if (allow_nested
&& (!cond
|| has_nested(cond
)))
4329 assigned_value_cache
cache(assigned_value
);
4330 scop_then
= extract(stmt
->getThen());
4333 if (stmt
->getElse()) {
4334 assigned_value_cache
cache(assigned_value
);
4335 scop_else
= extract(stmt
->getElse());
4336 if (options
->autodetect
) {
4337 if (scop_then
&& !scop_else
) {
4339 isl_pw_aff_free(cond
);
4342 if (!scop_then
&& scop_else
) {
4344 isl_pw_aff_free(cond
);
4351 (!is_nested_allowed(cond
, scop_then
) ||
4352 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
4353 isl_pw_aff_free(cond
);
4356 if (allow_nested
&& !cond
)
4357 return extract_non_affine_if(stmt
->getCond(), scop_then
,
4358 scop_else
, stmt
->getElse(), stmt_id
);
4361 cond
= extract_condition(stmt
->getCond());
4363 pet_skip_info_if
skip(ctx
, scop_then
, scop_else
, stmt
->getElse(), true);
4364 skip
.extract(this, cond
);
4366 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
4367 set
= isl_pw_aff_non_zero_set(cond
);
4368 scop
= pet_scop_restrict(scop_then
, isl_set_copy(set
));
4370 if (stmt
->getElse()) {
4371 set
= isl_set_subtract(isl_set_copy(valid
), set
);
4372 scop_else
= pet_scop_restrict(scop_else
, set
);
4373 scop
= pet_scop_add_par(ctx
, scop
, scop_else
);
4376 scop
= resolve_nested(scop
);
4377 scop
= pet_scop_restrict_context(scop
, valid
);
4380 scop
= pet_scop_prefix(scop
, 0);
4381 scop
= skip
.add(scop
, 1);
4386 /* Try and construct a pet_scop for a label statement.
4387 * We currently only allow labels on expression statements.
4389 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
4394 sub
= stmt
->getSubStmt();
4395 if (!isa
<Expr
>(sub
)) {
4400 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
4402 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
4405 /* Construct a pet_scop for a continue statement.
4407 * We simply create an empty scop with a universal pet_skip_now
4408 * skip condition. This skip condition will then be taken into
4409 * account by the enclosing loop construct, possibly after
4410 * being incorporated into outer skip conditions.
4412 struct pet_scop
*PetScan::extract(ContinueStmt
*stmt
)
4418 scop
= pet_scop_empty(ctx
);
4422 space
= isl_space_set_alloc(ctx
, 0, 1);
4423 set
= isl_set_universe(space
);
4424 set
= isl_set_fix_si(set
, isl_dim_set
, 0, 1);
4425 scop
= pet_scop_set_skip(scop
, pet_skip_now
, set
);
4430 /* Construct a pet_scop for a break statement.
4432 * We simply create an empty scop with both a universal pet_skip_now
4433 * skip condition and a universal pet_skip_later skip condition.
4434 * These skip conditions will then be taken into
4435 * account by the enclosing loop construct, possibly after
4436 * being incorporated into outer skip conditions.
4438 struct pet_scop
*PetScan::extract(BreakStmt
*stmt
)
4444 scop
= pet_scop_empty(ctx
);
4448 space
= isl_space_set_alloc(ctx
, 0, 1);
4449 set
= isl_set_universe(space
);
4450 set
= isl_set_fix_si(set
, isl_dim_set
, 0, 1);
4451 scop
= pet_scop_set_skip(scop
, pet_skip_now
, isl_set_copy(set
));
4452 scop
= pet_scop_set_skip(scop
, pet_skip_later
, set
);
4457 /* Try and construct a pet_scop corresponding to "stmt".
4459 * If "stmt" is a compound statement, then "skip_declarations"
4460 * indicates whether we should skip initial declarations in the
4461 * compound statement.
4463 * If the constructed pet_scop is not a (possibly) partial representation
4464 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4465 * In particular, if skip_declarations, then we may have skipped declarations
4466 * inside "stmt" and so the pet_scop may not represent the entire "stmt".
4467 * Note that this function may be called with "stmt" referring to the entire
4468 * body of the function, including the outer braces. In such cases,
4469 * skip_declarations will be set and the braces will not be taken into
4470 * account in scop->start and scop->end.
4472 struct pet_scop
*PetScan::extract(Stmt
*stmt
, bool skip_declarations
)
4474 struct pet_scop
*scop
;
4475 unsigned start
, end
;
4477 SourceManager
&SM
= PP
.getSourceManager();
4478 const LangOptions
&LO
= PP
.getLangOpts();
4480 if (isa
<Expr
>(stmt
))
4481 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
4483 switch (stmt
->getStmtClass()) {
4484 case Stmt::WhileStmtClass
:
4485 scop
= extract(cast
<WhileStmt
>(stmt
));
4487 case Stmt::ForStmtClass
:
4488 scop
= extract_for(cast
<ForStmt
>(stmt
));
4490 case Stmt::IfStmtClass
:
4491 scop
= extract(cast
<IfStmt
>(stmt
));
4493 case Stmt::CompoundStmtClass
:
4494 scop
= extract(cast
<CompoundStmt
>(stmt
), skip_declarations
);
4496 case Stmt::LabelStmtClass
:
4497 scop
= extract(cast
<LabelStmt
>(stmt
));
4499 case Stmt::ContinueStmtClass
:
4500 scop
= extract(cast
<ContinueStmt
>(stmt
));
4502 case Stmt::BreakStmtClass
:
4503 scop
= extract(cast
<BreakStmt
>(stmt
));
4505 case Stmt::DeclStmtClass
:
4506 scop
= extract(cast
<DeclStmt
>(stmt
));
4513 if (partial
|| skip_declarations
)
4516 loc
= stmt
->getLocStart();
4517 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
);
4518 start
= getExpansionOffset(SM
, loc
);
4519 loc
= PP
.getLocForEndOfToken(stmt
->getLocEnd());
4520 end
= getExpansionOffset(SM
, loc
);
4521 scop
= pet_scop_update_start_end(scop
, start
, end
);
4526 /* Do we need to construct a skip condition of the given type
4527 * on a sequence of statements?
4529 * There is no need to construct a new skip condition if only
4530 * only of the two statements has a skip condition or if both
4531 * of their skip conditions are affine.
4533 * In principle we also don't need a new continuation variable if
4534 * the continuation of scop2 is affine, but then we would need
4535 * to allow more complicated forms of continuations.
4537 static bool need_skip_seq(struct pet_scop
*scop1
, struct pet_scop
*scop2
,
4540 if (!scop1
|| !pet_scop_has_skip(scop1
, type
))
4542 if (!scop2
|| !pet_scop_has_skip(scop2
, type
))
4544 if (pet_scop_has_affine_skip(scop1
, type
) &&
4545 pet_scop_has_affine_skip(scop2
, type
))
4550 /* Construct a scop for computing the skip condition of the given type and
4551 * with access relation "skip_access" for a sequence of two scops "scop1"
4554 * The computed scop contains a single statement that essentially does
4556 * skip_cond = skip_cond_1 ? 1 : skip_cond_2
4558 * or, in other words, skip_cond1 || skip_cond2.
4559 * In this expression, skip_cond_2 is filtered to reflect that it is
4560 * only evaluated when skip_cond_1 is false.
4562 * The skip condition on scop1 is not removed because it still needs
4563 * to be applied to scop2 when these two scops are combined.
4565 static struct pet_scop
*extract_skip_seq(PetScan
*ps
,
4566 __isl_take isl_map
*skip_access
,
4567 struct pet_scop
*scop1
, struct pet_scop
*scop2
, enum pet_skip type
)
4570 struct pet_expr
*expr1
, *expr2
, *expr
, *expr_skip
;
4571 struct pet_stmt
*stmt
;
4572 struct pet_scop
*scop
;
4573 isl_ctx
*ctx
= ps
->ctx
;
4575 if (!scop1
|| !scop2
)
4578 expr1
= pet_scop_get_skip_expr(scop1
, type
);
4579 expr2
= pet_scop_get_skip_expr(scop2
, type
);
4580 pet_scop_reset_skip(scop2
, type
);
4582 expr2
= pet_expr_filter(expr2
, isl_map_copy(expr1
->acc
.access
), 0);
4584 expr
= universally_true(ctx
);
4585 expr
= pet_expr_new_ternary(ctx
, expr1
, expr
, expr2
);
4586 expr_skip
= pet_expr_from_access(isl_map_copy(skip_access
));
4588 expr_skip
->acc
.write
= 1;
4589 expr_skip
->acc
.read
= 0;
4591 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, expr_skip
, expr
);
4592 stmt
= pet_stmt_from_pet_expr(ctx
, -1, NULL
, ps
->n_stmt
++, expr
);
4594 scop
= pet_scop_from_pet_stmt(ctx
, stmt
);
4595 scop
= scop_add_array(scop
, skip_access
, ps
->ast_context
);
4596 isl_map_free(skip_access
);
4600 isl_map_free(skip_access
);
4604 /* Structure that handles the construction of skip conditions
4605 * on sequences of statements.
4607 * scop1 and scop2 represent the two statements that are combined
4609 struct pet_skip_info_seq
: public pet_skip_info
{
4610 struct pet_scop
*scop1
, *scop2
;
4612 pet_skip_info_seq(isl_ctx
*ctx
, struct pet_scop
*scop1
,
4613 struct pet_scop
*scop2
);
4614 void extract(PetScan
*scan
, enum pet_skip type
);
4615 void extract(PetScan
*scan
);
4616 struct pet_scop
*add(struct pet_scop
*scop
, enum pet_skip type
,
4618 struct pet_scop
*add(struct pet_scop
*scop
, int offset
);
4621 /* Initialize a pet_skip_info_seq structure based on
4622 * on the two statements that are going to be combined.
4624 pet_skip_info_seq::pet_skip_info_seq(isl_ctx
*ctx
, struct pet_scop
*scop1
,
4625 struct pet_scop
*scop2
) : pet_skip_info(ctx
), scop1(scop1
), scop2(scop2
)
4627 skip
[pet_skip_now
] = need_skip_seq(scop1
, scop2
, pet_skip_now
);
4628 equal
= skip
[pet_skip_now
] && skip_equals_skip_later(scop1
) &&
4629 skip_equals_skip_later(scop2
);
4630 skip
[pet_skip_later
] = skip
[pet_skip_now
] && !equal
&&
4631 need_skip_seq(scop1
, scop2
, pet_skip_later
);
4634 /* If we need to construct a skip condition of the given type,
4637 void pet_skip_info_seq::extract(PetScan
*scan
, enum pet_skip type
)
4642 access
[type
] = create_test_access(ctx
, scan
->n_test
++);
4643 scop
[type
] = extract_skip_seq(scan
, isl_map_copy(access
[type
]),
4644 scop1
, scop2
, type
);
4647 /* Construct the required skip conditions.
4649 void pet_skip_info_seq::extract(PetScan
*scan
)
4651 extract(scan
, pet_skip_now
);
4652 extract(scan
, pet_skip_later
);
4654 drop_skip_later(scop1
, scop2
);
4657 /* Add the computed skip condition of the given type to "main" and
4658 * add the scop for computing the condition at the given offset (the statement
4659 * number). Within this offset, the condition is computed at position 1
4660 * to ensure that it is computed after the corresponding statement.
4662 * If equal is set, then we only computed a skip condition for pet_skip_now,
4663 * but we also need to set it as main's pet_skip_later.
4665 struct pet_scop
*pet_skip_info_seq::add(struct pet_scop
*main
,
4666 enum pet_skip type
, int offset
)
4673 skip_set
= isl_map_range(access
[type
]);
4674 access
[type
] = NULL
;
4675 scop
[type
] = pet_scop_prefix(scop
[type
], 1);
4676 scop
[type
] = pet_scop_prefix(scop
[type
], offset
);
4677 main
= pet_scop_add_par(ctx
, main
, scop
[type
]);
4681 main
= pet_scop_set_skip(main
, pet_skip_later
,
4682 isl_set_copy(skip_set
));
4684 main
= pet_scop_set_skip(main
, type
, skip_set
);
4689 /* Add the computed skip conditions to "main" and
4690 * add the scops for computing the conditions at the given offset.
4692 struct pet_scop
*pet_skip_info_seq::add(struct pet_scop
*scop
, int offset
)
4694 scop
= add(scop
, pet_skip_now
, offset
);
4695 scop
= add(scop
, pet_skip_later
, offset
);
4700 /* Extract a clone of the kill statement in "scop".
4701 * "scop" is expected to have been created from a DeclStmt
4702 * and should have the kill as its first statement.
4704 struct pet_stmt
*PetScan::extract_kill(struct pet_scop
*scop
)
4706 struct pet_expr
*kill
;
4707 struct pet_stmt
*stmt
;
4712 if (scop
->n_stmt
< 1)
4713 isl_die(ctx
, isl_error_internal
,
4714 "expecting at least one statement", return NULL
);
4715 stmt
= scop
->stmts
[0];
4716 if (stmt
->body
->type
!= pet_expr_unary
||
4717 stmt
->body
->op
!= pet_op_kill
)
4718 isl_die(ctx
, isl_error_internal
,
4719 "expecting kill statement", return NULL
);
4721 access
= isl_map_copy(stmt
->body
->args
[0]->acc
.access
);
4722 access
= isl_map_reset_tuple_id(access
, isl_dim_in
);
4723 kill
= pet_expr_kill_from_access(access
);
4724 return pet_stmt_from_pet_expr(ctx
, stmt
->line
, NULL
, n_stmt
++, kill
);
4727 /* Mark all arrays in "scop" as being exposed.
4729 static struct pet_scop
*mark_exposed(struct pet_scop
*scop
)
4733 for (int i
= 0; i
< scop
->n_array
; ++i
)
4734 scop
->arrays
[i
]->exposed
= 1;
4738 /* Try and construct a pet_scop corresponding to (part of)
4739 * a sequence of statements.
4741 * "block" is set if the sequence respresents the children of
4742 * a compound statement.
4743 * "skip_declarations" is set if we should skip initial declarations
4744 * in the sequence of statements.
4746 * If there are any breaks or continues in the individual statements,
4747 * then we may have to compute a new skip condition.
4748 * This is handled using a pet_skip_info_seq object.
4749 * On initialization, the object checks if skip conditions need
4750 * to be computed. If so, it does so in "extract" and adds them in "add".
4752 * If "block" is set, then we need to insert kill statements at
4753 * the end of the block for any array that has been declared by
4754 * one of the statements in the sequence. Each of these declarations
4755 * results in the construction of a kill statement at the place
4756 * of the declaration, so we simply collect duplicates of
4757 * those kill statements and append these duplicates to the constructed scop.
4759 * If "block" is not set, then any array declared by one of the statements
4760 * in the sequence is marked as being exposed.
4762 struct pet_scop
*PetScan::extract(StmtRange stmt_range
, bool block
,
4763 bool skip_declarations
)
4768 bool partial_range
= false;
4769 set
<struct pet_stmt
*> kills
;
4770 set
<struct pet_stmt
*>::iterator it
;
4772 scop
= pet_scop_empty(ctx
);
4773 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
4775 struct pet_scop
*scop_i
;
4777 if (skip_declarations
&&
4778 child
->getStmtClass() == Stmt::DeclStmtClass
)
4781 scop_i
= extract(child
);
4782 if (scop
&& partial
) {
4783 pet_scop_free(scop_i
);
4786 pet_skip_info_seq
skip(ctx
, scop
, scop_i
);
4789 scop_i
= pet_scop_prefix(scop_i
, 0);
4790 if (scop_i
&& child
->getStmtClass() == Stmt::DeclStmtClass
) {
4792 kills
.insert(extract_kill(scop_i
));
4794 scop_i
= mark_exposed(scop_i
);
4796 scop_i
= pet_scop_prefix(scop_i
, j
);
4797 if (options
->autodetect
) {
4799 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4801 partial_range
= true;
4802 if (scop
->n_stmt
!= 0 && !scop_i
)
4805 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4808 scop
= skip
.add(scop
, j
);
4814 for (it
= kills
.begin(); it
!= kills
.end(); ++it
) {
4816 scop_j
= pet_scop_from_pet_stmt(ctx
, *it
);
4817 scop_j
= pet_scop_prefix(scop_j
, j
);
4818 scop
= pet_scop_add_seq(ctx
, scop
, scop_j
);
4821 if (scop
&& partial_range
) {
4822 if (scop
->n_stmt
== 0) {
4823 pet_scop_free(scop
);
4832 /* Check if the scop marked by the user is exactly this Stmt
4833 * or part of this Stmt.
4834 * If so, return a pet_scop corresponding to the marked region.
4835 * Otherwise, return NULL.
4837 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
4839 SourceManager
&SM
= PP
.getSourceManager();
4840 unsigned start_off
, end_off
;
4842 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
4843 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
4845 if (start_off
> loc
.end
)
4847 if (end_off
< loc
.start
)
4849 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
4850 return extract(stmt
);
4854 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
4855 Stmt
*child
= *start
;
4858 start_off
= getExpansionOffset(SM
, child
->getLocStart());
4859 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
4860 if (start_off
< loc
.start
&& end_off
>= loc
.end
)
4862 if (start_off
>= loc
.start
)
4867 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
4869 start_off
= SM
.getFileOffset(child
->getLocStart());
4870 if (start_off
>= loc
.end
)
4874 return extract(StmtRange(start
, end
), false, false);
4877 /* Set the size of index "pos" of "array" to "size".
4878 * In particular, add a constraint of the form
4882 * to array->extent and a constraint of the form
4886 * to array->context.
4888 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
4889 __isl_take isl_pw_aff
*size
)
4899 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
4900 array
->context
= isl_set_intersect(array
->context
, valid
);
4902 dim
= isl_set_get_space(array
->extent
);
4903 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
4904 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
4905 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
4906 index
= isl_pw_aff_alloc(univ
, aff
);
4908 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
4909 isl_set_dim(array
->extent
, isl_dim_set
));
4910 id
= isl_set_get_tuple_id(array
->extent
);
4911 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
4912 bound
= isl_pw_aff_lt_set(index
, size
);
4914 array
->extent
= isl_set_intersect(array
->extent
, bound
);
4916 if (!array
->context
|| !array
->extent
)
4921 pet_array_free(array
);
4925 /* Figure out the size of the array at position "pos" and all
4926 * subsequent positions from "type" and update "array" accordingly.
4928 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
4929 const Type
*type
, int pos
)
4931 const ArrayType
*atype
;
4937 if (type
->isPointerType()) {
4938 type
= type
->getPointeeType().getTypePtr();
4939 return set_upper_bounds(array
, type
, pos
+ 1);
4941 if (!type
->isArrayType())
4944 type
= type
->getCanonicalTypeInternal().getTypePtr();
4945 atype
= cast
<ArrayType
>(type
);
4947 if (type
->isConstantArrayType()) {
4948 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
4949 size
= extract_affine(ca
->getSize());
4950 array
= update_size(array
, pos
, size
);
4951 } else if (type
->isVariableArrayType()) {
4952 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
4953 size
= extract_affine(vla
->getSizeExpr());
4954 array
= update_size(array
, pos
, size
);
4957 type
= atype
->getElementType().getTypePtr();
4959 return set_upper_bounds(array
, type
, pos
+ 1);
4962 /* Is "T" the type of a variable length array with static size?
4964 static bool is_vla_with_static_size(QualType T
)
4966 const VariableArrayType
*vlatype
;
4968 if (!T
->isVariableArrayType())
4970 vlatype
= cast
<VariableArrayType
>(T
);
4971 return vlatype
->getSizeModifier() == VariableArrayType::Static
;
4974 /* Return the type of "decl" as an array.
4976 * In particular, if "decl" is a parameter declaration that
4977 * is a variable length array with a static size, then
4978 * return the original type (i.e., the variable length array).
4979 * Otherwise, return the type of decl.
4981 static QualType
get_array_type(ValueDecl
*decl
)
4986 parm
= dyn_cast
<ParmVarDecl
>(decl
);
4988 return decl
->getType();
4990 T
= parm
->getOriginalType();
4991 if (!is_vla_with_static_size(T
))
4992 return decl
->getType();
4996 /* Construct and return a pet_array corresponding to the variable "decl".
4997 * In particular, initialize array->extent to
4999 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
5001 * and then call set_upper_bounds to set the upper bounds on the indices
5002 * based on the type of the variable.
5004 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
)
5006 struct pet_array
*array
;
5007 QualType qt
= get_array_type(decl
);
5008 const Type
*type
= qt
.getTypePtr();
5009 int depth
= array_depth(type
);
5010 QualType base
= base_type(qt
);
5015 array
= isl_calloc_type(ctx
, struct pet_array
);
5019 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
5020 dim
= isl_space_set_alloc(ctx
, 0, depth
);
5021 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
5023 array
->extent
= isl_set_nat_universe(dim
);
5025 dim
= isl_space_params_alloc(ctx
, 0);
5026 array
->context
= isl_set_universe(dim
);
5028 array
= set_upper_bounds(array
, type
, 0);
5032 name
= base
.getAsString();
5033 array
->element_type
= strdup(name
.c_str());
5034 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
5039 /* Construct a list of pet_arrays, one for each array (or scalar)
5040 * accessed inside "scop", add this list to "scop" and return the result.
5042 * The context of "scop" is updated with the intersection of
5043 * the contexts of all arrays, i.e., constraints on the parameters
5044 * that ensure that the arrays have a valid (non-negative) size.
5046 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
5049 set
<ValueDecl
*> arrays
;
5050 set
<ValueDecl
*>::iterator it
;
5052 struct pet_array
**scop_arrays
;
5057 pet_scop_collect_arrays(scop
, arrays
);
5058 if (arrays
.size() == 0)
5061 n_array
= scop
->n_array
;
5063 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
5064 n_array
+ arrays
.size());
5067 scop
->arrays
= scop_arrays
;
5069 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
5070 struct pet_array
*array
;
5071 scop
->arrays
[n_array
+ i
] = array
= extract_array(ctx
, *it
);
5072 if (!scop
->arrays
[n_array
+ i
])
5075 scop
->context
= isl_set_intersect(scop
->context
,
5076 isl_set_copy(array
->context
));
5083 pet_scop_free(scop
);
5087 /* Bound all parameters in scop->context to the possible values
5088 * of the corresponding C variable.
5090 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
5097 n
= isl_set_dim(scop
->context
, isl_dim_param
);
5098 for (int i
= 0; i
< n
; ++i
) {
5102 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
5103 if (is_nested_parameter(id
)) {
5105 isl_die(isl_set_get_ctx(scop
->context
),
5107 "unresolved nested parameter", goto error
);
5109 decl
= (ValueDecl
*) isl_id_get_user(id
);
5112 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
5120 pet_scop_free(scop
);
5124 /* Construct a pet_scop from the given function.
5126 * If the scop was delimited by scop and endscop pragmas, then we override
5127 * the file offsets by those derived from the pragmas.
5129 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
5134 stmt
= fd
->getBody();
5136 if (options
->autodetect
)
5137 scop
= extract(stmt
, true);
5140 scop
= pet_scop_update_start_end(scop
, loc
.start
, loc
.end
);
5142 scop
= pet_scop_detect_parameter_accesses(scop
);
5143 scop
= scan_arrays(scop
);
5144 scop
= add_parameter_bounds(scop
);
5145 scop
= pet_scop_gist(scop
, value_bounds
);