PetScan::extract_affine: extract expression as pet_expr first
[pet.git] / scan.cc
blobddd13b792b327b3ac5168389fac963c29aece3ac
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, Expr *rhs)
1110 isl_id *id;
1111 ValueDecl *decl;
1112 isl_pw_aff *pa;
1114 if (!lhs)
1115 return;
1116 if (!pet_expr_is_scalar_access(lhs))
1117 return;
1119 id = pet_expr_access_get_id(lhs);
1120 decl = (ValueDecl *) isl_id_get_user(id);
1121 isl_id_free(id);
1123 pa = try_extract_affine(rhs);
1124 clear_assignment(assigned_value, decl);
1125 if (!pa)
1126 return;
1127 assigned_value[decl] = pa;
1128 insert_expression(pa);
1131 /* Construct a pet_expr representing a binary operator expression.
1133 * If the top level operator is an assignment and the LHS is an access,
1134 * then we mark that access as a write. If the operator is a compound
1135 * assignment, the access is marked as both a read and a write.
1137 * If "expr" assigns something to a scalar variable, then we mark
1138 * the variable as having been assigned. If, furthermore, the expression
1139 * is affine, then keep track of this value in assigned_value
1140 * so that we can plug it in when we later come across the same variable.
1142 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1144 int type_size;
1145 pet_expr *lhs, *rhs;
1146 enum pet_op_type op;
1148 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1149 if (op == pet_op_last) {
1150 unsupported(expr);
1151 return NULL;
1154 lhs = extract_expr(expr->getLHS());
1155 rhs = extract_expr(expr->getRHS());
1157 if (expr->isAssignmentOp() &&
1158 pet_expr_get_type(lhs) == pet_expr_access) {
1159 lhs = mark_write(lhs);
1160 if (expr->isCompoundAssignmentOp())
1161 lhs = pet_expr_access_set_read(lhs, 1);
1164 if (expr->getOpcode() == BO_Assign)
1165 assign(lhs, expr->getRHS());
1167 type_size = get_type_size(expr->getType(), ast_context);
1168 return pet_expr_new_binary(type_size, op, lhs, rhs);
1171 /* Construct a pet_scop with a single statement killing the entire
1172 * array "array".
1174 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1176 isl_id *id;
1177 isl_space *space;
1178 isl_multi_pw_aff *index;
1179 isl_map *access;
1180 pet_expr *expr;
1182 if (!array)
1183 return NULL;
1184 access = isl_map_from_range(isl_set_copy(array->extent));
1185 id = isl_set_get_tuple_id(array->extent);
1186 space = isl_space_alloc(ctx, 0, 0, 0);
1187 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1188 index = isl_multi_pw_aff_zero(space);
1189 expr = pet_expr_kill_from_access_and_index(access, index);
1190 return extract(expr, stmt->getSourceRange(), false);
1193 /* Construct a pet_scop for a (single) variable declaration.
1195 * The scop contains the variable being declared (as an array)
1196 * and a statement killing the array.
1198 * If the variable is initialized in the AST, then the scop
1199 * also contains an assignment to the variable.
1201 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1203 int type_size;
1204 Decl *decl;
1205 VarDecl *vd;
1206 pet_expr *lhs, *rhs, *pe;
1207 struct pet_scop *scop_decl, *scop;
1208 struct pet_array *array;
1210 if (!stmt->isSingleDecl()) {
1211 unsupported(stmt);
1212 return NULL;
1215 decl = stmt->getSingleDecl();
1216 vd = cast<VarDecl>(decl);
1218 array = extract_array(ctx, vd, NULL);
1219 if (array)
1220 array->declared = 1;
1221 scop_decl = kill(stmt, array);
1222 scop_decl = pet_scop_add_array(scop_decl, array);
1224 if (!vd->getInit())
1225 return scop_decl;
1227 lhs = extract_access_expr(vd);
1228 rhs = extract_expr(vd->getInit());
1230 lhs = mark_write(lhs);
1231 assign(lhs, vd->getInit());
1233 type_size = get_type_size(vd->getType(), ast_context);
1234 pe = pet_expr_new_binary(type_size, pet_op_assign, lhs, rhs);
1235 scop = extract(pe, stmt->getSourceRange(), false);
1237 scop_decl = pet_scop_prefix(scop_decl, 0);
1238 scop = pet_scop_prefix(scop, 1);
1240 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1242 return scop;
1245 /* Construct a pet_expr representing a conditional operation.
1247 * We first try to extract the condition as an affine expression.
1248 * If that fails, we construct a pet_expr tree representing the condition.
1250 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1252 pet_expr *cond, *lhs, *rhs;
1253 isl_pw_aff *pa;
1255 pa = try_extract_affine(expr->getCond());
1256 if (pa) {
1257 isl_multi_pw_aff *test = isl_multi_pw_aff_from_pw_aff(pa);
1258 cond = pet_expr_from_index(test);
1259 } else
1260 cond = extract_expr(expr->getCond());
1261 lhs = extract_expr(expr->getTrueExpr());
1262 rhs = extract_expr(expr->getFalseExpr());
1264 return pet_expr_new_ternary(cond, lhs, rhs);
1267 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1269 return extract_expr(expr->getSubExpr());
1272 /* Construct a pet_expr representing a floating point value.
1274 * If the floating point literal does not appear in a macro,
1275 * then we use the original representation in the source code
1276 * as the string representation. Otherwise, we use the pretty
1277 * printer to produce a string representation.
1279 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1281 double d;
1282 string s;
1283 const LangOptions &LO = PP.getLangOpts();
1284 SourceLocation loc = expr->getLocation();
1286 if (!loc.isMacroID()) {
1287 SourceManager &SM = PP.getSourceManager();
1288 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1289 s = string(SM.getCharacterData(loc), len);
1290 } else {
1291 llvm::raw_string_ostream S(s);
1292 expr->printPretty(S, 0, PrintingPolicy(LO));
1293 S.str();
1295 d = expr->getValueAsApproximateDouble();
1296 return pet_expr_new_double(ctx, d, s.c_str());
1299 /* Convert the index expression "index" into an access pet_expr of type "qt".
1301 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
1302 __isl_take isl_multi_pw_aff *index)
1304 pet_expr *pe;
1305 int depth;
1306 int type_size;
1308 depth = extract_depth(index);
1309 type_size = get_type_size(qt, ast_context);
1311 pe = pet_expr_from_index_and_depth(type_size, index, depth);
1313 return pe;
1316 /* Extract an index expression from "expr" and then convert it into
1317 * an access pet_expr.
1319 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
1321 return extract_access_expr(expr->getType(), extract_index(expr));
1324 /* Extract an index expression from "decl" and then convert it into
1325 * an access pet_expr.
1327 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1329 return extract_access_expr(decl->getType(), extract_index(decl));
1332 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
1334 return extract_expr(expr->getSubExpr());
1337 /* Extract an assume statement from the argument "expr"
1338 * of a __pencil_assume statement.
1340 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
1342 isl_pw_aff *cond;
1343 pet_expr *res;
1345 cond = try_extract_affine_condition(expr);
1346 if (!cond) {
1347 res = extract_expr(expr);
1348 } else {
1349 isl_multi_pw_aff *index;
1350 index = isl_multi_pw_aff_from_pw_aff(cond);
1351 res = pet_expr_from_index(index);
1353 return pet_expr_new_unary(pet_op_assume, res);
1356 /* Construct a pet_expr corresponding to the function call argument "expr".
1357 * The argument appears in position "pos" of a call to function "fd".
1359 * If we are passing along a pointer to an array element
1360 * or an entire row or even higher dimensional slice of an array,
1361 * then the function being called may write into the array.
1363 * We assume here that if the function is declared to take a pointer
1364 * to a const type, then the function will perform a read
1365 * and that otherwise, it will perform a write.
1367 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
1368 Expr *expr)
1370 pet_expr *res;
1371 int is_addr = 0, is_partial = 0;
1372 Stmt::StmtClass sc;
1374 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
1375 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
1376 expr = ice->getSubExpr();
1378 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
1379 UnaryOperator *op = cast<UnaryOperator>(expr);
1380 if (op->getOpcode() == UO_AddrOf) {
1381 is_addr = 1;
1382 expr = op->getSubExpr();
1385 res = extract_expr(expr);
1386 if (!res)
1387 return NULL;
1388 sc = expr->getStmtClass();
1389 if ((sc == Stmt::ArraySubscriptExprClass ||
1390 sc == Stmt::MemberExprClass) &&
1391 array_depth(expr->getType().getTypePtr()) > 0)
1392 is_partial = 1;
1393 if ((is_addr || is_partial) &&
1394 pet_expr_get_type(res) == pet_expr_access) {
1395 ParmVarDecl *parm;
1396 if (!fd->hasPrototype()) {
1397 report_prototype_required(expr);
1398 return pet_expr_free(res);
1400 parm = fd->getParamDecl(pos);
1401 if (!const_base(parm->getType()))
1402 res = mark_write(res);
1405 if (is_addr)
1406 res = pet_expr_new_unary(pet_op_address_of, res);
1407 return res;
1410 /* Construct a pet_expr representing a function call.
1412 * In the special case of a "call" to __pencil_assume,
1413 * construct an assume expression instead.
1415 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1417 pet_expr *res = NULL;
1418 FunctionDecl *fd;
1419 string name;
1420 unsigned n_arg;
1422 fd = expr->getDirectCallee();
1423 if (!fd) {
1424 unsupported(expr);
1425 return NULL;
1428 name = fd->getDeclName().getAsString();
1429 n_arg = expr->getNumArgs();
1431 if (n_arg == 1 && name == "__pencil_assume")
1432 return extract_assume(expr->getArg(0));
1434 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1435 if (!res)
1436 return NULL;
1438 for (int i = 0; i < n_arg; ++i) {
1439 Expr *arg = expr->getArg(i);
1440 res = pet_expr_set_arg(res, i,
1441 PetScan::extract_argument(fd, i, arg));
1444 return res;
1447 /* Construct a pet_expr representing a (C style) cast.
1449 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1451 pet_expr *arg;
1452 QualType type;
1454 arg = extract_expr(expr->getSubExpr());
1455 if (!arg)
1456 return NULL;
1458 type = expr->getTypeAsWritten();
1459 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1462 /* Construct a pet_expr representing an integer.
1464 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1466 return pet_expr_new_int(extract_int(expr));
1469 /* Try and construct a pet_expr representing "expr".
1471 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1473 switch (expr->getStmtClass()) {
1474 case Stmt::UnaryOperatorClass:
1475 return extract_expr(cast<UnaryOperator>(expr));
1476 case Stmt::CompoundAssignOperatorClass:
1477 case Stmt::BinaryOperatorClass:
1478 return extract_expr(cast<BinaryOperator>(expr));
1479 case Stmt::ImplicitCastExprClass:
1480 return extract_expr(cast<ImplicitCastExpr>(expr));
1481 case Stmt::ArraySubscriptExprClass:
1482 case Stmt::DeclRefExprClass:
1483 case Stmt::MemberExprClass:
1484 return extract_access_expr(expr);
1485 case Stmt::IntegerLiteralClass:
1486 return extract_expr(cast<IntegerLiteral>(expr));
1487 case Stmt::FloatingLiteralClass:
1488 return extract_expr(cast<FloatingLiteral>(expr));
1489 case Stmt::ParenExprClass:
1490 return extract_expr(cast<ParenExpr>(expr));
1491 case Stmt::ConditionalOperatorClass:
1492 return extract_expr(cast<ConditionalOperator>(expr));
1493 case Stmt::CallExprClass:
1494 return extract_expr(cast<CallExpr>(expr));
1495 case Stmt::CStyleCastExprClass:
1496 return extract_expr(cast<CStyleCastExpr>(expr));
1497 default:
1498 unsupported(expr);
1500 return NULL;
1503 /* Check if the given initialization statement is an assignment.
1504 * If so, return that assignment. Otherwise return NULL.
1506 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1508 BinaryOperator *ass;
1510 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1511 return NULL;
1513 ass = cast<BinaryOperator>(init);
1514 if (ass->getOpcode() != BO_Assign)
1515 return NULL;
1517 return ass;
1520 /* Check if the given initialization statement is a declaration
1521 * of a single variable.
1522 * If so, return that declaration. Otherwise return NULL.
1524 Decl *PetScan::initialization_declaration(Stmt *init)
1526 DeclStmt *decl;
1528 if (init->getStmtClass() != Stmt::DeclStmtClass)
1529 return NULL;
1531 decl = cast<DeclStmt>(init);
1533 if (!decl->isSingleDecl())
1534 return NULL;
1536 return decl->getSingleDecl();
1539 /* Given the assignment operator in the initialization of a for loop,
1540 * extract the induction variable, i.e., the (integer)variable being
1541 * assigned.
1543 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1545 Expr *lhs;
1546 DeclRefExpr *ref;
1547 ValueDecl *decl;
1548 const Type *type;
1550 lhs = init->getLHS();
1551 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1552 unsupported(init);
1553 return NULL;
1556 ref = cast<DeclRefExpr>(lhs);
1557 decl = ref->getDecl();
1558 type = decl->getType().getTypePtr();
1560 if (!type->isIntegerType()) {
1561 unsupported(lhs);
1562 return NULL;
1565 return decl;
1568 /* Given the initialization statement of a for loop and the single
1569 * declaration in this initialization statement,
1570 * extract the induction variable, i.e., the (integer) variable being
1571 * declared.
1573 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1575 VarDecl *vd;
1577 vd = cast<VarDecl>(decl);
1579 const QualType type = vd->getType();
1580 if (!type->isIntegerType()) {
1581 unsupported(init);
1582 return NULL;
1585 if (!vd->getInit()) {
1586 unsupported(init);
1587 return NULL;
1590 return vd;
1593 /* Check that op is of the form iv++ or iv--.
1594 * Return a pet_expr representing "1" or "-1" accordingly.
1596 __isl_give pet_expr *PetScan::extract_unary_increment(
1597 clang::UnaryOperator *op, clang::ValueDecl *iv)
1599 Expr *sub;
1600 DeclRefExpr *ref;
1601 isl_val *v;
1603 if (!op->isIncrementDecrementOp()) {
1604 unsupported(op);
1605 return NULL;
1608 sub = op->getSubExpr();
1609 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1610 unsupported(op);
1611 return NULL;
1614 ref = cast<DeclRefExpr>(sub);
1615 if (ref->getDecl() != iv) {
1616 unsupported(op);
1617 return NULL;
1620 if (op->isIncrementOp())
1621 v = isl_val_one(ctx);
1622 else
1623 v = isl_val_negone(ctx);
1625 return pet_expr_new_int(v);
1628 /* Check if op is of the form
1630 * iv = expr
1632 * and return the increment "expr - iv" as a pet_expr.
1634 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1635 clang::ValueDecl *iv)
1637 int type_size;
1638 Expr *lhs;
1639 DeclRefExpr *ref;
1640 pet_expr *expr, *expr_iv;
1642 if (op->getOpcode() != BO_Assign) {
1643 unsupported(op);
1644 return NULL;
1647 lhs = op->getLHS();
1648 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1649 unsupported(op);
1650 return NULL;
1653 ref = cast<DeclRefExpr>(lhs);
1654 if (ref->getDecl() != iv) {
1655 unsupported(op);
1656 return NULL;
1659 expr = extract_expr(op->getRHS());
1660 expr_iv = extract_expr(lhs);
1662 type_size = get_type_size(iv->getType(), ast_context);
1663 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1666 /* Check that op is of the form iv += cst or iv -= cst
1667 * and return a pet_expr corresponding to cst or -cst accordingly.
1669 __isl_give pet_expr *PetScan::extract_compound_increment(
1670 CompoundAssignOperator *op, clang::ValueDecl *iv)
1672 Expr *lhs;
1673 DeclRefExpr *ref;
1674 bool neg = false;
1675 pet_expr *expr;
1676 BinaryOperatorKind opcode;
1678 opcode = op->getOpcode();
1679 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1680 unsupported(op);
1681 return NULL;
1683 if (opcode == BO_SubAssign)
1684 neg = true;
1686 lhs = op->getLHS();
1687 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1688 unsupported(op);
1689 return NULL;
1692 ref = cast<DeclRefExpr>(lhs);
1693 if (ref->getDecl() != iv) {
1694 unsupported(op);
1695 return NULL;
1698 expr = extract_expr(op->getRHS());
1699 if (neg)
1700 expr = pet_expr_new_unary(pet_op_minus, expr);
1702 return expr;
1705 /* Check that the increment of the given for loop increments
1706 * (or decrements) the induction variable "iv" and return
1707 * the increment as a pet_expr if successful.
1709 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1710 ValueDecl *iv)
1712 Stmt *inc = stmt->getInc();
1714 if (!inc) {
1715 report_missing_increment(stmt);
1716 return NULL;
1719 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1720 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1721 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1722 return extract_compound_increment(
1723 cast<CompoundAssignOperator>(inc), iv);
1724 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1725 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1727 unsupported(inc);
1728 return NULL;
1731 /* Embed the given iteration domain in an extra outer loop
1732 * with induction variable "var".
1733 * If this variable appeared as a parameter in the constraints,
1734 * it is replaced by the new outermost dimension.
1736 static __isl_give isl_set *embed(__isl_take isl_set *set,
1737 __isl_take isl_id *var)
1739 int pos;
1741 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1742 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1743 if (pos >= 0) {
1744 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1745 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1748 isl_id_free(var);
1749 return set;
1752 /* Return those elements in the space of "cond" that come after
1753 * (based on "sign") an element in "cond".
1755 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
1757 isl_map *previous_to_this;
1759 if (sign > 0)
1760 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
1761 else
1762 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
1764 cond = isl_set_apply(cond, previous_to_this);
1766 return cond;
1769 /* Create the infinite iteration domain
1771 * { [id] : id >= 0 }
1773 * If "scop" has an affine skip of type pet_skip_later,
1774 * then remove those iterations i that have an earlier iteration
1775 * where the skip condition is satisfied, meaning that iteration i
1776 * is not executed.
1777 * Since we are dealing with a loop without loop iterator,
1778 * the skip condition cannot refer to the current loop iterator and
1779 * so effectively, the returned set is of the form
1781 * { [0]; [id] : id >= 1 and not skip }
1783 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
1784 struct pet_scop *scop)
1786 isl_ctx *ctx = isl_id_get_ctx(id);
1787 isl_set *domain;
1788 isl_set *skip;
1790 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1791 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
1793 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
1794 return domain;
1796 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
1797 skip = embed(skip, isl_id_copy(id));
1798 skip = isl_set_intersect(skip , isl_set_copy(domain));
1799 domain = isl_set_subtract(domain, after(skip, 1));
1801 return domain;
1804 /* Create an identity affine expression on the space containing "domain",
1805 * which is assumed to be one-dimensional.
1807 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
1809 isl_local_space *ls;
1811 ls = isl_local_space_from_space(isl_set_get_space(domain));
1812 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
1815 /* Create an affine expression that maps elements
1816 * of a single-dimensional array "id_test" to the previous element
1817 * (according to "inc"), provided this element belongs to "domain".
1818 * That is, create the affine expression
1820 * { id[x] -> id[x - inc] : x - inc in domain }
1822 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
1823 __isl_take isl_set *domain, __isl_take isl_val *inc)
1825 isl_space *space;
1826 isl_local_space *ls;
1827 isl_aff *aff;
1828 isl_multi_pw_aff *prev;
1830 space = isl_set_get_space(domain);
1831 ls = isl_local_space_from_space(space);
1832 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
1833 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
1834 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
1835 domain = isl_set_preimage_multi_pw_aff(domain,
1836 isl_multi_pw_aff_copy(prev));
1837 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
1838 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
1840 return prev;
1843 /* Add an implication to "scop" expressing that if an element of
1844 * virtual array "id_test" has value "satisfied" then all previous elements
1845 * of this array also have that value. The set of previous elements
1846 * is bounded by "domain". If "sign" is negative then the iterator
1847 * is decreasing and we express that all subsequent array elements
1848 * (but still defined previously) have the same value.
1850 static struct pet_scop *add_implication(struct pet_scop *scop,
1851 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
1852 int satisfied)
1854 isl_space *space;
1855 isl_map *map;
1857 domain = isl_set_set_tuple_id(domain, id_test);
1858 space = isl_set_get_space(domain);
1859 if (sign > 0)
1860 map = isl_map_lex_ge(space);
1861 else
1862 map = isl_map_lex_le(space);
1863 map = isl_map_intersect_range(map, domain);
1864 scop = pet_scop_add_implication(scop, map, satisfied);
1866 return scop;
1869 /* Add a filter to "scop" that imposes that it is only executed
1870 * when the variable identified by "id_test" has a zero value
1871 * for all previous iterations of "domain".
1873 * In particular, add a filter that imposes that the array
1874 * has a zero value at the previous iteration of domain and
1875 * add an implication that implies that it then has that
1876 * value for all previous iterations.
1878 static struct pet_scop *scop_add_break(struct pet_scop *scop,
1879 __isl_take isl_id *id_test, __isl_take isl_set *domain,
1880 __isl_take isl_val *inc)
1882 isl_multi_pw_aff *prev;
1883 int sign = isl_val_sgn(inc);
1885 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
1886 scop = add_implication(scop, id_test, domain, sign, 0);
1887 scop = pet_scop_filter(scop, prev, 0);
1889 return scop;
1892 /* Construct a pet_scop for an infinite loop around the given body.
1894 * We extract a pet_scop for the body and then embed it in a loop with
1895 * iteration domain
1897 * { [t] : t >= 0 }
1899 * and schedule
1901 * { [t] -> [t] }
1903 * If the body contains any break, then it is taken into
1904 * account in infinite_domain (if the skip condition is affine)
1905 * or in scop_add_break (if the skip condition is not affine).
1907 * If we were only able to extract part of the body, then simply
1908 * return that part.
1910 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1912 isl_id *id, *id_test;
1913 isl_set *domain;
1914 isl_aff *ident;
1915 struct pet_scop *scop;
1916 bool has_var_break;
1918 scop = extract(body);
1919 if (!scop)
1920 return NULL;
1921 if (partial)
1922 return scop;
1924 id = isl_id_alloc(ctx, "t", NULL);
1925 domain = infinite_domain(isl_id_copy(id), scop);
1926 ident = identity_aff(domain);
1928 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
1929 if (has_var_break)
1930 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
1932 scop = pet_scop_embed(scop, isl_set_copy(domain),
1933 isl_aff_copy(ident), ident, id);
1934 if (has_var_break)
1935 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
1936 else
1937 isl_set_free(domain);
1939 return scop;
1942 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1944 * for (;;)
1945 * body
1948 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1950 clear_assignments clear(assigned_value);
1951 clear.TraverseStmt(stmt->getBody());
1953 return extract_infinite_loop(stmt->getBody());
1956 /* Add an array with the given extent (range of "index") to the list
1957 * of arrays in "scop" and return the extended pet_scop.
1958 * The array is marked as attaining values 0 and 1 only and
1959 * as each element being assigned at most once.
1961 static struct pet_scop *scop_add_array(struct pet_scop *scop,
1962 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
1964 int int_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
1966 return pet_scop_add_boolean_array(scop, isl_multi_pw_aff_copy(index),
1967 int_size);
1970 /* Construct a pet_scop for a while loop of the form
1972 * while (pa)
1973 * body
1975 * In particular, construct a scop for an infinite loop around body and
1976 * intersect the domain with the affine expression.
1977 * Note that this intersection may result in an empty loop.
1979 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
1980 Stmt *body)
1982 struct pet_scop *scop;
1983 isl_set *dom;
1984 isl_set *valid;
1986 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
1987 dom = isl_pw_aff_non_zero_set(pa);
1988 scop = extract_infinite_loop(body);
1989 scop = pet_scop_restrict(scop, isl_set_params(dom));
1990 scop = pet_scop_restrict_context(scop, isl_set_params(valid));
1992 return scop;
1995 /* Construct a scop for a while, given the scops for the condition
1996 * and the body, the filter identifier and the iteration domain of
1997 * the while loop.
1999 * In particular, the scop for the condition is filtered to depend
2000 * on "id_test" evaluating to true for all previous iterations
2001 * of the loop, while the scop for the body is filtered to depend
2002 * on "id_test" evaluating to true for all iterations up to the
2003 * current iteration.
2004 * The actual filter only imposes that this virtual array has
2005 * value one on the previous or the current iteration.
2006 * The fact that this condition also applies to the previous
2007 * iterations is enforced by an implication.
2009 * These filtered scops are then combined into a single scop.
2011 * "sign" is positive if the iterator increases and negative
2012 * if it decreases.
2014 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2015 struct pet_scop *scop_body, __isl_take isl_id *id_test,
2016 __isl_take isl_set *domain, __isl_take isl_val *inc)
2018 isl_ctx *ctx = isl_set_get_ctx(domain);
2019 isl_space *space;
2020 isl_multi_pw_aff *test_index;
2021 isl_multi_pw_aff *prev;
2022 int sign = isl_val_sgn(inc);
2023 struct pet_scop *scop;
2025 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2026 scop_cond = pet_scop_filter(scop_cond, prev, 1);
2028 space = isl_space_map_from_set(isl_set_get_space(domain));
2029 test_index = isl_multi_pw_aff_identity(space);
2030 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
2031 isl_id_copy(id_test));
2032 scop_body = pet_scop_filter(scop_body, test_index, 1);
2034 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
2035 scop = add_implication(scop, id_test, domain, sign, 1);
2037 return scop;
2040 /* Check if the while loop is of the form
2042 * while (affine expression)
2043 * body
2045 * If so, call extract_affine_while to construct a scop.
2047 * Otherwise, extract the body and pass control to extract_while
2048 * to extend the iteration domain with an infinite loop.
2049 * If we were only able to extract part of the body, then simply
2050 * return that part.
2052 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2054 Expr *cond;
2055 int test_nr, stmt_nr;
2056 isl_pw_aff *pa;
2057 struct pet_scop *scop_body;
2059 cond = stmt->getCond();
2060 if (!cond) {
2061 unsupported(stmt);
2062 return NULL;
2065 clear_assignments clear(assigned_value);
2066 clear.TraverseStmt(stmt->getBody());
2068 pa = try_extract_affine_condition(cond);
2069 if (pa)
2070 return extract_affine_while(pa, stmt->getBody());
2072 if (!allow_nested) {
2073 unsupported(stmt);
2074 return NULL;
2077 test_nr = n_test++;
2078 stmt_nr = n_stmt++;
2079 scop_body = extract(stmt->getBody());
2080 if (partial)
2081 return scop_body;
2083 return extract_while(cond, test_nr, stmt_nr, scop_body, NULL);
2086 /* Construct a generic while scop, with iteration domain
2087 * { [t] : t >= 0 } around "scop_body". The scop consists of two parts,
2088 * one for evaluating the condition "cond" and one for the body.
2089 * "test_nr" is the sequence number of the virtual test variable that contains
2090 * the result of the condition and "stmt_nr" is the sequence number
2091 * of the statement that evaluates the condition.
2092 * If "scop_inc" is not NULL, then it is added at the end of the body,
2093 * after replacing any skip conditions resulting from continue statements
2094 * by the skip conditions resulting from break statements (if any).
2096 * The schedule is adjusted to reflect that the condition is evaluated
2097 * before the body is executed and the body is filtered to depend
2098 * on the result of the condition evaluating to true on all iterations
2099 * up to the current iteration, while the evaluation of the condition itself
2100 * is filtered to depend on the result of the condition evaluating to true
2101 * on all previous iterations.
2102 * The context of the scop representing the body is dropped
2103 * because we don't know how many times the body will be executed,
2104 * if at all.
2106 * If the body contains any break, then it is taken into
2107 * account in infinite_domain (if the skip condition is affine)
2108 * or in scop_add_break (if the skip condition is not affine).
2110 struct pet_scop *PetScan::extract_while(Expr *cond, int test_nr, int stmt_nr,
2111 struct pet_scop *scop_body, struct pet_scop *scop_inc)
2113 isl_id *id, *id_test, *id_break_test;
2114 isl_set *domain;
2115 isl_aff *ident;
2116 isl_multi_pw_aff *test_index;
2117 struct pet_scop *scop;
2118 bool has_var_break;
2120 test_index = pet_create_test_index(ctx, test_nr);
2121 scop = extract_non_affine_condition(cond, stmt_nr,
2122 isl_multi_pw_aff_copy(test_index));
2123 scop = scop_add_array(scop, test_index, ast_context);
2124 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2125 isl_multi_pw_aff_free(test_index);
2127 id = isl_id_alloc(ctx, "t", NULL);
2128 domain = infinite_domain(isl_id_copy(id), scop_body);
2129 ident = identity_aff(domain);
2131 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2132 if (has_var_break)
2133 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2135 scop = pet_scop_prefix(scop, 0);
2136 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_aff_copy(ident),
2137 isl_aff_copy(ident), isl_id_copy(id));
2138 scop_body = pet_scop_reset_context(scop_body);
2139 scop_body = pet_scop_prefix(scop_body, 1);
2140 if (scop_inc) {
2141 scop_inc = pet_scop_prefix(scop_inc, 2);
2142 if (pet_scop_has_skip(scop_body, pet_skip_later)) {
2143 isl_multi_pw_aff *skip;
2144 skip = pet_scop_get_skip(scop_body, pet_skip_later);
2145 scop_body = pet_scop_set_skip(scop_body,
2146 pet_skip_now, skip);
2147 } else
2148 pet_scop_reset_skip(scop_body, pet_skip_now);
2149 scop_body = pet_scop_add_seq(ctx, scop_body, scop_inc);
2151 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2152 isl_aff_copy(ident), ident, id);
2154 if (has_var_break) {
2155 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2156 isl_set_copy(domain), isl_val_one(ctx));
2157 scop_body = scop_add_break(scop_body, id_break_test,
2158 isl_set_copy(domain), isl_val_one(ctx));
2160 scop = scop_add_while(scop, scop_body, id_test, domain,
2161 isl_val_one(ctx));
2163 return scop;
2166 /* Check whether "cond" expresses a simple loop bound
2167 * on the only set dimension.
2168 * In particular, if "up" is set then "cond" should contain only
2169 * upper bounds on the set dimension.
2170 * Otherwise, it should contain only lower bounds.
2172 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2174 if (isl_val_is_pos(inc))
2175 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2176 else
2177 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2180 /* Extend a condition on a given iteration of a loop to one that
2181 * imposes the same condition on all previous iterations.
2182 * "domain" expresses the lower [upper] bound on the iterations
2183 * when inc is positive [negative].
2185 * In particular, we construct the condition (when inc is positive)
2187 * forall i' : (domain(i') and i' <= i) => cond(i')
2189 * which is equivalent to
2191 * not exists i' : domain(i') and i' <= i and not cond(i')
2193 * We construct this set by negating cond, applying a map
2195 * { [i'] -> [i] : domain(i') and i' <= i }
2197 * and then negating the result again.
2199 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2200 __isl_take isl_set *domain, __isl_take isl_val *inc)
2202 isl_map *previous_to_this;
2204 if (isl_val_is_pos(inc))
2205 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2206 else
2207 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2209 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2211 cond = isl_set_complement(cond);
2212 cond = isl_set_apply(cond, previous_to_this);
2213 cond = isl_set_complement(cond);
2215 isl_val_free(inc);
2217 return cond;
2220 /* Construct a domain of the form
2222 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2224 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2225 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2227 isl_aff *aff;
2228 isl_space *dim;
2229 isl_set *set;
2231 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2232 dim = isl_pw_aff_get_domain_space(init);
2233 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2234 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2235 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2237 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2238 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2239 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2240 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2242 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2244 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2246 return isl_set_params(set);
2249 /* Assuming "cond" represents a bound on a loop where the loop
2250 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2251 * is possible.
2253 * Under the given assumptions, wrapping is only possible if "cond" allows
2254 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2255 * increasing iterator and 0 in case of a decreasing iterator.
2257 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2258 __isl_keep isl_val *inc)
2260 bool cw;
2261 isl_ctx *ctx;
2262 isl_val *limit;
2263 isl_set *test;
2265 test = isl_set_copy(cond);
2267 ctx = isl_set_get_ctx(test);
2268 if (isl_val_is_neg(inc))
2269 limit = isl_val_zero(ctx);
2270 else {
2271 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2272 limit = isl_val_2exp(limit);
2273 limit = isl_val_sub_ui(limit, 1);
2276 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2277 cw = !isl_set_is_empty(test);
2278 isl_set_free(test);
2280 return cw;
2283 /* Given a one-dimensional space, construct the following affine expression
2284 * on this space
2286 * { [v] -> [v mod 2^width] }
2288 * where width is the number of bits used to represent the values
2289 * of the unsigned variable "iv".
2291 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2292 ValueDecl *iv)
2294 isl_ctx *ctx;
2295 isl_val *mod;
2296 isl_aff *aff;
2298 ctx = isl_space_get_ctx(dim);
2299 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2300 mod = isl_val_2exp(mod);
2302 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2303 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2304 aff = isl_aff_mod_val(aff, mod);
2306 return aff;
2309 /* Project out the parameter "id" from "set".
2311 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2312 __isl_keep isl_id *id)
2314 int pos;
2316 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2317 if (pos >= 0)
2318 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2320 return set;
2323 /* Compute the set of parameters for which "set1" is a subset of "set2".
2325 * set1 is a subset of set2 if
2327 * forall i in set1 : i in set2
2329 * or
2331 * not exists i in set1 and i not in set2
2333 * i.e.,
2335 * not exists i in set1 \ set2
2337 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2338 __isl_take isl_set *set2)
2340 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2343 /* Compute the set of parameter values for which "cond" holds
2344 * on the next iteration for each element of "dom".
2346 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2347 * and then compute the set of parameters for which the result is a subset
2348 * of "cond".
2350 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2351 __isl_take isl_set *dom, __isl_take isl_val *inc)
2353 isl_space *space;
2354 isl_aff *aff;
2355 isl_map *next;
2357 space = isl_set_get_space(dom);
2358 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2359 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2360 aff = isl_aff_add_constant_val(aff, inc);
2361 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2363 dom = isl_set_apply(dom, next);
2365 return enforce_subset(dom, cond);
2368 /* Extract the for loop "stmt" as a while loop.
2369 * "iv" is the loop iterator. "init" is the initialization.
2370 * "inc" is the increment.
2372 * That is, the for loop has the form
2374 * for (iv = init; cond; iv += inc)
2375 * body;
2377 * and is treated as
2379 * iv = init;
2380 * while (cond) {
2381 * body;
2382 * iv += inc;
2385 * except that the skips resulting from any continue statements
2386 * in body do not apply to the increment, but are replaced by the skips
2387 * resulting from break statements.
2389 * If "iv" is declared in the for loop, then it is killed before
2390 * and after the loop.
2392 struct pet_scop *PetScan::extract_non_affine_for(ForStmt *stmt, ValueDecl *iv,
2393 __isl_take pet_expr *init, __isl_take pet_expr *inc)
2395 int declared;
2396 int test_nr, stmt_nr;
2397 pet_expr *expr_iv;
2398 struct pet_scop *scop_init, *scop_inc, *scop, *scop_body;
2399 int type_size;
2400 struct pet_array *array;
2401 struct pet_scop *scop_kill;
2403 if (!allow_nested) {
2404 unsupported(stmt);
2405 return NULL;
2408 clear_assignment(assigned_value, iv);
2410 declared = !initialization_assignment(stmt->getInit());
2412 expr_iv = extract_access_expr(iv);
2413 expr_iv = mark_write(expr_iv);
2414 type_size = pet_expr_get_type_size(expr_iv);
2415 init = pet_expr_new_binary(type_size, pet_op_assign, expr_iv, init);
2416 scop_init = extract(init, stmt->getInit()->getSourceRange(), false);
2417 scop_init = pet_scop_prefix(scop_init, declared);
2419 test_nr = n_test++;
2420 stmt_nr = n_stmt++;
2421 scop_body = extract(stmt->getBody());
2422 if (partial) {
2423 pet_scop_free(scop_init);
2424 return scop_body;
2427 expr_iv = extract_access_expr(iv);
2428 expr_iv = mark_write(expr_iv);
2429 type_size = pet_expr_get_type_size(expr_iv);
2430 inc = pet_expr_new_binary(type_size, pet_op_add_assign, expr_iv, inc);
2431 scop_inc = extract(inc, stmt->getInc()->getSourceRange(), false);
2432 if (!scop_inc) {
2433 pet_scop_free(scop_init);
2434 pet_scop_free(scop_body);
2435 return NULL;
2438 scop = extract_while(stmt->getCond(), test_nr, stmt_nr, scop_body,
2439 scop_inc);
2441 scop = pet_scop_prefix(scop, declared + 1);
2442 scop = pet_scop_add_seq(ctx, scop_init, scop);
2444 if (!declared)
2445 return scop;
2447 array = extract_array(ctx, iv, NULL);
2448 if (array)
2449 array->declared = 1;
2450 scop_kill = kill(stmt, array);
2451 scop_kill = pet_scop_prefix(scop_kill, 0);
2452 scop = pet_scop_add_seq(ctx, scop_kill, scop);
2453 scop_kill = kill(stmt, array);
2454 scop_kill = pet_scop_add_array(scop_kill, array);
2455 scop_kill = pet_scop_prefix(scop_kill, 3);
2456 scop = pet_scop_add_seq(ctx, scop, scop_kill);
2458 return scop;
2461 /* Construct a pet_scop for a for statement.
2462 * The for loop is required to be of one of the following forms
2464 * for (i = init; condition; ++i)
2465 * for (i = init; condition; --i)
2466 * for (i = init; condition; i += constant)
2467 * for (i = init; condition; i -= constant)
2469 * The initialization of the for loop should either be an assignment
2470 * of a static affine value to an integer variable, or a declaration
2471 * of such a variable with initialization.
2473 * If the initialization or the increment do not satisfy the above
2474 * conditions, i.e., if the initialization is not static affine
2475 * or the increment is not constant, then the for loop is extracted
2476 * as a while loop instead.
2478 * The condition is allowed to contain nested accesses, provided
2479 * they are not being written to inside the body of the loop.
2480 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2481 * essentially treated as a while loop, with iteration domain
2482 * { [i] : i >= init }.
2484 * We extract a pet_scop for the body and then embed it in a loop with
2485 * iteration domain and schedule
2487 * { [i] : i >= init and condition' }
2488 * { [i] -> [i] }
2490 * or
2492 * { [i] : i <= init and condition' }
2493 * { [i] -> [-i] }
2495 * Where condition' is equal to condition if the latter is
2496 * a simple upper [lower] bound and a condition that is extended
2497 * to apply to all previous iterations otherwise.
2499 * If the condition is non-affine, then we drop the condition from the
2500 * iteration domain and instead create a separate statement
2501 * for evaluating the condition. The body is then filtered to depend
2502 * on the result of the condition evaluating to true on all iterations
2503 * up to the current iteration, while the evaluation the condition itself
2504 * is filtered to depend on the result of the condition evaluating to true
2505 * on all previous iterations.
2506 * The context of the scop representing the body is dropped
2507 * because we don't know how many times the body will be executed,
2508 * if at all.
2510 * If the stride of the loop is not 1, then "i >= init" is replaced by
2512 * (exists a: i = init + stride * a and a >= 0)
2514 * If the loop iterator i is unsigned, then wrapping may occur.
2515 * We therefore use a virtual iterator instead that does not wrap.
2516 * However, the condition in the code applies
2517 * to the wrapped value, so we need to change condition(i)
2518 * into condition([i % 2^width]). Similarly, we replace all accesses
2519 * to the original iterator by the wrapping of the virtual iterator.
2520 * Note that there may be no need to perform this final wrapping
2521 * if the loop condition (after wrapping) satisfies certain conditions.
2522 * However, the is_simple_bound condition is not enough since it doesn't
2523 * check if there even is an upper bound.
2525 * Wrapping on unsigned iterators can be avoided entirely if
2526 * loop condition is simple, the loop iterator is incremented
2527 * [decremented] by one and the last value before wrapping cannot
2528 * possibly satisfy the loop condition.
2530 * Before extracting a pet_scop from the body we remove all
2531 * assignments in assigned_value to variables that are assigned
2532 * somewhere in the body of the loop.
2534 * Valid parameters for a for loop are those for which the initial
2535 * value itself, the increment on each domain iteration and
2536 * the condition on both the initial value and
2537 * the result of incrementing the iterator for each iteration of the domain
2538 * can be evaluated.
2539 * If the loop condition is non-affine, then we only consider validity
2540 * of the initial value.
2542 * If the body contains any break, then we keep track of it in "skip"
2543 * (if the skip condition is affine) or it is handled in scop_add_break
2544 * (if the skip condition is not affine).
2545 * Note that the affine break condition needs to be considered with
2546 * respect to previous iterations in the virtual domain (if any).
2548 * If we were only able to extract part of the body, then simply
2549 * return that part.
2551 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2553 BinaryOperator *ass;
2554 Decl *decl;
2555 Stmt *init;
2556 Expr *lhs, *rhs;
2557 ValueDecl *iv;
2558 isl_local_space *ls;
2559 isl_set *domain;
2560 isl_aff *sched;
2561 isl_set *cond = NULL;
2562 isl_set *skip = NULL;
2563 isl_id *id, *id_test = NULL, *id_break_test;
2564 struct pet_scop *scop, *scop_cond = NULL;
2565 assigned_value_cache cache(assigned_value);
2566 isl_val *inc;
2567 bool is_one;
2568 bool is_unsigned;
2569 bool is_simple;
2570 bool is_virtual;
2571 bool has_affine_break;
2572 bool has_var_break;
2573 isl_aff *wrap = NULL;
2574 isl_pw_aff *pa, *pa_inc, *init_val;
2575 isl_set *valid_init;
2576 isl_set *valid_cond;
2577 isl_set *valid_cond_init;
2578 isl_set *valid_cond_next;
2579 isl_set *valid_inc;
2580 int stmt_id;
2581 pet_expr *pe_init, *pe_inc;
2582 pet_context *pc, *pc_init_val;
2584 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2585 return extract_infinite_for(stmt);
2587 init = stmt->getInit();
2588 if (!init) {
2589 unsupported(stmt);
2590 return NULL;
2592 if ((ass = initialization_assignment(init)) != NULL) {
2593 iv = extract_induction_variable(ass);
2594 if (!iv)
2595 return NULL;
2596 lhs = ass->getLHS();
2597 rhs = ass->getRHS();
2598 } else if ((decl = initialization_declaration(init)) != NULL) {
2599 VarDecl *var = extract_induction_variable(init, decl);
2600 if (!var)
2601 return NULL;
2602 iv = var;
2603 rhs = var->getInit();
2604 lhs = create_DeclRefExpr(var);
2605 } else {
2606 unsupported(stmt->getInit());
2607 return NULL;
2610 id = create_decl_id(ctx, iv);
2612 assigned_value.erase(iv);
2613 clear_assignments clear(assigned_value);
2614 clear.TraverseStmt(stmt->getBody());
2616 pe_init = extract_expr(rhs);
2617 pe_inc = extract_increment(stmt, iv);
2618 pc = convert_assignments(ctx, assigned_value);
2619 pc_init_val = pet_context_copy(pc);
2620 pc_init_val = pet_context_mark_unknown(pc_init_val, isl_id_copy(id));
2621 init_val = pet_expr_extract_affine(pe_init, pc_init_val);
2622 pet_context_free(pc_init_val);
2623 pa_inc = pet_expr_extract_affine(pe_inc, pc);
2624 pet_context_free(pc);
2625 inc = pet_extract_cst(pa_inc);
2626 if (!pe_init || !pe_inc || !inc || isl_val_is_nan(inc) ||
2627 isl_pw_aff_involves_nan(pa_inc) ||
2628 isl_pw_aff_involves_nan(init_val)) {
2629 isl_id_free(id);
2630 isl_val_free(inc);
2631 isl_pw_aff_free(pa_inc);
2632 isl_pw_aff_free(init_val);
2633 if (pe_init && pe_inc && !(pa_inc && !inc))
2634 return extract_non_affine_for(stmt, iv,
2635 pe_init, pe_inc);
2636 pet_expr_free(pe_init);
2637 pet_expr_free(pe_inc);
2638 return NULL;
2640 pet_expr_free(pe_init);
2641 pet_expr_free(pe_inc);
2643 pa = try_extract_nested_condition(stmt->getCond());
2644 if (allow_nested && (!pa || pet_nested_any_in_pw_aff(pa)))
2645 stmt_id = n_stmt++;
2647 scop = extract(stmt->getBody());
2648 if (partial) {
2649 isl_id_free(id);
2650 isl_pw_aff_free(init_val);
2651 isl_pw_aff_free(pa_inc);
2652 isl_pw_aff_free(pa);
2653 isl_val_free(inc);
2654 return scop;
2657 valid_inc = isl_pw_aff_domain(pa_inc);
2659 is_unsigned = iv->getType()->isUnsignedIntegerType();
2661 has_affine_break = scop &&
2662 pet_scop_has_affine_skip(scop, pet_skip_later);
2663 if (has_affine_break)
2664 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2665 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
2666 if (has_var_break)
2667 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
2669 if (pa && !is_nested_allowed(pa, scop)) {
2670 isl_pw_aff_free(pa);
2671 pa = NULL;
2674 if (!allow_nested && !pa)
2675 pa = try_extract_affine_condition(stmt->getCond());
2676 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2677 cond = isl_pw_aff_non_zero_set(pa);
2678 if (allow_nested && !cond) {
2679 isl_multi_pw_aff *test_index;
2680 int save_n_stmt = n_stmt;
2681 test_index = pet_create_test_index(ctx, n_test++);
2682 n_stmt = stmt_id;
2683 scop_cond = extract_non_affine_condition(stmt->getCond(),
2684 n_stmt++, isl_multi_pw_aff_copy(test_index));
2685 n_stmt = save_n_stmt;
2686 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
2687 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
2688 isl_dim_out);
2689 isl_multi_pw_aff_free(test_index);
2690 scop_cond = pet_scop_prefix(scop_cond, 0);
2691 scop = pet_scop_reset_context(scop);
2692 scop = pet_scop_prefix(scop, 1);
2693 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2696 cond = embed(cond, isl_id_copy(id));
2697 skip = embed(skip, isl_id_copy(id));
2698 valid_cond = isl_set_coalesce(valid_cond);
2699 valid_cond = embed(valid_cond, isl_id_copy(id));
2700 valid_inc = embed(valid_inc, isl_id_copy(id));
2701 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
2702 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2704 valid_cond_init = enforce_subset(
2705 isl_map_range(isl_map_from_pw_aff(isl_pw_aff_copy(init_val))),
2706 isl_set_copy(valid_cond));
2707 if (is_one && !is_virtual) {
2708 isl_pw_aff_free(init_val);
2709 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
2710 lhs, rhs, init);
2711 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2712 valid_init = set_project_out_by_id(valid_init, id);
2713 domain = isl_pw_aff_non_zero_set(pa);
2714 } else {
2715 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2716 domain = strided_domain(isl_id_copy(id), init_val,
2717 isl_val_copy(inc));
2720 domain = embed(domain, isl_id_copy(id));
2721 if (is_virtual) {
2722 isl_map *rev_wrap;
2723 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2724 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
2725 rev_wrap = isl_map_reverse(rev_wrap);
2726 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2727 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
2728 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2729 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2731 is_simple = is_simple_bound(cond, inc);
2732 if (!is_simple) {
2733 cond = isl_set_gist(cond, isl_set_copy(domain));
2734 is_simple = is_simple_bound(cond, inc);
2736 if (!is_simple)
2737 cond = valid_for_each_iteration(cond,
2738 isl_set_copy(domain), isl_val_copy(inc));
2739 domain = isl_set_intersect(domain, cond);
2740 if (has_affine_break) {
2741 skip = isl_set_intersect(skip , isl_set_copy(domain));
2742 skip = after(skip, isl_val_sgn(inc));
2743 domain = isl_set_subtract(domain, skip);
2745 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2746 ls = isl_local_space_from_space(isl_set_get_space(domain));
2747 sched = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2748 if (isl_val_is_neg(inc))
2749 sched = isl_aff_neg(sched);
2751 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
2752 isl_val_copy(inc));
2753 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2755 if (!is_virtual)
2756 wrap = identity_aff(domain);
2758 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
2759 isl_aff_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
2760 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
2761 scop = resolve_nested(scop);
2762 if (has_var_break)
2763 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
2764 isl_val_copy(inc));
2765 if (id_test) {
2766 scop = scop_add_while(scop_cond, scop, id_test, domain,
2767 isl_val_copy(inc));
2768 isl_set_free(valid_inc);
2769 } else {
2770 scop = pet_scop_restrict_context(scop, valid_inc);
2771 scop = pet_scop_restrict_context(scop, valid_cond_next);
2772 scop = pet_scop_restrict_context(scop, valid_cond_init);
2773 isl_set_free(domain);
2775 clear_assignment(assigned_value, iv);
2777 isl_val_free(inc);
2779 scop = pet_scop_restrict_context(scop, isl_set_params(valid_init));
2781 return scop;
2784 /* Try and construct a pet_scop corresponding to a compound statement.
2786 * "skip_declarations" is set if we should skip initial declarations
2787 * in the children of the compound statements. This then implies
2788 * that this sequence of children should not be treated as a block
2789 * since the initial statements may be skipped.
2791 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
2793 return extract(stmt->children(), !skip_declarations, skip_declarations);
2796 /* Extract a pet_expr from an isl_id created by pet_nested_pet_expr.
2797 * Such an isl_id has name "__pet_expr" and
2798 * the user pointer points to a pet_expr object.
2800 __isl_give pet_expr *PetScan::extract_expr(__isl_keep isl_id *id)
2802 return pet_expr_copy((pet_expr *) isl_id_get_user(id));
2805 /* For each nested access parameter in "space",
2806 * construct a corresponding pet_expr, place it in args and
2807 * record its position in "param2pos".
2808 * "n_arg" is the number of elements that are already in args.
2809 * The position recorded in "param2pos" takes this number into account.
2810 * If the pet_expr corresponding to a parameter is identical to
2811 * the pet_expr corresponding to an earlier parameter, then these two
2812 * parameters are made to refer to the same element in args.
2814 * Return the final number of elements in args or -1 if an error has occurred.
2816 int PetScan::extract_nested(__isl_keep isl_space *space,
2817 int n_arg, pet_expr **args, std::map<int,int> &param2pos)
2819 int nparam;
2821 nparam = isl_space_dim(space, isl_dim_param);
2822 for (int i = 0; i < nparam; ++i) {
2823 int j;
2824 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2826 if (!pet_nested_in_id(id)) {
2827 isl_id_free(id);
2828 continue;
2831 args[n_arg] = extract_expr(id);
2832 isl_id_free(id);
2833 if (!args[n_arg])
2834 return -1;
2836 for (j = 0; j < n_arg; ++j)
2837 if (pet_expr_is_equal(args[j], args[n_arg]))
2838 break;
2840 if (j < n_arg) {
2841 pet_expr_free(args[n_arg]);
2842 args[n_arg] = NULL;
2843 param2pos[i] = j;
2844 } else
2845 param2pos[i] = n_arg++;
2848 return n_arg;
2851 /* For each nested access parameter in the access relations in "expr",
2852 * construct a corresponding pet_expr, place it in the arguments of "expr"
2853 * and record its position in "param2pos".
2854 * n is the number of nested access parameters.
2856 __isl_give pet_expr *PetScan::extract_nested(__isl_take pet_expr *expr, int n,
2857 std::map<int,int> &param2pos)
2859 isl_space *space;
2860 int i;
2861 pet_expr **args;
2863 args = isl_calloc_array(ctx, pet_expr *, n);
2864 if (!args)
2865 return pet_expr_free(expr);
2867 space = pet_expr_access_get_parameter_space(expr);
2868 n = extract_nested(space, 0, args, param2pos);
2869 isl_space_free(space);
2871 if (n < 0)
2872 expr = pet_expr_free(expr);
2873 else
2874 expr = pet_expr_set_n_arg(expr, n);
2876 for (i = 0; i < n; ++i)
2877 expr = pet_expr_set_arg(expr, i, args[i]);
2878 free(args);
2880 return expr;
2883 /* Look for parameters in any access relation in "expr" that
2884 * refer to nested accesses. In particular, these are
2885 * parameters with name "__pet_expr".
2887 * If there are any such parameters, then the domain of the index
2888 * expression and the access relation, which is still [] at this point,
2889 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
2890 * (after identifying identical nested accesses).
2892 * This transformation is performed in several steps.
2893 * We first extract the arguments in extract_nested.
2894 * param2pos maps the original parameter position to the position
2895 * of the argument.
2896 * Then we move these parameters to input dimensions.
2897 * t2pos maps the positions of these temporary input dimensions
2898 * to the positions of the corresponding arguments.
2899 * Finally, we express these temporary dimensions in terms of the domain
2900 * [[] -> [t_1,...,t_n]] and precompose index expression and access
2901 * relations with this function.
2903 __isl_give pet_expr *PetScan::resolve_nested(__isl_take pet_expr *expr)
2905 int n;
2906 int nparam;
2907 isl_space *space;
2908 isl_local_space *ls;
2909 isl_aff *aff;
2910 isl_multi_aff *ma;
2911 std::map<int,int> param2pos;
2912 std::map<int,int> t2pos;
2914 if (!expr)
2915 return expr;
2917 n = pet_expr_get_n_arg(expr);
2918 for (int i = 0; i < n; ++i) {
2919 pet_expr *arg;
2920 arg = pet_expr_get_arg(expr, i);
2921 arg = resolve_nested(arg);
2922 expr = pet_expr_set_arg(expr, i, arg);
2925 if (pet_expr_get_type(expr) != pet_expr_access)
2926 return expr;
2928 space = pet_expr_access_get_parameter_space(expr);
2929 n = pet_nested_n_in_space(space);
2930 isl_space_free(space);
2931 if (n == 0)
2932 return expr;
2934 expr = extract_nested(expr, n, param2pos);
2935 if (!expr)
2936 return NULL;
2938 expr = pet_expr_access_align_params(expr);
2939 if (!expr)
2940 return NULL;
2942 n = 0;
2943 space = pet_expr_access_get_parameter_space(expr);
2944 nparam = isl_space_dim(space, isl_dim_param);
2945 for (int i = nparam - 1; i >= 0; --i) {
2946 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2947 if (!pet_nested_in_id(id)) {
2948 isl_id_free(id);
2949 continue;
2952 expr = pet_expr_access_move_dims(expr,
2953 isl_dim_in, n, isl_dim_param, i, 1);
2954 t2pos[n] = param2pos[i];
2955 n++;
2957 isl_id_free(id);
2959 isl_space_free(space);
2961 space = pet_expr_access_get_parameter_space(expr);
2962 space = isl_space_set_from_params(space);
2963 space = isl_space_add_dims(space, isl_dim_set,
2964 pet_expr_get_n_arg(expr));
2965 space = isl_space_wrap(isl_space_from_range(space));
2966 ls = isl_local_space_from_space(isl_space_copy(space));
2967 space = isl_space_from_domain(space);
2968 space = isl_space_add_dims(space, isl_dim_out, n);
2969 ma = isl_multi_aff_zero(space);
2971 for (int i = 0; i < n; ++i) {
2972 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2973 isl_dim_set, t2pos[i]);
2974 ma = isl_multi_aff_set_aff(ma, i, aff);
2976 isl_local_space_free(ls);
2978 expr = pet_expr_access_pullback_multi_aff(expr, ma);
2980 return expr;
2983 /* Return the file offset of the expansion location of "Loc".
2985 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
2987 return SM.getFileOffset(SM.getExpansionLoc(Loc));
2990 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
2992 /* Return a SourceLocation for the location after the first semicolon
2993 * after "loc". If Lexer::findLocationAfterToken is available, we simply
2994 * call it and also skip trailing spaces and newline.
2996 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
2997 const LangOptions &LO)
2999 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3002 #else
3004 /* Return a SourceLocation for the location after the first semicolon
3005 * after "loc". If Lexer::findLocationAfterToken is not available,
3006 * we look in the underlying character data for the first semicolon.
3008 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3009 const LangOptions &LO)
3011 const char *semi;
3012 const char *s = SM.getCharacterData(loc);
3014 semi = strchr(s, ';');
3015 if (!semi)
3016 return SourceLocation();
3017 return loc.getFileLocWithOffset(semi + 1 - s);
3020 #endif
3022 /* If the token at "loc" is the first token on the line, then return
3023 * a location referring to the start of the line.
3024 * Otherwise, return "loc".
3026 * This function is used to extend a scop to the start of the line
3027 * if the first token of the scop is also the first token on the line.
3029 * We look for the first token on the line. If its location is equal to "loc",
3030 * then the latter is the location of the first token on the line.
3032 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3033 SourceManager &SM, const LangOptions &LO)
3035 std::pair<FileID, unsigned> file_offset_pair;
3036 llvm::StringRef file;
3037 const char *pos;
3038 Token tok;
3039 SourceLocation token_loc, line_loc;
3040 int col;
3042 loc = SM.getExpansionLoc(loc);
3043 col = SM.getExpansionColumnNumber(loc);
3044 line_loc = loc.getLocWithOffset(1 - col);
3045 file_offset_pair = SM.getDecomposedLoc(line_loc);
3046 file = SM.getBufferData(file_offset_pair.first, NULL);
3047 pos = file.data() + file_offset_pair.second;
3049 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3050 file.begin(), pos, file.end());
3051 lexer.LexFromRawLexer(tok);
3052 token_loc = tok.getLocation();
3054 if (token_loc == loc)
3055 return line_loc;
3056 else
3057 return loc;
3060 /* Update start and end of "scop" to include the region covered by "range".
3061 * If "skip_semi" is set, then we assume "range" is followed by
3062 * a semicolon and also include this semicolon.
3064 struct pet_scop *PetScan::update_scop_start_end(struct pet_scop *scop,
3065 SourceRange range, bool skip_semi)
3067 SourceLocation loc = range.getBegin();
3068 SourceManager &SM = PP.getSourceManager();
3069 const LangOptions &LO = PP.getLangOpts();
3070 unsigned start, end;
3072 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3073 start = getExpansionOffset(SM, loc);
3074 loc = range.getEnd();
3075 if (skip_semi)
3076 loc = location_after_semi(loc, SM, LO);
3077 else
3078 loc = PP.getLocForEndOfToken(loc);
3079 end = getExpansionOffset(SM, loc);
3081 scop = pet_scop_update_start_end(scop, start, end);
3082 return scop;
3085 /* Convert a top-level pet_expr to a pet_scop with one statement.
3086 * This mainly involves resolving nested expression parameters
3087 * and setting the name of the iteration space.
3088 * The name is given by "label" if it is non-NULL. Otherwise,
3089 * it is of the form S_<n_stmt>.
3090 * start and end of the pet_scop are derived from "range" and "skip_semi".
3091 * In particular, if "skip_semi" is set then the semicolon following "range"
3092 * is also included.
3094 struct pet_scop *PetScan::extract(__isl_take pet_expr *expr, SourceRange range,
3095 bool skip_semi, __isl_take isl_id *label)
3097 struct pet_stmt *ps;
3098 struct pet_scop *scop;
3099 SourceLocation loc = range.getBegin();
3100 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3102 expr = resolve_nested(expr);
3103 ps = pet_stmt_from_pet_expr(line, label, n_stmt++, expr);
3104 scop = pet_scop_from_pet_stmt(ctx, ps);
3106 scop = update_scop_start_end(scop, range, skip_semi);
3107 return scop;
3110 /* Check if we can extract an affine expression from "expr".
3111 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3112 * We turn on autodetection so that we won't generate any warnings
3113 * and turn off nesting, so that we won't accept any non-affine constructs.
3115 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3117 isl_pw_aff *pwaff;
3118 int save_autodetect = options->autodetect;
3119 bool save_nesting = nesting_enabled;
3121 options->autodetect = 1;
3122 nesting_enabled = false;
3124 pwaff = extract_affine(expr);
3126 options->autodetect = save_autodetect;
3127 nesting_enabled = save_nesting;
3129 return pwaff;
3132 /* Check if we can extract an affine constraint from "expr".
3133 * Return the constraint as an isl_set if we can and NULL otherwise.
3134 * We turn on autodetection so that we won't generate any warnings
3135 * and turn off nesting, so that we won't accept any non-affine constructs.
3137 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3139 isl_pw_aff *cond;
3140 int save_autodetect = options->autodetect;
3141 bool save_nesting = nesting_enabled;
3143 options->autodetect = 1;
3144 nesting_enabled = false;
3146 cond = extract_condition(expr);
3148 options->autodetect = save_autodetect;
3149 nesting_enabled = save_nesting;
3151 return cond;
3154 /* Check whether "expr" is an affine constraint.
3156 bool PetScan::is_affine_condition(Expr *expr)
3158 isl_pw_aff *cond;
3160 cond = try_extract_affine_condition(expr);
3161 isl_pw_aff_free(cond);
3163 return cond != NULL;
3166 /* Check if we can extract a condition from "expr".
3167 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3168 * If allow_nested is set, then the condition may involve parameters
3169 * corresponding to nested accesses.
3170 * We turn on autodetection so that we won't generate any warnings.
3172 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3174 isl_pw_aff *cond;
3175 int save_autodetect = options->autodetect;
3176 bool save_nesting = nesting_enabled;
3178 options->autodetect = 1;
3179 nesting_enabled = allow_nested;
3180 cond = extract_condition(expr);
3182 options->autodetect = save_autodetect;
3183 nesting_enabled = save_nesting;
3185 return cond;
3188 /* If the top-level expression of "stmt" is an assignment, then
3189 * return that assignment as a BinaryOperator.
3190 * Otherwise return NULL.
3192 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3194 BinaryOperator *ass;
3196 if (!stmt)
3197 return NULL;
3198 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3199 return NULL;
3201 ass = cast<BinaryOperator>(stmt);
3202 if(ass->getOpcode() != BO_Assign)
3203 return NULL;
3205 return ass;
3208 /* Check if the given if statement is a conditional assignement
3209 * with a non-affine condition. If so, construct a pet_scop
3210 * corresponding to this conditional assignment. Otherwise return NULL.
3212 * In particular we check if "stmt" is of the form
3214 * if (condition)
3215 * a = f(...);
3216 * else
3217 * a = g(...);
3219 * where a is some array or scalar access.
3220 * The constructed pet_scop then corresponds to the expression
3222 * a = condition ? f(...) : g(...)
3224 * All access relations in f(...) are intersected with condition
3225 * while all access relation in g(...) are intersected with the complement.
3227 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3229 BinaryOperator *ass_then, *ass_else;
3230 isl_multi_pw_aff *write_then, *write_else;
3231 isl_set *cond, *comp;
3232 isl_multi_pw_aff *index;
3233 isl_pw_aff *pa;
3234 int equal;
3235 int type_size;
3236 pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3237 bool save_nesting = nesting_enabled;
3239 if (!options->detect_conditional_assignment)
3240 return NULL;
3242 ass_then = top_assignment_or_null(stmt->getThen());
3243 ass_else = top_assignment_or_null(stmt->getElse());
3245 if (!ass_then || !ass_else)
3246 return NULL;
3248 if (is_affine_condition(stmt->getCond()))
3249 return NULL;
3251 write_then = extract_index(ass_then->getLHS());
3252 write_else = extract_index(ass_else->getLHS());
3254 equal = isl_multi_pw_aff_plain_is_equal(write_then, write_else);
3255 isl_multi_pw_aff_free(write_else);
3256 if (equal < 0 || !equal) {
3257 isl_multi_pw_aff_free(write_then);
3258 return NULL;
3261 nesting_enabled = allow_nested;
3262 pa = extract_condition(stmt->getCond());
3263 nesting_enabled = save_nesting;
3264 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3265 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3266 index = isl_multi_pw_aff_from_pw_aff(pa);
3268 pe_cond = pet_expr_from_index(index);
3270 pe_then = extract_expr(ass_then->getRHS());
3271 pe_then = pet_expr_restrict(pe_then, cond);
3272 pe_else = extract_expr(ass_else->getRHS());
3273 pe_else = pet_expr_restrict(pe_else, comp);
3275 pe = pet_expr_new_ternary(pe_cond, pe_then, pe_else);
3276 type_size = get_type_size(ass_then->getType(), ast_context);
3277 pe_write = pet_expr_from_index_and_depth(type_size, write_then,
3278 extract_depth(write_then));
3279 pe_write = pet_expr_access_set_write(pe_write, 1);
3280 pe_write = pet_expr_access_set_read(pe_write, 0);
3281 pe = pet_expr_new_binary(type_size, pet_op_assign, pe_write, pe);
3282 return extract(pe, stmt->getSourceRange(), false);
3285 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3286 * evaluating "cond" and writing the result to a virtual scalar,
3287 * as expressed by "index".
3289 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond, int stmt_nr,
3290 __isl_take isl_multi_pw_aff *index)
3292 pet_expr *expr, *write;
3293 struct pet_stmt *ps;
3294 SourceLocation loc = cond->getLocStart();
3295 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3297 write = pet_expr_from_index(index);
3298 write = pet_expr_access_set_write(write, 1);
3299 write = pet_expr_access_set_read(write, 0);
3300 expr = extract_expr(cond);
3301 expr = resolve_nested(expr);
3302 expr = pet_expr_new_binary(1, pet_op_assign, write, expr);
3303 ps = pet_stmt_from_pet_expr(line, NULL, stmt_nr, expr);
3304 return pet_scop_from_pet_stmt(ctx, ps);
3307 extern "C" {
3308 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr,
3309 void *user);
3312 /* Precompose the access relation and the index expression associated
3313 * to "expr" with the function pointed to by "user",
3314 * thereby embedding the access relation in the domain of this function.
3315 * The initial domain of the access relation and the index expression
3316 * is the zero-dimensional domain.
3318 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr, void *user)
3320 isl_multi_aff *ma = (isl_multi_aff *) user;
3322 return pet_expr_access_pullback_multi_aff(expr, isl_multi_aff_copy(ma));
3325 /* Precompose all access relations in "expr" with "ma", thereby
3326 * embedding them in the domain of "ma".
3328 static __isl_give pet_expr *embed(__isl_take pet_expr *expr,
3329 __isl_keep isl_multi_aff *ma)
3331 return pet_expr_map_access(expr, &embed_access, ma);
3334 /* For each nested access parameter in the domain of "stmt",
3335 * construct a corresponding pet_expr, place it before the original
3336 * elements in stmt->args and record its position in "param2pos".
3337 * n is the number of nested access parameters.
3339 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3340 std::map<int,int> &param2pos)
3342 int i;
3343 isl_space *space;
3344 int n_arg;
3345 pet_expr **args;
3347 n_arg = stmt->n_arg;
3348 args = isl_calloc_array(ctx, pet_expr *, n + n_arg);
3349 if (!args)
3350 goto error;
3352 space = isl_set_get_space(stmt->domain);
3353 n_arg = extract_nested(space, 0, args, param2pos);
3354 isl_space_free(space);
3356 if (n_arg < 0)
3357 goto error;
3359 for (i = 0; i < stmt->n_arg; ++i)
3360 args[n_arg + i] = stmt->args[i];
3361 free(stmt->args);
3362 stmt->args = args;
3363 stmt->n_arg += n_arg;
3365 return stmt;
3366 error:
3367 if (args) {
3368 for (i = 0; i < n; ++i)
3369 pet_expr_free(args[i]);
3370 free(args);
3372 pet_stmt_free(stmt);
3373 return NULL;
3376 /* Check whether any of the arguments i of "stmt" starting at position "n"
3377 * is equal to one of the first "n" arguments j.
3378 * If so, combine the constraints on arguments i and j and remove
3379 * argument i.
3381 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3383 int i, j;
3384 isl_map *map;
3386 if (!stmt)
3387 return NULL;
3388 if (n == 0)
3389 return stmt;
3390 if (n == stmt->n_arg)
3391 return stmt;
3393 map = isl_set_unwrap(stmt->domain);
3395 for (i = stmt->n_arg - 1; i >= n; --i) {
3396 for (j = 0; j < n; ++j)
3397 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3398 break;
3399 if (j >= n)
3400 continue;
3402 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3403 map = isl_map_project_out(map, isl_dim_out, i, 1);
3405 pet_expr_free(stmt->args[i]);
3406 for (j = i; j + 1 < stmt->n_arg; ++j)
3407 stmt->args[j] = stmt->args[j + 1];
3408 stmt->n_arg--;
3411 stmt->domain = isl_map_wrap(map);
3412 if (!stmt->domain)
3413 goto error;
3414 return stmt;
3415 error:
3416 pet_stmt_free(stmt);
3417 return NULL;
3420 /* Look for parameters in the iteration domain of "stmt" that
3421 * refer to nested accesses. In particular, these are
3422 * parameters with name "__pet_expr".
3424 * If there are any such parameters, then as many extra variables
3425 * (after identifying identical nested accesses) are inserted in the
3426 * range of the map wrapped inside the domain, before the original variables.
3427 * If the original domain is not a wrapped map, then a new wrapped
3428 * map is created with zero output dimensions.
3429 * The parameters are then equated to the corresponding output dimensions
3430 * and subsequently projected out, from the iteration domain,
3431 * the schedule and the access relations.
3432 * For each of the output dimensions, a corresponding argument
3433 * expression is inserted. Initially they are created with
3434 * a zero-dimensional domain, so they have to be embedded
3435 * in the current iteration domain.
3436 * param2pos maps the position of the parameter to the position
3437 * of the corresponding output dimension in the wrapped map.
3439 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3441 int n;
3442 int nparam;
3443 unsigned n_arg;
3444 isl_map *map;
3445 isl_space *space;
3446 isl_multi_aff *ma;
3447 std::map<int,int> param2pos;
3449 if (!stmt)
3450 return NULL;
3452 n = pet_nested_n_in_set(stmt->domain);
3453 if (n == 0)
3454 return stmt;
3456 n_arg = stmt->n_arg;
3457 stmt = extract_nested(stmt, n, param2pos);
3458 if (!stmt)
3459 return NULL;
3461 n = stmt->n_arg - n_arg;
3462 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3463 if (isl_set_is_wrapping(stmt->domain))
3464 map = isl_set_unwrap(stmt->domain);
3465 else
3466 map = isl_map_from_domain(stmt->domain);
3467 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3469 for (int i = nparam - 1; i >= 0; --i) {
3470 isl_id *id;
3472 if (!pet_nested_in_map(map, i))
3473 continue;
3475 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
3476 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3477 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3478 param2pos[i]);
3479 map = isl_map_project_out(map, isl_dim_param, i, 1);
3482 stmt->domain = isl_map_wrap(map);
3484 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
3485 space = isl_space_from_domain(isl_space_domain(space));
3486 ma = isl_multi_aff_zero(space);
3487 for (int pos = 0; pos < n; ++pos)
3488 stmt->args[pos] = embed(stmt->args[pos], ma);
3489 isl_multi_aff_free(ma);
3491 stmt = pet_stmt_remove_nested_parameters(stmt);
3492 stmt = remove_duplicate_arguments(stmt, n);
3494 return stmt;
3497 /* For each statement in "scop", move the parameters that correspond
3498 * to nested access into the ranges of the domains and create
3499 * corresponding argument expressions.
3501 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3503 if (!scop)
3504 return NULL;
3506 for (int i = 0; i < scop->n_stmt; ++i) {
3507 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3508 if (!scop->stmts[i])
3509 goto error;
3512 return scop;
3513 error:
3514 pet_scop_free(scop);
3515 return NULL;
3518 /* Given an access expression "expr", is the variable accessed by
3519 * "expr" assigned anywhere inside "scop"?
3521 static bool is_assigned(__isl_keep pet_expr *expr, pet_scop *scop)
3523 bool assigned = false;
3524 isl_id *id;
3526 id = pet_expr_access_get_id(expr);
3527 assigned = pet_scop_writes(scop, id);
3528 isl_id_free(id);
3530 return assigned;
3533 /* Are all nested access parameters in "pa" allowed given "scop".
3534 * In particular, is none of them written by anywhere inside "scop".
3536 * If "scop" has any skip conditions, then no nested access parameters
3537 * are allowed. In particular, if there is any nested access in a guard
3538 * for a piece of code containing a "continue", then we want to introduce
3539 * a separate statement for evaluating this guard so that we can express
3540 * that the result is false for all previous iterations.
3542 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3544 int nparam;
3546 if (!scop)
3547 return true;
3549 if (!pet_nested_any_in_pw_aff(pa))
3550 return true;
3552 if (pet_scop_has_skip(scop, pet_skip_now))
3553 return false;
3555 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3556 for (int i = 0; i < nparam; ++i) {
3557 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3558 pet_expr *expr;
3559 bool allowed;
3561 if (!pet_nested_in_id(id)) {
3562 isl_id_free(id);
3563 continue;
3566 expr = extract_expr(id);
3567 allowed = pet_expr_get_type(expr) == pet_expr_access &&
3568 !is_assigned(expr, scop);
3570 pet_expr_free(expr);
3571 isl_id_free(id);
3573 if (!allowed)
3574 return false;
3577 return true;
3580 /* Construct a pet_scop for a non-affine if statement.
3582 * We create a separate statement that writes the result
3583 * of the non-affine condition to a virtual scalar.
3584 * A constraint requiring the value of this virtual scalar to be one
3585 * is added to the iteration domains of the then branch.
3586 * Similarly, a constraint requiring the value of this virtual scalar
3587 * to be zero is added to the iteration domains of the else branch, if any.
3588 * We adjust the schedules to ensure that the virtual scalar is written
3589 * before it is read.
3591 * If there are any breaks or continues in the then and/or else
3592 * branches, then we may have to compute a new skip condition.
3593 * This is handled using a pet_skip_info object.
3594 * On initialization, the object checks if skip conditions need
3595 * to be computed. If so, it does so in pet_skip_info_if_extract_index and
3596 * adds them in pet_skip_info_if_add.
3598 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
3599 struct pet_scop *scop_then, struct pet_scop *scop_else,
3600 bool have_else, int stmt_id)
3602 struct pet_scop *scop;
3603 isl_multi_pw_aff *test_index;
3604 int int_size;
3605 int save_n_stmt = n_stmt;
3607 test_index = pet_create_test_index(ctx, n_test++);
3608 n_stmt = stmt_id;
3609 scop = extract_non_affine_condition(cond, n_stmt++,
3610 isl_multi_pw_aff_copy(test_index));
3611 n_stmt = save_n_stmt;
3612 scop = scop_add_array(scop, test_index, ast_context);
3614 pet_skip_info skip;
3615 pet_skip_info_if_init(&skip, ctx, scop_then, scop_else, have_else, 0);
3616 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
3617 pet_skip_info_if_extract_index(&skip, test_index, int_size,
3618 &n_stmt, &n_test);
3620 scop = pet_scop_prefix(scop, 0);
3621 scop_then = pet_scop_prefix(scop_then, 1);
3622 scop_then = pet_scop_filter(scop_then,
3623 isl_multi_pw_aff_copy(test_index), 1);
3624 if (have_else) {
3625 scop_else = pet_scop_prefix(scop_else, 1);
3626 scop_else = pet_scop_filter(scop_else, test_index, 0);
3627 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
3628 } else
3629 isl_multi_pw_aff_free(test_index);
3631 scop = pet_scop_add_seq(ctx, scop, scop_then);
3633 scop = pet_skip_info_if_add(&skip, scop, 2);
3635 return scop;
3638 /* Construct a pet_scop for an if statement.
3640 * If the condition fits the pattern of a conditional assignment,
3641 * then it is handled by extract_conditional_assignment.
3642 * Otherwise, we do the following.
3644 * If the condition is affine, then the condition is added
3645 * to the iteration domains of the then branch, while the
3646 * opposite of the condition in added to the iteration domains
3647 * of the else branch, if any.
3648 * We allow the condition to be dynamic, i.e., to refer to
3649 * scalars or array elements that may be written to outside
3650 * of the given if statement. These nested accesses are then represented
3651 * as output dimensions in the wrapping iteration domain.
3652 * If it is also written _inside_ the then or else branch, then
3653 * we treat the condition as non-affine.
3654 * As explained in extract_non_affine_if, this will introduce
3655 * an extra statement.
3656 * For aesthetic reasons, we want this statement to have a statement
3657 * number that is lower than those of the then and else branches.
3658 * In order to evaluate if we will need such a statement, however, we
3659 * first construct scops for the then and else branches.
3660 * We therefore reserve a statement number if we might have to
3661 * introduce such an extra statement.
3663 * If the condition is not affine, then the scop is created in
3664 * extract_non_affine_if.
3666 * If there are any breaks or continues in the then and/or else
3667 * branches, then we may have to compute a new skip condition.
3668 * This is handled using a pet_skip_info object.
3669 * On initialization, the object checks if skip conditions need
3670 * to be computed. If so, it does so in pet_skip_info_if_extract_cond and
3671 * adds them in pet_skip_info_if_add.
3673 struct pet_scop *PetScan::extract(IfStmt *stmt)
3675 struct pet_scop *scop_then, *scop_else = NULL, *scop;
3676 isl_pw_aff *cond;
3677 int stmt_id;
3678 int int_size;
3679 isl_set *set;
3680 isl_set *valid;
3682 clear_assignments clear(assigned_value);
3683 clear.TraverseStmt(stmt->getThen());
3684 if (stmt->getElse())
3685 clear.TraverseStmt(stmt->getElse());
3687 scop = extract_conditional_assignment(stmt);
3688 if (scop)
3689 return scop;
3691 cond = try_extract_nested_condition(stmt->getCond());
3692 if (allow_nested && (!cond || pet_nested_any_in_pw_aff(cond)))
3693 stmt_id = n_stmt++;
3696 assigned_value_cache cache(assigned_value);
3697 scop_then = extract(stmt->getThen());
3700 if (stmt->getElse()) {
3701 assigned_value_cache cache(assigned_value);
3702 scop_else = extract(stmt->getElse());
3703 if (options->autodetect) {
3704 if (scop_then && !scop_else) {
3705 partial = true;
3706 isl_pw_aff_free(cond);
3707 return scop_then;
3709 if (!scop_then && scop_else) {
3710 partial = true;
3711 isl_pw_aff_free(cond);
3712 return scop_else;
3717 if (cond &&
3718 (!is_nested_allowed(cond, scop_then) ||
3719 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
3720 isl_pw_aff_free(cond);
3721 cond = NULL;
3723 if (allow_nested && !cond)
3724 return extract_non_affine_if(stmt->getCond(), scop_then,
3725 scop_else, stmt->getElse(), stmt_id);
3727 if (!cond)
3728 cond = extract_condition(stmt->getCond());
3730 pet_skip_info skip;
3731 pet_skip_info_if_init(&skip, ctx, scop_then, scop_else,
3732 stmt->getElse() != NULL, 1);
3733 pet_skip_info_if_extract_cond(&skip, cond, int_size, &n_stmt, &n_test);
3735 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
3736 set = isl_pw_aff_non_zero_set(cond);
3737 scop = pet_scop_restrict(scop_then, isl_set_params(isl_set_copy(set)));
3739 if (stmt->getElse()) {
3740 set = isl_set_subtract(isl_set_copy(valid), set);
3741 scop_else = pet_scop_restrict(scop_else, isl_set_params(set));
3742 scop = pet_scop_add_par(ctx, scop, scop_else);
3743 } else
3744 isl_set_free(set);
3745 scop = resolve_nested(scop);
3746 scop = pet_scop_restrict_context(scop, isl_set_params(valid));
3748 if (pet_skip_info_has_skip(&skip))
3749 scop = pet_scop_prefix(scop, 0);
3750 scop = pet_skip_info_if_add(&skip, scop, 1);
3752 return scop;
3755 /* Try and construct a pet_scop for a label statement.
3756 * We currently only allow labels on expression statements.
3758 struct pet_scop *PetScan::extract(LabelStmt *stmt)
3760 isl_id *label;
3761 Stmt *sub;
3763 sub = stmt->getSubStmt();
3764 if (!isa<Expr>(sub)) {
3765 unsupported(stmt);
3766 return NULL;
3769 label = isl_id_alloc(ctx, stmt->getName(), NULL);
3771 return extract(extract_expr(cast<Expr>(sub)), stmt->getSourceRange(),
3772 true, label);
3775 /* Return a one-dimensional multi piecewise affine expression that is equal
3776 * to the constant 1 and is defined over a zero-dimensional domain.
3778 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
3780 isl_space *space;
3781 isl_local_space *ls;
3782 isl_aff *aff;
3784 space = isl_space_set_alloc(ctx, 0, 0);
3785 ls = isl_local_space_from_space(space);
3786 aff = isl_aff_zero_on_domain(ls);
3787 aff = isl_aff_set_constant_si(aff, 1);
3789 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
3792 /* Construct a pet_scop for a continue statement.
3794 * We simply create an empty scop with a universal pet_skip_now
3795 * skip condition. This skip condition will then be taken into
3796 * account by the enclosing loop construct, possibly after
3797 * being incorporated into outer skip conditions.
3799 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
3801 pet_scop *scop;
3803 scop = pet_scop_empty(ctx);
3804 if (!scop)
3805 return NULL;
3807 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
3809 return scop;
3812 /* Construct a pet_scop for a break statement.
3814 * We simply create an empty scop with both a universal pet_skip_now
3815 * skip condition and a universal pet_skip_later skip condition.
3816 * These skip conditions will then be taken into
3817 * account by the enclosing loop construct, possibly after
3818 * being incorporated into outer skip conditions.
3820 struct pet_scop *PetScan::extract(BreakStmt *stmt)
3822 pet_scop *scop;
3823 isl_multi_pw_aff *skip;
3825 scop = pet_scop_empty(ctx);
3826 if (!scop)
3827 return NULL;
3829 skip = one_mpa(ctx);
3830 scop = pet_scop_set_skip(scop, pet_skip_now,
3831 isl_multi_pw_aff_copy(skip));
3832 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
3834 return scop;
3837 /* Try and construct a pet_scop corresponding to "stmt".
3839 * If "stmt" is a compound statement, then "skip_declarations"
3840 * indicates whether we should skip initial declarations in the
3841 * compound statement.
3843 * If the constructed pet_scop is not a (possibly) partial representation
3844 * of "stmt", we update start and end of the pet_scop to those of "stmt".
3845 * In particular, if skip_declarations is set, then we may have skipped
3846 * declarations inside "stmt" and so the pet_scop may not represent
3847 * the entire "stmt".
3848 * Note that this function may be called with "stmt" referring to the entire
3849 * body of the function, including the outer braces. In such cases,
3850 * skip_declarations will be set and the braces will not be taken into
3851 * account in scop->start and scop->end.
3853 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
3855 struct pet_scop *scop;
3857 if (isa<Expr>(stmt))
3858 return extract(extract_expr(cast<Expr>(stmt)),
3859 stmt->getSourceRange(), true);
3861 switch (stmt->getStmtClass()) {
3862 case Stmt::WhileStmtClass:
3863 scop = extract(cast<WhileStmt>(stmt));
3864 break;
3865 case Stmt::ForStmtClass:
3866 scop = extract_for(cast<ForStmt>(stmt));
3867 break;
3868 case Stmt::IfStmtClass:
3869 scop = extract(cast<IfStmt>(stmt));
3870 break;
3871 case Stmt::CompoundStmtClass:
3872 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
3873 break;
3874 case Stmt::LabelStmtClass:
3875 scop = extract(cast<LabelStmt>(stmt));
3876 break;
3877 case Stmt::ContinueStmtClass:
3878 scop = extract(cast<ContinueStmt>(stmt));
3879 break;
3880 case Stmt::BreakStmtClass:
3881 scop = extract(cast<BreakStmt>(stmt));
3882 break;
3883 case Stmt::DeclStmtClass:
3884 scop = extract(cast<DeclStmt>(stmt));
3885 break;
3886 default:
3887 unsupported(stmt);
3888 return NULL;
3891 if (partial || skip_declarations)
3892 return scop;
3894 scop = update_scop_start_end(scop, stmt->getSourceRange(), false);
3896 return scop;
3899 /* Extract a clone of the kill statement in "scop".
3900 * "scop" is expected to have been created from a DeclStmt
3901 * and should have the kill as its first statement.
3903 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
3905 pet_expr *kill;
3906 struct pet_stmt *stmt;
3907 isl_multi_pw_aff *index;
3908 isl_map *access;
3909 pet_expr *arg;
3911 if (!scop)
3912 return NULL;
3913 if (scop->n_stmt < 1)
3914 isl_die(ctx, isl_error_internal,
3915 "expecting at least one statement", return NULL);
3916 stmt = scop->stmts[0];
3917 if (!pet_stmt_is_kill(stmt))
3918 isl_die(ctx, isl_error_internal,
3919 "expecting kill statement", return NULL);
3921 arg = pet_expr_get_arg(stmt->body, 0);
3922 index = pet_expr_access_get_index(arg);
3923 access = pet_expr_access_get_access(arg);
3924 pet_expr_free(arg);
3925 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
3926 access = isl_map_reset_tuple_id(access, isl_dim_in);
3927 kill = pet_expr_kill_from_access_and_index(access, index);
3928 return pet_stmt_from_pet_expr(stmt->line, NULL, n_stmt++, kill);
3931 /* Mark all arrays in "scop" as being exposed.
3933 static struct pet_scop *mark_exposed(struct pet_scop *scop)
3935 if (!scop)
3936 return NULL;
3937 for (int i = 0; i < scop->n_array; ++i)
3938 scop->arrays[i]->exposed = 1;
3939 return scop;
3942 /* Try and construct a pet_scop corresponding to (part of)
3943 * a sequence of statements.
3945 * "block" is set if the sequence respresents the children of
3946 * a compound statement.
3947 * "skip_declarations" is set if we should skip initial declarations
3948 * in the sequence of statements.
3950 * If there are any breaks or continues in the individual statements,
3951 * then we may have to compute a new skip condition.
3952 * This is handled using a pet_skip_info object.
3953 * On initialization, the object checks if skip conditions need
3954 * to be computed. If so, it does so in pet_skip_info_seq_extract and
3955 * adds them in pet_skip_info_seq_add.
3957 * If "block" is set, then we need to insert kill statements at
3958 * the end of the block for any array that has been declared by
3959 * one of the statements in the sequence. Each of these declarations
3960 * results in the construction of a kill statement at the place
3961 * of the declaration, so we simply collect duplicates of
3962 * those kill statements and append these duplicates to the constructed scop.
3964 * If "block" is not set, then any array declared by one of the statements
3965 * in the sequence is marked as being exposed.
3967 * If autodetect is set, then we allow the extraction of only a subrange
3968 * of the sequence of statements. However, if there is at least one statement
3969 * for which we could not construct a scop and the final range contains
3970 * either no statements or at least one kill, then we discard the entire
3971 * range.
3973 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
3974 bool skip_declarations)
3976 pet_scop *scop;
3977 StmtIterator i;
3978 int int_size;
3979 int j;
3980 bool partial_range = false;
3981 set<struct pet_stmt *> kills;
3982 set<struct pet_stmt *>::iterator it;
3984 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
3986 scop = pet_scop_empty(ctx);
3987 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
3988 Stmt *child = *i;
3989 struct pet_scop *scop_i;
3991 if (scop->n_stmt == 0 && skip_declarations &&
3992 child->getStmtClass() == Stmt::DeclStmtClass)
3993 continue;
3995 scop_i = extract(child);
3996 if (scop->n_stmt != 0 && partial) {
3997 pet_scop_free(scop_i);
3998 break;
4000 pet_skip_info skip;
4001 pet_skip_info_seq_init(&skip, ctx, scop, scop_i);
4002 pet_skip_info_seq_extract(&skip, int_size, &n_stmt, &n_test);
4003 if (pet_skip_info_has_skip(&skip))
4004 scop_i = pet_scop_prefix(scop_i, 0);
4005 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4006 if (block)
4007 kills.insert(extract_kill(scop_i));
4008 else
4009 scop_i = mark_exposed(scop_i);
4011 scop_i = pet_scop_prefix(scop_i, j);
4012 if (options->autodetect) {
4013 if (scop_i)
4014 scop = pet_scop_add_seq(ctx, scop, scop_i);
4015 else
4016 partial_range = true;
4017 if (scop->n_stmt != 0 && !scop_i)
4018 partial = true;
4019 } else {
4020 scop = pet_scop_add_seq(ctx, scop, scop_i);
4023 scop = pet_skip_info_seq_add(&skip, scop, j);
4025 if (partial || !scop)
4026 break;
4029 for (it = kills.begin(); it != kills.end(); ++it) {
4030 pet_scop *scop_j;
4031 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4032 scop_j = pet_scop_prefix(scop_j, j);
4033 scop = pet_scop_add_seq(ctx, scop, scop_j);
4036 if (scop && partial_range) {
4037 if (scop->n_stmt == 0 || kills.size() != 0) {
4038 pet_scop_free(scop);
4039 return NULL;
4041 partial = true;
4044 return scop;
4047 /* Check if the scop marked by the user is exactly this Stmt
4048 * or part of this Stmt.
4049 * If so, return a pet_scop corresponding to the marked region.
4050 * Otherwise, return NULL.
4052 struct pet_scop *PetScan::scan(Stmt *stmt)
4054 SourceManager &SM = PP.getSourceManager();
4055 unsigned start_off, end_off;
4057 start_off = getExpansionOffset(SM, stmt->getLocStart());
4058 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4060 if (start_off > loc.end)
4061 return NULL;
4062 if (end_off < loc.start)
4063 return NULL;
4064 if (start_off >= loc.start && end_off <= loc.end) {
4065 return extract(stmt);
4068 StmtIterator start;
4069 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4070 Stmt *child = *start;
4071 if (!child)
4072 continue;
4073 start_off = getExpansionOffset(SM, child->getLocStart());
4074 end_off = getExpansionOffset(SM, child->getLocEnd());
4075 if (start_off < loc.start && end_off >= loc.end)
4076 return scan(child);
4077 if (start_off >= loc.start)
4078 break;
4081 StmtIterator end;
4082 for (end = start; end != stmt->child_end(); ++end) {
4083 Stmt *child = *end;
4084 start_off = SM.getFileOffset(child->getLocStart());
4085 if (start_off >= loc.end)
4086 break;
4089 return extract(StmtRange(start, end), false, false);
4092 /* Set the size of index "pos" of "array" to "size".
4093 * In particular, add a constraint of the form
4095 * i_pos < size
4097 * to array->extent and a constraint of the form
4099 * size >= 0
4101 * to array->context.
4103 static struct pet_array *update_size(struct pet_array *array, int pos,
4104 __isl_take isl_pw_aff *size)
4106 isl_set *valid;
4107 isl_set *univ;
4108 isl_set *bound;
4109 isl_space *dim;
4110 isl_aff *aff;
4111 isl_pw_aff *index;
4112 isl_id *id;
4114 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
4115 array->context = isl_set_intersect(array->context, valid);
4117 dim = isl_set_get_space(array->extent);
4118 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
4119 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
4120 univ = isl_set_universe(isl_aff_get_domain_space(aff));
4121 index = isl_pw_aff_alloc(univ, aff);
4123 size = isl_pw_aff_add_dims(size, isl_dim_in,
4124 isl_set_dim(array->extent, isl_dim_set));
4125 id = isl_set_get_tuple_id(array->extent);
4126 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
4127 bound = isl_pw_aff_lt_set(index, size);
4129 array->extent = isl_set_intersect(array->extent, bound);
4131 if (!array->context || !array->extent)
4132 goto error;
4134 return array;
4135 error:
4136 pet_array_free(array);
4137 return NULL;
4140 /* Figure out the size of the array at position "pos" and all
4141 * subsequent positions from "type" and update "array" accordingly.
4143 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
4144 const Type *type, int pos)
4146 const ArrayType *atype;
4147 isl_pw_aff *size;
4149 if (!array)
4150 return NULL;
4152 if (type->isPointerType()) {
4153 type = type->getPointeeType().getTypePtr();
4154 return set_upper_bounds(array, type, pos + 1);
4156 if (!type->isArrayType())
4157 return array;
4159 type = type->getCanonicalTypeInternal().getTypePtr();
4160 atype = cast<ArrayType>(type);
4162 if (type->isConstantArrayType()) {
4163 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
4164 size = extract_affine(ca->getSize());
4165 array = update_size(array, pos, size);
4166 } else if (type->isVariableArrayType()) {
4167 const VariableArrayType *vla = cast<VariableArrayType>(atype);
4168 size = extract_affine(vla->getSizeExpr());
4169 array = update_size(array, pos, size);
4172 type = atype->getElementType().getTypePtr();
4174 return set_upper_bounds(array, type, pos + 1);
4177 /* Is "T" the type of a variable length array with static size?
4179 static bool is_vla_with_static_size(QualType T)
4181 const VariableArrayType *vlatype;
4183 if (!T->isVariableArrayType())
4184 return false;
4185 vlatype = cast<VariableArrayType>(T);
4186 return vlatype->getSizeModifier() == VariableArrayType::Static;
4189 /* Return the type of "decl" as an array.
4191 * In particular, if "decl" is a parameter declaration that
4192 * is a variable length array with a static size, then
4193 * return the original type (i.e., the variable length array).
4194 * Otherwise, return the type of decl.
4196 static QualType get_array_type(ValueDecl *decl)
4198 ParmVarDecl *parm;
4199 QualType T;
4201 parm = dyn_cast<ParmVarDecl>(decl);
4202 if (!parm)
4203 return decl->getType();
4205 T = parm->getOriginalType();
4206 if (!is_vla_with_static_size(T))
4207 return decl->getType();
4208 return T;
4211 /* Does "decl" have definition that we can keep track of in a pet_type?
4213 static bool has_printable_definition(RecordDecl *decl)
4215 if (!decl->getDeclName())
4216 return false;
4217 return decl->getLexicalDeclContext() == decl->getDeclContext();
4220 /* Construct and return a pet_array corresponding to the variable "decl".
4221 * In particular, initialize array->extent to
4223 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4225 * and then call set_upper_bounds to set the upper bounds on the indices
4226 * based on the type of the variable.
4228 * If the base type is that of a record with a top-level definition and
4229 * if "types" is not null, then the RecordDecl corresponding to the type
4230 * is added to "types".
4232 * If the base type is that of a record with no top-level definition,
4233 * then we replace it by "<subfield>".
4235 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
4236 lex_recorddecl_set *types)
4238 struct pet_array *array;
4239 QualType qt = get_array_type(decl);
4240 const Type *type = qt.getTypePtr();
4241 int depth = array_depth(type);
4242 QualType base = pet_clang_base_type(qt);
4243 string name;
4244 isl_id *id;
4245 isl_space *dim;
4247 array = isl_calloc_type(ctx, struct pet_array);
4248 if (!array)
4249 return NULL;
4251 id = create_decl_id(ctx, decl);
4252 dim = isl_space_set_alloc(ctx, 0, depth);
4253 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
4255 array->extent = isl_set_nat_universe(dim);
4257 dim = isl_space_params_alloc(ctx, 0);
4258 array->context = isl_set_universe(dim);
4260 array = set_upper_bounds(array, type, 0);
4261 if (!array)
4262 return NULL;
4264 name = base.getAsString();
4266 if (types && base->isRecordType()) {
4267 RecordDecl *decl = pet_clang_record_decl(base);
4268 if (has_printable_definition(decl))
4269 types->insert(decl);
4270 else
4271 name = "<subfield>";
4274 array->element_type = strdup(name.c_str());
4275 array->element_is_record = base->isRecordType();
4276 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
4278 return array;
4281 /* Construct and return a pet_array corresponding to the sequence
4282 * of declarations "decls".
4283 * If the sequence contains a single declaration, then it corresponds
4284 * to a simple array access. Otherwise, it corresponds to a member access,
4285 * with the declaration for the substructure following that of the containing
4286 * structure in the sequence of declarations.
4287 * We start with the outermost substructure and then combine it with
4288 * information from the inner structures.
4290 * Additionally, keep track of all required types in "types".
4292 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
4293 vector<ValueDecl *> decls, lex_recorddecl_set *types)
4295 struct pet_array *array;
4296 vector<ValueDecl *>::iterator it;
4298 it = decls.begin();
4300 array = extract_array(ctx, *it, types);
4302 for (++it; it != decls.end(); ++it) {
4303 struct pet_array *parent;
4304 const char *base_name, *field_name;
4305 char *product_name;
4307 parent = array;
4308 array = extract_array(ctx, *it, types);
4309 if (!array)
4310 return pet_array_free(parent);
4312 base_name = isl_set_get_tuple_name(parent->extent);
4313 field_name = isl_set_get_tuple_name(array->extent);
4314 product_name = member_access_name(ctx, base_name, field_name);
4316 array->extent = isl_set_product(isl_set_copy(parent->extent),
4317 array->extent);
4318 if (product_name)
4319 array->extent = isl_set_set_tuple_name(array->extent,
4320 product_name);
4321 array->context = isl_set_intersect(array->context,
4322 isl_set_copy(parent->context));
4324 pet_array_free(parent);
4325 free(product_name);
4327 if (!array->extent || !array->context || !product_name)
4328 return pet_array_free(array);
4331 return array;
4334 /* Add a pet_type corresponding to "decl" to "scop, provided
4335 * it is a member of "types" and it has not been added before
4336 * (i.e., it is not a member of "types_done".
4338 * Since we want the user to be able to print the types
4339 * in the order in which they appear in the scop, we need to
4340 * make sure that types of fields in a structure appear before
4341 * that structure. We therefore call ourselves recursively
4342 * on the types of all record subfields.
4344 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
4345 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
4346 lex_recorddecl_set &types_done)
4348 string s;
4349 llvm::raw_string_ostream S(s);
4350 RecordDecl::field_iterator it;
4352 if (types.find(decl) == types.end())
4353 return scop;
4354 if (types_done.find(decl) != types_done.end())
4355 return scop;
4357 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
4358 RecordDecl *record;
4359 QualType type = it->getType();
4361 if (!type->isRecordType())
4362 continue;
4363 record = pet_clang_record_decl(type);
4364 scop = add_type(ctx, scop, record, PP, types, types_done);
4367 if (strlen(decl->getName().str().c_str()) == 0)
4368 return scop;
4370 decl->print(S, PrintingPolicy(PP.getLangOpts()));
4371 S.str();
4373 scop->types[scop->n_type] = pet_type_alloc(ctx,
4374 decl->getName().str().c_str(), s.c_str());
4375 if (!scop->types[scop->n_type])
4376 return pet_scop_free(scop);
4378 types_done.insert(decl);
4380 scop->n_type++;
4382 return scop;
4385 /* Construct a list of pet_arrays, one for each array (or scalar)
4386 * accessed inside "scop", add this list to "scop" and return the result.
4388 * The context of "scop" is updated with the intersection of
4389 * the contexts of all arrays, i.e., constraints on the parameters
4390 * that ensure that the arrays have a valid (non-negative) size.
4392 * If the any of the extracted arrays refers to a member access,
4393 * then also add the required types to "scop".
4395 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
4397 int i;
4398 array_desc_set arrays;
4399 array_desc_set::iterator it;
4400 lex_recorddecl_set types;
4401 lex_recorddecl_set types_done;
4402 lex_recorddecl_set::iterator types_it;
4403 int n_array;
4404 struct pet_array **scop_arrays;
4406 if (!scop)
4407 return NULL;
4409 pet_scop_collect_arrays(scop, arrays);
4410 if (arrays.size() == 0)
4411 return scop;
4413 n_array = scop->n_array;
4415 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
4416 n_array + arrays.size());
4417 if (!scop_arrays)
4418 goto error;
4419 scop->arrays = scop_arrays;
4421 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
4422 struct pet_array *array;
4423 array = extract_array(ctx, *it, &types);
4424 scop->arrays[n_array + i] = array;
4425 if (!scop->arrays[n_array + i])
4426 goto error;
4427 scop->n_array++;
4428 scop->context = isl_set_intersect(scop->context,
4429 isl_set_copy(array->context));
4430 if (!scop->context)
4431 goto error;
4434 if (types.size() == 0)
4435 return scop;
4437 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
4438 if (!scop->types)
4439 goto error;
4441 for (types_it = types.begin(); types_it != types.end(); ++types_it)
4442 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
4444 return scop;
4445 error:
4446 pet_scop_free(scop);
4447 return NULL;
4450 /* Bound all parameters in scop->context to the possible values
4451 * of the corresponding C variable.
4453 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
4455 int n;
4457 if (!scop)
4458 return NULL;
4460 n = isl_set_dim(scop->context, isl_dim_param);
4461 for (int i = 0; i < n; ++i) {
4462 isl_id *id;
4463 ValueDecl *decl;
4465 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
4466 if (pet_nested_in_id(id)) {
4467 isl_id_free(id);
4468 isl_die(isl_set_get_ctx(scop->context),
4469 isl_error_internal,
4470 "unresolved nested parameter", goto error);
4472 decl = (ValueDecl *) isl_id_get_user(id);
4473 isl_id_free(id);
4475 scop->context = set_parameter_bounds(scop->context, i, decl);
4477 if (!scop->context)
4478 goto error;
4481 return scop;
4482 error:
4483 pet_scop_free(scop);
4484 return NULL;
4487 /* Construct a pet_scop from the given function.
4489 * If the scop was delimited by scop and endscop pragmas, then we override
4490 * the file offsets by those derived from the pragmas.
4492 struct pet_scop *PetScan::scan(FunctionDecl *fd)
4494 pet_scop *scop;
4495 Stmt *stmt;
4497 stmt = fd->getBody();
4499 if (options->autodetect)
4500 scop = extract(stmt, true);
4501 else {
4502 scop = scan(stmt);
4503 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
4505 scop = pet_scop_detect_parameter_accesses(scop);
4506 scop = scan_arrays(scop);
4507 scop = add_parameter_bounds(scop);
4508 scop = pet_scop_gist(scop, value_bounds);
4510 return scop;