PetScan::extract_conditional_assignment: extract write access as pet_expr
[pet.git] / scan.cc
blob92c1d3c2abc2f673531fe0a9645990096d099525
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 /* Mark the given access pet_expr as a write.
1056 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
1058 access = pet_expr_access_set_write(access, 1);
1059 access = pet_expr_access_set_read(access, 0);
1061 return access;
1064 /* Construct a pet_expr representing a unary operator expression.
1066 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1068 pet_expr *arg;
1069 enum pet_op_type op;
1071 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1072 if (op == pet_op_last) {
1073 unsupported(expr);
1074 return NULL;
1077 arg = extract_expr(expr->getSubExpr());
1079 if (expr->isIncrementDecrementOp() &&
1080 pet_expr_get_type(arg) == pet_expr_access) {
1081 arg = mark_write(arg);
1082 arg = pet_expr_access_set_read(arg, 1);
1085 return pet_expr_new_unary(op, arg);
1088 /* If the access expression "expr" writes to a (non-virtual) scalar,
1089 * then mark the scalar as having an unknown value in "assigned_value".
1091 static int clear_write(__isl_keep pet_expr *expr, void *user)
1093 isl_id *id;
1094 ValueDecl *decl;
1095 PetScan *ps = (PetScan *) user;
1097 if (!pet_expr_access_is_write(expr))
1098 return 0;
1099 if (!pet_expr_is_scalar_access(expr))
1100 return 0;
1102 id = pet_expr_access_get_id(expr);
1103 decl = (ValueDecl *) isl_id_get_user(id);
1104 isl_id_free(id);
1106 if (decl)
1107 clear_assignment(ps->assigned_value, decl);
1109 return 0;
1112 /* Take into account the writes in "stmt".
1113 * That is, first mark all scalar variables that are written by "stmt"
1114 * as having an unknown value. Afterwards,
1115 * if "stmt" is a top-level (i.e., unconditional) assignment
1116 * to a scalar variable, then update "assigned_value" accordingly.
1118 * In particular, if the lhs of the assignment is a scalar variable, then mark
1119 * the variable as having been assigned. If, furthermore, the rhs
1120 * is an affine expression, then keep track of this value in assigned_value
1121 * so that we can plug it in when we later come across the same variable.
1123 * We skip assignments to virtual arrays (those with NULL user pointer).
1125 void PetScan::handle_writes(struct pet_stmt *stmt)
1127 pet_expr *body = stmt->body;
1128 pet_expr *arg;
1129 isl_id *id;
1130 ValueDecl *decl;
1131 pet_context *pc;
1132 isl_pw_aff *pa;
1134 pet_expr_foreach_access_expr(body, &clear_write, this);
1136 if (!pet_stmt_is_assign(stmt))
1137 return;
1138 if (!isl_set_plain_is_universe(stmt->domain))
1139 return;
1140 arg = pet_expr_get_arg(body, 0);
1141 if (!pet_expr_is_scalar_access(arg)) {
1142 pet_expr_free(arg);
1143 return;
1146 id = pet_expr_access_get_id(arg);
1147 decl = (ValueDecl *) isl_id_get_user(id);
1148 isl_id_free(id);
1149 pet_expr_free(arg);
1151 if (!decl)
1152 return;
1154 arg = pet_expr_get_arg(body, 1);
1155 pc = convert_assignments(ctx, assigned_value);
1156 pa = pet_expr_extract_affine(arg, pc);
1157 pet_context_free(pc);
1158 clear_assignment(assigned_value, decl);
1159 pet_expr_free(arg);
1161 if (isl_pw_aff_involves_nan(pa))
1162 pa = isl_pw_aff_free(pa);
1163 if (!pa)
1164 return;
1165 assigned_value[decl] = pa;
1166 insert_expression(pa);
1169 /* Update "assigned_value" based on the write accesses (and, in particular,
1170 * assignments) in "scop".
1172 void PetScan::handle_writes(struct pet_scop *scop)
1174 if (!scop)
1175 return;
1176 for (int i = 0; i < scop->n_stmt; ++i)
1177 handle_writes(scop->stmts[i]);
1180 /* Construct a pet_expr representing a binary operator expression.
1182 * If the top level operator is an assignment and the LHS is an access,
1183 * then we mark that access as a write. If the operator is a compound
1184 * assignment, the access is marked as both a read and a write.
1186 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1188 int type_size;
1189 pet_expr *lhs, *rhs;
1190 enum pet_op_type op;
1192 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1193 if (op == pet_op_last) {
1194 unsupported(expr);
1195 return NULL;
1198 lhs = extract_expr(expr->getLHS());
1199 rhs = extract_expr(expr->getRHS());
1201 if (expr->isAssignmentOp() &&
1202 pet_expr_get_type(lhs) == pet_expr_access) {
1203 lhs = mark_write(lhs);
1204 if (expr->isCompoundAssignmentOp())
1205 lhs = pet_expr_access_set_read(lhs, 1);
1208 type_size = get_type_size(expr->getType(), ast_context);
1209 return pet_expr_new_binary(type_size, op, lhs, rhs);
1212 /* Construct a pet_scop with a single statement killing the entire
1213 * array "array".
1215 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1217 isl_id *id;
1218 isl_space *space;
1219 isl_multi_pw_aff *index;
1220 isl_map *access;
1221 pet_expr *expr;
1223 if (!array)
1224 return NULL;
1225 access = isl_map_from_range(isl_set_copy(array->extent));
1226 id = isl_set_get_tuple_id(array->extent);
1227 space = isl_space_alloc(ctx, 0, 0, 0);
1228 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1229 index = isl_multi_pw_aff_zero(space);
1230 expr = pet_expr_kill_from_access_and_index(access, index);
1231 return extract(expr, stmt->getSourceRange(), false);
1234 /* Construct a pet_scop for a (single) variable declaration.
1236 * The scop contains the variable being declared (as an array)
1237 * and a statement killing the array.
1239 * If the variable is initialized in the AST, then the scop
1240 * also contains an assignment to the variable.
1242 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1244 int type_size;
1245 Decl *decl;
1246 VarDecl *vd;
1247 pet_expr *lhs, *rhs, *pe;
1248 struct pet_scop *scop_decl, *scop;
1249 struct pet_array *array;
1251 if (!stmt->isSingleDecl()) {
1252 unsupported(stmt);
1253 return NULL;
1256 decl = stmt->getSingleDecl();
1257 vd = cast<VarDecl>(decl);
1259 array = extract_array(ctx, vd, NULL);
1260 if (array)
1261 array->declared = 1;
1262 scop_decl = kill(stmt, array);
1263 scop_decl = pet_scop_add_array(scop_decl, array);
1265 if (!vd->getInit())
1266 return scop_decl;
1268 lhs = extract_access_expr(vd);
1269 rhs = extract_expr(vd->getInit());
1271 lhs = mark_write(lhs);
1273 type_size = get_type_size(vd->getType(), ast_context);
1274 pe = pet_expr_new_binary(type_size, pet_op_assign, lhs, rhs);
1275 scop = extract(pe, stmt->getSourceRange(), false);
1277 scop_decl = pet_scop_prefix(scop_decl, 0);
1278 scop = pet_scop_prefix(scop, 1);
1280 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1282 return scop;
1285 /* Construct a pet_expr representing a conditional operation.
1287 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1289 pet_expr *cond, *lhs, *rhs;
1290 isl_pw_aff *pa;
1292 cond = extract_expr(expr->getCond());
1293 lhs = extract_expr(expr->getTrueExpr());
1294 rhs = extract_expr(expr->getFalseExpr());
1296 return pet_expr_new_ternary(cond, lhs, rhs);
1299 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1301 return extract_expr(expr->getSubExpr());
1304 /* Construct a pet_expr representing a floating point value.
1306 * If the floating point literal does not appear in a macro,
1307 * then we use the original representation in the source code
1308 * as the string representation. Otherwise, we use the pretty
1309 * printer to produce a string representation.
1311 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1313 double d;
1314 string s;
1315 const LangOptions &LO = PP.getLangOpts();
1316 SourceLocation loc = expr->getLocation();
1318 if (!loc.isMacroID()) {
1319 SourceManager &SM = PP.getSourceManager();
1320 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1321 s = string(SM.getCharacterData(loc), len);
1322 } else {
1323 llvm::raw_string_ostream S(s);
1324 expr->printPretty(S, 0, PrintingPolicy(LO));
1325 S.str();
1327 d = expr->getValueAsApproximateDouble();
1328 return pet_expr_new_double(ctx, d, s.c_str());
1331 /* Convert the index expression "index" into an access pet_expr of type "qt".
1333 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
1334 __isl_take isl_multi_pw_aff *index)
1336 pet_expr *pe;
1337 int depth;
1338 int type_size;
1340 depth = extract_depth(index);
1341 type_size = get_type_size(qt, ast_context);
1343 pe = pet_expr_from_index_and_depth(type_size, index, depth);
1345 return pe;
1348 /* Extract an index expression from "expr" and then convert it into
1349 * an access pet_expr.
1351 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
1353 return extract_access_expr(expr->getType(), extract_index(expr));
1356 /* Extract an index expression from "decl" and then convert it into
1357 * an access pet_expr.
1359 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1361 return extract_access_expr(decl->getType(), extract_index(decl));
1364 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
1366 return extract_expr(expr->getSubExpr());
1369 /* Extract an assume statement from the argument "expr"
1370 * of a __pencil_assume statement.
1372 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
1374 isl_pw_aff *cond;
1375 pet_expr *res;
1377 cond = try_extract_affine_condition(expr);
1378 if (!cond) {
1379 res = extract_expr(expr);
1380 } else {
1381 isl_multi_pw_aff *index;
1382 index = isl_multi_pw_aff_from_pw_aff(cond);
1383 res = pet_expr_from_index(index);
1385 return pet_expr_new_unary(pet_op_assume, res);
1388 /* Construct a pet_expr corresponding to the function call argument "expr".
1389 * The argument appears in position "pos" of a call to function "fd".
1391 * If we are passing along a pointer to an array element
1392 * or an entire row or even higher dimensional slice of an array,
1393 * then the function being called may write into the array.
1395 * We assume here that if the function is declared to take a pointer
1396 * to a const type, then the function will perform a read
1397 * and that otherwise, it will perform a write.
1399 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
1400 Expr *expr)
1402 pet_expr *res;
1403 int is_addr = 0, is_partial = 0;
1404 Stmt::StmtClass sc;
1406 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
1407 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
1408 expr = ice->getSubExpr();
1410 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
1411 UnaryOperator *op = cast<UnaryOperator>(expr);
1412 if (op->getOpcode() == UO_AddrOf) {
1413 is_addr = 1;
1414 expr = op->getSubExpr();
1417 res = extract_expr(expr);
1418 if (!res)
1419 return NULL;
1420 sc = expr->getStmtClass();
1421 if ((sc == Stmt::ArraySubscriptExprClass ||
1422 sc == Stmt::MemberExprClass) &&
1423 array_depth(expr->getType().getTypePtr()) > 0)
1424 is_partial = 1;
1425 if ((is_addr || is_partial) &&
1426 pet_expr_get_type(res) == pet_expr_access) {
1427 ParmVarDecl *parm;
1428 if (!fd->hasPrototype()) {
1429 report_prototype_required(expr);
1430 return pet_expr_free(res);
1432 parm = fd->getParamDecl(pos);
1433 if (!const_base(parm->getType()))
1434 res = mark_write(res);
1437 if (is_addr)
1438 res = pet_expr_new_unary(pet_op_address_of, res);
1439 return res;
1442 /* Construct a pet_expr representing a function call.
1444 * In the special case of a "call" to __pencil_assume,
1445 * construct an assume expression instead.
1447 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1449 pet_expr *res = NULL;
1450 FunctionDecl *fd;
1451 string name;
1452 unsigned n_arg;
1454 fd = expr->getDirectCallee();
1455 if (!fd) {
1456 unsupported(expr);
1457 return NULL;
1460 name = fd->getDeclName().getAsString();
1461 n_arg = expr->getNumArgs();
1463 if (n_arg == 1 && name == "__pencil_assume")
1464 return extract_assume(expr->getArg(0));
1466 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1467 if (!res)
1468 return NULL;
1470 for (int i = 0; i < n_arg; ++i) {
1471 Expr *arg = expr->getArg(i);
1472 res = pet_expr_set_arg(res, i,
1473 PetScan::extract_argument(fd, i, arg));
1476 return res;
1479 /* Construct a pet_expr representing a (C style) cast.
1481 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1483 pet_expr *arg;
1484 QualType type;
1486 arg = extract_expr(expr->getSubExpr());
1487 if (!arg)
1488 return NULL;
1490 type = expr->getTypeAsWritten();
1491 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1494 /* Construct a pet_expr representing an integer.
1496 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1498 return pet_expr_new_int(extract_int(expr));
1501 /* Try and construct a pet_expr representing "expr".
1503 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1505 switch (expr->getStmtClass()) {
1506 case Stmt::UnaryOperatorClass:
1507 return extract_expr(cast<UnaryOperator>(expr));
1508 case Stmt::CompoundAssignOperatorClass:
1509 case Stmt::BinaryOperatorClass:
1510 return extract_expr(cast<BinaryOperator>(expr));
1511 case Stmt::ImplicitCastExprClass:
1512 return extract_expr(cast<ImplicitCastExpr>(expr));
1513 case Stmt::ArraySubscriptExprClass:
1514 case Stmt::DeclRefExprClass:
1515 case Stmt::MemberExprClass:
1516 return extract_access_expr(expr);
1517 case Stmt::IntegerLiteralClass:
1518 return extract_expr(cast<IntegerLiteral>(expr));
1519 case Stmt::FloatingLiteralClass:
1520 return extract_expr(cast<FloatingLiteral>(expr));
1521 case Stmt::ParenExprClass:
1522 return extract_expr(cast<ParenExpr>(expr));
1523 case Stmt::ConditionalOperatorClass:
1524 return extract_expr(cast<ConditionalOperator>(expr));
1525 case Stmt::CallExprClass:
1526 return extract_expr(cast<CallExpr>(expr));
1527 case Stmt::CStyleCastExprClass:
1528 return extract_expr(cast<CStyleCastExpr>(expr));
1529 default:
1530 unsupported(expr);
1532 return NULL;
1535 /* Check if the given initialization statement is an assignment.
1536 * If so, return that assignment. Otherwise return NULL.
1538 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1540 BinaryOperator *ass;
1542 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1543 return NULL;
1545 ass = cast<BinaryOperator>(init);
1546 if (ass->getOpcode() != BO_Assign)
1547 return NULL;
1549 return ass;
1552 /* Check if the given initialization statement is a declaration
1553 * of a single variable.
1554 * If so, return that declaration. Otherwise return NULL.
1556 Decl *PetScan::initialization_declaration(Stmt *init)
1558 DeclStmt *decl;
1560 if (init->getStmtClass() != Stmt::DeclStmtClass)
1561 return NULL;
1563 decl = cast<DeclStmt>(init);
1565 if (!decl->isSingleDecl())
1566 return NULL;
1568 return decl->getSingleDecl();
1571 /* Given the assignment operator in the initialization of a for loop,
1572 * extract the induction variable, i.e., the (integer)variable being
1573 * assigned.
1575 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1577 Expr *lhs;
1578 DeclRefExpr *ref;
1579 ValueDecl *decl;
1580 const Type *type;
1582 lhs = init->getLHS();
1583 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1584 unsupported(init);
1585 return NULL;
1588 ref = cast<DeclRefExpr>(lhs);
1589 decl = ref->getDecl();
1590 type = decl->getType().getTypePtr();
1592 if (!type->isIntegerType()) {
1593 unsupported(lhs);
1594 return NULL;
1597 return decl;
1600 /* Given the initialization statement of a for loop and the single
1601 * declaration in this initialization statement,
1602 * extract the induction variable, i.e., the (integer) variable being
1603 * declared.
1605 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1607 VarDecl *vd;
1609 vd = cast<VarDecl>(decl);
1611 const QualType type = vd->getType();
1612 if (!type->isIntegerType()) {
1613 unsupported(init);
1614 return NULL;
1617 if (!vd->getInit()) {
1618 unsupported(init);
1619 return NULL;
1622 return vd;
1625 /* Check that op is of the form iv++ or iv--.
1626 * Return a pet_expr representing "1" or "-1" accordingly.
1628 __isl_give pet_expr *PetScan::extract_unary_increment(
1629 clang::UnaryOperator *op, clang::ValueDecl *iv)
1631 Expr *sub;
1632 DeclRefExpr *ref;
1633 isl_val *v;
1635 if (!op->isIncrementDecrementOp()) {
1636 unsupported(op);
1637 return NULL;
1640 sub = op->getSubExpr();
1641 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1642 unsupported(op);
1643 return NULL;
1646 ref = cast<DeclRefExpr>(sub);
1647 if (ref->getDecl() != iv) {
1648 unsupported(op);
1649 return NULL;
1652 if (op->isIncrementOp())
1653 v = isl_val_one(ctx);
1654 else
1655 v = isl_val_negone(ctx);
1657 return pet_expr_new_int(v);
1660 /* Check if op is of the form
1662 * iv = expr
1664 * and return the increment "expr - iv" as a pet_expr.
1666 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1667 clang::ValueDecl *iv)
1669 int type_size;
1670 Expr *lhs;
1671 DeclRefExpr *ref;
1672 pet_expr *expr, *expr_iv;
1674 if (op->getOpcode() != BO_Assign) {
1675 unsupported(op);
1676 return NULL;
1679 lhs = op->getLHS();
1680 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1681 unsupported(op);
1682 return NULL;
1685 ref = cast<DeclRefExpr>(lhs);
1686 if (ref->getDecl() != iv) {
1687 unsupported(op);
1688 return NULL;
1691 expr = extract_expr(op->getRHS());
1692 expr_iv = extract_expr(lhs);
1694 type_size = get_type_size(iv->getType(), ast_context);
1695 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1698 /* Check that op is of the form iv += cst or iv -= cst
1699 * and return a pet_expr corresponding to cst or -cst accordingly.
1701 __isl_give pet_expr *PetScan::extract_compound_increment(
1702 CompoundAssignOperator *op, clang::ValueDecl *iv)
1704 Expr *lhs;
1705 DeclRefExpr *ref;
1706 bool neg = false;
1707 pet_expr *expr;
1708 BinaryOperatorKind opcode;
1710 opcode = op->getOpcode();
1711 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1712 unsupported(op);
1713 return NULL;
1715 if (opcode == BO_SubAssign)
1716 neg = true;
1718 lhs = op->getLHS();
1719 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1720 unsupported(op);
1721 return NULL;
1724 ref = cast<DeclRefExpr>(lhs);
1725 if (ref->getDecl() != iv) {
1726 unsupported(op);
1727 return NULL;
1730 expr = extract_expr(op->getRHS());
1731 if (neg)
1732 expr = pet_expr_new_unary(pet_op_minus, expr);
1734 return expr;
1737 /* Check that the increment of the given for loop increments
1738 * (or decrements) the induction variable "iv" and return
1739 * the increment as a pet_expr if successful.
1741 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1742 ValueDecl *iv)
1744 Stmt *inc = stmt->getInc();
1746 if (!inc) {
1747 report_missing_increment(stmt);
1748 return NULL;
1751 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1752 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1753 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1754 return extract_compound_increment(
1755 cast<CompoundAssignOperator>(inc), iv);
1756 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1757 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1759 unsupported(inc);
1760 return NULL;
1763 /* Embed the given iteration domain in an extra outer loop
1764 * with induction variable "var".
1765 * If this variable appeared as a parameter in the constraints,
1766 * it is replaced by the new outermost dimension.
1768 static __isl_give isl_set *embed(__isl_take isl_set *set,
1769 __isl_take isl_id *var)
1771 int pos;
1773 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1774 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1775 if (pos >= 0) {
1776 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1777 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1780 isl_id_free(var);
1781 return set;
1784 /* Return those elements in the space of "cond" that come after
1785 * (based on "sign") an element in "cond".
1787 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
1789 isl_map *previous_to_this;
1791 if (sign > 0)
1792 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
1793 else
1794 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
1796 cond = isl_set_apply(cond, previous_to_this);
1798 return cond;
1801 /* Create the infinite iteration domain
1803 * { [id] : id >= 0 }
1805 * If "scop" has an affine skip of type pet_skip_later,
1806 * then remove those iterations i that have an earlier iteration
1807 * where the skip condition is satisfied, meaning that iteration i
1808 * is not executed.
1809 * Since we are dealing with a loop without loop iterator,
1810 * the skip condition cannot refer to the current loop iterator and
1811 * so effectively, the returned set is of the form
1813 * { [0]; [id] : id >= 1 and not skip }
1815 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
1816 struct pet_scop *scop)
1818 isl_ctx *ctx = isl_id_get_ctx(id);
1819 isl_set *domain;
1820 isl_set *skip;
1822 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1823 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
1825 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
1826 return domain;
1828 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
1829 skip = embed(skip, isl_id_copy(id));
1830 skip = isl_set_intersect(skip , isl_set_copy(domain));
1831 domain = isl_set_subtract(domain, after(skip, 1));
1833 return domain;
1836 /* Create an identity affine expression on the space containing "domain",
1837 * which is assumed to be one-dimensional.
1839 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
1841 isl_local_space *ls;
1843 ls = isl_local_space_from_space(isl_set_get_space(domain));
1844 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
1847 /* Create an affine expression that maps elements
1848 * of a single-dimensional array "id_test" to the previous element
1849 * (according to "inc"), provided this element belongs to "domain".
1850 * That is, create the affine expression
1852 * { id[x] -> id[x - inc] : x - inc in domain }
1854 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
1855 __isl_take isl_set *domain, __isl_take isl_val *inc)
1857 isl_space *space;
1858 isl_local_space *ls;
1859 isl_aff *aff;
1860 isl_multi_pw_aff *prev;
1862 space = isl_set_get_space(domain);
1863 ls = isl_local_space_from_space(space);
1864 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
1865 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
1866 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
1867 domain = isl_set_preimage_multi_pw_aff(domain,
1868 isl_multi_pw_aff_copy(prev));
1869 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
1870 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
1872 return prev;
1875 /* Add an implication to "scop" expressing that if an element of
1876 * virtual array "id_test" has value "satisfied" then all previous elements
1877 * of this array also have that value. The set of previous elements
1878 * is bounded by "domain". If "sign" is negative then the iterator
1879 * is decreasing and we express that all subsequent array elements
1880 * (but still defined previously) have the same value.
1882 static struct pet_scop *add_implication(struct pet_scop *scop,
1883 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
1884 int satisfied)
1886 isl_space *space;
1887 isl_map *map;
1889 domain = isl_set_set_tuple_id(domain, id_test);
1890 space = isl_set_get_space(domain);
1891 if (sign > 0)
1892 map = isl_map_lex_ge(space);
1893 else
1894 map = isl_map_lex_le(space);
1895 map = isl_map_intersect_range(map, domain);
1896 scop = pet_scop_add_implication(scop, map, satisfied);
1898 return scop;
1901 /* Add a filter to "scop" that imposes that it is only executed
1902 * when the variable identified by "id_test" has a zero value
1903 * for all previous iterations of "domain".
1905 * In particular, add a filter that imposes that the array
1906 * has a zero value at the previous iteration of domain and
1907 * add an implication that implies that it then has that
1908 * value for all previous iterations.
1910 static struct pet_scop *scop_add_break(struct pet_scop *scop,
1911 __isl_take isl_id *id_test, __isl_take isl_set *domain,
1912 __isl_take isl_val *inc)
1914 isl_multi_pw_aff *prev;
1915 int sign = isl_val_sgn(inc);
1917 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
1918 scop = add_implication(scop, id_test, domain, sign, 0);
1919 scop = pet_scop_filter(scop, prev, 0);
1921 return scop;
1924 /* Construct a pet_scop for an infinite loop around the given body.
1926 * We extract a pet_scop for the body and then embed it in a loop with
1927 * iteration domain
1929 * { [t] : t >= 0 }
1931 * and schedule
1933 * { [t] -> [t] }
1935 * If the body contains any break, then it is taken into
1936 * account in infinite_domain (if the skip condition is affine)
1937 * or in scop_add_break (if the skip condition is not affine).
1939 * If we were only able to extract part of the body, then simply
1940 * return that part.
1942 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1944 isl_id *id, *id_test;
1945 isl_set *domain;
1946 isl_aff *ident;
1947 struct pet_scop *scop;
1948 bool has_var_break;
1950 scop = extract(body);
1951 if (!scop)
1952 return NULL;
1953 if (partial)
1954 return scop;
1956 id = isl_id_alloc(ctx, "t", NULL);
1957 domain = infinite_domain(isl_id_copy(id), scop);
1958 ident = identity_aff(domain);
1960 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
1961 if (has_var_break)
1962 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
1964 scop = pet_scop_embed(scop, isl_set_copy(domain),
1965 isl_aff_copy(ident), ident, id);
1966 if (has_var_break)
1967 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
1968 else
1969 isl_set_free(domain);
1971 return scop;
1974 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1976 * for (;;)
1977 * body
1980 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1982 clear_assignments clear(assigned_value);
1983 clear.TraverseStmt(stmt->getBody());
1985 return extract_infinite_loop(stmt->getBody());
1988 /* Add an array with the given extent (range of "index") to the list
1989 * of arrays in "scop" and return the extended pet_scop.
1990 * The array is marked as attaining values 0 and 1 only and
1991 * as each element being assigned at most once.
1993 static struct pet_scop *scop_add_array(struct pet_scop *scop,
1994 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
1996 int int_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
1998 return pet_scop_add_boolean_array(scop, isl_multi_pw_aff_copy(index),
1999 int_size);
2002 /* Construct a pet_scop for a while loop of the form
2004 * while (pa)
2005 * body
2007 * In particular, construct a scop for an infinite loop around body and
2008 * intersect the domain with the affine expression.
2009 * Note that this intersection may result in an empty loop.
2011 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2012 Stmt *body)
2014 struct pet_scop *scop;
2015 isl_set *dom;
2016 isl_set *valid;
2018 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2019 dom = isl_pw_aff_non_zero_set(pa);
2020 scop = extract_infinite_loop(body);
2021 scop = pet_scop_restrict(scop, isl_set_params(dom));
2022 scop = pet_scop_restrict_context(scop, isl_set_params(valid));
2024 return scop;
2027 /* Construct a scop for a while, given the scops for the condition
2028 * and the body, the filter identifier and the iteration domain of
2029 * the while loop.
2031 * In particular, the scop for the condition is filtered to depend
2032 * on "id_test" evaluating to true for all previous iterations
2033 * of the loop, while the scop for the body is filtered to depend
2034 * on "id_test" evaluating to true for all iterations up to the
2035 * current iteration.
2036 * The actual filter only imposes that this virtual array has
2037 * value one on the previous or the current iteration.
2038 * The fact that this condition also applies to the previous
2039 * iterations is enforced by an implication.
2041 * These filtered scops are then combined into a single scop.
2043 * "sign" is positive if the iterator increases and negative
2044 * if it decreases.
2046 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2047 struct pet_scop *scop_body, __isl_take isl_id *id_test,
2048 __isl_take isl_set *domain, __isl_take isl_val *inc)
2050 isl_ctx *ctx = isl_set_get_ctx(domain);
2051 isl_space *space;
2052 isl_multi_pw_aff *test_index;
2053 isl_multi_pw_aff *prev;
2054 int sign = isl_val_sgn(inc);
2055 struct pet_scop *scop;
2057 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2058 scop_cond = pet_scop_filter(scop_cond, prev, 1);
2060 space = isl_space_map_from_set(isl_set_get_space(domain));
2061 test_index = isl_multi_pw_aff_identity(space);
2062 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
2063 isl_id_copy(id_test));
2064 scop_body = pet_scop_filter(scop_body, test_index, 1);
2066 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
2067 scop = add_implication(scop, id_test, domain, sign, 1);
2069 return scop;
2072 /* Check if the while loop is of the form
2074 * while (affine expression)
2075 * body
2077 * If so, call extract_affine_while to construct a scop.
2079 * Otherwise, extract the body and pass control to extract_while
2080 * to extend the iteration domain with an infinite loop.
2081 * If we were only able to extract part of the body, then simply
2082 * return that part.
2084 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2086 Expr *cond;
2087 int test_nr, stmt_nr;
2088 isl_pw_aff *pa;
2089 struct pet_scop *scop_body;
2091 cond = stmt->getCond();
2092 if (!cond) {
2093 unsupported(stmt);
2094 return NULL;
2097 clear_assignments clear(assigned_value);
2098 clear.TraverseStmt(stmt->getBody());
2100 pa = try_extract_affine_condition(cond);
2101 if (pa)
2102 return extract_affine_while(pa, stmt->getBody());
2104 if (!allow_nested) {
2105 unsupported(stmt);
2106 return NULL;
2109 test_nr = n_test++;
2110 stmt_nr = n_stmt++;
2111 scop_body = extract(stmt->getBody());
2112 if (partial)
2113 return scop_body;
2115 return extract_while(cond, test_nr, stmt_nr, scop_body, NULL);
2118 /* Construct a generic while scop, with iteration domain
2119 * { [t] : t >= 0 } around "scop_body". The scop consists of two parts,
2120 * one for evaluating the condition "cond" and one for the body.
2121 * "test_nr" is the sequence number of the virtual test variable that contains
2122 * the result of the condition and "stmt_nr" is the sequence number
2123 * of the statement that evaluates the condition.
2124 * If "scop_inc" is not NULL, then it is added at the end of the body,
2125 * after replacing any skip conditions resulting from continue statements
2126 * by the skip conditions resulting from break statements (if any).
2128 * The schedule is adjusted to reflect that the condition is evaluated
2129 * before the body is executed and the body is filtered to depend
2130 * on the result of the condition evaluating to true on all iterations
2131 * up to the current iteration, while the evaluation of the condition itself
2132 * is filtered to depend on the result of the condition evaluating to true
2133 * on all previous iterations.
2134 * The context of the scop representing the body is dropped
2135 * because we don't know how many times the body will be executed,
2136 * if at all.
2138 * If the body contains any break, then it is taken into
2139 * account in infinite_domain (if the skip condition is affine)
2140 * or in scop_add_break (if the skip condition is not affine).
2142 struct pet_scop *PetScan::extract_while(Expr *cond, int test_nr, int stmt_nr,
2143 struct pet_scop *scop_body, struct pet_scop *scop_inc)
2145 isl_id *id, *id_test, *id_break_test;
2146 isl_set *domain;
2147 isl_aff *ident;
2148 isl_multi_pw_aff *test_index;
2149 struct pet_scop *scop;
2150 bool has_var_break;
2152 test_index = pet_create_test_index(ctx, test_nr);
2153 scop = extract_non_affine_condition(cond, stmt_nr,
2154 isl_multi_pw_aff_copy(test_index));
2155 scop = scop_add_array(scop, test_index, ast_context);
2156 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2157 isl_multi_pw_aff_free(test_index);
2159 id = isl_id_alloc(ctx, "t", NULL);
2160 domain = infinite_domain(isl_id_copy(id), scop_body);
2161 ident = identity_aff(domain);
2163 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2164 if (has_var_break)
2165 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2167 scop = pet_scop_prefix(scop, 0);
2168 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_aff_copy(ident),
2169 isl_aff_copy(ident), isl_id_copy(id));
2170 scop_body = pet_scop_reset_context(scop_body);
2171 scop_body = pet_scop_prefix(scop_body, 1);
2172 if (scop_inc) {
2173 scop_inc = pet_scop_prefix(scop_inc, 2);
2174 if (pet_scop_has_skip(scop_body, pet_skip_later)) {
2175 isl_multi_pw_aff *skip;
2176 skip = pet_scop_get_skip(scop_body, pet_skip_later);
2177 scop_body = pet_scop_set_skip(scop_body,
2178 pet_skip_now, skip);
2179 } else
2180 pet_scop_reset_skip(scop_body, pet_skip_now);
2181 scop_body = pet_scop_add_seq(ctx, scop_body, scop_inc);
2183 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2184 isl_aff_copy(ident), ident, id);
2186 if (has_var_break) {
2187 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2188 isl_set_copy(domain), isl_val_one(ctx));
2189 scop_body = scop_add_break(scop_body, id_break_test,
2190 isl_set_copy(domain), isl_val_one(ctx));
2192 scop = scop_add_while(scop, scop_body, id_test, domain,
2193 isl_val_one(ctx));
2195 return scop;
2198 /* Check whether "cond" expresses a simple loop bound
2199 * on the only set dimension.
2200 * In particular, if "up" is set then "cond" should contain only
2201 * upper bounds on the set dimension.
2202 * Otherwise, it should contain only lower bounds.
2204 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2206 if (isl_val_is_pos(inc))
2207 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2208 else
2209 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2212 /* Extend a condition on a given iteration of a loop to one that
2213 * imposes the same condition on all previous iterations.
2214 * "domain" expresses the lower [upper] bound on the iterations
2215 * when inc is positive [negative].
2217 * In particular, we construct the condition (when inc is positive)
2219 * forall i' : (domain(i') and i' <= i) => cond(i')
2221 * which is equivalent to
2223 * not exists i' : domain(i') and i' <= i and not cond(i')
2225 * We construct this set by negating cond, applying a map
2227 * { [i'] -> [i] : domain(i') and i' <= i }
2229 * and then negating the result again.
2231 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2232 __isl_take isl_set *domain, __isl_take isl_val *inc)
2234 isl_map *previous_to_this;
2236 if (isl_val_is_pos(inc))
2237 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2238 else
2239 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2241 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2243 cond = isl_set_complement(cond);
2244 cond = isl_set_apply(cond, previous_to_this);
2245 cond = isl_set_complement(cond);
2247 isl_val_free(inc);
2249 return cond;
2252 /* Construct a domain of the form
2254 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2256 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2257 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2259 isl_aff *aff;
2260 isl_space *dim;
2261 isl_set *set;
2263 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2264 dim = isl_pw_aff_get_domain_space(init);
2265 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2266 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2267 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2269 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2270 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2271 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2272 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2274 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2276 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2278 return isl_set_params(set);
2281 /* Assuming "cond" represents a bound on a loop where the loop
2282 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2283 * is possible.
2285 * Under the given assumptions, wrapping is only possible if "cond" allows
2286 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2287 * increasing iterator and 0 in case of a decreasing iterator.
2289 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2290 __isl_keep isl_val *inc)
2292 bool cw;
2293 isl_ctx *ctx;
2294 isl_val *limit;
2295 isl_set *test;
2297 test = isl_set_copy(cond);
2299 ctx = isl_set_get_ctx(test);
2300 if (isl_val_is_neg(inc))
2301 limit = isl_val_zero(ctx);
2302 else {
2303 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2304 limit = isl_val_2exp(limit);
2305 limit = isl_val_sub_ui(limit, 1);
2308 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2309 cw = !isl_set_is_empty(test);
2310 isl_set_free(test);
2312 return cw;
2315 /* Given a one-dimensional space, construct the following affine expression
2316 * on this space
2318 * { [v] -> [v mod 2^width] }
2320 * where width is the number of bits used to represent the values
2321 * of the unsigned variable "iv".
2323 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2324 ValueDecl *iv)
2326 isl_ctx *ctx;
2327 isl_val *mod;
2328 isl_aff *aff;
2330 ctx = isl_space_get_ctx(dim);
2331 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2332 mod = isl_val_2exp(mod);
2334 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2335 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2336 aff = isl_aff_mod_val(aff, mod);
2338 return aff;
2341 /* Project out the parameter "id" from "set".
2343 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2344 __isl_keep isl_id *id)
2346 int pos;
2348 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2349 if (pos >= 0)
2350 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2352 return set;
2355 /* Compute the set of parameters for which "set1" is a subset of "set2".
2357 * set1 is a subset of set2 if
2359 * forall i in set1 : i in set2
2361 * or
2363 * not exists i in set1 and i not in set2
2365 * i.e.,
2367 * not exists i in set1 \ set2
2369 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2370 __isl_take isl_set *set2)
2372 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2375 /* Compute the set of parameter values for which "cond" holds
2376 * on the next iteration for each element of "dom".
2378 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2379 * and then compute the set of parameters for which the result is a subset
2380 * of "cond".
2382 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2383 __isl_take isl_set *dom, __isl_take isl_val *inc)
2385 isl_space *space;
2386 isl_aff *aff;
2387 isl_map *next;
2389 space = isl_set_get_space(dom);
2390 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2391 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2392 aff = isl_aff_add_constant_val(aff, inc);
2393 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2395 dom = isl_set_apply(dom, next);
2397 return enforce_subset(dom, cond);
2400 /* Extract the for loop "stmt" as a while loop.
2401 * "iv" is the loop iterator. "init" is the initialization.
2402 * "inc" is the increment.
2404 * That is, the for loop has the form
2406 * for (iv = init; cond; iv += inc)
2407 * body;
2409 * and is treated as
2411 * iv = init;
2412 * while (cond) {
2413 * body;
2414 * iv += inc;
2417 * except that the skips resulting from any continue statements
2418 * in body do not apply to the increment, but are replaced by the skips
2419 * resulting from break statements.
2421 * If "iv" is declared in the for loop, then it is killed before
2422 * and after the loop.
2424 struct pet_scop *PetScan::extract_non_affine_for(ForStmt *stmt, ValueDecl *iv,
2425 __isl_take pet_expr *init, __isl_take pet_expr *inc)
2427 int declared;
2428 int test_nr, stmt_nr;
2429 pet_expr *expr_iv;
2430 struct pet_scop *scop_init, *scop_inc, *scop, *scop_body;
2431 int type_size;
2432 struct pet_array *array;
2433 struct pet_scop *scop_kill;
2435 if (!allow_nested) {
2436 unsupported(stmt);
2437 return NULL;
2440 clear_assignment(assigned_value, iv);
2442 declared = !initialization_assignment(stmt->getInit());
2444 expr_iv = extract_access_expr(iv);
2445 expr_iv = mark_write(expr_iv);
2446 type_size = pet_expr_get_type_size(expr_iv);
2447 init = pet_expr_new_binary(type_size, pet_op_assign, expr_iv, init);
2448 scop_init = extract(init, stmt->getInit()->getSourceRange(), false);
2449 scop_init = pet_scop_prefix(scop_init, declared);
2451 test_nr = n_test++;
2452 stmt_nr = n_stmt++;
2453 scop_body = extract(stmt->getBody());
2454 if (partial) {
2455 pet_scop_free(scop_init);
2456 return scop_body;
2459 expr_iv = extract_access_expr(iv);
2460 expr_iv = mark_write(expr_iv);
2461 type_size = pet_expr_get_type_size(expr_iv);
2462 inc = pet_expr_new_binary(type_size, pet_op_add_assign, expr_iv, inc);
2463 scop_inc = extract(inc, stmt->getInc()->getSourceRange(), false);
2464 if (!scop_inc) {
2465 pet_scop_free(scop_init);
2466 pet_scop_free(scop_body);
2467 return NULL;
2470 scop = extract_while(stmt->getCond(), test_nr, stmt_nr, scop_body,
2471 scop_inc);
2473 scop = pet_scop_prefix(scop, declared + 1);
2474 scop = pet_scop_add_seq(ctx, scop_init, scop);
2476 if (!declared)
2477 return scop;
2479 array = extract_array(ctx, iv, NULL);
2480 if (array)
2481 array->declared = 1;
2482 scop_kill = kill(stmt, array);
2483 scop_kill = pet_scop_prefix(scop_kill, 0);
2484 scop = pet_scop_add_seq(ctx, scop_kill, scop);
2485 scop_kill = kill(stmt, array);
2486 scop_kill = pet_scop_add_array(scop_kill, array);
2487 scop_kill = pet_scop_prefix(scop_kill, 3);
2488 scop = pet_scop_add_seq(ctx, scop, scop_kill);
2490 return scop;
2493 /* Construct a pet_scop for a for statement.
2494 * The for loop is required to be of one of the following forms
2496 * for (i = init; condition; ++i)
2497 * for (i = init; condition; --i)
2498 * for (i = init; condition; i += constant)
2499 * for (i = init; condition; i -= constant)
2501 * The initialization of the for loop should either be an assignment
2502 * of a static affine value to an integer variable, or a declaration
2503 * of such a variable with initialization.
2505 * If the initialization or the increment do not satisfy the above
2506 * conditions, i.e., if the initialization is not static affine
2507 * or the increment is not constant, then the for loop is extracted
2508 * as a while loop instead.
2510 * The condition is allowed to contain nested accesses, provided
2511 * they are not being written to inside the body of the loop.
2512 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2513 * essentially treated as a while loop, with iteration domain
2514 * { [i] : i >= init }.
2516 * We extract a pet_scop for the body and then embed it in a loop with
2517 * iteration domain and schedule
2519 * { [i] : i >= init and condition' }
2520 * { [i] -> [i] }
2522 * or
2524 * { [i] : i <= init and condition' }
2525 * { [i] -> [-i] }
2527 * Where condition' is equal to condition if the latter is
2528 * a simple upper [lower] bound and a condition that is extended
2529 * to apply to all previous iterations otherwise.
2531 * If the condition is non-affine, then we drop the condition from the
2532 * iteration domain and instead create a separate statement
2533 * for evaluating the condition. The body is then filtered to depend
2534 * on the result of the condition evaluating to true on all iterations
2535 * up to the current iteration, while the evaluation the condition itself
2536 * is filtered to depend on the result of the condition evaluating to true
2537 * on all previous iterations.
2538 * The context of the scop representing the body is dropped
2539 * because we don't know how many times the body will be executed,
2540 * if at all.
2542 * If the stride of the loop is not 1, then "i >= init" is replaced by
2544 * (exists a: i = init + stride * a and a >= 0)
2546 * If the loop iterator i is unsigned, then wrapping may occur.
2547 * We therefore use a virtual iterator instead that does not wrap.
2548 * However, the condition in the code applies
2549 * to the wrapped value, so we need to change condition(i)
2550 * into condition([i % 2^width]). Similarly, we replace all accesses
2551 * to the original iterator by the wrapping of the virtual iterator.
2552 * Note that there may be no need to perform this final wrapping
2553 * if the loop condition (after wrapping) satisfies certain conditions.
2554 * However, the is_simple_bound condition is not enough since it doesn't
2555 * check if there even is an upper bound.
2557 * Wrapping on unsigned iterators can be avoided entirely if
2558 * loop condition is simple, the loop iterator is incremented
2559 * [decremented] by one and the last value before wrapping cannot
2560 * possibly satisfy the loop condition.
2562 * Before extracting a pet_scop from the body we remove all
2563 * assignments in assigned_value to variables that are assigned
2564 * somewhere in the body of the loop.
2566 * Valid parameters for a for loop are those for which the initial
2567 * value itself, the increment on each domain iteration and
2568 * the condition on both the initial value and
2569 * the result of incrementing the iterator for each iteration of the domain
2570 * can be evaluated.
2571 * If the loop condition is non-affine, then we only consider validity
2572 * of the initial value.
2574 * If the body contains any break, then we keep track of it in "skip"
2575 * (if the skip condition is affine) or it is handled in scop_add_break
2576 * (if the skip condition is not affine).
2577 * Note that the affine break condition needs to be considered with
2578 * respect to previous iterations in the virtual domain (if any).
2580 * If we were only able to extract part of the body, then simply
2581 * return that part.
2583 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2585 BinaryOperator *ass;
2586 Decl *decl;
2587 Stmt *init;
2588 Expr *lhs, *rhs;
2589 ValueDecl *iv;
2590 isl_local_space *ls;
2591 isl_set *domain;
2592 isl_aff *sched;
2593 isl_set *cond = NULL;
2594 isl_set *skip = NULL;
2595 isl_id *id, *id_test = NULL, *id_break_test;
2596 struct pet_scop *scop, *scop_cond = NULL;
2597 assigned_value_cache cache(assigned_value);
2598 isl_val *inc;
2599 bool is_one;
2600 bool is_unsigned;
2601 bool is_simple;
2602 bool is_virtual;
2603 bool has_affine_break;
2604 bool has_var_break;
2605 isl_aff *wrap = NULL;
2606 isl_pw_aff *pa, *pa_inc, *init_val;
2607 isl_set *valid_init;
2608 isl_set *valid_cond;
2609 isl_set *valid_cond_init;
2610 isl_set *valid_cond_next;
2611 isl_set *valid_inc;
2612 int stmt_id;
2613 pet_expr *pe_init, *pe_inc;
2614 pet_context *pc, *pc_init_val;
2616 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2617 return extract_infinite_for(stmt);
2619 init = stmt->getInit();
2620 if (!init) {
2621 unsupported(stmt);
2622 return NULL;
2624 if ((ass = initialization_assignment(init)) != NULL) {
2625 iv = extract_induction_variable(ass);
2626 if (!iv)
2627 return NULL;
2628 lhs = ass->getLHS();
2629 rhs = ass->getRHS();
2630 } else if ((decl = initialization_declaration(init)) != NULL) {
2631 VarDecl *var = extract_induction_variable(init, decl);
2632 if (!var)
2633 return NULL;
2634 iv = var;
2635 rhs = var->getInit();
2636 lhs = create_DeclRefExpr(var);
2637 } else {
2638 unsupported(stmt->getInit());
2639 return NULL;
2642 id = create_decl_id(ctx, iv);
2644 assigned_value.erase(iv);
2645 clear_assignments clear(assigned_value);
2646 clear.TraverseStmt(stmt->getBody());
2648 pe_init = extract_expr(rhs);
2649 pe_inc = extract_increment(stmt, iv);
2650 pc = convert_assignments(ctx, assigned_value);
2651 pc_init_val = pet_context_copy(pc);
2652 pc_init_val = pet_context_mark_unknown(pc_init_val, isl_id_copy(id));
2653 init_val = pet_expr_extract_affine(pe_init, pc_init_val);
2654 pet_context_free(pc_init_val);
2655 pa_inc = pet_expr_extract_affine(pe_inc, pc);
2656 pet_context_free(pc);
2657 inc = pet_extract_cst(pa_inc);
2658 if (!pe_init || !pe_inc || !inc || isl_val_is_nan(inc) ||
2659 isl_pw_aff_involves_nan(pa_inc) ||
2660 isl_pw_aff_involves_nan(init_val)) {
2661 isl_id_free(id);
2662 isl_val_free(inc);
2663 isl_pw_aff_free(pa_inc);
2664 isl_pw_aff_free(init_val);
2665 if (pe_init && pe_inc && !(pa_inc && !inc))
2666 return extract_non_affine_for(stmt, iv,
2667 pe_init, pe_inc);
2668 pet_expr_free(pe_init);
2669 pet_expr_free(pe_inc);
2670 return NULL;
2672 pet_expr_free(pe_init);
2673 pet_expr_free(pe_inc);
2675 pa = try_extract_nested_condition(stmt->getCond());
2676 if (allow_nested && (!pa || pet_nested_any_in_pw_aff(pa)))
2677 stmt_id = n_stmt++;
2679 scop = extract(stmt->getBody());
2680 if (partial) {
2681 isl_id_free(id);
2682 isl_pw_aff_free(init_val);
2683 isl_pw_aff_free(pa_inc);
2684 isl_pw_aff_free(pa);
2685 isl_val_free(inc);
2686 return scop;
2689 valid_inc = isl_pw_aff_domain(pa_inc);
2691 is_unsigned = iv->getType()->isUnsignedIntegerType();
2693 has_affine_break = scop &&
2694 pet_scop_has_affine_skip(scop, pet_skip_later);
2695 if (has_affine_break)
2696 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2697 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
2698 if (has_var_break)
2699 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
2701 if (pa && !is_nested_allowed(pa, scop)) {
2702 isl_pw_aff_free(pa);
2703 pa = NULL;
2706 if (!allow_nested && !pa)
2707 pa = try_extract_affine_condition(stmt->getCond());
2708 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2709 cond = isl_pw_aff_non_zero_set(pa);
2710 if (allow_nested && !cond) {
2711 isl_multi_pw_aff *test_index;
2712 int save_n_stmt = n_stmt;
2713 test_index = pet_create_test_index(ctx, n_test++);
2714 n_stmt = stmt_id;
2715 scop_cond = extract_non_affine_condition(stmt->getCond(),
2716 n_stmt++, isl_multi_pw_aff_copy(test_index));
2717 n_stmt = save_n_stmt;
2718 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
2719 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
2720 isl_dim_out);
2721 isl_multi_pw_aff_free(test_index);
2722 scop_cond = pet_scop_prefix(scop_cond, 0);
2723 scop = pet_scop_reset_context(scop);
2724 scop = pet_scop_prefix(scop, 1);
2725 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2728 cond = embed(cond, isl_id_copy(id));
2729 skip = embed(skip, isl_id_copy(id));
2730 valid_cond = isl_set_coalesce(valid_cond);
2731 valid_cond = embed(valid_cond, isl_id_copy(id));
2732 valid_inc = embed(valid_inc, isl_id_copy(id));
2733 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
2734 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2736 valid_cond_init = enforce_subset(
2737 isl_map_range(isl_map_from_pw_aff(isl_pw_aff_copy(init_val))),
2738 isl_set_copy(valid_cond));
2739 if (is_one && !is_virtual) {
2740 isl_pw_aff_free(init_val);
2741 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
2742 lhs, rhs, init);
2743 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2744 valid_init = set_project_out_by_id(valid_init, id);
2745 domain = isl_pw_aff_non_zero_set(pa);
2746 } else {
2747 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2748 domain = strided_domain(isl_id_copy(id), init_val,
2749 isl_val_copy(inc));
2752 domain = embed(domain, isl_id_copy(id));
2753 if (is_virtual) {
2754 isl_map *rev_wrap;
2755 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2756 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
2757 rev_wrap = isl_map_reverse(rev_wrap);
2758 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2759 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
2760 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2761 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2763 is_simple = is_simple_bound(cond, inc);
2764 if (!is_simple) {
2765 cond = isl_set_gist(cond, isl_set_copy(domain));
2766 is_simple = is_simple_bound(cond, inc);
2768 if (!is_simple)
2769 cond = valid_for_each_iteration(cond,
2770 isl_set_copy(domain), isl_val_copy(inc));
2771 domain = isl_set_intersect(domain, cond);
2772 if (has_affine_break) {
2773 skip = isl_set_intersect(skip , isl_set_copy(domain));
2774 skip = after(skip, isl_val_sgn(inc));
2775 domain = isl_set_subtract(domain, skip);
2777 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2778 ls = isl_local_space_from_space(isl_set_get_space(domain));
2779 sched = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2780 if (isl_val_is_neg(inc))
2781 sched = isl_aff_neg(sched);
2783 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
2784 isl_val_copy(inc));
2785 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2787 if (!is_virtual)
2788 wrap = identity_aff(domain);
2790 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
2791 isl_aff_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
2792 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
2793 scop = resolve_nested(scop);
2794 if (has_var_break)
2795 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
2796 isl_val_copy(inc));
2797 if (id_test) {
2798 scop = scop_add_while(scop_cond, scop, id_test, domain,
2799 isl_val_copy(inc));
2800 isl_set_free(valid_inc);
2801 } else {
2802 scop = pet_scop_restrict_context(scop, valid_inc);
2803 scop = pet_scop_restrict_context(scop, valid_cond_next);
2804 scop = pet_scop_restrict_context(scop, valid_cond_init);
2805 isl_set_free(domain);
2807 clear_assignment(assigned_value, iv);
2809 isl_val_free(inc);
2811 scop = pet_scop_restrict_context(scop, isl_set_params(valid_init));
2813 return scop;
2816 /* Try and construct a pet_scop corresponding to a compound statement.
2818 * "skip_declarations" is set if we should skip initial declarations
2819 * in the children of the compound statements. This then implies
2820 * that this sequence of children should not be treated as a block
2821 * since the initial statements may be skipped.
2823 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
2825 return extract(stmt->children(), !skip_declarations, skip_declarations);
2828 /* For each nested access parameter in "space",
2829 * construct a corresponding pet_expr, place it in args and
2830 * record its position in "param2pos".
2831 * "n_arg" is the number of elements that are already in args.
2832 * The position recorded in "param2pos" takes this number into account.
2833 * If the pet_expr corresponding to a parameter is identical to
2834 * the pet_expr corresponding to an earlier parameter, then these two
2835 * parameters are made to refer to the same element in args.
2837 * Return the final number of elements in args or -1 if an error has occurred.
2839 int PetScan::extract_nested(__isl_keep isl_space *space,
2840 int n_arg, pet_expr **args, std::map<int,int> &param2pos)
2842 int nparam;
2844 nparam = isl_space_dim(space, isl_dim_param);
2845 for (int i = 0; i < nparam; ++i) {
2846 int j;
2847 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2849 if (!pet_nested_in_id(id)) {
2850 isl_id_free(id);
2851 continue;
2854 args[n_arg] = pet_nested_extract_expr(id);
2855 isl_id_free(id);
2856 if (!args[n_arg])
2857 return -1;
2859 for (j = 0; j < n_arg; ++j)
2860 if (pet_expr_is_equal(args[j], args[n_arg]))
2861 break;
2863 if (j < n_arg) {
2864 pet_expr_free(args[n_arg]);
2865 args[n_arg] = NULL;
2866 param2pos[i] = j;
2867 } else
2868 param2pos[i] = n_arg++;
2871 return n_arg;
2874 /* For each nested access parameter in the access relations in "expr",
2875 * construct a corresponding pet_expr, place it in the arguments of "expr"
2876 * and record its position in "param2pos".
2877 * n is the number of nested access parameters.
2879 __isl_give pet_expr *PetScan::extract_nested(__isl_take pet_expr *expr, int n,
2880 std::map<int,int> &param2pos)
2882 isl_space *space;
2883 int i;
2884 pet_expr **args;
2886 args = isl_calloc_array(ctx, pet_expr *, n);
2887 if (!args)
2888 return pet_expr_free(expr);
2890 space = pet_expr_access_get_parameter_space(expr);
2891 n = extract_nested(space, 0, args, param2pos);
2892 isl_space_free(space);
2894 if (n < 0)
2895 expr = pet_expr_free(expr);
2896 else
2897 expr = pet_expr_set_n_arg(expr, n);
2899 for (i = 0; i < n; ++i)
2900 expr = pet_expr_set_arg(expr, i, args[i]);
2901 free(args);
2903 return expr;
2906 /* Look for parameters in any access relation in "expr" that
2907 * refer to nested accesses. In particular, these are
2908 * parameters with name "__pet_expr".
2910 * If there are any such parameters, then the domain of the index
2911 * expression and the access relation, which is still [] at this point,
2912 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
2913 * (after identifying identical nested accesses).
2915 * This transformation is performed in several steps.
2916 * We first extract the arguments in extract_nested.
2917 * param2pos maps the original parameter position to the position
2918 * of the argument.
2919 * Then we move these parameters to input dimensions.
2920 * t2pos maps the positions of these temporary input dimensions
2921 * to the positions of the corresponding arguments.
2922 * Finally, we express these temporary dimensions in terms of the domain
2923 * [[] -> [t_1,...,t_n]] and precompose index expression and access
2924 * relations with this function.
2926 __isl_give pet_expr *PetScan::resolve_nested(__isl_take pet_expr *expr)
2928 int n;
2929 int nparam;
2930 isl_space *space;
2931 isl_local_space *ls;
2932 isl_aff *aff;
2933 isl_multi_aff *ma;
2934 std::map<int,int> param2pos;
2935 std::map<int,int> t2pos;
2937 if (!expr)
2938 return expr;
2940 n = pet_expr_get_n_arg(expr);
2941 for (int i = 0; i < n; ++i) {
2942 pet_expr *arg;
2943 arg = pet_expr_get_arg(expr, i);
2944 arg = resolve_nested(arg);
2945 expr = pet_expr_set_arg(expr, i, arg);
2948 if (pet_expr_get_type(expr) != pet_expr_access)
2949 return expr;
2951 space = pet_expr_access_get_parameter_space(expr);
2952 n = pet_nested_n_in_space(space);
2953 isl_space_free(space);
2954 if (n == 0)
2955 return expr;
2957 expr = extract_nested(expr, n, param2pos);
2958 if (!expr)
2959 return NULL;
2961 expr = pet_expr_access_align_params(expr);
2962 if (!expr)
2963 return NULL;
2965 n = 0;
2966 space = pet_expr_access_get_parameter_space(expr);
2967 nparam = isl_space_dim(space, isl_dim_param);
2968 for (int i = nparam - 1; i >= 0; --i) {
2969 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2970 if (!pet_nested_in_id(id)) {
2971 isl_id_free(id);
2972 continue;
2975 expr = pet_expr_access_move_dims(expr,
2976 isl_dim_in, n, isl_dim_param, i, 1);
2977 t2pos[n] = param2pos[i];
2978 n++;
2980 isl_id_free(id);
2982 isl_space_free(space);
2984 space = pet_expr_access_get_parameter_space(expr);
2985 space = isl_space_set_from_params(space);
2986 space = isl_space_add_dims(space, isl_dim_set,
2987 pet_expr_get_n_arg(expr));
2988 space = isl_space_wrap(isl_space_from_range(space));
2989 ls = isl_local_space_from_space(isl_space_copy(space));
2990 space = isl_space_from_domain(space);
2991 space = isl_space_add_dims(space, isl_dim_out, n);
2992 ma = isl_multi_aff_zero(space);
2994 for (int i = 0; i < n; ++i) {
2995 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2996 isl_dim_set, t2pos[i]);
2997 ma = isl_multi_aff_set_aff(ma, i, aff);
2999 isl_local_space_free(ls);
3001 expr = pet_expr_access_pullback_multi_aff(expr, ma);
3003 return expr;
3006 /* Return the file offset of the expansion location of "Loc".
3008 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3010 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3013 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3015 /* Return a SourceLocation for the location after the first semicolon
3016 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3017 * call it and also skip trailing spaces and newline.
3019 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3020 const LangOptions &LO)
3022 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3025 #else
3027 /* Return a SourceLocation for the location after the first semicolon
3028 * after "loc". If Lexer::findLocationAfterToken is not available,
3029 * we look in the underlying character data for the first semicolon.
3031 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3032 const LangOptions &LO)
3034 const char *semi;
3035 const char *s = SM.getCharacterData(loc);
3037 semi = strchr(s, ';');
3038 if (!semi)
3039 return SourceLocation();
3040 return loc.getFileLocWithOffset(semi + 1 - s);
3043 #endif
3045 /* If the token at "loc" is the first token on the line, then return
3046 * a location referring to the start of the line.
3047 * Otherwise, return "loc".
3049 * This function is used to extend a scop to the start of the line
3050 * if the first token of the scop is also the first token on the line.
3052 * We look for the first token on the line. If its location is equal to "loc",
3053 * then the latter is the location of the first token on the line.
3055 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3056 SourceManager &SM, const LangOptions &LO)
3058 std::pair<FileID, unsigned> file_offset_pair;
3059 llvm::StringRef file;
3060 const char *pos;
3061 Token tok;
3062 SourceLocation token_loc, line_loc;
3063 int col;
3065 loc = SM.getExpansionLoc(loc);
3066 col = SM.getExpansionColumnNumber(loc);
3067 line_loc = loc.getLocWithOffset(1 - col);
3068 file_offset_pair = SM.getDecomposedLoc(line_loc);
3069 file = SM.getBufferData(file_offset_pair.first, NULL);
3070 pos = file.data() + file_offset_pair.second;
3072 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3073 file.begin(), pos, file.end());
3074 lexer.LexFromRawLexer(tok);
3075 token_loc = tok.getLocation();
3077 if (token_loc == loc)
3078 return line_loc;
3079 else
3080 return loc;
3083 /* Update start and end of "scop" to include the region covered by "range".
3084 * If "skip_semi" is set, then we assume "range" is followed by
3085 * a semicolon and also include this semicolon.
3087 struct pet_scop *PetScan::update_scop_start_end(struct pet_scop *scop,
3088 SourceRange range, bool skip_semi)
3090 SourceLocation loc = range.getBegin();
3091 SourceManager &SM = PP.getSourceManager();
3092 const LangOptions &LO = PP.getLangOpts();
3093 unsigned start, end;
3095 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3096 start = getExpansionOffset(SM, loc);
3097 loc = range.getEnd();
3098 if (skip_semi)
3099 loc = location_after_semi(loc, SM, LO);
3100 else
3101 loc = PP.getLocForEndOfToken(loc);
3102 end = getExpansionOffset(SM, loc);
3104 scop = pet_scop_update_start_end(scop, start, end);
3105 return scop;
3108 /* Convert a top-level pet_expr to a pet_scop with one statement.
3109 * This mainly involves resolving nested expression parameters
3110 * and setting the name of the iteration space.
3111 * The name is given by "label" if it is non-NULL. Otherwise,
3112 * it is of the form S_<n_stmt>.
3113 * start and end of the pet_scop are derived from "range" and "skip_semi".
3114 * In particular, if "skip_semi" is set then the semicolon following "range"
3115 * is also included.
3117 struct pet_scop *PetScan::extract(__isl_take pet_expr *expr, SourceRange range,
3118 bool skip_semi, __isl_take isl_id *label)
3120 struct pet_stmt *ps;
3121 struct pet_scop *scop;
3122 SourceLocation loc = range.getBegin();
3123 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3125 expr = resolve_nested(expr);
3126 ps = pet_stmt_from_pet_expr(line, label, n_stmt++, expr);
3127 scop = pet_scop_from_pet_stmt(ctx, ps);
3129 scop = update_scop_start_end(scop, range, skip_semi);
3130 return scop;
3133 /* Check if we can extract an affine constraint from "expr".
3134 * Return the constraint as an isl_set if we can and NULL otherwise.
3135 * We turn on autodetection so that we won't generate any warnings
3136 * and turn off nesting, so that we won't accept any non-affine constructs.
3138 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3140 isl_pw_aff *cond;
3141 int save_autodetect = options->autodetect;
3142 bool save_nesting = nesting_enabled;
3144 options->autodetect = 1;
3145 nesting_enabled = false;
3147 cond = extract_condition(expr);
3149 options->autodetect = save_autodetect;
3150 nesting_enabled = save_nesting;
3152 return cond;
3155 /* Check whether "expr" is an affine constraint.
3157 bool PetScan::is_affine_condition(Expr *expr)
3159 isl_pw_aff *cond;
3161 cond = try_extract_affine_condition(expr);
3162 isl_pw_aff_free(cond);
3164 return cond != NULL;
3167 /* Check if we can extract a condition from "expr".
3168 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3169 * If allow_nested is set, then the condition may involve parameters
3170 * corresponding to nested accesses.
3171 * We turn on autodetection so that we won't generate any warnings.
3173 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3175 isl_pw_aff *cond;
3176 int save_autodetect = options->autodetect;
3177 bool save_nesting = nesting_enabled;
3179 options->autodetect = 1;
3180 nesting_enabled = allow_nested;
3181 cond = extract_condition(expr);
3183 options->autodetect = save_autodetect;
3184 nesting_enabled = save_nesting;
3186 return cond;
3189 /* If the top-level expression of "stmt" is an assignment, then
3190 * return that assignment as a BinaryOperator.
3191 * Otherwise return NULL.
3193 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3195 BinaryOperator *ass;
3197 if (!stmt)
3198 return NULL;
3199 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3200 return NULL;
3202 ass = cast<BinaryOperator>(stmt);
3203 if(ass->getOpcode() != BO_Assign)
3204 return NULL;
3206 return ass;
3209 /* Check if the given if statement is a conditional assignement
3210 * with a non-affine condition. If so, construct a pet_scop
3211 * corresponding to this conditional assignment. Otherwise return NULL.
3213 * In particular we check if "stmt" is of the form
3215 * if (condition)
3216 * a = f(...);
3217 * else
3218 * a = g(...);
3220 * where a is some array or scalar access.
3221 * The constructed pet_scop then corresponds to the expression
3223 * a = condition ? f(...) : g(...)
3225 * All access relations in f(...) are intersected with condition
3226 * while all access relation in g(...) are intersected with the complement.
3228 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3230 BinaryOperator *ass_then, *ass_else;
3231 pet_expr *write_then, *write_else;
3232 isl_set *cond, *comp;
3233 isl_multi_pw_aff *index;
3234 isl_pw_aff *pa;
3235 int equal;
3236 int type_size;
3237 pet_expr *pe_cond, *pe_then, *pe_else, *pe;
3238 bool save_nesting = nesting_enabled;
3240 if (!options->detect_conditional_assignment)
3241 return NULL;
3243 ass_then = top_assignment_or_null(stmt->getThen());
3244 ass_else = top_assignment_or_null(stmt->getElse());
3246 if (!ass_then || !ass_else)
3247 return NULL;
3249 if (is_affine_condition(stmt->getCond()))
3250 return NULL;
3252 write_then = extract_access_expr(ass_then->getLHS());
3253 write_else = extract_access_expr(ass_else->getLHS());
3255 equal = pet_expr_is_equal(write_then, write_else);
3256 pet_expr_free(write_else);
3257 if (equal < 0 || !equal) {
3258 pet_expr_free(write_then);
3259 return NULL;
3262 nesting_enabled = allow_nested;
3263 pa = extract_condition(stmt->getCond());
3264 nesting_enabled = save_nesting;
3265 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3266 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3267 index = isl_multi_pw_aff_from_pw_aff(pa);
3269 pe_cond = pet_expr_from_index(index);
3271 pe_then = extract_expr(ass_then->getRHS());
3272 pe_then = pet_expr_restrict(pe_then, cond);
3273 pe_else = extract_expr(ass_else->getRHS());
3274 pe_else = pet_expr_restrict(pe_else, comp);
3276 pe = pet_expr_new_ternary(pe_cond, pe_then, pe_else);
3277 write_then = pet_expr_access_set_write(write_then, 1);
3278 write_then = pet_expr_access_set_read(write_then, 0);
3279 type_size = get_type_size(ass_then->getType(), ast_context);
3280 pe = pet_expr_new_binary(type_size, pet_op_assign, write_then, pe);
3281 return extract(pe, stmt->getSourceRange(), false);
3284 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3285 * evaluating "cond" and writing the result to a virtual scalar,
3286 * as expressed by "index".
3288 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond, int stmt_nr,
3289 __isl_take isl_multi_pw_aff *index)
3291 pet_expr *expr, *write;
3292 struct pet_stmt *ps;
3293 SourceLocation loc = cond->getLocStart();
3294 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3296 write = pet_expr_from_index(index);
3297 write = pet_expr_access_set_write(write, 1);
3298 write = pet_expr_access_set_read(write, 0);
3299 expr = extract_expr(cond);
3300 expr = resolve_nested(expr);
3301 expr = pet_expr_new_binary(1, pet_op_assign, write, expr);
3302 ps = pet_stmt_from_pet_expr(line, NULL, stmt_nr, expr);
3303 return pet_scop_from_pet_stmt(ctx, ps);
3306 extern "C" {
3307 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr,
3308 void *user);
3311 /* Precompose the access relation and the index expression associated
3312 * to "expr" with the function pointed to by "user",
3313 * thereby embedding the access relation in the domain of this function.
3314 * The initial domain of the access relation and the index expression
3315 * is the zero-dimensional domain.
3317 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr, void *user)
3319 isl_multi_aff *ma = (isl_multi_aff *) user;
3321 return pet_expr_access_pullback_multi_aff(expr, isl_multi_aff_copy(ma));
3324 /* Precompose all access relations in "expr" with "ma", thereby
3325 * embedding them in the domain of "ma".
3327 static __isl_give pet_expr *embed(__isl_take pet_expr *expr,
3328 __isl_keep isl_multi_aff *ma)
3330 return pet_expr_map_access(expr, &embed_access, ma);
3333 /* For each nested access parameter in the domain of "stmt",
3334 * construct a corresponding pet_expr, place it before the original
3335 * elements in stmt->args and record its position in "param2pos".
3336 * n is the number of nested access parameters.
3338 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3339 std::map<int,int> &param2pos)
3341 int i;
3342 isl_space *space;
3343 int n_arg;
3344 pet_expr **args;
3346 n_arg = stmt->n_arg;
3347 args = isl_calloc_array(ctx, pet_expr *, n + n_arg);
3348 if (!args)
3349 goto error;
3351 space = isl_set_get_space(stmt->domain);
3352 n_arg = extract_nested(space, 0, args, param2pos);
3353 isl_space_free(space);
3355 if (n_arg < 0)
3356 goto error;
3358 for (i = 0; i < stmt->n_arg; ++i)
3359 args[n_arg + i] = stmt->args[i];
3360 free(stmt->args);
3361 stmt->args = args;
3362 stmt->n_arg += n_arg;
3364 return stmt;
3365 error:
3366 if (args) {
3367 for (i = 0; i < n; ++i)
3368 pet_expr_free(args[i]);
3369 free(args);
3371 pet_stmt_free(stmt);
3372 return NULL;
3375 /* Check whether any of the arguments i of "stmt" starting at position "n"
3376 * is equal to one of the first "n" arguments j.
3377 * If so, combine the constraints on arguments i and j and remove
3378 * argument i.
3380 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3382 int i, j;
3383 isl_map *map;
3385 if (!stmt)
3386 return NULL;
3387 if (n == 0)
3388 return stmt;
3389 if (n == stmt->n_arg)
3390 return stmt;
3392 map = isl_set_unwrap(stmt->domain);
3394 for (i = stmt->n_arg - 1; i >= n; --i) {
3395 for (j = 0; j < n; ++j)
3396 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3397 break;
3398 if (j >= n)
3399 continue;
3401 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3402 map = isl_map_project_out(map, isl_dim_out, i, 1);
3404 pet_expr_free(stmt->args[i]);
3405 for (j = i; j + 1 < stmt->n_arg; ++j)
3406 stmt->args[j] = stmt->args[j + 1];
3407 stmt->n_arg--;
3410 stmt->domain = isl_map_wrap(map);
3411 if (!stmt->domain)
3412 goto error;
3413 return stmt;
3414 error:
3415 pet_stmt_free(stmt);
3416 return NULL;
3419 /* Look for parameters in the iteration domain of "stmt" that
3420 * refer to nested accesses. In particular, these are
3421 * parameters with name "__pet_expr".
3423 * If there are any such parameters, then as many extra variables
3424 * (after identifying identical nested accesses) are inserted in the
3425 * range of the map wrapped inside the domain, before the original variables.
3426 * If the original domain is not a wrapped map, then a new wrapped
3427 * map is created with zero output dimensions.
3428 * The parameters are then equated to the corresponding output dimensions
3429 * and subsequently projected out, from the iteration domain,
3430 * the schedule and the access relations.
3431 * For each of the output dimensions, a corresponding argument
3432 * expression is inserted. Initially they are created with
3433 * a zero-dimensional domain, so they have to be embedded
3434 * in the current iteration domain.
3435 * param2pos maps the position of the parameter to the position
3436 * of the corresponding output dimension in the wrapped map.
3438 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3440 int n;
3441 int nparam;
3442 unsigned n_arg;
3443 isl_map *map;
3444 isl_space *space;
3445 isl_multi_aff *ma;
3446 std::map<int,int> param2pos;
3448 if (!stmt)
3449 return NULL;
3451 n = pet_nested_n_in_set(stmt->domain);
3452 if (n == 0)
3453 return stmt;
3455 n_arg = stmt->n_arg;
3456 stmt = extract_nested(stmt, n, param2pos);
3457 if (!stmt)
3458 return NULL;
3460 n = stmt->n_arg - n_arg;
3461 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3462 if (isl_set_is_wrapping(stmt->domain))
3463 map = isl_set_unwrap(stmt->domain);
3464 else
3465 map = isl_map_from_domain(stmt->domain);
3466 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3468 for (int i = nparam - 1; i >= 0; --i) {
3469 isl_id *id;
3471 if (!pet_nested_in_map(map, i))
3472 continue;
3474 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
3475 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3476 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3477 param2pos[i]);
3478 map = isl_map_project_out(map, isl_dim_param, i, 1);
3481 stmt->domain = isl_map_wrap(map);
3483 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
3484 space = isl_space_from_domain(isl_space_domain(space));
3485 ma = isl_multi_aff_zero(space);
3486 for (int pos = 0; pos < n; ++pos)
3487 stmt->args[pos] = embed(stmt->args[pos], ma);
3488 isl_multi_aff_free(ma);
3490 stmt = pet_stmt_remove_nested_parameters(stmt);
3491 stmt = remove_duplicate_arguments(stmt, n);
3493 return stmt;
3496 /* For each statement in "scop", move the parameters that correspond
3497 * to nested access into the ranges of the domains and create
3498 * corresponding argument expressions.
3500 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3502 if (!scop)
3503 return NULL;
3505 for (int i = 0; i < scop->n_stmt; ++i) {
3506 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3507 if (!scop->stmts[i])
3508 goto error;
3511 return scop;
3512 error:
3513 pet_scop_free(scop);
3514 return NULL;
3517 /* Given an access expression "expr", is the variable accessed by
3518 * "expr" assigned anywhere inside "scop"?
3520 static bool is_assigned(__isl_keep pet_expr *expr, pet_scop *scop)
3522 bool assigned = false;
3523 isl_id *id;
3525 id = pet_expr_access_get_id(expr);
3526 assigned = pet_scop_writes(scop, id);
3527 isl_id_free(id);
3529 return assigned;
3532 /* Are all nested access parameters in "pa" allowed given "scop".
3533 * In particular, is none of them written by anywhere inside "scop".
3535 * If "scop" has any skip conditions, then no nested access parameters
3536 * are allowed. In particular, if there is any nested access in a guard
3537 * for a piece of code containing a "continue", then we want to introduce
3538 * a separate statement for evaluating this guard so that we can express
3539 * that the result is false for all previous iterations.
3541 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3543 int nparam;
3545 if (!scop)
3546 return true;
3548 if (!pet_nested_any_in_pw_aff(pa))
3549 return true;
3551 if (pet_scop_has_skip(scop, pet_skip_now))
3552 return false;
3554 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3555 for (int i = 0; i < nparam; ++i) {
3556 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3557 pet_expr *expr;
3558 bool allowed;
3560 if (!pet_nested_in_id(id)) {
3561 isl_id_free(id);
3562 continue;
3565 expr = pet_nested_extract_expr(id);
3566 allowed = pet_expr_get_type(expr) == pet_expr_access &&
3567 !is_assigned(expr, scop);
3569 pet_expr_free(expr);
3570 isl_id_free(id);
3572 if (!allowed)
3573 return false;
3576 return true;
3579 /* Construct a pet_scop for a non-affine if statement.
3581 * We create a separate statement that writes the result
3582 * of the non-affine condition to a virtual scalar.
3583 * A constraint requiring the value of this virtual scalar to be one
3584 * is added to the iteration domains of the then branch.
3585 * Similarly, a constraint requiring the value of this virtual scalar
3586 * to be zero is added to the iteration domains of the else branch, if any.
3587 * We adjust the schedules to ensure that the virtual scalar is written
3588 * before it is read.
3590 * If there are any breaks or continues in the then and/or else
3591 * branches, then we may have to compute a new skip condition.
3592 * This is handled using a pet_skip_info object.
3593 * On initialization, the object checks if skip conditions need
3594 * to be computed. If so, it does so in pet_skip_info_if_extract_index and
3595 * adds them in pet_skip_info_if_add.
3597 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
3598 struct pet_scop *scop_then, struct pet_scop *scop_else,
3599 bool have_else, int stmt_id)
3601 struct pet_scop *scop;
3602 isl_multi_pw_aff *test_index;
3603 int int_size;
3604 int save_n_stmt = n_stmt;
3606 test_index = pet_create_test_index(ctx, n_test++);
3607 n_stmt = stmt_id;
3608 scop = extract_non_affine_condition(cond, n_stmt++,
3609 isl_multi_pw_aff_copy(test_index));
3610 n_stmt = save_n_stmt;
3611 scop = scop_add_array(scop, test_index, ast_context);
3613 pet_skip_info skip;
3614 pet_skip_info_if_init(&skip, ctx, scop_then, scop_else, have_else, 0);
3615 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
3616 pet_skip_info_if_extract_index(&skip, test_index, int_size,
3617 &n_stmt, &n_test);
3619 scop = pet_scop_prefix(scop, 0);
3620 scop_then = pet_scop_prefix(scop_then, 1);
3621 scop_then = pet_scop_filter(scop_then,
3622 isl_multi_pw_aff_copy(test_index), 1);
3623 if (have_else) {
3624 scop_else = pet_scop_prefix(scop_else, 1);
3625 scop_else = pet_scop_filter(scop_else, test_index, 0);
3626 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
3627 } else
3628 isl_multi_pw_aff_free(test_index);
3630 scop = pet_scop_add_seq(ctx, scop, scop_then);
3632 scop = pet_skip_info_if_add(&skip, scop, 2);
3634 return scop;
3637 /* Construct a pet_scop for an if statement.
3639 * If the condition fits the pattern of a conditional assignment,
3640 * then it is handled by extract_conditional_assignment.
3641 * Otherwise, we do the following.
3643 * If the condition is affine, then the condition is added
3644 * to the iteration domains of the then branch, while the
3645 * opposite of the condition in added to the iteration domains
3646 * of the else branch, if any.
3647 * We allow the condition to be dynamic, i.e., to refer to
3648 * scalars or array elements that may be written to outside
3649 * of the given if statement. These nested accesses are then represented
3650 * as output dimensions in the wrapping iteration domain.
3651 * If it is also written _inside_ the then or else branch, then
3652 * we treat the condition as non-affine.
3653 * As explained in extract_non_affine_if, this will introduce
3654 * an extra statement.
3655 * For aesthetic reasons, we want this statement to have a statement
3656 * number that is lower than those of the then and else branches.
3657 * In order to evaluate if we will need such a statement, however, we
3658 * first construct scops for the then and else branches.
3659 * We therefore reserve a statement number if we might have to
3660 * introduce such an extra statement.
3662 * If the condition is not affine, then the scop is created in
3663 * extract_non_affine_if.
3665 * If there are any breaks or continues in the then and/or else
3666 * branches, then we may have to compute a new skip condition.
3667 * This is handled using a pet_skip_info object.
3668 * On initialization, the object checks if skip conditions need
3669 * to be computed. If so, it does so in pet_skip_info_if_extract_cond and
3670 * adds them in pet_skip_info_if_add.
3672 struct pet_scop *PetScan::extract(IfStmt *stmt)
3674 struct pet_scop *scop_then, *scop_else = NULL, *scop;
3675 isl_pw_aff *cond;
3676 int stmt_id;
3677 int int_size;
3678 isl_set *set;
3679 isl_set *valid;
3681 clear_assignments clear(assigned_value);
3682 clear.TraverseStmt(stmt->getThen());
3683 if (stmt->getElse())
3684 clear.TraverseStmt(stmt->getElse());
3686 scop = extract_conditional_assignment(stmt);
3687 if (scop)
3688 return scop;
3690 cond = try_extract_nested_condition(stmt->getCond());
3691 if (allow_nested && (!cond || pet_nested_any_in_pw_aff(cond)))
3692 stmt_id = n_stmt++;
3695 assigned_value_cache cache(assigned_value);
3696 scop_then = extract(stmt->getThen());
3699 if (stmt->getElse()) {
3700 assigned_value_cache cache(assigned_value);
3701 scop_else = extract(stmt->getElse());
3702 if (options->autodetect) {
3703 if (scop_then && !scop_else) {
3704 partial = true;
3705 isl_pw_aff_free(cond);
3706 return scop_then;
3708 if (!scop_then && scop_else) {
3709 partial = true;
3710 isl_pw_aff_free(cond);
3711 return scop_else;
3716 if (cond &&
3717 (!is_nested_allowed(cond, scop_then) ||
3718 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
3719 isl_pw_aff_free(cond);
3720 cond = NULL;
3722 if (allow_nested && !cond)
3723 return extract_non_affine_if(stmt->getCond(), scop_then,
3724 scop_else, stmt->getElse(), stmt_id);
3726 if (!cond)
3727 cond = extract_condition(stmt->getCond());
3729 pet_skip_info skip;
3730 pet_skip_info_if_init(&skip, ctx, scop_then, scop_else,
3731 stmt->getElse() != NULL, 1);
3732 pet_skip_info_if_extract_cond(&skip, cond, int_size, &n_stmt, &n_test);
3734 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
3735 set = isl_pw_aff_non_zero_set(cond);
3736 scop = pet_scop_restrict(scop_then, isl_set_params(isl_set_copy(set)));
3738 if (stmt->getElse()) {
3739 set = isl_set_subtract(isl_set_copy(valid), set);
3740 scop_else = pet_scop_restrict(scop_else, isl_set_params(set));
3741 scop = pet_scop_add_par(ctx, scop, scop_else);
3742 } else
3743 isl_set_free(set);
3744 scop = resolve_nested(scop);
3745 scop = pet_scop_restrict_context(scop, isl_set_params(valid));
3747 if (pet_skip_info_has_skip(&skip))
3748 scop = pet_scop_prefix(scop, 0);
3749 scop = pet_skip_info_if_add(&skip, scop, 1);
3751 return scop;
3754 /* Try and construct a pet_scop for a label statement.
3755 * We currently only allow labels on expression statements.
3757 struct pet_scop *PetScan::extract(LabelStmt *stmt)
3759 isl_id *label;
3760 Stmt *sub;
3762 sub = stmt->getSubStmt();
3763 if (!isa<Expr>(sub)) {
3764 unsupported(stmt);
3765 return NULL;
3768 label = isl_id_alloc(ctx, stmt->getName(), NULL);
3770 return extract(extract_expr(cast<Expr>(sub)), stmt->getSourceRange(),
3771 true, label);
3774 /* Return a one-dimensional multi piecewise affine expression that is equal
3775 * to the constant 1 and is defined over a zero-dimensional domain.
3777 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
3779 isl_space *space;
3780 isl_local_space *ls;
3781 isl_aff *aff;
3783 space = isl_space_set_alloc(ctx, 0, 0);
3784 ls = isl_local_space_from_space(space);
3785 aff = isl_aff_zero_on_domain(ls);
3786 aff = isl_aff_set_constant_si(aff, 1);
3788 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
3791 /* Construct a pet_scop for a continue statement.
3793 * We simply create an empty scop with a universal pet_skip_now
3794 * skip condition. This skip condition will then be taken into
3795 * account by the enclosing loop construct, possibly after
3796 * being incorporated into outer skip conditions.
3798 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
3800 pet_scop *scop;
3802 scop = pet_scop_empty(ctx);
3803 if (!scop)
3804 return NULL;
3806 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
3808 return scop;
3811 /* Construct a pet_scop for a break statement.
3813 * We simply create an empty scop with both a universal pet_skip_now
3814 * skip condition and a universal pet_skip_later skip condition.
3815 * These skip conditions will then be taken into
3816 * account by the enclosing loop construct, possibly after
3817 * being incorporated into outer skip conditions.
3819 struct pet_scop *PetScan::extract(BreakStmt *stmt)
3821 pet_scop *scop;
3822 isl_multi_pw_aff *skip;
3824 scop = pet_scop_empty(ctx);
3825 if (!scop)
3826 return NULL;
3828 skip = one_mpa(ctx);
3829 scop = pet_scop_set_skip(scop, pet_skip_now,
3830 isl_multi_pw_aff_copy(skip));
3831 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
3833 return scop;
3836 /* Try and construct a pet_scop corresponding to "stmt".
3838 * If "stmt" is a compound statement, then "skip_declarations"
3839 * indicates whether we should skip initial declarations in the
3840 * compound statement.
3842 * If the constructed pet_scop is not a (possibly) partial representation
3843 * of "stmt", we update start and end of the pet_scop to those of "stmt".
3844 * In particular, if skip_declarations is set, then we may have skipped
3845 * declarations inside "stmt" and so the pet_scop may not represent
3846 * the entire "stmt".
3847 * Note that this function may be called with "stmt" referring to the entire
3848 * body of the function, including the outer braces. In such cases,
3849 * skip_declarations will be set and the braces will not be taken into
3850 * account in scop->start and scop->end.
3852 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
3854 struct pet_scop *scop;
3856 if (isa<Expr>(stmt))
3857 return extract(extract_expr(cast<Expr>(stmt)),
3858 stmt->getSourceRange(), true);
3860 switch (stmt->getStmtClass()) {
3861 case Stmt::WhileStmtClass:
3862 scop = extract(cast<WhileStmt>(stmt));
3863 break;
3864 case Stmt::ForStmtClass:
3865 scop = extract_for(cast<ForStmt>(stmt));
3866 break;
3867 case Stmt::IfStmtClass:
3868 scop = extract(cast<IfStmt>(stmt));
3869 break;
3870 case Stmt::CompoundStmtClass:
3871 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
3872 break;
3873 case Stmt::LabelStmtClass:
3874 scop = extract(cast<LabelStmt>(stmt));
3875 break;
3876 case Stmt::ContinueStmtClass:
3877 scop = extract(cast<ContinueStmt>(stmt));
3878 break;
3879 case Stmt::BreakStmtClass:
3880 scop = extract(cast<BreakStmt>(stmt));
3881 break;
3882 case Stmt::DeclStmtClass:
3883 scop = extract(cast<DeclStmt>(stmt));
3884 break;
3885 default:
3886 unsupported(stmt);
3887 return NULL;
3890 if (partial || skip_declarations)
3891 return scop;
3893 scop = update_scop_start_end(scop, stmt->getSourceRange(), false);
3895 return scop;
3898 /* Extract a clone of the kill statement in "scop".
3899 * "scop" is expected to have been created from a DeclStmt
3900 * and should have the kill as its first statement.
3902 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
3904 pet_expr *kill;
3905 struct pet_stmt *stmt;
3906 isl_multi_pw_aff *index;
3907 isl_map *access;
3908 pet_expr *arg;
3910 if (!scop)
3911 return NULL;
3912 if (scop->n_stmt < 1)
3913 isl_die(ctx, isl_error_internal,
3914 "expecting at least one statement", return NULL);
3915 stmt = scop->stmts[0];
3916 if (!pet_stmt_is_kill(stmt))
3917 isl_die(ctx, isl_error_internal,
3918 "expecting kill statement", return NULL);
3920 arg = pet_expr_get_arg(stmt->body, 0);
3921 index = pet_expr_access_get_index(arg);
3922 access = pet_expr_access_get_access(arg);
3923 pet_expr_free(arg);
3924 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
3925 access = isl_map_reset_tuple_id(access, isl_dim_in);
3926 kill = pet_expr_kill_from_access_and_index(access, index);
3927 return pet_stmt_from_pet_expr(stmt->line, NULL, n_stmt++, kill);
3930 /* Mark all arrays in "scop" as being exposed.
3932 static struct pet_scop *mark_exposed(struct pet_scop *scop)
3934 if (!scop)
3935 return NULL;
3936 for (int i = 0; i < scop->n_array; ++i)
3937 scop->arrays[i]->exposed = 1;
3938 return scop;
3941 /* Try and construct a pet_scop corresponding to (part of)
3942 * a sequence of statements.
3944 * "block" is set if the sequence respresents the children of
3945 * a compound statement.
3946 * "skip_declarations" is set if we should skip initial declarations
3947 * in the sequence of statements.
3949 * After extracting a statement, we update "assigned_value"
3950 * based on the top-level assignments in the statement
3951 * so that we can exploit them in subsequent statements in the same block.
3953 * If there are any breaks or continues in the individual statements,
3954 * then we may have to compute a new skip condition.
3955 * This is handled using a pet_skip_info object.
3956 * On initialization, the object checks if skip conditions need
3957 * to be computed. If so, it does so in pet_skip_info_seq_extract and
3958 * adds them in pet_skip_info_seq_add.
3960 * If "block" is set, then we need to insert kill statements at
3961 * the end of the block for any array that has been declared by
3962 * one of the statements in the sequence. Each of these declarations
3963 * results in the construction of a kill statement at the place
3964 * of the declaration, so we simply collect duplicates of
3965 * those kill statements and append these duplicates to the constructed scop.
3967 * If "block" is not set, then any array declared by one of the statements
3968 * in the sequence is marked as being exposed.
3970 * If autodetect is set, then we allow the extraction of only a subrange
3971 * of the sequence of statements. However, if there is at least one statement
3972 * for which we could not construct a scop and the final range contains
3973 * either no statements or at least one kill, then we discard the entire
3974 * range.
3976 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
3977 bool skip_declarations)
3979 pet_scop *scop;
3980 StmtIterator i;
3981 int int_size;
3982 int j;
3983 bool partial_range = false;
3984 set<struct pet_stmt *> kills;
3985 set<struct pet_stmt *>::iterator it;
3987 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
3989 scop = pet_scop_empty(ctx);
3990 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
3991 Stmt *child = *i;
3992 struct pet_scop *scop_i;
3994 if (scop->n_stmt == 0 && skip_declarations &&
3995 child->getStmtClass() == Stmt::DeclStmtClass)
3996 continue;
3998 scop_i = extract(child);
3999 if (scop->n_stmt != 0 && partial) {
4000 pet_scop_free(scop_i);
4001 break;
4003 handle_writes(scop_i);
4004 pet_skip_info skip;
4005 pet_skip_info_seq_init(&skip, ctx, scop, scop_i);
4006 pet_skip_info_seq_extract(&skip, int_size, &n_stmt, &n_test);
4007 if (pet_skip_info_has_skip(&skip))
4008 scop_i = pet_scop_prefix(scop_i, 0);
4009 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4010 if (block)
4011 kills.insert(extract_kill(scop_i));
4012 else
4013 scop_i = mark_exposed(scop_i);
4015 scop_i = pet_scop_prefix(scop_i, j);
4016 if (options->autodetect) {
4017 if (scop_i)
4018 scop = pet_scop_add_seq(ctx, scop, scop_i);
4019 else
4020 partial_range = true;
4021 if (scop->n_stmt != 0 && !scop_i)
4022 partial = true;
4023 } else {
4024 scop = pet_scop_add_seq(ctx, scop, scop_i);
4027 scop = pet_skip_info_seq_add(&skip, scop, j);
4029 if (partial || !scop)
4030 break;
4033 for (it = kills.begin(); it != kills.end(); ++it) {
4034 pet_scop *scop_j;
4035 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4036 scop_j = pet_scop_prefix(scop_j, j);
4037 scop = pet_scop_add_seq(ctx, scop, scop_j);
4040 if (scop && partial_range) {
4041 if (scop->n_stmt == 0 || kills.size() != 0) {
4042 pet_scop_free(scop);
4043 return NULL;
4045 partial = true;
4048 return scop;
4051 /* Check if the scop marked by the user is exactly this Stmt
4052 * or part of this Stmt.
4053 * If so, return a pet_scop corresponding to the marked region.
4054 * Otherwise, return NULL.
4056 struct pet_scop *PetScan::scan(Stmt *stmt)
4058 SourceManager &SM = PP.getSourceManager();
4059 unsigned start_off, end_off;
4061 start_off = getExpansionOffset(SM, stmt->getLocStart());
4062 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4064 if (start_off > loc.end)
4065 return NULL;
4066 if (end_off < loc.start)
4067 return NULL;
4068 if (start_off >= loc.start && end_off <= loc.end) {
4069 return extract(stmt);
4072 StmtIterator start;
4073 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4074 Stmt *child = *start;
4075 if (!child)
4076 continue;
4077 start_off = getExpansionOffset(SM, child->getLocStart());
4078 end_off = getExpansionOffset(SM, child->getLocEnd());
4079 if (start_off < loc.start && end_off >= loc.end)
4080 return scan(child);
4081 if (start_off >= loc.start)
4082 break;
4085 StmtIterator end;
4086 for (end = start; end != stmt->child_end(); ++end) {
4087 Stmt *child = *end;
4088 start_off = SM.getFileOffset(child->getLocStart());
4089 if (start_off >= loc.end)
4090 break;
4093 return extract(StmtRange(start, end), false, false);
4096 /* Set the size of index "pos" of "array" to "size".
4097 * In particular, add a constraint of the form
4099 * i_pos < size
4101 * to array->extent and a constraint of the form
4103 * size >= 0
4105 * to array->context.
4107 static struct pet_array *update_size(struct pet_array *array, int pos,
4108 __isl_take isl_pw_aff *size)
4110 isl_set *valid;
4111 isl_set *univ;
4112 isl_set *bound;
4113 isl_space *dim;
4114 isl_aff *aff;
4115 isl_pw_aff *index;
4116 isl_id *id;
4118 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
4119 array->context = isl_set_intersect(array->context, valid);
4121 dim = isl_set_get_space(array->extent);
4122 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
4123 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
4124 univ = isl_set_universe(isl_aff_get_domain_space(aff));
4125 index = isl_pw_aff_alloc(univ, aff);
4127 size = isl_pw_aff_add_dims(size, isl_dim_in,
4128 isl_set_dim(array->extent, isl_dim_set));
4129 id = isl_set_get_tuple_id(array->extent);
4130 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
4131 bound = isl_pw_aff_lt_set(index, size);
4133 array->extent = isl_set_intersect(array->extent, bound);
4135 if (!array->context || !array->extent)
4136 goto error;
4138 return array;
4139 error:
4140 pet_array_free(array);
4141 return NULL;
4144 /* Figure out the size of the array at position "pos" and all
4145 * subsequent positions from "type" and update "array" accordingly.
4147 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
4148 const Type *type, int pos)
4150 const ArrayType *atype;
4151 isl_pw_aff *size;
4153 if (!array)
4154 return NULL;
4156 if (type->isPointerType()) {
4157 type = type->getPointeeType().getTypePtr();
4158 return set_upper_bounds(array, type, pos + 1);
4160 if (!type->isArrayType())
4161 return array;
4163 type = type->getCanonicalTypeInternal().getTypePtr();
4164 atype = cast<ArrayType>(type);
4166 if (type->isConstantArrayType()) {
4167 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
4168 size = extract_affine(ca->getSize());
4169 array = update_size(array, pos, size);
4170 } else if (type->isVariableArrayType()) {
4171 const VariableArrayType *vla = cast<VariableArrayType>(atype);
4172 size = extract_affine(vla->getSizeExpr());
4173 array = update_size(array, pos, size);
4176 type = atype->getElementType().getTypePtr();
4178 return set_upper_bounds(array, type, pos + 1);
4181 /* Is "T" the type of a variable length array with static size?
4183 static bool is_vla_with_static_size(QualType T)
4185 const VariableArrayType *vlatype;
4187 if (!T->isVariableArrayType())
4188 return false;
4189 vlatype = cast<VariableArrayType>(T);
4190 return vlatype->getSizeModifier() == VariableArrayType::Static;
4193 /* Return the type of "decl" as an array.
4195 * In particular, if "decl" is a parameter declaration that
4196 * is a variable length array with a static size, then
4197 * return the original type (i.e., the variable length array).
4198 * Otherwise, return the type of decl.
4200 static QualType get_array_type(ValueDecl *decl)
4202 ParmVarDecl *parm;
4203 QualType T;
4205 parm = dyn_cast<ParmVarDecl>(decl);
4206 if (!parm)
4207 return decl->getType();
4209 T = parm->getOriginalType();
4210 if (!is_vla_with_static_size(T))
4211 return decl->getType();
4212 return T;
4215 /* Does "decl" have definition that we can keep track of in a pet_type?
4217 static bool has_printable_definition(RecordDecl *decl)
4219 if (!decl->getDeclName())
4220 return false;
4221 return decl->getLexicalDeclContext() == decl->getDeclContext();
4224 /* Construct and return a pet_array corresponding to the variable "decl".
4225 * In particular, initialize array->extent to
4227 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4229 * and then call set_upper_bounds to set the upper bounds on the indices
4230 * based on the type of the variable.
4232 * If the base type is that of a record with a top-level definition and
4233 * if "types" is not null, then the RecordDecl corresponding to the type
4234 * is added to "types".
4236 * If the base type is that of a record with no top-level definition,
4237 * then we replace it by "<subfield>".
4239 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
4240 lex_recorddecl_set *types)
4242 struct pet_array *array;
4243 QualType qt = get_array_type(decl);
4244 const Type *type = qt.getTypePtr();
4245 int depth = array_depth(type);
4246 QualType base = pet_clang_base_type(qt);
4247 string name;
4248 isl_id *id;
4249 isl_space *dim;
4251 array = isl_calloc_type(ctx, struct pet_array);
4252 if (!array)
4253 return NULL;
4255 id = create_decl_id(ctx, decl);
4256 dim = isl_space_set_alloc(ctx, 0, depth);
4257 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
4259 array->extent = isl_set_nat_universe(dim);
4261 dim = isl_space_params_alloc(ctx, 0);
4262 array->context = isl_set_universe(dim);
4264 array = set_upper_bounds(array, type, 0);
4265 if (!array)
4266 return NULL;
4268 name = base.getAsString();
4270 if (types && base->isRecordType()) {
4271 RecordDecl *decl = pet_clang_record_decl(base);
4272 if (has_printable_definition(decl))
4273 types->insert(decl);
4274 else
4275 name = "<subfield>";
4278 array->element_type = strdup(name.c_str());
4279 array->element_is_record = base->isRecordType();
4280 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
4282 return array;
4285 /* Construct and return a pet_array corresponding to the sequence
4286 * of declarations "decls".
4287 * If the sequence contains a single declaration, then it corresponds
4288 * to a simple array access. Otherwise, it corresponds to a member access,
4289 * with the declaration for the substructure following that of the containing
4290 * structure in the sequence of declarations.
4291 * We start with the outermost substructure and then combine it with
4292 * information from the inner structures.
4294 * Additionally, keep track of all required types in "types".
4296 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
4297 vector<ValueDecl *> decls, lex_recorddecl_set *types)
4299 struct pet_array *array;
4300 vector<ValueDecl *>::iterator it;
4302 it = decls.begin();
4304 array = extract_array(ctx, *it, types);
4306 for (++it; it != decls.end(); ++it) {
4307 struct pet_array *parent;
4308 const char *base_name, *field_name;
4309 char *product_name;
4311 parent = array;
4312 array = extract_array(ctx, *it, types);
4313 if (!array)
4314 return pet_array_free(parent);
4316 base_name = isl_set_get_tuple_name(parent->extent);
4317 field_name = isl_set_get_tuple_name(array->extent);
4318 product_name = member_access_name(ctx, base_name, field_name);
4320 array->extent = isl_set_product(isl_set_copy(parent->extent),
4321 array->extent);
4322 if (product_name)
4323 array->extent = isl_set_set_tuple_name(array->extent,
4324 product_name);
4325 array->context = isl_set_intersect(array->context,
4326 isl_set_copy(parent->context));
4328 pet_array_free(parent);
4329 free(product_name);
4331 if (!array->extent || !array->context || !product_name)
4332 return pet_array_free(array);
4335 return array;
4338 /* Add a pet_type corresponding to "decl" to "scop, provided
4339 * it is a member of "types" and it has not been added before
4340 * (i.e., it is not a member of "types_done".
4342 * Since we want the user to be able to print the types
4343 * in the order in which they appear in the scop, we need to
4344 * make sure that types of fields in a structure appear before
4345 * that structure. We therefore call ourselves recursively
4346 * on the types of all record subfields.
4348 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
4349 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
4350 lex_recorddecl_set &types_done)
4352 string s;
4353 llvm::raw_string_ostream S(s);
4354 RecordDecl::field_iterator it;
4356 if (types.find(decl) == types.end())
4357 return scop;
4358 if (types_done.find(decl) != types_done.end())
4359 return scop;
4361 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
4362 RecordDecl *record;
4363 QualType type = it->getType();
4365 if (!type->isRecordType())
4366 continue;
4367 record = pet_clang_record_decl(type);
4368 scop = add_type(ctx, scop, record, PP, types, types_done);
4371 if (strlen(decl->getName().str().c_str()) == 0)
4372 return scop;
4374 decl->print(S, PrintingPolicy(PP.getLangOpts()));
4375 S.str();
4377 scop->types[scop->n_type] = pet_type_alloc(ctx,
4378 decl->getName().str().c_str(), s.c_str());
4379 if (!scop->types[scop->n_type])
4380 return pet_scop_free(scop);
4382 types_done.insert(decl);
4384 scop->n_type++;
4386 return scop;
4389 /* Construct a list of pet_arrays, one for each array (or scalar)
4390 * accessed inside "scop", add this list to "scop" and return the result.
4392 * The context of "scop" is updated with the intersection of
4393 * the contexts of all arrays, i.e., constraints on the parameters
4394 * that ensure that the arrays have a valid (non-negative) size.
4396 * If the any of the extracted arrays refers to a member access,
4397 * then also add the required types to "scop".
4399 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
4401 int i;
4402 array_desc_set arrays;
4403 array_desc_set::iterator it;
4404 lex_recorddecl_set types;
4405 lex_recorddecl_set types_done;
4406 lex_recorddecl_set::iterator types_it;
4407 int n_array;
4408 struct pet_array **scop_arrays;
4410 if (!scop)
4411 return NULL;
4413 pet_scop_collect_arrays(scop, arrays);
4414 if (arrays.size() == 0)
4415 return scop;
4417 n_array = scop->n_array;
4419 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
4420 n_array + arrays.size());
4421 if (!scop_arrays)
4422 goto error;
4423 scop->arrays = scop_arrays;
4425 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
4426 struct pet_array *array;
4427 array = extract_array(ctx, *it, &types);
4428 scop->arrays[n_array + i] = array;
4429 if (!scop->arrays[n_array + i])
4430 goto error;
4431 scop->n_array++;
4432 scop->context = isl_set_intersect(scop->context,
4433 isl_set_copy(array->context));
4434 if (!scop->context)
4435 goto error;
4438 if (types.size() == 0)
4439 return scop;
4441 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
4442 if (!scop->types)
4443 goto error;
4445 for (types_it = types.begin(); types_it != types.end(); ++types_it)
4446 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
4448 return scop;
4449 error:
4450 pet_scop_free(scop);
4451 return NULL;
4454 /* Bound all parameters in scop->context to the possible values
4455 * of the corresponding C variable.
4457 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
4459 int n;
4461 if (!scop)
4462 return NULL;
4464 n = isl_set_dim(scop->context, isl_dim_param);
4465 for (int i = 0; i < n; ++i) {
4466 isl_id *id;
4467 ValueDecl *decl;
4469 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
4470 if (pet_nested_in_id(id)) {
4471 isl_id_free(id);
4472 isl_die(isl_set_get_ctx(scop->context),
4473 isl_error_internal,
4474 "unresolved nested parameter", goto error);
4476 decl = (ValueDecl *) isl_id_get_user(id);
4477 isl_id_free(id);
4479 scop->context = set_parameter_bounds(scop->context, i, decl);
4481 if (!scop->context)
4482 goto error;
4485 return scop;
4486 error:
4487 pet_scop_free(scop);
4488 return NULL;
4491 /* Construct a pet_scop from the given function.
4493 * If the scop was delimited by scop and endscop pragmas, then we override
4494 * the file offsets by those derived from the pragmas.
4496 struct pet_scop *PetScan::scan(FunctionDecl *fd)
4498 pet_scop *scop;
4499 Stmt *stmt;
4501 stmt = fd->getBody();
4503 if (options->autodetect)
4504 scop = extract(stmt, true);
4505 else {
4506 scop = scan(stmt);
4507 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
4509 scop = pet_scop_detect_parameter_accesses(scop);
4510 scop = scan_arrays(scop);
4511 scop = add_parameter_bounds(scop);
4512 scop = pet_scop_gist(scop, value_bounds);
4514 return scop;