[RS6000] PR69645, -ffixed-reg ignored
[official-gcc.git] / gcc / genmatch.c
blob2b666ddd6f7c790e2f1beda3722391e3eee1e79c
1 /* Generate pattern matching and transform code shared between
2 GENERIC and GIMPLE folding code from match-and-simplify description.
4 Copyright (C) 2014-2016 Free Software Foundation, Inc.
5 Contributed by Richard Biener <rguenther@suse.de>
6 and Prathamesh Kulkarni <bilbotheelffriend@gmail.com>
8 This file is part of GCC.
10 GCC is free software; you can redistribute it and/or modify it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 3, or (at your option) any later
13 version.
15 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 for more details.
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3. If not see
22 <http://www.gnu.org/licenses/>. */
24 #include "bconfig.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include <cpplib.h>
28 #include "errors.h"
29 #include "hash-table.h"
30 #include "hash-set.h"
31 #include "is-a.h"
34 /* Stubs for GGC referenced through instantiations triggered by hash-map. */
35 void *ggc_internal_cleared_alloc (size_t, void (*)(void *),
36 size_t, size_t MEM_STAT_DECL)
38 return NULL;
40 void ggc_free (void *)
45 /* Global state. */
47 /* Verboseness. 0 is quiet, 1 adds some warnings, 2 is for debugging. */
48 unsigned verbose;
51 /* libccp helpers. */
53 static struct line_maps *line_table;
55 /* The rich_location class within libcpp requires a way to expand
56 source_location instances, and relies on the client code
57 providing a symbol named
58 linemap_client_expand_location_to_spelling_point
59 to do this.
61 This is the implementation for genmatch. */
63 expanded_location
64 linemap_client_expand_location_to_spelling_point (source_location loc)
66 const struct line_map_ordinary *map;
67 loc = linemap_resolve_location (line_table, loc, LRK_SPELLING_LOCATION, &map);
68 return linemap_expand_location (line_table, map, loc);
71 static bool
72 #if GCC_VERSION >= 4001
73 __attribute__((format (printf, 5, 0)))
74 #endif
75 error_cb (cpp_reader *, int errtype, int, rich_location *richloc,
76 const char *msg, va_list *ap)
78 const line_map_ordinary *map;
79 source_location location = richloc->get_loc ();
80 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
81 expanded_location loc = linemap_expand_location (line_table, map, location);
82 fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
83 (errtype == CPP_DL_WARNING) ? "warning" : "error");
84 vfprintf (stderr, msg, *ap);
85 fprintf (stderr, "\n");
86 FILE *f = fopen (loc.file, "r");
87 if (f)
89 char buf[128];
90 while (loc.line > 0)
92 if (!fgets (buf, 128, f))
93 goto notfound;
94 if (buf[strlen (buf) - 1] != '\n')
96 if (loc.line > 1)
97 loc.line++;
99 loc.line--;
101 fprintf (stderr, "%s", buf);
102 for (int i = 0; i < loc.column - 1; ++i)
103 fputc (' ', stderr);
104 fputc ('^', stderr);
105 fputc ('\n', stderr);
106 notfound:
107 fclose (f);
110 if (errtype == CPP_DL_FATAL)
111 exit (1);
112 return false;
115 static void
116 #if GCC_VERSION >= 4001
117 __attribute__((format (printf, 2, 3)))
118 #endif
119 fatal_at (const cpp_token *tk, const char *msg, ...)
121 rich_location richloc (line_table, tk->src_loc);
122 va_list ap;
123 va_start (ap, msg);
124 error_cb (NULL, CPP_DL_FATAL, 0, &richloc, msg, &ap);
125 va_end (ap);
128 static void
129 #if GCC_VERSION >= 4001
130 __attribute__((format (printf, 2, 3)))
131 #endif
132 fatal_at (source_location loc, const char *msg, ...)
134 rich_location richloc (line_table, loc);
135 va_list ap;
136 va_start (ap, msg);
137 error_cb (NULL, CPP_DL_FATAL, 0, &richloc, msg, &ap);
138 va_end (ap);
141 static void
142 #if GCC_VERSION >= 4001
143 __attribute__((format (printf, 2, 3)))
144 #endif
145 warning_at (const cpp_token *tk, const char *msg, ...)
147 rich_location richloc (line_table, tk->src_loc);
148 va_list ap;
149 va_start (ap, msg);
150 error_cb (NULL, CPP_DL_WARNING, 0, &richloc, msg, &ap);
151 va_end (ap);
154 static void
155 #if GCC_VERSION >= 4001
156 __attribute__((format (printf, 2, 3)))
157 #endif
158 warning_at (source_location loc, const char *msg, ...)
160 rich_location richloc (line_table, loc);
161 va_list ap;
162 va_start (ap, msg);
163 error_cb (NULL, CPP_DL_WARNING, 0, &richloc, msg, &ap);
164 va_end (ap);
167 /* Like fprintf, but print INDENT spaces at the beginning. */
169 static void
170 #if GCC_VERSION >= 4001
171 __attribute__((format (printf, 3, 4)))
172 #endif
173 fprintf_indent (FILE *f, unsigned int indent, const char *format, ...)
175 va_list ap;
176 for (; indent >= 8; indent -= 8)
177 fputc ('\t', f);
178 fprintf (f, "%*s", indent, "");
179 va_start (ap, format);
180 vfprintf (f, format, ap);
181 va_end (ap);
184 static void
185 output_line_directive (FILE *f, source_location location,
186 bool dumpfile = false)
188 const line_map_ordinary *map;
189 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
190 expanded_location loc = linemap_expand_location (line_table, map, location);
191 if (dumpfile)
193 /* When writing to a dumpfile only dump the filename. */
194 const char *file = strrchr (loc.file, DIR_SEPARATOR);
195 if (!file)
196 file = loc.file;
197 else
198 ++file;
199 fprintf (f, "%s:%d", file, loc.line);
201 else
202 /* Other gen programs really output line directives here, at least for
203 development it's right now more convenient to have line information
204 from the generated file. Still keep the directives as comment for now
205 to easily back-point to the meta-description. */
206 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
210 /* Pull in tree codes and builtin function codes from their
211 definition files. */
213 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
214 enum tree_code {
215 #include "tree.def"
216 CONVERT0,
217 CONVERT1,
218 CONVERT2,
219 VIEW_CONVERT0,
220 VIEW_CONVERT1,
221 VIEW_CONVERT2,
222 MAX_TREE_CODES
224 #undef DEFTREECODE
226 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
227 enum built_in_function {
228 #include "builtins.def"
229 END_BUILTINS
232 #define DEF_INTERNAL_FN(CODE, FLAGS, FNSPEC) IFN_##CODE,
233 enum internal_fn {
234 #include "internal-fn.def"
235 IFN_LAST
238 /* Return true if CODE represents a commutative tree code. Otherwise
239 return false. */
240 bool
241 commutative_tree_code (enum tree_code code)
243 switch (code)
245 case PLUS_EXPR:
246 case MULT_EXPR:
247 case MULT_HIGHPART_EXPR:
248 case MIN_EXPR:
249 case MAX_EXPR:
250 case BIT_IOR_EXPR:
251 case BIT_XOR_EXPR:
252 case BIT_AND_EXPR:
253 case NE_EXPR:
254 case EQ_EXPR:
255 case UNORDERED_EXPR:
256 case ORDERED_EXPR:
257 case UNEQ_EXPR:
258 case LTGT_EXPR:
259 case TRUTH_AND_EXPR:
260 case TRUTH_XOR_EXPR:
261 case TRUTH_OR_EXPR:
262 case WIDEN_MULT_EXPR:
263 case VEC_WIDEN_MULT_HI_EXPR:
264 case VEC_WIDEN_MULT_LO_EXPR:
265 case VEC_WIDEN_MULT_EVEN_EXPR:
266 case VEC_WIDEN_MULT_ODD_EXPR:
267 return true;
269 default:
270 break;
272 return false;
275 /* Return true if CODE represents a ternary tree code for which the
276 first two operands are commutative. Otherwise return false. */
277 bool
278 commutative_ternary_tree_code (enum tree_code code)
280 switch (code)
282 case WIDEN_MULT_PLUS_EXPR:
283 case WIDEN_MULT_MINUS_EXPR:
284 case DOT_PROD_EXPR:
285 case FMA_EXPR:
286 return true;
288 default:
289 break;
291 return false;
295 /* Base class for all identifiers the parser knows. */
297 struct id_base : nofree_ptr_hash<id_base>
299 enum id_kind { CODE, FN, PREDICATE, USER, NULL_ID } kind;
301 id_base (id_kind, const char *, int = -1);
303 hashval_t hashval;
304 int nargs;
305 const char *id;
307 /* hash_table support. */
308 static inline hashval_t hash (const id_base *);
309 static inline int equal (const id_base *, const id_base *);
312 inline hashval_t
313 id_base::hash (const id_base *op)
315 return op->hashval;
318 inline int
319 id_base::equal (const id_base *op1,
320 const id_base *op2)
322 return (op1->hashval == op2->hashval
323 && strcmp (op1->id, op2->id) == 0);
326 /* The special id "null", which matches nothing. */
327 static id_base *null_id;
329 /* Hashtable of known pattern operators. This is pre-seeded from
330 all known tree codes and all known builtin function ids. */
331 static hash_table<id_base> *operators;
333 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
335 kind = kind_;
336 id = id_;
337 nargs = nargs_;
338 hashval = htab_hash_string (id);
341 /* Identifier that maps to a tree code. */
343 struct operator_id : public id_base
345 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
346 const char *tcc_)
347 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
348 enum tree_code code;
349 const char *tcc;
352 /* Identifier that maps to a builtin or internal function code. */
354 struct fn_id : public id_base
356 fn_id (enum built_in_function fn_, const char *id_)
357 : id_base (id_base::FN, id_), fn (fn_) {}
358 fn_id (enum internal_fn fn_, const char *id_)
359 : id_base (id_base::FN, id_), fn (int (END_BUILTINS) + int (fn_)) {}
360 unsigned int fn;
363 struct simplify;
365 /* Identifier that maps to a user-defined predicate. */
367 struct predicate_id : public id_base
369 predicate_id (const char *id_)
370 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
371 vec<simplify *> matchers;
374 /* Identifier that maps to a operator defined by a 'for' directive. */
376 struct user_id : public id_base
378 user_id (const char *id_, bool is_oper_list_ = false)
379 : id_base (id_base::USER, id_), substitutes (vNULL),
380 used (false), is_oper_list (is_oper_list_) {}
381 vec<id_base *> substitutes;
382 bool used;
383 bool is_oper_list;
386 template<>
387 template<>
388 inline bool
389 is_a_helper <fn_id *>::test (id_base *id)
391 return id->kind == id_base::FN;
394 template<>
395 template<>
396 inline bool
397 is_a_helper <operator_id *>::test (id_base *id)
399 return id->kind == id_base::CODE;
402 template<>
403 template<>
404 inline bool
405 is_a_helper <predicate_id *>::test (id_base *id)
407 return id->kind == id_base::PREDICATE;
410 template<>
411 template<>
412 inline bool
413 is_a_helper <user_id *>::test (id_base *id)
415 return id->kind == id_base::USER;
418 /* Add a predicate identifier to the hash. */
420 static predicate_id *
421 add_predicate (const char *id)
423 predicate_id *p = new predicate_id (id);
424 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
425 if (*slot)
426 fatal ("duplicate id definition");
427 *slot = p;
428 return p;
431 /* Add a tree code identifier to the hash. */
433 static void
434 add_operator (enum tree_code code, const char *id,
435 const char *tcc, unsigned nargs)
437 if (strcmp (tcc, "tcc_unary") != 0
438 && strcmp (tcc, "tcc_binary") != 0
439 && strcmp (tcc, "tcc_comparison") != 0
440 && strcmp (tcc, "tcc_expression") != 0
441 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
442 && strcmp (tcc, "tcc_reference") != 0
443 /* To have INTEGER_CST and friends as "predicate operators". */
444 && strcmp (tcc, "tcc_constant") != 0
445 /* And allow CONSTRUCTOR for vector initializers. */
446 && !(code == CONSTRUCTOR)
447 /* Allow SSA_NAME as predicate operator. */
448 && !(code == SSA_NAME))
449 return;
450 /* Treat ADDR_EXPR as atom, thus don't allow matching its operand. */
451 if (code == ADDR_EXPR)
452 nargs = 0;
453 operator_id *op = new operator_id (code, id, nargs, tcc);
454 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
455 if (*slot)
456 fatal ("duplicate id definition");
457 *slot = op;
460 /* Add a built-in or internal function identifier to the hash. ID is
461 the name of its CFN_* enumeration value. */
463 template <typename T>
464 static void
465 add_function (T code, const char *id)
467 fn_id *fn = new fn_id (code, id);
468 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
469 if (*slot)
470 fatal ("duplicate id definition");
471 *slot = fn;
474 /* Helper for easy comparing ID with tree code CODE. */
476 static bool
477 operator==(id_base &id, enum tree_code code)
479 if (operator_id *oid = dyn_cast <operator_id *> (&id))
480 return oid->code == code;
481 return false;
484 /* Lookup the identifier ID. Allow "null" if ALLOW_NULL. */
486 id_base *
487 get_operator (const char *id, bool allow_null = false)
489 if (allow_null && strcmp (id, "null") == 0)
490 return null_id;
492 id_base tem (id_base::CODE, id);
494 id_base *op = operators->find_with_hash (&tem, tem.hashval);
495 if (op)
497 /* If this is a user-defined identifier track whether it was used. */
498 if (user_id *uid = dyn_cast<user_id *> (op))
499 uid->used = true;
500 return op;
503 char *id2;
504 bool all_upper = true;
505 bool all_lower = true;
506 for (unsigned int i = 0; id[i]; ++i)
507 if (ISUPPER (id[i]))
508 all_lower = false;
509 else if (ISLOWER (id[i]))
510 all_upper = false;
511 if (all_lower)
513 /* Try in caps with _EXPR appended. */
514 id2 = ACONCAT ((id, "_EXPR", NULL));
515 for (unsigned int i = 0; id2[i]; ++i)
516 id2[i] = TOUPPER (id2[i]);
518 else if (all_upper && strncmp (id, "IFN_", 4) == 0)
519 /* Try CFN_ instead of IFN_. */
520 id2 = ACONCAT (("CFN_", id + 4, NULL));
521 else if (all_upper && strncmp (id, "BUILT_IN_", 9) == 0)
522 /* Try prepending CFN_. */
523 id2 = ACONCAT (("CFN_", id, NULL));
524 else
525 return NULL;
527 new (&tem) id_base (id_base::CODE, id2);
528 return operators->find_with_hash (&tem, tem.hashval);
531 typedef hash_map<nofree_string_hash, unsigned> cid_map_t;
534 /* The AST produced by parsing of the pattern definitions. */
536 struct dt_operand;
537 struct capture_info;
539 /* The base class for operands. */
541 struct operand {
542 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR, OP_IF, OP_WITH };
543 operand (enum op_type type_, source_location loc_)
544 : type (type_), location (loc_) {}
545 enum op_type type;
546 source_location location;
547 virtual void gen_transform (FILE *, int, const char *, bool, int,
548 const char *, capture_info *,
549 dt_operand ** = 0,
550 int = 0)
551 { gcc_unreachable (); }
554 /* A predicate operand. Predicates are leafs in the AST. */
556 struct predicate : public operand
558 predicate (predicate_id *p_, source_location loc)
559 : operand (OP_PREDICATE, loc), p (p_) {}
560 predicate_id *p;
563 /* An operand that constitutes an expression. Expressions include
564 function calls and user-defined predicate invocations. */
566 struct expr : public operand
568 expr (id_base *operation_, source_location loc, bool is_commutative_ = false)
569 : operand (OP_EXPR, loc), operation (operation_),
570 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
571 is_generic (false), force_single_use (false) {}
572 expr (expr *e)
573 : operand (OP_EXPR, e->location), operation (e->operation),
574 ops (vNULL), expr_type (e->expr_type), is_commutative (e->is_commutative),
575 is_generic (e->is_generic), force_single_use (e->force_single_use) {}
576 void append_op (operand *op) { ops.safe_push (op); }
577 /* The operator and its operands. */
578 id_base *operation;
579 vec<operand *> ops;
580 /* An explicitely specified type - used exclusively for conversions. */
581 const char *expr_type;
582 /* Whether the operation is to be applied commutatively. This is
583 later lowered to two separate patterns. */
584 bool is_commutative;
585 /* Whether the expression is expected to be in GENERIC form. */
586 bool is_generic;
587 /* Whether pushing any stmt to the sequence should be conditional
588 on this expression having a single-use. */
589 bool force_single_use;
590 virtual void gen_transform (FILE *f, int, const char *, bool, int,
591 const char *, capture_info *,
592 dt_operand ** = 0, int = 0);
595 /* An operator that is represented by native C code. This is always
596 a leaf operand in the AST. This class is also used to represent
597 the code to be generated for 'if' and 'with' expressions. */
599 struct c_expr : public operand
601 /* A mapping of an identifier and its replacement. Used to apply
602 'for' lowering. */
603 struct id_tab {
604 const char *id;
605 const char *oper;
606 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
609 c_expr (cpp_reader *r_, source_location loc,
610 vec<cpp_token> code_, unsigned nr_stmts_,
611 vec<id_tab> ids_, cid_map_t *capture_ids_)
612 : operand (OP_C_EXPR, loc), r (r_), code (code_),
613 capture_ids (capture_ids_), nr_stmts (nr_stmts_), ids (ids_) {}
614 /* cpplib tokens and state to transform this back to source. */
615 cpp_reader *r;
616 vec<cpp_token> code;
617 cid_map_t *capture_ids;
618 /* The number of statements parsed (well, the number of ';'s). */
619 unsigned nr_stmts;
620 /* The identifier replacement vector. */
621 vec<id_tab> ids;
622 virtual void gen_transform (FILE *f, int, const char *, bool, int,
623 const char *, capture_info *,
624 dt_operand ** = 0, int = 0);
627 /* A wrapper around another operand that captures its value. */
629 struct capture : public operand
631 capture (source_location loc, unsigned where_, operand *what_)
632 : operand (OP_CAPTURE, loc), where (where_), what (what_) {}
633 /* Identifier index for the value. */
634 unsigned where;
635 /* The captured value. */
636 operand *what;
637 virtual void gen_transform (FILE *f, int, const char *, bool, int,
638 const char *, capture_info *,
639 dt_operand ** = 0, int = 0);
642 /* if expression. */
644 struct if_expr : public operand
646 if_expr (source_location loc)
647 : operand (OP_IF, loc), cond (NULL), trueexpr (NULL), falseexpr (NULL) {}
648 c_expr *cond;
649 operand *trueexpr;
650 operand *falseexpr;
653 /* with expression. */
655 struct with_expr : public operand
657 with_expr (source_location loc)
658 : operand (OP_WITH, loc), with (NULL), subexpr (NULL) {}
659 c_expr *with;
660 operand *subexpr;
663 template<>
664 template<>
665 inline bool
666 is_a_helper <capture *>::test (operand *op)
668 return op->type == operand::OP_CAPTURE;
671 template<>
672 template<>
673 inline bool
674 is_a_helper <predicate *>::test (operand *op)
676 return op->type == operand::OP_PREDICATE;
679 template<>
680 template<>
681 inline bool
682 is_a_helper <c_expr *>::test (operand *op)
684 return op->type == operand::OP_C_EXPR;
687 template<>
688 template<>
689 inline bool
690 is_a_helper <expr *>::test (operand *op)
692 return op->type == operand::OP_EXPR;
695 template<>
696 template<>
697 inline bool
698 is_a_helper <if_expr *>::test (operand *op)
700 return op->type == operand::OP_IF;
703 template<>
704 template<>
705 inline bool
706 is_a_helper <with_expr *>::test (operand *op)
708 return op->type == operand::OP_WITH;
711 /* The main class of a pattern and its transform. This is used to
712 represent both (simplify ...) and (match ...) kinds. The AST
713 duplicates all outer 'if' and 'for' expressions here so each
714 simplify can exist in isolation. */
716 struct simplify
718 enum simplify_kind { SIMPLIFY, MATCH };
720 simplify (simplify_kind kind_, operand *match_, operand *result_,
721 vec<vec<user_id *> > for_vec_, cid_map_t *capture_ids_)
722 : kind (kind_), match (match_), result (result_),
723 for_vec (for_vec_), for_subst_vec (vNULL),
724 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
726 simplify_kind kind;
727 /* The expression that is matched against the GENERIC or GIMPLE IL. */
728 operand *match;
729 /* For a (simplify ...) an expression with ifs and withs with the expression
730 produced when the pattern applies in the leafs.
731 For a (match ...) the leafs are either empty if it is a simple predicate
732 or the single expression specifying the matched operands. */
733 struct operand *result;
734 /* Collected 'for' expression operators that have to be replaced
735 in the lowering phase. */
736 vec<vec<user_id *> > for_vec;
737 vec<std::pair<user_id *, id_base *> > for_subst_vec;
738 /* A map of capture identifiers to indexes. */
739 cid_map_t *capture_ids;
740 int capture_max;
743 /* Debugging routines for dumping the AST. */
745 DEBUG_FUNCTION void
746 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
748 if (capture *c = dyn_cast<capture *> (o))
750 if (c->what && flattened == false)
751 print_operand (c->what, f, flattened);
752 fprintf (f, "@%u", c->where);
755 else if (predicate *p = dyn_cast<predicate *> (o))
756 fprintf (f, "%s", p->p->id);
758 else if (is_a<c_expr *> (o))
759 fprintf (f, "c_expr");
761 else if (expr *e = dyn_cast<expr *> (o))
763 if (e->ops.length () == 0)
764 fprintf (f, "%s", e->operation->id);
765 else
767 fprintf (f, "(%s", e->operation->id);
769 if (flattened == false)
771 for (unsigned i = 0; i < e->ops.length (); ++i)
773 putc (' ', f);
774 print_operand (e->ops[i], f, flattened);
777 putc (')', f);
781 else
782 gcc_unreachable ();
785 DEBUG_FUNCTION void
786 print_matches (struct simplify *s, FILE *f = stderr)
788 fprintf (f, "for expression: ");
789 print_operand (s->match, f);
790 putc ('\n', f);
794 /* AST lowering. */
796 /* Lowering of commutative operators. */
798 static void
799 cartesian_product (const vec< vec<operand *> >& ops_vector,
800 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
802 if (n == ops_vector.length ())
804 vec<operand *> xv = v.copy ();
805 result.safe_push (xv);
806 return;
809 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
811 v[n] = ops_vector[n][i];
812 cartesian_product (ops_vector, result, v, n + 1);
816 /* Lower OP to two operands in case it is marked as commutative. */
818 static vec<operand *>
819 commutate (operand *op)
821 vec<operand *> ret = vNULL;
823 if (capture *c = dyn_cast <capture *> (op))
825 if (!c->what)
827 ret.safe_push (op);
828 return ret;
830 vec<operand *> v = commutate (c->what);
831 for (unsigned i = 0; i < v.length (); ++i)
833 capture *nc = new capture (c->location, c->where, v[i]);
834 ret.safe_push (nc);
836 return ret;
839 expr *e = dyn_cast <expr *> (op);
840 if (!e || e->ops.length () == 0)
842 ret.safe_push (op);
843 return ret;
846 vec< vec<operand *> > ops_vector = vNULL;
847 for (unsigned i = 0; i < e->ops.length (); ++i)
848 ops_vector.safe_push (commutate (e->ops[i]));
850 auto_vec< vec<operand *> > result;
851 auto_vec<operand *> v (e->ops.length ());
852 v.quick_grow_cleared (e->ops.length ());
853 cartesian_product (ops_vector, result, v, 0);
856 for (unsigned i = 0; i < result.length (); ++i)
858 expr *ne = new expr (e);
859 ne->is_commutative = false;
860 for (unsigned j = 0; j < result[i].length (); ++j)
861 ne->append_op (result[i][j]);
862 ret.safe_push (ne);
865 if (!e->is_commutative)
866 return ret;
868 for (unsigned i = 0; i < result.length (); ++i)
870 expr *ne = new expr (e);
871 ne->is_commutative = false;
872 // result[i].length () is 2 since e->operation is binary
873 for (unsigned j = result[i].length (); j; --j)
874 ne->append_op (result[i][j-1]);
875 ret.safe_push (ne);
878 return ret;
881 /* Lower operations marked as commutative in the AST of S and push
882 the resulting patterns to SIMPLIFIERS. */
884 static void
885 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
887 vec<operand *> matchers = commutate (s->match);
888 for (unsigned i = 0; i < matchers.length (); ++i)
890 simplify *ns = new simplify (s->kind, matchers[i], s->result,
891 s->for_vec, s->capture_ids);
892 simplifiers.safe_push (ns);
896 /* Strip conditional conversios using operator OPER from O and its
897 children if STRIP, else replace them with an unconditional convert. */
899 operand *
900 lower_opt_convert (operand *o, enum tree_code oper,
901 enum tree_code to_oper, bool strip)
903 if (capture *c = dyn_cast<capture *> (o))
905 if (c->what)
906 return new capture (c->location, c->where,
907 lower_opt_convert (c->what, oper, to_oper, strip));
908 else
909 return c;
912 expr *e = dyn_cast<expr *> (o);
913 if (!e)
914 return o;
916 if (*e->operation == oper)
918 if (strip)
919 return lower_opt_convert (e->ops[0], oper, to_oper, strip);
921 expr *ne = new expr (e);
922 ne->operation = (to_oper == CONVERT_EXPR
923 ? get_operator ("CONVERT_EXPR")
924 : get_operator ("VIEW_CONVERT_EXPR"));
925 ne->append_op (lower_opt_convert (e->ops[0], oper, to_oper, strip));
926 return ne;
929 expr *ne = new expr (e);
930 for (unsigned i = 0; i < e->ops.length (); ++i)
931 ne->append_op (lower_opt_convert (e->ops[i], oper, to_oper, strip));
933 return ne;
936 /* Determine whether O or its children uses the conditional conversion
937 operator OPER. */
939 static bool
940 has_opt_convert (operand *o, enum tree_code oper)
942 if (capture *c = dyn_cast<capture *> (o))
944 if (c->what)
945 return has_opt_convert (c->what, oper);
946 else
947 return false;
950 expr *e = dyn_cast<expr *> (o);
951 if (!e)
952 return false;
954 if (*e->operation == oper)
955 return true;
957 for (unsigned i = 0; i < e->ops.length (); ++i)
958 if (has_opt_convert (e->ops[i], oper))
959 return true;
961 return false;
964 /* Lower conditional convert operators in O, expanding it to a vector
965 if required. */
967 static vec<operand *>
968 lower_opt_convert (operand *o)
970 vec<operand *> v1 = vNULL, v2;
972 v1.safe_push (o);
974 enum tree_code opers[]
975 = { CONVERT0, CONVERT_EXPR,
976 CONVERT1, CONVERT_EXPR,
977 CONVERT2, CONVERT_EXPR,
978 VIEW_CONVERT0, VIEW_CONVERT_EXPR,
979 VIEW_CONVERT1, VIEW_CONVERT_EXPR,
980 VIEW_CONVERT2, VIEW_CONVERT_EXPR };
982 /* Conditional converts are lowered to a pattern with the
983 conversion and one without. The three different conditional
984 convert codes are lowered separately. */
986 for (unsigned i = 0; i < sizeof (opers) / sizeof (enum tree_code); i += 2)
988 v2 = vNULL;
989 for (unsigned j = 0; j < v1.length (); ++j)
990 if (has_opt_convert (v1[j], opers[i]))
992 v2.safe_push (lower_opt_convert (v1[j],
993 opers[i], opers[i+1], false));
994 v2.safe_push (lower_opt_convert (v1[j],
995 opers[i], opers[i+1], true));
998 if (v2 != vNULL)
1000 v1 = vNULL;
1001 for (unsigned j = 0; j < v2.length (); ++j)
1002 v1.safe_push (v2[j]);
1006 return v1;
1009 /* Lower conditional convert operators in the AST of S and push
1010 the resulting multiple patterns to SIMPLIFIERS. */
1012 static void
1013 lower_opt_convert (simplify *s, vec<simplify *>& simplifiers)
1015 vec<operand *> matchers = lower_opt_convert (s->match);
1016 for (unsigned i = 0; i < matchers.length (); ++i)
1018 simplify *ns = new simplify (s->kind, matchers[i], s->result,
1019 s->for_vec, s->capture_ids);
1020 simplifiers.safe_push (ns);
1024 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1025 GENERIC and a GIMPLE variant. */
1027 static vec<operand *>
1028 lower_cond (operand *o)
1030 vec<operand *> ro = vNULL;
1032 if (capture *c = dyn_cast<capture *> (o))
1034 if (c->what)
1036 vec<operand *> lop = vNULL;
1037 lop = lower_cond (c->what);
1039 for (unsigned i = 0; i < lop.length (); ++i)
1040 ro.safe_push (new capture (c->location, c->where, lop[i]));
1041 return ro;
1045 expr *e = dyn_cast<expr *> (o);
1046 if (!e || e->ops.length () == 0)
1048 ro.safe_push (o);
1049 return ro;
1052 vec< vec<operand *> > ops_vector = vNULL;
1053 for (unsigned i = 0; i < e->ops.length (); ++i)
1054 ops_vector.safe_push (lower_cond (e->ops[i]));
1056 auto_vec< vec<operand *> > result;
1057 auto_vec<operand *> v (e->ops.length ());
1058 v.quick_grow_cleared (e->ops.length ());
1059 cartesian_product (ops_vector, result, v, 0);
1061 for (unsigned i = 0; i < result.length (); ++i)
1063 expr *ne = new expr (e);
1064 for (unsigned j = 0; j < result[i].length (); ++j)
1065 ne->append_op (result[i][j]);
1066 ro.safe_push (ne);
1067 /* If this is a COND with a captured expression or an
1068 expression with two operands then also match a GENERIC
1069 form on the compare. */
1070 if ((*e->operation == COND_EXPR
1071 || *e->operation == VEC_COND_EXPR)
1072 && ((is_a <capture *> (e->ops[0])
1073 && as_a <capture *> (e->ops[0])->what
1074 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
1075 && as_a <expr *>
1076 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
1077 || (is_a <expr *> (e->ops[0])
1078 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
1080 expr *ne = new expr (e);
1081 for (unsigned j = 0; j < result[i].length (); ++j)
1082 ne->append_op (result[i][j]);
1083 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
1085 expr *ocmp = as_a <expr *> (c->what);
1086 expr *cmp = new expr (ocmp);
1087 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1088 cmp->append_op (ocmp->ops[j]);
1089 cmp->is_generic = true;
1090 ne->ops[0] = new capture (c->location, c->where, cmp);
1092 else
1094 expr *ocmp = as_a <expr *> (ne->ops[0]);
1095 expr *cmp = new expr (ocmp);
1096 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1097 cmp->append_op (ocmp->ops[j]);
1098 cmp->is_generic = true;
1099 ne->ops[0] = cmp;
1101 ro.safe_push (ne);
1105 return ro;
1108 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1109 GENERIC and a GIMPLE variant. */
1111 static void
1112 lower_cond (simplify *s, vec<simplify *>& simplifiers)
1114 vec<operand *> matchers = lower_cond (s->match);
1115 for (unsigned i = 0; i < matchers.length (); ++i)
1117 simplify *ns = new simplify (s->kind, matchers[i], s->result,
1118 s->for_vec, s->capture_ids);
1119 simplifiers.safe_push (ns);
1123 /* Return true if O refers to ID. */
1125 bool
1126 contains_id (operand *o, user_id *id)
1128 if (capture *c = dyn_cast<capture *> (o))
1129 return c->what && contains_id (c->what, id);
1131 if (expr *e = dyn_cast<expr *> (o))
1133 if (e->operation == id)
1134 return true;
1135 for (unsigned i = 0; i < e->ops.length (); ++i)
1136 if (contains_id (e->ops[i], id))
1137 return true;
1138 return false;
1141 if (with_expr *w = dyn_cast <with_expr *> (o))
1142 return (contains_id (w->with, id)
1143 || contains_id (w->subexpr, id));
1145 if (if_expr *ife = dyn_cast <if_expr *> (o))
1146 return (contains_id (ife->cond, id)
1147 || contains_id (ife->trueexpr, id)
1148 || (ife->falseexpr && contains_id (ife->falseexpr, id)));
1150 if (c_expr *ce = dyn_cast<c_expr *> (o))
1151 return ce->capture_ids && ce->capture_ids->get (id->id);
1153 return false;
1157 /* In AST operand O replace operator ID with operator WITH. */
1159 operand *
1160 replace_id (operand *o, user_id *id, id_base *with)
1162 /* Deep-copy captures and expressions, replacing operations as
1163 needed. */
1164 if (capture *c = dyn_cast<capture *> (o))
1166 if (!c->what)
1167 return c;
1168 return new capture (c->location, c->where,
1169 replace_id (c->what, id, with));
1171 else if (expr *e = dyn_cast<expr *> (o))
1173 expr *ne = new expr (e);
1174 if (e->operation == id)
1175 ne->operation = with;
1176 for (unsigned i = 0; i < e->ops.length (); ++i)
1177 ne->append_op (replace_id (e->ops[i], id, with));
1178 return ne;
1180 else if (with_expr *w = dyn_cast <with_expr *> (o))
1182 with_expr *nw = new with_expr (w->location);
1183 nw->with = as_a <c_expr *> (replace_id (w->with, id, with));
1184 nw->subexpr = replace_id (w->subexpr, id, with);
1185 return nw;
1187 else if (if_expr *ife = dyn_cast <if_expr *> (o))
1189 if_expr *nife = new if_expr (ife->location);
1190 nife->cond = as_a <c_expr *> (replace_id (ife->cond, id, with));
1191 nife->trueexpr = replace_id (ife->trueexpr, id, with);
1192 if (ife->falseexpr)
1193 nife->falseexpr = replace_id (ife->falseexpr, id, with);
1194 return nife;
1197 /* For c_expr we simply record a string replacement table which is
1198 applied at code-generation time. */
1199 if (c_expr *ce = dyn_cast<c_expr *> (o))
1201 vec<c_expr::id_tab> ids = ce->ids.copy ();
1202 ids.safe_push (c_expr::id_tab (id->id, with->id));
1203 return new c_expr (ce->r, ce->location,
1204 ce->code, ce->nr_stmts, ids, ce->capture_ids);
1207 return o;
1210 /* Return true if the binary operator OP is ok for delayed substitution
1211 during for lowering. */
1213 static bool
1214 binary_ok (operator_id *op)
1216 switch (op->code)
1218 case PLUS_EXPR:
1219 case MINUS_EXPR:
1220 case MULT_EXPR:
1221 case TRUNC_DIV_EXPR:
1222 case CEIL_DIV_EXPR:
1223 case FLOOR_DIV_EXPR:
1224 case ROUND_DIV_EXPR:
1225 case TRUNC_MOD_EXPR:
1226 case CEIL_MOD_EXPR:
1227 case FLOOR_MOD_EXPR:
1228 case ROUND_MOD_EXPR:
1229 case RDIV_EXPR:
1230 case EXACT_DIV_EXPR:
1231 case MIN_EXPR:
1232 case MAX_EXPR:
1233 case BIT_IOR_EXPR:
1234 case BIT_XOR_EXPR:
1235 case BIT_AND_EXPR:
1236 return true;
1237 default:
1238 return false;
1242 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
1244 static void
1245 lower_for (simplify *sin, vec<simplify *>& simplifiers)
1247 vec<vec<user_id *> >& for_vec = sin->for_vec;
1248 unsigned worklist_start = 0;
1249 auto_vec<simplify *> worklist;
1250 worklist.safe_push (sin);
1252 /* Lower each recorded for separately, operating on the
1253 set of simplifiers created by the previous one.
1254 Lower inner-to-outer so inner for substitutes can refer
1255 to operators replaced by outer fors. */
1256 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1258 vec<user_id *>& ids = for_vec[fi];
1259 unsigned n_ids = ids.length ();
1260 unsigned max_n_opers = 0;
1261 bool can_delay_subst = (sin->kind == simplify::SIMPLIFY);
1262 for (unsigned i = 0; i < n_ids; ++i)
1264 if (ids[i]->substitutes.length () > max_n_opers)
1265 max_n_opers = ids[i]->substitutes.length ();
1266 /* Require that all substitutes are of the same kind so that
1267 if we delay substitution to the result op code generation
1268 can look at the first substitute for deciding things like
1269 types of operands. */
1270 enum id_base::id_kind kind = ids[i]->substitutes[0]->kind;
1271 for (unsigned j = 0; j < ids[i]->substitutes.length (); ++j)
1272 if (ids[i]->substitutes[j]->kind != kind)
1273 can_delay_subst = false;
1274 else if (operator_id *op
1275 = dyn_cast <operator_id *> (ids[i]->substitutes[j]))
1277 operator_id *op0
1278 = as_a <operator_id *> (ids[i]->substitutes[0]);
1279 if (strcmp (op->tcc, "tcc_comparison") == 0
1280 && strcmp (op0->tcc, "tcc_comparison") == 0)
1282 /* Unfortunately we can't just allow all tcc_binary. */
1283 else if (strcmp (op->tcc, "tcc_binary") == 0
1284 && strcmp (op0->tcc, "tcc_binary") == 0
1285 && binary_ok (op)
1286 && binary_ok (op0))
1288 else if ((strcmp (op->id + 1, "SHIFT_EXPR") == 0
1289 || strcmp (op->id + 1, "ROTATE_EXPR") == 0)
1290 && (strcmp (op0->id + 1, "SHIFT_EXPR") == 0
1291 || strcmp (op0->id + 1, "ROTATE_EXPR") == 0))
1293 else
1294 can_delay_subst = false;
1296 else if (is_a <fn_id *> (ids[i]->substitutes[j]))
1298 else
1299 can_delay_subst = false;
1302 unsigned worklist_end = worklist.length ();
1303 for (unsigned si = worklist_start; si < worklist_end; ++si)
1305 simplify *s = worklist[si];
1306 for (unsigned j = 0; j < max_n_opers; ++j)
1308 operand *match_op = s->match;
1309 operand *result_op = s->result;
1310 vec<std::pair<user_id *, id_base *> > subst;
1311 subst.create (n_ids);
1312 bool skip = false;
1313 for (unsigned i = 0; i < n_ids; ++i)
1315 user_id *id = ids[i];
1316 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1317 if (oper == null_id
1318 && (contains_id (match_op, id)
1319 || contains_id (result_op, id)))
1321 skip = true;
1322 break;
1324 subst.quick_push (std::make_pair (id, oper));
1325 match_op = replace_id (match_op, id, oper);
1326 if (result_op
1327 && !can_delay_subst)
1328 result_op = replace_id (result_op, id, oper);
1330 if (skip)
1332 subst.release ();
1333 continue;
1335 simplify *ns = new simplify (s->kind, match_op, result_op,
1336 vNULL, s->capture_ids);
1337 ns->for_subst_vec.safe_splice (s->for_subst_vec);
1338 if (result_op
1339 && can_delay_subst)
1340 ns->for_subst_vec.safe_splice (subst);
1341 else
1342 subst.release ();
1343 worklist.safe_push (ns);
1346 worklist_start = worklist_end;
1349 /* Copy out the result from the last for lowering. */
1350 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1351 simplifiers.safe_push (worklist[i]);
1354 /* Lower the AST for everything in SIMPLIFIERS. */
1356 static void
1357 lower (vec<simplify *>& simplifiers, bool gimple)
1359 auto_vec<simplify *> out_simplifiers;
1360 for (unsigned i = 0; i < simplifiers.length (); ++i)
1361 lower_opt_convert (simplifiers[i], out_simplifiers);
1363 simplifiers.truncate (0);
1364 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1365 lower_commutative (out_simplifiers[i], simplifiers);
1367 out_simplifiers.truncate (0);
1368 if (gimple)
1369 for (unsigned i = 0; i < simplifiers.length (); ++i)
1370 lower_cond (simplifiers[i], out_simplifiers);
1371 else
1372 out_simplifiers.safe_splice (simplifiers);
1375 simplifiers.truncate (0);
1376 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1377 lower_for (out_simplifiers[i], simplifiers);
1383 /* The decision tree built for generating GIMPLE and GENERIC pattern
1384 matching code. It represents the 'match' expression of all
1385 simplifies and has those as its leafs. */
1387 struct dt_simplify;
1389 /* A hash-map collecting semantically equivalent leafs in the decision
1390 tree for splitting out to separate functions. */
1391 struct sinfo
1393 dt_simplify *s;
1395 const char *fname;
1396 unsigned cnt;
1399 struct sinfo_hashmap_traits : simple_hashmap_traits<pointer_hash<dt_simplify>,
1400 sinfo *>
1402 static inline hashval_t hash (const key_type &);
1403 static inline bool equal_keys (const key_type &, const key_type &);
1404 template <typename T> static inline void remove (T &) {}
1407 typedef hash_map<void * /* unused */, sinfo *, sinfo_hashmap_traits>
1408 sinfo_map_t;
1411 /* Decision tree base class, used for DT_TRUE and DT_NODE. */
1413 struct dt_node
1415 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1417 enum dt_type type;
1418 unsigned level;
1419 vec<dt_node *> kids;
1421 /* Statistics. */
1422 unsigned num_leafs;
1423 unsigned total_size;
1424 unsigned max_level;
1426 dt_node (enum dt_type type_): type (type_), level (0), kids (vNULL) {}
1428 dt_node *append_node (dt_node *);
1429 dt_node *append_op (operand *, dt_node *parent = 0, unsigned pos = 0);
1430 dt_node *append_true_op (dt_node *parent = 0, unsigned pos = 0);
1431 dt_node *append_match_op (dt_operand *, dt_node *parent = 0, unsigned pos = 0);
1432 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1434 virtual void gen (FILE *, int, bool) {}
1436 void gen_kids (FILE *, int, bool);
1437 void gen_kids_1 (FILE *, int, bool,
1438 vec<dt_operand *>, vec<dt_operand *>, vec<dt_operand *>,
1439 vec<dt_operand *>, vec<dt_operand *>, vec<dt_node *>);
1441 void analyze (sinfo_map_t &);
1444 /* Generic decision tree node used for DT_OPERAND and DT_MATCH. */
1446 struct dt_operand : public dt_node
1448 operand *op;
1449 dt_operand *match_dop;
1450 dt_operand *parent;
1451 unsigned pos;
1453 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1454 dt_operand *parent_ = 0, unsigned pos_ = 0)
1455 : dt_node (type), op (op_), match_dop (match_dop_),
1456 parent (parent_), pos (pos_) {}
1458 void gen (FILE *, int, bool);
1459 unsigned gen_predicate (FILE *, int, const char *, bool);
1460 unsigned gen_match_op (FILE *, int, const char *);
1462 unsigned gen_gimple_expr (FILE *, int);
1463 unsigned gen_generic_expr (FILE *, int, const char *);
1465 char *get_name (char *);
1466 void gen_opname (char *, unsigned);
1469 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1471 struct dt_simplify : public dt_node
1473 simplify *s;
1474 unsigned pattern_no;
1475 dt_operand **indexes;
1476 sinfo *info;
1478 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1479 : dt_node (DT_SIMPLIFY), s (s_), pattern_no (pattern_no_),
1480 indexes (indexes_), info (NULL) {}
1482 void gen_1 (FILE *, int, bool, operand *);
1483 void gen (FILE *f, int, bool);
1486 template<>
1487 template<>
1488 inline bool
1489 is_a_helper <dt_operand *>::test (dt_node *n)
1491 return (n->type == dt_node::DT_OPERAND
1492 || n->type == dt_node::DT_MATCH);
1495 template<>
1496 template<>
1497 inline bool
1498 is_a_helper <dt_simplify *>::test (dt_node *n)
1500 return n->type == dt_node::DT_SIMPLIFY;
1505 /* A container for the actual decision tree. */
1507 struct decision_tree
1509 dt_node *root;
1511 void insert (struct simplify *, unsigned);
1512 void gen (FILE *f, bool gimple);
1513 void print (FILE *f = stderr);
1515 decision_tree () { root = new dt_node (dt_node::DT_NODE); }
1517 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1518 unsigned pos = 0, dt_node *parent = 0);
1519 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1520 static bool cmp_node (dt_node *, dt_node *);
1521 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1524 /* Compare two AST operands O1 and O2 and return true if they are equal. */
1526 bool
1527 cmp_operand (operand *o1, operand *o2)
1529 if (!o1 || !o2 || o1->type != o2->type)
1530 return false;
1532 if (o1->type == operand::OP_PREDICATE)
1534 predicate *p1 = as_a<predicate *>(o1);
1535 predicate *p2 = as_a<predicate *>(o2);
1536 return p1->p == p2->p;
1538 else if (o1->type == operand::OP_EXPR)
1540 expr *e1 = static_cast<expr *>(o1);
1541 expr *e2 = static_cast<expr *>(o2);
1542 return (e1->operation == e2->operation
1543 && e1->is_generic == e2->is_generic);
1545 else
1546 return false;
1549 /* Compare two decision tree nodes N1 and N2 and return true if they
1550 are equal. */
1552 bool
1553 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1555 if (!n1 || !n2 || n1->type != n2->type)
1556 return false;
1558 if (n1 == n2)
1559 return true;
1561 if (n1->type == dt_node::DT_TRUE)
1562 return false;
1564 if (n1->type == dt_node::DT_OPERAND)
1565 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1566 (as_a<dt_operand *> (n2))->op);
1567 else if (n1->type == dt_node::DT_MATCH)
1568 return ((as_a<dt_operand *> (n1))->match_dop
1569 == (as_a<dt_operand *> (n2))->match_dop);
1570 return false;
1573 /* Search OPS for a decision tree node like P and return it if found. */
1575 dt_node *
1576 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1578 /* We can merge adjacent DT_TRUE. */
1579 if (p->type == dt_node::DT_TRUE
1580 && !ops.is_empty ()
1581 && ops.last ()->type == dt_node::DT_TRUE)
1582 return ops.last ();
1583 for (int i = ops.length () - 1; i >= 0; --i)
1585 /* But we can't merge across DT_TRUE nodes as they serve as
1586 pattern order barriers to make sure that patterns apply
1587 in order of appearance in case multiple matches are possible. */
1588 if (ops[i]->type == dt_node::DT_TRUE)
1589 return NULL;
1590 if (decision_tree::cmp_node (ops[i], p))
1591 return ops[i];
1593 return NULL;
1596 /* Append N to the decision tree if it there is not already an existing
1597 identical child. */
1599 dt_node *
1600 dt_node::append_node (dt_node *n)
1602 dt_node *kid;
1604 kid = decision_tree::find_node (kids, n);
1605 if (kid)
1606 return kid;
1608 kids.safe_push (n);
1609 n->level = this->level + 1;
1611 return n;
1614 /* Append OP to the decision tree. */
1616 dt_node *
1617 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1619 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1620 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1621 return append_node (n);
1624 /* Append a DT_TRUE decision tree node. */
1626 dt_node *
1627 dt_node::append_true_op (dt_node *parent, unsigned pos)
1629 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1630 dt_operand *n = new dt_operand (DT_TRUE, 0, 0, parent_, pos);
1631 return append_node (n);
1634 /* Append a DT_MATCH decision tree node. */
1636 dt_node *
1637 dt_node::append_match_op (dt_operand *match_dop, dt_node *parent, unsigned pos)
1639 dt_operand *parent_ = as_a<dt_operand *> (parent);
1640 dt_operand *n = new dt_operand (DT_MATCH, 0, match_dop, parent_, pos);
1641 return append_node (n);
1644 /* Append S to the decision tree. */
1646 dt_node *
1647 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1648 dt_operand **indexes)
1650 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1651 for (unsigned i = 0; i < kids.length (); ++i)
1652 if (dt_simplify *s2 = dyn_cast <dt_simplify *> (kids[i]))
1654 warning_at (s->match->location, "duplicate pattern");
1655 warning_at (s2->s->match->location, "previous pattern defined here");
1656 print_operand (s->match, stderr);
1657 fprintf (stderr, "\n");
1659 return append_node (n);
1662 /* Analyze the node and its children. */
1664 void
1665 dt_node::analyze (sinfo_map_t &map)
1667 num_leafs = 0;
1668 total_size = 1;
1669 max_level = level;
1671 if (type == DT_SIMPLIFY)
1673 /* Populate the map of equivalent simplifies. */
1674 dt_simplify *s = as_a <dt_simplify *> (this);
1675 bool existed;
1676 sinfo *&si = map.get_or_insert (s, &existed);
1677 if (!existed)
1679 si = new sinfo;
1680 si->s = s;
1681 si->cnt = 1;
1682 si->fname = NULL;
1684 else
1685 si->cnt++;
1686 s->info = si;
1687 num_leafs = 1;
1688 return;
1691 for (unsigned i = 0; i < kids.length (); ++i)
1693 kids[i]->analyze (map);
1694 num_leafs += kids[i]->num_leafs;
1695 total_size += kids[i]->total_size;
1696 max_level = MAX (max_level, kids[i]->max_level);
1700 /* Insert O into the decision tree and return the decision tree node found
1701 or created. */
1703 dt_node *
1704 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1705 unsigned pos, dt_node *parent)
1707 dt_node *q, *elm = 0;
1709 if (capture *c = dyn_cast<capture *> (o))
1711 unsigned capt_index = c->where;
1713 if (indexes[capt_index] == 0)
1715 if (c->what)
1716 q = insert_operand (p, c->what, indexes, pos, parent);
1717 else
1719 q = elm = p->append_true_op (parent, pos);
1720 goto at_assert_elm;
1722 // get to the last capture
1723 for (operand *what = c->what;
1724 what && is_a<capture *> (what);
1725 c = as_a<capture *> (what), what = c->what)
1728 if (!c->what)
1730 unsigned cc_index = c->where;
1731 dt_operand *match_op = indexes[cc_index];
1733 dt_operand temp (dt_node::DT_TRUE, 0, 0);
1734 elm = decision_tree::find_node (p->kids, &temp);
1736 if (elm == 0)
1738 dt_operand temp (dt_node::DT_MATCH, 0, match_op);
1739 elm = decision_tree::find_node (p->kids, &temp);
1742 else
1744 dt_operand temp (dt_node::DT_OPERAND, c->what, 0);
1745 elm = decision_tree::find_node (p->kids, &temp);
1748 at_assert_elm:
1749 gcc_assert (elm->type == dt_node::DT_TRUE
1750 || elm->type == dt_node::DT_OPERAND
1751 || elm->type == dt_node::DT_MATCH);
1752 indexes[capt_index] = static_cast<dt_operand *> (elm);
1753 return q;
1755 else
1757 p = p->append_match_op (indexes[capt_index], parent, pos);
1758 if (c->what)
1759 return insert_operand (p, c->what, indexes, 0, p);
1760 else
1761 return p;
1764 p = p->append_op (o, parent, pos);
1765 q = p;
1767 if (expr *e = dyn_cast <expr *>(o))
1769 for (unsigned i = 0; i < e->ops.length (); ++i)
1770 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
1773 return q;
1776 /* Insert S into the decision tree. */
1778 void
1779 decision_tree::insert (struct simplify *s, unsigned pattern_no)
1781 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
1782 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
1783 p->append_simplify (s, pattern_no, indexes);
1786 /* Debug functions to dump the decision tree. */
1788 DEBUG_FUNCTION void
1789 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
1791 if (p->type == dt_node::DT_NODE)
1792 fprintf (f, "root");
1793 else
1795 fprintf (f, "|");
1796 for (unsigned i = 0; i < indent; i++)
1797 fprintf (f, "-");
1799 if (p->type == dt_node::DT_OPERAND)
1801 dt_operand *dop = static_cast<dt_operand *>(p);
1802 print_operand (dop->op, f, true);
1804 else if (p->type == dt_node::DT_TRUE)
1805 fprintf (f, "true");
1806 else if (p->type == dt_node::DT_MATCH)
1807 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
1808 else if (p->type == dt_node::DT_SIMPLIFY)
1810 dt_simplify *s = static_cast<dt_simplify *> (p);
1811 fprintf (f, "simplify_%u { ", s->pattern_no);
1812 for (int i = 0; i <= s->s->capture_max; ++i)
1813 fprintf (f, "%p, ", (void *) s->indexes[i]);
1814 fprintf (f, " } ");
1818 fprintf (stderr, " (%p), %u, %u\n", (void *) p, p->level, p->kids.length ());
1820 for (unsigned i = 0; i < p->kids.length (); ++i)
1821 decision_tree::print_node (p->kids[i], f, indent + 2);
1824 DEBUG_FUNCTION void
1825 decision_tree::print (FILE *f)
1827 return decision_tree::print_node (root, f);
1831 /* For GENERIC we have to take care of wrapping multiple-used
1832 expressions with side-effects in save_expr and preserve side-effects
1833 of expressions with omit_one_operand. Analyze captures in
1834 match, result and with expressions and perform early-outs
1835 on the outermost match expression operands for cases we cannot
1836 handle. */
1838 struct capture_info
1840 capture_info (simplify *s, operand *, bool);
1841 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
1842 bool walk_result (operand *o, bool, operand *);
1843 void walk_c_expr (c_expr *);
1845 struct cinfo
1847 bool expr_p;
1848 bool cse_p;
1849 bool force_no_side_effects_p;
1850 bool force_single_use;
1851 bool cond_expr_cond_p;
1852 unsigned long toplevel_msk;
1853 unsigned match_use_count;
1854 unsigned result_use_count;
1855 unsigned same_as;
1856 capture *c;
1859 auto_vec<cinfo> info;
1860 unsigned long force_no_side_effects;
1861 bool gimple;
1864 /* Analyze captures in S. */
1866 capture_info::capture_info (simplify *s, operand *result, bool gimple_)
1868 gimple = gimple_;
1870 expr *e;
1871 if (s->kind == simplify::MATCH)
1873 force_no_side_effects = -1;
1874 return;
1877 force_no_side_effects = 0;
1878 info.safe_grow_cleared (s->capture_max + 1);
1879 for (int i = 0; i <= s->capture_max; ++i)
1880 info[i].same_as = i;
1882 e = as_a <expr *> (s->match);
1883 for (unsigned i = 0; i < e->ops.length (); ++i)
1884 walk_match (e->ops[i], i,
1885 (i != 0 && *e->operation == COND_EXPR)
1886 || *e->operation == TRUTH_ANDIF_EXPR
1887 || *e->operation == TRUTH_ORIF_EXPR,
1888 i == 0
1889 && (*e->operation == COND_EXPR
1890 || *e->operation == VEC_COND_EXPR));
1892 walk_result (s->result, false, result);
1895 /* Analyze captures in the match expression piece O. */
1897 void
1898 capture_info::walk_match (operand *o, unsigned toplevel_arg,
1899 bool conditional_p, bool cond_expr_cond_p)
1901 if (capture *c = dyn_cast <capture *> (o))
1903 unsigned where = c->where;
1904 info[where].match_use_count++;
1905 info[where].toplevel_msk |= 1 << toplevel_arg;
1906 info[where].force_no_side_effects_p |= conditional_p;
1907 info[where].cond_expr_cond_p |= cond_expr_cond_p;
1908 if (!info[where].c)
1909 info[where].c = c;
1910 if (!c->what)
1911 return;
1912 /* Recurse to exprs and captures. */
1913 if (is_a <capture *> (c->what)
1914 || is_a <expr *> (c->what))
1915 walk_match (c->what, toplevel_arg, conditional_p, false);
1916 /* We need to look past multiple captures to find a captured
1917 expression as with conditional converts two captures
1918 can be collapsed onto the same expression. Also collect
1919 what captures capture the same thing. */
1920 while (c->what && is_a <capture *> (c->what))
1922 c = as_a <capture *> (c->what);
1923 if (info[c->where].same_as != c->where
1924 && info[c->where].same_as != info[where].same_as)
1925 fatal_at (c->location, "cannot handle this collapsed capture");
1926 info[c->where].same_as = info[where].same_as;
1928 /* Mark expr (non-leaf) captures and forced single-use exprs. */
1929 expr *e;
1930 if (c->what
1931 && (e = dyn_cast <expr *> (c->what)))
1933 info[where].expr_p = true;
1934 info[where].force_single_use |= e->force_single_use;
1937 else if (expr *e = dyn_cast <expr *> (o))
1939 for (unsigned i = 0; i < e->ops.length (); ++i)
1941 bool cond_p = conditional_p;
1942 bool cond_expr_cond_p = false;
1943 if (i != 0 && *e->operation == COND_EXPR)
1944 cond_p = true;
1945 else if (*e->operation == TRUTH_ANDIF_EXPR
1946 || *e->operation == TRUTH_ORIF_EXPR)
1947 cond_p = true;
1948 if (i == 0
1949 && (*e->operation == COND_EXPR
1950 || *e->operation == VEC_COND_EXPR))
1951 cond_expr_cond_p = true;
1952 walk_match (e->ops[i], toplevel_arg, cond_p, cond_expr_cond_p);
1955 else if (is_a <predicate *> (o))
1957 /* Mark non-captured leafs toplevel arg for checking. */
1958 force_no_side_effects |= 1 << toplevel_arg;
1959 if (verbose >= 1
1960 && !gimple)
1961 warning_at (o->location,
1962 "forcing no side-effects on possibly lost leaf");
1964 else
1965 gcc_unreachable ();
1968 /* Analyze captures in the result expression piece O. Return true
1969 if RESULT was visited in one of the children. Only visit
1970 non-if/with children if they are rooted on RESULT. */
1972 bool
1973 capture_info::walk_result (operand *o, bool conditional_p, operand *result)
1975 if (capture *c = dyn_cast <capture *> (o))
1977 unsigned where = info[c->where].same_as;
1978 info[where].result_use_count++;
1979 /* If we substitute an expression capture we don't know
1980 which captures this will end up using (well, we don't
1981 compute that). Force the uses to be side-effect free
1982 which means forcing the toplevels that reach the
1983 expression side-effect free. */
1984 if (info[where].expr_p)
1985 force_no_side_effects |= info[where].toplevel_msk;
1986 /* Mark CSE capture uses as forced to have no side-effects. */
1987 if (c->what
1988 && is_a <expr *> (c->what))
1990 info[where].cse_p = true;
1991 walk_result (c->what, true, result);
1994 else if (expr *e = dyn_cast <expr *> (o))
1996 id_base *opr = e->operation;
1997 if (user_id *uid = dyn_cast <user_id *> (opr))
1998 opr = uid->substitutes[0];
1999 for (unsigned i = 0; i < e->ops.length (); ++i)
2001 bool cond_p = conditional_p;
2002 if (i != 0 && *e->operation == COND_EXPR)
2003 cond_p = true;
2004 else if (*e->operation == TRUTH_ANDIF_EXPR
2005 || *e->operation == TRUTH_ORIF_EXPR)
2006 cond_p = true;
2007 walk_result (e->ops[i], cond_p, result);
2010 else if (if_expr *e = dyn_cast <if_expr *> (o))
2012 /* 'if' conditions should be all fine. */
2013 if (e->trueexpr == result)
2015 walk_result (e->trueexpr, false, result);
2016 return true;
2018 if (e->falseexpr == result)
2020 walk_result (e->falseexpr, false, result);
2021 return true;
2023 bool res = false;
2024 if (is_a <if_expr *> (e->trueexpr)
2025 || is_a <with_expr *> (e->trueexpr))
2026 res |= walk_result (e->trueexpr, false, result);
2027 if (e->falseexpr
2028 && (is_a <if_expr *> (e->falseexpr)
2029 || is_a <with_expr *> (e->falseexpr)))
2030 res |= walk_result (e->falseexpr, false, result);
2031 return res;
2033 else if (with_expr *e = dyn_cast <with_expr *> (o))
2035 bool res = (e->subexpr == result);
2036 if (res
2037 || is_a <if_expr *> (e->subexpr)
2038 || is_a <with_expr *> (e->subexpr))
2039 res |= walk_result (e->subexpr, false, result);
2040 if (res)
2041 walk_c_expr (e->with);
2042 return res;
2044 else if (c_expr *e = dyn_cast <c_expr *> (o))
2045 walk_c_expr (e);
2046 else
2047 gcc_unreachable ();
2049 return false;
2052 /* Look for captures in the C expr E. */
2054 void
2055 capture_info::walk_c_expr (c_expr *e)
2057 /* Give up for C exprs mentioning captures not inside TREE_TYPE,
2058 TREE_REAL_CST, TREE_CODE or a predicate where they cannot
2059 really escape through. */
2060 unsigned p_depth = 0;
2061 for (unsigned i = 0; i < e->code.length (); ++i)
2063 const cpp_token *t = &e->code[i];
2064 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
2065 id_base *id;
2066 if (t->type == CPP_NAME
2067 && (strcmp ((const char *)CPP_HASHNODE
2068 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
2069 || strcmp ((const char *)CPP_HASHNODE
2070 (t->val.node.node)->ident.str, "TREE_CODE") == 0
2071 || strcmp ((const char *)CPP_HASHNODE
2072 (t->val.node.node)->ident.str, "TREE_REAL_CST") == 0
2073 || ((id = get_operator ((const char *)CPP_HASHNODE
2074 (t->val.node.node)->ident.str))
2075 && is_a <predicate_id *> (id)))
2076 && n->type == CPP_OPEN_PAREN)
2077 p_depth++;
2078 else if (t->type == CPP_CLOSE_PAREN
2079 && p_depth > 0)
2080 p_depth--;
2081 else if (p_depth == 0
2082 && t->type == CPP_ATSIGN
2083 && (n->type == CPP_NUMBER
2084 || n->type == CPP_NAME)
2085 && !(n->flags & PREV_WHITE))
2087 const char *id;
2088 if (n->type == CPP_NUMBER)
2089 id = (const char *)n->val.str.text;
2090 else
2091 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2092 unsigned where = *e->capture_ids->get(id);
2093 info[info[where].same_as].force_no_side_effects_p = true;
2094 if (verbose >= 1
2095 && !gimple)
2096 warning_at (t, "capture escapes");
2102 /* Code generation off the decision tree and the refered AST nodes. */
2104 bool
2105 is_conversion (id_base *op)
2107 return (*op == CONVERT_EXPR
2108 || *op == NOP_EXPR
2109 || *op == FLOAT_EXPR
2110 || *op == FIX_TRUNC_EXPR
2111 || *op == VIEW_CONVERT_EXPR);
2114 /* Get the type to be used for generating operands of OP from the
2115 various sources. */
2117 static const char *
2118 get_operand_type (id_base *op, const char *in_type,
2119 const char *expr_type,
2120 const char *other_oprnd_type)
2122 /* Generally operands whose type does not match the type of the
2123 expression generated need to know their types but match and
2124 thus can fall back to 'other_oprnd_type'. */
2125 if (is_conversion (op))
2126 return other_oprnd_type;
2127 else if (*op == REALPART_EXPR
2128 || *op == IMAGPART_EXPR)
2129 return other_oprnd_type;
2130 else if (is_a <operator_id *> (op)
2131 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
2132 return other_oprnd_type;
2133 else
2135 /* Otherwise all types should match - choose one in order of
2136 preference. */
2137 if (expr_type)
2138 return expr_type;
2139 else if (in_type)
2140 return in_type;
2141 else
2142 return other_oprnd_type;
2146 /* Generate transform code for an expression. */
2148 void
2149 expr::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2150 int depth, const char *in_type, capture_info *cinfo,
2151 dt_operand **indexes, int)
2153 id_base *opr = operation;
2154 /* When we delay operator substituting during lowering of fors we
2155 make sure that for code-gen purposes the effects of each substitute
2156 are the same. Thus just look at that. */
2157 if (user_id *uid = dyn_cast <user_id *> (opr))
2158 opr = uid->substitutes[0];
2160 bool conversion_p = is_conversion (opr);
2161 const char *type = expr_type;
2162 char optype[64];
2163 if (type)
2164 /* If there was a type specification in the pattern use it. */
2166 else if (conversion_p)
2167 /* For conversions we need to build the expression using the
2168 outer type passed in. */
2169 type = in_type;
2170 else if (*opr == REALPART_EXPR
2171 || *opr == IMAGPART_EXPR)
2173 /* __real and __imag use the component type of its operand. */
2174 sprintf (optype, "TREE_TYPE (TREE_TYPE (ops%d[0]))", depth);
2175 type = optype;
2177 else if (is_a <operator_id *> (opr)
2178 && !strcmp (as_a <operator_id *> (opr)->tcc, "tcc_comparison"))
2180 /* comparisons use boolean_type_node (or what gets in), but
2181 their operands need to figure out the types themselves. */
2182 sprintf (optype, "boolean_type_node");
2183 type = optype;
2185 else if (*opr == COND_EXPR
2186 || *opr == VEC_COND_EXPR)
2188 /* Conditions are of the same type as their first alternative. */
2189 sprintf (optype, "TREE_TYPE (ops%d[1])", depth);
2190 type = optype;
2192 else
2194 /* Other operations are of the same type as their first operand. */
2195 sprintf (optype, "TREE_TYPE (ops%d[0])", depth);
2196 type = optype;
2198 if (!type)
2199 fatal_at (location, "cannot determine type of operand");
2201 fprintf_indent (f, indent, "{\n");
2202 indent += 2;
2203 fprintf_indent (f, indent, "tree ops%d[%u], res;\n", depth, ops.length ());
2204 char op0type[64];
2205 snprintf (op0type, 64, "TREE_TYPE (ops%d[0])", depth);
2206 for (unsigned i = 0; i < ops.length (); ++i)
2208 char dest[32];
2209 snprintf (dest, 32, "ops%d[%u]", depth, i);
2210 const char *optype
2211 = get_operand_type (opr, in_type, expr_type,
2212 i == 0 ? NULL : op0type);
2213 ops[i]->gen_transform (f, indent, dest, gimple, depth + 1, optype,
2214 cinfo, indexes,
2215 (*opr == COND_EXPR
2216 || *opr == VEC_COND_EXPR) && i == 0 ? 1 : 2);
2219 const char *opr_name;
2220 if (*operation == CONVERT_EXPR)
2221 opr_name = "NOP_EXPR";
2222 else
2223 opr_name = operation->id;
2225 if (gimple)
2227 if (*opr == CONVERT_EXPR)
2229 fprintf_indent (f, indent,
2230 "if (%s != TREE_TYPE (ops%d[0])\n",
2231 type, depth);
2232 fprintf_indent (f, indent,
2233 " && !useless_type_conversion_p (%s, TREE_TYPE (ops%d[0])))\n",
2234 type, depth);
2235 fprintf_indent (f, indent + 2, "{\n");
2236 indent += 4;
2238 /* ??? Building a stmt can fail for various reasons here, seq being
2239 NULL or the stmt referencing SSA names occuring in abnormal PHIs.
2240 So if we fail here we should continue matching other patterns. */
2241 fprintf_indent (f, indent, "code_helper tem_code = %s;\n", opr_name);
2242 fprintf_indent (f, indent, "tree tem_ops[3] = { ");
2243 for (unsigned i = 0; i < ops.length (); ++i)
2244 fprintf (f, "ops%d[%u]%s", depth, i,
2245 i == ops.length () - 1 ? " };\n" : ", ");
2246 fprintf_indent (f, indent,
2247 "gimple_resimplify%d (lseq, &tem_code, %s, tem_ops, valueize);\n",
2248 ops.length (), type);
2249 fprintf_indent (f, indent,
2250 "res = maybe_push_res_to_seq (tem_code, %s, tem_ops, lseq);\n",
2251 type);
2252 fprintf_indent (f, indent,
2253 "if (!res) return false;\n");
2254 if (*opr == CONVERT_EXPR)
2256 indent -= 4;
2257 fprintf_indent (f, indent, " }\n");
2258 fprintf_indent (f, indent, "else\n");
2259 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
2262 else
2264 if (*opr == CONVERT_EXPR)
2266 fprintf_indent (f, indent, "if (TREE_TYPE (ops%d[0]) != %s)\n",
2267 depth, type);
2268 indent += 2;
2270 if (opr->kind == id_base::CODE)
2271 fprintf_indent (f, indent, "res = fold_build%d_loc (loc, %s, %s",
2272 ops.length(), opr_name, type);
2273 else
2275 fprintf_indent (f, indent, "{\n");
2276 fprintf_indent (f, indent, " res = maybe_build_call_expr_loc (loc, "
2277 "%s, %s, %d", opr_name, type, ops.length());
2279 for (unsigned i = 0; i < ops.length (); ++i)
2280 fprintf (f, ", ops%d[%u]", depth, i);
2281 fprintf (f, ");\n");
2282 if (opr->kind != id_base::CODE)
2284 fprintf_indent (f, indent, " if (!res)\n");
2285 fprintf_indent (f, indent, " return NULL_TREE;\n");
2286 fprintf_indent (f, indent, "}\n");
2288 if (*opr == CONVERT_EXPR)
2290 indent -= 2;
2291 fprintf_indent (f, indent, "else\n");
2292 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
2295 fprintf_indent (f, indent, "%s = res;\n", dest);
2296 indent -= 2;
2297 fprintf_indent (f, indent, "}\n");
2300 /* Generate code for a c_expr which is either the expression inside
2301 an if statement or a sequence of statements which computes a
2302 result to be stored to DEST. */
2304 void
2305 c_expr::gen_transform (FILE *f, int indent, const char *dest,
2306 bool, int, const char *, capture_info *,
2307 dt_operand **, int)
2309 if (dest && nr_stmts == 1)
2310 fprintf_indent (f, indent, "%s = ", dest);
2312 unsigned stmt_nr = 1;
2313 for (unsigned i = 0; i < code.length (); ++i)
2315 const cpp_token *token = &code[i];
2317 /* Replace captures for code-gen. */
2318 if (token->type == CPP_ATSIGN)
2320 const cpp_token *n = &code[i+1];
2321 if ((n->type == CPP_NUMBER
2322 || n->type == CPP_NAME)
2323 && !(n->flags & PREV_WHITE))
2325 if (token->flags & PREV_WHITE)
2326 fputc (' ', f);
2327 const char *id;
2328 if (n->type == CPP_NUMBER)
2329 id = (const char *)n->val.str.text;
2330 else
2331 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2332 unsigned *cid = capture_ids->get (id);
2333 if (!cid)
2334 fatal_at (token, "unknown capture id");
2335 fprintf (f, "captures[%u]", *cid);
2336 ++i;
2337 continue;
2341 if (token->flags & PREV_WHITE)
2342 fputc (' ', f);
2344 if (token->type == CPP_NAME)
2346 const char *id = (const char *) NODE_NAME (token->val.node.node);
2347 unsigned j;
2348 for (j = 0; j < ids.length (); ++j)
2350 if (strcmp (id, ids[j].id) == 0)
2352 fprintf (f, "%s", ids[j].oper);
2353 break;
2356 if (j < ids.length ())
2357 continue;
2360 /* Output the token as string. */
2361 char *tk = (char *)cpp_token_as_text (r, token);
2362 fputs (tk, f);
2364 if (token->type == CPP_SEMICOLON)
2366 stmt_nr++;
2367 fputc ('\n', f);
2368 if (dest && stmt_nr == nr_stmts)
2369 fprintf_indent (f, indent, "%s = ", dest);
2374 /* Generate transform code for a capture. */
2376 void
2377 capture::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2378 int depth, const char *in_type, capture_info *cinfo,
2379 dt_operand **indexes, int cond_handling)
2381 if (what && is_a<expr *> (what))
2383 if (indexes[where] == 0)
2385 char buf[20];
2386 sprintf (buf, "captures[%u]", where);
2387 what->gen_transform (f, indent, buf, gimple, depth, in_type,
2388 cinfo, NULL);
2392 fprintf_indent (f, indent, "%s = captures[%u];\n", dest, where);
2394 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2395 with substituting a capture of that. */
2396 if (gimple
2397 && cond_handling != 0
2398 && cinfo->info[where].cond_expr_cond_p)
2400 /* If substituting into a cond_expr condition, unshare. */
2401 if (cond_handling == 1)
2402 fprintf_indent (f, indent, "%s = unshare_expr (%s);\n", dest, dest);
2403 /* If substituting elsewhere we might need to decompose it. */
2404 else if (cond_handling == 2)
2406 /* ??? Returning false here will also not allow any other patterns
2407 to match unless this generator was split out. */
2408 fprintf_indent (f, indent, "if (COMPARISON_CLASS_P (%s))\n", dest);
2409 fprintf_indent (f, indent, " {\n");
2410 fprintf_indent (f, indent, " if (!seq) return false;\n");
2411 fprintf_indent (f, indent, " %s = gimple_build (seq,"
2412 " TREE_CODE (%s),"
2413 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
2414 " TREE_OPERAND (%s, 1));\n",
2415 dest, dest, dest, dest, dest);
2416 fprintf_indent (f, indent, " }\n");
2421 /* Return the name of the operand representing the decision tree node.
2422 Use NAME as space to generate it. */
2424 char *
2425 dt_operand::get_name (char *name)
2427 if (!parent)
2428 sprintf (name, "t");
2429 else if (parent->level == 1)
2430 sprintf (name, "op%u", pos);
2431 else if (parent->type == dt_node::DT_MATCH)
2432 return parent->get_name (name);
2433 else
2434 sprintf (name, "o%u%u", parent->level, pos);
2435 return name;
2438 /* Fill NAME with the operand name at position POS. */
2440 void
2441 dt_operand::gen_opname (char *name, unsigned pos)
2443 if (!parent)
2444 sprintf (name, "op%u", pos);
2445 else
2446 sprintf (name, "o%u%u", level, pos);
2449 /* Generate matching code for the decision tree operand which is
2450 a predicate. */
2452 unsigned
2453 dt_operand::gen_predicate (FILE *f, int indent, const char *opname, bool gimple)
2455 predicate *p = as_a <predicate *> (op);
2457 if (p->p->matchers.exists ())
2459 /* If this is a predicate generated from a pattern mangle its
2460 name and pass on the valueize hook. */
2461 if (gimple)
2462 fprintf_indent (f, indent, "if (gimple_%s (%s, valueize))\n",
2463 p->p->id, opname);
2464 else
2465 fprintf_indent (f, indent, "if (tree_%s (%s))\n", p->p->id, opname);
2467 else
2468 fprintf_indent (f, indent, "if (%s (%s))\n", p->p->id, opname);
2469 fprintf_indent (f, indent + 2, "{\n");
2470 return 1;
2473 /* Generate matching code for the decision tree operand which is
2474 a capture-match. */
2476 unsigned
2477 dt_operand::gen_match_op (FILE *f, int indent, const char *opname)
2479 char match_opname[20];
2480 match_dop->get_name (match_opname);
2481 fprintf_indent (f, indent, "if (%s == %s || operand_equal_p (%s, %s, 0))\n",
2482 opname, match_opname, opname, match_opname);
2483 fprintf_indent (f, indent + 2, "{\n");
2484 return 1;
2487 /* Generate GIMPLE matching code for the decision tree operand. */
2489 unsigned
2490 dt_operand::gen_gimple_expr (FILE *f, int indent)
2492 expr *e = static_cast<expr *> (op);
2493 id_base *id = e->operation;
2494 unsigned n_ops = e->ops.length ();
2496 for (unsigned i = 0; i < n_ops; ++i)
2498 char child_opname[20];
2499 gen_opname (child_opname, i);
2501 if (id->kind == id_base::CODE)
2503 if (e->is_generic
2504 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2505 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
2507 /* ??? If this is a memory operation we can't (and should not)
2508 match this. The only sensible operand types are
2509 SSA names and invariants. */
2510 fprintf_indent (f, indent,
2511 "tree %s = TREE_OPERAND (gimple_assign_rhs1 (def), %i);\n",
2512 child_opname, i);
2513 fprintf_indent (f, indent,
2514 "if ((TREE_CODE (%s) == SSA_NAME\n",
2515 child_opname);
2516 fprintf_indent (f, indent,
2517 " || is_gimple_min_invariant (%s))\n",
2518 child_opname);
2519 fprintf_indent (f, indent,
2520 " && (%s = do_valueize (valueize, %s)))\n",
2521 child_opname, child_opname);
2522 fprintf_indent (f, indent,
2523 " {\n");
2524 indent += 4;
2525 continue;
2527 else
2528 fprintf_indent (f, indent,
2529 "tree %s = gimple_assign_rhs%u (def);\n",
2530 child_opname, i + 1);
2532 else
2533 fprintf_indent (f, indent,
2534 "tree %s = gimple_call_arg (def, %u);\n",
2535 child_opname, i);
2536 fprintf_indent (f, indent,
2537 "if ((%s = do_valueize (valueize, %s)))\n",
2538 child_opname, child_opname);
2539 fprintf_indent (f, indent, " {\n");
2540 indent += 4;
2542 /* While the toplevel operands are canonicalized by the caller
2543 after valueizing operands of sub-expressions we have to
2544 re-canonicalize operand order. */
2545 if (operator_id *code = dyn_cast <operator_id *> (id))
2547 /* ??? We can't canonicalize tcc_comparison operands here
2548 because that requires changing the comparison code which
2549 we already matched... */
2550 if (commutative_tree_code (code->code)
2551 || commutative_ternary_tree_code (code->code))
2553 char child_opname0[20], child_opname1[20];
2554 gen_opname (child_opname0, 0);
2555 gen_opname (child_opname1, 1);
2556 fprintf_indent (f, indent,
2557 "if (tree_swap_operands_p (%s, %s, false))\n",
2558 child_opname0, child_opname1);
2559 fprintf_indent (f, indent,
2560 " std::swap (%s, %s);\n",
2561 child_opname0, child_opname1);
2565 return n_ops;
2568 /* Generate GENERIC matching code for the decision tree operand. */
2570 unsigned
2571 dt_operand::gen_generic_expr (FILE *f, int indent, const char *opname)
2573 expr *e = static_cast<expr *> (op);
2574 unsigned n_ops = e->ops.length ();
2576 for (unsigned i = 0; i < n_ops; ++i)
2578 char child_opname[20];
2579 gen_opname (child_opname, i);
2581 if (e->operation->kind == id_base::CODE)
2582 fprintf_indent (f, indent, "tree %s = TREE_OPERAND (%s, %u);\n",
2583 child_opname, opname, i);
2584 else
2585 fprintf_indent (f, indent, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
2586 child_opname, opname, i);
2589 return 0;
2592 /* Generate matching code for the children of the decision tree node. */
2594 void
2595 dt_node::gen_kids (FILE *f, int indent, bool gimple)
2597 auto_vec<dt_operand *> gimple_exprs;
2598 auto_vec<dt_operand *> generic_exprs;
2599 auto_vec<dt_operand *> fns;
2600 auto_vec<dt_operand *> generic_fns;
2601 auto_vec<dt_operand *> preds;
2602 auto_vec<dt_node *> others;
2604 for (unsigned i = 0; i < kids.length (); ++i)
2606 if (kids[i]->type == dt_node::DT_OPERAND)
2608 dt_operand *op = as_a<dt_operand *> (kids[i]);
2609 if (expr *e = dyn_cast <expr *> (op->op))
2611 if (e->ops.length () == 0
2612 && (!gimple || !(*e->operation == CONSTRUCTOR)))
2613 generic_exprs.safe_push (op);
2614 else if (e->operation->kind == id_base::FN)
2616 if (gimple)
2617 fns.safe_push (op);
2618 else
2619 generic_fns.safe_push (op);
2621 else if (e->operation->kind == id_base::PREDICATE)
2622 preds.safe_push (op);
2623 else
2625 if (gimple && !e->is_generic)
2626 gimple_exprs.safe_push (op);
2627 else
2628 generic_exprs.safe_push (op);
2631 else if (op->op->type == operand::OP_PREDICATE)
2632 others.safe_push (kids[i]);
2633 else
2634 gcc_unreachable ();
2636 else if (kids[i]->type == dt_node::DT_SIMPLIFY)
2637 others.safe_push (kids[i]);
2638 else if (kids[i]->type == dt_node::DT_MATCH
2639 || kids[i]->type == dt_node::DT_TRUE)
2641 /* A DT_TRUE operand serves as a barrier - generate code now
2642 for what we have collected sofar.
2643 Like DT_TRUE, DT_MATCH serves as a barrier as it can cause
2644 dependent matches to get out-of-order. Generate code now
2645 for what we have collected sofar. */
2646 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2647 fns, generic_fns, preds, others);
2648 /* And output the true operand itself. */
2649 kids[i]->gen (f, indent, gimple);
2650 gimple_exprs.truncate (0);
2651 generic_exprs.truncate (0);
2652 fns.truncate (0);
2653 generic_fns.truncate (0);
2654 preds.truncate (0);
2655 others.truncate (0);
2657 else
2658 gcc_unreachable ();
2661 /* Generate code for the remains. */
2662 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2663 fns, generic_fns, preds, others);
2666 /* Generate matching code for the children of the decision tree node. */
2668 void
2669 dt_node::gen_kids_1 (FILE *f, int indent, bool gimple,
2670 vec<dt_operand *> gimple_exprs,
2671 vec<dt_operand *> generic_exprs,
2672 vec<dt_operand *> fns,
2673 vec<dt_operand *> generic_fns,
2674 vec<dt_operand *> preds,
2675 vec<dt_node *> others)
2677 char buf[128];
2678 char *kid_opname = buf;
2680 unsigned exprs_len = gimple_exprs.length ();
2681 unsigned gexprs_len = generic_exprs.length ();
2682 unsigned fns_len = fns.length ();
2683 unsigned gfns_len = generic_fns.length ();
2685 if (exprs_len || fns_len || gexprs_len || gfns_len)
2687 if (exprs_len)
2688 gimple_exprs[0]->get_name (kid_opname);
2689 else if (fns_len)
2690 fns[0]->get_name (kid_opname);
2691 else if (gfns_len)
2692 generic_fns[0]->get_name (kid_opname);
2693 else
2694 generic_exprs[0]->get_name (kid_opname);
2696 fprintf_indent (f, indent, "switch (TREE_CODE (%s))\n", kid_opname);
2697 fprintf_indent (f, indent, " {\n");
2698 indent += 2;
2701 if (exprs_len || fns_len)
2703 fprintf_indent (f, indent,
2704 "case SSA_NAME:\n");
2705 fprintf_indent (f, indent,
2706 " if (do_valueize (valueize, %s) != NULL_TREE)\n",
2707 kid_opname);
2708 fprintf_indent (f, indent,
2709 " {\n");
2710 fprintf_indent (f, indent,
2711 " gimple *def_stmt = SSA_NAME_DEF_STMT (%s);\n",
2712 kid_opname);
2714 indent += 6;
2715 if (exprs_len)
2717 fprintf_indent (f, indent,
2718 "if (gassign *def = dyn_cast <gassign *> (def_stmt))\n");
2719 fprintf_indent (f, indent,
2720 " switch (gimple_assign_rhs_code (def))\n");
2721 indent += 4;
2722 fprintf_indent (f, indent, "{\n");
2723 for (unsigned i = 0; i < exprs_len; ++i)
2725 expr *e = as_a <expr *> (gimple_exprs[i]->op);
2726 id_base *op = e->operation;
2727 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2728 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2729 else
2730 fprintf_indent (f, indent, "case %s:\n", op->id);
2731 fprintf_indent (f, indent, " {\n");
2732 gimple_exprs[i]->gen (f, indent + 4, true);
2733 fprintf_indent (f, indent, " break;\n");
2734 fprintf_indent (f, indent, " }\n");
2736 fprintf_indent (f, indent, "default:;\n");
2737 fprintf_indent (f, indent, "}\n");
2738 indent -= 4;
2741 if (fns_len)
2743 fprintf_indent (f, indent,
2744 "%sif (gcall *def = dyn_cast <gcall *>"
2745 " (def_stmt))\n",
2746 exprs_len ? "else " : "");
2747 fprintf_indent (f, indent,
2748 " switch (gimple_call_combined_fn (def))\n");
2750 indent += 4;
2751 fprintf_indent (f, indent, "{\n");
2752 for (unsigned i = 0; i < fns_len; ++i)
2754 expr *e = as_a <expr *>(fns[i]->op);
2755 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2756 fprintf_indent (f, indent, " {\n");
2757 fns[i]->gen (f, indent + 4, true);
2758 fprintf_indent (f, indent, " break;\n");
2759 fprintf_indent (f, indent, " }\n");
2762 fprintf_indent (f, indent, "default:;\n");
2763 fprintf_indent (f, indent, "}\n");
2764 indent -= 4;
2767 indent -= 6;
2768 fprintf_indent (f, indent, " }\n");
2769 fprintf_indent (f, indent, " break;\n");
2772 for (unsigned i = 0; i < generic_exprs.length (); ++i)
2774 expr *e = as_a <expr *>(generic_exprs[i]->op);
2775 id_base *op = e->operation;
2776 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2777 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2778 else
2779 fprintf_indent (f, indent, "case %s:\n", op->id);
2780 fprintf_indent (f, indent, " {\n");
2781 generic_exprs[i]->gen (f, indent + 4, gimple);
2782 fprintf_indent (f, indent, " break;\n");
2783 fprintf_indent (f, indent, " }\n");
2786 if (gfns_len)
2788 fprintf_indent (f, indent,
2789 "case CALL_EXPR:\n");
2790 fprintf_indent (f, indent,
2791 " switch (get_call_combined_fn (%s))\n",
2792 kid_opname);
2793 fprintf_indent (f, indent,
2794 " {\n");
2795 indent += 4;
2797 for (unsigned j = 0; j < generic_fns.length (); ++j)
2799 expr *e = as_a <expr *>(generic_fns[j]->op);
2800 gcc_assert (e->operation->kind == id_base::FN);
2802 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2803 fprintf_indent (f, indent, " {\n");
2804 generic_fns[j]->gen (f, indent + 4, false);
2805 fprintf_indent (f, indent, " break;\n");
2806 fprintf_indent (f, indent, " }\n");
2808 fprintf_indent (f, indent, "default:;\n");
2810 indent -= 4;
2811 fprintf_indent (f, indent, " }\n");
2812 fprintf_indent (f, indent, " break;\n");
2815 /* Close switch (TREE_CODE ()). */
2816 if (exprs_len || fns_len || gexprs_len || gfns_len)
2818 indent -= 4;
2819 fprintf_indent (f, indent, " default:;\n");
2820 fprintf_indent (f, indent, " }\n");
2823 for (unsigned i = 0; i < preds.length (); ++i)
2825 expr *e = as_a <expr *> (preds[i]->op);
2826 predicate_id *p = as_a <predicate_id *> (e->operation);
2827 preds[i]->get_name (kid_opname);
2828 fprintf_indent (f, indent, "tree %s_pops[%d];\n", kid_opname, p->nargs);
2829 fprintf_indent (f, indent, "if (%s_%s (%s, %s_pops%s))\n",
2830 gimple ? "gimple" : "tree",
2831 p->id, kid_opname, kid_opname,
2832 gimple ? ", valueize" : "");
2833 fprintf_indent (f, indent, " {\n");
2834 for (int j = 0; j < p->nargs; ++j)
2836 char child_opname[20];
2837 preds[i]->gen_opname (child_opname, j);
2838 fprintf_indent (f, indent + 4, "tree %s = %s_pops[%d];\n",
2839 child_opname, kid_opname, j);
2841 preds[i]->gen_kids (f, indent + 4, gimple);
2842 fprintf (f, "}\n");
2845 for (unsigned i = 0; i < others.length (); ++i)
2846 others[i]->gen (f, indent, gimple);
2849 /* Generate matching code for the decision tree operand. */
2851 void
2852 dt_operand::gen (FILE *f, int indent, bool gimple)
2854 char opname[20];
2855 get_name (opname);
2857 unsigned n_braces = 0;
2859 if (type == DT_OPERAND)
2860 switch (op->type)
2862 case operand::OP_PREDICATE:
2863 n_braces = gen_predicate (f, indent, opname, gimple);
2864 break;
2866 case operand::OP_EXPR:
2867 if (gimple)
2868 n_braces = gen_gimple_expr (f, indent);
2869 else
2870 n_braces = gen_generic_expr (f, indent, opname);
2871 break;
2873 default:
2874 gcc_unreachable ();
2876 else if (type == DT_TRUE)
2878 else if (type == DT_MATCH)
2879 n_braces = gen_match_op (f, indent, opname);
2880 else
2881 gcc_unreachable ();
2883 indent += 4 * n_braces;
2884 gen_kids (f, indent, gimple);
2886 for (unsigned i = 0; i < n_braces; ++i)
2888 indent -= 4;
2889 if (indent < 0)
2890 indent = 0;
2891 fprintf_indent (f, indent, " }\n");
2896 /* Generate code for the '(if ...)', '(with ..)' and actual transform
2897 step of a '(simplify ...)' or '(match ...)'. This handles everything
2898 that is not part of the decision tree (simplify->match).
2899 Main recursive worker. */
2901 void
2902 dt_simplify::gen_1 (FILE *f, int indent, bool gimple, operand *result)
2904 if (result)
2906 if (with_expr *w = dyn_cast <with_expr *> (result))
2908 fprintf_indent (f, indent, "{\n");
2909 indent += 4;
2910 output_line_directive (f, w->location);
2911 w->with->gen_transform (f, indent, NULL, true, 1, "type", NULL);
2912 gen_1 (f, indent, gimple, w->subexpr);
2913 indent -= 4;
2914 fprintf_indent (f, indent, "}\n");
2915 return;
2917 else if (if_expr *ife = dyn_cast <if_expr *> (result))
2919 output_line_directive (f, ife->location);
2920 fprintf_indent (f, indent, "if (");
2921 ife->cond->gen_transform (f, indent, NULL, true, 1, "type", NULL);
2922 fprintf (f, ")\n");
2923 fprintf_indent (f, indent + 2, "{\n");
2924 indent += 4;
2925 gen_1 (f, indent, gimple, ife->trueexpr);
2926 indent -= 4;
2927 fprintf_indent (f, indent + 2, "}\n");
2928 if (ife->falseexpr)
2930 fprintf_indent (f, indent, "else\n");
2931 fprintf_indent (f, indent + 2, "{\n");
2932 indent += 4;
2933 gen_1 (f, indent, gimple, ife->falseexpr);
2934 indent -= 4;
2935 fprintf_indent (f, indent + 2, "}\n");
2937 return;
2941 /* Analyze captures and perform early-outs on the incoming arguments
2942 that cover cases we cannot handle. */
2943 capture_info cinfo (s, result, gimple);
2944 if (s->kind == simplify::SIMPLIFY)
2946 if (!gimple)
2948 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
2949 if (cinfo.force_no_side_effects & (1 << i))
2951 fprintf_indent (f, indent,
2952 "if (TREE_SIDE_EFFECTS (op%d)) return NULL_TREE;\n",
2954 if (verbose >= 1)
2955 warning_at (as_a <expr *> (s->match)->ops[i]->location,
2956 "forcing toplevel operand to have no "
2957 "side-effects");
2959 for (int i = 0; i <= s->capture_max; ++i)
2960 if (cinfo.info[i].cse_p)
2962 else if (cinfo.info[i].force_no_side_effects_p
2963 && (cinfo.info[i].toplevel_msk
2964 & cinfo.force_no_side_effects) == 0)
2966 fprintf_indent (f, indent,
2967 "if (TREE_SIDE_EFFECTS (captures[%d])) "
2968 "return NULL_TREE;\n", i);
2969 if (verbose >= 1)
2970 warning_at (cinfo.info[i].c->location,
2971 "forcing captured operand to have no "
2972 "side-effects");
2974 else if ((cinfo.info[i].toplevel_msk
2975 & cinfo.force_no_side_effects) != 0)
2976 /* Mark capture as having no side-effects if we had to verify
2977 that via forced toplevel operand checks. */
2978 cinfo.info[i].force_no_side_effects_p = true;
2980 if (gimple)
2982 /* Force single-use restriction by only allowing simple
2983 results via setting seq to NULL. */
2984 fprintf_indent (f, indent, "gimple_seq *lseq = seq;\n");
2985 bool first_p = true;
2986 for (int i = 0; i <= s->capture_max; ++i)
2987 if (cinfo.info[i].force_single_use)
2989 if (first_p)
2991 fprintf_indent (f, indent, "if (lseq\n");
2992 fprintf_indent (f, indent, " && (");
2993 first_p = false;
2995 else
2997 fprintf (f, "\n");
2998 fprintf_indent (f, indent, " || ");
3000 fprintf (f, "!single_use (captures[%d])", i);
3002 if (!first_p)
3004 fprintf (f, "))\n");
3005 fprintf_indent (f, indent, " lseq = NULL;\n");
3010 fprintf_indent (f, indent, "if (dump_file && (dump_flags & TDF_DETAILS)) "
3011 "fprintf (dump_file, \"Applying pattern ");
3012 output_line_directive (f,
3013 result ? result->location : s->match->location, true);
3014 fprintf (f, ", %%s:%%d\\n\", __FILE__, __LINE__);\n");
3016 if (!result)
3018 /* If there is no result then this is a predicate implementation. */
3019 fprintf_indent (f, indent, "return true;\n");
3021 else if (gimple)
3023 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
3024 in outermost position). */
3025 if (result->type == operand::OP_EXPR
3026 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
3027 result = as_a <expr *> (result)->ops[0];
3028 if (result->type == operand::OP_EXPR)
3030 expr *e = as_a <expr *> (result);
3031 id_base *opr = e->operation;
3032 bool is_predicate = false;
3033 /* When we delay operator substituting during lowering of fors we
3034 make sure that for code-gen purposes the effects of each substitute
3035 are the same. Thus just look at that. */
3036 if (user_id *uid = dyn_cast <user_id *> (opr))
3037 opr = uid->substitutes[0];
3038 else if (is_a <predicate_id *> (opr))
3039 is_predicate = true;
3040 if (!is_predicate)
3041 fprintf_indent (f, indent, "*res_code = %s;\n",
3042 *e->operation == CONVERT_EXPR
3043 ? "NOP_EXPR" : e->operation->id);
3044 for (unsigned j = 0; j < e->ops.length (); ++j)
3046 char dest[32];
3047 snprintf (dest, 32, "res_ops[%d]", j);
3048 const char *optype
3049 = get_operand_type (opr,
3050 "type", e->expr_type,
3051 j == 0 ? NULL : "TREE_TYPE (res_ops[0])");
3052 /* We need to expand GENERIC conditions we captured from
3053 COND_EXPRs and we need to unshare them when substituting
3054 into COND_EXPRs. */
3055 int cond_handling = 0;
3056 if (!is_predicate)
3057 cond_handling = ((*opr == COND_EXPR
3058 || *opr == VEC_COND_EXPR) && j == 0) ? 1 : 2;
3059 e->ops[j]->gen_transform (f, indent, dest, true, 1, optype,
3060 &cinfo, indexes, cond_handling);
3063 /* Re-fold the toplevel result. It's basically an embedded
3064 gimple_build w/o actually building the stmt. */
3065 if (!is_predicate)
3066 fprintf_indent (f, indent,
3067 "gimple_resimplify%d (lseq, res_code, type, "
3068 "res_ops, valueize);\n", e->ops.length ());
3070 else if (result->type == operand::OP_CAPTURE
3071 || result->type == operand::OP_C_EXPR)
3073 result->gen_transform (f, indent, "res_ops[0]", true, 1, "type",
3074 &cinfo, indexes);
3075 fprintf_indent (f, indent, "*res_code = TREE_CODE (res_ops[0]);\n");
3076 if (is_a <capture *> (result)
3077 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
3079 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
3080 with substituting a capture of that. */
3081 fprintf_indent (f, indent,
3082 "if (COMPARISON_CLASS_P (res_ops[0]))\n");
3083 fprintf_indent (f, indent,
3084 " {\n");
3085 fprintf_indent (f, indent,
3086 " tree tem = res_ops[0];\n");
3087 fprintf_indent (f, indent,
3088 " res_ops[0] = TREE_OPERAND (tem, 0);\n");
3089 fprintf_indent (f, indent,
3090 " res_ops[1] = TREE_OPERAND (tem, 1);\n");
3091 fprintf_indent (f, indent,
3092 " }\n");
3095 else
3096 gcc_unreachable ();
3097 fprintf_indent (f, indent, "return true;\n");
3099 else /* GENERIC */
3101 bool is_predicate = false;
3102 if (result->type == operand::OP_EXPR)
3104 expr *e = as_a <expr *> (result);
3105 id_base *opr = e->operation;
3106 /* When we delay operator substituting during lowering of fors we
3107 make sure that for code-gen purposes the effects of each substitute
3108 are the same. Thus just look at that. */
3109 if (user_id *uid = dyn_cast <user_id *> (opr))
3110 opr = uid->substitutes[0];
3111 else if (is_a <predicate_id *> (opr))
3112 is_predicate = true;
3113 /* Search for captures used multiple times in the result expression
3114 and wrap them in a SAVE_EXPR. Allow as many uses as in the
3115 original expression. */
3116 if (!is_predicate)
3117 for (int i = 0; i < s->capture_max + 1; ++i)
3119 if (cinfo.info[i].same_as != (unsigned)i
3120 || cinfo.info[i].cse_p)
3121 continue;
3122 if (cinfo.info[i].result_use_count
3123 > cinfo.info[i].match_use_count)
3124 fprintf_indent (f, indent,
3125 "if (! tree_invariant_p (captures[%d])) "
3126 "return NULL_TREE;\n", i);
3128 for (unsigned j = 0; j < e->ops.length (); ++j)
3130 char dest[32];
3131 if (is_predicate)
3132 snprintf (dest, 32, "res_ops[%d]", j);
3133 else
3135 fprintf_indent (f, indent, "tree res_op%d;\n", j);
3136 snprintf (dest, 32, "res_op%d", j);
3138 const char *optype
3139 = get_operand_type (opr,
3140 "type", e->expr_type,
3141 j == 0
3142 ? NULL : "TREE_TYPE (res_op0)");
3143 e->ops[j]->gen_transform (f, indent, dest, false, 1, optype,
3144 &cinfo, indexes);
3146 if (is_predicate)
3147 fprintf_indent (f, indent, "return true;\n");
3148 else
3150 fprintf_indent (f, indent, "tree res;\n");
3151 /* Re-fold the toplevel result. Use non_lvalue to
3152 build NON_LVALUE_EXPRs so they get properly
3153 ignored when in GIMPLE form. */
3154 if (*opr == NON_LVALUE_EXPR)
3155 fprintf_indent (f, indent,
3156 "res = non_lvalue_loc (loc, res_op0);\n");
3157 else
3159 if (is_a <operator_id *> (opr))
3160 fprintf_indent (f, indent,
3161 "res = fold_build%d_loc (loc, %s, type",
3162 e->ops.length (),
3163 *e->operation == CONVERT_EXPR
3164 ? "NOP_EXPR" : e->operation->id);
3165 else
3166 fprintf_indent (f, indent,
3167 "res = maybe_build_call_expr_loc (loc, "
3168 "%s, type, %d", e->operation->id,
3169 e->ops.length());
3170 for (unsigned j = 0; j < e->ops.length (); ++j)
3171 fprintf (f, ", res_op%d", j);
3172 fprintf (f, ");\n");
3173 if (!is_a <operator_id *> (opr))
3175 fprintf_indent (f, indent, "if (!res)\n");
3176 fprintf_indent (f, indent, " return NULL_TREE;\n");
3181 else if (result->type == operand::OP_CAPTURE
3182 || result->type == operand::OP_C_EXPR)
3185 fprintf_indent (f, indent, "tree res;\n");
3186 result->gen_transform (f, indent, "res", false, 1, "type",
3187 &cinfo, indexes);
3189 else
3190 gcc_unreachable ();
3191 if (!is_predicate)
3193 /* Search for captures not used in the result expression and dependent
3194 on TREE_SIDE_EFFECTS emit omit_one_operand. */
3195 for (int i = 0; i < s->capture_max + 1; ++i)
3197 if (cinfo.info[i].same_as != (unsigned)i)
3198 continue;
3199 if (!cinfo.info[i].force_no_side_effects_p
3200 && !cinfo.info[i].expr_p
3201 && cinfo.info[i].result_use_count == 0)
3203 fprintf_indent (f, indent,
3204 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
3206 fprintf_indent (f, indent + 2,
3207 "res = build2_loc (loc, COMPOUND_EXPR, type, "
3208 "fold_ignored_result (captures[%d]), res);\n",
3212 fprintf_indent (f, indent, "return res;\n");
3217 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3218 step of a '(simplify ...)' or '(match ...)'. This handles everything
3219 that is not part of the decision tree (simplify->match). */
3221 void
3222 dt_simplify::gen (FILE *f, int indent, bool gimple)
3224 fprintf_indent (f, indent, "{\n");
3225 indent += 2;
3226 output_line_directive (f,
3227 s->result ? s->result->location : s->match->location);
3228 if (s->capture_max >= 0)
3230 char opname[20];
3231 fprintf_indent (f, indent, "tree captures[%u] ATTRIBUTE_UNUSED = { %s",
3232 s->capture_max + 1, indexes[0]->get_name (opname));
3234 for (int i = 1; i <= s->capture_max; ++i)
3236 if (!indexes[i])
3237 break;
3238 fprintf (f, ", %s", indexes[i]->get_name (opname));
3240 fprintf (f, " };\n");
3243 /* If we have a split-out function for the actual transform, call it. */
3244 if (info && info->fname)
3246 if (gimple)
3248 fprintf_indent (f, indent, "if (%s (res_code, res_ops, seq, "
3249 "valueize, type, captures", info->fname);
3250 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3251 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3252 fprintf (f, "))\n");
3253 fprintf_indent (f, indent, " return true;\n");
3255 else
3257 fprintf_indent (f, indent, "tree res = %s (loc, type",
3258 info->fname);
3259 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3260 fprintf (f, ", op%d", i);
3261 fprintf (f, ", captures");
3262 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3263 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3264 fprintf (f, ");\n");
3265 fprintf_indent (f, indent, "if (res) return res;\n");
3268 else
3270 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3272 if (is_a <operator_id *> (s->for_subst_vec[i].second))
3273 fprintf_indent (f, indent, "enum tree_code %s = %s;\n",
3274 s->for_subst_vec[i].first->id,
3275 s->for_subst_vec[i].second->id);
3276 else if (is_a <fn_id *> (s->for_subst_vec[i].second))
3277 fprintf_indent (f, indent, "combined_fn %s = %s;\n",
3278 s->for_subst_vec[i].first->id,
3279 s->for_subst_vec[i].second->id);
3280 else
3281 gcc_unreachable ();
3283 gen_1 (f, indent, gimple, s->result);
3286 indent -= 2;
3287 fprintf_indent (f, indent, "}\n");
3291 /* Hash function for finding equivalent transforms. */
3293 hashval_t
3294 sinfo_hashmap_traits::hash (const key_type &v)
3296 /* Only bother to compare those originating from the same source pattern. */
3297 return v->s->result->location;
3300 /* Compare function for finding equivalent transforms. */
3302 static bool
3303 compare_op (operand *o1, simplify *s1, operand *o2, simplify *s2)
3305 if (o1->type != o2->type)
3306 return false;
3308 switch (o1->type)
3310 case operand::OP_IF:
3312 if_expr *if1 = as_a <if_expr *> (o1);
3313 if_expr *if2 = as_a <if_expr *> (o2);
3314 /* ??? Properly compare c-exprs. */
3315 if (if1->cond != if2->cond)
3316 return false;
3317 if (!compare_op (if1->trueexpr, s1, if2->trueexpr, s2))
3318 return false;
3319 if (if1->falseexpr != if2->falseexpr
3320 || (if1->falseexpr
3321 && !compare_op (if1->falseexpr, s1, if2->falseexpr, s2)))
3322 return false;
3323 return true;
3325 case operand::OP_WITH:
3327 with_expr *with1 = as_a <with_expr *> (o1);
3328 with_expr *with2 = as_a <with_expr *> (o2);
3329 if (with1->with != with2->with)
3330 return false;
3331 return compare_op (with1->subexpr, s1, with2->subexpr, s2);
3333 default:;
3336 /* We've hit a result. Time to compare capture-infos - this is required
3337 in addition to the conservative pointer-equivalency of the result IL. */
3338 capture_info cinfo1 (s1, o1, true);
3339 capture_info cinfo2 (s2, o2, true);
3341 if (cinfo1.force_no_side_effects != cinfo2.force_no_side_effects
3342 || cinfo1.info.length () != cinfo2.info.length ())
3343 return false;
3345 for (unsigned i = 0; i < cinfo1.info.length (); ++i)
3347 if (cinfo1.info[i].expr_p != cinfo2.info[i].expr_p
3348 || cinfo1.info[i].cse_p != cinfo2.info[i].cse_p
3349 || (cinfo1.info[i].force_no_side_effects_p
3350 != cinfo2.info[i].force_no_side_effects_p)
3351 || cinfo1.info[i].force_single_use != cinfo2.info[i].force_single_use
3352 || cinfo1.info[i].cond_expr_cond_p != cinfo2.info[i].cond_expr_cond_p
3353 /* toplevel_msk is an optimization */
3354 || cinfo1.info[i].result_use_count != cinfo2.info[i].result_use_count
3355 || cinfo1.info[i].same_as != cinfo2.info[i].same_as
3356 /* the pointer back to the capture is for diagnostics only */)
3357 return false;
3360 /* ??? Deep-compare the actual result. */
3361 return o1 == o2;
3364 bool
3365 sinfo_hashmap_traits::equal_keys (const key_type &v,
3366 const key_type &candidate)
3368 return compare_op (v->s->result, v->s, candidate->s->result, candidate->s);
3372 /* Main entry to generate code for matching GIMPLE IL off the decision
3373 tree. */
3375 void
3376 decision_tree::gen (FILE *f, bool gimple)
3378 sinfo_map_t si;
3380 root->analyze (si);
3382 fprintf (stderr, "%s decision tree has %u leafs, maximum depth %u and "
3383 "a total number of %u nodes\n",
3384 gimple ? "GIMPLE" : "GENERIC",
3385 root->num_leafs, root->max_level, root->total_size);
3387 /* First split out the transform part of equal leafs. */
3388 unsigned rcnt = 0;
3389 unsigned fcnt = 1;
3390 for (sinfo_map_t::iterator iter = si.begin ();
3391 iter != si.end (); ++iter)
3393 sinfo *s = (*iter).second;
3394 /* Do not split out single uses. */
3395 if (s->cnt <= 1)
3396 continue;
3398 rcnt += s->cnt - 1;
3399 if (verbose >= 1)
3401 fprintf (stderr, "found %u uses of", s->cnt);
3402 output_line_directive (stderr, s->s->s->result->location);
3405 /* Generate a split out function with the leaf transform code. */
3406 s->fname = xasprintf ("%s_simplify_%u", gimple ? "gimple" : "generic",
3407 fcnt++);
3408 if (gimple)
3409 fprintf (f, "\nstatic bool\n"
3410 "%s (code_helper *res_code, tree *res_ops,\n"
3411 " gimple_seq *seq, tree (*valueize)(tree) "
3412 "ATTRIBUTE_UNUSED,\n"
3413 " tree ARG_UNUSED (type), tree *ARG_UNUSED "
3414 "(captures)\n",
3415 s->fname);
3416 else
3418 fprintf (f, "\nstatic tree\n"
3419 "%s (location_t ARG_UNUSED (loc), tree ARG_UNUSED (type),\n",
3420 (*iter).second->fname);
3421 for (unsigned i = 0;
3422 i < as_a <expr *>(s->s->s->match)->ops.length (); ++i)
3423 fprintf (f, " tree ARG_UNUSED (op%d),", i);
3424 fprintf (f, " tree *captures\n");
3426 for (unsigned i = 0; i < s->s->s->for_subst_vec.length (); ++i)
3428 if (is_a <operator_id *> (s->s->s->for_subst_vec[i].second))
3429 fprintf (f, ", enum tree_code ARG_UNUSED (%s)",
3430 s->s->s->for_subst_vec[i].first->id);
3431 else if (is_a <fn_id *> (s->s->s->for_subst_vec[i].second))
3432 fprintf (f, ", combined_fn ARG_UNUSED (%s)",
3433 s->s->s->for_subst_vec[i].first->id);
3436 fprintf (f, ")\n{\n");
3437 s->s->gen_1 (f, 2, gimple, s->s->s->result);
3438 if (gimple)
3439 fprintf (f, " return false;\n");
3440 else
3441 fprintf (f, " return NULL_TREE;\n");
3442 fprintf (f, "}\n");
3444 fprintf (stderr, "removed %u duplicate tails\n", rcnt);
3446 for (unsigned n = 1; n <= 3; ++n)
3448 /* First generate split-out functions. */
3449 for (unsigned i = 0; i < root->kids.length (); i++)
3451 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3452 expr *e = static_cast<expr *>(dop->op);
3453 if (e->ops.length () != n
3454 /* Builtin simplifications are somewhat premature on
3455 GENERIC. The following drops patterns with outermost
3456 calls. It's easy to emit overloads for function code
3457 though if necessary. */
3458 || (!gimple
3459 && e->operation->kind != id_base::CODE))
3460 continue;
3462 if (gimple)
3463 fprintf (f, "\nstatic bool\n"
3464 "gimple_simplify_%s (code_helper *res_code, tree *res_ops,\n"
3465 " gimple_seq *seq, tree (*valueize)(tree) "
3466 "ATTRIBUTE_UNUSED,\n"
3467 " code_helper ARG_UNUSED (code), tree "
3468 "ARG_UNUSED (type)\n",
3469 e->operation->id);
3470 else
3471 fprintf (f, "\nstatic tree\n"
3472 "generic_simplify_%s (location_t ARG_UNUSED (loc), enum "
3473 "tree_code ARG_UNUSED (code), tree ARG_UNUSED (type)",
3474 e->operation->id);
3475 for (unsigned i = 0; i < n; ++i)
3476 fprintf (f, ", tree op%d", i);
3477 fprintf (f, ")\n");
3478 fprintf (f, "{\n");
3479 dop->gen_kids (f, 2, gimple);
3480 if (gimple)
3481 fprintf (f, " return false;\n");
3482 else
3483 fprintf (f, " return NULL_TREE;\n");
3484 fprintf (f, "}\n");
3487 /* Then generate the main entry with the outermost switch and
3488 tail-calls to the split-out functions. */
3489 if (gimple)
3490 fprintf (f, "\nstatic bool\n"
3491 "gimple_simplify (code_helper *res_code, tree *res_ops,\n"
3492 " gimple_seq *seq, tree (*valueize)(tree),\n"
3493 " code_helper code, tree type");
3494 else
3495 fprintf (f, "\ntree\n"
3496 "generic_simplify (location_t loc, enum tree_code code, "
3497 "tree type ATTRIBUTE_UNUSED");
3498 for (unsigned i = 0; i < n; ++i)
3499 fprintf (f, ", tree op%d", i);
3500 fprintf (f, ")\n");
3501 fprintf (f, "{\n");
3503 if (gimple)
3504 fprintf (f, " switch (code.get_rep())\n"
3505 " {\n");
3506 else
3507 fprintf (f, " switch (code)\n"
3508 " {\n");
3509 for (unsigned i = 0; i < root->kids.length (); i++)
3511 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3512 expr *e = static_cast<expr *>(dop->op);
3513 if (e->ops.length () != n
3514 /* Builtin simplifications are somewhat premature on
3515 GENERIC. The following drops patterns with outermost
3516 calls. It's easy to emit overloads for function code
3517 though if necessary. */
3518 || (!gimple
3519 && e->operation->kind != id_base::CODE))
3520 continue;
3522 if (*e->operation == CONVERT_EXPR
3523 || *e->operation == NOP_EXPR)
3524 fprintf (f, " CASE_CONVERT:\n");
3525 else
3526 fprintf (f, " case %s%s:\n",
3527 is_a <fn_id *> (e->operation) ? "-" : "",
3528 e->operation->id);
3529 if (gimple)
3530 fprintf (f, " return gimple_simplify_%s (res_code, res_ops, "
3531 "seq, valueize, code, type", e->operation->id);
3532 else
3533 fprintf (f, " return generic_simplify_%s (loc, code, type",
3534 e->operation->id);
3535 for (unsigned i = 0; i < n; ++i)
3536 fprintf (f, ", op%d", i);
3537 fprintf (f, ");\n");
3539 fprintf (f, " default:;\n"
3540 " }\n");
3542 if (gimple)
3543 fprintf (f, " return false;\n");
3544 else
3545 fprintf (f, " return NULL_TREE;\n");
3546 fprintf (f, "}\n");
3550 /* Output code to implement the predicate P from the decision tree DT. */
3552 void
3553 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
3555 fprintf (f, "\nbool\n"
3556 "%s%s (tree t%s%s)\n"
3557 "{\n", gimple ? "gimple_" : "tree_", p->id,
3558 p->nargs > 0 ? ", tree *res_ops" : "",
3559 gimple ? ", tree (*valueize)(tree) ATTRIBUTE_UNUSED" : "");
3560 /* Conveniently make 'type' available. */
3561 fprintf_indent (f, 2, "tree type = TREE_TYPE (t);\n");
3563 if (!gimple)
3564 fprintf_indent (f, 2, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
3565 dt.root->gen_kids (f, 2, gimple);
3567 fprintf_indent (f, 2, "return false;\n"
3568 "}\n");
3571 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
3573 static void
3574 write_header (FILE *f, const char *head)
3576 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
3577 fprintf (f, " a IL pattern matching and simplification description. */\n");
3579 /* Include the header instead of writing it awkwardly quoted here. */
3580 fprintf (f, "\n#include \"%s\"\n", head);
3585 /* AST parsing. */
3587 class parser
3589 public:
3590 parser (cpp_reader *);
3592 private:
3593 const cpp_token *next ();
3594 const cpp_token *peek (unsigned = 1);
3595 const cpp_token *peek_ident (const char * = NULL, unsigned = 1);
3596 const cpp_token *expect (enum cpp_ttype);
3597 const cpp_token *eat_token (enum cpp_ttype);
3598 const char *get_string ();
3599 const char *get_ident ();
3600 const cpp_token *eat_ident (const char *);
3601 const char *get_number ();
3603 id_base *parse_operation ();
3604 operand *parse_capture (operand *, bool);
3605 operand *parse_expr ();
3606 c_expr *parse_c_expr (cpp_ttype);
3607 operand *parse_op ();
3609 void record_operlist (source_location, user_id *);
3611 void parse_pattern ();
3612 operand *parse_result (operand *, predicate_id *);
3613 void push_simplify (simplify::simplify_kind,
3614 vec<simplify *>&, operand *, operand *);
3615 void parse_simplify (simplify::simplify_kind,
3616 vec<simplify *>&, predicate_id *, operand *);
3617 void parse_for (source_location);
3618 void parse_if (source_location);
3619 void parse_predicates (source_location);
3620 void parse_operator_list (source_location);
3622 cpp_reader *r;
3623 vec<c_expr *> active_ifs;
3624 vec<vec<user_id *> > active_fors;
3625 hash_set<user_id *> *oper_lists_set;
3626 vec<user_id *> oper_lists;
3628 cid_map_t *capture_ids;
3630 public:
3631 vec<simplify *> simplifiers;
3632 vec<predicate_id *> user_predicates;
3633 bool parsing_match_operand;
3636 /* Lexing helpers. */
3638 /* Read the next non-whitespace token from R. */
3640 const cpp_token *
3641 parser::next ()
3643 const cpp_token *token;
3646 token = cpp_get_token (r);
3648 while (token->type == CPP_PADDING
3649 && token->type != CPP_EOF);
3650 return token;
3653 /* Peek at the next non-whitespace token from R. */
3655 const cpp_token *
3656 parser::peek (unsigned num)
3658 const cpp_token *token;
3659 unsigned i = 0;
3662 token = cpp_peek_token (r, i++);
3664 while ((token->type == CPP_PADDING
3665 && token->type != CPP_EOF)
3666 || (--num > 0));
3667 /* If we peek at EOF this is a fatal error as it leaves the
3668 cpp_reader in unusable state. Assume we really wanted a
3669 token and thus this EOF is unexpected. */
3670 if (token->type == CPP_EOF)
3671 fatal_at (token, "unexpected end of file");
3672 return token;
3675 /* Peek at the next identifier token (or return NULL if the next
3676 token is not an identifier or equal to ID if supplied). */
3678 const cpp_token *
3679 parser::peek_ident (const char *id, unsigned num)
3681 const cpp_token *token = peek (num);
3682 if (token->type != CPP_NAME)
3683 return 0;
3685 if (id == 0)
3686 return token;
3688 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
3689 if (strcmp (id, t) == 0)
3690 return token;
3692 return 0;
3695 /* Read the next token from R and assert it is of type TK. */
3697 const cpp_token *
3698 parser::expect (enum cpp_ttype tk)
3700 const cpp_token *token = next ();
3701 if (token->type != tk)
3702 fatal_at (token, "expected %s, got %s",
3703 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
3705 return token;
3708 /* Consume the next token from R and assert it is of type TK. */
3710 const cpp_token *
3711 parser::eat_token (enum cpp_ttype tk)
3713 return expect (tk);
3716 /* Read the next token from R and assert it is of type CPP_STRING and
3717 return its value. */
3719 const char *
3720 parser::get_string ()
3722 const cpp_token *token = expect (CPP_STRING);
3723 return (const char *)token->val.str.text;
3726 /* Read the next token from R and assert it is of type CPP_NAME and
3727 return its value. */
3729 const char *
3730 parser::get_ident ()
3732 const cpp_token *token = expect (CPP_NAME);
3733 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
3736 /* Eat an identifier token with value S from R. */
3738 const cpp_token *
3739 parser::eat_ident (const char *s)
3741 const cpp_token *token = peek ();
3742 const char *t = get_ident ();
3743 if (strcmp (s, t) != 0)
3744 fatal_at (token, "expected '%s' got '%s'\n", s, t);
3745 return token;
3748 /* Read the next token from R and assert it is of type CPP_NUMBER and
3749 return its value. */
3751 const char *
3752 parser::get_number ()
3754 const cpp_token *token = expect (CPP_NUMBER);
3755 return (const char *)token->val.str.text;
3759 /* Record an operator-list use for transparent for handling. */
3761 void
3762 parser::record_operlist (source_location loc, user_id *p)
3764 if (!oper_lists_set->add (p))
3766 if (!oper_lists.is_empty ()
3767 && oper_lists[0]->substitutes.length () != p->substitutes.length ())
3768 fatal_at (loc, "User-defined operator list does not have the "
3769 "same number of entries as others used in the pattern");
3770 oper_lists.safe_push (p);
3774 /* Parse the operator ID, special-casing convert?, convert1? and
3775 convert2? */
3777 id_base *
3778 parser::parse_operation ()
3780 const cpp_token *id_tok = peek ();
3781 const char *id = get_ident ();
3782 const cpp_token *token = peek ();
3783 if (strcmp (id, "convert0") == 0)
3784 fatal_at (id_tok, "use 'convert?' here");
3785 else if (strcmp (id, "view_convert0") == 0)
3786 fatal_at (id_tok, "use 'view_convert?' here");
3787 if (token->type == CPP_QUERY
3788 && !(token->flags & PREV_WHITE))
3790 if (strcmp (id, "convert") == 0)
3791 id = "convert0";
3792 else if (strcmp (id, "convert1") == 0)
3794 else if (strcmp (id, "convert2") == 0)
3796 else if (strcmp (id, "view_convert") == 0)
3797 id = "view_convert0";
3798 else if (strcmp (id, "view_convert1") == 0)
3800 else if (strcmp (id, "view_convert2") == 0)
3802 else
3803 fatal_at (id_tok, "non-convert operator conditionalized");
3805 if (!parsing_match_operand)
3806 fatal_at (id_tok, "conditional convert can only be used in "
3807 "match expression");
3808 eat_token (CPP_QUERY);
3810 else if (strcmp (id, "convert1") == 0
3811 || strcmp (id, "convert2") == 0
3812 || strcmp (id, "view_convert1") == 0
3813 || strcmp (id, "view_convert2") == 0)
3814 fatal_at (id_tok, "expected '?' after conditional operator");
3815 id_base *op = get_operator (id);
3816 if (!op)
3817 fatal_at (id_tok, "unknown operator %s", id);
3819 user_id *p = dyn_cast<user_id *> (op);
3820 if (p && p->is_oper_list)
3822 if (active_fors.length() == 0)
3823 record_operlist (id_tok->src_loc, p);
3824 else
3825 fatal_at (id_tok, "operator-list %s cannot be exapnded inside 'for'", id);
3827 return op;
3830 /* Parse a capture.
3831 capture = '@'<number> */
3833 struct operand *
3834 parser::parse_capture (operand *op, bool require_existing)
3836 source_location src_loc = eat_token (CPP_ATSIGN)->src_loc;
3837 const cpp_token *token = peek ();
3838 const char *id = NULL;
3839 if (token->type == CPP_NUMBER)
3840 id = get_number ();
3841 else if (token->type == CPP_NAME)
3842 id = get_ident ();
3843 else
3844 fatal_at (token, "expected number or identifier");
3845 unsigned next_id = capture_ids->elements ();
3846 bool existed;
3847 unsigned &num = capture_ids->get_or_insert (id, &existed);
3848 if (!existed)
3850 if (require_existing)
3851 fatal_at (src_loc, "unknown capture id");
3852 num = next_id;
3854 return new capture (src_loc, num, op);
3857 /* Parse an expression
3858 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
3860 struct operand *
3861 parser::parse_expr ()
3863 const cpp_token *token = peek ();
3864 expr *e = new expr (parse_operation (), token->src_loc);
3865 token = peek ();
3866 operand *op;
3867 bool is_commutative = false;
3868 bool force_capture = false;
3869 const char *expr_type = NULL;
3871 if (token->type == CPP_COLON
3872 && !(token->flags & PREV_WHITE))
3874 eat_token (CPP_COLON);
3875 token = peek ();
3876 if (token->type == CPP_NAME
3877 && !(token->flags & PREV_WHITE))
3879 const char *s = get_ident ();
3880 if (!parsing_match_operand)
3881 expr_type = s;
3882 else
3884 const char *sp = s;
3885 while (*sp)
3887 if (*sp == 'c')
3888 is_commutative = true;
3889 else if (*sp == 's')
3891 e->force_single_use = true;
3892 force_capture = true;
3894 else
3895 fatal_at (token, "flag %c not recognized", *sp);
3896 sp++;
3899 token = peek ();
3901 else
3902 fatal_at (token, "expected flag or type specifying identifier");
3905 if (token->type == CPP_ATSIGN
3906 && !(token->flags & PREV_WHITE))
3907 op = parse_capture (e, false);
3908 else if (force_capture)
3910 unsigned num = capture_ids->elements ();
3911 char id[8];
3912 bool existed;
3913 sprintf (id, "__%u", num);
3914 capture_ids->get_or_insert (xstrdup (id), &existed);
3915 if (existed)
3916 fatal_at (token, "reserved capture id '%s' already used", id);
3917 op = new capture (token->src_loc, num, e);
3919 else
3920 op = e;
3923 const cpp_token *token = peek ();
3924 if (token->type == CPP_CLOSE_PAREN)
3926 if (e->operation->nargs != -1
3927 && e->operation->nargs != (int) e->ops.length ())
3928 fatal_at (token, "'%s' expects %u operands, not %u",
3929 e->operation->id, e->operation->nargs, e->ops.length ());
3930 if (is_commutative)
3932 if (e->ops.length () == 2)
3933 e->is_commutative = true;
3934 else
3935 fatal_at (token, "only binary operators or function with "
3936 "two arguments can be marked commutative");
3938 e->expr_type = expr_type;
3939 return op;
3941 else if (!(token->flags & PREV_WHITE))
3942 fatal_at (token, "expected expression operand");
3944 e->append_op (parse_op ());
3946 while (1);
3949 /* Lex native C code delimited by START recording the preprocessing tokens
3950 for later processing.
3951 c_expr = ('{'|'(') <pp token>... ('}'|')') */
3953 c_expr *
3954 parser::parse_c_expr (cpp_ttype start)
3956 const cpp_token *token;
3957 cpp_ttype end;
3958 unsigned opencnt;
3959 vec<cpp_token> code = vNULL;
3960 unsigned nr_stmts = 0;
3961 source_location loc = eat_token (start)->src_loc;
3962 if (start == CPP_OPEN_PAREN)
3963 end = CPP_CLOSE_PAREN;
3964 else if (start == CPP_OPEN_BRACE)
3965 end = CPP_CLOSE_BRACE;
3966 else
3967 gcc_unreachable ();
3968 opencnt = 1;
3971 token = next ();
3973 /* Count brace pairs to find the end of the expr to match. */
3974 if (token->type == start)
3975 opencnt++;
3976 else if (token->type == end
3977 && --opencnt == 0)
3978 break;
3980 /* This is a lame way of counting the number of statements. */
3981 if (token->type == CPP_SEMICOLON)
3982 nr_stmts++;
3984 /* If this is possibly a user-defined identifier mark it used. */
3985 if (token->type == CPP_NAME)
3987 id_base *idb = get_operator ((const char *)CPP_HASHNODE
3988 (token->val.node.node)->ident.str);
3989 user_id *p;
3990 if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
3991 record_operlist (token->src_loc, p);
3994 /* Record the token. */
3995 code.safe_push (*token);
3997 while (1);
3998 return new c_expr (r, loc, code, nr_stmts, vNULL, capture_ids);
4001 /* Parse an operand which is either an expression, a predicate or
4002 a standalone capture.
4003 op = predicate | expr | c_expr | capture */
4005 struct operand *
4006 parser::parse_op ()
4008 const cpp_token *token = peek ();
4009 struct operand *op = NULL;
4010 if (token->type == CPP_OPEN_PAREN)
4012 eat_token (CPP_OPEN_PAREN);
4013 op = parse_expr ();
4014 eat_token (CPP_CLOSE_PAREN);
4016 else if (token->type == CPP_OPEN_BRACE)
4018 op = parse_c_expr (CPP_OPEN_BRACE);
4020 else
4022 /* Remaining ops are either empty or predicates */
4023 if (token->type == CPP_NAME)
4025 const char *id = get_ident ();
4026 id_base *opr = get_operator (id);
4027 if (!opr)
4028 fatal_at (token, "expected predicate name");
4029 if (operator_id *code = dyn_cast <operator_id *> (opr))
4031 if (code->nargs != 0)
4032 fatal_at (token, "using an operator with operands as predicate");
4033 /* Parse the zero-operand operator "predicates" as
4034 expression. */
4035 op = new expr (opr, token->src_loc);
4037 else if (user_id *code = dyn_cast <user_id *> (opr))
4039 if (code->nargs != 0)
4040 fatal_at (token, "using an operator with operands as predicate");
4041 /* Parse the zero-operand operator "predicates" as
4042 expression. */
4043 op = new expr (opr, token->src_loc);
4045 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
4046 op = new predicate (p, token->src_loc);
4047 else
4048 fatal_at (token, "using an unsupported operator as predicate");
4049 if (!parsing_match_operand)
4050 fatal_at (token, "predicates are only allowed in match expression");
4051 token = peek ();
4052 if (token->flags & PREV_WHITE)
4053 return op;
4055 else if (token->type != CPP_COLON
4056 && token->type != CPP_ATSIGN)
4057 fatal_at (token, "expected expression or predicate");
4058 /* optionally followed by a capture and a predicate. */
4059 if (token->type == CPP_COLON)
4060 fatal_at (token, "not implemented: predicate on leaf operand");
4061 if (token->type == CPP_ATSIGN)
4062 op = parse_capture (op, !parsing_match_operand);
4065 return op;
4068 /* Create a new simplify from the current parsing state and MATCH,
4069 MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS. */
4071 void
4072 parser::push_simplify (simplify::simplify_kind kind,
4073 vec<simplify *>& simplifiers,
4074 operand *match, operand *result)
4076 /* Build and push a temporary for operator list uses in expressions. */
4077 if (!oper_lists.is_empty ())
4078 active_fors.safe_push (oper_lists);
4080 simplifiers.safe_push
4081 (new simplify (kind, match, result,
4082 active_fors.copy (), capture_ids));
4084 if (!oper_lists.is_empty ())
4085 active_fors.pop ();
4088 /* Parse
4089 <result-op> = <op> | <if> | <with>
4090 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
4091 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
4092 and return it. */
4094 operand *
4095 parser::parse_result (operand *result, predicate_id *matcher)
4097 const cpp_token *token = peek ();
4098 if (token->type != CPP_OPEN_PAREN)
4099 return parse_op ();
4101 eat_token (CPP_OPEN_PAREN);
4102 if (peek_ident ("if"))
4104 eat_ident ("if");
4105 if_expr *ife = new if_expr (token->src_loc);
4106 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4107 if (peek ()->type == CPP_OPEN_PAREN)
4109 ife->trueexpr = parse_result (result, matcher);
4110 if (peek ()->type == CPP_OPEN_PAREN)
4111 ife->falseexpr = parse_result (result, matcher);
4112 else if (peek ()->type != CPP_CLOSE_PAREN)
4113 ife->falseexpr = parse_op ();
4115 else if (peek ()->type != CPP_CLOSE_PAREN)
4117 ife->trueexpr = parse_op ();
4118 if (peek ()->type == CPP_OPEN_PAREN)
4119 ife->falseexpr = parse_result (result, matcher);
4120 else if (peek ()->type != CPP_CLOSE_PAREN)
4121 ife->falseexpr = parse_op ();
4123 /* If this if is immediately closed then it contains a
4124 manual matcher or is part of a predicate definition. */
4125 else /* if (peek ()->type == CPP_CLOSE_PAREN) */
4127 if (!matcher)
4128 fatal_at (peek (), "manual transform not implemented");
4129 ife->trueexpr = result;
4131 eat_token (CPP_CLOSE_PAREN);
4132 return ife;
4134 else if (peek_ident ("with"))
4136 eat_ident ("with");
4137 with_expr *withe = new with_expr (token->src_loc);
4138 /* Parse (with c-expr expr) as (if-with (true) expr). */
4139 withe->with = parse_c_expr (CPP_OPEN_BRACE);
4140 withe->with->nr_stmts = 0;
4141 withe->subexpr = parse_result (result, matcher);
4142 eat_token (CPP_CLOSE_PAREN);
4143 return withe;
4145 else if (peek_ident ("switch"))
4147 token = eat_ident ("switch");
4148 source_location ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4149 eat_ident ("if");
4150 if_expr *ife = new if_expr (ifloc);
4151 operand *res = ife;
4152 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4153 if (peek ()->type == CPP_OPEN_PAREN)
4154 ife->trueexpr = parse_result (result, matcher);
4155 else
4156 ife->trueexpr = parse_op ();
4157 eat_token (CPP_CLOSE_PAREN);
4158 if (peek ()->type != CPP_OPEN_PAREN
4159 || !peek_ident ("if", 2))
4160 fatal_at (token, "switch can be implemented with a single if");
4161 while (peek ()->type != CPP_CLOSE_PAREN)
4163 if (peek ()->type == CPP_OPEN_PAREN)
4165 if (peek_ident ("if", 2))
4167 ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4168 eat_ident ("if");
4169 ife->falseexpr = new if_expr (ifloc);
4170 ife = as_a <if_expr *> (ife->falseexpr);
4171 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4172 if (peek ()->type == CPP_OPEN_PAREN)
4173 ife->trueexpr = parse_result (result, matcher);
4174 else
4175 ife->trueexpr = parse_op ();
4176 eat_token (CPP_CLOSE_PAREN);
4178 else
4180 /* switch default clause */
4181 ife->falseexpr = parse_result (result, matcher);
4182 eat_token (CPP_CLOSE_PAREN);
4183 return res;
4186 else
4188 /* switch default clause */
4189 ife->falseexpr = parse_op ();
4190 eat_token (CPP_CLOSE_PAREN);
4191 return res;
4194 eat_token (CPP_CLOSE_PAREN);
4195 return res;
4197 else
4199 operand *op = result;
4200 if (!matcher)
4201 op = parse_expr ();
4202 eat_token (CPP_CLOSE_PAREN);
4203 return op;
4207 /* Parse
4208 simplify = 'simplify' <expr> <result-op>
4210 match = 'match' <ident> <expr> [<result-op>]
4211 and fill SIMPLIFIERS with the results. */
4213 void
4214 parser::parse_simplify (simplify::simplify_kind kind,
4215 vec<simplify *>& simplifiers, predicate_id *matcher,
4216 operand *result)
4218 /* Reset the capture map. */
4219 if (!capture_ids)
4220 capture_ids = new cid_map_t;
4221 /* Reset oper_lists and set. */
4222 hash_set <user_id *> olist;
4223 oper_lists_set = &olist;
4224 oper_lists = vNULL;
4226 const cpp_token *loc = peek ();
4227 parsing_match_operand = true;
4228 struct operand *match = parse_op ();
4229 parsing_match_operand = false;
4230 if (match->type == operand::OP_CAPTURE && !matcher)
4231 fatal_at (loc, "outermost expression cannot be captured");
4232 if (match->type == operand::OP_EXPR
4233 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
4234 fatal_at (loc, "outermost expression cannot be a predicate");
4236 /* Splice active_ifs onto result and continue parsing the
4237 "then" expr. */
4238 if_expr *active_if = NULL;
4239 for (int i = active_ifs.length (); i > 0; --i)
4241 if_expr *ifc = new if_expr (active_ifs[i-1]->location);
4242 ifc->cond = active_ifs[i-1];
4243 ifc->trueexpr = active_if;
4244 active_if = ifc;
4246 if_expr *outermost_if = active_if;
4247 while (active_if && active_if->trueexpr)
4248 active_if = as_a <if_expr *> (active_if->trueexpr);
4250 const cpp_token *token = peek ();
4252 /* If this if is immediately closed then it is part of a predicate
4253 definition. Push it. */
4254 if (token->type == CPP_CLOSE_PAREN)
4256 if (!matcher)
4257 fatal_at (token, "expected transform expression");
4258 if (active_if)
4260 active_if->trueexpr = result;
4261 result = outermost_if;
4263 push_simplify (kind, simplifiers, match, result);
4264 return;
4267 operand *tem = parse_result (result, matcher);
4268 if (active_if)
4270 active_if->trueexpr = tem;
4271 result = outermost_if;
4273 else
4274 result = tem;
4276 push_simplify (kind, simplifiers, match, result);
4279 /* Parsing of the outer control structures. */
4281 /* Parse a for expression
4282 for = '(' 'for' <subst>... <pattern> ')'
4283 subst = <ident> '(' <ident>... ')' */
4285 void
4286 parser::parse_for (source_location)
4288 auto_vec<const cpp_token *> user_id_tokens;
4289 vec<user_id *> user_ids = vNULL;
4290 const cpp_token *token;
4291 unsigned min_n_opers = 0, max_n_opers = 0;
4293 while (1)
4295 token = peek ();
4296 if (token->type != CPP_NAME)
4297 break;
4299 /* Insert the user defined operators into the operator hash. */
4300 const char *id = get_ident ();
4301 if (get_operator (id, true) != NULL)
4302 fatal_at (token, "operator already defined");
4303 user_id *op = new user_id (id);
4304 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4305 *slot = op;
4306 user_ids.safe_push (op);
4307 user_id_tokens.safe_push (token);
4309 eat_token (CPP_OPEN_PAREN);
4311 int arity = -1;
4312 while ((token = peek_ident ()) != 0)
4314 const char *oper = get_ident ();
4315 id_base *idb = get_operator (oper, true);
4316 if (idb == NULL)
4317 fatal_at (token, "no such operator '%s'", oper);
4318 if (*idb == CONVERT0 || *idb == CONVERT1 || *idb == CONVERT2
4319 || *idb == VIEW_CONVERT0 || *idb == VIEW_CONVERT1
4320 || *idb == VIEW_CONVERT2)
4321 fatal_at (token, "conditional operators cannot be used inside for");
4323 if (arity == -1)
4324 arity = idb->nargs;
4325 else if (idb->nargs == -1)
4327 else if (idb->nargs != arity)
4328 fatal_at (token, "operator '%s' with arity %d does not match "
4329 "others with arity %d", oper, idb->nargs, arity);
4331 user_id *p = dyn_cast<user_id *> (idb);
4332 if (p)
4334 if (p->is_oper_list)
4335 op->substitutes.safe_splice (p->substitutes);
4336 else
4337 fatal_at (token, "iterator cannot be used as operator-list");
4339 else
4340 op->substitutes.safe_push (idb);
4342 op->nargs = arity;
4343 token = expect (CPP_CLOSE_PAREN);
4345 unsigned nsubstitutes = op->substitutes.length ();
4346 if (nsubstitutes == 0)
4347 fatal_at (token, "A user-defined operator must have at least "
4348 "one substitution");
4349 if (max_n_opers == 0)
4351 min_n_opers = nsubstitutes;
4352 max_n_opers = nsubstitutes;
4354 else
4356 if (nsubstitutes % min_n_opers != 0
4357 && min_n_opers % nsubstitutes != 0)
4358 fatal_at (token, "All user-defined identifiers must have a "
4359 "multiple number of operator substitutions of the "
4360 "smallest number of substitutions");
4361 if (nsubstitutes < min_n_opers)
4362 min_n_opers = nsubstitutes;
4363 else if (nsubstitutes > max_n_opers)
4364 max_n_opers = nsubstitutes;
4368 unsigned n_ids = user_ids.length ();
4369 if (n_ids == 0)
4370 fatal_at (token, "for requires at least one user-defined identifier");
4372 token = peek ();
4373 if (token->type == CPP_CLOSE_PAREN)
4374 fatal_at (token, "no pattern defined in for");
4376 active_fors.safe_push (user_ids);
4377 while (1)
4379 token = peek ();
4380 if (token->type == CPP_CLOSE_PAREN)
4381 break;
4382 parse_pattern ();
4384 active_fors.pop ();
4386 /* Remove user-defined operators from the hash again. */
4387 for (unsigned i = 0; i < user_ids.length (); ++i)
4389 if (!user_ids[i]->used)
4390 warning_at (user_id_tokens[i],
4391 "operator %s defined but not used", user_ids[i]->id);
4392 operators->remove_elt (user_ids[i]);
4396 /* Parse an identifier associated with a list of operators.
4397 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
4399 void
4400 parser::parse_operator_list (source_location)
4402 const cpp_token *token = peek ();
4403 const char *id = get_ident ();
4405 if (get_operator (id, true) != 0)
4406 fatal_at (token, "operator %s already defined", id);
4408 user_id *op = new user_id (id, true);
4409 int arity = -1;
4411 while ((token = peek_ident ()) != 0)
4413 token = peek ();
4414 const char *oper = get_ident ();
4415 id_base *idb = get_operator (oper, true);
4417 if (idb == 0)
4418 fatal_at (token, "no such operator '%s'", oper);
4420 if (arity == -1)
4421 arity = idb->nargs;
4422 else if (idb->nargs == -1)
4424 else if (arity != idb->nargs)
4425 fatal_at (token, "operator '%s' with arity %d does not match "
4426 "others with arity %d", oper, idb->nargs, arity);
4428 /* We allow composition of multiple operator lists. */
4429 if (user_id *p = dyn_cast<user_id *> (idb))
4430 op->substitutes.safe_splice (p->substitutes);
4431 else
4432 op->substitutes.safe_push (idb);
4435 // Check that there is no junk after id-list
4436 token = peek();
4437 if (token->type != CPP_CLOSE_PAREN)
4438 fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
4440 if (op->substitutes.length () == 0)
4441 fatal_at (token, "operator-list cannot be empty");
4443 op->nargs = arity;
4444 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4445 *slot = op;
4448 /* Parse an outer if expression.
4449 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
4451 void
4452 parser::parse_if (source_location)
4454 c_expr *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
4456 const cpp_token *token = peek ();
4457 if (token->type == CPP_CLOSE_PAREN)
4458 fatal_at (token, "no pattern defined in if");
4460 active_ifs.safe_push (ifexpr);
4461 while (1)
4463 const cpp_token *token = peek ();
4464 if (token->type == CPP_CLOSE_PAREN)
4465 break;
4467 parse_pattern ();
4469 active_ifs.pop ();
4472 /* Parse a list of predefined predicate identifiers.
4473 preds = '(' 'define_predicates' <ident>... ')' */
4475 void
4476 parser::parse_predicates (source_location)
4480 const cpp_token *token = peek ();
4481 if (token->type != CPP_NAME)
4482 break;
4484 add_predicate (get_ident ());
4486 while (1);
4489 /* Parse outer control structures.
4490 pattern = <preds>|<for>|<if>|<simplify>|<match> */
4492 void
4493 parser::parse_pattern ()
4495 /* All clauses start with '('. */
4496 eat_token (CPP_OPEN_PAREN);
4497 const cpp_token *token = peek ();
4498 const char *id = get_ident ();
4499 if (strcmp (id, "simplify") == 0)
4501 parse_simplify (simplify::SIMPLIFY, simplifiers, NULL, NULL);
4502 capture_ids = NULL;
4504 else if (strcmp (id, "match") == 0)
4506 bool with_args = false;
4507 source_location e_loc = peek ()->src_loc;
4508 if (peek ()->type == CPP_OPEN_PAREN)
4510 eat_token (CPP_OPEN_PAREN);
4511 with_args = true;
4513 const char *name = get_ident ();
4514 id_base *id = get_operator (name);
4515 predicate_id *p;
4516 if (!id)
4518 p = add_predicate (name);
4519 user_predicates.safe_push (p);
4521 else if ((p = dyn_cast <predicate_id *> (id)))
4523 else
4524 fatal_at (token, "cannot add a match to a non-predicate ID");
4525 /* Parse (match <id> <arg>... (match-expr)) here. */
4526 expr *e = NULL;
4527 if (with_args)
4529 capture_ids = new cid_map_t;
4530 e = new expr (p, e_loc);
4531 while (peek ()->type == CPP_ATSIGN)
4532 e->append_op (parse_capture (NULL, false));
4533 eat_token (CPP_CLOSE_PAREN);
4535 if (p->nargs != -1
4536 && ((e && e->ops.length () != (unsigned)p->nargs)
4537 || (!e && p->nargs != 0)))
4538 fatal_at (token, "non-matching number of match operands");
4539 p->nargs = e ? e->ops.length () : 0;
4540 parse_simplify (simplify::MATCH, p->matchers, p, e);
4541 capture_ids = NULL;
4543 else if (strcmp (id, "for") == 0)
4544 parse_for (token->src_loc);
4545 else if (strcmp (id, "if") == 0)
4546 parse_if (token->src_loc);
4547 else if (strcmp (id, "define_predicates") == 0)
4549 if (active_ifs.length () > 0
4550 || active_fors.length () > 0)
4551 fatal_at (token, "define_predicates inside if or for is not supported");
4552 parse_predicates (token->src_loc);
4554 else if (strcmp (id, "define_operator_list") == 0)
4556 if (active_ifs.length () > 0
4557 || active_fors.length () > 0)
4558 fatal_at (token, "operator-list inside if or for is not supported");
4559 parse_operator_list (token->src_loc);
4561 else
4562 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
4563 active_ifs.length () == 0 && active_fors.length () == 0
4564 ? "'define_predicates', " : "");
4566 eat_token (CPP_CLOSE_PAREN);
4569 /* Main entry of the parser. Repeatedly parse outer control structures. */
4571 parser::parser (cpp_reader *r_)
4573 r = r_;
4574 active_ifs = vNULL;
4575 active_fors = vNULL;
4576 simplifiers = vNULL;
4577 oper_lists_set = NULL;
4578 oper_lists = vNULL;
4579 capture_ids = NULL;
4580 user_predicates = vNULL;
4581 parsing_match_operand = false;
4583 const cpp_token *token = next ();
4584 while (token->type != CPP_EOF)
4586 _cpp_backup_tokens (r, 1);
4587 parse_pattern ();
4588 token = next ();
4593 /* Helper for the linemap code. */
4595 static size_t
4596 round_alloc_size (size_t s)
4598 return s;
4602 /* The genmatch generator progam. It reads from a pattern description
4603 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
4606 main (int argc, char **argv)
4608 cpp_reader *r;
4610 progname = "genmatch";
4612 if (argc < 2)
4613 return 1;
4615 bool gimple = true;
4616 char *input = argv[argc-1];
4617 for (int i = 1; i < argc - 1; ++i)
4619 if (strcmp (argv[i], "--gimple") == 0)
4620 gimple = true;
4621 else if (strcmp (argv[i], "--generic") == 0)
4622 gimple = false;
4623 else if (strcmp (argv[i], "-v") == 0)
4624 verbose = 1;
4625 else if (strcmp (argv[i], "-vv") == 0)
4626 verbose = 2;
4627 else
4629 fprintf (stderr, "Usage: genmatch "
4630 "[--gimple] [--generic] [-v[v]] input\n");
4631 return 1;
4635 line_table = XCNEW (struct line_maps);
4636 linemap_init (line_table, 0);
4637 line_table->reallocator = xrealloc;
4638 line_table->round_alloc_size = round_alloc_size;
4640 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
4641 cpp_callbacks *cb = cpp_get_callbacks (r);
4642 cb->error = error_cb;
4644 /* Add the build directory to the #include "" search path. */
4645 cpp_dir *dir = XCNEW (cpp_dir);
4646 dir->name = getpwd ();
4647 if (!dir->name)
4648 dir->name = ASTRDUP (".");
4649 cpp_set_include_chains (r, dir, NULL, false);
4651 if (!cpp_read_main_file (r, input))
4652 return 1;
4653 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
4654 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
4656 null_id = new id_base (id_base::NULL_ID, "null");
4658 /* Pre-seed operators. */
4659 operators = new hash_table<id_base> (1024);
4660 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
4661 add_operator (SYM, # SYM, # TYPE, NARGS);
4662 #define END_OF_BASE_TREE_CODES
4663 #include "tree.def"
4664 add_operator (CONVERT0, "convert0", "tcc_unary", 1);
4665 add_operator (CONVERT1, "convert1", "tcc_unary", 1);
4666 add_operator (CONVERT2, "convert2", "tcc_unary", 1);
4667 add_operator (VIEW_CONVERT0, "view_convert0", "tcc_unary", 1);
4668 add_operator (VIEW_CONVERT1, "view_convert1", "tcc_unary", 1);
4669 add_operator (VIEW_CONVERT2, "view_convert2", "tcc_unary", 1);
4670 #undef END_OF_BASE_TREE_CODES
4671 #undef DEFTREECODE
4673 /* Pre-seed builtin functions.
4674 ??? Cannot use N (name) as that is targetm.emultls.get_address
4675 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
4676 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
4677 add_function (ENUM, "CFN_" # ENUM);
4678 #include "builtins.def"
4680 #define DEF_INTERNAL_FN(CODE, NAME, FNSPEC) \
4681 add_function (IFN_##CODE, "CFN_" #CODE);
4682 #include "internal-fn.def"
4684 /* Parse ahead! */
4685 parser p (r);
4687 if (gimple)
4688 write_header (stdout, "gimple-match-head.c");
4689 else
4690 write_header (stdout, "generic-match-head.c");
4692 /* Go over all predicates defined with patterns and perform
4693 lowering and code generation. */
4694 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
4696 predicate_id *pred = p.user_predicates[i];
4697 lower (pred->matchers, gimple);
4699 if (verbose == 2)
4700 for (unsigned i = 0; i < pred->matchers.length (); ++i)
4701 print_matches (pred->matchers[i]);
4703 decision_tree dt;
4704 for (unsigned i = 0; i < pred->matchers.length (); ++i)
4705 dt.insert (pred->matchers[i], i);
4707 if (verbose == 2)
4708 dt.print (stderr);
4710 write_predicate (stdout, pred, dt, gimple);
4713 /* Lower the main simplifiers and generate code for them. */
4714 lower (p.simplifiers, gimple);
4716 if (verbose == 2)
4717 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
4718 print_matches (p.simplifiers[i]);
4720 decision_tree dt;
4721 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
4722 dt.insert (p.simplifiers[i], i);
4724 if (verbose == 2)
4725 dt.print (stderr);
4727 dt.gen (stdout, gimple);
4729 /* Finalize. */
4730 cpp_finish (r, NULL);
4731 cpp_destroy (r);
4733 delete operators;
4735 return 0;