compiler: Create dummy labels for blank labels.
[official-gcc.git] / gcc / genmatch.c
blob1434719a88ed023047e5180d4ce3e60459938081
1 /* Generate pattern matching and transform code shared between
2 GENERIC and GIMPLE folding code from match-and-simplify description.
4 Copyright (C) 2014-2015 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 <new>
26 #include "system.h"
27 #include "coretypes.h"
28 #include <cpplib.h>
29 #include "errors.h"
30 #include "hash-table.h"
31 #include "hash-set.h"
32 #include "is-a.h"
35 /* Stubs for GGC referenced through instantiations triggered by hash-map. */
36 void *ggc_internal_cleared_alloc (size_t, void (*)(void *),
37 size_t, size_t MEM_STAT_DECL)
39 return NULL;
41 void ggc_free (void *)
46 /* libccp helpers. */
48 static struct line_maps *line_table;
50 static bool
51 #if GCC_VERSION >= 4001
52 __attribute__((format (printf, 6, 0)))
53 #endif
54 error_cb (cpp_reader *, int errtype, int, source_location location,
55 unsigned int, const char *msg, va_list *ap)
57 const line_map_ordinary *map;
58 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
59 expanded_location loc = linemap_expand_location (line_table, map, location);
60 fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
61 (errtype == CPP_DL_WARNING) ? "warning" : "error");
62 vfprintf (stderr, msg, *ap);
63 fprintf (stderr, "\n");
64 FILE *f = fopen (loc.file, "r");
65 if (f)
67 char buf[128];
68 while (loc.line > 0)
70 if (!fgets (buf, 128, f))
71 goto notfound;
72 if (buf[strlen (buf) - 1] != '\n')
74 if (loc.line > 1)
75 loc.line++;
77 loc.line--;
79 fprintf (stderr, "%s", buf);
80 for (int i = 0; i < loc.column - 1; ++i)
81 fputc (' ', stderr);
82 fputc ('^', stderr);
83 fputc ('\n', stderr);
84 notfound:
85 fclose (f);
88 if (errtype == CPP_DL_FATAL)
89 exit (1);
90 return false;
93 static void
94 #if GCC_VERSION >= 4001
95 __attribute__((format (printf, 2, 3)))
96 #endif
97 fatal_at (const cpp_token *tk, const char *msg, ...)
99 va_list ap;
100 va_start (ap, msg);
101 error_cb (NULL, CPP_DL_FATAL, 0, tk->src_loc, 0, msg, &ap);
102 va_end (ap);
105 static void
106 #if GCC_VERSION >= 4001
107 __attribute__((format (printf, 2, 3)))
108 #endif
109 fatal_at (source_location loc, const char *msg, ...)
111 va_list ap;
112 va_start (ap, msg);
113 error_cb (NULL, CPP_DL_FATAL, 0, loc, 0, msg, &ap);
114 va_end (ap);
117 static void
118 #if GCC_VERSION >= 4001
119 __attribute__((format (printf, 2, 3)))
120 #endif
121 warning_at (const cpp_token *tk, const char *msg, ...)
123 va_list ap;
124 va_start (ap, msg);
125 error_cb (NULL, CPP_DL_WARNING, 0, tk->src_loc, 0, msg, &ap);
126 va_end (ap);
129 /* Like fprintf, but print INDENT spaces at the beginning. */
131 static void
132 #if GCC_VERSION >= 4001
133 __attribute__((format (printf, 3, 4)))
134 #endif
135 fprintf_indent (FILE *f, unsigned int indent, const char *format, ...)
137 va_list ap;
138 for (; indent >= 8; indent -= 8)
139 fputc ('\t', f);
140 fprintf (f, "%*s", indent, "");
141 va_start (ap, format);
142 vfprintf (f, format, ap);
143 va_end (ap);
146 static void
147 output_line_directive (FILE *f, source_location location,
148 bool dumpfile = false)
150 const line_map_ordinary *map;
151 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
152 expanded_location loc = linemap_expand_location (line_table, map, location);
153 if (dumpfile)
155 /* When writing to a dumpfile only dump the filename. */
156 const char *file = strrchr (loc.file, DIR_SEPARATOR);
157 if (!file)
158 file = loc.file;
159 else
160 ++file;
161 fprintf (f, "%s:%d", file, loc.line);
163 else
164 /* Other gen programs really output line directives here, at least for
165 development it's right now more convenient to have line information
166 from the generated file. Still keep the directives as comment for now
167 to easily back-point to the meta-description. */
168 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
172 /* Pull in tree codes and builtin function codes from their
173 definition files. */
175 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
176 enum tree_code {
177 #include "tree.def"
178 CONVERT0,
179 CONVERT1,
180 CONVERT2,
181 VIEW_CONVERT0,
182 VIEW_CONVERT1,
183 VIEW_CONVERT2,
184 MAX_TREE_CODES
186 #undef DEFTREECODE
188 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
189 enum built_in_function {
190 #include "builtins.def"
191 END_BUILTINS
193 #undef DEF_BUILTIN
195 /* Return true if CODE represents a commutative tree code. Otherwise
196 return false. */
197 bool
198 commutative_tree_code (enum tree_code code)
200 switch (code)
202 case PLUS_EXPR:
203 case MULT_EXPR:
204 case MULT_HIGHPART_EXPR:
205 case MIN_EXPR:
206 case MAX_EXPR:
207 case BIT_IOR_EXPR:
208 case BIT_XOR_EXPR:
209 case BIT_AND_EXPR:
210 case NE_EXPR:
211 case EQ_EXPR:
212 case UNORDERED_EXPR:
213 case ORDERED_EXPR:
214 case UNEQ_EXPR:
215 case LTGT_EXPR:
216 case TRUTH_AND_EXPR:
217 case TRUTH_XOR_EXPR:
218 case TRUTH_OR_EXPR:
219 case WIDEN_MULT_EXPR:
220 case VEC_WIDEN_MULT_HI_EXPR:
221 case VEC_WIDEN_MULT_LO_EXPR:
222 case VEC_WIDEN_MULT_EVEN_EXPR:
223 case VEC_WIDEN_MULT_ODD_EXPR:
224 return true;
226 default:
227 break;
229 return false;
232 /* Return true if CODE represents a ternary tree code for which the
233 first two operands are commutative. Otherwise return false. */
234 bool
235 commutative_ternary_tree_code (enum tree_code code)
237 switch (code)
239 case WIDEN_MULT_PLUS_EXPR:
240 case WIDEN_MULT_MINUS_EXPR:
241 case DOT_PROD_EXPR:
242 case FMA_EXPR:
243 return true;
245 default:
246 break;
248 return false;
252 /* Base class for all identifiers the parser knows. */
254 struct id_base : nofree_ptr_hash<id_base>
256 enum id_kind { CODE, FN, PREDICATE, USER } kind;
258 id_base (id_kind, const char *, int = -1);
260 hashval_t hashval;
261 int nargs;
262 const char *id;
264 /* hash_table support. */
265 static inline hashval_t hash (const id_base *);
266 static inline int equal (const id_base *, const id_base *);
269 inline hashval_t
270 id_base::hash (const id_base *op)
272 return op->hashval;
275 inline int
276 id_base::equal (const id_base *op1,
277 const id_base *op2)
279 return (op1->hashval == op2->hashval
280 && strcmp (op1->id, op2->id) == 0);
283 /* Hashtable of known pattern operators. This is pre-seeded from
284 all known tree codes and all known builtin function ids. */
285 static hash_table<id_base> *operators;
287 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
289 kind = kind_;
290 id = id_;
291 nargs = nargs_;
292 hashval = htab_hash_string (id);
295 /* Identifier that maps to a tree code. */
297 struct operator_id : public id_base
299 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
300 const char *tcc_)
301 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
302 enum tree_code code;
303 const char *tcc;
306 /* Identifier that maps to a builtin function code. */
308 struct fn_id : public id_base
310 fn_id (enum built_in_function fn_, const char *id_)
311 : id_base (id_base::FN, id_), fn (fn_) {}
312 enum built_in_function fn;
315 struct simplify;
317 /* Identifier that maps to a user-defined predicate. */
319 struct predicate_id : public id_base
321 predicate_id (const char *id_)
322 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
323 vec<simplify *> matchers;
326 /* Identifier that maps to a operator defined by a 'for' directive. */
328 struct user_id : public id_base
330 user_id (const char *id_, bool is_oper_list_ = false)
331 : id_base (id_base::USER, id_), substitutes (vNULL),
332 used (false), is_oper_list (is_oper_list_) {}
333 vec<id_base *> substitutes;
334 bool used;
335 bool is_oper_list;
338 template<>
339 template<>
340 inline bool
341 is_a_helper <fn_id *>::test (id_base *id)
343 return id->kind == id_base::FN;
346 template<>
347 template<>
348 inline bool
349 is_a_helper <operator_id *>::test (id_base *id)
351 return id->kind == id_base::CODE;
354 template<>
355 template<>
356 inline bool
357 is_a_helper <predicate_id *>::test (id_base *id)
359 return id->kind == id_base::PREDICATE;
362 template<>
363 template<>
364 inline bool
365 is_a_helper <user_id *>::test (id_base *id)
367 return id->kind == id_base::USER;
370 /* Add a predicate identifier to the hash. */
372 static predicate_id *
373 add_predicate (const char *id)
375 predicate_id *p = new predicate_id (id);
376 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
377 if (*slot)
378 fatal ("duplicate id definition");
379 *slot = p;
380 return p;
383 /* Add a tree code identifier to the hash. */
385 static void
386 add_operator (enum tree_code code, const char *id,
387 const char *tcc, unsigned nargs)
389 if (strcmp (tcc, "tcc_unary") != 0
390 && strcmp (tcc, "tcc_binary") != 0
391 && strcmp (tcc, "tcc_comparison") != 0
392 && strcmp (tcc, "tcc_expression") != 0
393 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
394 && strcmp (tcc, "tcc_reference") != 0
395 /* To have INTEGER_CST and friends as "predicate operators". */
396 && strcmp (tcc, "tcc_constant") != 0
397 /* And allow CONSTRUCTOR for vector initializers. */
398 && !(code == CONSTRUCTOR))
399 return;
400 /* Treat ADDR_EXPR as atom, thus don't allow matching its operand. */
401 if (code == ADDR_EXPR)
402 nargs = 0;
403 operator_id *op = new operator_id (code, id, nargs, tcc);
404 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
405 if (*slot)
406 fatal ("duplicate id definition");
407 *slot = op;
410 /* Add a builtin identifier to the hash. */
412 static void
413 add_builtin (enum built_in_function code, const char *id)
415 fn_id *fn = new fn_id (code, id);
416 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
417 if (*slot)
418 fatal ("duplicate id definition");
419 *slot = fn;
422 /* Helper for easy comparing ID with tree code CODE. */
424 static bool
425 operator==(id_base &id, enum tree_code code)
427 if (operator_id *oid = dyn_cast <operator_id *> (&id))
428 return oid->code == code;
429 return false;
432 /* Lookup the identifier ID. */
434 id_base *
435 get_operator (const char *id)
437 id_base tem (id_base::CODE, id);
439 id_base *op = operators->find_with_hash (&tem, tem.hashval);
440 if (op)
442 /* If this is a user-defined identifier track whether it was used. */
443 if (user_id *uid = dyn_cast<user_id *> (op))
444 uid->used = true;
445 return op;
448 /* Try all-uppercase. */
449 char *id2 = xstrdup (id);
450 for (unsigned i = 0; i < strlen (id2); ++i)
451 id2[i] = TOUPPER (id2[i]);
452 new (&tem) id_base (id_base::CODE, id2);
453 op = operators->find_with_hash (&tem, tem.hashval);
454 if (op)
456 free (id2);
457 return op;
460 /* Try _EXPR appended. */
461 id2 = (char *)xrealloc (id2, strlen (id2) + sizeof ("_EXPR") + 1);
462 strcat (id2, "_EXPR");
463 new (&tem) id_base (id_base::CODE, id2);
464 op = operators->find_with_hash (&tem, tem.hashval);
465 if (op)
467 free (id2);
468 return op;
471 return 0;
474 typedef hash_map<nofree_string_hash, unsigned> cid_map_t;
477 /* The AST produced by parsing of the pattern definitions. */
479 struct dt_operand;
480 struct capture_info;
482 /* The base class for operands. */
484 struct operand {
485 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR, OP_IF, OP_WITH };
486 operand (enum op_type type_) : type (type_) {}
487 enum op_type type;
488 virtual void gen_transform (FILE *, int, const char *, bool, int,
489 const char *, capture_info *,
490 dt_operand ** = 0,
491 bool = true)
492 { gcc_unreachable (); }
495 /* A predicate operand. Predicates are leafs in the AST. */
497 struct predicate : public operand
499 predicate (predicate_id *p_) : operand (OP_PREDICATE), p (p_) {}
500 predicate_id *p;
503 /* An operand that constitutes an expression. Expressions include
504 function calls and user-defined predicate invocations. */
506 struct expr : public operand
508 expr (id_base *operation_, bool is_commutative_ = false)
509 : operand (OP_EXPR), operation (operation_),
510 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
511 is_generic (false), force_single_use (false) {}
512 expr (expr *e)
513 : operand (OP_EXPR), operation (e->operation),
514 ops (vNULL), expr_type (e->expr_type), is_commutative (e->is_commutative),
515 is_generic (e->is_generic), force_single_use (e->force_single_use) {}
516 void append_op (operand *op) { ops.safe_push (op); }
517 /* The operator and its operands. */
518 id_base *operation;
519 vec<operand *> ops;
520 /* An explicitely specified type - used exclusively for conversions. */
521 const char *expr_type;
522 /* Whether the operation is to be applied commutatively. This is
523 later lowered to two separate patterns. */
524 bool is_commutative;
525 /* Whether the expression is expected to be in GENERIC form. */
526 bool is_generic;
527 /* Whether pushing any stmt to the sequence should be conditional
528 on this expression having a single-use. */
529 bool force_single_use;
530 virtual void gen_transform (FILE *f, int, const char *, bool, int,
531 const char *, capture_info *,
532 dt_operand ** = 0, bool = true);
535 /* An operator that is represented by native C code. This is always
536 a leaf operand in the AST. This class is also used to represent
537 the code to be generated for 'if' and 'with' expressions. */
539 struct c_expr : public operand
541 /* A mapping of an identifier and its replacement. Used to apply
542 'for' lowering. */
543 struct id_tab {
544 const char *id;
545 const char *oper;
546 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
549 c_expr (cpp_reader *r_, vec<cpp_token> code_, unsigned nr_stmts_,
550 vec<id_tab> ids_, cid_map_t *capture_ids_)
551 : operand (OP_C_EXPR), r (r_), code (code_), capture_ids (capture_ids_),
552 nr_stmts (nr_stmts_), ids (ids_) {}
553 /* cpplib tokens and state to transform this back to source. */
554 cpp_reader *r;
555 vec<cpp_token> code;
556 cid_map_t *capture_ids;
557 /* The number of statements parsed (well, the number of ';'s). */
558 unsigned nr_stmts;
559 /* The identifier replacement vector. */
560 vec<id_tab> ids;
561 virtual void gen_transform (FILE *f, int, const char *, bool, int,
562 const char *, capture_info *,
563 dt_operand ** = 0, bool = true);
566 /* A wrapper around another operand that captures its value. */
568 struct capture : public operand
570 capture (unsigned where_, operand *what_)
571 : operand (OP_CAPTURE), where (where_), what (what_) {}
572 /* Identifier index for the value. */
573 unsigned where;
574 /* The captured value. */
575 operand *what;
576 virtual void gen_transform (FILE *f, int, const char *, bool, int,
577 const char *, capture_info *,
578 dt_operand ** = 0, bool = true);
581 /* if expression. */
583 struct if_expr : public operand
585 if_expr () : operand (OP_IF), cond (NULL), trueexpr (NULL),
586 falseexpr (NULL) {}
587 c_expr *cond;
588 operand *trueexpr;
589 operand *falseexpr;
592 /* with expression. */
594 struct with_expr : public operand
596 with_expr () : operand (OP_WITH), with (NULL), subexpr (NULL) {}
597 c_expr *with;
598 operand *subexpr;
601 template<>
602 template<>
603 inline bool
604 is_a_helper <capture *>::test (operand *op)
606 return op->type == operand::OP_CAPTURE;
609 template<>
610 template<>
611 inline bool
612 is_a_helper <predicate *>::test (operand *op)
614 return op->type == operand::OP_PREDICATE;
617 template<>
618 template<>
619 inline bool
620 is_a_helper <c_expr *>::test (operand *op)
622 return op->type == operand::OP_C_EXPR;
625 template<>
626 template<>
627 inline bool
628 is_a_helper <expr *>::test (operand *op)
630 return op->type == operand::OP_EXPR;
633 template<>
634 template<>
635 inline bool
636 is_a_helper <if_expr *>::test (operand *op)
638 return op->type == operand::OP_IF;
641 template<>
642 template<>
643 inline bool
644 is_a_helper <with_expr *>::test (operand *op)
646 return op->type == operand::OP_WITH;
649 /* The main class of a pattern and its transform. This is used to
650 represent both (simplify ...) and (match ...) kinds. The AST
651 duplicates all outer 'if' and 'for' expressions here so each
652 simplify can exist in isolation. */
654 struct simplify
656 enum simplify_kind { SIMPLIFY, MATCH };
658 simplify (simplify_kind kind_,
659 operand *match_, source_location match_location_,
660 struct operand *result_, source_location result_location_,
661 vec<vec<user_id *> > for_vec_, cid_map_t *capture_ids_)
662 : kind (kind_), match (match_), match_location (match_location_),
663 result (result_), result_location (result_location_),
664 for_vec (for_vec_),
665 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
667 simplify_kind kind;
668 /* The expression that is matched against the GENERIC or GIMPLE IL. */
669 operand *match;
670 source_location match_location;
671 /* For a (simplify ...) an expression with ifs and withs with the expression
672 produced when the pattern applies in the leafs.
673 For a (match ...) the leafs are either empty if it is a simple predicate
674 or the single expression specifying the matched operands. */
675 struct operand *result;
676 source_location result_location;
677 /* Collected 'for' expression operators that have to be replaced
678 in the lowering phase. */
679 vec<vec<user_id *> > for_vec;
680 /* A map of capture identifiers to indexes. */
681 cid_map_t *capture_ids;
682 int capture_max;
685 /* Debugging routines for dumping the AST. */
687 DEBUG_FUNCTION void
688 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
690 if (capture *c = dyn_cast<capture *> (o))
692 fprintf (f, "@%u", c->where);
693 if (c->what && flattened == false)
695 putc (':', f);
696 print_operand (c->what, f, flattened);
697 putc (' ', f);
701 else if (predicate *p = dyn_cast<predicate *> (o))
702 fprintf (f, "%s", p->p->id);
704 else if (is_a<c_expr *> (o))
705 fprintf (f, "c_expr");
707 else if (expr *e = dyn_cast<expr *> (o))
709 fprintf (f, "(%s", e->operation->id);
711 if (flattened == false)
713 putc (' ', f);
714 for (unsigned i = 0; i < e->ops.length (); ++i)
716 print_operand (e->ops[i], f, flattened);
717 putc (' ', f);
720 putc (')', f);
723 else
724 gcc_unreachable ();
727 DEBUG_FUNCTION void
728 print_matches (struct simplify *s, FILE *f = stderr)
730 fprintf (f, "for expression: ");
731 print_operand (s->match, f);
732 putc ('\n', f);
736 /* AST lowering. */
738 /* Lowering of commutative operators. */
740 static void
741 cartesian_product (const vec< vec<operand *> >& ops_vector,
742 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
744 if (n == ops_vector.length ())
746 vec<operand *> xv = v.copy ();
747 result.safe_push (xv);
748 return;
751 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
753 v[n] = ops_vector[n][i];
754 cartesian_product (ops_vector, result, v, n + 1);
758 /* Lower OP to two operands in case it is marked as commutative. */
760 static vec<operand *>
761 commutate (operand *op)
763 vec<operand *> ret = vNULL;
765 if (capture *c = dyn_cast <capture *> (op))
767 if (!c->what)
769 ret.safe_push (op);
770 return ret;
772 vec<operand *> v = commutate (c->what);
773 for (unsigned i = 0; i < v.length (); ++i)
775 capture *nc = new capture (c->where, v[i]);
776 ret.safe_push (nc);
778 return ret;
781 expr *e = dyn_cast <expr *> (op);
782 if (!e || e->ops.length () == 0)
784 ret.safe_push (op);
785 return ret;
788 vec< vec<operand *> > ops_vector = vNULL;
789 for (unsigned i = 0; i < e->ops.length (); ++i)
790 ops_vector.safe_push (commutate (e->ops[i]));
792 auto_vec< vec<operand *> > result;
793 auto_vec<operand *> v (e->ops.length ());
794 v.quick_grow_cleared (e->ops.length ());
795 cartesian_product (ops_vector, result, v, 0);
798 for (unsigned i = 0; i < result.length (); ++i)
800 expr *ne = new expr (e);
801 ne->is_commutative = false;
802 for (unsigned j = 0; j < result[i].length (); ++j)
803 ne->append_op (result[i][j]);
804 ret.safe_push (ne);
807 if (!e->is_commutative)
808 return ret;
810 for (unsigned i = 0; i < result.length (); ++i)
812 expr *ne = new expr (e);
813 ne->is_commutative = false;
814 // result[i].length () is 2 since e->operation is binary
815 for (unsigned j = result[i].length (); j; --j)
816 ne->append_op (result[i][j-1]);
817 ret.safe_push (ne);
820 return ret;
823 /* Lower operations marked as commutative in the AST of S and push
824 the resulting patterns to SIMPLIFIERS. */
826 static void
827 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
829 vec<operand *> matchers = commutate (s->match);
830 for (unsigned i = 0; i < matchers.length (); ++i)
832 simplify *ns = new simplify (s->kind, matchers[i], s->match_location,
833 s->result, s->result_location,
834 s->for_vec, s->capture_ids);
835 simplifiers.safe_push (ns);
839 /* Strip conditional conversios using operator OPER from O and its
840 children if STRIP, else replace them with an unconditional convert. */
842 operand *
843 lower_opt_convert (operand *o, enum tree_code oper,
844 enum tree_code to_oper, bool strip)
846 if (capture *c = dyn_cast<capture *> (o))
848 if (c->what)
849 return new capture (c->where,
850 lower_opt_convert (c->what, oper, to_oper, strip));
851 else
852 return c;
855 expr *e = dyn_cast<expr *> (o);
856 if (!e)
857 return o;
859 if (*e->operation == oper)
861 if (strip)
862 return lower_opt_convert (e->ops[0], oper, to_oper, strip);
864 expr *ne = new expr (e);
865 ne->operation = (to_oper == CONVERT_EXPR
866 ? get_operator ("CONVERT_EXPR")
867 : get_operator ("VIEW_CONVERT_EXPR"));
868 ne->append_op (lower_opt_convert (e->ops[0], oper, to_oper, strip));
869 return ne;
872 expr *ne = new expr (e);
873 for (unsigned i = 0; i < e->ops.length (); ++i)
874 ne->append_op (lower_opt_convert (e->ops[i], oper, to_oper, strip));
876 return ne;
879 /* Determine whether O or its children uses the conditional conversion
880 operator OPER. */
882 static bool
883 has_opt_convert (operand *o, enum tree_code oper)
885 if (capture *c = dyn_cast<capture *> (o))
887 if (c->what)
888 return has_opt_convert (c->what, oper);
889 else
890 return false;
893 expr *e = dyn_cast<expr *> (o);
894 if (!e)
895 return false;
897 if (*e->operation == oper)
898 return true;
900 for (unsigned i = 0; i < e->ops.length (); ++i)
901 if (has_opt_convert (e->ops[i], oper))
902 return true;
904 return false;
907 /* Lower conditional convert operators in O, expanding it to a vector
908 if required. */
910 static vec<operand *>
911 lower_opt_convert (operand *o)
913 vec<operand *> v1 = vNULL, v2;
915 v1.safe_push (o);
917 enum tree_code opers[]
918 = { CONVERT0, CONVERT_EXPR,
919 CONVERT1, CONVERT_EXPR,
920 CONVERT2, CONVERT_EXPR,
921 VIEW_CONVERT0, VIEW_CONVERT_EXPR,
922 VIEW_CONVERT1, VIEW_CONVERT_EXPR,
923 VIEW_CONVERT2, VIEW_CONVERT_EXPR };
925 /* Conditional converts are lowered to a pattern with the
926 conversion and one without. The three different conditional
927 convert codes are lowered separately. */
929 for (unsigned i = 0; i < sizeof (opers) / sizeof (enum tree_code); i += 2)
931 v2 = vNULL;
932 for (unsigned j = 0; j < v1.length (); ++j)
933 if (has_opt_convert (v1[j], opers[i]))
935 v2.safe_push (lower_opt_convert (v1[j],
936 opers[i], opers[i+1], false));
937 v2.safe_push (lower_opt_convert (v1[j],
938 opers[i], opers[i+1], true));
941 if (v2 != vNULL)
943 v1 = vNULL;
944 for (unsigned j = 0; j < v2.length (); ++j)
945 v1.safe_push (v2[j]);
949 return v1;
952 /* Lower conditional convert operators in the AST of S and push
953 the resulting multiple patterns to SIMPLIFIERS. */
955 static void
956 lower_opt_convert (simplify *s, vec<simplify *>& simplifiers)
958 vec<operand *> matchers = lower_opt_convert (s->match);
959 for (unsigned i = 0; i < matchers.length (); ++i)
961 simplify *ns = new simplify (s->kind, matchers[i], s->match_location,
962 s->result, s->result_location,
963 s->for_vec, s->capture_ids);
964 simplifiers.safe_push (ns);
968 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
969 GENERIC and a GIMPLE variant. */
971 static vec<operand *>
972 lower_cond (operand *o)
974 vec<operand *> ro = vNULL;
976 if (capture *c = dyn_cast<capture *> (o))
978 if (c->what)
980 vec<operand *> lop = vNULL;
981 lop = lower_cond (c->what);
983 for (unsigned i = 0; i < lop.length (); ++i)
984 ro.safe_push (new capture (c->where, lop[i]));
985 return ro;
989 expr *e = dyn_cast<expr *> (o);
990 if (!e || e->ops.length () == 0)
992 ro.safe_push (o);
993 return ro;
996 vec< vec<operand *> > ops_vector = vNULL;
997 for (unsigned i = 0; i < e->ops.length (); ++i)
998 ops_vector.safe_push (lower_cond (e->ops[i]));
1000 auto_vec< vec<operand *> > result;
1001 auto_vec<operand *> v (e->ops.length ());
1002 v.quick_grow_cleared (e->ops.length ());
1003 cartesian_product (ops_vector, result, v, 0);
1005 for (unsigned i = 0; i < result.length (); ++i)
1007 expr *ne = new expr (e);
1008 for (unsigned j = 0; j < result[i].length (); ++j)
1009 ne->append_op (result[i][j]);
1010 ro.safe_push (ne);
1011 /* If this is a COND with a captured expression or an
1012 expression with two operands then also match a GENERIC
1013 form on the compare. */
1014 if ((*e->operation == COND_EXPR
1015 || *e->operation == VEC_COND_EXPR)
1016 && ((is_a <capture *> (e->ops[0])
1017 && as_a <capture *> (e->ops[0])->what
1018 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
1019 && as_a <expr *>
1020 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
1021 || (is_a <expr *> (e->ops[0])
1022 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
1024 expr *ne = new expr (e);
1025 for (unsigned j = 0; j < result[i].length (); ++j)
1026 ne->append_op (result[i][j]);
1027 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
1029 expr *ocmp = as_a <expr *> (c->what);
1030 expr *cmp = new expr (ocmp);
1031 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1032 cmp->append_op (ocmp->ops[j]);
1033 cmp->is_generic = true;
1034 ne->ops[0] = new capture (c->where, cmp);
1036 else
1038 expr *ocmp = as_a <expr *> (ne->ops[0]);
1039 expr *cmp = new expr (ocmp);
1040 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1041 cmp->append_op (ocmp->ops[j]);
1042 cmp->is_generic = true;
1043 ne->ops[0] = cmp;
1045 ro.safe_push (ne);
1049 return ro;
1052 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1053 GENERIC and a GIMPLE variant. */
1055 static void
1056 lower_cond (simplify *s, vec<simplify *>& simplifiers)
1058 vec<operand *> matchers = lower_cond (s->match);
1059 for (unsigned i = 0; i < matchers.length (); ++i)
1061 simplify *ns = new simplify (s->kind, matchers[i], s->match_location,
1062 s->result, s->result_location,
1063 s->for_vec, s->capture_ids);
1064 simplifiers.safe_push (ns);
1068 /* In AST operand O replace operator ID with operator WITH. */
1070 operand *
1071 replace_id (operand *o, user_id *id, id_base *with)
1073 /* Deep-copy captures and expressions, replacing operations as
1074 needed. */
1075 if (capture *c = dyn_cast<capture *> (o))
1077 if (!c->what)
1078 return c;
1079 return new capture (c->where, replace_id (c->what, id, with));
1081 else if (expr *e = dyn_cast<expr *> (o))
1083 expr *ne = new expr (e);
1084 if (e->operation == id)
1085 ne->operation = with;
1086 for (unsigned i = 0; i < e->ops.length (); ++i)
1087 ne->append_op (replace_id (e->ops[i], id, with));
1088 return ne;
1090 else if (with_expr *w = dyn_cast <with_expr *> (o))
1092 with_expr *nw = new with_expr ();
1093 nw->with = as_a <c_expr *> (replace_id (w->with, id, with));
1094 nw->subexpr = replace_id (w->subexpr, id, with);
1095 return nw;
1097 else if (if_expr *ife = dyn_cast <if_expr *> (o))
1099 if_expr *nife = new if_expr ();
1100 nife->cond = as_a <c_expr *> (replace_id (ife->cond, id, with));
1101 nife->trueexpr = replace_id (ife->trueexpr, id, with);
1102 if (ife->falseexpr)
1103 nife->falseexpr = replace_id (ife->falseexpr, id, with);
1104 return nife;
1107 /* For c_expr we simply record a string replacement table which is
1108 applied at code-generation time. */
1109 if (c_expr *ce = dyn_cast<c_expr *> (o))
1111 vec<c_expr::id_tab> ids = ce->ids.copy ();
1112 ids.safe_push (c_expr::id_tab (id->id, with->id));
1113 return new c_expr (ce->r, ce->code, ce->nr_stmts, ids, ce->capture_ids);
1116 return o;
1119 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
1121 static void
1122 lower_for (simplify *sin, vec<simplify *>& simplifiers)
1124 vec<vec<user_id *> >& for_vec = sin->for_vec;
1125 unsigned worklist_start = 0;
1126 auto_vec<simplify *> worklist;
1127 worklist.safe_push (sin);
1129 /* Lower each recorded for separately, operating on the
1130 set of simplifiers created by the previous one.
1131 Lower inner-to-outer so inner for substitutes can refer
1132 to operators replaced by outer fors. */
1133 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1135 vec<user_id *>& ids = for_vec[fi];
1136 unsigned n_ids = ids.length ();
1137 unsigned max_n_opers = 0;
1138 for (unsigned i = 0; i < n_ids; ++i)
1139 if (ids[i]->substitutes.length () > max_n_opers)
1140 max_n_opers = ids[i]->substitutes.length ();
1142 unsigned worklist_end = worklist.length ();
1143 for (unsigned si = worklist_start; si < worklist_end; ++si)
1145 simplify *s = worklist[si];
1146 for (unsigned j = 0; j < max_n_opers; ++j)
1148 operand *match_op = s->match;
1149 operand *result_op = s->result;
1150 for (unsigned i = 0; i < n_ids; ++i)
1152 user_id *id = ids[i];
1153 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1154 match_op = replace_id (match_op, id, oper);
1155 if (result_op)
1156 result_op = replace_id (result_op, id, oper);
1158 simplify *ns = new simplify (s->kind, match_op, s->match_location,
1159 result_op, s->result_location,
1160 vNULL, s->capture_ids);
1161 worklist.safe_push (ns);
1164 worklist_start = worklist_end;
1167 /* Copy out the result from the last for lowering. */
1168 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1169 simplifiers.safe_push (worklist[i]);
1172 /* Lower the AST for everything in SIMPLIFIERS. */
1174 static void
1175 lower (vec<simplify *>& simplifiers, bool gimple)
1177 auto_vec<simplify *> out_simplifiers;
1178 for (unsigned i = 0; i < simplifiers.length (); ++i)
1179 lower_opt_convert (simplifiers[i], out_simplifiers);
1181 simplifiers.truncate (0);
1182 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1183 lower_commutative (out_simplifiers[i], simplifiers);
1185 out_simplifiers.truncate (0);
1186 if (gimple)
1187 for (unsigned i = 0; i < simplifiers.length (); ++i)
1188 lower_cond (simplifiers[i], out_simplifiers);
1189 else
1190 out_simplifiers.safe_splice (simplifiers);
1193 simplifiers.truncate (0);
1194 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1195 lower_for (out_simplifiers[i], simplifiers);
1201 /* The decision tree built for generating GIMPLE and GENERIC pattern
1202 matching code. It represents the 'match' expression of all
1203 simplifies and has those as its leafs. */
1205 /* Decision tree base class, used for DT_TRUE and DT_NODE. */
1207 struct dt_node
1209 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1211 enum dt_type type;
1212 unsigned level;
1213 vec<dt_node *> kids;
1215 dt_node (enum dt_type type_): type (type_), level (0), kids (vNULL) {}
1217 dt_node *append_node (dt_node *);
1218 dt_node *append_op (operand *, dt_node *parent = 0, unsigned pos = 0);
1219 dt_node *append_true_op (dt_node *parent = 0, unsigned pos = 0);
1220 dt_node *append_match_op (dt_operand *, dt_node *parent = 0, unsigned pos = 0);
1221 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1223 virtual void gen (FILE *, int, bool) {}
1225 void gen_kids (FILE *, int, bool);
1226 void gen_kids_1 (FILE *, int, bool,
1227 vec<dt_operand *>, vec<dt_operand *>, vec<dt_operand *>,
1228 vec<dt_operand *>, vec<dt_operand *>, vec<dt_node *>);
1231 /* Generic decision tree node used for DT_OPERAND and DT_MATCH. */
1233 struct dt_operand : public dt_node
1235 operand *op;
1236 dt_operand *match_dop;
1237 dt_operand *parent;
1238 unsigned pos;
1240 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1241 dt_operand *parent_ = 0, unsigned pos_ = 0)
1242 : dt_node (type), op (op_), match_dop (match_dop_),
1243 parent (parent_), pos (pos_) {}
1245 void gen (FILE *, int, bool);
1246 unsigned gen_predicate (FILE *, int, const char *, bool);
1247 unsigned gen_match_op (FILE *, int, const char *);
1249 unsigned gen_gimple_expr (FILE *, int);
1250 unsigned gen_generic_expr (FILE *, int, const char *);
1252 char *get_name (char *);
1253 void gen_opname (char *, unsigned);
1256 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1258 struct dt_simplify : public dt_node
1260 simplify *s;
1261 unsigned pattern_no;
1262 dt_operand **indexes;
1264 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1265 : dt_node (DT_SIMPLIFY), s (s_), pattern_no (pattern_no_),
1266 indexes (indexes_) {}
1268 void gen_1 (FILE *, int, bool, operand *);
1269 void gen (FILE *f, int, bool);
1272 template<>
1273 template<>
1274 inline bool
1275 is_a_helper <dt_operand *>::test (dt_node *n)
1277 return (n->type == dt_node::DT_OPERAND
1278 || n->type == dt_node::DT_MATCH);
1281 /* A container for the actual decision tree. */
1283 struct decision_tree
1285 dt_node *root;
1287 void insert (struct simplify *, unsigned);
1288 void gen_gimple (FILE *f = stderr);
1289 void gen_generic (FILE *f = stderr);
1290 void print (FILE *f = stderr);
1292 decision_tree () { root = new dt_node (dt_node::DT_NODE); }
1294 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1295 unsigned pos = 0, dt_node *parent = 0);
1296 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1297 static bool cmp_node (dt_node *, dt_node *);
1298 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1301 /* Compare two AST operands O1 and O2 and return true if they are equal. */
1303 bool
1304 cmp_operand (operand *o1, operand *o2)
1306 if (!o1 || !o2 || o1->type != o2->type)
1307 return false;
1309 if (o1->type == operand::OP_PREDICATE)
1311 predicate *p1 = as_a<predicate *>(o1);
1312 predicate *p2 = as_a<predicate *>(o2);
1313 return p1->p == p2->p;
1315 else if (o1->type == operand::OP_EXPR)
1317 expr *e1 = static_cast<expr *>(o1);
1318 expr *e2 = static_cast<expr *>(o2);
1319 return (e1->operation == e2->operation
1320 && e1->is_generic == e2->is_generic);
1322 else
1323 return false;
1326 /* Compare two decision tree nodes N1 and N2 and return true if they
1327 are equal. */
1329 bool
1330 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1332 if (!n1 || !n2 || n1->type != n2->type)
1333 return false;
1335 if (n1 == n2)
1336 return true;
1338 if (n1->type == dt_node::DT_TRUE)
1339 return false;
1341 if (n1->type == dt_node::DT_OPERAND)
1342 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1343 (as_a<dt_operand *> (n2))->op);
1344 else if (n1->type == dt_node::DT_MATCH)
1345 return ((as_a<dt_operand *> (n1))->match_dop
1346 == (as_a<dt_operand *> (n2))->match_dop);
1347 return false;
1350 /* Search OPS for a decision tree node like P and return it if found. */
1352 dt_node *
1353 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1355 /* We can merge adjacent DT_TRUE. */
1356 if (p->type == dt_node::DT_TRUE
1357 && !ops.is_empty ()
1358 && ops.last ()->type == dt_node::DT_TRUE)
1359 return ops.last ();
1360 for (int i = ops.length () - 1; i >= 0; --i)
1362 /* But we can't merge across DT_TRUE nodes as they serve as
1363 pattern order barriers to make sure that patterns apply
1364 in order of appearance in case multiple matches are possible. */
1365 if (ops[i]->type == dt_node::DT_TRUE)
1366 return NULL;
1367 if (decision_tree::cmp_node (ops[i], p))
1368 return ops[i];
1370 return NULL;
1373 /* Append N to the decision tree if it there is not already an existing
1374 identical child. */
1376 dt_node *
1377 dt_node::append_node (dt_node *n)
1379 dt_node *kid;
1381 kid = decision_tree::find_node (kids, n);
1382 if (kid)
1383 return kid;
1385 kids.safe_push (n);
1386 n->level = this->level + 1;
1388 return n;
1391 /* Append OP to the decision tree. */
1393 dt_node *
1394 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1396 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1397 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1398 return append_node (n);
1401 /* Append a DT_TRUE decision tree node. */
1403 dt_node *
1404 dt_node::append_true_op (dt_node *parent, unsigned pos)
1406 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1407 dt_operand *n = new dt_operand (DT_TRUE, 0, 0, parent_, pos);
1408 return append_node (n);
1411 /* Append a DT_MATCH decision tree node. */
1413 dt_node *
1414 dt_node::append_match_op (dt_operand *match_dop, dt_node *parent, unsigned pos)
1416 dt_operand *parent_ = as_a<dt_operand *> (parent);
1417 dt_operand *n = new dt_operand (DT_MATCH, 0, match_dop, parent_, pos);
1418 return append_node (n);
1421 /* Append S to the decision tree. */
1423 dt_node *
1424 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1425 dt_operand **indexes)
1427 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1428 return append_node (n);
1431 /* Insert O into the decision tree and return the decision tree node found
1432 or created. */
1434 dt_node *
1435 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1436 unsigned pos, dt_node *parent)
1438 dt_node *q, *elm = 0;
1440 if (capture *c = dyn_cast<capture *> (o))
1442 unsigned capt_index = c->where;
1444 if (indexes[capt_index] == 0)
1446 if (c->what)
1447 q = insert_operand (p, c->what, indexes, pos, parent);
1448 else
1450 q = elm = p->append_true_op (parent, pos);
1451 goto at_assert_elm;
1453 // get to the last capture
1454 for (operand *what = c->what;
1455 what && is_a<capture *> (what);
1456 c = as_a<capture *> (what), what = c->what)
1459 if (!c->what)
1461 unsigned cc_index = c->where;
1462 dt_operand *match_op = indexes[cc_index];
1464 dt_operand temp (dt_node::DT_TRUE, 0, 0);
1465 elm = decision_tree::find_node (p->kids, &temp);
1467 if (elm == 0)
1469 dt_operand temp (dt_node::DT_MATCH, 0, match_op);
1470 elm = decision_tree::find_node (p->kids, &temp);
1473 else
1475 dt_operand temp (dt_node::DT_OPERAND, c->what, 0);
1476 elm = decision_tree::find_node (p->kids, &temp);
1479 at_assert_elm:
1480 gcc_assert (elm->type == dt_node::DT_TRUE
1481 || elm->type == dt_node::DT_OPERAND
1482 || elm->type == dt_node::DT_MATCH);
1483 indexes[capt_index] = static_cast<dt_operand *> (elm);
1484 return q;
1486 else
1488 p = p->append_match_op (indexes[capt_index], parent, pos);
1489 if (c->what)
1490 return insert_operand (p, c->what, indexes, 0, p);
1491 else
1492 return p;
1495 p = p->append_op (o, parent, pos);
1496 q = p;
1498 if (expr *e = dyn_cast <expr *>(o))
1500 for (unsigned i = 0; i < e->ops.length (); ++i)
1501 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
1504 return q;
1507 /* Insert S into the decision tree. */
1509 void
1510 decision_tree::insert (struct simplify *s, unsigned pattern_no)
1512 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
1513 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
1514 p->append_simplify (s, pattern_no, indexes);
1517 /* Debug functions to dump the decision tree. */
1519 DEBUG_FUNCTION void
1520 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
1522 if (p->type == dt_node::DT_NODE)
1523 fprintf (f, "root");
1524 else
1526 fprintf (f, "|");
1527 for (unsigned i = 0; i < indent; i++)
1528 fprintf (f, "-");
1530 if (p->type == dt_node::DT_OPERAND)
1532 dt_operand *dop = static_cast<dt_operand *>(p);
1533 print_operand (dop->op, f, true);
1535 else if (p->type == dt_node::DT_TRUE)
1536 fprintf (f, "true");
1537 else if (p->type == dt_node::DT_MATCH)
1538 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
1539 else if (p->type == dt_node::DT_SIMPLIFY)
1541 dt_simplify *s = static_cast<dt_simplify *> (p);
1542 fprintf (f, "simplify_%u { ", s->pattern_no);
1543 for (int i = 0; i <= s->s->capture_max; ++i)
1544 fprintf (f, "%p, ", (void *) s->indexes[i]);
1545 fprintf (f, " } ");
1549 fprintf (stderr, " (%p), %u, %u\n", (void *) p, p->level, p->kids.length ());
1551 for (unsigned i = 0; i < p->kids.length (); ++i)
1552 decision_tree::print_node (p->kids[i], f, indent + 2);
1555 DEBUG_FUNCTION void
1556 decision_tree::print (FILE *f)
1558 return decision_tree::print_node (root, f);
1562 /* For GENERIC we have to take care of wrapping multiple-used
1563 expressions with side-effects in save_expr and preserve side-effects
1564 of expressions with omit_one_operand. Analyze captures in
1565 match, result and with expressions and perform early-outs
1566 on the outermost match expression operands for cases we cannot
1567 handle. */
1569 struct capture_info
1571 capture_info (simplify *s, operand *);
1572 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
1573 bool walk_result (operand *o, bool, operand *);
1574 void walk_c_expr (c_expr *);
1576 struct cinfo
1578 bool expr_p;
1579 bool cse_p;
1580 bool force_no_side_effects_p;
1581 bool force_single_use;
1582 bool cond_expr_cond_p;
1583 unsigned long toplevel_msk;
1584 int result_use_count;
1587 auto_vec<cinfo> info;
1588 unsigned long force_no_side_effects;
1591 /* Analyze captures in S. */
1593 capture_info::capture_info (simplify *s, operand *result)
1595 expr *e;
1596 if (s->kind == simplify::MATCH)
1598 force_no_side_effects = -1;
1599 return;
1602 force_no_side_effects = 0;
1603 info.safe_grow_cleared (s->capture_max + 1);
1604 e = as_a <expr *> (s->match);
1605 for (unsigned i = 0; i < e->ops.length (); ++i)
1606 walk_match (e->ops[i], i,
1607 (i != 0 && *e->operation == COND_EXPR)
1608 || *e->operation == TRUTH_ANDIF_EXPR
1609 || *e->operation == TRUTH_ORIF_EXPR,
1610 i == 0
1611 && (*e->operation == COND_EXPR
1612 || *e->operation == VEC_COND_EXPR));
1614 walk_result (s->result, false, result);
1617 /* Analyze captures in the match expression piece O. */
1619 void
1620 capture_info::walk_match (operand *o, unsigned toplevel_arg,
1621 bool conditional_p, bool cond_expr_cond_p)
1623 if (capture *c = dyn_cast <capture *> (o))
1625 info[c->where].toplevel_msk |= 1 << toplevel_arg;
1626 info[c->where].force_no_side_effects_p |= conditional_p;
1627 info[c->where].cond_expr_cond_p |= cond_expr_cond_p;
1628 /* Mark expr (non-leaf) captures and recurse. */
1629 expr *e;
1630 if (c->what
1631 && (e = dyn_cast <expr *> (c->what)))
1633 info[c->where].expr_p = true;
1634 info[c->where].force_single_use |= e->force_single_use;
1635 walk_match (c->what, toplevel_arg, conditional_p, false);
1638 else if (expr *e = dyn_cast <expr *> (o))
1640 for (unsigned i = 0; i < e->ops.length (); ++i)
1642 bool cond_p = conditional_p;
1643 bool cond_expr_cond_p = false;
1644 if (i != 0 && *e->operation == COND_EXPR)
1645 cond_p = true;
1646 else if (*e->operation == TRUTH_ANDIF_EXPR
1647 || *e->operation == TRUTH_ORIF_EXPR)
1648 cond_p = true;
1649 if (i == 0
1650 && (*e->operation == COND_EXPR
1651 || *e->operation == VEC_COND_EXPR))
1652 cond_expr_cond_p = true;
1653 walk_match (e->ops[i], toplevel_arg, cond_p, cond_expr_cond_p);
1656 else if (is_a <predicate *> (o))
1658 /* Mark non-captured leafs toplevel arg for checking. */
1659 force_no_side_effects |= 1 << toplevel_arg;
1661 else
1662 gcc_unreachable ();
1665 /* Analyze captures in the result expression piece O. Return true
1666 if RESULT was visited in one of the children. Only visit
1667 non-if/with children if they are rooted on RESULT. */
1669 bool
1670 capture_info::walk_result (operand *o, bool conditional_p, operand *result)
1672 if (capture *c = dyn_cast <capture *> (o))
1674 info[c->where].result_use_count++;
1675 /* If we substitute an expression capture we don't know
1676 which captures this will end up using (well, we don't
1677 compute that). Force the uses to be side-effect free
1678 which means forcing the toplevels that reach the
1679 expression side-effect free. */
1680 if (info[c->where].expr_p)
1681 force_no_side_effects |= info[c->where].toplevel_msk;
1682 /* Mark CSE capture uses as forced to have no side-effects. */
1683 if (c->what
1684 && is_a <expr *> (c->what))
1686 info[c->where].cse_p = true;
1687 walk_result (c->what, true, result);
1690 else if (expr *e = dyn_cast <expr *> (o))
1692 for (unsigned i = 0; i < e->ops.length (); ++i)
1694 bool cond_p = conditional_p;
1695 if (i != 0 && *e->operation == COND_EXPR)
1696 cond_p = true;
1697 else if (*e->operation == TRUTH_ANDIF_EXPR
1698 || *e->operation == TRUTH_ORIF_EXPR)
1699 cond_p = true;
1700 walk_result (e->ops[i], cond_p, result);
1703 else if (if_expr *e = dyn_cast <if_expr *> (o))
1705 /* 'if' conditions should be all fine. */
1706 if (e->trueexpr == result)
1708 walk_result (e->trueexpr, false, result);
1709 return true;
1711 if (e->falseexpr == result)
1713 walk_result (e->falseexpr, false, result);
1714 return true;
1716 bool res = false;
1717 if (is_a <if_expr *> (e->trueexpr)
1718 || is_a <with_expr *> (e->trueexpr))
1719 res |= walk_result (e->trueexpr, false, result);
1720 if (e->falseexpr
1721 && (is_a <if_expr *> (e->falseexpr)
1722 || is_a <with_expr *> (e->falseexpr)))
1723 res |= walk_result (e->falseexpr, false, result);
1724 return res;
1726 else if (with_expr *e = dyn_cast <with_expr *> (o))
1728 bool res = (e->subexpr == result);
1729 if (res
1730 || is_a <if_expr *> (e->subexpr)
1731 || is_a <with_expr *> (e->subexpr))
1732 res |= walk_result (e->subexpr, false, result);
1733 if (res)
1734 walk_c_expr (e->with);
1735 return res;
1737 else if (c_expr *e = dyn_cast <c_expr *> (o))
1738 walk_c_expr (e);
1739 else
1740 gcc_unreachable ();
1742 return false;
1745 /* Look for captures in the C expr E. */
1747 void
1748 capture_info::walk_c_expr (c_expr *e)
1750 /* Give up for C exprs mentioning captures not inside TREE_TYPE (). */
1751 unsigned p_depth = 0;
1752 for (unsigned i = 0; i < e->code.length (); ++i)
1754 const cpp_token *t = &e->code[i];
1755 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
1756 if (t->type == CPP_NAME
1757 && strcmp ((const char *)CPP_HASHNODE
1758 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
1759 && n->type == CPP_OPEN_PAREN)
1760 p_depth++;
1761 else if (t->type == CPP_CLOSE_PAREN
1762 && p_depth > 0)
1763 p_depth--;
1764 else if (p_depth == 0
1765 && t->type == CPP_ATSIGN
1766 && (n->type == CPP_NUMBER
1767 || n->type == CPP_NAME)
1768 && !(n->flags & PREV_WHITE))
1770 const char *id;
1771 if (n->type == CPP_NUMBER)
1772 id = (const char *)n->val.str.text;
1773 else
1774 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
1775 info[*e->capture_ids->get(id)].force_no_side_effects_p = true;
1781 /* Code generation off the decision tree and the refered AST nodes. */
1783 bool
1784 is_conversion (id_base *op)
1786 return (*op == CONVERT_EXPR
1787 || *op == NOP_EXPR
1788 || *op == FLOAT_EXPR
1789 || *op == FIX_TRUNC_EXPR
1790 || *op == VIEW_CONVERT_EXPR);
1793 /* Get the type to be used for generating operands of OP from the
1794 various sources. */
1796 static const char *
1797 get_operand_type (id_base *op, const char *in_type,
1798 const char *expr_type,
1799 const char *other_oprnd_type)
1801 /* Generally operands whose type does not match the type of the
1802 expression generated need to know their types but match and
1803 thus can fall back to 'other_oprnd_type'. */
1804 if (is_conversion (op))
1805 return other_oprnd_type;
1806 else if (*op == REALPART_EXPR
1807 || *op == IMAGPART_EXPR)
1808 return other_oprnd_type;
1809 else if (is_a <operator_id *> (op)
1810 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
1811 return other_oprnd_type;
1812 else
1814 /* Otherwise all types should match - choose one in order of
1815 preference. */
1816 if (expr_type)
1817 return expr_type;
1818 else if (in_type)
1819 return in_type;
1820 else
1821 return other_oprnd_type;
1825 /* Generate transform code for an expression. */
1827 void
1828 expr::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
1829 int depth, const char *in_type, capture_info *cinfo,
1830 dt_operand **indexes, bool)
1832 bool conversion_p = is_conversion (operation);
1833 const char *type = expr_type;
1834 char optype[64];
1835 if (type)
1836 /* If there was a type specification in the pattern use it. */
1838 else if (conversion_p)
1839 /* For conversions we need to build the expression using the
1840 outer type passed in. */
1841 type = in_type;
1842 else if (*operation == REALPART_EXPR
1843 || *operation == IMAGPART_EXPR)
1845 /* __real and __imag use the component type of its operand. */
1846 sprintf (optype, "TREE_TYPE (TREE_TYPE (ops%d[0]))", depth);
1847 type = optype;
1849 else if (is_a <operator_id *> (operation)
1850 && !strcmp (as_a <operator_id *> (operation)->tcc, "tcc_comparison"))
1852 /* comparisons use boolean_type_node (or what gets in), but
1853 their operands need to figure out the types themselves. */
1854 sprintf (optype, "boolean_type_node");
1855 type = optype;
1857 else if (*operation == COND_EXPR
1858 || *operation == VEC_COND_EXPR)
1860 /* Conditions are of the same type as their first alternative. */
1861 sprintf (optype, "TREE_TYPE (ops%d[1])", depth);
1862 type = optype;
1864 else
1866 /* Other operations are of the same type as their first operand. */
1867 sprintf (optype, "TREE_TYPE (ops%d[0])", depth);
1868 type = optype;
1870 if (!type)
1871 fatal ("two conversions in a row");
1873 fprintf_indent (f, indent, "{\n");
1874 indent += 2;
1875 fprintf_indent (f, indent, "tree ops%d[%u], res;\n", depth, ops.length ());
1876 char op0type[64];
1877 snprintf (op0type, 64, "TREE_TYPE (ops%d[0])", depth);
1878 for (unsigned i = 0; i < ops.length (); ++i)
1880 char dest[32];
1881 snprintf (dest, 32, "ops%d[%u]", depth, i);
1882 const char *optype
1883 = get_operand_type (operation, in_type, expr_type,
1884 i == 0 ? NULL : op0type);
1885 ops[i]->gen_transform (f, indent, dest, gimple, depth + 1, optype,
1886 cinfo, indexes,
1887 ((!(*operation == COND_EXPR)
1888 && !(*operation == VEC_COND_EXPR))
1889 || i != 0));
1892 const char *opr;
1893 if (*operation == CONVERT_EXPR)
1894 opr = "NOP_EXPR";
1895 else
1896 opr = operation->id;
1898 if (gimple)
1900 if (*operation == CONVERT_EXPR)
1902 fprintf_indent (f, indent,
1903 "if (%s != TREE_TYPE (ops%d[0])\n",
1904 type, depth);
1905 fprintf_indent (f, indent,
1906 " && !useless_type_conversion_p (%s, TREE_TYPE (ops%d[0])))\n",
1907 type, depth);
1908 fprintf_indent (f, indent + 2, "{\n");
1909 indent += 4;
1911 /* ??? Building a stmt can fail for various reasons here, seq being
1912 NULL or the stmt referencing SSA names occuring in abnormal PHIs.
1913 So if we fail here we should continue matching other patterns. */
1914 fprintf_indent (f, indent, "code_helper tem_code = %s;\n", opr);
1915 fprintf_indent (f, indent, "tree tem_ops[3] = { ");
1916 for (unsigned i = 0; i < ops.length (); ++i)
1917 fprintf (f, "ops%d[%u]%s", depth, i,
1918 i == ops.length () - 1 ? " };\n" : ", ");
1919 fprintf_indent (f, indent,
1920 "gimple_resimplify%d (lseq, &tem_code, %s, tem_ops, valueize);\n",
1921 ops.length (), type);
1922 fprintf_indent (f, indent,
1923 "res = maybe_push_res_to_seq (tem_code, %s, tem_ops, lseq);\n",
1924 type);
1925 fprintf_indent (f, indent,
1926 "if (!res) return false;\n");
1927 if (*operation == CONVERT_EXPR)
1929 indent -= 4;
1930 fprintf_indent (f, indent, " }\n");
1931 fprintf_indent (f, indent, "else\n");
1932 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
1935 else
1937 if (*operation == CONVERT_EXPR)
1939 fprintf_indent (f, indent, "if (TREE_TYPE (ops%d[0]) != %s)\n",
1940 depth, type);
1941 indent += 2;
1943 if (operation->kind == id_base::CODE)
1944 fprintf_indent (f, indent, "res = fold_build%d_loc (loc, %s, %s",
1945 ops.length(), opr, type);
1946 else
1947 fprintf_indent (f, indent, "res = build_call_expr_loc (loc, "
1948 "builtin_decl_implicit (%s), %d", opr, ops.length());
1949 for (unsigned i = 0; i < ops.length (); ++i)
1950 fprintf (f, ", ops%d[%u]", depth, i);
1951 fprintf (f, ");\n");
1952 if (*operation == CONVERT_EXPR)
1954 indent -= 2;
1955 fprintf_indent (f, indent, "else\n");
1956 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
1959 fprintf_indent (f, indent, "%s = res;\n", dest);
1960 indent -= 2;
1961 fprintf_indent (f, indent, "}\n");
1964 /* Generate code for a c_expr which is either the expression inside
1965 an if statement or a sequence of statements which computes a
1966 result to be stored to DEST. */
1968 void
1969 c_expr::gen_transform (FILE *f, int indent, const char *dest,
1970 bool, int, const char *, capture_info *,
1971 dt_operand **, bool)
1973 if (dest && nr_stmts == 1)
1974 fprintf_indent (f, indent, "%s = ", dest);
1976 unsigned stmt_nr = 1;
1977 for (unsigned i = 0; i < code.length (); ++i)
1979 const cpp_token *token = &code[i];
1981 /* Replace captures for code-gen. */
1982 if (token->type == CPP_ATSIGN)
1984 const cpp_token *n = &code[i+1];
1985 if ((n->type == CPP_NUMBER
1986 || n->type == CPP_NAME)
1987 && !(n->flags & PREV_WHITE))
1989 if (token->flags & PREV_WHITE)
1990 fputc (' ', f);
1991 const char *id;
1992 if (n->type == CPP_NUMBER)
1993 id = (const char *)n->val.str.text;
1994 else
1995 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
1996 fprintf (f, "captures[%u]", *capture_ids->get(id));
1997 ++i;
1998 continue;
2002 if (token->flags & PREV_WHITE)
2003 fputc (' ', f);
2005 if (token->type == CPP_NAME)
2007 const char *id = (const char *) NODE_NAME (token->val.node.node);
2008 unsigned j;
2009 for (j = 0; j < ids.length (); ++j)
2011 if (strcmp (id, ids[j].id) == 0)
2013 fprintf (f, "%s", ids[j].oper);
2014 break;
2017 if (j < ids.length ())
2018 continue;
2021 /* Output the token as string. */
2022 char *tk = (char *)cpp_token_as_text (r, token);
2023 fputs (tk, f);
2025 if (token->type == CPP_SEMICOLON)
2027 stmt_nr++;
2028 fputc ('\n', f);
2029 if (dest && stmt_nr == nr_stmts)
2030 fprintf_indent (f, indent, "%s = ", dest);
2035 /* Generate transform code for a capture. */
2037 void
2038 capture::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2039 int depth, const char *in_type, capture_info *cinfo,
2040 dt_operand **indexes, bool expand_compares)
2042 if (what && is_a<expr *> (what))
2044 if (indexes[where] == 0)
2046 char buf[20];
2047 sprintf (buf, "captures[%u]", where);
2048 what->gen_transform (f, indent, buf, gimple, depth, in_type,
2049 cinfo, NULL);
2053 fprintf_indent (f, indent, "%s = captures[%u];\n", dest, where);
2055 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2056 with substituting a capture of that.
2057 ??? Returning false here will also not allow any other patterns
2058 to match. */
2059 if (gimple && expand_compares
2060 && cinfo->info[where].cond_expr_cond_p)
2062 fprintf_indent (f, indent, "if (COMPARISON_CLASS_P (%s))\n", dest);
2063 fprintf_indent (f, indent, " {\n");
2064 fprintf_indent (f, indent, " if (!seq) return false;\n");
2065 fprintf_indent (f, indent, " %s = gimple_build (seq, TREE_CODE (%s),"
2066 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
2067 " TREE_OPERAND (%s, 1));\n",
2068 dest, dest, dest, dest, dest);
2069 fprintf_indent (f, indent, " }\n");
2073 /* Return the name of the operand representing the decision tree node.
2074 Use NAME as space to generate it. */
2076 char *
2077 dt_operand::get_name (char *name)
2079 if (!parent)
2080 sprintf (name, "t");
2081 else if (parent->level == 1)
2082 sprintf (name, "op%u", pos);
2083 else if (parent->type == dt_node::DT_MATCH)
2084 return parent->get_name (name);
2085 else
2086 sprintf (name, "o%u%u", parent->level, pos);
2087 return name;
2090 /* Fill NAME with the operand name at position POS. */
2092 void
2093 dt_operand::gen_opname (char *name, unsigned pos)
2095 if (!parent)
2096 sprintf (name, "op%u", pos);
2097 else
2098 sprintf (name, "o%u%u", level, pos);
2101 /* Generate matching code for the decision tree operand which is
2102 a predicate. */
2104 unsigned
2105 dt_operand::gen_predicate (FILE *f, int indent, const char *opname, bool gimple)
2107 predicate *p = as_a <predicate *> (op);
2109 if (p->p->matchers.exists ())
2111 /* If this is a predicate generated from a pattern mangle its
2112 name and pass on the valueize hook. */
2113 if (gimple)
2114 fprintf_indent (f, indent, "if (gimple_%s (%s, valueize))\n",
2115 p->p->id, opname);
2116 else
2117 fprintf_indent (f, indent, "if (tree_%s (%s))\n", p->p->id, opname);
2119 else
2120 fprintf_indent (f, indent, "if (%s (%s))\n", p->p->id, opname);
2121 fprintf_indent (f, indent + 2, "{\n");
2122 return 1;
2125 /* Generate matching code for the decision tree operand which is
2126 a capture-match. */
2128 unsigned
2129 dt_operand::gen_match_op (FILE *f, int indent, const char *opname)
2131 char match_opname[20];
2132 match_dop->get_name (match_opname);
2133 fprintf_indent (f, indent, "if (%s == %s || operand_equal_p (%s, %s, 0))\n",
2134 opname, match_opname, opname, match_opname);
2135 fprintf_indent (f, indent + 2, "{\n");
2136 return 1;
2139 /* Generate GIMPLE matching code for the decision tree operand. */
2141 unsigned
2142 dt_operand::gen_gimple_expr (FILE *f, int indent)
2144 expr *e = static_cast<expr *> (op);
2145 id_base *id = e->operation;
2146 unsigned n_ops = e->ops.length ();
2148 for (unsigned i = 0; i < n_ops; ++i)
2150 char child_opname[20];
2151 gen_opname (child_opname, i);
2153 if (id->kind == id_base::CODE)
2155 if (e->is_generic
2156 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2157 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
2159 /* ??? If this is a memory operation we can't (and should not)
2160 match this. The only sensible operand types are
2161 SSA names and invariants. */
2162 fprintf_indent (f, indent,
2163 "tree %s = TREE_OPERAND (gimple_assign_rhs1 (def_stmt), %i);\n",
2164 child_opname, i);
2165 fprintf_indent (f, indent,
2166 "if ((TREE_CODE (%s) == SSA_NAME\n",
2167 child_opname);
2168 fprintf_indent (f, indent,
2169 " || is_gimple_min_invariant (%s))\n",
2170 child_opname);
2171 fprintf_indent (f, indent,
2172 " && (%s = do_valueize (valueize, %s)))\n",
2173 child_opname, child_opname);
2174 fprintf_indent (f, indent,
2175 " {\n");
2176 indent += 4;
2177 continue;
2179 else
2180 fprintf_indent (f, indent,
2181 "tree %s = gimple_assign_rhs%u (def_stmt);\n",
2182 child_opname, i + 1);
2184 else
2185 fprintf_indent (f, indent,
2186 "tree %s = gimple_call_arg (def_stmt, %u);\n",
2187 child_opname, i);
2188 fprintf_indent (f, indent,
2189 "if ((%s = do_valueize (valueize, %s)))\n",
2190 child_opname, child_opname);
2191 fprintf_indent (f, indent, " {\n");
2192 indent += 4;
2194 /* While the toplevel operands are canonicalized by the caller
2195 after valueizing operands of sub-expressions we have to
2196 re-canonicalize operand order. */
2197 if (operator_id *code = dyn_cast <operator_id *> (id))
2199 /* ??? We can't canonicalize tcc_comparison operands here
2200 because that requires changing the comparison code which
2201 we already matched... */
2202 if (commutative_tree_code (code->code)
2203 || commutative_ternary_tree_code (code->code))
2205 char child_opname0[20], child_opname1[20];
2206 gen_opname (child_opname0, 0);
2207 gen_opname (child_opname1, 1);
2208 fprintf_indent (f, indent,
2209 "if (tree_swap_operands_p (%s, %s, false))\n",
2210 child_opname0, child_opname1);
2211 fprintf_indent (f, indent,
2212 " std::swap (%s, %s);\n",
2213 child_opname0, child_opname1);
2217 return n_ops;
2220 /* Generate GENERIC matching code for the decision tree operand. */
2222 unsigned
2223 dt_operand::gen_generic_expr (FILE *f, int indent, const char *opname)
2225 expr *e = static_cast<expr *> (op);
2226 unsigned n_ops = e->ops.length ();
2228 for (unsigned i = 0; i < n_ops; ++i)
2230 char child_opname[20];
2231 gen_opname (child_opname, i);
2233 if (e->operation->kind == id_base::CODE)
2234 fprintf_indent (f, indent, "tree %s = TREE_OPERAND (%s, %u);\n",
2235 child_opname, opname, i);
2236 else
2237 fprintf_indent (f, indent, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
2238 child_opname, opname, i);
2241 return 0;
2244 /* Generate matching code for the children of the decision tree node. */
2246 void
2247 dt_node::gen_kids (FILE *f, int indent, bool gimple)
2249 auto_vec<dt_operand *> gimple_exprs;
2250 auto_vec<dt_operand *> generic_exprs;
2251 auto_vec<dt_operand *> fns;
2252 auto_vec<dt_operand *> generic_fns;
2253 auto_vec<dt_operand *> preds;
2254 auto_vec<dt_node *> others;
2256 for (unsigned i = 0; i < kids.length (); ++i)
2258 if (kids[i]->type == dt_node::DT_OPERAND)
2260 dt_operand *op = as_a<dt_operand *> (kids[i]);
2261 if (expr *e = dyn_cast <expr *> (op->op))
2263 if (e->ops.length () == 0
2264 && (!gimple || !(*e->operation == CONSTRUCTOR)))
2265 generic_exprs.safe_push (op);
2266 else if (e->operation->kind == id_base::FN)
2268 if (gimple)
2269 fns.safe_push (op);
2270 else
2271 generic_fns.safe_push (op);
2273 else if (e->operation->kind == id_base::PREDICATE)
2274 preds.safe_push (op);
2275 else
2277 if (gimple)
2278 gimple_exprs.safe_push (op);
2279 else
2280 generic_exprs.safe_push (op);
2283 else if (op->op->type == operand::OP_PREDICATE)
2284 others.safe_push (kids[i]);
2285 else
2286 gcc_unreachable ();
2288 else if (kids[i]->type == dt_node::DT_MATCH
2289 || kids[i]->type == dt_node::DT_SIMPLIFY)
2290 others.safe_push (kids[i]);
2291 else if (kids[i]->type == dt_node::DT_TRUE)
2293 /* A DT_TRUE operand serves as a barrier - generate code now
2294 for what we have collected sofar. */
2295 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2296 fns, generic_fns, preds, others);
2297 /* And output the true operand itself. */
2298 kids[i]->gen (f, indent, gimple);
2299 gimple_exprs.truncate (0);
2300 generic_exprs.truncate (0);
2301 fns.truncate (0);
2302 generic_fns.truncate (0);
2303 preds.truncate (0);
2304 others.truncate (0);
2306 else
2307 gcc_unreachable ();
2310 /* Generate code for the remains. */
2311 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2312 fns, generic_fns, preds, others);
2315 /* Generate matching code for the children of the decision tree node. */
2317 void
2318 dt_node::gen_kids_1 (FILE *f, int indent, bool gimple,
2319 vec<dt_operand *> gimple_exprs,
2320 vec<dt_operand *> generic_exprs,
2321 vec<dt_operand *> fns,
2322 vec<dt_operand *> generic_fns,
2323 vec<dt_operand *> preds,
2324 vec<dt_node *> others)
2326 char buf[128];
2327 char *kid_opname = buf;
2329 unsigned exprs_len = gimple_exprs.length ();
2330 unsigned gexprs_len = generic_exprs.length ();
2331 unsigned fns_len = fns.length ();
2332 unsigned gfns_len = generic_fns.length ();
2334 if (exprs_len || fns_len || gexprs_len || gfns_len)
2336 if (exprs_len)
2337 gimple_exprs[0]->get_name (kid_opname);
2338 else if (fns_len)
2339 fns[0]->get_name (kid_opname);
2340 else if (gfns_len)
2341 generic_fns[0]->get_name (kid_opname);
2342 else
2343 generic_exprs[0]->get_name (kid_opname);
2345 fprintf_indent (f, indent, "switch (TREE_CODE (%s))\n", kid_opname);
2346 fprintf_indent (f, indent, " {\n");
2347 indent += 2;
2350 if (exprs_len || fns_len)
2352 fprintf_indent (f, indent,
2353 "case SSA_NAME:\n");
2354 fprintf_indent (f, indent,
2355 " if (do_valueize (valueize, %s) != NULL_TREE)\n",
2356 kid_opname);
2357 fprintf_indent (f, indent,
2358 " {\n");
2359 fprintf_indent (f, indent,
2360 " gimple def_stmt = SSA_NAME_DEF_STMT (%s);\n",
2361 kid_opname);
2363 indent += 6;
2364 if (exprs_len)
2366 fprintf_indent (f, indent,
2367 "if (is_gimple_assign (def_stmt))\n");
2368 fprintf_indent (f, indent,
2369 " switch (gimple_assign_rhs_code (def_stmt))\n");
2370 indent += 4;
2371 fprintf_indent (f, indent, "{\n");
2372 for (unsigned i = 0; i < exprs_len; ++i)
2374 expr *e = as_a <expr *> (gimple_exprs[i]->op);
2375 id_base *op = e->operation;
2376 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2377 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2378 else
2379 fprintf_indent (f, indent, "case %s:\n", op->id);
2380 fprintf_indent (f, indent, " {\n");
2381 gimple_exprs[i]->gen (f, indent + 4, true);
2382 fprintf_indent (f, indent, " break;\n");
2383 fprintf_indent (f, indent, " }\n");
2385 fprintf_indent (f, indent, "default:;\n");
2386 fprintf_indent (f, indent, "}\n");
2387 indent -= 4;
2390 if (fns_len)
2392 if (exprs_len)
2393 fprintf_indent (f, indent, "else ");
2394 else
2395 fprintf_indent (f, indent, " ");
2397 fprintf (f, "if (gimple_call_builtin_p (def_stmt, BUILT_IN_NORMAL))\n");
2398 fprintf_indent (f, indent,
2399 " {\n");
2400 fprintf_indent (f, indent,
2401 " tree fndecl = gimple_call_fndecl (def_stmt);\n");
2402 fprintf_indent (f, indent,
2403 " switch (DECL_FUNCTION_CODE (fndecl))\n");
2404 fprintf_indent (f, indent,
2405 " {\n");
2407 indent += 6;
2408 for (unsigned i = 0; i < fns_len; ++i)
2410 expr *e = as_a <expr *>(fns[i]->op);
2411 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2412 fprintf_indent (f, indent, " {\n");
2413 fns[i]->gen (f, indent + 4, true);
2414 fprintf_indent (f, indent, " break;\n");
2415 fprintf_indent (f, indent, " }\n");
2418 fprintf_indent (f, indent, "default:;\n");
2419 fprintf_indent (f, indent, "}\n");
2420 indent -= 6;
2421 fprintf_indent (f, indent, " }\n");
2424 indent -= 6;
2425 fprintf_indent (f, indent, " }\n");
2426 fprintf_indent (f, indent, " break;\n");
2429 for (unsigned i = 0; i < generic_exprs.length (); ++i)
2431 expr *e = as_a <expr *>(generic_exprs[i]->op);
2432 id_base *op = e->operation;
2433 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2434 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2435 else
2436 fprintf_indent (f, indent, "case %s:\n", op->id);
2437 fprintf_indent (f, indent, " {\n");
2438 generic_exprs[i]->gen (f, indent + 4, gimple);
2439 fprintf_indent (f, indent, " break;\n");
2440 fprintf_indent (f, indent, " }\n");
2443 if (gfns_len)
2445 fprintf_indent (f, indent,
2446 "case CALL_EXPR:\n");
2447 fprintf_indent (f, indent,
2448 " {\n");
2449 fprintf_indent (f, indent,
2450 " tree fndecl = get_callee_fndecl (%s);\n",
2451 kid_opname);
2452 fprintf_indent (f, indent,
2453 " if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)\n");
2454 fprintf_indent (f, indent,
2455 " switch (DECL_FUNCTION_CODE (fndecl))\n");
2456 fprintf_indent (f, indent,
2457 " {\n");
2458 indent += 8;
2460 for (unsigned j = 0; j < generic_fns.length (); ++j)
2462 expr *e = as_a <expr *>(generic_fns[j]->op);
2463 gcc_assert (e->operation->kind == id_base::FN);
2465 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2466 fprintf_indent (f, indent, " {\n");
2467 generic_fns[j]->gen (f, indent + 4, false);
2468 fprintf_indent (f, indent, " break;\n");
2469 fprintf_indent (f, indent, " }\n");
2472 indent -= 8;
2473 fprintf_indent (f, indent, " default:;\n");
2474 fprintf_indent (f, indent, " }\n");
2475 fprintf_indent (f, indent, " break;\n");
2476 fprintf_indent (f, indent, " }\n");
2479 /* Close switch (TREE_CODE ()). */
2480 if (exprs_len || fns_len || gexprs_len || gfns_len)
2482 indent -= 4;
2483 fprintf_indent (f, indent, " default:;\n");
2484 fprintf_indent (f, indent, " }\n");
2487 for (unsigned i = 0; i < preds.length (); ++i)
2489 expr *e = as_a <expr *> (preds[i]->op);
2490 predicate_id *p = as_a <predicate_id *> (e->operation);
2491 preds[i]->get_name (kid_opname);
2492 fprintf_indent (f, indent, "tree %s_pops[%d];\n", kid_opname, p->nargs);
2493 fprintf_indent (f, indent, "if (%s_%s (%s, %s_pops%s))\n",
2494 gimple ? "gimple" : "tree",
2495 p->id, kid_opname, kid_opname,
2496 gimple ? ", valueize" : "");
2497 fprintf_indent (f, indent, " {\n");
2498 for (int j = 0; j < p->nargs; ++j)
2500 char child_opname[20];
2501 preds[i]->gen_opname (child_opname, j);
2502 fprintf_indent (f, indent + 4, "tree %s = %s_pops[%d];\n",
2503 child_opname, kid_opname, j);
2505 preds[i]->gen_kids (f, indent + 4, gimple);
2506 fprintf (f, "}\n");
2509 for (unsigned i = 0; i < others.length (); ++i)
2510 others[i]->gen (f, indent, gimple);
2513 /* Generate matching code for the decision tree operand. */
2515 void
2516 dt_operand::gen (FILE *f, int indent, bool gimple)
2518 char opname[20];
2519 get_name (opname);
2521 unsigned n_braces = 0;
2523 if (type == DT_OPERAND)
2524 switch (op->type)
2526 case operand::OP_PREDICATE:
2527 n_braces = gen_predicate (f, indent, opname, gimple);
2528 break;
2530 case operand::OP_EXPR:
2531 if (gimple)
2532 n_braces = gen_gimple_expr (f, indent);
2533 else
2534 n_braces = gen_generic_expr (f, indent, opname);
2535 break;
2537 default:
2538 gcc_unreachable ();
2540 else if (type == DT_TRUE)
2542 else if (type == DT_MATCH)
2543 n_braces = gen_match_op (f, indent, opname);
2544 else
2545 gcc_unreachable ();
2547 indent += 4 * n_braces;
2548 gen_kids (f, indent, gimple);
2550 for (unsigned i = 0; i < n_braces; ++i)
2552 indent -= 4;
2553 if (indent < 0)
2554 indent = 0;
2555 fprintf_indent (f, indent, " }\n");
2560 /* Generate code for the '(if ...)', '(with ..)' and actual transform
2561 step of a '(simplify ...)' or '(match ...)'. This handles everything
2562 that is not part of the decision tree (simplify->match).
2563 Main recursive worker. */
2565 void
2566 dt_simplify::gen_1 (FILE *f, int indent, bool gimple, operand *result)
2568 if (result)
2570 if (with_expr *w = dyn_cast <with_expr *> (result))
2572 fprintf_indent (f, indent, "{\n");
2573 indent += 4;
2574 output_line_directive (f, w->with->code[0].src_loc);
2575 w->with->gen_transform (f, indent, NULL, true, 1, "type", NULL);
2576 gen_1 (f, indent, gimple, w->subexpr);
2577 indent -= 4;
2578 fprintf_indent (f, indent, "}\n");
2579 return;
2581 else if (if_expr *ife = dyn_cast <if_expr *> (result))
2583 output_line_directive (f, ife->cond->code[0].src_loc);
2584 fprintf_indent (f, indent, "if (");
2585 ife->cond->gen_transform (f, indent, NULL, true, 1, "type", NULL);
2586 fprintf (f, ")\n");
2587 fprintf_indent (f, indent + 2, "{\n");
2588 indent += 4;
2589 gen_1 (f, indent, gimple, ife->trueexpr);
2590 indent -= 4;
2591 fprintf_indent (f, indent + 2, "}\n");
2592 if (ife->falseexpr)
2594 fprintf_indent (f, indent, "else\n");
2595 fprintf_indent (f, indent + 2, "{\n");
2596 indent += 4;
2597 gen_1 (f, indent, gimple, ife->falseexpr);
2598 indent -= 4;
2599 fprintf_indent (f, indent + 2, "}\n");
2601 return;
2605 /* Analyze captures and perform early-outs on the incoming arguments
2606 that cover cases we cannot handle. */
2607 capture_info cinfo (s, result);
2608 if (s->kind == simplify::SIMPLIFY)
2610 if (!gimple)
2612 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
2613 if (cinfo.force_no_side_effects & (1 << i))
2614 fprintf_indent (f, indent,
2615 "if (TREE_SIDE_EFFECTS (op%d)) return NULL_TREE;\n",
2617 for (int i = 0; i <= s->capture_max; ++i)
2618 if (cinfo.info[i].cse_p)
2620 else if (cinfo.info[i].force_no_side_effects_p
2621 && (cinfo.info[i].toplevel_msk
2622 & cinfo.force_no_side_effects) == 0)
2623 fprintf_indent (f, indent,
2624 "if (TREE_SIDE_EFFECTS (captures[%d])) "
2625 "return NULL_TREE;\n", i);
2626 else if ((cinfo.info[i].toplevel_msk
2627 & cinfo.force_no_side_effects) != 0)
2628 /* Mark capture as having no side-effects if we had to verify
2629 that via forced toplevel operand checks. */
2630 cinfo.info[i].force_no_side_effects_p = true;
2632 if (gimple)
2634 /* Force single-use restriction by only allowing simple
2635 results via setting seq to NULL. */
2636 fprintf_indent (f, indent, "gimple_seq *lseq = seq;\n");
2637 bool first_p = true;
2638 for (int i = 0; i <= s->capture_max; ++i)
2639 if (cinfo.info[i].force_single_use)
2641 if (first_p)
2643 fprintf_indent (f, indent, "if (lseq\n");
2644 fprintf_indent (f, indent, " && (");
2645 first_p = false;
2647 else
2649 fprintf (f, "\n");
2650 fprintf_indent (f, indent, " || ");
2652 fprintf (f, "!single_use (captures[%d])", i);
2654 if (!first_p)
2656 fprintf (f, "))\n");
2657 fprintf_indent (f, indent, " lseq = NULL;\n");
2662 fprintf_indent (f, indent, "if (dump_file && (dump_flags & TDF_DETAILS)) "
2663 "fprintf (dump_file, \"Applying pattern ");
2664 output_line_directive (f, s->result_location, true);
2665 fprintf (f, ", %%s:%%d\\n\", __FILE__, __LINE__);\n");
2667 if (!result)
2669 /* If there is no result then this is a predicate implementation. */
2670 fprintf_indent (f, indent, "return true;\n");
2672 else if (gimple)
2674 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
2675 in outermost position). */
2676 if (result->type == operand::OP_EXPR
2677 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
2678 result = as_a <expr *> (result)->ops[0];
2679 if (result->type == operand::OP_EXPR)
2681 expr *e = as_a <expr *> (result);
2682 bool is_predicate = is_a <predicate_id *> (e->operation);
2683 if (!is_predicate)
2684 fprintf_indent (f, indent, "*res_code = %s;\n",
2685 *e->operation == CONVERT_EXPR
2686 ? "NOP_EXPR" : e->operation->id);
2687 for (unsigned j = 0; j < e->ops.length (); ++j)
2689 char dest[32];
2690 snprintf (dest, 32, "res_ops[%d]", j);
2691 const char *optype
2692 = get_operand_type (e->operation,
2693 "type", e->expr_type,
2694 j == 0 ? NULL : "TREE_TYPE (res_ops[0])");
2695 /* We need to expand GENERIC conditions we captured from
2696 COND_EXPRs. */
2697 bool expand_generic_cond_exprs_p
2698 = (!is_predicate
2699 /* But avoid doing that if the GENERIC condition is
2700 valid - which it is in the first operand of COND_EXPRs
2701 and VEC_COND_EXRPs. */
2702 && ((!(*e->operation == COND_EXPR)
2703 && !(*e->operation == VEC_COND_EXPR))
2704 || j != 0));
2705 e->ops[j]->gen_transform (f, indent, dest, true, 1, optype,
2706 &cinfo,
2707 indexes, expand_generic_cond_exprs_p);
2710 /* Re-fold the toplevel result. It's basically an embedded
2711 gimple_build w/o actually building the stmt. */
2712 if (!is_predicate)
2713 fprintf_indent (f, indent,
2714 "gimple_resimplify%d (lseq, res_code, type, "
2715 "res_ops, valueize);\n", e->ops.length ());
2717 else if (result->type == operand::OP_CAPTURE
2718 || result->type == operand::OP_C_EXPR)
2720 result->gen_transform (f, indent, "res_ops[0]", true, 1, "type",
2721 &cinfo, indexes, false);
2722 fprintf_indent (f, indent, "*res_code = TREE_CODE (res_ops[0]);\n");
2723 if (is_a <capture *> (result)
2724 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
2726 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2727 with substituting a capture of that. */
2728 fprintf_indent (f, indent,
2729 "if (COMPARISON_CLASS_P (res_ops[0]))\n");
2730 fprintf_indent (f, indent,
2731 " {\n");
2732 fprintf_indent (f, indent,
2733 " tree tem = res_ops[0];\n");
2734 fprintf_indent (f, indent,
2735 " res_ops[0] = TREE_OPERAND (tem, 0);\n");
2736 fprintf_indent (f, indent,
2737 " res_ops[1] = TREE_OPERAND (tem, 1);\n");
2738 fprintf_indent (f, indent,
2739 " }\n");
2742 else
2743 gcc_unreachable ();
2744 fprintf_indent (f, indent, "return true;\n");
2746 else /* GENERIC */
2748 bool is_predicate = false;
2749 if (result->type == operand::OP_EXPR)
2751 expr *e = as_a <expr *> (result);
2752 is_predicate = is_a <predicate_id *> (e->operation);
2753 /* Search for captures used multiple times in the result expression
2754 and dependent on TREE_SIDE_EFFECTS emit a SAVE_EXPR. */
2755 if (!is_predicate)
2756 for (int i = 0; i < s->capture_max + 1; ++i)
2758 if (!cinfo.info[i].force_no_side_effects_p
2759 && cinfo.info[i].result_use_count > 1)
2761 fprintf_indent (f, indent,
2762 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
2764 fprintf_indent (f, indent,
2765 " captures[%d] = save_expr (captures[%d]);\n",
2766 i, i);
2769 for (unsigned j = 0; j < e->ops.length (); ++j)
2771 char dest[32];
2772 if (is_predicate)
2773 snprintf (dest, 32, "res_ops[%d]", j);
2774 else
2776 fprintf_indent (f, indent, "tree res_op%d;\n", j);
2777 snprintf (dest, 32, "res_op%d", j);
2779 const char *optype
2780 = get_operand_type (e->operation,
2781 "type", e->expr_type,
2782 j == 0
2783 ? NULL : "TREE_TYPE (res_op0)");
2784 e->ops[j]->gen_transform (f, indent, dest, false, 1, optype,
2785 &cinfo, indexes);
2787 if (is_predicate)
2788 fprintf_indent (f, indent, "return true;\n");
2789 else
2791 fprintf_indent (f, indent, "tree res;\n");
2792 /* Re-fold the toplevel result. Use non_lvalue to
2793 build NON_LVALUE_EXPRs so they get properly
2794 ignored when in GIMPLE form. */
2795 if (*e->operation == NON_LVALUE_EXPR)
2796 fprintf_indent (f, indent,
2797 "res = non_lvalue_loc (loc, res_op0);\n");
2798 else
2800 if (e->operation->kind == id_base::CODE)
2801 fprintf_indent (f, indent,
2802 "res = fold_build%d_loc (loc, %s, type",
2803 e->ops.length (),
2804 *e->operation == CONVERT_EXPR
2805 ? "NOP_EXPR" : e->operation->id);
2806 else
2807 fprintf_indent (f, indent,
2808 "res = build_call_expr_loc "
2809 "(loc, builtin_decl_implicit (%s), %d",
2810 e->operation->id, e->ops.length());
2811 for (unsigned j = 0; j < e->ops.length (); ++j)
2812 fprintf (f, ", res_op%d", j);
2813 fprintf (f, ");\n");
2817 else if (result->type == operand::OP_CAPTURE
2818 || result->type == operand::OP_C_EXPR)
2821 fprintf_indent (f, indent, "tree res;\n");
2822 result->gen_transform (f, indent, "res", false, 1, "type",
2823 &cinfo, indexes);
2825 else
2826 gcc_unreachable ();
2827 if (!is_predicate)
2829 /* Search for captures not used in the result expression and dependent
2830 on TREE_SIDE_EFFECTS emit omit_one_operand. */
2831 for (int i = 0; i < s->capture_max + 1; ++i)
2833 if (!cinfo.info[i].force_no_side_effects_p
2834 && !cinfo.info[i].expr_p
2835 && cinfo.info[i].result_use_count == 0)
2837 fprintf_indent (f, indent,
2838 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
2840 fprintf_indent (f, indent + 2,
2841 "res = build2_loc (loc, COMPOUND_EXPR, type, "
2842 "fold_ignored_result (captures[%d]), res);\n",
2846 fprintf_indent (f, indent, "return res;\n");
2851 /* Generate code for the '(if ...)', '(with ..)' and actual transform
2852 step of a '(simplify ...)' or '(match ...)'. This handles everything
2853 that is not part of the decision tree (simplify->match). */
2855 void
2856 dt_simplify::gen (FILE *f, int indent, bool gimple)
2858 fprintf_indent (f, indent, "{\n");
2859 indent += 2;
2860 output_line_directive (f, s->result_location);
2861 if (s->capture_max >= 0)
2862 fprintf_indent (f, indent, "tree captures[%u] ATTRIBUTE_UNUSED = {};\n",
2863 s->capture_max + 1);
2865 for (int i = 0; i <= s->capture_max; ++i)
2866 if (indexes[i])
2868 char opname[20];
2869 fprintf_indent (f, indent, "captures[%u] = %s;\n",
2870 i, indexes[i]->get_name (opname));
2873 gen_1 (f, indent, gimple, s->result);
2875 indent -= 2;
2876 fprintf_indent (f, indent, "}\n");
2879 /* Main entry to generate code for matching GIMPLE IL off the decision
2880 tree. */
2882 void
2883 decision_tree::gen_gimple (FILE *f)
2885 for (unsigned n = 1; n <= 3; ++n)
2887 fprintf (f, "\nstatic bool\n"
2888 "gimple_simplify (code_helper *res_code, tree *res_ops,\n"
2889 " gimple_seq *seq, tree (*valueize)(tree),\n"
2890 " code_helper code, tree type");
2891 for (unsigned i = 0; i < n; ++i)
2892 fprintf (f, ", tree op%d", i);
2893 fprintf (f, ")\n");
2894 fprintf (f, "{\n");
2896 fprintf (f, " switch (code.get_rep())\n"
2897 " {\n");
2898 for (unsigned i = 0; i < root->kids.length (); i++)
2900 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
2901 expr *e = static_cast<expr *>(dop->op);
2902 if (e->ops.length () != n)
2903 continue;
2905 if (*e->operation == CONVERT_EXPR
2906 || *e->operation == NOP_EXPR)
2907 fprintf (f, " CASE_CONVERT:\n");
2908 else
2909 fprintf (f, " case %s%s:\n",
2910 is_a <fn_id *> (e->operation) ? "-" : "",
2911 e->operation->id);
2912 fprintf (f, " {\n");
2913 dop->gen_kids (f, 8, true);
2914 fprintf (f, " break;\n");
2915 fprintf (f, " }\n");
2917 fprintf (f, " default:;\n"
2918 " }\n");
2920 fprintf (f, " return false;\n");
2921 fprintf (f, "}\n");
2925 /* Main entry to generate code for matching GENERIC IL off the decision
2926 tree. */
2928 void
2929 decision_tree::gen_generic (FILE *f)
2931 for (unsigned n = 1; n <= 3; ++n)
2933 fprintf (f, "\ntree\n"
2934 "generic_simplify (location_t loc, enum tree_code code, "
2935 "tree type ATTRIBUTE_UNUSED");
2936 for (unsigned i = 0; i < n; ++i)
2937 fprintf (f, ", tree op%d", i);
2938 fprintf (f, ")\n");
2939 fprintf (f, "{\n");
2941 fprintf (f, " switch (code)\n"
2942 " {\n");
2943 for (unsigned i = 0; i < root->kids.length (); i++)
2945 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
2946 expr *e = static_cast<expr *>(dop->op);
2947 if (e->ops.length () != n
2948 /* Builtin simplifications are somewhat premature on
2949 GENERIC. The following drops patterns with outermost
2950 calls. It's easy to emit overloads for function code
2951 though if necessary. */
2952 || e->operation->kind != id_base::CODE)
2953 continue;
2955 operator_id *op_id = static_cast <operator_id *> (e->operation);
2956 if (op_id->code == NOP_EXPR || op_id->code == CONVERT_EXPR)
2957 fprintf (f, " CASE_CONVERT:\n");
2958 else
2959 fprintf (f, " case %s:\n", e->operation->id);
2960 fprintf (f, " {\n");
2961 dop->gen_kids (f, 8, false);
2962 fprintf (f, " break;\n"
2963 " }\n");
2965 fprintf (f, " default:;\n"
2966 " }\n");
2968 fprintf (f, " return NULL_TREE;\n");
2969 fprintf (f, "}\n");
2973 /* Output code to implement the predicate P from the decision tree DT. */
2975 void
2976 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
2978 fprintf (f, "\nbool\n"
2979 "%s%s (tree t%s%s)\n"
2980 "{\n", gimple ? "gimple_" : "tree_", p->id,
2981 p->nargs > 0 ? ", tree *res_ops" : "",
2982 gimple ? ", tree (*valueize)(tree)" : "");
2983 /* Conveniently make 'type' available. */
2984 fprintf_indent (f, 2, "tree type = TREE_TYPE (t);\n");
2986 if (!gimple)
2987 fprintf_indent (f, 2, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
2988 dt.root->gen_kids (f, 2, gimple);
2990 fprintf_indent (f, 2, "return false;\n"
2991 "}\n");
2994 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
2996 static void
2997 write_header (FILE *f, const char *head)
2999 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
3000 fprintf (f, " a IL pattern matching and simplification description. */\n");
3002 /* Include the header instead of writing it awkwardly quoted here. */
3003 fprintf (f, "\n#include \"%s\"\n", head);
3008 /* AST parsing. */
3010 class parser
3012 public:
3013 parser (cpp_reader *);
3015 private:
3016 const cpp_token *next ();
3017 const cpp_token *peek (unsigned = 1);
3018 const cpp_token *peek_ident (const char * = NULL, unsigned = 1);
3019 const cpp_token *expect (enum cpp_ttype);
3020 const cpp_token *eat_token (enum cpp_ttype);
3021 const char *get_string ();
3022 const char *get_ident ();
3023 const cpp_token *eat_ident (const char *);
3024 const char *get_number ();
3026 id_base *parse_operation ();
3027 operand *parse_capture (operand *);
3028 operand *parse_expr ();
3029 c_expr *parse_c_expr (cpp_ttype);
3030 operand *parse_op ();
3032 void record_operlist (source_location, user_id *);
3034 void parse_pattern ();
3035 operand *parse_result (operand *, predicate_id *);
3036 void push_simplify (simplify::simplify_kind,
3037 vec<simplify *>&, operand *, source_location,
3038 operand *, source_location);
3039 void parse_simplify (simplify::simplify_kind,
3040 source_location, vec<simplify *>&, predicate_id *,
3041 operand *);
3042 void parse_for (source_location);
3043 void parse_if (source_location);
3044 void parse_predicates (source_location);
3045 void parse_operator_list (source_location);
3047 cpp_reader *r;
3048 vec<c_expr *> active_ifs;
3049 vec<vec<user_id *> > active_fors;
3050 hash_set<user_id *> *oper_lists_set;
3051 vec<user_id *> oper_lists;
3053 cid_map_t *capture_ids;
3055 public:
3056 vec<simplify *> simplifiers;
3057 vec<predicate_id *> user_predicates;
3058 bool parsing_match_operand;
3061 /* Lexing helpers. */
3063 /* Read the next non-whitespace token from R. */
3065 const cpp_token *
3066 parser::next ()
3068 const cpp_token *token;
3071 token = cpp_get_token (r);
3073 while (token->type == CPP_PADDING
3074 && token->type != CPP_EOF);
3075 return token;
3078 /* Peek at the next non-whitespace token from R. */
3080 const cpp_token *
3081 parser::peek (unsigned num)
3083 const cpp_token *token;
3084 unsigned i = 0;
3087 token = cpp_peek_token (r, i++);
3089 while ((token->type == CPP_PADDING
3090 && token->type != CPP_EOF)
3091 || (--num > 0));
3092 /* If we peek at EOF this is a fatal error as it leaves the
3093 cpp_reader in unusable state. Assume we really wanted a
3094 token and thus this EOF is unexpected. */
3095 if (token->type == CPP_EOF)
3096 fatal_at (token, "unexpected end of file");
3097 return token;
3100 /* Peek at the next identifier token (or return NULL if the next
3101 token is not an identifier or equal to ID if supplied). */
3103 const cpp_token *
3104 parser::peek_ident (const char *id, unsigned num)
3106 const cpp_token *token = peek (num);
3107 if (token->type != CPP_NAME)
3108 return 0;
3110 if (id == 0)
3111 return token;
3113 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
3114 if (strcmp (id, t) == 0)
3115 return token;
3117 return 0;
3120 /* Read the next token from R and assert it is of type TK. */
3122 const cpp_token *
3123 parser::expect (enum cpp_ttype tk)
3125 const cpp_token *token = next ();
3126 if (token->type != tk)
3127 fatal_at (token, "expected %s, got %s",
3128 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
3130 return token;
3133 /* Consume the next token from R and assert it is of type TK. */
3135 const cpp_token *
3136 parser::eat_token (enum cpp_ttype tk)
3138 return expect (tk);
3141 /* Read the next token from R and assert it is of type CPP_STRING and
3142 return its value. */
3144 const char *
3145 parser::get_string ()
3147 const cpp_token *token = expect (CPP_STRING);
3148 return (const char *)token->val.str.text;
3151 /* Read the next token from R and assert it is of type CPP_NAME and
3152 return its value. */
3154 const char *
3155 parser::get_ident ()
3157 const cpp_token *token = expect (CPP_NAME);
3158 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
3161 /* Eat an identifier token with value S from R. */
3163 const cpp_token *
3164 parser::eat_ident (const char *s)
3166 const cpp_token *token = peek ();
3167 const char *t = get_ident ();
3168 if (strcmp (s, t) != 0)
3169 fatal_at (token, "expected '%s' got '%s'\n", s, t);
3170 return token;
3173 /* Read the next token from R and assert it is of type CPP_NUMBER and
3174 return its value. */
3176 const char *
3177 parser::get_number ()
3179 const cpp_token *token = expect (CPP_NUMBER);
3180 return (const char *)token->val.str.text;
3184 /* Record an operator-list use for transparent for handling. */
3186 void
3187 parser::record_operlist (source_location loc, user_id *p)
3189 if (!oper_lists_set->add (p))
3191 if (!oper_lists.is_empty ()
3192 && oper_lists[0]->substitutes.length () != p->substitutes.length ())
3193 fatal_at (loc, "User-defined operator list does not have the "
3194 "same number of entries as others used in the pattern");
3195 oper_lists.safe_push (p);
3199 /* Parse the operator ID, special-casing convert?, convert1? and
3200 convert2? */
3202 id_base *
3203 parser::parse_operation ()
3205 const cpp_token *id_tok = peek ();
3206 const char *id = get_ident ();
3207 const cpp_token *token = peek ();
3208 if (strcmp (id, "convert0") == 0)
3209 fatal_at (id_tok, "use 'convert?' here");
3210 else if (strcmp (id, "view_convert0") == 0)
3211 fatal_at (id_tok, "use 'view_convert?' here");
3212 if (token->type == CPP_QUERY
3213 && !(token->flags & PREV_WHITE))
3215 if (strcmp (id, "convert") == 0)
3216 id = "convert0";
3217 else if (strcmp (id, "convert1") == 0)
3219 else if (strcmp (id, "convert2") == 0)
3221 else if (strcmp (id, "view_convert") == 0)
3222 id = "view_convert0";
3223 else if (strcmp (id, "view_convert1") == 0)
3225 else if (strcmp (id, "view_convert2") == 0)
3227 else
3228 fatal_at (id_tok, "non-convert operator conditionalized");
3230 if (!parsing_match_operand)
3231 fatal_at (id_tok, "conditional convert can only be used in "
3232 "match expression");
3233 eat_token (CPP_QUERY);
3235 else if (strcmp (id, "convert1") == 0
3236 || strcmp (id, "convert2") == 0
3237 || strcmp (id, "view_convert1") == 0
3238 || strcmp (id, "view_convert2") == 0)
3239 fatal_at (id_tok, "expected '?' after conditional operator");
3240 id_base *op = get_operator (id);
3241 if (!op)
3242 fatal_at (id_tok, "unknown operator %s", id);
3244 user_id *p = dyn_cast<user_id *> (op);
3245 if (p && p->is_oper_list)
3247 if (active_fors.length() == 0)
3248 record_operlist (id_tok->src_loc, p);
3249 else
3250 fatal_at (id_tok, "operator-list %s cannot be exapnded inside 'for'", id);
3252 return op;
3255 /* Parse a capture.
3256 capture = '@'<number> */
3258 struct operand *
3259 parser::parse_capture (operand *op)
3261 eat_token (CPP_ATSIGN);
3262 const cpp_token *token = peek ();
3263 const char *id = NULL;
3264 if (token->type == CPP_NUMBER)
3265 id = get_number ();
3266 else if (token->type == CPP_NAME)
3267 id = get_ident ();
3268 else
3269 fatal_at (token, "expected number or identifier");
3270 unsigned next_id = capture_ids->elements ();
3271 bool existed;
3272 unsigned &num = capture_ids->get_or_insert (id, &existed);
3273 if (!existed)
3274 num = next_id;
3275 return new capture (num, op);
3278 /* Parse an expression
3279 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
3281 struct operand *
3282 parser::parse_expr ()
3284 expr *e = new expr (parse_operation ());
3285 const cpp_token *token = peek ();
3286 operand *op;
3287 bool is_commutative = false;
3288 bool force_capture = false;
3289 const char *expr_type = NULL;
3291 if (token->type == CPP_COLON
3292 && !(token->flags & PREV_WHITE))
3294 eat_token (CPP_COLON);
3295 token = peek ();
3296 if (token->type == CPP_NAME
3297 && !(token->flags & PREV_WHITE))
3299 const char *s = get_ident ();
3300 if (!parsing_match_operand)
3301 expr_type = s;
3302 else
3304 const char *sp = s;
3305 while (*sp)
3307 if (*sp == 'c')
3308 is_commutative = true;
3309 else if (*sp == 's')
3311 e->force_single_use = true;
3312 force_capture = true;
3314 else
3315 fatal_at (token, "flag %c not recognized", *sp);
3316 sp++;
3319 token = peek ();
3321 else
3322 fatal_at (token, "expected flag or type specifying identifier");
3325 if (token->type == CPP_ATSIGN
3326 && !(token->flags & PREV_WHITE))
3327 op = parse_capture (e);
3328 else if (force_capture)
3330 unsigned num = capture_ids->elements ();
3331 char id[8];
3332 bool existed;
3333 sprintf (id, "__%u", num);
3334 capture_ids->get_or_insert (xstrdup (id), &existed);
3335 if (existed)
3336 fatal_at (token, "reserved capture id '%s' already used", id);
3337 op = new capture (num, e);
3339 else
3340 op = e;
3343 const cpp_token *token = peek ();
3344 if (token->type == CPP_CLOSE_PAREN)
3346 if (e->operation->nargs != -1
3347 && e->operation->nargs != (int) e->ops.length ())
3348 fatal_at (token, "'%s' expects %u operands, not %u",
3349 e->operation->id, e->operation->nargs, e->ops.length ());
3350 if (is_commutative)
3352 if (e->ops.length () == 2)
3353 e->is_commutative = true;
3354 else
3355 fatal_at (token, "only binary operators or function with "
3356 "two arguments can be marked commutative");
3358 e->expr_type = expr_type;
3359 return op;
3361 e->append_op (parse_op ());
3363 while (1);
3366 /* Lex native C code delimited by START recording the preprocessing tokens
3367 for later processing.
3368 c_expr = ('{'|'(') <pp token>... ('}'|')') */
3370 c_expr *
3371 parser::parse_c_expr (cpp_ttype start)
3373 const cpp_token *token;
3374 cpp_ttype end;
3375 unsigned opencnt;
3376 vec<cpp_token> code = vNULL;
3377 unsigned nr_stmts = 0;
3378 eat_token (start);
3379 if (start == CPP_OPEN_PAREN)
3380 end = CPP_CLOSE_PAREN;
3381 else if (start == CPP_OPEN_BRACE)
3382 end = CPP_CLOSE_BRACE;
3383 else
3384 gcc_unreachable ();
3385 opencnt = 1;
3388 token = next ();
3390 /* Count brace pairs to find the end of the expr to match. */
3391 if (token->type == start)
3392 opencnt++;
3393 else if (token->type == end
3394 && --opencnt == 0)
3395 break;
3397 /* This is a lame way of counting the number of statements. */
3398 if (token->type == CPP_SEMICOLON)
3399 nr_stmts++;
3401 /* If this is possibly a user-defined identifier mark it used. */
3402 if (token->type == CPP_NAME)
3404 id_base *idb = get_operator ((const char *)CPP_HASHNODE
3405 (token->val.node.node)->ident.str);
3406 user_id *p;
3407 if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
3408 record_operlist (token->src_loc, p);
3411 /* Record the token. */
3412 code.safe_push (*token);
3414 while (1);
3415 return new c_expr (r, code, nr_stmts, vNULL, capture_ids);
3418 /* Parse an operand which is either an expression, a predicate or
3419 a standalone capture.
3420 op = predicate | expr | c_expr | capture */
3422 struct operand *
3423 parser::parse_op ()
3425 const cpp_token *token = peek ();
3426 struct operand *op = NULL;
3427 if (token->type == CPP_OPEN_PAREN)
3429 eat_token (CPP_OPEN_PAREN);
3430 op = parse_expr ();
3431 eat_token (CPP_CLOSE_PAREN);
3433 else if (token->type == CPP_OPEN_BRACE)
3435 op = parse_c_expr (CPP_OPEN_BRACE);
3437 else
3439 /* Remaining ops are either empty or predicates */
3440 if (token->type == CPP_NAME)
3442 const char *id = get_ident ();
3443 id_base *opr = get_operator (id);
3444 if (!opr)
3445 fatal_at (token, "expected predicate name");
3446 if (operator_id *code = dyn_cast <operator_id *> (opr))
3448 if (code->nargs != 0)
3449 fatal_at (token, "using an operator with operands as predicate");
3450 /* Parse the zero-operand operator "predicates" as
3451 expression. */
3452 op = new expr (opr);
3454 else if (user_id *code = dyn_cast <user_id *> (opr))
3456 if (code->nargs != 0)
3457 fatal_at (token, "using an operator with operands as predicate");
3458 /* Parse the zero-operand operator "predicates" as
3459 expression. */
3460 op = new expr (opr);
3462 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
3463 op = new predicate (p);
3464 else
3465 fatal_at (token, "using an unsupported operator as predicate");
3466 if (!parsing_match_operand)
3467 fatal_at (token, "predicates are only allowed in match expression");
3468 token = peek ();
3469 if (token->flags & PREV_WHITE)
3470 return op;
3472 else if (token->type != CPP_COLON
3473 && token->type != CPP_ATSIGN)
3474 fatal_at (token, "expected expression or predicate");
3475 /* optionally followed by a capture and a predicate. */
3476 if (token->type == CPP_COLON)
3477 fatal_at (token, "not implemented: predicate on leaf operand");
3478 if (token->type == CPP_ATSIGN)
3479 op = parse_capture (op);
3482 return op;
3485 /* Create a new simplify from the current parsing state and MATCH,
3486 MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS. */
3488 void
3489 parser::push_simplify (simplify::simplify_kind kind,
3490 vec<simplify *>& simplifiers,
3491 operand *match, source_location match_loc,
3492 operand *result, source_location result_loc)
3494 /* Build and push a temporary for operator list uses in expressions. */
3495 if (!oper_lists.is_empty ())
3496 active_fors.safe_push (oper_lists);
3498 simplifiers.safe_push
3499 (new simplify (kind, match, match_loc, result, result_loc,
3500 active_fors.copy (), capture_ids));
3502 if (!oper_lists.is_empty ())
3503 active_fors.pop ();
3506 /* Parse
3507 <result-op> = <op> | <if> | <with>
3508 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
3509 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
3510 and return it. */
3512 operand *
3513 parser::parse_result (operand *result, predicate_id *matcher)
3515 const cpp_token *token = peek ();
3516 if (token->type != CPP_OPEN_PAREN)
3517 return parse_op ();
3519 eat_token (CPP_OPEN_PAREN);
3520 if (peek_ident ("if"))
3522 eat_ident ("if");
3523 if_expr *ife = new if_expr ();
3524 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
3525 if (peek ()->type == CPP_OPEN_PAREN)
3527 ife->trueexpr = parse_result (result, matcher);
3528 if (peek ()->type == CPP_OPEN_PAREN)
3529 ife->falseexpr = parse_result (result, matcher);
3530 else if (peek ()->type != CPP_CLOSE_PAREN)
3531 ife->falseexpr = parse_op ();
3533 else if (peek ()->type != CPP_CLOSE_PAREN)
3535 ife->trueexpr = parse_op ();
3536 if (peek ()->type == CPP_OPEN_PAREN)
3537 ife->falseexpr = parse_result (result, matcher);
3538 else if (peek ()->type != CPP_CLOSE_PAREN)
3539 ife->falseexpr = parse_op ();
3541 /* If this if is immediately closed then it contains a
3542 manual matcher or is part of a predicate definition. */
3543 else /* if (peek ()->type == CPP_CLOSE_PAREN) */
3545 if (!matcher)
3546 fatal_at (peek (), "manual transform not implemented");
3548 eat_token (CPP_CLOSE_PAREN);
3549 return ife;
3551 else if (peek_ident ("with"))
3553 eat_ident ("with");
3554 with_expr *withe = new with_expr ();
3555 /* Parse (with c-expr expr) as (if-with (true) expr). */
3556 withe->with = parse_c_expr (CPP_OPEN_BRACE);
3557 withe->with->nr_stmts = 0;
3558 withe->subexpr = parse_result (result, matcher);
3559 eat_token (CPP_CLOSE_PAREN);
3560 return withe;
3562 else if (peek_ident ("switch"))
3564 token = eat_ident ("switch");
3565 eat_token (CPP_OPEN_PAREN);
3566 eat_ident ("if");
3567 if_expr *ife = new if_expr ();
3568 operand *res = ife;
3569 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
3570 if (peek ()->type == CPP_OPEN_PAREN)
3571 ife->trueexpr = parse_result (result, matcher);
3572 else
3573 ife->trueexpr = parse_op ();
3574 eat_token (CPP_CLOSE_PAREN);
3575 if (peek ()->type != CPP_OPEN_PAREN
3576 || !peek_ident ("if", 2))
3577 fatal_at (token, "switch can be implemented with a single if");
3578 while (peek ()->type != CPP_CLOSE_PAREN)
3580 if (peek ()->type == CPP_OPEN_PAREN)
3582 if (peek_ident ("if", 2))
3584 eat_token (CPP_OPEN_PAREN);
3585 eat_ident ("if");
3586 ife->falseexpr = new if_expr ();
3587 ife = as_a <if_expr *> (ife->falseexpr);
3588 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
3589 if (peek ()->type == CPP_OPEN_PAREN)
3590 ife->trueexpr = parse_result (result, matcher);
3591 else
3592 ife->trueexpr = parse_op ();
3593 eat_token (CPP_CLOSE_PAREN);
3595 else
3597 /* switch default clause */
3598 ife->falseexpr = parse_result (result, matcher);
3599 eat_token (CPP_CLOSE_PAREN);
3600 return res;
3603 else
3605 /* switch default clause */
3606 ife->falseexpr = parse_op ();
3607 eat_token (CPP_CLOSE_PAREN);
3608 return res;
3611 eat_token (CPP_CLOSE_PAREN);
3612 return res;
3614 else
3616 operand *op = result;
3617 if (!matcher)
3618 op = parse_expr ();
3619 eat_token (CPP_CLOSE_PAREN);
3620 return op;
3624 /* Parse
3625 simplify = 'simplify' <expr> <result-op>
3627 match = 'match' <ident> <expr> [<result-op>]
3628 and fill SIMPLIFIERS with the results. */
3630 void
3631 parser::parse_simplify (simplify::simplify_kind kind,
3632 source_location match_location,
3633 vec<simplify *>& simplifiers, predicate_id *matcher,
3634 operand *result)
3636 /* Reset the capture map. */
3637 if (!capture_ids)
3638 capture_ids = new cid_map_t;
3639 /* Reset oper_lists and set. */
3640 hash_set <user_id *> olist;
3641 oper_lists_set = &olist;
3642 oper_lists = vNULL;
3644 const cpp_token *loc = peek ();
3645 parsing_match_operand = true;
3646 struct operand *match = parse_op ();
3647 parsing_match_operand = false;
3648 if (match->type == operand::OP_CAPTURE && !matcher)
3649 fatal_at (loc, "outermost expression cannot be captured");
3650 if (match->type == operand::OP_EXPR
3651 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
3652 fatal_at (loc, "outermost expression cannot be a predicate");
3654 /* Splice active_ifs onto result and continue parsing the
3655 "then" expr. */
3656 if_expr *active_if = NULL;
3657 for (int i = active_ifs.length (); i > 0; --i)
3659 if_expr *ifc = new if_expr ();
3660 ifc->cond = active_ifs[i-1];
3661 ifc->trueexpr = active_if;
3662 active_if = ifc;
3664 if_expr *outermost_if = active_if;
3665 while (active_if && active_if->trueexpr)
3666 active_if = as_a <if_expr *> (active_if->trueexpr);
3668 const cpp_token *token = peek ();
3670 /* If this if is immediately closed then it is part of a predicate
3671 definition. Push it. */
3672 if (token->type == CPP_CLOSE_PAREN)
3674 if (!matcher)
3675 fatal_at (token, "expected transform expression");
3676 if (active_if)
3678 active_if->trueexpr = result;
3679 result = outermost_if;
3681 push_simplify (kind, simplifiers, match, match_location,
3682 result, token->src_loc);
3683 return;
3686 operand *tem = parse_result (result, matcher);
3687 if (active_if)
3689 active_if->trueexpr = tem;
3690 result = outermost_if;
3692 else
3693 result = tem;
3695 push_simplify (kind, simplifiers, match, match_location,
3696 result, token->src_loc);
3699 /* Parsing of the outer control structures. */
3701 /* Parse a for expression
3702 for = '(' 'for' <subst>... <pattern> ')'
3703 subst = <ident> '(' <ident>... ')' */
3705 void
3706 parser::parse_for (source_location)
3708 auto_vec<const cpp_token *> user_id_tokens;
3709 vec<user_id *> user_ids = vNULL;
3710 const cpp_token *token;
3711 unsigned min_n_opers = 0, max_n_opers = 0;
3713 while (1)
3715 token = peek ();
3716 if (token->type != CPP_NAME)
3717 break;
3719 /* Insert the user defined operators into the operator hash. */
3720 const char *id = get_ident ();
3721 if (get_operator (id) != NULL)
3722 fatal_at (token, "operator already defined");
3723 user_id *op = new user_id (id);
3724 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
3725 *slot = op;
3726 user_ids.safe_push (op);
3727 user_id_tokens.safe_push (token);
3729 eat_token (CPP_OPEN_PAREN);
3731 int arity = -1;
3732 while ((token = peek_ident ()) != 0)
3734 const char *oper = get_ident ();
3735 id_base *idb = get_operator (oper);
3736 if (idb == NULL)
3737 fatal_at (token, "no such operator '%s'", oper);
3738 if (*idb == CONVERT0 || *idb == CONVERT1 || *idb == CONVERT2
3739 || *idb == VIEW_CONVERT0 || *idb == VIEW_CONVERT1
3740 || *idb == VIEW_CONVERT2)
3741 fatal_at (token, "conditional operators cannot be used inside for");
3743 if (arity == -1)
3744 arity = idb->nargs;
3745 else if (idb->nargs == -1)
3747 else if (idb->nargs != arity)
3748 fatal_at (token, "operator '%s' with arity %d does not match "
3749 "others with arity %d", oper, idb->nargs, arity);
3751 user_id *p = dyn_cast<user_id *> (idb);
3752 if (p)
3754 if (p->is_oper_list)
3755 op->substitutes.safe_splice (p->substitutes);
3756 else
3757 fatal_at (token, "iterator cannot be used as operator-list");
3759 else
3760 op->substitutes.safe_push (idb);
3762 op->nargs = arity;
3763 token = expect (CPP_CLOSE_PAREN);
3765 unsigned nsubstitutes = op->substitutes.length ();
3766 if (nsubstitutes == 0)
3767 fatal_at (token, "A user-defined operator must have at least "
3768 "one substitution");
3769 if (max_n_opers == 0)
3771 min_n_opers = nsubstitutes;
3772 max_n_opers = nsubstitutes;
3774 else
3776 if (nsubstitutes % min_n_opers != 0
3777 && min_n_opers % nsubstitutes != 0)
3778 fatal_at (token, "All user-defined identifiers must have a "
3779 "multiple number of operator substitutions of the "
3780 "smallest number of substitutions");
3781 if (nsubstitutes < min_n_opers)
3782 min_n_opers = nsubstitutes;
3783 else if (nsubstitutes > max_n_opers)
3784 max_n_opers = nsubstitutes;
3788 unsigned n_ids = user_ids.length ();
3789 if (n_ids == 0)
3790 fatal_at (token, "for requires at least one user-defined identifier");
3792 token = peek ();
3793 if (token->type == CPP_CLOSE_PAREN)
3794 fatal_at (token, "no pattern defined in for");
3796 active_fors.safe_push (user_ids);
3797 while (1)
3799 token = peek ();
3800 if (token->type == CPP_CLOSE_PAREN)
3801 break;
3802 parse_pattern ();
3804 active_fors.pop ();
3806 /* Remove user-defined operators from the hash again. */
3807 for (unsigned i = 0; i < user_ids.length (); ++i)
3809 if (!user_ids[i]->used)
3810 warning_at (user_id_tokens[i],
3811 "operator %s defined but not used", user_ids[i]->id);
3812 operators->remove_elt (user_ids[i]);
3816 /* Parse an identifier associated with a list of operators.
3817 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
3819 void
3820 parser::parse_operator_list (source_location)
3822 const cpp_token *token = peek ();
3823 const char *id = get_ident ();
3825 if (get_operator (id) != 0)
3826 fatal_at (token, "operator %s already defined", id);
3828 user_id *op = new user_id (id, true);
3829 int arity = -1;
3831 while ((token = peek_ident ()) != 0)
3833 token = peek ();
3834 const char *oper = get_ident ();
3835 id_base *idb = get_operator (oper);
3837 if (idb == 0)
3838 fatal_at (token, "no such operator '%s'", oper);
3840 if (arity == -1)
3841 arity = idb->nargs;
3842 else if (idb->nargs == -1)
3844 else if (arity != idb->nargs)
3845 fatal_at (token, "operator '%s' with arity %d does not match "
3846 "others with arity %d", oper, idb->nargs, arity);
3848 /* We allow composition of multiple operator lists. */
3849 if (user_id *p = dyn_cast<user_id *> (idb))
3850 op->substitutes.safe_splice (p->substitutes);
3851 else
3852 op->substitutes.safe_push (idb);
3855 // Check that there is no junk after id-list
3856 token = peek();
3857 if (token->type != CPP_CLOSE_PAREN)
3858 fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
3860 if (op->substitutes.length () == 0)
3861 fatal_at (token, "operator-list cannot be empty");
3863 op->nargs = arity;
3864 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
3865 *slot = op;
3868 /* Parse an outer if expression.
3869 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
3871 void
3872 parser::parse_if (source_location)
3874 c_expr *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
3876 const cpp_token *token = peek ();
3877 if (token->type == CPP_CLOSE_PAREN)
3878 fatal_at (token, "no pattern defined in if");
3880 active_ifs.safe_push (ifexpr);
3881 while (1)
3883 const cpp_token *token = peek ();
3884 if (token->type == CPP_CLOSE_PAREN)
3885 break;
3887 parse_pattern ();
3889 active_ifs.pop ();
3892 /* Parse a list of predefined predicate identifiers.
3893 preds = '(' 'define_predicates' <ident>... ')' */
3895 void
3896 parser::parse_predicates (source_location)
3900 const cpp_token *token = peek ();
3901 if (token->type != CPP_NAME)
3902 break;
3904 add_predicate (get_ident ());
3906 while (1);
3909 /* Parse outer control structures.
3910 pattern = <preds>|<for>|<if>|<simplify>|<match> */
3912 void
3913 parser::parse_pattern ()
3915 /* All clauses start with '('. */
3916 eat_token (CPP_OPEN_PAREN);
3917 const cpp_token *token = peek ();
3918 const char *id = get_ident ();
3919 if (strcmp (id, "simplify") == 0)
3921 parse_simplify (simplify::SIMPLIFY,
3922 token->src_loc, simplifiers, NULL, NULL);
3923 capture_ids = NULL;
3925 else if (strcmp (id, "match") == 0)
3927 bool with_args = false;
3928 if (peek ()->type == CPP_OPEN_PAREN)
3930 eat_token (CPP_OPEN_PAREN);
3931 with_args = true;
3933 const char *name = get_ident ();
3934 id_base *id = get_operator (name);
3935 predicate_id *p;
3936 if (!id)
3938 p = add_predicate (name);
3939 user_predicates.safe_push (p);
3941 else if ((p = dyn_cast <predicate_id *> (id)))
3943 else
3944 fatal_at (token, "cannot add a match to a non-predicate ID");
3945 /* Parse (match <id> <arg>... (match-expr)) here. */
3946 expr *e = NULL;
3947 if (with_args)
3949 capture_ids = new cid_map_t;
3950 e = new expr (p);
3951 while (peek ()->type == CPP_ATSIGN)
3952 e->append_op (parse_capture (NULL));
3953 eat_token (CPP_CLOSE_PAREN);
3955 if (p->nargs != -1
3956 && ((e && e->ops.length () != (unsigned)p->nargs)
3957 || (!e && p->nargs != 0)))
3958 fatal_at (token, "non-matching number of match operands");
3959 p->nargs = e ? e->ops.length () : 0;
3960 parse_simplify (simplify::MATCH, token->src_loc, p->matchers, p, e);
3961 capture_ids = NULL;
3963 else if (strcmp (id, "for") == 0)
3964 parse_for (token->src_loc);
3965 else if (strcmp (id, "if") == 0)
3966 parse_if (token->src_loc);
3967 else if (strcmp (id, "define_predicates") == 0)
3969 if (active_ifs.length () > 0
3970 || active_fors.length () > 0)
3971 fatal_at (token, "define_predicates inside if or for is not supported");
3972 parse_predicates (token->src_loc);
3974 else if (strcmp (id, "define_operator_list") == 0)
3976 if (active_ifs.length () > 0
3977 || active_fors.length () > 0)
3978 fatal_at (token, "operator-list inside if or for is not supported");
3979 parse_operator_list (token->src_loc);
3981 else
3982 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
3983 active_ifs.length () == 0 && active_fors.length () == 0
3984 ? "'define_predicates', " : "");
3986 eat_token (CPP_CLOSE_PAREN);
3989 /* Main entry of the parser. Repeatedly parse outer control structures. */
3991 parser::parser (cpp_reader *r_)
3993 r = r_;
3994 active_ifs = vNULL;
3995 active_fors = vNULL;
3996 simplifiers = vNULL;
3997 oper_lists_set = NULL;
3998 oper_lists = vNULL;
3999 capture_ids = NULL;
4000 user_predicates = vNULL;
4001 parsing_match_operand = false;
4003 const cpp_token *token = next ();
4004 while (token->type != CPP_EOF)
4006 _cpp_backup_tokens (r, 1);
4007 parse_pattern ();
4008 token = next ();
4013 /* Helper for the linemap code. */
4015 static size_t
4016 round_alloc_size (size_t s)
4018 return s;
4022 /* The genmatch generator progam. It reads from a pattern description
4023 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
4026 main (int argc, char **argv)
4028 cpp_reader *r;
4030 progname = "genmatch";
4032 if (argc < 2)
4033 return 1;
4035 bool gimple = true;
4036 bool verbose = false;
4037 char *input = argv[argc-1];
4038 for (int i = 1; i < argc - 1; ++i)
4040 if (strcmp (argv[i], "--gimple") == 0)
4041 gimple = true;
4042 else if (strcmp (argv[i], "--generic") == 0)
4043 gimple = false;
4044 else if (strcmp (argv[i], "-v") == 0)
4045 verbose = true;
4046 else
4048 fprintf (stderr, "Usage: genmatch "
4049 "[--gimple] [--generic] [-v] input\n");
4050 return 1;
4054 line_table = XCNEW (struct line_maps);
4055 linemap_init (line_table, 0);
4056 line_table->reallocator = xrealloc;
4057 line_table->round_alloc_size = round_alloc_size;
4059 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
4060 cpp_callbacks *cb = cpp_get_callbacks (r);
4061 cb->error = error_cb;
4063 if (!cpp_read_main_file (r, input))
4064 return 1;
4065 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
4066 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
4068 /* Pre-seed operators. */
4069 operators = new hash_table<id_base> (1024);
4070 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
4071 add_operator (SYM, # SYM, # TYPE, NARGS);
4072 #define END_OF_BASE_TREE_CODES
4073 #include "tree.def"
4074 add_operator (CONVERT0, "CONVERT0", "tcc_unary", 1);
4075 add_operator (CONVERT1, "CONVERT1", "tcc_unary", 1);
4076 add_operator (CONVERT2, "CONVERT2", "tcc_unary", 1);
4077 add_operator (VIEW_CONVERT0, "VIEW_CONVERT0", "tcc_unary", 1);
4078 add_operator (VIEW_CONVERT1, "VIEW_CONVERT1", "tcc_unary", 1);
4079 add_operator (VIEW_CONVERT2, "VIEW_CONVERT2", "tcc_unary", 1);
4080 #undef END_OF_BASE_TREE_CODES
4081 #undef DEFTREECODE
4083 /* Pre-seed builtin functions.
4084 ??? Cannot use N (name) as that is targetm.emultls.get_address
4085 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
4086 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
4087 add_builtin (ENUM, # ENUM);
4088 #include "builtins.def"
4089 #undef DEF_BUILTIN
4091 /* Parse ahead! */
4092 parser p (r);
4094 if (gimple)
4095 write_header (stdout, "gimple-match-head.c");
4096 else
4097 write_header (stdout, "generic-match-head.c");
4099 /* Go over all predicates defined with patterns and perform
4100 lowering and code generation. */
4101 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
4103 predicate_id *pred = p.user_predicates[i];
4104 lower (pred->matchers, gimple);
4106 if (verbose)
4107 for (unsigned i = 0; i < pred->matchers.length (); ++i)
4108 print_matches (pred->matchers[i]);
4110 decision_tree dt;
4111 for (unsigned i = 0; i < pred->matchers.length (); ++i)
4112 dt.insert (pred->matchers[i], i);
4114 if (verbose)
4115 dt.print (stderr);
4117 write_predicate (stdout, pred, dt, gimple);
4120 /* Lower the main simplifiers and generate code for them. */
4121 lower (p.simplifiers, gimple);
4123 if (verbose)
4124 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
4125 print_matches (p.simplifiers[i]);
4127 decision_tree dt;
4128 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
4129 dt.insert (p.simplifiers[i], i);
4131 if (verbose)
4132 dt.print (stderr);
4134 if (gimple)
4135 dt.gen_gimple (stdout);
4136 else
4137 dt.gen_generic (stdout);
4139 /* Finalize. */
4140 cpp_finish (r, NULL);
4141 cpp_destroy (r);
4143 delete operators;
4145 return 0;