PetScan::assign: take pet_expr as input
[pet.git] / scan.cc
blob6e8d932bf6e2499af76d79b4407ebe13ef5d398a
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2014 Ecole Normale Superieure. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
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
32 * Leiden University.
33 */
35 #include <string.h>
36 #include <set>
37 #include <map>
38 #include <iostream>
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>
45 #include <isl/id.h>
46 #include <isl/space.h>
47 #include <isl/aff.h>
48 #include <isl/set.h>
50 #include "aff.h"
51 #include "clang.h"
52 #include "context.h"
53 #include "expr.h"
54 #include "nest.h"
55 #include "options.h"
56 #include "scan.h"
57 #include "scop.h"
58 #include "scop_plus.h"
59 #include "skip.h"
61 #include "config.h"
63 using namespace std;
64 using namespace clang;
66 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
68 switch (kind) {
69 case UO_Minus:
70 return pet_op_minus;
71 case UO_Not:
72 return pet_op_not;
73 case UO_LNot:
74 return pet_op_lnot;
75 case UO_PostInc:
76 return pet_op_post_inc;
77 case UO_PostDec:
78 return pet_op_post_dec;
79 case UO_PreInc:
80 return pet_op_pre_inc;
81 case UO_PreDec:
82 return pet_op_pre_dec;
83 default:
84 return pet_op_last;
88 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
90 switch (kind) {
91 case BO_AddAssign:
92 return pet_op_add_assign;
93 case BO_SubAssign:
94 return pet_op_sub_assign;
95 case BO_MulAssign:
96 return pet_op_mul_assign;
97 case BO_DivAssign:
98 return pet_op_div_assign;
99 case BO_Assign:
100 return pet_op_assign;
101 case BO_Add:
102 return pet_op_add;
103 case BO_Sub:
104 return pet_op_sub;
105 case BO_Mul:
106 return pet_op_mul;
107 case BO_Div:
108 return pet_op_div;
109 case BO_Rem:
110 return pet_op_mod;
111 case BO_Shl:
112 return pet_op_shl;
113 case BO_Shr:
114 return pet_op_shr;
115 case BO_EQ:
116 return pet_op_eq;
117 case BO_NE:
118 return pet_op_ne;
119 case BO_LE:
120 return pet_op_le;
121 case BO_GE:
122 return pet_op_ge;
123 case BO_LT:
124 return pet_op_lt;
125 case BO_GT:
126 return pet_op_gt;
127 case BO_And:
128 return pet_op_and;
129 case BO_Xor:
130 return pet_op_xor;
131 case BO_Or:
132 return pet_op_or;
133 case BO_LAnd:
134 return pet_op_land;
135 case BO_LOr:
136 return pet_op_lor;
137 default:
138 return pet_op_last;
142 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
143 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
145 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
146 SourceLocation(), var, false, var->getInnerLocStart(),
147 var->getType(), VK_LValue);
149 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
150 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
152 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
153 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
154 VK_LValue);
156 #else
157 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
159 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
160 var, var->getInnerLocStart(), var->getType(), VK_LValue);
162 #endif
164 /* Check if the element type corresponding to the given array type
165 * has a const qualifier.
167 static bool const_base(QualType qt)
169 const Type *type = qt.getTypePtr();
171 if (type->isPointerType())
172 return const_base(type->getPointeeType());
173 if (type->isArrayType()) {
174 const ArrayType *atype;
175 type = type->getCanonicalTypeInternal().getTypePtr();
176 atype = cast<ArrayType>(type);
177 return const_base(atype->getElementType());
180 return qt.isConstQualified();
183 /* Create an isl_id that refers to the named declarator "decl".
185 static __isl_give isl_id *create_decl_id(isl_ctx *ctx, NamedDecl *decl)
187 return isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
190 /* Mark "decl" as having an unknown value in "assigned_value".
192 * If no (known or unknown) value was assigned to "decl" before,
193 * then it may have been treated as a parameter before and may
194 * therefore appear in a value assigned to another variable.
195 * If so, this assignment needs to be turned into an unknown value too.
197 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
198 ValueDecl *decl)
200 map<ValueDecl *, isl_pw_aff *>::iterator it;
202 it = assigned_value.find(decl);
204 assigned_value[decl] = NULL;
206 if (it != assigned_value.end())
207 return;
209 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
210 isl_pw_aff *pa = it->second;
211 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
213 for (int i = 0; i < nparam; ++i) {
214 isl_id *id;
216 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
217 continue;
218 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
219 if (isl_id_get_user(id) == decl)
220 it->second = NULL;
221 isl_id_free(id);
226 /* Look for any assignments to scalar variables in part of the parse
227 * tree and set assigned_value to NULL for each of them.
228 * Also reset assigned_value if the address of a scalar variable
229 * is being taken. As an exception, if the address is passed to a function
230 * that is declared to receive a const pointer, then assigned_value is
231 * not reset.
233 * This ensures that we won't use any previously stored value
234 * in the current subtree and its parents.
236 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
237 map<ValueDecl *, isl_pw_aff *> &assigned_value;
238 set<UnaryOperator *> skip;
240 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
241 assigned_value(assigned_value) {}
243 /* Check for "address of" operators whose value is passed
244 * to a const pointer argument and add them to "skip", so that
245 * we can skip them in VisitUnaryOperator.
247 bool VisitCallExpr(CallExpr *expr) {
248 FunctionDecl *fd;
249 fd = expr->getDirectCallee();
250 if (!fd)
251 return true;
252 for (int i = 0; i < expr->getNumArgs(); ++i) {
253 Expr *arg = expr->getArg(i);
254 UnaryOperator *op;
255 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
256 ImplicitCastExpr *ice;
257 ice = cast<ImplicitCastExpr>(arg);
258 arg = ice->getSubExpr();
260 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
261 continue;
262 op = cast<UnaryOperator>(arg);
263 if (op->getOpcode() != UO_AddrOf)
264 continue;
265 if (const_base(fd->getParamDecl(i)->getType()))
266 skip.insert(op);
268 return true;
271 bool VisitUnaryOperator(UnaryOperator *expr) {
272 Expr *arg;
273 DeclRefExpr *ref;
274 ValueDecl *decl;
276 switch (expr->getOpcode()) {
277 case UO_AddrOf:
278 case UO_PostInc:
279 case UO_PostDec:
280 case UO_PreInc:
281 case UO_PreDec:
282 break;
283 default:
284 return true;
286 if (skip.find(expr) != skip.end())
287 return true;
289 arg = expr->getSubExpr();
290 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
291 return true;
292 ref = cast<DeclRefExpr>(arg);
293 decl = ref->getDecl();
294 clear_assignment(assigned_value, decl);
295 return true;
298 bool VisitBinaryOperator(BinaryOperator *expr) {
299 Expr *lhs;
300 DeclRefExpr *ref;
301 ValueDecl *decl;
303 if (!expr->isAssignmentOp())
304 return true;
305 lhs = expr->getLHS();
306 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
307 return true;
308 ref = cast<DeclRefExpr>(lhs);
309 decl = ref->getDecl();
310 clear_assignment(assigned_value, decl);
311 return true;
315 /* Keep a copy of the currently assigned values.
317 * Any variable that is assigned a value inside the current scope
318 * is removed again when we leave the scope (either because it wasn't
319 * stored in the cache or because it has a different value in the cache).
321 struct assigned_value_cache {
322 map<ValueDecl *, isl_pw_aff *> &assigned_value;
323 map<ValueDecl *, isl_pw_aff *> cache;
325 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
326 assigned_value(assigned_value), cache(assigned_value) {}
327 ~assigned_value_cache() {
328 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
329 for (it = assigned_value.begin(); it != assigned_value.end();
330 ++it) {
331 if (!it->second ||
332 (cache.find(it->first) != cache.end() &&
333 cache[it->first] != it->second))
334 cache[it->first] = NULL;
336 assigned_value = cache;
340 /* Convert the mapping from identifiers to values in "assigned_value"
341 * to a pet_context to be used by pet_expr_extract_*.
342 * In particular, the clang identifiers are wrapped in an isl_id and
343 * a NULL value (representing an unknown value) is replaced by a NaN.
345 static __isl_give pet_context *convert_assignments(isl_ctx *ctx,
346 map<ValueDecl *, isl_pw_aff *> &assigned_value)
348 pet_context *pc;
349 map<ValueDecl *, isl_pw_aff *>::iterator it;
351 pc = pet_context_alloc(isl_space_set_alloc(ctx, 0, 0));
353 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
354 ValueDecl *decl = it->first;
355 isl_pw_aff *pa = it->second;
356 isl_id *id;
358 id = create_decl_id(ctx, decl);
359 if (pa)
360 pc = pet_context_set_value(pc, id, isl_pw_aff_copy(pa));
361 else
362 pc = pet_context_mark_unknown(pc, id);
365 return pc;
368 /* Insert an expression into the collection of expressions,
369 * provided it is not already in there.
370 * The isl_pw_affs are freed in the destructor.
372 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
374 std::set<isl_pw_aff *>::iterator it;
376 if (expressions.find(expr) == expressions.end())
377 expressions.insert(expr);
378 else
379 isl_pw_aff_free(expr);
382 PetScan::~PetScan()
384 std::set<isl_pw_aff *>::iterator it;
386 for (it = expressions.begin(); it != expressions.end(); ++it)
387 isl_pw_aff_free(*it);
389 isl_union_map_free(value_bounds);
392 /* Report a diagnostic, unless autodetect is set.
394 void PetScan::report(Stmt *stmt, unsigned id)
396 if (options->autodetect)
397 return;
399 SourceLocation loc = stmt->getLocStart();
400 DiagnosticsEngine &diag = PP.getDiagnostics();
401 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
404 /* Called if we found something we (currently) cannot handle.
405 * We'll provide more informative warnings later.
407 * We only actually complain if autodetect is false.
409 void PetScan::unsupported(Stmt *stmt)
411 DiagnosticsEngine &diag = PP.getDiagnostics();
412 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
413 "unsupported");
414 report(stmt, id);
417 /* Report a missing prototype, unless autodetect is set.
419 void PetScan::report_prototype_required(Stmt *stmt)
421 DiagnosticsEngine &diag = PP.getDiagnostics();
422 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
423 "prototype required");
424 report(stmt, id);
427 /* Report a missing increment, unless autodetect is set.
429 void PetScan::report_missing_increment(Stmt *stmt)
431 DiagnosticsEngine &diag = PP.getDiagnostics();
432 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
433 "missing increment");
434 report(stmt, id);
437 /* Extract an integer from "expr".
439 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
441 const Type *type = expr->getType().getTypePtr();
442 int is_signed = type->hasSignedIntegerRepresentation();
443 llvm::APInt val = expr->getValue();
444 int is_negative = is_signed && val.isNegative();
445 isl_val *v;
447 if (is_negative)
448 val = -val;
450 v = extract_unsigned(ctx, val);
452 if (is_negative)
453 v = isl_val_neg(v);
454 return v;
457 /* Extract an integer from "val", which is assumed to be non-negative.
459 __isl_give isl_val *PetScan::extract_unsigned(isl_ctx *ctx,
460 const llvm::APInt &val)
462 unsigned n;
463 const uint64_t *data;
465 data = val.getRawData();
466 n = val.getNumWords();
467 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
470 /* Extract an integer from "expr".
471 * Return NULL if "expr" does not (obviously) represent an integer.
473 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
475 return extract_int(expr->getSubExpr());
478 /* Extract an integer from "expr".
479 * Return NULL if "expr" does not (obviously) represent an integer.
481 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
483 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
484 return extract_int(ctx, cast<IntegerLiteral>(expr));
485 if (expr->getStmtClass() == Stmt::ParenExprClass)
486 return extract_int(cast<ParenExpr>(expr));
488 unsupported(expr);
489 return NULL;
492 /* Extract an affine expression from the APInt "val", which is assumed
493 * to be non-negative.
494 * If the value of "val" is "v", then the returned expression
495 * is
497 * { [] -> [v] }
499 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
501 isl_space *space = isl_space_set_alloc(ctx, 0, 0);
502 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(space));
503 isl_aff *aff = isl_aff_zero_on_domain(ls);
504 isl_set *dom = isl_set_universe(space);
505 isl_val *v;
507 v = extract_unsigned(ctx, val);
508 aff = isl_aff_add_constant_val(aff, v);
510 return isl_pw_aff_alloc(dom, aff);
513 /* Return the number of bits needed to represent the type "qt",
514 * if it is an integer type. Otherwise return 0.
515 * If qt is signed then return the opposite of the number of bits.
517 static int get_type_size(QualType qt, ASTContext &ast_context)
519 int size;
521 if (!qt->isIntegerType())
522 return 0;
524 size = ast_context.getIntWidth(qt);
525 if (!qt->isUnsignedIntegerType())
526 size = -size;
528 return size;
531 /* Return the number of bits needed to represent the type of "decl",
532 * if it is an integer type. Otherwise return 0.
533 * If qt is signed then return the opposite of the number of bits.
535 static int get_type_size(ValueDecl *decl)
537 return get_type_size(decl->getType(), decl->getASTContext());
540 /* Bound parameter "pos" of "set" to the possible values of "decl".
542 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
543 unsigned pos, ValueDecl *decl)
545 int type_size;
546 isl_ctx *ctx;
547 isl_val *bound;
549 ctx = isl_set_get_ctx(set);
550 type_size = get_type_size(decl);
551 if (type_size == 0)
552 isl_die(ctx, isl_error_invalid, "not an integer type",
553 return isl_set_free(set));
554 if (type_size > 0) {
555 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
556 bound = isl_val_int_from_ui(ctx, type_size);
557 bound = isl_val_2exp(bound);
558 bound = isl_val_sub_ui(bound, 1);
559 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
560 } else {
561 bound = isl_val_int_from_ui(ctx, -type_size - 1);
562 bound = isl_val_2exp(bound);
563 bound = isl_val_sub_ui(bound, 1);
564 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
565 isl_val_copy(bound));
566 bound = isl_val_neg(bound);
567 bound = isl_val_sub_ui(bound, 1);
568 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
571 return set;
574 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
576 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
577 __isl_take isl_set *dom)
579 isl_pw_aff *pa;
580 pa = isl_set_indicator_function(set);
581 pa = isl_pw_aff_intersect_domain(pa, isl_set_coalesce(dom));
582 return pa;
585 /* Extract an affine expression, if possible, from "expr".
586 * Otherwise return NULL.
588 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
590 pet_expr *pe;
591 pet_context *pc;
592 isl_pw_aff *pa;
594 pe = extract_expr(expr);
595 if (!pe)
596 return NULL;
597 pc = convert_assignments(ctx, assigned_value);
598 pc = pet_context_set_allow_nested(pc, nesting_enabled);
599 pa = pet_expr_extract_affine(pe, pc);
600 if (isl_pw_aff_involves_nan(pa)) {
601 unsupported(expr);
602 pa = isl_pw_aff_free(pa);
604 pet_context_free(pc);
605 pet_expr_free(pe);
607 return pa;
610 __isl_give isl_multi_pw_aff *PetScan::extract_index(ImplicitCastExpr *expr)
612 return extract_index(expr->getSubExpr());
615 /* Return the depth of an array of the given type.
617 static int array_depth(const Type *type)
619 if (type->isPointerType())
620 return 1 + array_depth(type->getPointeeType().getTypePtr());
621 if (type->isArrayType()) {
622 const ArrayType *atype;
623 type = type->getCanonicalTypeInternal().getTypePtr();
624 atype = cast<ArrayType>(type);
625 return 1 + array_depth(atype->getElementType().getTypePtr());
627 return 0;
630 /* Return the depth of the array accessed by the index expression "index".
631 * If "index" is an affine expression, i.e., if it does not access
632 * any array, then return 1.
633 * If "index" represent a member access, i.e., if its range is a wrapped
634 * relation, then return the sum of the depth of the array of structures
635 * and that of the member inside the structure.
637 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
639 isl_id *id;
640 ValueDecl *decl;
642 if (!index)
643 return -1;
645 if (isl_multi_pw_aff_range_is_wrapping(index)) {
646 int domain_depth, range_depth;
647 isl_multi_pw_aff *domain, *range;
649 domain = isl_multi_pw_aff_copy(index);
650 domain = isl_multi_pw_aff_range_factor_domain(domain);
651 domain_depth = extract_depth(domain);
652 isl_multi_pw_aff_free(domain);
653 range = isl_multi_pw_aff_copy(index);
654 range = isl_multi_pw_aff_range_factor_range(range);
655 range_depth = extract_depth(range);
656 isl_multi_pw_aff_free(range);
658 return domain_depth + range_depth;
661 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
662 return 1;
664 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
665 if (!id)
666 return -1;
667 decl = (ValueDecl *) isl_id_get_user(id);
668 isl_id_free(id);
670 return array_depth(decl->getType().getTypePtr());
673 /* Extract an index expression from a reference to a variable.
674 * If the variable has name "A", then the returned index expression
675 * is of the form
677 * { [] -> A[] }
679 __isl_give isl_multi_pw_aff *PetScan::extract_index(DeclRefExpr *expr)
681 return extract_index(expr->getDecl());
684 /* Extract an index expression from a variable.
685 * If the variable has name "A", then the returned index expression
686 * is of the form
688 * { [] -> A[] }
690 __isl_give isl_multi_pw_aff *PetScan::extract_index(ValueDecl *decl)
692 isl_id *id = create_decl_id(ctx, decl);
693 isl_space *space = isl_space_alloc(ctx, 0, 0, 0);
695 space = isl_space_set_tuple_id(space, isl_dim_out, id);
697 return isl_multi_pw_aff_zero(space);
700 /* Extract an index expression from an integer contant.
701 * If the value of the constant is "v", then the returned access relation
702 * is
704 * { [] -> [v] }
706 __isl_give isl_multi_pw_aff *PetScan::extract_index(IntegerLiteral *expr)
708 isl_multi_pw_aff *mpa;
710 mpa = isl_multi_pw_aff_from_pw_aff(extract_affine(expr));
711 return mpa;
714 /* Try and extract an index expression from the given Expr.
715 * Return NULL if it doesn't work out.
717 __isl_give isl_multi_pw_aff *PetScan::extract_index(Expr *expr)
719 switch (expr->getStmtClass()) {
720 case Stmt::ImplicitCastExprClass:
721 return extract_index(cast<ImplicitCastExpr>(expr));
722 case Stmt::DeclRefExprClass:
723 return extract_index(cast<DeclRefExpr>(expr));
724 case Stmt::ArraySubscriptExprClass:
725 return extract_index(cast<ArraySubscriptExpr>(expr));
726 case Stmt::IntegerLiteralClass:
727 return extract_index(cast<IntegerLiteral>(expr));
728 case Stmt::MemberExprClass:
729 return extract_index(cast<MemberExpr>(expr));
730 default:
731 unsupported(expr);
733 return NULL;
736 /* Given a partial index expression "base" and an extra index "index",
737 * append the extra index to "base" and return the result.
738 * Additionally, add the constraints that the extra index is non-negative.
739 * If "index" represent a member access, i.e., if its range is a wrapped
740 * relation, then we recursively extend the range of this nested relation.
742 * The inputs "base" and "index", as well as the result, all have
743 * an anonymous zero-dimensional domain.
745 static __isl_give isl_multi_pw_aff *subscript(__isl_take isl_multi_pw_aff *base,
746 __isl_take isl_pw_aff *index)
748 isl_id *id;
749 isl_set *domain;
750 isl_multi_pw_aff *access;
751 int member_access;
753 member_access = isl_multi_pw_aff_range_is_wrapping(base);
754 if (member_access < 0)
755 goto error;
756 if (member_access) {
757 isl_multi_pw_aff *domain, *range;
758 isl_id *id;
760 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_out);
761 domain = isl_multi_pw_aff_copy(base);
762 domain = isl_multi_pw_aff_range_factor_domain(domain);
763 range = isl_multi_pw_aff_range_factor_range(base);
764 range = subscript(range, index);
765 access = isl_multi_pw_aff_range_product(domain, range);
766 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_out, id);
767 return access;
770 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_set);
771 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
772 index = isl_pw_aff_intersect_domain(index, domain);
773 access = isl_multi_pw_aff_from_pw_aff(index);
774 access = isl_multi_pw_aff_flat_range_product(base, access);
775 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_set, id);
777 return access;
778 error:
779 isl_multi_pw_aff_free(base);
780 isl_pw_aff_free(index);
781 return NULL;
784 /* Extract an index expression from the given array subscript expression.
785 * If nesting is allowed in general, then we turn it on while
786 * examining the index expression.
788 * We first extract an index expression from the base.
789 * This will result in an index expression with a range that corresponds
790 * to the earlier indices.
791 * We then extract the current index, restrict its domain
792 * to those values that result in a non-negative index and
793 * append the index to the base index expression.
795 __isl_give isl_multi_pw_aff *PetScan::extract_index(ArraySubscriptExpr *expr)
797 Expr *base = expr->getBase();
798 Expr *idx = expr->getIdx();
799 isl_pw_aff *index;
800 isl_multi_pw_aff *base_access;
801 isl_multi_pw_aff *access;
802 bool save_nesting = nesting_enabled;
804 nesting_enabled = allow_nested;
806 base_access = extract_index(base);
807 index = extract_affine(idx);
809 nesting_enabled = save_nesting;
811 access = subscript(base_access, index);
813 return access;
816 /* Construct a name for a member access by concatenating the name
817 * of the array of structures and the member, separated by an underscore.
819 * The caller is responsible for freeing the result.
821 static char *member_access_name(isl_ctx *ctx, const char *base,
822 const char *field)
824 int len;
825 char *name;
827 len = strlen(base) + 1 + strlen(field);
828 name = isl_alloc_array(ctx, char, len + 1);
829 if (!name)
830 return NULL;
831 snprintf(name, len + 1, "%s_%s", base, field);
833 return name;
836 /* Given an index expression "base" for an element of an array of structures
837 * and an expression "field" for the field member being accessed, construct
838 * an index expression for an access to that member of the given structure.
839 * In particular, take the range product of "base" and "field" and
840 * attach a name to the result.
842 static __isl_give isl_multi_pw_aff *member(__isl_take isl_multi_pw_aff *base,
843 __isl_take isl_multi_pw_aff *field)
845 isl_ctx *ctx;
846 isl_multi_pw_aff *access;
847 const char *base_name, *field_name;
848 char *name;
850 ctx = isl_multi_pw_aff_get_ctx(base);
852 base_name = isl_multi_pw_aff_get_tuple_name(base, isl_dim_out);
853 field_name = isl_multi_pw_aff_get_tuple_name(field, isl_dim_out);
854 name = member_access_name(ctx, base_name, field_name);
856 access = isl_multi_pw_aff_range_product(base, field);
858 access = isl_multi_pw_aff_set_tuple_name(access, isl_dim_out, name);
859 free(name);
861 return access;
864 /* Extract an index expression from a member expression.
866 * If the base access (to the structure containing the member)
867 * is of the form
869 * [] -> A[..]
871 * and the member is called "f", then the member access is of
872 * the form
874 * [] -> A_f[A[..] -> f[]]
876 * If the member access is to an anonymous struct, then simply return
878 * [] -> A[..]
880 * If the member access in the source code is of the form
882 * A->f
884 * then it is treated as
886 * A[0].f
888 __isl_give isl_multi_pw_aff *PetScan::extract_index(MemberExpr *expr)
890 Expr *base = expr->getBase();
891 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
892 isl_multi_pw_aff *base_access, *field_access;
893 isl_id *id;
894 isl_space *space;
896 base_access = extract_index(base);
898 if (expr->isArrow()) {
899 isl_space *space = isl_space_set_alloc(ctx, 0, 0);
900 isl_local_space *ls = isl_local_space_from_space(space);
901 isl_aff *aff = isl_aff_zero_on_domain(ls);
902 isl_pw_aff *index = isl_pw_aff_from_aff(aff);
903 base_access = subscript(base_access, index);
906 if (field->isAnonymousStructOrUnion())
907 return base_access;
909 id = create_decl_id(ctx, field);
910 space = isl_multi_pw_aff_get_domain_space(base_access);
911 space = isl_space_from_domain(space);
912 space = isl_space_set_tuple_id(space, isl_dim_out, id);
913 field_access = isl_multi_pw_aff_zero(space);
915 return member(base_access, field_access);
918 /* Check if "expr" calls function "minmax" with two arguments and if so
919 * make lhs and rhs refer to these two arguments.
921 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
923 CallExpr *call;
924 FunctionDecl *fd;
925 string name;
927 if (expr->getStmtClass() != Stmt::CallExprClass)
928 return false;
930 call = cast<CallExpr>(expr);
931 fd = call->getDirectCallee();
932 if (!fd)
933 return false;
935 if (call->getNumArgs() != 2)
936 return false;
938 name = fd->getDeclName().getAsString();
939 if (name != minmax)
940 return false;
942 lhs = call->getArg(0);
943 rhs = call->getArg(1);
945 return true;
948 /* Check if "expr" is of the form min(lhs, rhs) and if so make
949 * lhs and rhs refer to the two arguments.
951 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
953 return is_minmax(expr, "min", lhs, rhs);
956 /* Check if "expr" is of the form max(lhs, rhs) and if so make
957 * lhs and rhs refer to the two arguments.
959 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
961 return is_minmax(expr, "max", lhs, rhs);
964 /* Extract an affine expressions representing the comparison "LHS op RHS"
965 * "comp" is the original statement that "LHS op RHS" is derived from
966 * and is used for diagnostics.
968 * If the comparison is of the form
970 * a <= min(b,c)
972 * then the expression is constructed as the conjunction of
973 * the comparisons
975 * a <= b and a <= c
977 * A similar optimization is performed for max(a,b) <= c.
978 * We do this because that will lead to simpler representations
979 * of the expression.
980 * If isl is ever enhanced to explicitly deal with min and max expressions,
981 * this optimization can be removed.
983 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
984 Expr *LHS, Expr *RHS, Stmt *comp)
986 isl_pw_aff *lhs;
987 isl_pw_aff *rhs;
988 isl_pw_aff *res;
989 isl_set *cond;
990 isl_set *dom;
991 enum pet_op_type type;
993 if (op == BO_GT)
994 return extract_comparison(BO_LT, RHS, LHS, comp);
995 if (op == BO_GE)
996 return extract_comparison(BO_LE, RHS, LHS, comp);
998 if (op == BO_LT || op == BO_LE) {
999 Expr *expr1, *expr2;
1000 if (is_min(RHS, expr1, expr2)) {
1001 lhs = extract_comparison(op, LHS, expr1, comp);
1002 rhs = extract_comparison(op, LHS, expr2, comp);
1003 return pet_and(lhs, rhs);
1005 if (is_max(LHS, expr1, expr2)) {
1006 lhs = extract_comparison(op, expr1, RHS, comp);
1007 rhs = extract_comparison(op, expr2, RHS, comp);
1008 return pet_and(lhs, rhs);
1012 lhs = extract_affine(LHS);
1013 rhs = extract_affine(RHS);
1015 type = BinaryOperatorKind2pet_op_type(op);
1016 return pet_comparison(type, lhs, rhs);
1019 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1021 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1022 comp->getRHS(), comp);
1025 /* Extract an affine expression from a boolean expression.
1026 * In particular, return the expression "expr ? 1 : 0".
1027 * Return NULL if we are unable to extract an affine expression.
1029 * We first convert the clang::Expr to a pet_expr and
1030 * then extract an affine expression from that pet_expr.
1032 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1034 isl_pw_aff *cond;
1035 pet_expr *pe;
1036 pet_context *pc;
1038 if (!expr) {
1039 isl_set *u = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
1040 return indicator_function(u, isl_set_copy(u));
1043 pe = extract_expr(expr);
1044 pc = convert_assignments(ctx, assigned_value);
1045 pc = pet_context_set_allow_nested(pc, nesting_enabled);
1046 cond = pet_expr_extract_affine_condition(pe, pc);
1047 if (isl_pw_aff_involves_nan(cond))
1048 cond = isl_pw_aff_free(cond);
1049 pet_context_free(pc);
1050 pet_expr_free(pe);
1051 return cond;
1054 /* Construct a pet_expr representing a unary operator expression.
1056 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1058 pet_expr *arg;
1059 enum pet_op_type op;
1061 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1062 if (op == pet_op_last) {
1063 unsupported(expr);
1064 return NULL;
1067 arg = extract_expr(expr->getSubExpr());
1069 if (expr->isIncrementDecrementOp() &&
1070 pet_expr_get_type(arg) == pet_expr_access) {
1071 arg = mark_write(arg);
1072 arg = pet_expr_access_set_read(arg, 1);
1075 return pet_expr_new_unary(op, arg);
1078 /* Mark the given access pet_expr as a write.
1079 * If a scalar is being accessed, then mark its value
1080 * as unknown in assigned_value.
1082 __isl_give pet_expr *PetScan::mark_write(__isl_take pet_expr *access)
1084 isl_id *id;
1085 ValueDecl *decl;
1087 access = pet_expr_access_set_write(access, 1);
1088 access = pet_expr_access_set_read(access, 0);
1090 if (!access || !pet_expr_is_scalar_access(access))
1091 return access;
1093 id = pet_expr_access_get_id(access);
1094 decl = (ValueDecl *) isl_id_get_user(id);
1095 clear_assignment(assigned_value, decl);
1096 isl_id_free(id);
1098 return access;
1101 /* Assign "rhs" to "lhs".
1103 * In particular, if "lhs" is a scalar variable, then mark
1104 * the variable as having been assigned. If, furthermore, "rhs"
1105 * is an affine expression, then keep track of this value in assigned_value
1106 * so that we can plug it in when we later come across the same variable.
1108 void PetScan::assign(__isl_keep pet_expr *lhs, __isl_keep pet_expr *rhs)
1110 isl_id *id;
1111 ValueDecl *decl;
1112 pet_context *pc;
1113 isl_pw_aff *pa;
1115 if (!lhs)
1116 return;
1117 if (!pet_expr_is_scalar_access(lhs))
1118 return;
1120 id = pet_expr_access_get_id(lhs);
1121 decl = (ValueDecl *) isl_id_get_user(id);
1122 isl_id_free(id);
1124 pc = convert_assignments(ctx, assigned_value);
1125 pa = pet_expr_extract_affine(rhs, pc);
1126 pet_context_free(pc);
1127 clear_assignment(assigned_value, decl);
1128 if (isl_pw_aff_involves_nan(pa))
1129 pa = isl_pw_aff_free(pa);
1130 if (!pa)
1131 return;
1132 assigned_value[decl] = pa;
1133 insert_expression(pa);
1136 /* Construct a pet_expr representing a binary operator expression.
1138 * If the top level operator is an assignment and the LHS is an access,
1139 * then we mark that access as a write. If the operator is a compound
1140 * assignment, the access is marked as both a read and a write.
1142 * If "expr" assigns something to a scalar variable, then we mark
1143 * the variable as having been assigned. If, furthermore, the expression
1144 * is affine, then keep track of this value in assigned_value
1145 * so that we can plug it in when we later come across the same variable.
1147 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1149 int type_size;
1150 pet_expr *lhs, *rhs;
1151 enum pet_op_type op;
1153 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1154 if (op == pet_op_last) {
1155 unsupported(expr);
1156 return NULL;
1159 lhs = extract_expr(expr->getLHS());
1160 rhs = extract_expr(expr->getRHS());
1162 if (expr->isAssignmentOp() &&
1163 pet_expr_get_type(lhs) == pet_expr_access) {
1164 lhs = mark_write(lhs);
1165 if (expr->isCompoundAssignmentOp())
1166 lhs = pet_expr_access_set_read(lhs, 1);
1169 if (expr->getOpcode() == BO_Assign)
1170 assign(lhs, rhs);
1172 type_size = get_type_size(expr->getType(), ast_context);
1173 return pet_expr_new_binary(type_size, op, lhs, rhs);
1176 /* Construct a pet_scop with a single statement killing the entire
1177 * array "array".
1179 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1181 isl_id *id;
1182 isl_space *space;
1183 isl_multi_pw_aff *index;
1184 isl_map *access;
1185 pet_expr *expr;
1187 if (!array)
1188 return NULL;
1189 access = isl_map_from_range(isl_set_copy(array->extent));
1190 id = isl_set_get_tuple_id(array->extent);
1191 space = isl_space_alloc(ctx, 0, 0, 0);
1192 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1193 index = isl_multi_pw_aff_zero(space);
1194 expr = pet_expr_kill_from_access_and_index(access, index);
1195 return extract(expr, stmt->getSourceRange(), false);
1198 /* Construct a pet_scop for a (single) variable declaration.
1200 * The scop contains the variable being declared (as an array)
1201 * and a statement killing the array.
1203 * If the variable is initialized in the AST, then the scop
1204 * also contains an assignment to the variable.
1206 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1208 int type_size;
1209 Decl *decl;
1210 VarDecl *vd;
1211 pet_expr *lhs, *rhs, *pe;
1212 struct pet_scop *scop_decl, *scop;
1213 struct pet_array *array;
1215 if (!stmt->isSingleDecl()) {
1216 unsupported(stmt);
1217 return NULL;
1220 decl = stmt->getSingleDecl();
1221 vd = cast<VarDecl>(decl);
1223 array = extract_array(ctx, vd, NULL);
1224 if (array)
1225 array->declared = 1;
1226 scop_decl = kill(stmt, array);
1227 scop_decl = pet_scop_add_array(scop_decl, array);
1229 if (!vd->getInit())
1230 return scop_decl;
1232 lhs = extract_access_expr(vd);
1233 rhs = extract_expr(vd->getInit());
1235 lhs = mark_write(lhs);
1236 assign(lhs, rhs);
1238 type_size = get_type_size(vd->getType(), ast_context);
1239 pe = pet_expr_new_binary(type_size, pet_op_assign, lhs, rhs);
1240 scop = extract(pe, stmt->getSourceRange(), false);
1242 scop_decl = pet_scop_prefix(scop_decl, 0);
1243 scop = pet_scop_prefix(scop, 1);
1245 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1247 return scop;
1250 /* Construct a pet_expr representing a conditional operation.
1252 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1254 pet_expr *cond, *lhs, *rhs;
1255 isl_pw_aff *pa;
1257 cond = extract_expr(expr->getCond());
1258 lhs = extract_expr(expr->getTrueExpr());
1259 rhs = extract_expr(expr->getFalseExpr());
1261 return pet_expr_new_ternary(cond, lhs, rhs);
1264 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1266 return extract_expr(expr->getSubExpr());
1269 /* Construct a pet_expr representing a floating point value.
1271 * If the floating point literal does not appear in a macro,
1272 * then we use the original representation in the source code
1273 * as the string representation. Otherwise, we use the pretty
1274 * printer to produce a string representation.
1276 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1278 double d;
1279 string s;
1280 const LangOptions &LO = PP.getLangOpts();
1281 SourceLocation loc = expr->getLocation();
1283 if (!loc.isMacroID()) {
1284 SourceManager &SM = PP.getSourceManager();
1285 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1286 s = string(SM.getCharacterData(loc), len);
1287 } else {
1288 llvm::raw_string_ostream S(s);
1289 expr->printPretty(S, 0, PrintingPolicy(LO));
1290 S.str();
1292 d = expr->getValueAsApproximateDouble();
1293 return pet_expr_new_double(ctx, d, s.c_str());
1296 /* Convert the index expression "index" into an access pet_expr of type "qt".
1298 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
1299 __isl_take isl_multi_pw_aff *index)
1301 pet_expr *pe;
1302 int depth;
1303 int type_size;
1305 depth = extract_depth(index);
1306 type_size = get_type_size(qt, ast_context);
1308 pe = pet_expr_from_index_and_depth(type_size, index, depth);
1310 return pe;
1313 /* Extract an index expression from "expr" and then convert it into
1314 * an access pet_expr.
1316 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
1318 return extract_access_expr(expr->getType(), extract_index(expr));
1321 /* Extract an index expression from "decl" and then convert it into
1322 * an access pet_expr.
1324 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1326 return extract_access_expr(decl->getType(), extract_index(decl));
1329 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
1331 return extract_expr(expr->getSubExpr());
1334 /* Extract an assume statement from the argument "expr"
1335 * of a __pencil_assume statement.
1337 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
1339 isl_pw_aff *cond;
1340 pet_expr *res;
1342 cond = try_extract_affine_condition(expr);
1343 if (!cond) {
1344 res = extract_expr(expr);
1345 } else {
1346 isl_multi_pw_aff *index;
1347 index = isl_multi_pw_aff_from_pw_aff(cond);
1348 res = pet_expr_from_index(index);
1350 return pet_expr_new_unary(pet_op_assume, res);
1353 /* Construct a pet_expr corresponding to the function call argument "expr".
1354 * The argument appears in position "pos" of a call to function "fd".
1356 * If we are passing along a pointer to an array element
1357 * or an entire row or even higher dimensional slice of an array,
1358 * then the function being called may write into the array.
1360 * We assume here that if the function is declared to take a pointer
1361 * to a const type, then the function will perform a read
1362 * and that otherwise, it will perform a write.
1364 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
1365 Expr *expr)
1367 pet_expr *res;
1368 int is_addr = 0, is_partial = 0;
1369 Stmt::StmtClass sc;
1371 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
1372 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
1373 expr = ice->getSubExpr();
1375 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
1376 UnaryOperator *op = cast<UnaryOperator>(expr);
1377 if (op->getOpcode() == UO_AddrOf) {
1378 is_addr = 1;
1379 expr = op->getSubExpr();
1382 res = extract_expr(expr);
1383 if (!res)
1384 return NULL;
1385 sc = expr->getStmtClass();
1386 if ((sc == Stmt::ArraySubscriptExprClass ||
1387 sc == Stmt::MemberExprClass) &&
1388 array_depth(expr->getType().getTypePtr()) > 0)
1389 is_partial = 1;
1390 if ((is_addr || is_partial) &&
1391 pet_expr_get_type(res) == pet_expr_access) {
1392 ParmVarDecl *parm;
1393 if (!fd->hasPrototype()) {
1394 report_prototype_required(expr);
1395 return pet_expr_free(res);
1397 parm = fd->getParamDecl(pos);
1398 if (!const_base(parm->getType()))
1399 res = mark_write(res);
1402 if (is_addr)
1403 res = pet_expr_new_unary(pet_op_address_of, res);
1404 return res;
1407 /* Construct a pet_expr representing a function call.
1409 * In the special case of a "call" to __pencil_assume,
1410 * construct an assume expression instead.
1412 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1414 pet_expr *res = NULL;
1415 FunctionDecl *fd;
1416 string name;
1417 unsigned n_arg;
1419 fd = expr->getDirectCallee();
1420 if (!fd) {
1421 unsupported(expr);
1422 return NULL;
1425 name = fd->getDeclName().getAsString();
1426 n_arg = expr->getNumArgs();
1428 if (n_arg == 1 && name == "__pencil_assume")
1429 return extract_assume(expr->getArg(0));
1431 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1432 if (!res)
1433 return NULL;
1435 for (int i = 0; i < n_arg; ++i) {
1436 Expr *arg = expr->getArg(i);
1437 res = pet_expr_set_arg(res, i,
1438 PetScan::extract_argument(fd, i, arg));
1441 return res;
1444 /* Construct a pet_expr representing a (C style) cast.
1446 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1448 pet_expr *arg;
1449 QualType type;
1451 arg = extract_expr(expr->getSubExpr());
1452 if (!arg)
1453 return NULL;
1455 type = expr->getTypeAsWritten();
1456 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1459 /* Construct a pet_expr representing an integer.
1461 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1463 return pet_expr_new_int(extract_int(expr));
1466 /* Try and construct a pet_expr representing "expr".
1468 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1470 switch (expr->getStmtClass()) {
1471 case Stmt::UnaryOperatorClass:
1472 return extract_expr(cast<UnaryOperator>(expr));
1473 case Stmt::CompoundAssignOperatorClass:
1474 case Stmt::BinaryOperatorClass:
1475 return extract_expr(cast<BinaryOperator>(expr));
1476 case Stmt::ImplicitCastExprClass:
1477 return extract_expr(cast<ImplicitCastExpr>(expr));
1478 case Stmt::ArraySubscriptExprClass:
1479 case Stmt::DeclRefExprClass:
1480 case Stmt::MemberExprClass:
1481 return extract_access_expr(expr);
1482 case Stmt::IntegerLiteralClass:
1483 return extract_expr(cast<IntegerLiteral>(expr));
1484 case Stmt::FloatingLiteralClass:
1485 return extract_expr(cast<FloatingLiteral>(expr));
1486 case Stmt::ParenExprClass:
1487 return extract_expr(cast<ParenExpr>(expr));
1488 case Stmt::ConditionalOperatorClass:
1489 return extract_expr(cast<ConditionalOperator>(expr));
1490 case Stmt::CallExprClass:
1491 return extract_expr(cast<CallExpr>(expr));
1492 case Stmt::CStyleCastExprClass:
1493 return extract_expr(cast<CStyleCastExpr>(expr));
1494 default:
1495 unsupported(expr);
1497 return NULL;
1500 /* Check if the given initialization statement is an assignment.
1501 * If so, return that assignment. Otherwise return NULL.
1503 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1505 BinaryOperator *ass;
1507 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1508 return NULL;
1510 ass = cast<BinaryOperator>(init);
1511 if (ass->getOpcode() != BO_Assign)
1512 return NULL;
1514 return ass;
1517 /* Check if the given initialization statement is a declaration
1518 * of a single variable.
1519 * If so, return that declaration. Otherwise return NULL.
1521 Decl *PetScan::initialization_declaration(Stmt *init)
1523 DeclStmt *decl;
1525 if (init->getStmtClass() != Stmt::DeclStmtClass)
1526 return NULL;
1528 decl = cast<DeclStmt>(init);
1530 if (!decl->isSingleDecl())
1531 return NULL;
1533 return decl->getSingleDecl();
1536 /* Given the assignment operator in the initialization of a for loop,
1537 * extract the induction variable, i.e., the (integer)variable being
1538 * assigned.
1540 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1542 Expr *lhs;
1543 DeclRefExpr *ref;
1544 ValueDecl *decl;
1545 const Type *type;
1547 lhs = init->getLHS();
1548 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1549 unsupported(init);
1550 return NULL;
1553 ref = cast<DeclRefExpr>(lhs);
1554 decl = ref->getDecl();
1555 type = decl->getType().getTypePtr();
1557 if (!type->isIntegerType()) {
1558 unsupported(lhs);
1559 return NULL;
1562 return decl;
1565 /* Given the initialization statement of a for loop and the single
1566 * declaration in this initialization statement,
1567 * extract the induction variable, i.e., the (integer) variable being
1568 * declared.
1570 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1572 VarDecl *vd;
1574 vd = cast<VarDecl>(decl);
1576 const QualType type = vd->getType();
1577 if (!type->isIntegerType()) {
1578 unsupported(init);
1579 return NULL;
1582 if (!vd->getInit()) {
1583 unsupported(init);
1584 return NULL;
1587 return vd;
1590 /* Check that op is of the form iv++ or iv--.
1591 * Return a pet_expr representing "1" or "-1" accordingly.
1593 __isl_give pet_expr *PetScan::extract_unary_increment(
1594 clang::UnaryOperator *op, clang::ValueDecl *iv)
1596 Expr *sub;
1597 DeclRefExpr *ref;
1598 isl_val *v;
1600 if (!op->isIncrementDecrementOp()) {
1601 unsupported(op);
1602 return NULL;
1605 sub = op->getSubExpr();
1606 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1607 unsupported(op);
1608 return NULL;
1611 ref = cast<DeclRefExpr>(sub);
1612 if (ref->getDecl() != iv) {
1613 unsupported(op);
1614 return NULL;
1617 if (op->isIncrementOp())
1618 v = isl_val_one(ctx);
1619 else
1620 v = isl_val_negone(ctx);
1622 return pet_expr_new_int(v);
1625 /* Check if op is of the form
1627 * iv = expr
1629 * and return the increment "expr - iv" as a pet_expr.
1631 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1632 clang::ValueDecl *iv)
1634 int type_size;
1635 Expr *lhs;
1636 DeclRefExpr *ref;
1637 pet_expr *expr, *expr_iv;
1639 if (op->getOpcode() != BO_Assign) {
1640 unsupported(op);
1641 return NULL;
1644 lhs = op->getLHS();
1645 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1646 unsupported(op);
1647 return NULL;
1650 ref = cast<DeclRefExpr>(lhs);
1651 if (ref->getDecl() != iv) {
1652 unsupported(op);
1653 return NULL;
1656 expr = extract_expr(op->getRHS());
1657 expr_iv = extract_expr(lhs);
1659 type_size = get_type_size(iv->getType(), ast_context);
1660 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1663 /* Check that op is of the form iv += cst or iv -= cst
1664 * and return a pet_expr corresponding to cst or -cst accordingly.
1666 __isl_give pet_expr *PetScan::extract_compound_increment(
1667 CompoundAssignOperator *op, clang::ValueDecl *iv)
1669 Expr *lhs;
1670 DeclRefExpr *ref;
1671 bool neg = false;
1672 pet_expr *expr;
1673 BinaryOperatorKind opcode;
1675 opcode = op->getOpcode();
1676 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1677 unsupported(op);
1678 return NULL;
1680 if (opcode == BO_SubAssign)
1681 neg = true;
1683 lhs = op->getLHS();
1684 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1685 unsupported(op);
1686 return NULL;
1689 ref = cast<DeclRefExpr>(lhs);
1690 if (ref->getDecl() != iv) {
1691 unsupported(op);
1692 return NULL;
1695 expr = extract_expr(op->getRHS());
1696 if (neg)
1697 expr = pet_expr_new_unary(pet_op_minus, expr);
1699 return expr;
1702 /* Check that the increment of the given for loop increments
1703 * (or decrements) the induction variable "iv" and return
1704 * the increment as a pet_expr if successful.
1706 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1707 ValueDecl *iv)
1709 Stmt *inc = stmt->getInc();
1711 if (!inc) {
1712 report_missing_increment(stmt);
1713 return NULL;
1716 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1717 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1718 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1719 return extract_compound_increment(
1720 cast<CompoundAssignOperator>(inc), iv);
1721 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1722 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1724 unsupported(inc);
1725 return NULL;
1728 /* Embed the given iteration domain in an extra outer loop
1729 * with induction variable "var".
1730 * If this variable appeared as a parameter in the constraints,
1731 * it is replaced by the new outermost dimension.
1733 static __isl_give isl_set *embed(__isl_take isl_set *set,
1734 __isl_take isl_id *var)
1736 int pos;
1738 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1739 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1740 if (pos >= 0) {
1741 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1742 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1745 isl_id_free(var);
1746 return set;
1749 /* Return those elements in the space of "cond" that come after
1750 * (based on "sign") an element in "cond".
1752 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
1754 isl_map *previous_to_this;
1756 if (sign > 0)
1757 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
1758 else
1759 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
1761 cond = isl_set_apply(cond, previous_to_this);
1763 return cond;
1766 /* Create the infinite iteration domain
1768 * { [id] : id >= 0 }
1770 * If "scop" has an affine skip of type pet_skip_later,
1771 * then remove those iterations i that have an earlier iteration
1772 * where the skip condition is satisfied, meaning that iteration i
1773 * is not executed.
1774 * Since we are dealing with a loop without loop iterator,
1775 * the skip condition cannot refer to the current loop iterator and
1776 * so effectively, the returned set is of the form
1778 * { [0]; [id] : id >= 1 and not skip }
1780 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
1781 struct pet_scop *scop)
1783 isl_ctx *ctx = isl_id_get_ctx(id);
1784 isl_set *domain;
1785 isl_set *skip;
1787 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1788 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
1790 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
1791 return domain;
1793 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
1794 skip = embed(skip, isl_id_copy(id));
1795 skip = isl_set_intersect(skip , isl_set_copy(domain));
1796 domain = isl_set_subtract(domain, after(skip, 1));
1798 return domain;
1801 /* Create an identity affine expression on the space containing "domain",
1802 * which is assumed to be one-dimensional.
1804 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
1806 isl_local_space *ls;
1808 ls = isl_local_space_from_space(isl_set_get_space(domain));
1809 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
1812 /* Create an affine expression that maps elements
1813 * of a single-dimensional array "id_test" to the previous element
1814 * (according to "inc"), provided this element belongs to "domain".
1815 * That is, create the affine expression
1817 * { id[x] -> id[x - inc] : x - inc in domain }
1819 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
1820 __isl_take isl_set *domain, __isl_take isl_val *inc)
1822 isl_space *space;
1823 isl_local_space *ls;
1824 isl_aff *aff;
1825 isl_multi_pw_aff *prev;
1827 space = isl_set_get_space(domain);
1828 ls = isl_local_space_from_space(space);
1829 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
1830 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
1831 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
1832 domain = isl_set_preimage_multi_pw_aff(domain,
1833 isl_multi_pw_aff_copy(prev));
1834 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
1835 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
1837 return prev;
1840 /* Add an implication to "scop" expressing that if an element of
1841 * virtual array "id_test" has value "satisfied" then all previous elements
1842 * of this array also have that value. The set of previous elements
1843 * is bounded by "domain". If "sign" is negative then the iterator
1844 * is decreasing and we express that all subsequent array elements
1845 * (but still defined previously) have the same value.
1847 static struct pet_scop *add_implication(struct pet_scop *scop,
1848 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
1849 int satisfied)
1851 isl_space *space;
1852 isl_map *map;
1854 domain = isl_set_set_tuple_id(domain, id_test);
1855 space = isl_set_get_space(domain);
1856 if (sign > 0)
1857 map = isl_map_lex_ge(space);
1858 else
1859 map = isl_map_lex_le(space);
1860 map = isl_map_intersect_range(map, domain);
1861 scop = pet_scop_add_implication(scop, map, satisfied);
1863 return scop;
1866 /* Add a filter to "scop" that imposes that it is only executed
1867 * when the variable identified by "id_test" has a zero value
1868 * for all previous iterations of "domain".
1870 * In particular, add a filter that imposes that the array
1871 * has a zero value at the previous iteration of domain and
1872 * add an implication that implies that it then has that
1873 * value for all previous iterations.
1875 static struct pet_scop *scop_add_break(struct pet_scop *scop,
1876 __isl_take isl_id *id_test, __isl_take isl_set *domain,
1877 __isl_take isl_val *inc)
1879 isl_multi_pw_aff *prev;
1880 int sign = isl_val_sgn(inc);
1882 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
1883 scop = add_implication(scop, id_test, domain, sign, 0);
1884 scop = pet_scop_filter(scop, prev, 0);
1886 return scop;
1889 /* Construct a pet_scop for an infinite loop around the given body.
1891 * We extract a pet_scop for the body and then embed it in a loop with
1892 * iteration domain
1894 * { [t] : t >= 0 }
1896 * and schedule
1898 * { [t] -> [t] }
1900 * If the body contains any break, then it is taken into
1901 * account in infinite_domain (if the skip condition is affine)
1902 * or in scop_add_break (if the skip condition is not affine).
1904 * If we were only able to extract part of the body, then simply
1905 * return that part.
1907 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1909 isl_id *id, *id_test;
1910 isl_set *domain;
1911 isl_aff *ident;
1912 struct pet_scop *scop;
1913 bool has_var_break;
1915 scop = extract(body);
1916 if (!scop)
1917 return NULL;
1918 if (partial)
1919 return scop;
1921 id = isl_id_alloc(ctx, "t", NULL);
1922 domain = infinite_domain(isl_id_copy(id), scop);
1923 ident = identity_aff(domain);
1925 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
1926 if (has_var_break)
1927 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
1929 scop = pet_scop_embed(scop, isl_set_copy(domain),
1930 isl_aff_copy(ident), ident, id);
1931 if (has_var_break)
1932 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
1933 else
1934 isl_set_free(domain);
1936 return scop;
1939 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1941 * for (;;)
1942 * body
1945 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1947 clear_assignments clear(assigned_value);
1948 clear.TraverseStmt(stmt->getBody());
1950 return extract_infinite_loop(stmt->getBody());
1953 /* Add an array with the given extent (range of "index") to the list
1954 * of arrays in "scop" and return the extended pet_scop.
1955 * The array is marked as attaining values 0 and 1 only and
1956 * as each element being assigned at most once.
1958 static struct pet_scop *scop_add_array(struct pet_scop *scop,
1959 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
1961 int int_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
1963 return pet_scop_add_boolean_array(scop, isl_multi_pw_aff_copy(index),
1964 int_size);
1967 /* Construct a pet_scop for a while loop of the form
1969 * while (pa)
1970 * body
1972 * In particular, construct a scop for an infinite loop around body and
1973 * intersect the domain with the affine expression.
1974 * Note that this intersection may result in an empty loop.
1976 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
1977 Stmt *body)
1979 struct pet_scop *scop;
1980 isl_set *dom;
1981 isl_set *valid;
1983 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
1984 dom = isl_pw_aff_non_zero_set(pa);
1985 scop = extract_infinite_loop(body);
1986 scop = pet_scop_restrict(scop, isl_set_params(dom));
1987 scop = pet_scop_restrict_context(scop, isl_set_params(valid));
1989 return scop;
1992 /* Construct a scop for a while, given the scops for the condition
1993 * and the body, the filter identifier and the iteration domain of
1994 * the while loop.
1996 * In particular, the scop for the condition is filtered to depend
1997 * on "id_test" evaluating to true for all previous iterations
1998 * of the loop, while the scop for the body is filtered to depend
1999 * on "id_test" evaluating to true for all iterations up to the
2000 * current iteration.
2001 * The actual filter only imposes that this virtual array has
2002 * value one on the previous or the current iteration.
2003 * The fact that this condition also applies to the previous
2004 * iterations is enforced by an implication.
2006 * These filtered scops are then combined into a single scop.
2008 * "sign" is positive if the iterator increases and negative
2009 * if it decreases.
2011 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2012 struct pet_scop *scop_body, __isl_take isl_id *id_test,
2013 __isl_take isl_set *domain, __isl_take isl_val *inc)
2015 isl_ctx *ctx = isl_set_get_ctx(domain);
2016 isl_space *space;
2017 isl_multi_pw_aff *test_index;
2018 isl_multi_pw_aff *prev;
2019 int sign = isl_val_sgn(inc);
2020 struct pet_scop *scop;
2022 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2023 scop_cond = pet_scop_filter(scop_cond, prev, 1);
2025 space = isl_space_map_from_set(isl_set_get_space(domain));
2026 test_index = isl_multi_pw_aff_identity(space);
2027 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
2028 isl_id_copy(id_test));
2029 scop_body = pet_scop_filter(scop_body, test_index, 1);
2031 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
2032 scop = add_implication(scop, id_test, domain, sign, 1);
2034 return scop;
2037 /* Check if the while loop is of the form
2039 * while (affine expression)
2040 * body
2042 * If so, call extract_affine_while to construct a scop.
2044 * Otherwise, extract the body and pass control to extract_while
2045 * to extend the iteration domain with an infinite loop.
2046 * If we were only able to extract part of the body, then simply
2047 * return that part.
2049 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2051 Expr *cond;
2052 int test_nr, stmt_nr;
2053 isl_pw_aff *pa;
2054 struct pet_scop *scop_body;
2056 cond = stmt->getCond();
2057 if (!cond) {
2058 unsupported(stmt);
2059 return NULL;
2062 clear_assignments clear(assigned_value);
2063 clear.TraverseStmt(stmt->getBody());
2065 pa = try_extract_affine_condition(cond);
2066 if (pa)
2067 return extract_affine_while(pa, stmt->getBody());
2069 if (!allow_nested) {
2070 unsupported(stmt);
2071 return NULL;
2074 test_nr = n_test++;
2075 stmt_nr = n_stmt++;
2076 scop_body = extract(stmt->getBody());
2077 if (partial)
2078 return scop_body;
2080 return extract_while(cond, test_nr, stmt_nr, scop_body, NULL);
2083 /* Construct a generic while scop, with iteration domain
2084 * { [t] : t >= 0 } around "scop_body". The scop consists of two parts,
2085 * one for evaluating the condition "cond" and one for the body.
2086 * "test_nr" is the sequence number of the virtual test variable that contains
2087 * the result of the condition and "stmt_nr" is the sequence number
2088 * of the statement that evaluates the condition.
2089 * If "scop_inc" is not NULL, then it is added at the end of the body,
2090 * after replacing any skip conditions resulting from continue statements
2091 * by the skip conditions resulting from break statements (if any).
2093 * The schedule is adjusted to reflect that the condition is evaluated
2094 * before the body is executed and the body is filtered to depend
2095 * on the result of the condition evaluating to true on all iterations
2096 * up to the current iteration, while the evaluation of the condition itself
2097 * is filtered to depend on the result of the condition evaluating to true
2098 * on all previous iterations.
2099 * The context of the scop representing the body is dropped
2100 * because we don't know how many times the body will be executed,
2101 * if at all.
2103 * If the body contains any break, then it is taken into
2104 * account in infinite_domain (if the skip condition is affine)
2105 * or in scop_add_break (if the skip condition is not affine).
2107 struct pet_scop *PetScan::extract_while(Expr *cond, int test_nr, int stmt_nr,
2108 struct pet_scop *scop_body, struct pet_scop *scop_inc)
2110 isl_id *id, *id_test, *id_break_test;
2111 isl_set *domain;
2112 isl_aff *ident;
2113 isl_multi_pw_aff *test_index;
2114 struct pet_scop *scop;
2115 bool has_var_break;
2117 test_index = pet_create_test_index(ctx, test_nr);
2118 scop = extract_non_affine_condition(cond, stmt_nr,
2119 isl_multi_pw_aff_copy(test_index));
2120 scop = scop_add_array(scop, test_index, ast_context);
2121 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2122 isl_multi_pw_aff_free(test_index);
2124 id = isl_id_alloc(ctx, "t", NULL);
2125 domain = infinite_domain(isl_id_copy(id), scop_body);
2126 ident = identity_aff(domain);
2128 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2129 if (has_var_break)
2130 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2132 scop = pet_scop_prefix(scop, 0);
2133 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_aff_copy(ident),
2134 isl_aff_copy(ident), isl_id_copy(id));
2135 scop_body = pet_scop_reset_context(scop_body);
2136 scop_body = pet_scop_prefix(scop_body, 1);
2137 if (scop_inc) {
2138 scop_inc = pet_scop_prefix(scop_inc, 2);
2139 if (pet_scop_has_skip(scop_body, pet_skip_later)) {
2140 isl_multi_pw_aff *skip;
2141 skip = pet_scop_get_skip(scop_body, pet_skip_later);
2142 scop_body = pet_scop_set_skip(scop_body,
2143 pet_skip_now, skip);
2144 } else
2145 pet_scop_reset_skip(scop_body, pet_skip_now);
2146 scop_body = pet_scop_add_seq(ctx, scop_body, scop_inc);
2148 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2149 isl_aff_copy(ident), ident, id);
2151 if (has_var_break) {
2152 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2153 isl_set_copy(domain), isl_val_one(ctx));
2154 scop_body = scop_add_break(scop_body, id_break_test,
2155 isl_set_copy(domain), isl_val_one(ctx));
2157 scop = scop_add_while(scop, scop_body, id_test, domain,
2158 isl_val_one(ctx));
2160 return scop;
2163 /* Check whether "cond" expresses a simple loop bound
2164 * on the only set dimension.
2165 * In particular, if "up" is set then "cond" should contain only
2166 * upper bounds on the set dimension.
2167 * Otherwise, it should contain only lower bounds.
2169 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2171 if (isl_val_is_pos(inc))
2172 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2173 else
2174 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2177 /* Extend a condition on a given iteration of a loop to one that
2178 * imposes the same condition on all previous iterations.
2179 * "domain" expresses the lower [upper] bound on the iterations
2180 * when inc is positive [negative].
2182 * In particular, we construct the condition (when inc is positive)
2184 * forall i' : (domain(i') and i' <= i) => cond(i')
2186 * which is equivalent to
2188 * not exists i' : domain(i') and i' <= i and not cond(i')
2190 * We construct this set by negating cond, applying a map
2192 * { [i'] -> [i] : domain(i') and i' <= i }
2194 * and then negating the result again.
2196 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2197 __isl_take isl_set *domain, __isl_take isl_val *inc)
2199 isl_map *previous_to_this;
2201 if (isl_val_is_pos(inc))
2202 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2203 else
2204 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2206 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2208 cond = isl_set_complement(cond);
2209 cond = isl_set_apply(cond, previous_to_this);
2210 cond = isl_set_complement(cond);
2212 isl_val_free(inc);
2214 return cond;
2217 /* Construct a domain of the form
2219 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2221 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2222 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2224 isl_aff *aff;
2225 isl_space *dim;
2226 isl_set *set;
2228 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2229 dim = isl_pw_aff_get_domain_space(init);
2230 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2231 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2232 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2234 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2235 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2236 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2237 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2239 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2241 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2243 return isl_set_params(set);
2246 /* Assuming "cond" represents a bound on a loop where the loop
2247 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2248 * is possible.
2250 * Under the given assumptions, wrapping is only possible if "cond" allows
2251 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2252 * increasing iterator and 0 in case of a decreasing iterator.
2254 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2255 __isl_keep isl_val *inc)
2257 bool cw;
2258 isl_ctx *ctx;
2259 isl_val *limit;
2260 isl_set *test;
2262 test = isl_set_copy(cond);
2264 ctx = isl_set_get_ctx(test);
2265 if (isl_val_is_neg(inc))
2266 limit = isl_val_zero(ctx);
2267 else {
2268 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2269 limit = isl_val_2exp(limit);
2270 limit = isl_val_sub_ui(limit, 1);
2273 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2274 cw = !isl_set_is_empty(test);
2275 isl_set_free(test);
2277 return cw;
2280 /* Given a one-dimensional space, construct the following affine expression
2281 * on this space
2283 * { [v] -> [v mod 2^width] }
2285 * where width is the number of bits used to represent the values
2286 * of the unsigned variable "iv".
2288 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2289 ValueDecl *iv)
2291 isl_ctx *ctx;
2292 isl_val *mod;
2293 isl_aff *aff;
2295 ctx = isl_space_get_ctx(dim);
2296 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2297 mod = isl_val_2exp(mod);
2299 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2300 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2301 aff = isl_aff_mod_val(aff, mod);
2303 return aff;
2306 /* Project out the parameter "id" from "set".
2308 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2309 __isl_keep isl_id *id)
2311 int pos;
2313 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2314 if (pos >= 0)
2315 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2317 return set;
2320 /* Compute the set of parameters for which "set1" is a subset of "set2".
2322 * set1 is a subset of set2 if
2324 * forall i in set1 : i in set2
2326 * or
2328 * not exists i in set1 and i not in set2
2330 * i.e.,
2332 * not exists i in set1 \ set2
2334 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2335 __isl_take isl_set *set2)
2337 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2340 /* Compute the set of parameter values for which "cond" holds
2341 * on the next iteration for each element of "dom".
2343 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2344 * and then compute the set of parameters for which the result is a subset
2345 * of "cond".
2347 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2348 __isl_take isl_set *dom, __isl_take isl_val *inc)
2350 isl_space *space;
2351 isl_aff *aff;
2352 isl_map *next;
2354 space = isl_set_get_space(dom);
2355 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2356 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2357 aff = isl_aff_add_constant_val(aff, inc);
2358 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2360 dom = isl_set_apply(dom, next);
2362 return enforce_subset(dom, cond);
2365 /* Extract the for loop "stmt" as a while loop.
2366 * "iv" is the loop iterator. "init" is the initialization.
2367 * "inc" is the increment.
2369 * That is, the for loop has the form
2371 * for (iv = init; cond; iv += inc)
2372 * body;
2374 * and is treated as
2376 * iv = init;
2377 * while (cond) {
2378 * body;
2379 * iv += inc;
2382 * except that the skips resulting from any continue statements
2383 * in body do not apply to the increment, but are replaced by the skips
2384 * resulting from break statements.
2386 * If "iv" is declared in the for loop, then it is killed before
2387 * and after the loop.
2389 struct pet_scop *PetScan::extract_non_affine_for(ForStmt *stmt, ValueDecl *iv,
2390 __isl_take pet_expr *init, __isl_take pet_expr *inc)
2392 int declared;
2393 int test_nr, stmt_nr;
2394 pet_expr *expr_iv;
2395 struct pet_scop *scop_init, *scop_inc, *scop, *scop_body;
2396 int type_size;
2397 struct pet_array *array;
2398 struct pet_scop *scop_kill;
2400 if (!allow_nested) {
2401 unsupported(stmt);
2402 return NULL;
2405 clear_assignment(assigned_value, iv);
2407 declared = !initialization_assignment(stmt->getInit());
2409 expr_iv = extract_access_expr(iv);
2410 expr_iv = mark_write(expr_iv);
2411 type_size = pet_expr_get_type_size(expr_iv);
2412 init = pet_expr_new_binary(type_size, pet_op_assign, expr_iv, init);
2413 scop_init = extract(init, stmt->getInit()->getSourceRange(), false);
2414 scop_init = pet_scop_prefix(scop_init, declared);
2416 test_nr = n_test++;
2417 stmt_nr = n_stmt++;
2418 scop_body = extract(stmt->getBody());
2419 if (partial) {
2420 pet_scop_free(scop_init);
2421 return scop_body;
2424 expr_iv = extract_access_expr(iv);
2425 expr_iv = mark_write(expr_iv);
2426 type_size = pet_expr_get_type_size(expr_iv);
2427 inc = pet_expr_new_binary(type_size, pet_op_add_assign, expr_iv, inc);
2428 scop_inc = extract(inc, stmt->getInc()->getSourceRange(), false);
2429 if (!scop_inc) {
2430 pet_scop_free(scop_init);
2431 pet_scop_free(scop_body);
2432 return NULL;
2435 scop = extract_while(stmt->getCond(), test_nr, stmt_nr, scop_body,
2436 scop_inc);
2438 scop = pet_scop_prefix(scop, declared + 1);
2439 scop = pet_scop_add_seq(ctx, scop_init, scop);
2441 if (!declared)
2442 return scop;
2444 array = extract_array(ctx, iv, NULL);
2445 if (array)
2446 array->declared = 1;
2447 scop_kill = kill(stmt, array);
2448 scop_kill = pet_scop_prefix(scop_kill, 0);
2449 scop = pet_scop_add_seq(ctx, scop_kill, scop);
2450 scop_kill = kill(stmt, array);
2451 scop_kill = pet_scop_add_array(scop_kill, array);
2452 scop_kill = pet_scop_prefix(scop_kill, 3);
2453 scop = pet_scop_add_seq(ctx, scop, scop_kill);
2455 return scop;
2458 /* Construct a pet_scop for a for statement.
2459 * The for loop is required to be of one of the following forms
2461 * for (i = init; condition; ++i)
2462 * for (i = init; condition; --i)
2463 * for (i = init; condition; i += constant)
2464 * for (i = init; condition; i -= constant)
2466 * The initialization of the for loop should either be an assignment
2467 * of a static affine value to an integer variable, or a declaration
2468 * of such a variable with initialization.
2470 * If the initialization or the increment do not satisfy the above
2471 * conditions, i.e., if the initialization is not static affine
2472 * or the increment is not constant, then the for loop is extracted
2473 * as a while loop instead.
2475 * The condition is allowed to contain nested accesses, provided
2476 * they are not being written to inside the body of the loop.
2477 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2478 * essentially treated as a while loop, with iteration domain
2479 * { [i] : i >= init }.
2481 * We extract a pet_scop for the body and then embed it in a loop with
2482 * iteration domain and schedule
2484 * { [i] : i >= init and condition' }
2485 * { [i] -> [i] }
2487 * or
2489 * { [i] : i <= init and condition' }
2490 * { [i] -> [-i] }
2492 * Where condition' is equal to condition if the latter is
2493 * a simple upper [lower] bound and a condition that is extended
2494 * to apply to all previous iterations otherwise.
2496 * If the condition is non-affine, then we drop the condition from the
2497 * iteration domain and instead create a separate statement
2498 * for evaluating the condition. The body is then filtered to depend
2499 * on the result of the condition evaluating to true on all iterations
2500 * up to the current iteration, while the evaluation the condition itself
2501 * is filtered to depend on the result of the condition evaluating to true
2502 * on all previous iterations.
2503 * The context of the scop representing the body is dropped
2504 * because we don't know how many times the body will be executed,
2505 * if at all.
2507 * If the stride of the loop is not 1, then "i >= init" is replaced by
2509 * (exists a: i = init + stride * a and a >= 0)
2511 * If the loop iterator i is unsigned, then wrapping may occur.
2512 * We therefore use a virtual iterator instead that does not wrap.
2513 * However, the condition in the code applies
2514 * to the wrapped value, so we need to change condition(i)
2515 * into condition([i % 2^width]). Similarly, we replace all accesses
2516 * to the original iterator by the wrapping of the virtual iterator.
2517 * Note that there may be no need to perform this final wrapping
2518 * if the loop condition (after wrapping) satisfies certain conditions.
2519 * However, the is_simple_bound condition is not enough since it doesn't
2520 * check if there even is an upper bound.
2522 * Wrapping on unsigned iterators can be avoided entirely if
2523 * loop condition is simple, the loop iterator is incremented
2524 * [decremented] by one and the last value before wrapping cannot
2525 * possibly satisfy the loop condition.
2527 * Before extracting a pet_scop from the body we remove all
2528 * assignments in assigned_value to variables that are assigned
2529 * somewhere in the body of the loop.
2531 * Valid parameters for a for loop are those for which the initial
2532 * value itself, the increment on each domain iteration and
2533 * the condition on both the initial value and
2534 * the result of incrementing the iterator for each iteration of the domain
2535 * can be evaluated.
2536 * If the loop condition is non-affine, then we only consider validity
2537 * of the initial value.
2539 * If the body contains any break, then we keep track of it in "skip"
2540 * (if the skip condition is affine) or it is handled in scop_add_break
2541 * (if the skip condition is not affine).
2542 * Note that the affine break condition needs to be considered with
2543 * respect to previous iterations in the virtual domain (if any).
2545 * If we were only able to extract part of the body, then simply
2546 * return that part.
2548 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2550 BinaryOperator *ass;
2551 Decl *decl;
2552 Stmt *init;
2553 Expr *lhs, *rhs;
2554 ValueDecl *iv;
2555 isl_local_space *ls;
2556 isl_set *domain;
2557 isl_aff *sched;
2558 isl_set *cond = NULL;
2559 isl_set *skip = NULL;
2560 isl_id *id, *id_test = NULL, *id_break_test;
2561 struct pet_scop *scop, *scop_cond = NULL;
2562 assigned_value_cache cache(assigned_value);
2563 isl_val *inc;
2564 bool is_one;
2565 bool is_unsigned;
2566 bool is_simple;
2567 bool is_virtual;
2568 bool has_affine_break;
2569 bool has_var_break;
2570 isl_aff *wrap = NULL;
2571 isl_pw_aff *pa, *pa_inc, *init_val;
2572 isl_set *valid_init;
2573 isl_set *valid_cond;
2574 isl_set *valid_cond_init;
2575 isl_set *valid_cond_next;
2576 isl_set *valid_inc;
2577 int stmt_id;
2578 pet_expr *pe_init, *pe_inc;
2579 pet_context *pc, *pc_init_val;
2581 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2582 return extract_infinite_for(stmt);
2584 init = stmt->getInit();
2585 if (!init) {
2586 unsupported(stmt);
2587 return NULL;
2589 if ((ass = initialization_assignment(init)) != NULL) {
2590 iv = extract_induction_variable(ass);
2591 if (!iv)
2592 return NULL;
2593 lhs = ass->getLHS();
2594 rhs = ass->getRHS();
2595 } else if ((decl = initialization_declaration(init)) != NULL) {
2596 VarDecl *var = extract_induction_variable(init, decl);
2597 if (!var)
2598 return NULL;
2599 iv = var;
2600 rhs = var->getInit();
2601 lhs = create_DeclRefExpr(var);
2602 } else {
2603 unsupported(stmt->getInit());
2604 return NULL;
2607 id = create_decl_id(ctx, iv);
2609 assigned_value.erase(iv);
2610 clear_assignments clear(assigned_value);
2611 clear.TraverseStmt(stmt->getBody());
2613 pe_init = extract_expr(rhs);
2614 pe_inc = extract_increment(stmt, iv);
2615 pc = convert_assignments(ctx, assigned_value);
2616 pc_init_val = pet_context_copy(pc);
2617 pc_init_val = pet_context_mark_unknown(pc_init_val, isl_id_copy(id));
2618 init_val = pet_expr_extract_affine(pe_init, pc_init_val);
2619 pet_context_free(pc_init_val);
2620 pa_inc = pet_expr_extract_affine(pe_inc, pc);
2621 pet_context_free(pc);
2622 inc = pet_extract_cst(pa_inc);
2623 if (!pe_init || !pe_inc || !inc || isl_val_is_nan(inc) ||
2624 isl_pw_aff_involves_nan(pa_inc) ||
2625 isl_pw_aff_involves_nan(init_val)) {
2626 isl_id_free(id);
2627 isl_val_free(inc);
2628 isl_pw_aff_free(pa_inc);
2629 isl_pw_aff_free(init_val);
2630 if (pe_init && pe_inc && !(pa_inc && !inc))
2631 return extract_non_affine_for(stmt, iv,
2632 pe_init, pe_inc);
2633 pet_expr_free(pe_init);
2634 pet_expr_free(pe_inc);
2635 return NULL;
2637 pet_expr_free(pe_init);
2638 pet_expr_free(pe_inc);
2640 pa = try_extract_nested_condition(stmt->getCond());
2641 if (allow_nested && (!pa || pet_nested_any_in_pw_aff(pa)))
2642 stmt_id = n_stmt++;
2644 scop = extract(stmt->getBody());
2645 if (partial) {
2646 isl_id_free(id);
2647 isl_pw_aff_free(init_val);
2648 isl_pw_aff_free(pa_inc);
2649 isl_pw_aff_free(pa);
2650 isl_val_free(inc);
2651 return scop;
2654 valid_inc = isl_pw_aff_domain(pa_inc);
2656 is_unsigned = iv->getType()->isUnsignedIntegerType();
2658 has_affine_break = scop &&
2659 pet_scop_has_affine_skip(scop, pet_skip_later);
2660 if (has_affine_break)
2661 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2662 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
2663 if (has_var_break)
2664 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
2666 if (pa && !is_nested_allowed(pa, scop)) {
2667 isl_pw_aff_free(pa);
2668 pa = NULL;
2671 if (!allow_nested && !pa)
2672 pa = try_extract_affine_condition(stmt->getCond());
2673 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2674 cond = isl_pw_aff_non_zero_set(pa);
2675 if (allow_nested && !cond) {
2676 isl_multi_pw_aff *test_index;
2677 int save_n_stmt = n_stmt;
2678 test_index = pet_create_test_index(ctx, n_test++);
2679 n_stmt = stmt_id;
2680 scop_cond = extract_non_affine_condition(stmt->getCond(),
2681 n_stmt++, isl_multi_pw_aff_copy(test_index));
2682 n_stmt = save_n_stmt;
2683 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
2684 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
2685 isl_dim_out);
2686 isl_multi_pw_aff_free(test_index);
2687 scop_cond = pet_scop_prefix(scop_cond, 0);
2688 scop = pet_scop_reset_context(scop);
2689 scop = pet_scop_prefix(scop, 1);
2690 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2693 cond = embed(cond, isl_id_copy(id));
2694 skip = embed(skip, isl_id_copy(id));
2695 valid_cond = isl_set_coalesce(valid_cond);
2696 valid_cond = embed(valid_cond, isl_id_copy(id));
2697 valid_inc = embed(valid_inc, isl_id_copy(id));
2698 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
2699 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2701 valid_cond_init = enforce_subset(
2702 isl_map_range(isl_map_from_pw_aff(isl_pw_aff_copy(init_val))),
2703 isl_set_copy(valid_cond));
2704 if (is_one && !is_virtual) {
2705 isl_pw_aff_free(init_val);
2706 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
2707 lhs, rhs, init);
2708 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2709 valid_init = set_project_out_by_id(valid_init, id);
2710 domain = isl_pw_aff_non_zero_set(pa);
2711 } else {
2712 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2713 domain = strided_domain(isl_id_copy(id), init_val,
2714 isl_val_copy(inc));
2717 domain = embed(domain, isl_id_copy(id));
2718 if (is_virtual) {
2719 isl_map *rev_wrap;
2720 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2721 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
2722 rev_wrap = isl_map_reverse(rev_wrap);
2723 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2724 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
2725 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2726 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2728 is_simple = is_simple_bound(cond, inc);
2729 if (!is_simple) {
2730 cond = isl_set_gist(cond, isl_set_copy(domain));
2731 is_simple = is_simple_bound(cond, inc);
2733 if (!is_simple)
2734 cond = valid_for_each_iteration(cond,
2735 isl_set_copy(domain), isl_val_copy(inc));
2736 domain = isl_set_intersect(domain, cond);
2737 if (has_affine_break) {
2738 skip = isl_set_intersect(skip , isl_set_copy(domain));
2739 skip = after(skip, isl_val_sgn(inc));
2740 domain = isl_set_subtract(domain, skip);
2742 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2743 ls = isl_local_space_from_space(isl_set_get_space(domain));
2744 sched = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2745 if (isl_val_is_neg(inc))
2746 sched = isl_aff_neg(sched);
2748 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
2749 isl_val_copy(inc));
2750 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2752 if (!is_virtual)
2753 wrap = identity_aff(domain);
2755 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
2756 isl_aff_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
2757 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
2758 scop = resolve_nested(scop);
2759 if (has_var_break)
2760 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
2761 isl_val_copy(inc));
2762 if (id_test) {
2763 scop = scop_add_while(scop_cond, scop, id_test, domain,
2764 isl_val_copy(inc));
2765 isl_set_free(valid_inc);
2766 } else {
2767 scop = pet_scop_restrict_context(scop, valid_inc);
2768 scop = pet_scop_restrict_context(scop, valid_cond_next);
2769 scop = pet_scop_restrict_context(scop, valid_cond_init);
2770 isl_set_free(domain);
2772 clear_assignment(assigned_value, iv);
2774 isl_val_free(inc);
2776 scop = pet_scop_restrict_context(scop, isl_set_params(valid_init));
2778 return scop;
2781 /* Try and construct a pet_scop corresponding to a compound statement.
2783 * "skip_declarations" is set if we should skip initial declarations
2784 * in the children of the compound statements. This then implies
2785 * that this sequence of children should not be treated as a block
2786 * since the initial statements may be skipped.
2788 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
2790 return extract(stmt->children(), !skip_declarations, skip_declarations);
2793 /* For each nested access parameter in "space",
2794 * construct a corresponding pet_expr, place it in args and
2795 * record its position in "param2pos".
2796 * "n_arg" is the number of elements that are already in args.
2797 * The position recorded in "param2pos" takes this number into account.
2798 * If the pet_expr corresponding to a parameter is identical to
2799 * the pet_expr corresponding to an earlier parameter, then these two
2800 * parameters are made to refer to the same element in args.
2802 * Return the final number of elements in args or -1 if an error has occurred.
2804 int PetScan::extract_nested(__isl_keep isl_space *space,
2805 int n_arg, pet_expr **args, std::map<int,int> &param2pos)
2807 int nparam;
2809 nparam = isl_space_dim(space, isl_dim_param);
2810 for (int i = 0; i < nparam; ++i) {
2811 int j;
2812 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2814 if (!pet_nested_in_id(id)) {
2815 isl_id_free(id);
2816 continue;
2819 args[n_arg] = pet_nested_extract_expr(id);
2820 isl_id_free(id);
2821 if (!args[n_arg])
2822 return -1;
2824 for (j = 0; j < n_arg; ++j)
2825 if (pet_expr_is_equal(args[j], args[n_arg]))
2826 break;
2828 if (j < n_arg) {
2829 pet_expr_free(args[n_arg]);
2830 args[n_arg] = NULL;
2831 param2pos[i] = j;
2832 } else
2833 param2pos[i] = n_arg++;
2836 return n_arg;
2839 /* For each nested access parameter in the access relations in "expr",
2840 * construct a corresponding pet_expr, place it in the arguments of "expr"
2841 * and record its position in "param2pos".
2842 * n is the number of nested access parameters.
2844 __isl_give pet_expr *PetScan::extract_nested(__isl_take pet_expr *expr, int n,
2845 std::map<int,int> &param2pos)
2847 isl_space *space;
2848 int i;
2849 pet_expr **args;
2851 args = isl_calloc_array(ctx, pet_expr *, n);
2852 if (!args)
2853 return pet_expr_free(expr);
2855 space = pet_expr_access_get_parameter_space(expr);
2856 n = extract_nested(space, 0, args, param2pos);
2857 isl_space_free(space);
2859 if (n < 0)
2860 expr = pet_expr_free(expr);
2861 else
2862 expr = pet_expr_set_n_arg(expr, n);
2864 for (i = 0; i < n; ++i)
2865 expr = pet_expr_set_arg(expr, i, args[i]);
2866 free(args);
2868 return expr;
2871 /* Look for parameters in any access relation in "expr" that
2872 * refer to nested accesses. In particular, these are
2873 * parameters with name "__pet_expr".
2875 * If there are any such parameters, then the domain of the index
2876 * expression and the access relation, which is still [] at this point,
2877 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
2878 * (after identifying identical nested accesses).
2880 * This transformation is performed in several steps.
2881 * We first extract the arguments in extract_nested.
2882 * param2pos maps the original parameter position to the position
2883 * of the argument.
2884 * Then we move these parameters to input dimensions.
2885 * t2pos maps the positions of these temporary input dimensions
2886 * to the positions of the corresponding arguments.
2887 * Finally, we express these temporary dimensions in terms of the domain
2888 * [[] -> [t_1,...,t_n]] and precompose index expression and access
2889 * relations with this function.
2891 __isl_give pet_expr *PetScan::resolve_nested(__isl_take pet_expr *expr)
2893 int n;
2894 int nparam;
2895 isl_space *space;
2896 isl_local_space *ls;
2897 isl_aff *aff;
2898 isl_multi_aff *ma;
2899 std::map<int,int> param2pos;
2900 std::map<int,int> t2pos;
2902 if (!expr)
2903 return expr;
2905 n = pet_expr_get_n_arg(expr);
2906 for (int i = 0; i < n; ++i) {
2907 pet_expr *arg;
2908 arg = pet_expr_get_arg(expr, i);
2909 arg = resolve_nested(arg);
2910 expr = pet_expr_set_arg(expr, i, arg);
2913 if (pet_expr_get_type(expr) != pet_expr_access)
2914 return expr;
2916 space = pet_expr_access_get_parameter_space(expr);
2917 n = pet_nested_n_in_space(space);
2918 isl_space_free(space);
2919 if (n == 0)
2920 return expr;
2922 expr = extract_nested(expr, n, param2pos);
2923 if (!expr)
2924 return NULL;
2926 expr = pet_expr_access_align_params(expr);
2927 if (!expr)
2928 return NULL;
2930 n = 0;
2931 space = pet_expr_access_get_parameter_space(expr);
2932 nparam = isl_space_dim(space, isl_dim_param);
2933 for (int i = nparam - 1; i >= 0; --i) {
2934 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2935 if (!pet_nested_in_id(id)) {
2936 isl_id_free(id);
2937 continue;
2940 expr = pet_expr_access_move_dims(expr,
2941 isl_dim_in, n, isl_dim_param, i, 1);
2942 t2pos[n] = param2pos[i];
2943 n++;
2945 isl_id_free(id);
2947 isl_space_free(space);
2949 space = pet_expr_access_get_parameter_space(expr);
2950 space = isl_space_set_from_params(space);
2951 space = isl_space_add_dims(space, isl_dim_set,
2952 pet_expr_get_n_arg(expr));
2953 space = isl_space_wrap(isl_space_from_range(space));
2954 ls = isl_local_space_from_space(isl_space_copy(space));
2955 space = isl_space_from_domain(space);
2956 space = isl_space_add_dims(space, isl_dim_out, n);
2957 ma = isl_multi_aff_zero(space);
2959 for (int i = 0; i < n; ++i) {
2960 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2961 isl_dim_set, t2pos[i]);
2962 ma = isl_multi_aff_set_aff(ma, i, aff);
2964 isl_local_space_free(ls);
2966 expr = pet_expr_access_pullback_multi_aff(expr, ma);
2968 return expr;
2971 /* Return the file offset of the expansion location of "Loc".
2973 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
2975 return SM.getFileOffset(SM.getExpansionLoc(Loc));
2978 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
2980 /* Return a SourceLocation for the location after the first semicolon
2981 * after "loc". If Lexer::findLocationAfterToken is available, we simply
2982 * call it and also skip trailing spaces and newline.
2984 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
2985 const LangOptions &LO)
2987 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
2990 #else
2992 /* Return a SourceLocation for the location after the first semicolon
2993 * after "loc". If Lexer::findLocationAfterToken is not available,
2994 * we look in the underlying character data for the first semicolon.
2996 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
2997 const LangOptions &LO)
2999 const char *semi;
3000 const char *s = SM.getCharacterData(loc);
3002 semi = strchr(s, ';');
3003 if (!semi)
3004 return SourceLocation();
3005 return loc.getFileLocWithOffset(semi + 1 - s);
3008 #endif
3010 /* If the token at "loc" is the first token on the line, then return
3011 * a location referring to the start of the line.
3012 * Otherwise, return "loc".
3014 * This function is used to extend a scop to the start of the line
3015 * if the first token of the scop is also the first token on the line.
3017 * We look for the first token on the line. If its location is equal to "loc",
3018 * then the latter is the location of the first token on the line.
3020 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3021 SourceManager &SM, const LangOptions &LO)
3023 std::pair<FileID, unsigned> file_offset_pair;
3024 llvm::StringRef file;
3025 const char *pos;
3026 Token tok;
3027 SourceLocation token_loc, line_loc;
3028 int col;
3030 loc = SM.getExpansionLoc(loc);
3031 col = SM.getExpansionColumnNumber(loc);
3032 line_loc = loc.getLocWithOffset(1 - col);
3033 file_offset_pair = SM.getDecomposedLoc(line_loc);
3034 file = SM.getBufferData(file_offset_pair.first, NULL);
3035 pos = file.data() + file_offset_pair.second;
3037 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3038 file.begin(), pos, file.end());
3039 lexer.LexFromRawLexer(tok);
3040 token_loc = tok.getLocation();
3042 if (token_loc == loc)
3043 return line_loc;
3044 else
3045 return loc;
3048 /* Update start and end of "scop" to include the region covered by "range".
3049 * If "skip_semi" is set, then we assume "range" is followed by
3050 * a semicolon and also include this semicolon.
3052 struct pet_scop *PetScan::update_scop_start_end(struct pet_scop *scop,
3053 SourceRange range, bool skip_semi)
3055 SourceLocation loc = range.getBegin();
3056 SourceManager &SM = PP.getSourceManager();
3057 const LangOptions &LO = PP.getLangOpts();
3058 unsigned start, end;
3060 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3061 start = getExpansionOffset(SM, loc);
3062 loc = range.getEnd();
3063 if (skip_semi)
3064 loc = location_after_semi(loc, SM, LO);
3065 else
3066 loc = PP.getLocForEndOfToken(loc);
3067 end = getExpansionOffset(SM, loc);
3069 scop = pet_scop_update_start_end(scop, start, end);
3070 return scop;
3073 /* Convert a top-level pet_expr to a pet_scop with one statement.
3074 * This mainly involves resolving nested expression parameters
3075 * and setting the name of the iteration space.
3076 * The name is given by "label" if it is non-NULL. Otherwise,
3077 * it is of the form S_<n_stmt>.
3078 * start and end of the pet_scop are derived from "range" and "skip_semi".
3079 * In particular, if "skip_semi" is set then the semicolon following "range"
3080 * is also included.
3082 struct pet_scop *PetScan::extract(__isl_take pet_expr *expr, SourceRange range,
3083 bool skip_semi, __isl_take isl_id *label)
3085 struct pet_stmt *ps;
3086 struct pet_scop *scop;
3087 SourceLocation loc = range.getBegin();
3088 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3090 expr = resolve_nested(expr);
3091 ps = pet_stmt_from_pet_expr(line, label, n_stmt++, expr);
3092 scop = pet_scop_from_pet_stmt(ctx, ps);
3094 scop = update_scop_start_end(scop, range, skip_semi);
3095 return scop;
3098 /* Check if we can extract an affine constraint from "expr".
3099 * Return the constraint as an isl_set if we can and NULL otherwise.
3100 * We turn on autodetection so that we won't generate any warnings
3101 * and turn off nesting, so that we won't accept any non-affine constructs.
3103 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3105 isl_pw_aff *cond;
3106 int save_autodetect = options->autodetect;
3107 bool save_nesting = nesting_enabled;
3109 options->autodetect = 1;
3110 nesting_enabled = false;
3112 cond = extract_condition(expr);
3114 options->autodetect = save_autodetect;
3115 nesting_enabled = save_nesting;
3117 return cond;
3120 /* Check whether "expr" is an affine constraint.
3122 bool PetScan::is_affine_condition(Expr *expr)
3124 isl_pw_aff *cond;
3126 cond = try_extract_affine_condition(expr);
3127 isl_pw_aff_free(cond);
3129 return cond != NULL;
3132 /* Check if we can extract a condition from "expr".
3133 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3134 * If allow_nested is set, then the condition may involve parameters
3135 * corresponding to nested accesses.
3136 * We turn on autodetection so that we won't generate any warnings.
3138 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3140 isl_pw_aff *cond;
3141 int save_autodetect = options->autodetect;
3142 bool save_nesting = nesting_enabled;
3144 options->autodetect = 1;
3145 nesting_enabled = allow_nested;
3146 cond = extract_condition(expr);
3148 options->autodetect = save_autodetect;
3149 nesting_enabled = save_nesting;
3151 return cond;
3154 /* If the top-level expression of "stmt" is an assignment, then
3155 * return that assignment as a BinaryOperator.
3156 * Otherwise return NULL.
3158 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3160 BinaryOperator *ass;
3162 if (!stmt)
3163 return NULL;
3164 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3165 return NULL;
3167 ass = cast<BinaryOperator>(stmt);
3168 if(ass->getOpcode() != BO_Assign)
3169 return NULL;
3171 return ass;
3174 /* Check if the given if statement is a conditional assignement
3175 * with a non-affine condition. If so, construct a pet_scop
3176 * corresponding to this conditional assignment. Otherwise return NULL.
3178 * In particular we check if "stmt" is of the form
3180 * if (condition)
3181 * a = f(...);
3182 * else
3183 * a = g(...);
3185 * where a is some array or scalar access.
3186 * The constructed pet_scop then corresponds to the expression
3188 * a = condition ? f(...) : g(...)
3190 * All access relations in f(...) are intersected with condition
3191 * while all access relation in g(...) are intersected with the complement.
3193 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3195 BinaryOperator *ass_then, *ass_else;
3196 isl_multi_pw_aff *write_then, *write_else;
3197 isl_set *cond, *comp;
3198 isl_multi_pw_aff *index;
3199 isl_pw_aff *pa;
3200 int equal;
3201 int type_size;
3202 pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3203 bool save_nesting = nesting_enabled;
3205 if (!options->detect_conditional_assignment)
3206 return NULL;
3208 ass_then = top_assignment_or_null(stmt->getThen());
3209 ass_else = top_assignment_or_null(stmt->getElse());
3211 if (!ass_then || !ass_else)
3212 return NULL;
3214 if (is_affine_condition(stmt->getCond()))
3215 return NULL;
3217 write_then = extract_index(ass_then->getLHS());
3218 write_else = extract_index(ass_else->getLHS());
3220 equal = isl_multi_pw_aff_plain_is_equal(write_then, write_else);
3221 isl_multi_pw_aff_free(write_else);
3222 if (equal < 0 || !equal) {
3223 isl_multi_pw_aff_free(write_then);
3224 return NULL;
3227 nesting_enabled = allow_nested;
3228 pa = extract_condition(stmt->getCond());
3229 nesting_enabled = save_nesting;
3230 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3231 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3232 index = isl_multi_pw_aff_from_pw_aff(pa);
3234 pe_cond = pet_expr_from_index(index);
3236 pe_then = extract_expr(ass_then->getRHS());
3237 pe_then = pet_expr_restrict(pe_then, cond);
3238 pe_else = extract_expr(ass_else->getRHS());
3239 pe_else = pet_expr_restrict(pe_else, comp);
3241 pe = pet_expr_new_ternary(pe_cond, pe_then, pe_else);
3242 type_size = get_type_size(ass_then->getType(), ast_context);
3243 pe_write = pet_expr_from_index_and_depth(type_size, write_then,
3244 extract_depth(write_then));
3245 pe_write = pet_expr_access_set_write(pe_write, 1);
3246 pe_write = pet_expr_access_set_read(pe_write, 0);
3247 pe = pet_expr_new_binary(type_size, pet_op_assign, pe_write, pe);
3248 return extract(pe, stmt->getSourceRange(), false);
3251 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3252 * evaluating "cond" and writing the result to a virtual scalar,
3253 * as expressed by "index".
3255 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond, int stmt_nr,
3256 __isl_take isl_multi_pw_aff *index)
3258 pet_expr *expr, *write;
3259 struct pet_stmt *ps;
3260 SourceLocation loc = cond->getLocStart();
3261 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3263 write = pet_expr_from_index(index);
3264 write = pet_expr_access_set_write(write, 1);
3265 write = pet_expr_access_set_read(write, 0);
3266 expr = extract_expr(cond);
3267 expr = resolve_nested(expr);
3268 expr = pet_expr_new_binary(1, pet_op_assign, write, expr);
3269 ps = pet_stmt_from_pet_expr(line, NULL, stmt_nr, expr);
3270 return pet_scop_from_pet_stmt(ctx, ps);
3273 extern "C" {
3274 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr,
3275 void *user);
3278 /* Precompose the access relation and the index expression associated
3279 * to "expr" with the function pointed to by "user",
3280 * thereby embedding the access relation in the domain of this function.
3281 * The initial domain of the access relation and the index expression
3282 * is the zero-dimensional domain.
3284 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr, void *user)
3286 isl_multi_aff *ma = (isl_multi_aff *) user;
3288 return pet_expr_access_pullback_multi_aff(expr, isl_multi_aff_copy(ma));
3291 /* Precompose all access relations in "expr" with "ma", thereby
3292 * embedding them in the domain of "ma".
3294 static __isl_give pet_expr *embed(__isl_take pet_expr *expr,
3295 __isl_keep isl_multi_aff *ma)
3297 return pet_expr_map_access(expr, &embed_access, ma);
3300 /* For each nested access parameter in the domain of "stmt",
3301 * construct a corresponding pet_expr, place it before the original
3302 * elements in stmt->args and record its position in "param2pos".
3303 * n is the number of nested access parameters.
3305 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3306 std::map<int,int> &param2pos)
3308 int i;
3309 isl_space *space;
3310 int n_arg;
3311 pet_expr **args;
3313 n_arg = stmt->n_arg;
3314 args = isl_calloc_array(ctx, pet_expr *, n + n_arg);
3315 if (!args)
3316 goto error;
3318 space = isl_set_get_space(stmt->domain);
3319 n_arg = extract_nested(space, 0, args, param2pos);
3320 isl_space_free(space);
3322 if (n_arg < 0)
3323 goto error;
3325 for (i = 0; i < stmt->n_arg; ++i)
3326 args[n_arg + i] = stmt->args[i];
3327 free(stmt->args);
3328 stmt->args = args;
3329 stmt->n_arg += n_arg;
3331 return stmt;
3332 error:
3333 if (args) {
3334 for (i = 0; i < n; ++i)
3335 pet_expr_free(args[i]);
3336 free(args);
3338 pet_stmt_free(stmt);
3339 return NULL;
3342 /* Check whether any of the arguments i of "stmt" starting at position "n"
3343 * is equal to one of the first "n" arguments j.
3344 * If so, combine the constraints on arguments i and j and remove
3345 * argument i.
3347 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3349 int i, j;
3350 isl_map *map;
3352 if (!stmt)
3353 return NULL;
3354 if (n == 0)
3355 return stmt;
3356 if (n == stmt->n_arg)
3357 return stmt;
3359 map = isl_set_unwrap(stmt->domain);
3361 for (i = stmt->n_arg - 1; i >= n; --i) {
3362 for (j = 0; j < n; ++j)
3363 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3364 break;
3365 if (j >= n)
3366 continue;
3368 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3369 map = isl_map_project_out(map, isl_dim_out, i, 1);
3371 pet_expr_free(stmt->args[i]);
3372 for (j = i; j + 1 < stmt->n_arg; ++j)
3373 stmt->args[j] = stmt->args[j + 1];
3374 stmt->n_arg--;
3377 stmt->domain = isl_map_wrap(map);
3378 if (!stmt->domain)
3379 goto error;
3380 return stmt;
3381 error:
3382 pet_stmt_free(stmt);
3383 return NULL;
3386 /* Look for parameters in the iteration domain of "stmt" that
3387 * refer to nested accesses. In particular, these are
3388 * parameters with name "__pet_expr".
3390 * If there are any such parameters, then as many extra variables
3391 * (after identifying identical nested accesses) are inserted in the
3392 * range of the map wrapped inside the domain, before the original variables.
3393 * If the original domain is not a wrapped map, then a new wrapped
3394 * map is created with zero output dimensions.
3395 * The parameters are then equated to the corresponding output dimensions
3396 * and subsequently projected out, from the iteration domain,
3397 * the schedule and the access relations.
3398 * For each of the output dimensions, a corresponding argument
3399 * expression is inserted. Initially they are created with
3400 * a zero-dimensional domain, so they have to be embedded
3401 * in the current iteration domain.
3402 * param2pos maps the position of the parameter to the position
3403 * of the corresponding output dimension in the wrapped map.
3405 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3407 int n;
3408 int nparam;
3409 unsigned n_arg;
3410 isl_map *map;
3411 isl_space *space;
3412 isl_multi_aff *ma;
3413 std::map<int,int> param2pos;
3415 if (!stmt)
3416 return NULL;
3418 n = pet_nested_n_in_set(stmt->domain);
3419 if (n == 0)
3420 return stmt;
3422 n_arg = stmt->n_arg;
3423 stmt = extract_nested(stmt, n, param2pos);
3424 if (!stmt)
3425 return NULL;
3427 n = stmt->n_arg - n_arg;
3428 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3429 if (isl_set_is_wrapping(stmt->domain))
3430 map = isl_set_unwrap(stmt->domain);
3431 else
3432 map = isl_map_from_domain(stmt->domain);
3433 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3435 for (int i = nparam - 1; i >= 0; --i) {
3436 isl_id *id;
3438 if (!pet_nested_in_map(map, i))
3439 continue;
3441 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
3442 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3443 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3444 param2pos[i]);
3445 map = isl_map_project_out(map, isl_dim_param, i, 1);
3448 stmt->domain = isl_map_wrap(map);
3450 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
3451 space = isl_space_from_domain(isl_space_domain(space));
3452 ma = isl_multi_aff_zero(space);
3453 for (int pos = 0; pos < n; ++pos)
3454 stmt->args[pos] = embed(stmt->args[pos], ma);
3455 isl_multi_aff_free(ma);
3457 stmt = pet_stmt_remove_nested_parameters(stmt);
3458 stmt = remove_duplicate_arguments(stmt, n);
3460 return stmt;
3463 /* For each statement in "scop", move the parameters that correspond
3464 * to nested access into the ranges of the domains and create
3465 * corresponding argument expressions.
3467 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3469 if (!scop)
3470 return NULL;
3472 for (int i = 0; i < scop->n_stmt; ++i) {
3473 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3474 if (!scop->stmts[i])
3475 goto error;
3478 return scop;
3479 error:
3480 pet_scop_free(scop);
3481 return NULL;
3484 /* Given an access expression "expr", is the variable accessed by
3485 * "expr" assigned anywhere inside "scop"?
3487 static bool is_assigned(__isl_keep pet_expr *expr, pet_scop *scop)
3489 bool assigned = false;
3490 isl_id *id;
3492 id = pet_expr_access_get_id(expr);
3493 assigned = pet_scop_writes(scop, id);
3494 isl_id_free(id);
3496 return assigned;
3499 /* Are all nested access parameters in "pa" allowed given "scop".
3500 * In particular, is none of them written by anywhere inside "scop".
3502 * If "scop" has any skip conditions, then no nested access parameters
3503 * are allowed. In particular, if there is any nested access in a guard
3504 * for a piece of code containing a "continue", then we want to introduce
3505 * a separate statement for evaluating this guard so that we can express
3506 * that the result is false for all previous iterations.
3508 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3510 int nparam;
3512 if (!scop)
3513 return true;
3515 if (!pet_nested_any_in_pw_aff(pa))
3516 return true;
3518 if (pet_scop_has_skip(scop, pet_skip_now))
3519 return false;
3521 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3522 for (int i = 0; i < nparam; ++i) {
3523 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3524 pet_expr *expr;
3525 bool allowed;
3527 if (!pet_nested_in_id(id)) {
3528 isl_id_free(id);
3529 continue;
3532 expr = pet_nested_extract_expr(id);
3533 allowed = pet_expr_get_type(expr) == pet_expr_access &&
3534 !is_assigned(expr, scop);
3536 pet_expr_free(expr);
3537 isl_id_free(id);
3539 if (!allowed)
3540 return false;
3543 return true;
3546 /* Construct a pet_scop for a non-affine if statement.
3548 * We create a separate statement that writes the result
3549 * of the non-affine condition to a virtual scalar.
3550 * A constraint requiring the value of this virtual scalar to be one
3551 * is added to the iteration domains of the then branch.
3552 * Similarly, a constraint requiring the value of this virtual scalar
3553 * to be zero is added to the iteration domains of the else branch, if any.
3554 * We adjust the schedules to ensure that the virtual scalar is written
3555 * before it is read.
3557 * If there are any breaks or continues in the then and/or else
3558 * branches, then we may have to compute a new skip condition.
3559 * This is handled using a pet_skip_info object.
3560 * On initialization, the object checks if skip conditions need
3561 * to be computed. If so, it does so in pet_skip_info_if_extract_index and
3562 * adds them in pet_skip_info_if_add.
3564 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
3565 struct pet_scop *scop_then, struct pet_scop *scop_else,
3566 bool have_else, int stmt_id)
3568 struct pet_scop *scop;
3569 isl_multi_pw_aff *test_index;
3570 int int_size;
3571 int save_n_stmt = n_stmt;
3573 test_index = pet_create_test_index(ctx, n_test++);
3574 n_stmt = stmt_id;
3575 scop = extract_non_affine_condition(cond, n_stmt++,
3576 isl_multi_pw_aff_copy(test_index));
3577 n_stmt = save_n_stmt;
3578 scop = scop_add_array(scop, test_index, ast_context);
3580 pet_skip_info skip;
3581 pet_skip_info_if_init(&skip, ctx, scop_then, scop_else, have_else, 0);
3582 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
3583 pet_skip_info_if_extract_index(&skip, test_index, int_size,
3584 &n_stmt, &n_test);
3586 scop = pet_scop_prefix(scop, 0);
3587 scop_then = pet_scop_prefix(scop_then, 1);
3588 scop_then = pet_scop_filter(scop_then,
3589 isl_multi_pw_aff_copy(test_index), 1);
3590 if (have_else) {
3591 scop_else = pet_scop_prefix(scop_else, 1);
3592 scop_else = pet_scop_filter(scop_else, test_index, 0);
3593 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
3594 } else
3595 isl_multi_pw_aff_free(test_index);
3597 scop = pet_scop_add_seq(ctx, scop, scop_then);
3599 scop = pet_skip_info_if_add(&skip, scop, 2);
3601 return scop;
3604 /* Construct a pet_scop for an if statement.
3606 * If the condition fits the pattern of a conditional assignment,
3607 * then it is handled by extract_conditional_assignment.
3608 * Otherwise, we do the following.
3610 * If the condition is affine, then the condition is added
3611 * to the iteration domains of the then branch, while the
3612 * opposite of the condition in added to the iteration domains
3613 * of the else branch, if any.
3614 * We allow the condition to be dynamic, i.e., to refer to
3615 * scalars or array elements that may be written to outside
3616 * of the given if statement. These nested accesses are then represented
3617 * as output dimensions in the wrapping iteration domain.
3618 * If it is also written _inside_ the then or else branch, then
3619 * we treat the condition as non-affine.
3620 * As explained in extract_non_affine_if, this will introduce
3621 * an extra statement.
3622 * For aesthetic reasons, we want this statement to have a statement
3623 * number that is lower than those of the then and else branches.
3624 * In order to evaluate if we will need such a statement, however, we
3625 * first construct scops for the then and else branches.
3626 * We therefore reserve a statement number if we might have to
3627 * introduce such an extra statement.
3629 * If the condition is not affine, then the scop is created in
3630 * extract_non_affine_if.
3632 * If there are any breaks or continues in the then and/or else
3633 * branches, then we may have to compute a new skip condition.
3634 * This is handled using a pet_skip_info object.
3635 * On initialization, the object checks if skip conditions need
3636 * to be computed. If so, it does so in pet_skip_info_if_extract_cond and
3637 * adds them in pet_skip_info_if_add.
3639 struct pet_scop *PetScan::extract(IfStmt *stmt)
3641 struct pet_scop *scop_then, *scop_else = NULL, *scop;
3642 isl_pw_aff *cond;
3643 int stmt_id;
3644 int int_size;
3645 isl_set *set;
3646 isl_set *valid;
3648 clear_assignments clear(assigned_value);
3649 clear.TraverseStmt(stmt->getThen());
3650 if (stmt->getElse())
3651 clear.TraverseStmt(stmt->getElse());
3653 scop = extract_conditional_assignment(stmt);
3654 if (scop)
3655 return scop;
3657 cond = try_extract_nested_condition(stmt->getCond());
3658 if (allow_nested && (!cond || pet_nested_any_in_pw_aff(cond)))
3659 stmt_id = n_stmt++;
3662 assigned_value_cache cache(assigned_value);
3663 scop_then = extract(stmt->getThen());
3666 if (stmt->getElse()) {
3667 assigned_value_cache cache(assigned_value);
3668 scop_else = extract(stmt->getElse());
3669 if (options->autodetect) {
3670 if (scop_then && !scop_else) {
3671 partial = true;
3672 isl_pw_aff_free(cond);
3673 return scop_then;
3675 if (!scop_then && scop_else) {
3676 partial = true;
3677 isl_pw_aff_free(cond);
3678 return scop_else;
3683 if (cond &&
3684 (!is_nested_allowed(cond, scop_then) ||
3685 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
3686 isl_pw_aff_free(cond);
3687 cond = NULL;
3689 if (allow_nested && !cond)
3690 return extract_non_affine_if(stmt->getCond(), scop_then,
3691 scop_else, stmt->getElse(), stmt_id);
3693 if (!cond)
3694 cond = extract_condition(stmt->getCond());
3696 pet_skip_info skip;
3697 pet_skip_info_if_init(&skip, ctx, scop_then, scop_else,
3698 stmt->getElse() != NULL, 1);
3699 pet_skip_info_if_extract_cond(&skip, cond, int_size, &n_stmt, &n_test);
3701 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
3702 set = isl_pw_aff_non_zero_set(cond);
3703 scop = pet_scop_restrict(scop_then, isl_set_params(isl_set_copy(set)));
3705 if (stmt->getElse()) {
3706 set = isl_set_subtract(isl_set_copy(valid), set);
3707 scop_else = pet_scop_restrict(scop_else, isl_set_params(set));
3708 scop = pet_scop_add_par(ctx, scop, scop_else);
3709 } else
3710 isl_set_free(set);
3711 scop = resolve_nested(scop);
3712 scop = pet_scop_restrict_context(scop, isl_set_params(valid));
3714 if (pet_skip_info_has_skip(&skip))
3715 scop = pet_scop_prefix(scop, 0);
3716 scop = pet_skip_info_if_add(&skip, scop, 1);
3718 return scop;
3721 /* Try and construct a pet_scop for a label statement.
3722 * We currently only allow labels on expression statements.
3724 struct pet_scop *PetScan::extract(LabelStmt *stmt)
3726 isl_id *label;
3727 Stmt *sub;
3729 sub = stmt->getSubStmt();
3730 if (!isa<Expr>(sub)) {
3731 unsupported(stmt);
3732 return NULL;
3735 label = isl_id_alloc(ctx, stmt->getName(), NULL);
3737 return extract(extract_expr(cast<Expr>(sub)), stmt->getSourceRange(),
3738 true, label);
3741 /* Return a one-dimensional multi piecewise affine expression that is equal
3742 * to the constant 1 and is defined over a zero-dimensional domain.
3744 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
3746 isl_space *space;
3747 isl_local_space *ls;
3748 isl_aff *aff;
3750 space = isl_space_set_alloc(ctx, 0, 0);
3751 ls = isl_local_space_from_space(space);
3752 aff = isl_aff_zero_on_domain(ls);
3753 aff = isl_aff_set_constant_si(aff, 1);
3755 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
3758 /* Construct a pet_scop for a continue statement.
3760 * We simply create an empty scop with a universal pet_skip_now
3761 * skip condition. This skip condition will then be taken into
3762 * account by the enclosing loop construct, possibly after
3763 * being incorporated into outer skip conditions.
3765 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
3767 pet_scop *scop;
3769 scop = pet_scop_empty(ctx);
3770 if (!scop)
3771 return NULL;
3773 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
3775 return scop;
3778 /* Construct a pet_scop for a break statement.
3780 * We simply create an empty scop with both a universal pet_skip_now
3781 * skip condition and a universal pet_skip_later skip condition.
3782 * These skip conditions will then be taken into
3783 * account by the enclosing loop construct, possibly after
3784 * being incorporated into outer skip conditions.
3786 struct pet_scop *PetScan::extract(BreakStmt *stmt)
3788 pet_scop *scop;
3789 isl_multi_pw_aff *skip;
3791 scop = pet_scop_empty(ctx);
3792 if (!scop)
3793 return NULL;
3795 skip = one_mpa(ctx);
3796 scop = pet_scop_set_skip(scop, pet_skip_now,
3797 isl_multi_pw_aff_copy(skip));
3798 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
3800 return scop;
3803 /* Try and construct a pet_scop corresponding to "stmt".
3805 * If "stmt" is a compound statement, then "skip_declarations"
3806 * indicates whether we should skip initial declarations in the
3807 * compound statement.
3809 * If the constructed pet_scop is not a (possibly) partial representation
3810 * of "stmt", we update start and end of the pet_scop to those of "stmt".
3811 * In particular, if skip_declarations is set, then we may have skipped
3812 * declarations inside "stmt" and so the pet_scop may not represent
3813 * the entire "stmt".
3814 * Note that this function may be called with "stmt" referring to the entire
3815 * body of the function, including the outer braces. In such cases,
3816 * skip_declarations will be set and the braces will not be taken into
3817 * account in scop->start and scop->end.
3819 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
3821 struct pet_scop *scop;
3823 if (isa<Expr>(stmt))
3824 return extract(extract_expr(cast<Expr>(stmt)),
3825 stmt->getSourceRange(), true);
3827 switch (stmt->getStmtClass()) {
3828 case Stmt::WhileStmtClass:
3829 scop = extract(cast<WhileStmt>(stmt));
3830 break;
3831 case Stmt::ForStmtClass:
3832 scop = extract_for(cast<ForStmt>(stmt));
3833 break;
3834 case Stmt::IfStmtClass:
3835 scop = extract(cast<IfStmt>(stmt));
3836 break;
3837 case Stmt::CompoundStmtClass:
3838 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
3839 break;
3840 case Stmt::LabelStmtClass:
3841 scop = extract(cast<LabelStmt>(stmt));
3842 break;
3843 case Stmt::ContinueStmtClass:
3844 scop = extract(cast<ContinueStmt>(stmt));
3845 break;
3846 case Stmt::BreakStmtClass:
3847 scop = extract(cast<BreakStmt>(stmt));
3848 break;
3849 case Stmt::DeclStmtClass:
3850 scop = extract(cast<DeclStmt>(stmt));
3851 break;
3852 default:
3853 unsupported(stmt);
3854 return NULL;
3857 if (partial || skip_declarations)
3858 return scop;
3860 scop = update_scop_start_end(scop, stmt->getSourceRange(), false);
3862 return scop;
3865 /* Extract a clone of the kill statement in "scop".
3866 * "scop" is expected to have been created from a DeclStmt
3867 * and should have the kill as its first statement.
3869 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
3871 pet_expr *kill;
3872 struct pet_stmt *stmt;
3873 isl_multi_pw_aff *index;
3874 isl_map *access;
3875 pet_expr *arg;
3877 if (!scop)
3878 return NULL;
3879 if (scop->n_stmt < 1)
3880 isl_die(ctx, isl_error_internal,
3881 "expecting at least one statement", return NULL);
3882 stmt = scop->stmts[0];
3883 if (!pet_stmt_is_kill(stmt))
3884 isl_die(ctx, isl_error_internal,
3885 "expecting kill statement", return NULL);
3887 arg = pet_expr_get_arg(stmt->body, 0);
3888 index = pet_expr_access_get_index(arg);
3889 access = pet_expr_access_get_access(arg);
3890 pet_expr_free(arg);
3891 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
3892 access = isl_map_reset_tuple_id(access, isl_dim_in);
3893 kill = pet_expr_kill_from_access_and_index(access, index);
3894 return pet_stmt_from_pet_expr(stmt->line, NULL, n_stmt++, kill);
3897 /* Mark all arrays in "scop" as being exposed.
3899 static struct pet_scop *mark_exposed(struct pet_scop *scop)
3901 if (!scop)
3902 return NULL;
3903 for (int i = 0; i < scop->n_array; ++i)
3904 scop->arrays[i]->exposed = 1;
3905 return scop;
3908 /* Try and construct a pet_scop corresponding to (part of)
3909 * a sequence of statements.
3911 * "block" is set if the sequence respresents the children of
3912 * a compound statement.
3913 * "skip_declarations" is set if we should skip initial declarations
3914 * in the sequence of statements.
3916 * If there are any breaks or continues in the individual statements,
3917 * then we may have to compute a new skip condition.
3918 * This is handled using a pet_skip_info object.
3919 * On initialization, the object checks if skip conditions need
3920 * to be computed. If so, it does so in pet_skip_info_seq_extract and
3921 * adds them in pet_skip_info_seq_add.
3923 * If "block" is set, then we need to insert kill statements at
3924 * the end of the block for any array that has been declared by
3925 * one of the statements in the sequence. Each of these declarations
3926 * results in the construction of a kill statement at the place
3927 * of the declaration, so we simply collect duplicates of
3928 * those kill statements and append these duplicates to the constructed scop.
3930 * If "block" is not set, then any array declared by one of the statements
3931 * in the sequence is marked as being exposed.
3933 * If autodetect is set, then we allow the extraction of only a subrange
3934 * of the sequence of statements. However, if there is at least one statement
3935 * for which we could not construct a scop and the final range contains
3936 * either no statements or at least one kill, then we discard the entire
3937 * range.
3939 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
3940 bool skip_declarations)
3942 pet_scop *scop;
3943 StmtIterator i;
3944 int int_size;
3945 int j;
3946 bool partial_range = false;
3947 set<struct pet_stmt *> kills;
3948 set<struct pet_stmt *>::iterator it;
3950 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
3952 scop = pet_scop_empty(ctx);
3953 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
3954 Stmt *child = *i;
3955 struct pet_scop *scop_i;
3957 if (scop->n_stmt == 0 && skip_declarations &&
3958 child->getStmtClass() == Stmt::DeclStmtClass)
3959 continue;
3961 scop_i = extract(child);
3962 if (scop->n_stmt != 0 && partial) {
3963 pet_scop_free(scop_i);
3964 break;
3966 pet_skip_info skip;
3967 pet_skip_info_seq_init(&skip, ctx, scop, scop_i);
3968 pet_skip_info_seq_extract(&skip, int_size, &n_stmt, &n_test);
3969 if (pet_skip_info_has_skip(&skip))
3970 scop_i = pet_scop_prefix(scop_i, 0);
3971 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
3972 if (block)
3973 kills.insert(extract_kill(scop_i));
3974 else
3975 scop_i = mark_exposed(scop_i);
3977 scop_i = pet_scop_prefix(scop_i, j);
3978 if (options->autodetect) {
3979 if (scop_i)
3980 scop = pet_scop_add_seq(ctx, scop, scop_i);
3981 else
3982 partial_range = true;
3983 if (scop->n_stmt != 0 && !scop_i)
3984 partial = true;
3985 } else {
3986 scop = pet_scop_add_seq(ctx, scop, scop_i);
3989 scop = pet_skip_info_seq_add(&skip, scop, j);
3991 if (partial || !scop)
3992 break;
3995 for (it = kills.begin(); it != kills.end(); ++it) {
3996 pet_scop *scop_j;
3997 scop_j = pet_scop_from_pet_stmt(ctx, *it);
3998 scop_j = pet_scop_prefix(scop_j, j);
3999 scop = pet_scop_add_seq(ctx, scop, scop_j);
4002 if (scop && partial_range) {
4003 if (scop->n_stmt == 0 || kills.size() != 0) {
4004 pet_scop_free(scop);
4005 return NULL;
4007 partial = true;
4010 return scop;
4013 /* Check if the scop marked by the user is exactly this Stmt
4014 * or part of this Stmt.
4015 * If so, return a pet_scop corresponding to the marked region.
4016 * Otherwise, return NULL.
4018 struct pet_scop *PetScan::scan(Stmt *stmt)
4020 SourceManager &SM = PP.getSourceManager();
4021 unsigned start_off, end_off;
4023 start_off = getExpansionOffset(SM, stmt->getLocStart());
4024 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4026 if (start_off > loc.end)
4027 return NULL;
4028 if (end_off < loc.start)
4029 return NULL;
4030 if (start_off >= loc.start && end_off <= loc.end) {
4031 return extract(stmt);
4034 StmtIterator start;
4035 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4036 Stmt *child = *start;
4037 if (!child)
4038 continue;
4039 start_off = getExpansionOffset(SM, child->getLocStart());
4040 end_off = getExpansionOffset(SM, child->getLocEnd());
4041 if (start_off < loc.start && end_off >= loc.end)
4042 return scan(child);
4043 if (start_off >= loc.start)
4044 break;
4047 StmtIterator end;
4048 for (end = start; end != stmt->child_end(); ++end) {
4049 Stmt *child = *end;
4050 start_off = SM.getFileOffset(child->getLocStart());
4051 if (start_off >= loc.end)
4052 break;
4055 return extract(StmtRange(start, end), false, false);
4058 /* Set the size of index "pos" of "array" to "size".
4059 * In particular, add a constraint of the form
4061 * i_pos < size
4063 * to array->extent and a constraint of the form
4065 * size >= 0
4067 * to array->context.
4069 static struct pet_array *update_size(struct pet_array *array, int pos,
4070 __isl_take isl_pw_aff *size)
4072 isl_set *valid;
4073 isl_set *univ;
4074 isl_set *bound;
4075 isl_space *dim;
4076 isl_aff *aff;
4077 isl_pw_aff *index;
4078 isl_id *id;
4080 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
4081 array->context = isl_set_intersect(array->context, valid);
4083 dim = isl_set_get_space(array->extent);
4084 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
4085 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
4086 univ = isl_set_universe(isl_aff_get_domain_space(aff));
4087 index = isl_pw_aff_alloc(univ, aff);
4089 size = isl_pw_aff_add_dims(size, isl_dim_in,
4090 isl_set_dim(array->extent, isl_dim_set));
4091 id = isl_set_get_tuple_id(array->extent);
4092 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
4093 bound = isl_pw_aff_lt_set(index, size);
4095 array->extent = isl_set_intersect(array->extent, bound);
4097 if (!array->context || !array->extent)
4098 goto error;
4100 return array;
4101 error:
4102 pet_array_free(array);
4103 return NULL;
4106 /* Figure out the size of the array at position "pos" and all
4107 * subsequent positions from "type" and update "array" accordingly.
4109 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
4110 const Type *type, int pos)
4112 const ArrayType *atype;
4113 isl_pw_aff *size;
4115 if (!array)
4116 return NULL;
4118 if (type->isPointerType()) {
4119 type = type->getPointeeType().getTypePtr();
4120 return set_upper_bounds(array, type, pos + 1);
4122 if (!type->isArrayType())
4123 return array;
4125 type = type->getCanonicalTypeInternal().getTypePtr();
4126 atype = cast<ArrayType>(type);
4128 if (type->isConstantArrayType()) {
4129 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
4130 size = extract_affine(ca->getSize());
4131 array = update_size(array, pos, size);
4132 } else if (type->isVariableArrayType()) {
4133 const VariableArrayType *vla = cast<VariableArrayType>(atype);
4134 size = extract_affine(vla->getSizeExpr());
4135 array = update_size(array, pos, size);
4138 type = atype->getElementType().getTypePtr();
4140 return set_upper_bounds(array, type, pos + 1);
4143 /* Is "T" the type of a variable length array with static size?
4145 static bool is_vla_with_static_size(QualType T)
4147 const VariableArrayType *vlatype;
4149 if (!T->isVariableArrayType())
4150 return false;
4151 vlatype = cast<VariableArrayType>(T);
4152 return vlatype->getSizeModifier() == VariableArrayType::Static;
4155 /* Return the type of "decl" as an array.
4157 * In particular, if "decl" is a parameter declaration that
4158 * is a variable length array with a static size, then
4159 * return the original type (i.e., the variable length array).
4160 * Otherwise, return the type of decl.
4162 static QualType get_array_type(ValueDecl *decl)
4164 ParmVarDecl *parm;
4165 QualType T;
4167 parm = dyn_cast<ParmVarDecl>(decl);
4168 if (!parm)
4169 return decl->getType();
4171 T = parm->getOriginalType();
4172 if (!is_vla_with_static_size(T))
4173 return decl->getType();
4174 return T;
4177 /* Does "decl" have definition that we can keep track of in a pet_type?
4179 static bool has_printable_definition(RecordDecl *decl)
4181 if (!decl->getDeclName())
4182 return false;
4183 return decl->getLexicalDeclContext() == decl->getDeclContext();
4186 /* Construct and return a pet_array corresponding to the variable "decl".
4187 * In particular, initialize array->extent to
4189 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4191 * and then call set_upper_bounds to set the upper bounds on the indices
4192 * based on the type of the variable.
4194 * If the base type is that of a record with a top-level definition and
4195 * if "types" is not null, then the RecordDecl corresponding to the type
4196 * is added to "types".
4198 * If the base type is that of a record with no top-level definition,
4199 * then we replace it by "<subfield>".
4201 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
4202 lex_recorddecl_set *types)
4204 struct pet_array *array;
4205 QualType qt = get_array_type(decl);
4206 const Type *type = qt.getTypePtr();
4207 int depth = array_depth(type);
4208 QualType base = pet_clang_base_type(qt);
4209 string name;
4210 isl_id *id;
4211 isl_space *dim;
4213 array = isl_calloc_type(ctx, struct pet_array);
4214 if (!array)
4215 return NULL;
4217 id = create_decl_id(ctx, decl);
4218 dim = isl_space_set_alloc(ctx, 0, depth);
4219 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
4221 array->extent = isl_set_nat_universe(dim);
4223 dim = isl_space_params_alloc(ctx, 0);
4224 array->context = isl_set_universe(dim);
4226 array = set_upper_bounds(array, type, 0);
4227 if (!array)
4228 return NULL;
4230 name = base.getAsString();
4232 if (types && base->isRecordType()) {
4233 RecordDecl *decl = pet_clang_record_decl(base);
4234 if (has_printable_definition(decl))
4235 types->insert(decl);
4236 else
4237 name = "<subfield>";
4240 array->element_type = strdup(name.c_str());
4241 array->element_is_record = base->isRecordType();
4242 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
4244 return array;
4247 /* Construct and return a pet_array corresponding to the sequence
4248 * of declarations "decls".
4249 * If the sequence contains a single declaration, then it corresponds
4250 * to a simple array access. Otherwise, it corresponds to a member access,
4251 * with the declaration for the substructure following that of the containing
4252 * structure in the sequence of declarations.
4253 * We start with the outermost substructure and then combine it with
4254 * information from the inner structures.
4256 * Additionally, keep track of all required types in "types".
4258 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
4259 vector<ValueDecl *> decls, lex_recorddecl_set *types)
4261 struct pet_array *array;
4262 vector<ValueDecl *>::iterator it;
4264 it = decls.begin();
4266 array = extract_array(ctx, *it, types);
4268 for (++it; it != decls.end(); ++it) {
4269 struct pet_array *parent;
4270 const char *base_name, *field_name;
4271 char *product_name;
4273 parent = array;
4274 array = extract_array(ctx, *it, types);
4275 if (!array)
4276 return pet_array_free(parent);
4278 base_name = isl_set_get_tuple_name(parent->extent);
4279 field_name = isl_set_get_tuple_name(array->extent);
4280 product_name = member_access_name(ctx, base_name, field_name);
4282 array->extent = isl_set_product(isl_set_copy(parent->extent),
4283 array->extent);
4284 if (product_name)
4285 array->extent = isl_set_set_tuple_name(array->extent,
4286 product_name);
4287 array->context = isl_set_intersect(array->context,
4288 isl_set_copy(parent->context));
4290 pet_array_free(parent);
4291 free(product_name);
4293 if (!array->extent || !array->context || !product_name)
4294 return pet_array_free(array);
4297 return array;
4300 /* Add a pet_type corresponding to "decl" to "scop, provided
4301 * it is a member of "types" and it has not been added before
4302 * (i.e., it is not a member of "types_done".
4304 * Since we want the user to be able to print the types
4305 * in the order in which they appear in the scop, we need to
4306 * make sure that types of fields in a structure appear before
4307 * that structure. We therefore call ourselves recursively
4308 * on the types of all record subfields.
4310 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
4311 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
4312 lex_recorddecl_set &types_done)
4314 string s;
4315 llvm::raw_string_ostream S(s);
4316 RecordDecl::field_iterator it;
4318 if (types.find(decl) == types.end())
4319 return scop;
4320 if (types_done.find(decl) != types_done.end())
4321 return scop;
4323 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
4324 RecordDecl *record;
4325 QualType type = it->getType();
4327 if (!type->isRecordType())
4328 continue;
4329 record = pet_clang_record_decl(type);
4330 scop = add_type(ctx, scop, record, PP, types, types_done);
4333 if (strlen(decl->getName().str().c_str()) == 0)
4334 return scop;
4336 decl->print(S, PrintingPolicy(PP.getLangOpts()));
4337 S.str();
4339 scop->types[scop->n_type] = pet_type_alloc(ctx,
4340 decl->getName().str().c_str(), s.c_str());
4341 if (!scop->types[scop->n_type])
4342 return pet_scop_free(scop);
4344 types_done.insert(decl);
4346 scop->n_type++;
4348 return scop;
4351 /* Construct a list of pet_arrays, one for each array (or scalar)
4352 * accessed inside "scop", add this list to "scop" and return the result.
4354 * The context of "scop" is updated with the intersection of
4355 * the contexts of all arrays, i.e., constraints on the parameters
4356 * that ensure that the arrays have a valid (non-negative) size.
4358 * If the any of the extracted arrays refers to a member access,
4359 * then also add the required types to "scop".
4361 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
4363 int i;
4364 array_desc_set arrays;
4365 array_desc_set::iterator it;
4366 lex_recorddecl_set types;
4367 lex_recorddecl_set types_done;
4368 lex_recorddecl_set::iterator types_it;
4369 int n_array;
4370 struct pet_array **scop_arrays;
4372 if (!scop)
4373 return NULL;
4375 pet_scop_collect_arrays(scop, arrays);
4376 if (arrays.size() == 0)
4377 return scop;
4379 n_array = scop->n_array;
4381 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
4382 n_array + arrays.size());
4383 if (!scop_arrays)
4384 goto error;
4385 scop->arrays = scop_arrays;
4387 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
4388 struct pet_array *array;
4389 array = extract_array(ctx, *it, &types);
4390 scop->arrays[n_array + i] = array;
4391 if (!scop->arrays[n_array + i])
4392 goto error;
4393 scop->n_array++;
4394 scop->context = isl_set_intersect(scop->context,
4395 isl_set_copy(array->context));
4396 if (!scop->context)
4397 goto error;
4400 if (types.size() == 0)
4401 return scop;
4403 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
4404 if (!scop->types)
4405 goto error;
4407 for (types_it = types.begin(); types_it != types.end(); ++types_it)
4408 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
4410 return scop;
4411 error:
4412 pet_scop_free(scop);
4413 return NULL;
4416 /* Bound all parameters in scop->context to the possible values
4417 * of the corresponding C variable.
4419 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
4421 int n;
4423 if (!scop)
4424 return NULL;
4426 n = isl_set_dim(scop->context, isl_dim_param);
4427 for (int i = 0; i < n; ++i) {
4428 isl_id *id;
4429 ValueDecl *decl;
4431 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
4432 if (pet_nested_in_id(id)) {
4433 isl_id_free(id);
4434 isl_die(isl_set_get_ctx(scop->context),
4435 isl_error_internal,
4436 "unresolved nested parameter", goto error);
4438 decl = (ValueDecl *) isl_id_get_user(id);
4439 isl_id_free(id);
4441 scop->context = set_parameter_bounds(scop->context, i, decl);
4443 if (!scop->context)
4444 goto error;
4447 return scop;
4448 error:
4449 pet_scop_free(scop);
4450 return NULL;
4453 /* Construct a pet_scop from the given function.
4455 * If the scop was delimited by scop and endscop pragmas, then we override
4456 * the file offsets by those derived from the pragmas.
4458 struct pet_scop *PetScan::scan(FunctionDecl *fd)
4460 pet_scop *scop;
4461 Stmt *stmt;
4463 stmt = fd->getBody();
4465 if (options->autodetect)
4466 scop = extract(stmt, true);
4467 else {
4468 scop = scan(stmt);
4469 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
4471 scop = pet_scop_detect_parameter_accesses(scop);
4472 scop = scan_arrays(scop);
4473 scop = add_parameter_bounds(scop);
4474 scop = pet_scop_gist(scop, value_bounds);
4476 return scop;