Fixups after merge
[official-gcc.git] / gcc / genmatch.c
blobfdd02a5358ac04879b2d15e5b551cf3e0512bb50
1 /* Generate pattern matching and transform code shared between
2 GENERIC and GIMPLE folding code from match-and-simplify description.
4 Copyright (C) 2014 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 "ggc.h"
29 #include <cpplib.h>
30 #include "errors.h"
31 #include "hashtab.h"
32 #include "hash-table.h"
33 #include "hash-map.h"
34 #include "vec.h"
35 #include "is-a.h"
38 /* Stubs for GGC referenced through instantiations triggered by hash-map. */
39 void *ggc_internal_cleared_alloc (size_t, void (*)(void *),
40 size_t, size_t MEM_STAT_DECL)
42 return NULL;
44 void ggc_free (void *)
49 /* libccp helpers. */
51 static struct line_maps *line_table;
53 static bool
54 #if GCC_VERSION >= 4001
55 __attribute__((format (printf, 6, 0)))
56 #endif
57 error_cb (cpp_reader *, int errtype, int, source_location location,
58 unsigned int, const char *msg, va_list *ap)
60 const line_map *map;
61 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
62 expanded_location loc = linemap_expand_location (line_table, map, location);
63 fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
64 (errtype == CPP_DL_WARNING) ? "warning" : "error");
65 vfprintf (stderr, msg, *ap);
66 fprintf (stderr, "\n");
67 FILE *f = fopen (loc.file, "r");
68 if (f)
70 char buf[128];
71 while (loc.line > 0)
73 if (!fgets (buf, 128, f))
74 goto notfound;
75 if (buf[strlen (buf) - 1] != '\n')
77 if (loc.line > 1)
78 loc.line++;
80 loc.line--;
82 fprintf (stderr, "%s", buf);
83 for (int i = 0; i < loc.column - 1; ++i)
84 fputc (' ', stderr);
85 fputc ('^', stderr);
86 fputc ('\n', stderr);
87 notfound:
88 fclose (f);
91 if (errtype == CPP_DL_FATAL)
92 exit (1);
93 return false;
96 static void
97 #if GCC_VERSION >= 4001
98 __attribute__((format (printf, 2, 3)))
99 #endif
100 fatal_at (const cpp_token *tk, const char *msg, ...)
102 va_list ap;
103 va_start (ap, msg);
104 error_cb (NULL, CPP_DL_FATAL, 0, tk->src_loc, 0, msg, &ap);
105 va_end (ap);
108 static void
109 #if GCC_VERSION >= 4001
110 __attribute__((format (printf, 2, 3)))
111 #endif
112 warning_at (const cpp_token *tk, const char *msg, ...)
114 va_list ap;
115 va_start (ap, msg);
116 error_cb (NULL, CPP_DL_WARNING, 0, tk->src_loc, 0, msg, &ap);
117 va_end (ap);
120 static void
121 output_line_directive (FILE *f, source_location location,
122 bool dumpfile = false)
124 const line_map *map;
125 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
126 expanded_location loc = linemap_expand_location (line_table, map, location);
127 if (dumpfile)
129 /* When writing to a dumpfile only dump the filename. */
130 const char *file = strrchr (loc.file, DIR_SEPARATOR);
131 if (!file)
132 file = loc.file;
133 else
134 ++file;
135 fprintf (f, "%s:%d", file, loc.line);
137 else
138 /* Other gen programs really output line directives here, at least for
139 development it's right now more convenient to have line information
140 from the generated file. Still keep the directives as comment for now
141 to easily back-point to the meta-description. */
142 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
146 /* Pull in tree codes and builtin function codes from their
147 definition files. */
149 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
150 enum tree_code {
151 #include "tree.def"
152 CONVERT0,
153 CONVERT1,
154 CONVERT2,
155 MAX_TREE_CODES
157 #undef DEFTREECODE
159 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
160 enum built_in_function {
161 #include "builtins.def"
162 END_BUILTINS
164 #undef DEF_BUILTIN
167 /* Base class for all identifiers the parser knows. */
169 struct id_base : typed_noop_remove<id_base>
171 enum id_kind { CODE, FN, PREDICATE, USER } kind;
173 id_base (id_kind, const char *, int = -1);
175 hashval_t hashval;
176 int nargs;
177 const char *id;
179 /* hash_table support. */
180 typedef id_base value_type;
181 typedef id_base compare_type;
182 static inline hashval_t hash (const value_type *);
183 static inline int equal (const value_type *, const compare_type *);
186 inline hashval_t
187 id_base::hash (const value_type *op)
189 return op->hashval;
192 inline int
193 id_base::equal (const value_type *op1,
194 const compare_type *op2)
196 return (op1->hashval == op2->hashval
197 && strcmp (op1->id, op2->id) == 0);
200 /* Hashtable of known pattern operators. This is pre-seeded from
201 all known tree codes and all known builtin function ids. */
202 static hash_table<id_base> *operators;
204 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
206 kind = kind_;
207 id = id_;
208 nargs = nargs_;
209 hashval = htab_hash_string (id);
212 /* Identifier that maps to a tree code. */
214 struct operator_id : public id_base
216 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
217 const char *tcc_)
218 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
219 enum tree_code code;
220 const char *tcc;
223 /* Identifier that maps to a builtin function code. */
225 struct fn_id : public id_base
227 fn_id (enum built_in_function fn_, const char *id_)
228 : id_base (id_base::FN, id_), fn (fn_) {}
229 enum built_in_function fn;
232 struct simplify;
234 /* Identifier that maps to a user-defined predicate. */
236 struct predicate_id : public id_base
238 predicate_id (const char *id_)
239 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
240 vec<simplify *> matchers;
243 /* Identifier that maps to a operator defined by a 'for' directive. */
245 struct user_id : public id_base
247 user_id (const char *id_, bool is_oper_list_ = false)
248 : id_base (id_base::USER, id_), substitutes (vNULL),
249 used (false), is_oper_list (is_oper_list_) {}
250 vec<id_base *> substitutes;
251 bool used;
252 bool is_oper_list;
255 template<>
256 template<>
257 inline bool
258 is_a_helper <fn_id *>::test (id_base *id)
260 return id->kind == id_base::FN;
263 template<>
264 template<>
265 inline bool
266 is_a_helper <operator_id *>::test (id_base *id)
268 return id->kind == id_base::CODE;
271 template<>
272 template<>
273 inline bool
274 is_a_helper <predicate_id *>::test (id_base *id)
276 return id->kind == id_base::PREDICATE;
279 template<>
280 template<>
281 inline bool
282 is_a_helper <user_id *>::test (id_base *id)
284 return id->kind == id_base::USER;
287 /* Add a predicate identifier to the hash. */
289 static predicate_id *
290 add_predicate (const char *id)
292 predicate_id *p = new predicate_id (id);
293 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
294 if (*slot)
295 fatal ("duplicate id definition");
296 *slot = p;
297 return p;
300 /* Add a tree code identifier to the hash. */
302 static void
303 add_operator (enum tree_code code, const char *id,
304 const char *tcc, unsigned nargs)
306 if (strcmp (tcc, "tcc_unary") != 0
307 && strcmp (tcc, "tcc_binary") != 0
308 && strcmp (tcc, "tcc_comparison") != 0
309 && strcmp (tcc, "tcc_expression") != 0
310 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
311 && strcmp (tcc, "tcc_reference") != 0
312 /* To have INTEGER_CST and friends as "predicate operators". */
313 && strcmp (tcc, "tcc_constant") != 0
314 /* And allow CONSTRUCTOR for vector initializers. */
315 && !(code == CONSTRUCTOR))
316 return;
317 operator_id *op = new operator_id (code, id, nargs, tcc);
318 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
319 if (*slot)
320 fatal ("duplicate id definition");
321 *slot = op;
324 /* Add a builtin identifier to the hash. */
326 static void
327 add_builtin (enum built_in_function code, const char *id)
329 fn_id *fn = new fn_id (code, id);
330 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
331 if (*slot)
332 fatal ("duplicate id definition");
333 *slot = fn;
336 /* Helper for easy comparing ID with tree code CODE. */
338 static bool
339 operator==(id_base &id, enum tree_code code)
341 if (operator_id *oid = dyn_cast <operator_id *> (&id))
342 return oid->code == code;
343 return false;
346 /* Lookup the identifier ID. */
348 id_base *
349 get_operator (const char *id)
351 id_base tem (id_base::CODE, id);
353 id_base *op = operators->find_with_hash (&tem, tem.hashval);
354 if (op)
356 /* If this is a user-defined identifier track whether it was used. */
357 if (user_id *uid = dyn_cast<user_id *> (op))
358 uid->used = true;
359 return op;
362 /* Try all-uppercase. */
363 char *id2 = xstrdup (id);
364 for (unsigned i = 0; i < strlen (id2); ++i)
365 id2[i] = TOUPPER (id2[i]);
366 new (&tem) id_base (id_base::CODE, id2);
367 op = operators->find_with_hash (&tem, tem.hashval);
368 if (op)
370 free (id2);
371 return op;
374 /* Try _EXPR appended. */
375 id2 = (char *)xrealloc (id2, strlen (id2) + sizeof ("_EXPR") + 1);
376 strcat (id2, "_EXPR");
377 new (&tem) id_base (id_base::CODE, id2);
378 op = operators->find_with_hash (&tem, tem.hashval);
379 if (op)
381 free (id2);
382 return op;
385 return 0;
389 /* Helper for the capture-id map. */
391 struct capture_id_map_hasher : default_hashmap_traits
393 static inline hashval_t hash (const char *);
394 static inline bool equal_keys (const char *, const char *);
397 inline hashval_t
398 capture_id_map_hasher::hash (const char *id)
400 return htab_hash_string (id);
403 inline bool
404 capture_id_map_hasher::equal_keys (const char *id1, const char *id2)
406 return strcmp (id1, id2) == 0;
409 typedef hash_map<const char *, unsigned, capture_id_map_hasher> cid_map_t;
412 /* The AST produced by parsing of the pattern definitions. */
414 struct dt_operand;
415 struct capture_info;
417 /* The base class for operands. */
419 struct operand {
420 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR };
421 operand (enum op_type type_) : type (type_) {}
422 enum op_type type;
423 virtual void gen_transform (FILE *, const char *, bool, int,
424 const char *, capture_info *,
425 dt_operand ** = 0,
426 bool = true)
427 { gcc_unreachable (); }
430 /* A predicate operand. Predicates are leafs in the AST. */
432 struct predicate : public operand
434 predicate (predicate_id *p_) : operand (OP_PREDICATE), p (p_) {}
435 predicate_id *p;
438 /* An operand that constitutes an expression. Expressions include
439 function calls and user-defined predicate invocations. */
441 struct expr : public operand
443 expr (id_base *operation_, bool is_commutative_ = false)
444 : operand (OP_EXPR), operation (operation_),
445 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
446 is_generic (false) {}
447 void append_op (operand *op) { ops.safe_push (op); }
448 /* The operator and its operands. */
449 id_base *operation;
450 vec<operand *> ops;
451 /* An explicitely specified type - used exclusively for conversions. */
452 const char *expr_type;
453 /* Whether the operation is to be applied commutatively. This is
454 later lowered to two separate patterns. */
455 bool is_commutative;
456 /* Whether the expression is expected to be in GENERIC form. */
457 bool is_generic;
458 virtual void gen_transform (FILE *f, const char *, bool, int,
459 const char *, capture_info *,
460 dt_operand ** = 0, bool = true);
463 /* An operator that is represented by native C code. This is always
464 a leaf operand in the AST. This class is also used to represent
465 the code to be generated for 'if' and 'with' expressions. */
467 struct c_expr : public operand
469 /* A mapping of an identifier and its replacement. Used to apply
470 'for' lowering. */
471 struct id_tab {
472 const char *id;
473 const char *oper;
474 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
477 c_expr (cpp_reader *r_, vec<cpp_token> code_, unsigned nr_stmts_,
478 vec<id_tab> ids_, cid_map_t *capture_ids_)
479 : operand (OP_C_EXPR), r (r_), code (code_), capture_ids (capture_ids_),
480 nr_stmts (nr_stmts_), ids (ids_) {}
481 /* cpplib tokens and state to transform this back to source. */
482 cpp_reader *r;
483 vec<cpp_token> code;
484 cid_map_t *capture_ids;
485 /* The number of statements parsed (well, the number of ';'s). */
486 unsigned nr_stmts;
487 /* The identifier replacement vector. */
488 vec<id_tab> ids;
489 virtual void gen_transform (FILE *f, const char *, bool, int,
490 const char *, capture_info *,
491 dt_operand ** = 0, bool = true);
494 /* A wrapper around another operand that captures its value. */
496 struct capture : public operand
498 capture (unsigned where_, operand *what_)
499 : operand (OP_CAPTURE), where (where_), what (what_) {}
500 /* Identifier index for the value. */
501 unsigned where;
502 /* The captured value. */
503 operand *what;
504 virtual void gen_transform (FILE *f, const char *, bool, int,
505 const char *, capture_info *,
506 dt_operand ** = 0, bool = true);
509 template<>
510 template<>
511 inline bool
512 is_a_helper <capture *>::test (operand *op)
514 return op->type == operand::OP_CAPTURE;
517 template<>
518 template<>
519 inline bool
520 is_a_helper <predicate *>::test (operand *op)
522 return op->type == operand::OP_PREDICATE;
525 template<>
526 template<>
527 inline bool
528 is_a_helper <c_expr *>::test (operand *op)
530 return op->type == operand::OP_C_EXPR;
533 template<>
534 template<>
535 inline bool
536 is_a_helper <expr *>::test (operand *op)
538 return op->type == operand::OP_EXPR;
541 /* Helper to distinguish 'if' from 'with' expressions. */
543 struct if_or_with
545 if_or_with (operand *cexpr_, source_location location_, bool is_with_)
546 : location (location_), cexpr (cexpr_), is_with (is_with_) {}
547 source_location location;
548 operand *cexpr;
549 bool is_with;
552 /* The main class of a pattern and its transform. This is used to
553 represent both (simplify ...) and (match ...) kinds. The AST
554 duplicates all outer 'if' and 'for' expressions here so each
555 simplify can exist in isolation. */
557 struct simplify
559 simplify (operand *match_, source_location match_location_,
560 struct operand *result_, source_location result_location_,
561 vec<if_or_with> ifexpr_vec_, vec<vec<user_id *> > for_vec_,
562 cid_map_t *capture_ids_)
563 : match (match_), match_location (match_location_),
564 result (result_), result_location (result_location_),
565 ifexpr_vec (ifexpr_vec_), for_vec (for_vec_),
566 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
568 /* The expression that is matched against the GENERIC or GIMPLE IL. */
569 operand *match;
570 source_location match_location;
571 /* For a (simplify ...) the expression produced when the pattern applies.
572 For a (match ...) either NULL if it is a simple predicate or the
573 single expression specifying the matched operands. */
574 struct operand *result;
575 source_location result_location;
576 /* Collected 'if' expressions that need to evaluate to true to make
577 the pattern apply. */
578 vec<if_or_with> ifexpr_vec;
579 /* Collected 'for' expression operators that have to be replaced
580 in the lowering phase. */
581 vec<vec<user_id *> > for_vec;
582 /* A map of capture identifiers to indexes. */
583 cid_map_t *capture_ids;
584 int capture_max;
587 /* Debugging routines for dumping the AST. */
589 DEBUG_FUNCTION void
590 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
592 if (capture *c = dyn_cast<capture *> (o))
594 fprintf (f, "@%u", c->where);
595 if (c->what && flattened == false)
597 putc (':', f);
598 print_operand (c->what, f, flattened);
599 putc (' ', f);
603 else if (predicate *p = dyn_cast<predicate *> (o))
604 fprintf (f, "%s", p->p->id);
606 else if (is_a<c_expr *> (o))
607 fprintf (f, "c_expr");
609 else if (expr *e = dyn_cast<expr *> (o))
611 fprintf (f, "(%s", e->operation->id);
613 if (flattened == false)
615 putc (' ', f);
616 for (unsigned i = 0; i < e->ops.length (); ++i)
618 print_operand (e->ops[i], f, flattened);
619 putc (' ', f);
622 putc (')', f);
625 else
626 gcc_unreachable ();
629 DEBUG_FUNCTION void
630 print_matches (struct simplify *s, FILE *f = stderr)
632 fprintf (f, "for expression: ");
633 print_operand (s->match, f);
634 putc ('\n', f);
638 /* AST lowering. */
640 /* Lowering of commutative operators. */
642 static void
643 cartesian_product (const vec< vec<operand *> >& ops_vector,
644 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
646 if (n == ops_vector.length ())
648 vec<operand *> xv = v.copy ();
649 result.safe_push (xv);
650 return;
653 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
655 v[n] = ops_vector[n][i];
656 cartesian_product (ops_vector, result, v, n + 1);
660 /* Lower OP to two operands in case it is marked as commutative. */
662 static vec<operand *>
663 commutate (operand *op)
665 vec<operand *> ret = vNULL;
667 if (capture *c = dyn_cast <capture *> (op))
669 if (!c->what)
671 ret.safe_push (op);
672 return ret;
674 vec<operand *> v = commutate (c->what);
675 for (unsigned i = 0; i < v.length (); ++i)
677 capture *nc = new capture (c->where, v[i]);
678 ret.safe_push (nc);
680 return ret;
683 expr *e = dyn_cast <expr *> (op);
684 if (!e || e->ops.length () == 0)
686 ret.safe_push (op);
687 return ret;
690 vec< vec<operand *> > ops_vector = vNULL;
691 for (unsigned i = 0; i < e->ops.length (); ++i)
692 ops_vector.safe_push (commutate (e->ops[i]));
694 auto_vec< vec<operand *> > result;
695 auto_vec<operand *> v (e->ops.length ());
696 v.quick_grow_cleared (e->ops.length ());
697 cartesian_product (ops_vector, result, v, 0);
700 for (unsigned i = 0; i < result.length (); ++i)
702 expr *ne = new expr (e->operation);
703 for (unsigned j = 0; j < result[i].length (); ++j)
704 ne->append_op (result[i][j]);
705 ret.safe_push (ne);
708 if (!e->is_commutative)
709 return ret;
711 for (unsigned i = 0; i < result.length (); ++i)
713 expr *ne = new expr (e->operation);
714 // result[i].length () is 2 since e->operation is binary
715 for (unsigned j = result[i].length (); j; --j)
716 ne->append_op (result[i][j-1]);
717 ret.safe_push (ne);
720 return ret;
723 /* Lower operations marked as commutative in the AST of S and push
724 the resulting patterns to SIMPLIFIERS. */
726 static void
727 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
729 vec<operand *> matchers = commutate (s->match);
730 for (unsigned i = 0; i < matchers.length (); ++i)
732 simplify *ns = new simplify (matchers[i], s->match_location,
733 s->result, s->result_location, s->ifexpr_vec,
734 s->for_vec, s->capture_ids);
735 simplifiers.safe_push (ns);
739 /* Strip conditional conversios using operator OPER from O and its
740 children if STRIP, else replace them with an unconditional convert. */
742 operand *
743 lower_opt_convert (operand *o, enum tree_code oper, bool strip)
745 if (capture *c = dyn_cast<capture *> (o))
747 if (c->what)
748 return new capture (c->where, lower_opt_convert (c->what, oper, strip));
749 else
750 return c;
753 expr *e = dyn_cast<expr *> (o);
754 if (!e)
755 return o;
757 if (*e->operation == oper)
759 if (strip)
760 return lower_opt_convert (e->ops[0], oper, strip);
762 expr *ne = new expr (get_operator ("CONVERT_EXPR"));
763 ne->append_op (lower_opt_convert (e->ops[0], oper, strip));
764 return ne;
767 expr *ne = new expr (e->operation, e->is_commutative);
768 for (unsigned i = 0; i < e->ops.length (); ++i)
769 ne->append_op (lower_opt_convert (e->ops[i], oper, strip));
771 return ne;
774 /* Determine whether O or its children uses the conditional conversion
775 operator OPER. */
777 static bool
778 has_opt_convert (operand *o, enum tree_code oper)
780 if (capture *c = dyn_cast<capture *> (o))
782 if (c->what)
783 return has_opt_convert (c->what, oper);
784 else
785 return false;
788 expr *e = dyn_cast<expr *> (o);
789 if (!e)
790 return false;
792 if (*e->operation == oper)
793 return true;
795 for (unsigned i = 0; i < e->ops.length (); ++i)
796 if (has_opt_convert (e->ops[i], oper))
797 return true;
799 return false;
802 /* Lower conditional convert operators in O, expanding it to a vector
803 if required. */
805 static vec<operand *>
806 lower_opt_convert (operand *o)
808 vec<operand *> v1 = vNULL, v2;
810 v1.safe_push (o);
812 enum tree_code opers[] = { CONVERT0, CONVERT1, CONVERT2 };
814 /* Conditional converts are lowered to a pattern with the
815 conversion and one without. The three different conditional
816 convert codes are lowered separately. */
818 for (unsigned i = 0; i < 3; ++i)
820 v2 = vNULL;
821 for (unsigned j = 0; j < v1.length (); ++j)
822 if (has_opt_convert (v1[j], opers[i]))
824 v2.safe_push (lower_opt_convert (v1[j], opers[i], false));
825 v2.safe_push (lower_opt_convert (v1[j], opers[i], true));
828 if (v2 != vNULL)
830 v1 = vNULL;
831 for (unsigned j = 0; j < v2.length (); ++j)
832 v1.safe_push (v2[j]);
836 return v1;
839 /* Lower conditional convert operators in the AST of S and push
840 the resulting multiple patterns to SIMPLIFIERS. */
842 static void
843 lower_opt_convert (simplify *s, vec<simplify *>& simplifiers)
845 vec<operand *> matchers = lower_opt_convert (s->match);
846 for (unsigned i = 0; i < matchers.length (); ++i)
848 simplify *ns = new simplify (matchers[i], s->match_location,
849 s->result, s->result_location, s->ifexpr_vec,
850 s->for_vec, s->capture_ids);
851 simplifiers.safe_push (ns);
855 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
856 GENERIC and a GIMPLE variant. */
858 static vec<operand *>
859 lower_cond (operand *o)
861 vec<operand *> ro = vNULL;
863 if (capture *c = dyn_cast<capture *> (o))
865 if (c->what)
867 vec<operand *> lop = vNULL;
868 lop = lower_cond (c->what);
870 for (unsigned i = 0; i < lop.length (); ++i)
871 ro.safe_push (new capture (c->where, lop[i]));
872 return ro;
876 expr *e = dyn_cast<expr *> (o);
877 if (!e || e->ops.length () == 0)
879 ro.safe_push (o);
880 return ro;
883 vec< vec<operand *> > ops_vector = vNULL;
884 for (unsigned i = 0; i < e->ops.length (); ++i)
885 ops_vector.safe_push (lower_cond (e->ops[i]));
887 auto_vec< vec<operand *> > result;
888 auto_vec<operand *> v (e->ops.length ());
889 v.quick_grow_cleared (e->ops.length ());
890 cartesian_product (ops_vector, result, v, 0);
892 for (unsigned i = 0; i < result.length (); ++i)
894 expr *ne = new expr (e->operation);
895 for (unsigned j = 0; j < result[i].length (); ++j)
896 ne->append_op (result[i][j]);
897 ro.safe_push (ne);
898 /* If this is a COND with a captured expression or an
899 expression with two operands then also match a GENERIC
900 form on the compare. */
901 if ((*e->operation == COND_EXPR
902 || *e->operation == VEC_COND_EXPR)
903 && ((is_a <capture *> (e->ops[0])
904 && as_a <capture *> (e->ops[0])->what
905 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
906 && as_a <expr *>
907 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
908 || (is_a <expr *> (e->ops[0])
909 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
911 expr *ne = new expr (e->operation);
912 for (unsigned j = 0; j < result[i].length (); ++j)
913 ne->append_op (result[i][j]);
914 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
916 expr *ocmp = as_a <expr *> (c->what);
917 expr *cmp = new expr (ocmp->operation);
918 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
919 cmp->append_op (ocmp->ops[j]);
920 cmp->is_generic = true;
921 ne->ops[0] = new capture (c->where, cmp);
923 else
925 expr *ocmp = as_a <expr *> (ne->ops[0]);
926 expr *cmp = new expr (ocmp->operation);
927 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
928 cmp->append_op (ocmp->ops[j]);
929 cmp->is_generic = true;
930 ne->ops[0] = cmp;
932 ro.safe_push (ne);
936 return ro;
939 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
940 GENERIC and a GIMPLE variant. */
942 static void
943 lower_cond (simplify *s, vec<simplify *>& simplifiers)
945 vec<operand *> matchers = lower_cond (s->match);
946 for (unsigned i = 0; i < matchers.length (); ++i)
948 simplify *ns = new simplify (matchers[i], s->match_location,
949 s->result, s->result_location, s->ifexpr_vec,
950 s->for_vec, s->capture_ids);
951 simplifiers.safe_push (ns);
955 /* In AST operand O replace operator ID with operator WITH. */
957 operand *
958 replace_id (operand *o, user_id *id, id_base *with)
960 /* Deep-copy captures and expressions, replacing operations as
961 needed. */
962 if (capture *c = dyn_cast<capture *> (o))
964 if (!c->what)
965 return c;
966 return new capture (c->where, replace_id (c->what, id, with));
968 else if (expr *e = dyn_cast<expr *> (o))
970 expr *ne = new expr (e->operation == id ? with : e->operation,
971 e->is_commutative);
972 for (unsigned i = 0; i < e->ops.length (); ++i)
973 ne->append_op (replace_id (e->ops[i], id, with));
974 return ne;
977 /* For c_expr we simply record a string replacement table which is
978 applied at code-generation time. */
979 if (c_expr *ce = dyn_cast<c_expr *> (o))
981 vec<c_expr::id_tab> ids = ce->ids.copy ();
982 ids.safe_push (c_expr::id_tab (id->id, with->id));
983 return new c_expr (ce->r, ce->code, ce->nr_stmts, ids, ce->capture_ids);
986 return o;
989 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
991 static void
992 lower_for (simplify *sin, vec<simplify *>& simplifiers)
994 vec<vec<user_id *> >& for_vec = sin->for_vec;
995 unsigned worklist_start = 0;
996 auto_vec<simplify *> worklist;
997 worklist.safe_push (sin);
999 /* Lower each recorded for separately, operating on the
1000 set of simplifiers created by the previous one.
1001 Lower inner-to-outer so inner for substitutes can refer
1002 to operators replaced by outer fors. */
1003 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1005 vec<user_id *>& ids = for_vec[fi];
1006 unsigned n_ids = ids.length ();
1007 unsigned max_n_opers = 0;
1008 for (unsigned i = 0; i < n_ids; ++i)
1009 if (ids[i]->substitutes.length () > max_n_opers)
1010 max_n_opers = ids[i]->substitutes.length ();
1012 unsigned worklist_end = worklist.length ();
1013 for (unsigned si = worklist_start; si < worklist_end; ++si)
1015 simplify *s = worklist[si];
1016 for (unsigned j = 0; j < max_n_opers; ++j)
1018 operand *match_op = s->match;
1019 operand *result_op = s->result;
1020 vec<if_or_with> ifexpr_vec = s->ifexpr_vec.copy ();
1022 for (unsigned i = 0; i < n_ids; ++i)
1024 user_id *id = ids[i];
1025 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1026 match_op = replace_id (match_op, id, oper);
1027 if (result_op)
1028 result_op = replace_id (result_op, id, oper);
1029 for (unsigned k = 0; k < s->ifexpr_vec.length (); ++k)
1030 ifexpr_vec[k].cexpr = replace_id (ifexpr_vec[k].cexpr,
1031 id, oper);
1033 simplify *ns = new simplify (match_op, s->match_location,
1034 result_op, s->result_location,
1035 ifexpr_vec, vNULL, s->capture_ids);
1036 worklist.safe_push (ns);
1039 worklist_start = worklist_end;
1042 /* Copy out the result from the last for lowering. */
1043 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1044 simplifiers.safe_push (worklist[i]);
1047 /* Lower the AST for everything in SIMPLIFIERS. */
1049 static void
1050 lower (vec<simplify *>& simplifiers, bool gimple)
1052 auto_vec<simplify *> out_simplifiers;
1053 for (unsigned i = 0; i < simplifiers.length (); ++i)
1054 lower_opt_convert (simplifiers[i], out_simplifiers);
1056 simplifiers.truncate (0);
1057 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1058 lower_commutative (out_simplifiers[i], simplifiers);
1060 out_simplifiers.truncate (0);
1061 if (gimple)
1062 for (unsigned i = 0; i < simplifiers.length (); ++i)
1063 lower_cond (simplifiers[i], out_simplifiers);
1064 else
1065 out_simplifiers.safe_splice (simplifiers);
1068 simplifiers.truncate (0);
1069 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1070 lower_for (out_simplifiers[i], simplifiers);
1076 /* The decision tree built for generating GIMPLE and GENERIC pattern
1077 matching code. It represents the 'match' expression of all
1078 simplifies and has those as its leafs. */
1080 /* Decision tree base class, used for DT_TRUE and DT_NODE. */
1082 struct dt_node
1084 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1086 enum dt_type type;
1087 unsigned level;
1088 vec<dt_node *> kids;
1090 dt_node (enum dt_type type_): type (type_), level (0), kids (vNULL) {}
1092 dt_node *append_node (dt_node *);
1093 dt_node *append_op (operand *, dt_node *parent = 0, unsigned pos = 0);
1094 dt_node *append_true_op (dt_node *parent = 0, unsigned pos = 0);
1095 dt_node *append_match_op (dt_operand *, dt_node *parent = 0, unsigned pos = 0);
1096 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1098 virtual void gen (FILE *, bool) {}
1100 void gen_kids (FILE *, bool);
1103 /* Generic decision tree node used for DT_OPERAND and DT_MATCH. */
1105 struct dt_operand : public dt_node
1107 operand *op;
1108 dt_operand *match_dop;
1109 dt_operand *parent;
1110 unsigned pos;
1112 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1113 dt_operand *parent_ = 0, unsigned pos_ = 0)
1114 : dt_node (type), op (op_), match_dop (match_dop_),
1115 parent (parent_), pos (pos_) {}
1117 void gen (FILE *, bool);
1118 unsigned gen_predicate (FILE *, const char *, bool);
1119 unsigned gen_match_op (FILE *, const char *);
1121 unsigned gen_gimple_expr (FILE *);
1122 unsigned gen_generic_expr (FILE *, const char *);
1124 char *get_name (char *);
1125 void gen_opname (char *, unsigned);
1128 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1130 struct dt_simplify : public dt_node
1132 simplify *s;
1133 unsigned pattern_no;
1134 dt_operand **indexes;
1136 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1137 : dt_node (DT_SIMPLIFY), s (s_), pattern_no (pattern_no_),
1138 indexes (indexes_) {}
1140 void gen (FILE *f, bool);
1143 template<>
1144 template<>
1145 inline bool
1146 is_a_helper <dt_operand *>::test (dt_node *n)
1148 return (n->type == dt_node::DT_OPERAND
1149 || n->type == dt_node::DT_MATCH);
1152 /* A container for the actual decision tree. */
1154 struct decision_tree
1156 dt_node *root;
1158 void insert (struct simplify *, unsigned);
1159 void gen_gimple (FILE *f = stderr);
1160 void gen_generic (FILE *f = stderr);
1161 void print (FILE *f = stderr);
1163 decision_tree () { root = new dt_node (dt_node::DT_NODE); }
1165 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1166 unsigned pos = 0, dt_node *parent = 0);
1167 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1168 static bool cmp_node (dt_node *, dt_node *);
1169 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1172 /* Compare two AST operands O1 and O2 and return true if they are equal. */
1174 bool
1175 cmp_operand (operand *o1, operand *o2)
1177 if (!o1 || !o2 || o1->type != o2->type)
1178 return false;
1180 if (o1->type == operand::OP_PREDICATE)
1182 predicate *p1 = as_a<predicate *>(o1);
1183 predicate *p2 = as_a<predicate *>(o2);
1184 return p1->p == p2->p;
1186 else if (o1->type == operand::OP_EXPR)
1188 expr *e1 = static_cast<expr *>(o1);
1189 expr *e2 = static_cast<expr *>(o2);
1190 return (e1->operation == e2->operation
1191 && e1->is_generic == e2->is_generic);
1193 else
1194 return false;
1197 /* Compare two decision tree nodes N1 and N2 and return true if they
1198 are equal. */
1200 bool
1201 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1203 if (!n1 || !n2 || n1->type != n2->type)
1204 return false;
1206 if (n1 == n2 || n1->type == dt_node::DT_TRUE)
1207 return true;
1209 if (n1->type == dt_node::DT_OPERAND)
1210 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1211 (as_a<dt_operand *> (n2))->op);
1212 else if (n1->type == dt_node::DT_MATCH)
1213 return ((as_a<dt_operand *> (n1))->match_dop
1214 == (as_a<dt_operand *> (n2))->match_dop);
1215 return false;
1218 /* Search OPS for a decision tree node like P and return it if found. */
1220 dt_node *
1221 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1223 for (unsigned i = 0; i < ops.length (); ++i)
1224 if (decision_tree::cmp_node (ops[i], p))
1225 return ops[i];
1227 return NULL;
1230 /* Append N to the decision tree if it there is not already an existing
1231 identical child. */
1233 dt_node *
1234 dt_node::append_node (dt_node *n)
1236 dt_node *kid;
1238 kid = decision_tree::find_node (kids, n);
1239 if (kid)
1240 return kid;
1242 kids.safe_push (n);
1243 n->level = this->level + 1;
1245 unsigned len = kids.length ();
1247 if (len > 1 && kids[len - 2]->type == dt_node::DT_TRUE)
1249 dt_node *p = kids[len - 2];
1250 kids[len - 2] = kids[len - 1];
1251 kids[len - 1] = p;
1254 return n;
1257 /* Append OP to the decision tree. */
1259 dt_node *
1260 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1262 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1263 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1264 return append_node (n);
1267 /* Append a DT_TRUE decision tree node. */
1269 dt_node *
1270 dt_node::append_true_op (dt_node *parent, unsigned pos)
1272 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1273 dt_operand *n = new dt_operand (DT_TRUE, 0, 0, parent_, pos);
1274 return append_node (n);
1277 /* Append a DT_MATCH decision tree node. */
1279 dt_node *
1280 dt_node::append_match_op (dt_operand *match_dop, dt_node *parent, unsigned pos)
1282 dt_operand *parent_ = as_a<dt_operand *> (parent);
1283 dt_operand *n = new dt_operand (DT_MATCH, 0, match_dop, parent_, pos);
1284 return append_node (n);
1287 /* Append S to the decision tree. */
1289 dt_node *
1290 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1291 dt_operand **indexes)
1293 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1294 return append_node (n);
1297 /* Insert O into the decision tree and return the decision tree node found
1298 or created. */
1300 dt_node *
1301 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1302 unsigned pos, dt_node *parent)
1304 dt_node *q, *elm = 0;
1306 if (capture *c = dyn_cast<capture *> (o))
1308 unsigned capt_index = c->where;
1310 if (indexes[capt_index] == 0)
1312 if (c->what)
1313 q = insert_operand (p, c->what, indexes, pos, parent);
1314 else
1316 q = elm = p->append_true_op (parent, pos);
1317 goto at_assert_elm;
1319 // get to the last capture
1320 for (operand *what = c->what;
1321 what && is_a<capture *> (what);
1322 c = as_a<capture *> (what), what = c->what)
1325 if (!c->what)
1327 unsigned cc_index = c->where;
1328 dt_operand *match_op = indexes[cc_index];
1330 dt_operand temp (dt_node::DT_TRUE, 0, 0);
1331 elm = decision_tree::find_node (p->kids, &temp);
1333 if (elm == 0)
1335 dt_operand temp (dt_node::DT_MATCH, 0, match_op);
1336 elm = decision_tree::find_node (p->kids, &temp);
1339 else
1341 dt_operand temp (dt_node::DT_OPERAND, c->what, 0);
1342 elm = decision_tree::find_node (p->kids, &temp);
1345 at_assert_elm:
1346 gcc_assert (elm->type == dt_node::DT_TRUE
1347 || elm->type == dt_node::DT_OPERAND
1348 || elm->type == dt_node::DT_MATCH);
1349 indexes[capt_index] = static_cast<dt_operand *> (elm);
1350 return q;
1352 else
1354 p = p->append_match_op (indexes[capt_index], parent, pos);
1355 if (c->what)
1356 return insert_operand (p, c->what, indexes, 0, p);
1357 else
1358 return p;
1361 p = p->append_op (o, parent, pos);
1362 q = p;
1364 if (expr *e = dyn_cast <expr *>(o))
1366 for (unsigned i = 0; i < e->ops.length (); ++i)
1367 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
1370 return q;
1373 /* Insert S into the decision tree. */
1375 void
1376 decision_tree::insert (struct simplify *s, unsigned pattern_no)
1378 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
1379 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
1380 p->append_simplify (s, pattern_no, indexes);
1383 /* Debug functions to dump the decision tree. */
1385 DEBUG_FUNCTION void
1386 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
1388 if (p->type == dt_node::DT_NODE)
1389 fprintf (f, "root");
1390 else
1392 fprintf (f, "|");
1393 for (unsigned i = 0; i < indent; i++)
1394 fprintf (f, "-");
1396 if (p->type == dt_node::DT_OPERAND)
1398 dt_operand *dop = static_cast<dt_operand *>(p);
1399 print_operand (dop->op, f, true);
1401 else if (p->type == dt_node::DT_TRUE)
1402 fprintf (f, "true");
1403 else if (p->type == dt_node::DT_MATCH)
1404 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
1405 else if (p->type == dt_node::DT_SIMPLIFY)
1407 dt_simplify *s = static_cast<dt_simplify *> (p);
1408 fprintf (f, "simplify_%u { ", s->pattern_no);
1409 for (int i = 0; i <= s->s->capture_max; ++i)
1410 fprintf (f, "%p, ", (void *) s->indexes[i]);
1411 fprintf (f, " } ");
1415 fprintf (stderr, " (%p), %u, %u\n", (void *) p, p->level, p->kids.length ());
1417 for (unsigned i = 0; i < p->kids.length (); ++i)
1418 decision_tree::print_node (p->kids[i], f, indent + 2);
1421 DEBUG_FUNCTION void
1422 decision_tree::print (FILE *f)
1424 return decision_tree::print_node (root, f);
1428 /* For GENERIC we have to take care of wrapping multiple-used
1429 expressions with side-effects in save_expr and preserve side-effects
1430 of expressions with omit_one_operand. Analyze captures in
1431 match, result and with expressions and perform early-outs
1432 on the outermost match expression operands for cases we cannot
1433 handle. */
1435 struct capture_info
1437 capture_info (simplify *s);
1438 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
1439 void walk_result (operand *o, bool);
1440 void walk_c_expr (c_expr *);
1442 struct cinfo
1444 bool expr_p;
1445 bool cse_p;
1446 bool force_no_side_effects_p;
1447 bool cond_expr_cond_p;
1448 unsigned long toplevel_msk;
1449 int result_use_count;
1452 auto_vec<cinfo> info;
1453 unsigned long force_no_side_effects;
1456 /* Analyze captures in S. */
1458 capture_info::capture_info (simplify *s)
1460 expr *e;
1461 if (!s->result
1462 || ((e = dyn_cast <expr *> (s->result))
1463 && is_a <predicate_id *> (e->operation)))
1465 force_no_side_effects = -1;
1466 return;
1469 force_no_side_effects = 0;
1470 info.safe_grow_cleared (s->capture_max + 1);
1471 e = as_a <expr *> (s->match);
1472 for (unsigned i = 0; i < e->ops.length (); ++i)
1473 walk_match (e->ops[i], i,
1474 (i != 0 && *e->operation == COND_EXPR)
1475 || *e->operation == TRUTH_ANDIF_EXPR
1476 || *e->operation == TRUTH_ORIF_EXPR,
1477 i == 0
1478 && (*e->operation == COND_EXPR
1479 || *e->operation == VEC_COND_EXPR));
1481 walk_result (s->result, false);
1483 for (unsigned i = 0; i < s->ifexpr_vec.length (); ++i)
1484 if (s->ifexpr_vec[i].is_with)
1485 walk_c_expr (as_a <c_expr *>(s->ifexpr_vec[i].cexpr));
1488 /* Analyze captures in the match expression piece O. */
1490 void
1491 capture_info::walk_match (operand *o, unsigned toplevel_arg,
1492 bool conditional_p, bool cond_expr_cond_p)
1494 if (capture *c = dyn_cast <capture *> (o))
1496 info[c->where].toplevel_msk |= 1 << toplevel_arg;
1497 info[c->where].force_no_side_effects_p |= conditional_p;
1498 info[c->where].cond_expr_cond_p |= cond_expr_cond_p;
1499 /* Mark expr (non-leaf) captures and recurse. */
1500 if (c->what
1501 && is_a <expr *> (c->what))
1503 info[c->where].expr_p = true;
1504 walk_match (c->what, toplevel_arg, conditional_p, false);
1507 else if (expr *e = dyn_cast <expr *> (o))
1509 for (unsigned i = 0; i < e->ops.length (); ++i)
1511 bool cond_p = conditional_p;
1512 bool cond_expr_cond_p = false;
1513 if (i != 0 && *e->operation == COND_EXPR)
1514 cond_p = true;
1515 else if (*e->operation == TRUTH_ANDIF_EXPR
1516 || *e->operation == TRUTH_ORIF_EXPR)
1517 cond_p = true;
1518 if (i == 0
1519 && (*e->operation == COND_EXPR
1520 || *e->operation == VEC_COND_EXPR))
1521 cond_expr_cond_p = true;
1522 walk_match (e->ops[i], toplevel_arg, cond_p, cond_expr_cond_p);
1525 else if (is_a <predicate *> (o))
1527 /* Mark non-captured leafs toplevel arg for checking. */
1528 force_no_side_effects |= 1 << toplevel_arg;
1530 else
1531 gcc_unreachable ();
1534 /* Analyze captures in the result expression piece O. */
1536 void
1537 capture_info::walk_result (operand *o, bool conditional_p)
1539 if (capture *c = dyn_cast <capture *> (o))
1541 info[c->where].result_use_count++;
1542 /* If we substitute an expression capture we don't know
1543 which captures this will end up using (well, we don't
1544 compute that). Force the uses to be side-effect free
1545 which means forcing the toplevels that reach the
1546 expression side-effect free. */
1547 if (info[c->where].expr_p)
1548 force_no_side_effects |= info[c->where].toplevel_msk;
1549 /* Mark CSE capture capture uses as forced to have
1550 no side-effects. */
1551 if (c->what
1552 && is_a <expr *> (c->what))
1554 info[c->where].cse_p = true;
1555 walk_result (c->what, true);
1558 else if (expr *e = dyn_cast <expr *> (o))
1560 for (unsigned i = 0; i < e->ops.length (); ++i)
1562 bool cond_p = conditional_p;
1563 if (i != 0 && *e->operation == COND_EXPR)
1564 cond_p = true;
1565 else if (*e->operation == TRUTH_ANDIF_EXPR
1566 || *e->operation == TRUTH_ORIF_EXPR)
1567 cond_p = true;
1568 walk_result (e->ops[i], cond_p);
1571 else if (c_expr *e = dyn_cast <c_expr *> (o))
1572 walk_c_expr (e);
1573 else
1574 gcc_unreachable ();
1577 /* Look for captures in the C expr E. */
1579 void
1580 capture_info::walk_c_expr (c_expr *e)
1582 /* Give up for C exprs mentioning captures not inside TREE_TYPE (). */
1583 unsigned p_depth = 0;
1584 for (unsigned i = 0; i < e->code.length (); ++i)
1586 const cpp_token *t = &e->code[i];
1587 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
1588 if (t->type == CPP_NAME
1589 && strcmp ((const char *)CPP_HASHNODE
1590 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
1591 && n->type == CPP_OPEN_PAREN)
1592 p_depth++;
1593 else if (t->type == CPP_CLOSE_PAREN
1594 && p_depth > 0)
1595 p_depth--;
1596 else if (p_depth == 0
1597 && t->type == CPP_ATSIGN
1598 && (n->type == CPP_NUMBER
1599 || n->type == CPP_NAME)
1600 && !(n->flags & PREV_WHITE))
1602 const char *id;
1603 if (n->type == CPP_NUMBER)
1604 id = (const char *)n->val.str.text;
1605 else
1606 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
1607 info[*e->capture_ids->get(id)].force_no_side_effects_p = true;
1613 /* Code generation off the decision tree and the refered AST nodes. */
1615 bool
1616 is_conversion (id_base *op)
1618 return (*op == CONVERT_EXPR
1619 || *op == NOP_EXPR
1620 || *op == FLOAT_EXPR
1621 || *op == FIX_TRUNC_EXPR
1622 || *op == VIEW_CONVERT_EXPR);
1625 /* Get the type to be used for generating operands of OP from the
1626 various sources. */
1628 static const char *
1629 get_operand_type (id_base *op, const char *in_type,
1630 const char *expr_type,
1631 const char *other_oprnd_type)
1633 /* Generally operands whose type does not match the type of the
1634 expression generated need to know their types but match and
1635 thus can fall back to 'other_oprnd_type'. */
1636 if (is_conversion (op))
1637 return other_oprnd_type;
1638 else if (*op == REALPART_EXPR
1639 || *op == IMAGPART_EXPR)
1640 return other_oprnd_type;
1641 else if (is_a <operator_id *> (op)
1642 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
1643 return other_oprnd_type;
1644 else
1646 /* Otherwise all types should match - choose one in order of
1647 preference. */
1648 if (expr_type)
1649 return expr_type;
1650 else if (in_type)
1651 return in_type;
1652 else
1653 return other_oprnd_type;
1657 /* Generate transform code for an expression. */
1659 void
1660 expr::gen_transform (FILE *f, const char *dest, bool gimple, int depth,
1661 const char *in_type, capture_info *cinfo,
1662 dt_operand **indexes, bool)
1664 bool conversion_p = is_conversion (operation);
1665 const char *type = expr_type;
1666 char optype[64];
1667 if (type)
1668 /* If there was a type specification in the pattern use it. */
1670 else if (conversion_p)
1671 /* For conversions we need to build the expression using the
1672 outer type passed in. */
1673 type = in_type;
1674 else if (*operation == REALPART_EXPR
1675 || *operation == IMAGPART_EXPR)
1677 /* __real and __imag use the component type of its operand. */
1678 sprintf (optype, "TREE_TYPE (TREE_TYPE (ops%d[0]))", depth);
1679 type = optype;
1681 else if (is_a <operator_id *> (operation)
1682 && !strcmp (as_a <operator_id *> (operation)->tcc, "tcc_comparison"))
1684 /* comparisons use boolean_type_node (or what gets in), but
1685 their operands need to figure out the types themselves. */
1686 sprintf (optype, "boolean_type_node");
1687 type = optype;
1689 else
1691 /* Other operations are of the same type as their first operand. */
1692 sprintf (optype, "TREE_TYPE (ops%d[0])", depth);
1693 type = optype;
1695 if (!type)
1696 fatal ("two conversions in a row");
1698 fprintf (f, "{\n");
1699 fprintf (f, " tree ops%d[%u], res;\n", depth, ops.length ());
1700 char op0type[64];
1701 snprintf (op0type, 64, "TREE_TYPE (ops%d[0])", depth);
1702 for (unsigned i = 0; i < ops.length (); ++i)
1704 char dest[32];
1705 snprintf (dest, 32, " ops%d[%u]", depth, i);
1706 const char *optype
1707 = get_operand_type (operation, in_type, expr_type,
1708 i == 0 ? NULL : op0type);
1709 ops[i]->gen_transform (f, dest, gimple, depth + 1, optype, cinfo, indexes,
1710 ((!(*operation == COND_EXPR)
1711 && !(*operation == VEC_COND_EXPR))
1712 || i != 0));
1715 const char *opr;
1716 if (*operation == CONVERT_EXPR)
1717 opr = "NOP_EXPR";
1718 else
1719 opr = operation->id;
1721 if (gimple)
1723 /* ??? Have another helper that is like gimple_build but may
1724 fail if seq == NULL. */
1725 fprintf (f, " if (!seq)\n"
1726 " {\n"
1727 " res = gimple_simplify (%s, %s", opr, type);
1728 for (unsigned i = 0; i < ops.length (); ++i)
1729 fprintf (f, ", ops%d[%u]", depth, i);
1730 fprintf (f, ", seq, valueize);\n");
1731 fprintf (f, " if (!res) return false;\n");
1732 fprintf (f, " }\n");
1733 fprintf (f, " else\n");
1734 fprintf (f, " res = gimple_build (seq, UNKNOWN_LOCATION, %s, %s",
1735 opr, type);
1736 for (unsigned i = 0; i < ops.length (); ++i)
1737 fprintf (f, ", ops%d[%u]", depth, i);
1738 fprintf (f, ", valueize);\n");
1740 else
1742 if (operation->kind == id_base::CODE)
1743 fprintf (f, " res = fold_build%d_loc (loc, %s, %s",
1744 ops.length(), opr, type);
1745 else
1746 fprintf (f, " res = build_call_expr_loc (loc, "
1747 "builtin_decl_implicit (%s), %d", opr, ops.length());
1748 for (unsigned i = 0; i < ops.length (); ++i)
1749 fprintf (f, ", ops%d[%u]", depth, i);
1750 fprintf (f, ");\n");
1752 fprintf (f, " %s = res;\n", dest);
1753 fprintf (f, "}\n");
1756 /* Generate code for a c_expr which is either the expression inside
1757 an if statement or a sequence of statements which computes a
1758 result to be stored to DEST. */
1760 void
1761 c_expr::gen_transform (FILE *f, const char *dest,
1762 bool, int, const char *, capture_info *,
1763 dt_operand **, bool)
1765 if (dest && nr_stmts == 1)
1766 fprintf (f, "%s = ", dest);
1768 unsigned stmt_nr = 1;
1769 for (unsigned i = 0; i < code.length (); ++i)
1771 const cpp_token *token = &code[i];
1773 /* Replace captures for code-gen. */
1774 if (token->type == CPP_ATSIGN)
1776 const cpp_token *n = &code[i+1];
1777 if ((n->type == CPP_NUMBER
1778 || n->type == CPP_NAME)
1779 && !(n->flags & PREV_WHITE))
1781 if (token->flags & PREV_WHITE)
1782 fputc (' ', f);
1783 const char *id;
1784 if (n->type == CPP_NUMBER)
1785 id = (const char *)n->val.str.text;
1786 else
1787 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
1788 fprintf (f, "captures[%u]", *capture_ids->get(id));
1789 ++i;
1790 continue;
1794 if (token->flags & PREV_WHITE)
1795 fputc (' ', f);
1797 if (token->type == CPP_NAME)
1799 const char *id = (const char *) NODE_NAME (token->val.node.node);
1800 unsigned j;
1801 for (j = 0; j < ids.length (); ++j)
1803 if (strcmp (id, ids[j].id) == 0)
1805 fprintf (f, "%s", ids[j].oper);
1806 break;
1809 if (j < ids.length ())
1810 continue;
1813 /* Output the token as string. */
1814 char *tk = (char *)cpp_token_as_text (r, token);
1815 fputs (tk, f);
1817 if (token->type == CPP_SEMICOLON)
1819 stmt_nr++;
1820 if (dest && stmt_nr == nr_stmts)
1821 fprintf (f, "\n %s = ", dest);
1822 else
1823 fputc ('\n', f);
1828 /* Generate transform code for a capture. */
1830 void
1831 capture::gen_transform (FILE *f, const char *dest, bool gimple, int depth,
1832 const char *in_type, capture_info *cinfo,
1833 dt_operand **indexes, bool expand_compares)
1835 if (what && is_a<expr *> (what))
1837 if (indexes[where] == 0)
1839 char buf[20];
1840 sprintf (buf, "captures[%u]", where);
1841 what->gen_transform (f, buf, gimple, depth, in_type, cinfo, NULL);
1845 fprintf (f, "%s = captures[%u];\n", dest, where);
1847 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
1848 with substituting a capture of that.
1849 ??? Returning false here will also not allow any other patterns
1850 to match. */
1851 if (gimple && expand_compares
1852 && cinfo->info[where].cond_expr_cond_p)
1853 fprintf (f, "if (COMPARISON_CLASS_P (%s))\n"
1854 " {\n"
1855 " if (!seq) return false;\n"
1856 " %s = gimple_build (seq, TREE_CODE (%s),"
1857 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
1858 " TREE_OPERAND (%s, 1));\n"
1859 " }\n", dest, dest, dest, dest, dest, dest);
1862 /* Return the name of the operand representing the decision tree node.
1863 Use NAME as space to generate it. */
1865 char *
1866 dt_operand::get_name (char *name)
1868 if (!parent)
1869 sprintf (name, "t");
1870 else if (parent->level == 1)
1871 sprintf (name, "op%u", pos);
1872 else if (parent->type == dt_node::DT_MATCH)
1873 return parent->get_name (name);
1874 else
1875 sprintf (name, "o%u%u", parent->level, pos);
1876 return name;
1879 /* Fill NAME with the operand name at position POS. */
1881 void
1882 dt_operand::gen_opname (char *name, unsigned pos)
1884 if (!parent)
1885 sprintf (name, "op%u", pos);
1886 else
1887 sprintf (name, "o%u%u", level, pos);
1890 /* Generate matching code for the decision tree operand which is
1891 a predicate. */
1893 unsigned
1894 dt_operand::gen_predicate (FILE *f, const char *opname, bool gimple)
1896 predicate *p = as_a <predicate *> (op);
1898 if (p->p->matchers.exists ())
1900 /* If this is a predicate generated from a pattern mangle its
1901 name and pass on the valueize hook. */
1902 if (gimple)
1903 fprintf (f, "if (gimple_%s (%s, valueize))\n", p->p->id, opname);
1904 else
1905 fprintf (f, "if (tree_%s (%s))\n", p->p->id, opname);
1907 else
1908 fprintf (f, "if (%s (%s))\n", p->p->id, opname);
1909 fprintf (f, "{\n");
1910 return 1;
1913 /* Generate matching code for the decision tree operand which is
1914 a capture-match. */
1916 unsigned
1917 dt_operand::gen_match_op (FILE *f, const char *opname)
1919 char match_opname[20];
1920 match_dop->get_name (match_opname);
1921 fprintf (f, "if (%s == %s || operand_equal_p (%s, %s, 0))\n",
1922 opname, match_opname, opname, match_opname);
1923 fprintf (f, "{\n");
1924 return 1;
1927 /* Generate GIMPLE matching code for the decision tree operand. */
1929 unsigned
1930 dt_operand::gen_gimple_expr (FILE *f)
1932 expr *e = static_cast<expr *> (op);
1933 id_base *id = e->operation;
1934 unsigned n_ops = e->ops.length ();
1936 for (unsigned i = 0; i < n_ops; ++i)
1938 char child_opname[20];
1939 gen_opname (child_opname, i);
1941 if (id->kind == id_base::CODE)
1943 if (e->is_generic
1944 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
1945 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
1947 /* ??? If this is a memory operation we can't (and should not)
1948 match this. The only sensible operand types are
1949 SSA names and invariants. */
1950 fprintf (f, "tree %s = TREE_OPERAND (gimple_assign_rhs1 (def_stmt), %i);\n",
1951 child_opname, i);
1952 fprintf (f, "if ((TREE_CODE (%s) == SSA_NAME\n"
1953 "|| is_gimple_min_invariant (%s))\n"
1954 "&& (%s = do_valueize (valueize, %s)))\n"
1955 "{\n", child_opname, child_opname, child_opname,
1956 child_opname);
1957 continue;
1959 else
1960 fprintf (f, "tree %s = gimple_assign_rhs%u (def_stmt);\n",
1961 child_opname, i + 1);
1963 else
1964 fprintf (f, "tree %s = gimple_call_arg (def_stmt, %u);\n",
1965 child_opname, i);
1966 fprintf (f, "if ((%s = do_valueize (valueize, %s)))\n",
1967 child_opname, child_opname);
1968 fprintf (f, "{\n");
1971 return n_ops;
1974 /* Generate GENERIC matching code for the decision tree operand. */
1976 unsigned
1977 dt_operand::gen_generic_expr (FILE *f, const char *opname)
1979 expr *e = static_cast<expr *> (op);
1980 unsigned n_ops = e->ops.length ();
1982 for (unsigned i = 0; i < n_ops; ++i)
1984 char child_opname[20];
1985 gen_opname (child_opname, i);
1987 if (e->operation->kind == id_base::CODE)
1988 fprintf (f, "tree %s = TREE_OPERAND (%s, %u);\n",
1989 child_opname, opname, i);
1990 else
1991 fprintf (f, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
1992 child_opname, opname, i);
1995 return 0;
1998 /* Generate matching code for the children of the decision tree node. */
2000 void
2001 dt_node::gen_kids (FILE *f, bool gimple)
2003 auto_vec<dt_operand *> gimple_exprs;
2004 auto_vec<dt_operand *> generic_exprs;
2005 auto_vec<dt_operand *> fns;
2006 auto_vec<dt_operand *> generic_fns;
2007 auto_vec<dt_operand *> preds;
2008 auto_vec<dt_node *> others;
2009 dt_node *true_operand = NULL;
2011 for (unsigned i = 0; i < kids.length (); ++i)
2013 if (kids[i]->type == dt_node::DT_OPERAND)
2015 dt_operand *op = as_a<dt_operand *> (kids[i]);
2016 if (expr *e = dyn_cast <expr *> (op->op))
2018 if (e->ops.length () == 0
2019 && (!gimple || !(*e->operation == CONSTRUCTOR)))
2020 generic_exprs.safe_push (op);
2021 else if (e->operation->kind == id_base::FN)
2023 if (gimple)
2024 fns.safe_push (op);
2025 else
2026 generic_fns.safe_push (op);
2028 else if (e->operation->kind == id_base::PREDICATE)
2029 preds.safe_push (op);
2030 else
2032 if (gimple)
2033 gimple_exprs.safe_push (op);
2034 else
2035 generic_exprs.safe_push (op);
2038 else if (op->op->type == operand::OP_PREDICATE)
2039 others.safe_push (kids[i]);
2040 else
2041 gcc_unreachable ();
2043 else if (kids[i]->type == dt_node::DT_MATCH
2044 || kids[i]->type == dt_node::DT_SIMPLIFY)
2045 others.safe_push (kids[i]);
2046 else if (kids[i]->type == dt_node::DT_TRUE)
2047 true_operand = kids[i];
2048 else
2049 gcc_unreachable ();
2052 char buf[128];
2053 char *kid_opname = buf;
2055 unsigned exprs_len = gimple_exprs.length ();
2056 unsigned gexprs_len = generic_exprs.length ();
2057 unsigned fns_len = fns.length ();
2058 unsigned gfns_len = generic_fns.length ();
2060 if (exprs_len || fns_len || gexprs_len || gfns_len)
2062 if (exprs_len)
2063 gimple_exprs[0]->get_name (kid_opname);
2064 else if (fns_len)
2065 fns[0]->get_name (kid_opname);
2066 else if (gfns_len)
2067 generic_fns[0]->get_name (kid_opname);
2068 else
2069 generic_exprs[0]->get_name (kid_opname);
2071 fprintf (f, "switch (TREE_CODE (%s))\n"
2072 "{\n", kid_opname);
2075 if (exprs_len || fns_len)
2077 fprintf (f, "case SSA_NAME:\n");
2078 fprintf (f, "if (do_valueize (valueize, %s) != NULL_TREE)\n", kid_opname);
2079 fprintf (f, "{\n");
2080 fprintf (f, "gimple def_stmt = SSA_NAME_DEF_STMT (%s);\n", kid_opname);
2082 if (exprs_len)
2084 fprintf (f, "if (is_gimple_assign (def_stmt))\n");
2085 fprintf (f, "switch (gimple_assign_rhs_code (def_stmt))\n"
2086 "{\n");
2087 for (unsigned i = 0; i < exprs_len; ++i)
2089 expr *e = as_a <expr *> (gimple_exprs[i]->op);
2090 id_base *op = e->operation;
2091 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2092 fprintf (f, "CASE_CONVERT:\n");
2093 else
2094 fprintf (f, "case %s:\n", op->id);
2095 fprintf (f, "{\n");
2096 gimple_exprs[i]->gen (f, true);
2097 fprintf (f, "break;\n"
2098 "}\n");
2100 fprintf (f, "default:;\n"
2101 "}\n");
2104 if (fns_len)
2106 if (exprs_len)
2107 fprintf (f, "else ");
2109 fprintf (f, "if (gimple_call_builtin_p (def_stmt, BUILT_IN_NORMAL))\n"
2110 "{\n"
2111 "tree fndecl = gimple_call_fndecl (def_stmt);\n"
2112 "switch (DECL_FUNCTION_CODE (fndecl))\n"
2113 "{\n");
2115 for (unsigned i = 0; i < fns_len; ++i)
2117 expr *e = as_a <expr *>(fns[i]->op);
2118 fprintf (f, "case %s:\n"
2119 "{\n", e->operation->id);
2120 fns[i]->gen (f, true);
2121 fprintf (f, "break;\n"
2122 "}\n");
2125 fprintf (f, "default:;\n"
2126 "}\n"
2127 "}\n");
2130 fprintf (f, "}\n"
2131 "break;\n");
2134 for (unsigned i = 0; i < generic_exprs.length (); ++i)
2136 expr *e = as_a <expr *>(generic_exprs[i]->op);
2137 id_base *op = e->operation;
2138 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2139 fprintf (f, "CASE_CONVERT:\n");
2140 else
2141 fprintf (f, "case %s:\n", op->id);
2142 fprintf (f, "{\n");
2143 generic_exprs[i]->gen (f, gimple);
2144 fprintf (f, "break;\n"
2145 "}\n");
2148 if (gfns_len)
2150 fprintf (f, "case CALL_EXPR:\n"
2151 "{\n"
2152 "tree fndecl = get_callee_fndecl (%s);\n"
2153 "if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)\n"
2154 "switch (DECL_FUNCTION_CODE (fndecl))\n"
2155 "{\n", kid_opname);
2157 for (unsigned j = 0; j < generic_fns.length (); ++j)
2159 expr *e = as_a <expr *>(generic_fns[j]->op);
2160 gcc_assert (e->operation->kind == id_base::FN);
2162 fprintf (f, "case %s:\n"
2163 "{\n", e->operation->id);
2164 generic_fns[j]->gen (f, false);
2165 fprintf (f, "break;\n"
2166 "}\n");
2169 fprintf (f, "default:;\n"
2170 "}\n"
2171 "break;\n"
2172 "}\n");
2175 /* Close switch (TREE_CODE ()). */
2176 if (exprs_len || fns_len || gexprs_len || gfns_len)
2177 fprintf (f, "default:;\n"
2178 "}\n");
2180 for (unsigned i = 0; i < preds.length (); ++i)
2182 expr *e = as_a <expr *> (preds[i]->op);
2183 predicate_id *p = as_a <predicate_id *> (e->operation);
2184 preds[i]->get_name (kid_opname);
2185 fprintf (f, "tree %s_pops[%d];\n", kid_opname, p->nargs);
2186 fprintf (f, "if (%s_%s (%s, %s_pops%s))\n",
2187 gimple ? "gimple" : "tree",
2188 p->id, kid_opname, kid_opname,
2189 gimple ? ", valueize" : "");
2190 fprintf (f, "{\n");
2191 for (int j = 0; j < p->nargs; ++j)
2193 char child_opname[20];
2194 preds[i]->gen_opname (child_opname, j);
2195 fprintf (f, "tree %s = %s_pops[%d];\n", child_opname, kid_opname, j);
2197 preds[i]->gen_kids (f, gimple);
2198 fprintf (f, "}\n");
2201 for (unsigned i = 0; i < others.length (); ++i)
2202 others[i]->gen (f, gimple);
2204 if (true_operand)
2205 true_operand->gen (f, gimple);
2208 /* Generate matching code for the decision tree operand. */
2210 void
2211 dt_operand::gen (FILE *f, bool gimple)
2213 char opname[20];
2214 get_name (opname);
2216 unsigned n_braces = 0;
2218 if (type == DT_OPERAND)
2219 switch (op->type)
2221 case operand::OP_PREDICATE:
2222 n_braces = gen_predicate (f, opname, gimple);
2223 break;
2225 case operand::OP_EXPR:
2226 if (gimple)
2227 n_braces = gen_gimple_expr (f);
2228 else
2229 n_braces = gen_generic_expr (f, opname);
2230 break;
2232 default:
2233 gcc_unreachable ();
2235 else if (type == DT_TRUE)
2237 else if (type == DT_MATCH)
2238 n_braces = gen_match_op (f, opname);
2239 else
2240 gcc_unreachable ();
2242 gen_kids (f, gimple);
2244 for (unsigned i = 0; i < n_braces; ++i)
2245 fprintf (f, "}\n");
2250 /* Generate code for the '(if ...)', '(with ..)' and actual transform
2251 step of a '(simplify ...)' or '(match ...)'. This handles everything
2252 that is not part of the decision tree (simplify->match). */
2254 void
2255 dt_simplify::gen (FILE *f, bool gimple)
2257 fprintf (f, "{\n");
2258 output_line_directive (f, s->result_location);
2259 if (s->capture_max >= 0)
2260 fprintf (f, "tree captures[%u] ATTRIBUTE_UNUSED = {};\n",
2261 s->capture_max + 1);
2263 for (int i = 0; i <= s->capture_max; ++i)
2264 if (indexes[i])
2266 char opname[20];
2267 fprintf (f, "captures[%u] = %s;\n", i, indexes[i]->get_name (opname));
2270 unsigned n_braces = 0;
2271 if (s->ifexpr_vec != vNULL)
2273 for (unsigned i = 0; i < s->ifexpr_vec.length (); ++i)
2275 if_or_with &w = s->ifexpr_vec[i];
2276 if (w.is_with)
2278 fprintf (f, "{\n");
2279 output_line_directive (f, w.location);
2280 w.cexpr->gen_transform (f, NULL, true, 1, "type", NULL);
2281 n_braces++;
2283 else
2285 output_line_directive (f, w.location);
2286 fprintf (f, "if (");
2287 if (i == s->ifexpr_vec.length () - 1
2288 || s->ifexpr_vec[i+1].is_with)
2289 w.cexpr->gen_transform (f, NULL, true, 1, "type", NULL);
2290 else
2292 unsigned j = i;
2295 if (j != i)
2297 fprintf (f, "\n");
2298 output_line_directive (f, s->ifexpr_vec[j].location);
2299 fprintf (f, "&& ");
2301 fprintf (f, "(");
2302 s->ifexpr_vec[j].cexpr->gen_transform (f, NULL,
2303 true, 1, "type",
2304 NULL);
2305 fprintf (f, ")");
2306 ++j;
2308 while (j < s->ifexpr_vec.length ()
2309 && !s->ifexpr_vec[j].is_with);
2310 i = j - 1;
2312 fprintf (f, ")\n");
2315 fprintf (f, "{\n");
2316 n_braces++;
2319 /* Analyze captures and perform early-outs on the incoming arguments
2320 that cover cases we cannot handle. */
2321 capture_info cinfo (s);
2322 expr *e;
2323 if (!gimple
2324 && s->result
2325 && !((e = dyn_cast <expr *> (s->result))
2326 && is_a <predicate_id *> (e->operation)))
2328 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
2329 if (cinfo.force_no_side_effects & (1 << i))
2330 fprintf (f, "if (TREE_SIDE_EFFECTS (op%d)) return NULL_TREE;\n", i);
2331 for (int i = 0; i <= s->capture_max; ++i)
2332 if (cinfo.info[i].cse_p)
2334 else if (cinfo.info[i].force_no_side_effects_p
2335 && (cinfo.info[i].toplevel_msk
2336 & cinfo.force_no_side_effects) == 0)
2337 fprintf (f, "if (TREE_SIDE_EFFECTS (captures[%d])) "
2338 "return NULL_TREE;\n", i);
2339 else if ((cinfo.info[i].toplevel_msk
2340 & cinfo.force_no_side_effects) != 0)
2341 /* Mark capture as having no side-effects if we had to verify
2342 that via forced toplevel operand checks. */
2343 cinfo.info[i].force_no_side_effects_p = true;
2346 fprintf (f, "if (dump_file && (dump_flags & TDF_DETAILS)) "
2347 "fprintf (dump_file, \"Applying pattern ");
2348 output_line_directive (f, s->result_location, true);
2349 fprintf (f, ", %%s:%%d\\n\", __FILE__, __LINE__);\n");
2351 operand *result = s->result;
2352 if (!result)
2354 /* If there is no result then this is a predicate implementation. */
2355 fprintf (f, "return true;\n");
2357 else if (gimple)
2359 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
2360 in outermost position). */
2361 if (result->type == operand::OP_EXPR
2362 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
2363 result = as_a <expr *> (result)->ops[0];
2364 if (result->type == operand::OP_EXPR)
2366 expr *e = as_a <expr *> (result);
2367 bool is_predicate = is_a <predicate_id *> (e->operation);
2368 if (!is_predicate)
2369 fprintf (f, "*res_code = %s;\n",
2370 *e->operation == CONVERT_EXPR
2371 ? "NOP_EXPR" : e->operation->id);
2372 for (unsigned j = 0; j < e->ops.length (); ++j)
2374 char dest[32];
2375 snprintf (dest, 32, " res_ops[%d]", j);
2376 const char *optype
2377 = get_operand_type (e->operation,
2378 "type", e->expr_type,
2379 j == 0
2380 ? NULL : "TREE_TYPE (res_ops[0])");
2381 /* We need to expand GENERIC conditions we captured from
2382 COND_EXPRs. */
2383 bool expand_generic_cond_exprs_p
2384 = (!is_predicate
2385 /* But avoid doing that if the GENERIC condition is
2386 valid - which it is in the first operand of COND_EXPRs
2387 and VEC_COND_EXRPs. */
2388 && ((!(*e->operation == COND_EXPR)
2389 && !(*e->operation == VEC_COND_EXPR))
2390 || j != 0));
2391 e->ops[j]->gen_transform (f, dest, true, 1, optype, &cinfo,
2392 indexes, expand_generic_cond_exprs_p);
2395 /* Re-fold the toplevel result. It's basically an embedded
2396 gimple_build w/o actually building the stmt. */
2397 if (!is_predicate)
2398 fprintf (f, "gimple_resimplify%d (seq, res_code, type, "
2399 "res_ops, valueize);\n", e->ops.length ());
2401 else if (result->type == operand::OP_CAPTURE
2402 || result->type == operand::OP_C_EXPR)
2404 result->gen_transform (f, "res_ops[0]", true, 1, "type",
2405 &cinfo, indexes, false);
2406 fprintf (f, "*res_code = TREE_CODE (res_ops[0]);\n");
2407 if (is_a <capture *> (result)
2408 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
2410 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2411 with substituting a capture of that. */
2412 fprintf (f, "if (COMPARISON_CLASS_P (res_ops[0]))\n"
2413 " {\n"
2414 " tree tem = res_ops[0];\n"
2415 " res_ops[0] = TREE_OPERAND (tem, 0);\n"
2416 " res_ops[1] = TREE_OPERAND (tem, 1);\n"
2417 " }\n");
2420 else
2421 gcc_unreachable ();
2422 fprintf (f, "return true;\n");
2424 else /* GENERIC */
2426 bool is_predicate = false;
2427 if (result->type == operand::OP_EXPR)
2429 expr *e = as_a <expr *> (result);
2430 is_predicate = is_a <predicate_id *> (e->operation);
2431 /* Search for captures used multiple times in the result expression
2432 and dependent on TREE_SIDE_EFFECTS emit a SAVE_EXPR. */
2433 if (!is_predicate)
2434 for (int i = 0; i < s->capture_max + 1; ++i)
2436 if (!cinfo.info[i].force_no_side_effects_p
2437 && cinfo.info[i].result_use_count > 1)
2438 fprintf (f, " if (TREE_SIDE_EFFECTS (captures[%d]))\n"
2439 " captures[%d] = save_expr (captures[%d]);\n",
2440 i, i, i);
2442 for (unsigned j = 0; j < e->ops.length (); ++j)
2444 char dest[32];
2445 if (is_predicate)
2446 snprintf (dest, 32, "res_ops[%d]", j);
2447 else
2449 fprintf (f, " tree res_op%d;\n", j);
2450 snprintf (dest, 32, " res_op%d", j);
2452 const char *optype
2453 = get_operand_type (e->operation,
2454 "type", e->expr_type,
2455 j == 0
2456 ? NULL : "TREE_TYPE (res_op0)");
2457 e->ops[j]->gen_transform (f, dest, false, 1, optype,
2458 &cinfo, indexes);
2460 if (is_predicate)
2461 fprintf (f, "return true;\n");
2462 else
2464 fprintf (f, " tree res;\n");
2465 /* Re-fold the toplevel result. Use non_lvalue to
2466 build NON_LVALUE_EXPRs so they get properly
2467 ignored when in GIMPLE form. */
2468 if (*e->operation == NON_LVALUE_EXPR)
2469 fprintf (f, " res = non_lvalue_loc (loc, res_op0);\n");
2470 else
2472 if (e->operation->kind == id_base::CODE)
2473 fprintf (f, " res = fold_build%d_loc (loc, %s, type",
2474 e->ops.length (),
2475 *e->operation == CONVERT_EXPR
2476 ? "NOP_EXPR" : e->operation->id);
2477 else
2478 fprintf (f, " res = build_call_expr_loc "
2479 "(loc, builtin_decl_implicit (%s), %d",
2480 e->operation->id, e->ops.length());
2481 for (unsigned j = 0; j < e->ops.length (); ++j)
2482 fprintf (f, ", res_op%d", j);
2483 fprintf (f, ");\n");
2487 else if (result->type == operand::OP_CAPTURE
2488 || result->type == operand::OP_C_EXPR)
2491 fprintf (f, " tree res;\n");
2492 s->result->gen_transform (f, " res", false, 1, "type",
2493 &cinfo, indexes);
2495 else
2496 gcc_unreachable ();
2497 if (!is_predicate)
2499 /* Search for captures not used in the result expression and dependent
2500 on TREE_SIDE_EFFECTS emit omit_one_operand. */
2501 for (int i = 0; i < s->capture_max + 1; ++i)
2503 if (!cinfo.info[i].force_no_side_effects_p
2504 && !cinfo.info[i].expr_p
2505 && cinfo.info[i].result_use_count == 0)
2506 fprintf (f, " if (TREE_SIDE_EFFECTS (captures[%d]))\n"
2507 " res = build2_loc (loc, COMPOUND_EXPR, type,"
2508 " fold_ignored_result (captures[%d]), res);\n",
2509 i, i);
2511 fprintf (f, " return res;\n");
2515 for (unsigned i = 0; i < n_braces; ++i)
2516 fprintf (f, "}\n");
2518 fprintf (f, "}\n");
2521 /* Main entry to generate code for matching GIMPLE IL off the decision
2522 tree. */
2524 void
2525 decision_tree::gen_gimple (FILE *f)
2527 for (unsigned n = 1; n <= 3; ++n)
2529 fprintf (f, "\nstatic bool\n"
2530 "gimple_simplify (code_helper *res_code, tree *res_ops,\n"
2531 " gimple_seq *seq, tree (*valueize)(tree),\n"
2532 " code_helper code, tree type");
2533 for (unsigned i = 0; i < n; ++i)
2534 fprintf (f, ", tree op%d", i);
2535 fprintf (f, ")\n");
2536 fprintf (f, "{\n");
2538 fprintf (f, "switch (code.get_rep())\n"
2539 "{\n");
2540 for (unsigned i = 0; i < root->kids.length (); i++)
2542 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
2543 expr *e = static_cast<expr *>(dop->op);
2544 if (e->ops.length () != n)
2545 continue;
2547 if (*e->operation == CONVERT_EXPR
2548 || *e->operation == NOP_EXPR)
2549 fprintf (f, "CASE_CONVERT:\n");
2550 else
2551 fprintf (f, "case %s%s:\n",
2552 is_a <fn_id *> (e->operation) ? "-" : "",
2553 e->operation->id);
2554 fprintf (f, "{\n");
2555 dop->gen_kids (f, true);
2556 fprintf (f, "break;\n");
2557 fprintf (f, "}\n");
2559 fprintf (f, "default:;\n"
2560 "}\n");
2562 fprintf (f, "return false;\n");
2563 fprintf (f, "}\n");
2567 /* Main entry to generate code for matching GENERIC IL off the decision
2568 tree. */
2570 void
2571 decision_tree::gen_generic (FILE *f)
2573 for (unsigned n = 1; n <= 3; ++n)
2575 fprintf (f, "\ntree\n"
2576 "generic_simplify (location_t loc, enum tree_code code, "
2577 "tree type ATTRIBUTE_UNUSED");
2578 for (unsigned i = 0; i < n; ++i)
2579 fprintf (f, ", tree op%d", i);
2580 fprintf (f, ")\n");
2581 fprintf (f, "{\n");
2583 fprintf (f, "switch (code)\n"
2584 "{\n");
2585 for (unsigned i = 0; i < root->kids.length (); i++)
2587 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
2588 expr *e = static_cast<expr *>(dop->op);
2589 if (e->ops.length () != n
2590 /* Builtin simplifications are somewhat premature on
2591 GENERIC. The following drops patterns with outermost
2592 calls. It's easy to emit overloads for function code
2593 though if necessary. */
2594 || e->operation->kind != id_base::CODE)
2595 continue;
2597 operator_id *op_id = static_cast <operator_id *> (e->operation);
2598 if (op_id->code == NOP_EXPR || op_id->code == CONVERT_EXPR)
2599 fprintf (f, "CASE_CONVERT:\n");
2600 else
2601 fprintf (f, "case %s:\n", e->operation->id);
2602 fprintf (f, "{\n");
2603 dop->gen_kids (f, false);
2604 fprintf (f, "break;\n"
2605 "}\n");
2607 fprintf (f, "default:;\n"
2608 "}\n");
2610 fprintf (f, "return NULL_TREE;\n");
2611 fprintf (f, "}\n");
2615 /* Output code to implement the predicate P from the decision tree DT. */
2617 void
2618 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
2620 fprintf (f, "\nbool\n"
2621 "%s%s (tree t%s%s)\n"
2622 "{\n", gimple ? "gimple_" : "tree_", p->id,
2623 p->nargs > 0 ? ", tree *res_ops" : "",
2624 gimple ? ", tree (*valueize)(tree)" : "");
2625 /* Conveniently make 'type' available. */
2626 fprintf (f, "tree type = TREE_TYPE (t);\n");
2628 if (!gimple)
2629 fprintf (f, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
2630 dt.root->gen_kids (f, gimple);
2632 fprintf (f, "return false;\n"
2633 "}\n");
2636 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
2638 static void
2639 write_header (FILE *f, const char *head)
2641 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
2642 fprintf (f, " a IL pattern matching and simplification description. */\n");
2644 /* Include the header instead of writing it awkwardly quoted here. */
2645 fprintf (f, "\n#include \"%s\"\n", head);
2650 /* AST parsing. */
2652 class parser
2654 public:
2655 parser (cpp_reader *);
2657 private:
2658 const cpp_token *next ();
2659 const cpp_token *peek ();
2660 const cpp_token *peek_ident (const char * = NULL);
2661 const cpp_token *expect (enum cpp_ttype);
2662 void eat_token (enum cpp_ttype);
2663 const char *get_string ();
2664 const char *get_ident ();
2665 void eat_ident (const char *);
2666 const char *get_number ();
2668 id_base *parse_operation ();
2669 operand *parse_capture (operand *);
2670 operand *parse_expr ();
2671 c_expr *parse_c_expr (cpp_ttype);
2672 operand *parse_op ();
2674 void parse_pattern ();
2675 void parse_simplify (source_location, vec<simplify *>&, predicate_id *,
2676 expr *);
2677 void parse_for (source_location);
2678 void parse_if (source_location);
2679 void parse_predicates (source_location);
2680 void parse_operator_list (source_location);
2682 cpp_reader *r;
2683 vec<if_or_with> active_ifs;
2684 vec<vec<user_id *> > active_fors;
2686 cid_map_t *capture_ids;
2688 public:
2689 vec<simplify *> simplifiers;
2690 vec<predicate_id *> user_predicates;
2691 bool parsing_match_operand;
2694 /* Lexing helpers. */
2696 /* Read the next non-whitespace token from R. */
2698 const cpp_token *
2699 parser::next ()
2701 const cpp_token *token;
2704 token = cpp_get_token (r);
2706 while (token->type == CPP_PADDING
2707 && token->type != CPP_EOF);
2708 return token;
2711 /* Peek at the next non-whitespace token from R. */
2713 const cpp_token *
2714 parser::peek ()
2716 const cpp_token *token;
2717 unsigned i = 0;
2720 token = cpp_peek_token (r, i++);
2722 while (token->type == CPP_PADDING
2723 && token->type != CPP_EOF);
2724 /* If we peek at EOF this is a fatal error as it leaves the
2725 cpp_reader in unusable state. Assume we really wanted a
2726 token and thus this EOF is unexpected. */
2727 if (token->type == CPP_EOF)
2728 fatal_at (token, "unexpected end of file");
2729 return token;
2732 /* Peek at the next identifier token (or return NULL if the next
2733 token is not an identifier or equal to ID if supplied). */
2735 const cpp_token *
2736 parser::peek_ident (const char *id)
2738 const cpp_token *token = peek ();
2739 if (token->type != CPP_NAME)
2740 return 0;
2742 if (id == 0)
2743 return token;
2745 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
2746 if (strcmp (id, t) == 0)
2747 return token;
2749 return 0;
2752 /* Read the next token from R and assert it is of type TK. */
2754 const cpp_token *
2755 parser::expect (enum cpp_ttype tk)
2757 const cpp_token *token = next ();
2758 if (token->type != tk)
2759 fatal_at (token, "expected %s, got %s",
2760 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
2762 return token;
2765 /* Consume the next token from R and assert it is of type TK. */
2767 void
2768 parser::eat_token (enum cpp_ttype tk)
2770 expect (tk);
2773 /* Read the next token from R and assert it is of type CPP_STRING and
2774 return its value. */
2776 const char *
2777 parser::get_string ()
2779 const cpp_token *token = expect (CPP_STRING);
2780 return (const char *)token->val.str.text;
2783 /* Read the next token from R and assert it is of type CPP_NAME and
2784 return its value. */
2786 const char *
2787 parser::get_ident ()
2789 const cpp_token *token = expect (CPP_NAME);
2790 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
2793 /* Eat an identifier token with value S from R. */
2795 void
2796 parser::eat_ident (const char *s)
2798 const cpp_token *token = peek ();
2799 const char *t = get_ident ();
2800 if (strcmp (s, t) != 0)
2801 fatal_at (token, "expected '%s' got '%s'\n", s, t);
2804 /* Read the next token from R and assert it is of type CPP_NUMBER and
2805 return its value. */
2807 const char *
2808 parser::get_number ()
2810 const cpp_token *token = expect (CPP_NUMBER);
2811 return (const char *)token->val.str.text;
2815 /* Parse the operator ID, special-casing convert?, convert1? and
2816 convert2? */
2818 id_base *
2819 parser::parse_operation ()
2821 const cpp_token *id_tok = peek ();
2822 const char *id = get_ident ();
2823 const cpp_token *token = peek ();
2824 if (strcmp (id, "convert0") == 0)
2825 fatal_at (id_tok, "use 'convert?' here");
2826 if (token->type == CPP_QUERY
2827 && !(token->flags & PREV_WHITE))
2829 if (strcmp (id, "convert") == 0)
2830 id = "convert0";
2831 else if (strcmp (id, "convert1") == 0)
2833 else if (strcmp (id, "convert2") == 0)
2835 else
2836 fatal_at (id_tok, "non-convert operator conditionalized");
2838 if (!parsing_match_operand)
2839 fatal_at (id_tok, "conditional convert can only be used in "
2840 "match expression");
2841 eat_token (CPP_QUERY);
2843 else if (strcmp (id, "convert1") == 0
2844 || strcmp (id, "convert2") == 0)
2845 fatal_at (id_tok, "expected '?' after conditional operator");
2846 id_base *op = get_operator (id);
2847 if (!op)
2848 fatal_at (id_tok, "unknown operator %s", id);
2850 user_id *p = dyn_cast<user_id *> (op);
2851 if (p && p->is_oper_list)
2852 fatal_at (id_tok, "operator-list not allowed in expression");
2854 return op;
2857 /* Parse a capture.
2858 capture = '@'<number> */
2860 struct operand *
2861 parser::parse_capture (operand *op)
2863 eat_token (CPP_ATSIGN);
2864 const cpp_token *token = peek ();
2865 const char *id = NULL;
2866 if (token->type == CPP_NUMBER)
2867 id = get_number ();
2868 else if (token->type == CPP_NAME)
2869 id = get_ident ();
2870 else
2871 fatal_at (token, "expected number or identifier");
2872 unsigned next_id = capture_ids->elements ();
2873 bool existed;
2874 unsigned &num = capture_ids->get_or_insert (id, &existed);
2875 if (!existed)
2876 num = next_id;
2877 return new capture (num, op);
2880 /* Parse an expression
2881 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
2883 struct operand *
2884 parser::parse_expr ()
2886 expr *e = new expr (parse_operation ());
2887 const cpp_token *token = peek ();
2888 operand *op;
2889 bool is_commutative = false;
2890 const char *expr_type = NULL;
2892 if (token->type == CPP_COLON
2893 && !(token->flags & PREV_WHITE))
2895 eat_token (CPP_COLON);
2896 token = peek ();
2897 if (token->type == CPP_NAME
2898 && !(token->flags & PREV_WHITE))
2900 const char *s = get_ident ();
2901 if (s[0] == 'c' && !s[1])
2903 if (!parsing_match_operand)
2904 fatal_at (token,
2905 "flag 'c' can only be used in match expression");
2906 is_commutative = true;
2908 else if (s[1] != '\0')
2910 if (parsing_match_operand)
2911 fatal_at (token, "type can only be used in result expression");
2912 expr_type = s;
2914 else
2915 fatal_at (token, "flag %s not recognized", s);
2917 token = peek ();
2919 else
2920 fatal_at (token, "expected flag or type specifying identifier");
2923 if (token->type == CPP_ATSIGN
2924 && !(token->flags & PREV_WHITE))
2925 op = parse_capture (e);
2926 else
2927 op = e;
2930 const cpp_token *token = peek ();
2931 if (token->type == CPP_CLOSE_PAREN)
2933 if (e->operation->nargs != -1
2934 && e->operation->nargs != (int) e->ops.length ())
2935 fatal_at (token, "'%s' expects %u operands, not %u",
2936 e->operation->id, e->operation->nargs, e->ops.length ());
2937 if (is_commutative)
2939 if (e->ops.length () == 2)
2940 e->is_commutative = true;
2941 else
2942 fatal_at (token, "only binary operators or function with "
2943 "two arguments can be marked commutative");
2945 e->expr_type = expr_type;
2946 return op;
2948 e->append_op (parse_op ());
2950 while (1);
2953 /* Lex native C code delimited by START recording the preprocessing tokens
2954 for later processing.
2955 c_expr = ('{'|'(') <pp token>... ('}'|')') */
2957 c_expr *
2958 parser::parse_c_expr (cpp_ttype start)
2960 const cpp_token *token;
2961 cpp_ttype end;
2962 unsigned opencnt;
2963 vec<cpp_token> code = vNULL;
2964 unsigned nr_stmts = 0;
2965 eat_token (start);
2966 if (start == CPP_OPEN_PAREN)
2967 end = CPP_CLOSE_PAREN;
2968 else if (start == CPP_OPEN_BRACE)
2969 end = CPP_CLOSE_BRACE;
2970 else
2971 gcc_unreachable ();
2972 opencnt = 1;
2975 token = next ();
2977 /* Count brace pairs to find the end of the expr to match. */
2978 if (token->type == start)
2979 opencnt++;
2980 else if (token->type == end
2981 && --opencnt == 0)
2982 break;
2984 /* This is a lame way of counting the number of statements. */
2985 if (token->type == CPP_SEMICOLON)
2986 nr_stmts++;
2988 /* If this is possibly a user-defined identifier mark it used. */
2989 if (token->type == CPP_NAME)
2990 get_operator ((const char *)CPP_HASHNODE
2991 (token->val.node.node)->ident.str);
2993 /* Record the token. */
2994 code.safe_push (*token);
2996 while (1);
2997 return new c_expr (r, code, nr_stmts, vNULL, capture_ids);
3000 /* Parse an operand which is either an expression, a predicate or
3001 a standalone capture.
3002 op = predicate | expr | c_expr | capture */
3004 struct operand *
3005 parser::parse_op ()
3007 const cpp_token *token = peek ();
3008 struct operand *op = NULL;
3009 if (token->type == CPP_OPEN_PAREN)
3011 eat_token (CPP_OPEN_PAREN);
3012 op = parse_expr ();
3013 eat_token (CPP_CLOSE_PAREN);
3015 else if (token->type == CPP_OPEN_BRACE)
3017 op = parse_c_expr (CPP_OPEN_BRACE);
3019 else
3021 /* Remaining ops are either empty or predicates */
3022 if (token->type == CPP_NAME)
3024 const char *id = get_ident ();
3025 id_base *opr = get_operator (id);
3026 if (!opr)
3027 fatal_at (token, "expected predicate name");
3028 if (operator_id *code = dyn_cast <operator_id *> (opr))
3030 if (code->nargs != 0)
3031 fatal_at (token, "using an operator with operands as predicate");
3032 /* Parse the zero-operand operator "predicates" as
3033 expression. */
3034 op = new expr (opr);
3036 else if (user_id *code = dyn_cast <user_id *> (opr))
3038 if (code->nargs != 0)
3039 fatal_at (token, "using an operator with operands as predicate");
3040 /* Parse the zero-operand operator "predicates" as
3041 expression. */
3042 op = new expr (opr);
3044 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
3045 op = new predicate (p);
3046 else
3047 fatal_at (token, "using an unsupported operator as predicate");
3048 if (!parsing_match_operand)
3049 fatal_at (token, "predicates are only allowed in match expression");
3050 token = peek ();
3051 if (token->flags & PREV_WHITE)
3052 return op;
3054 else if (token->type != CPP_COLON
3055 && token->type != CPP_ATSIGN)
3056 fatal_at (token, "expected expression or predicate");
3057 /* optionally followed by a capture and a predicate. */
3058 if (token->type == CPP_COLON)
3059 fatal_at (token, "not implemented: predicate on leaf operand");
3060 if (token->type == CPP_ATSIGN)
3061 op = parse_capture (op);
3064 return op;
3067 /* Parse
3068 simplify = 'simplify' <expr> <result-op>
3070 match = 'match' <ident> <expr> [<result-op>]
3071 with
3072 <result-op> = <op> | <if> | <with>
3073 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
3074 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
3075 and fill SIMPLIFIERS with the results. */
3077 void
3078 parser::parse_simplify (source_location match_location,
3079 vec<simplify *>& simplifiers, predicate_id *matcher,
3080 expr *result)
3082 /* Reset the capture map. */
3083 capture_ids = new cid_map_t;
3085 const cpp_token *loc = peek ();
3086 parsing_match_operand = true;
3087 struct operand *match = parse_op ();
3088 parsing_match_operand = false;
3089 if (match->type == operand::OP_CAPTURE && !matcher)
3090 fatal_at (loc, "outermost expression cannot be captured");
3091 if (match->type == operand::OP_EXPR
3092 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
3093 fatal_at (loc, "outermost expression cannot be a predicate");
3095 const cpp_token *token = peek ();
3097 /* If this if is immediately closed then it is part of a predicate
3098 definition. Push it. */
3099 if (token->type == CPP_CLOSE_PAREN)
3101 if (!matcher)
3102 fatal_at (token, "expected transform expression");
3103 simplifiers.safe_push
3104 (new simplify (match, match_location, result, token->src_loc,
3105 active_ifs.copy (), active_fors.copy (),
3106 capture_ids));
3107 return;
3110 unsigned active_ifs_len = active_ifs.length ();
3111 while (1)
3113 if (token->type == CPP_OPEN_PAREN)
3115 source_location paren_loc = token->src_loc;
3116 eat_token (CPP_OPEN_PAREN);
3117 if (peek_ident ("if"))
3119 eat_ident ("if");
3120 active_ifs.safe_push (if_or_with (parse_c_expr (CPP_OPEN_PAREN),
3121 token->src_loc, false));
3122 /* If this if is immediately closed then it contains a
3123 manual matcher or is part of a predicate definition.
3124 Push it. */
3125 if (peek ()->type == CPP_CLOSE_PAREN)
3127 if (!matcher)
3128 fatal_at (token, "manual transform not implemented");
3129 simplifiers.safe_push
3130 (new simplify (match, match_location, result,
3131 paren_loc, active_ifs.copy (),
3132 active_fors.copy (), capture_ids));
3135 else if (peek_ident ("with"))
3137 eat_ident ("with");
3138 /* Parse (with c-expr expr) as (if-with (true) expr). */
3139 c_expr *e = parse_c_expr (CPP_OPEN_BRACE);
3140 e->nr_stmts = 0;
3141 active_ifs.safe_push (if_or_with (e, token->src_loc, true));
3143 else
3145 operand *op = result;
3146 if (!matcher)
3147 op = parse_expr ();
3148 simplifiers.safe_push
3149 (new simplify (match, match_location, op,
3150 token->src_loc, active_ifs.copy (),
3151 active_fors.copy (), capture_ids));
3152 eat_token (CPP_CLOSE_PAREN);
3153 /* A "default" result closes the enclosing scope. */
3154 if (active_ifs.length () > active_ifs_len)
3156 eat_token (CPP_CLOSE_PAREN);
3157 active_ifs.pop ();
3159 else
3160 return;
3163 else if (token->type == CPP_CLOSE_PAREN)
3165 /* Close a scope if requested. */
3166 if (active_ifs.length () > active_ifs_len)
3168 eat_token (CPP_CLOSE_PAREN);
3169 active_ifs.pop ();
3170 token = peek ();
3172 else
3173 return;
3175 else
3177 if (matcher)
3178 fatal_at (token, "expected match operand expression");
3179 simplifiers.safe_push
3180 (new simplify (match, match_location,
3181 matcher ? result : parse_op (),
3182 token->src_loc, active_ifs.copy (),
3183 active_fors.copy (), capture_ids));
3184 /* A "default" result closes the enclosing scope. */
3185 if (active_ifs.length () > active_ifs_len)
3187 eat_token (CPP_CLOSE_PAREN);
3188 active_ifs.pop ();
3190 else
3191 return;
3193 token = peek ();
3197 /* Parsing of the outer control structures. */
3199 /* Parse a for expression
3200 for = '(' 'for' <subst>... <pattern> ')'
3201 subst = <ident> '(' <ident>... ')' */
3203 void
3204 parser::parse_for (source_location)
3206 auto_vec<const cpp_token *> user_id_tokens;
3207 vec<user_id *> user_ids = vNULL;
3208 const cpp_token *token;
3209 unsigned min_n_opers = 0, max_n_opers = 0;
3211 while (1)
3213 token = peek ();
3214 if (token->type != CPP_NAME)
3215 break;
3217 /* Insert the user defined operators into the operator hash. */
3218 const char *id = get_ident ();
3219 if (get_operator (id) != NULL)
3220 fatal_at (token, "operator already defined");
3221 user_id *op = new user_id (id);
3222 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
3223 *slot = op;
3224 user_ids.safe_push (op);
3225 user_id_tokens.safe_push (token);
3227 eat_token (CPP_OPEN_PAREN);
3229 int arity = -1;
3230 while ((token = peek_ident ()) != 0)
3232 const char *oper = get_ident ();
3233 id_base *idb = get_operator (oper);
3234 if (idb == NULL)
3235 fatal_at (token, "no such operator '%s'", oper);
3236 if (*idb == CONVERT0 || *idb == CONVERT1 || *idb == CONVERT2)
3237 fatal_at (token, "conditional operators cannot be used inside for");
3239 if (arity == -1)
3240 arity = idb->nargs;
3241 else if (idb->nargs == -1)
3243 else if (idb->nargs != arity)
3244 fatal_at (token, "operator '%s' with arity %d does not match "
3245 "others with arity %d", oper, idb->nargs, arity);
3247 user_id *p = dyn_cast<user_id *> (idb);
3248 if (p && p->is_oper_list)
3249 op->substitutes.safe_splice (p->substitutes);
3250 else
3251 op->substitutes.safe_push (idb);
3253 op->nargs = arity;
3254 token = expect (CPP_CLOSE_PAREN);
3256 unsigned nsubstitutes = op->substitutes.length ();
3257 if (nsubstitutes == 0)
3258 fatal_at (token, "A user-defined operator must have at least "
3259 "one substitution");
3260 if (max_n_opers == 0)
3262 min_n_opers = nsubstitutes;
3263 max_n_opers = nsubstitutes;
3265 else
3267 if (nsubstitutes % min_n_opers != 0
3268 && min_n_opers % nsubstitutes != 0)
3269 fatal_at (token, "All user-defined identifiers must have a "
3270 "multiple number of operator substitutions of the "
3271 "smallest number of substitutions");
3272 if (nsubstitutes < min_n_opers)
3273 min_n_opers = nsubstitutes;
3274 else if (nsubstitutes > max_n_opers)
3275 max_n_opers = nsubstitutes;
3279 unsigned n_ids = user_ids.length ();
3280 if (n_ids == 0)
3281 fatal_at (token, "for requires at least one user-defined identifier");
3283 token = peek ();
3284 if (token->type == CPP_CLOSE_PAREN)
3285 fatal_at (token, "no pattern defined in for");
3287 active_fors.safe_push (user_ids);
3288 while (1)
3290 token = peek ();
3291 if (token->type == CPP_CLOSE_PAREN)
3292 break;
3293 parse_pattern ();
3295 active_fors.pop ();
3297 /* Remove user-defined operators from the hash again. */
3298 for (unsigned i = 0; i < user_ids.length (); ++i)
3300 if (!user_ids[i]->used)
3301 warning_at (user_id_tokens[i],
3302 "operator %s defined but not used", user_ids[i]->id);
3303 operators->remove_elt (user_ids[i]);
3307 /* Parse an identifier associated with a list of operators.
3308 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
3310 void
3311 parser::parse_operator_list (source_location)
3313 const cpp_token *token = peek ();
3314 const char *id = get_ident ();
3316 if (get_operator (id) != 0)
3317 fatal_at (token, "operator %s already defined", id);
3319 user_id *op = new user_id (id, true);
3320 int arity = -1;
3322 while ((token = peek_ident ()) != 0)
3324 token = peek ();
3325 const char *oper = get_ident ();
3326 id_base *idb = get_operator (oper);
3328 if (idb == 0)
3329 fatal_at (token, "no such operator '%s'", oper);
3331 if (arity == -1)
3332 arity = idb->nargs;
3333 else if (idb->nargs == -1)
3335 else if (arity != idb->nargs)
3336 fatal_at (token, "operator '%s' with arity %d does not match "
3337 "others with arity %d", oper, idb->nargs, arity);
3339 /* We allow composition of multiple operator lists. */
3340 if (user_id *p = dyn_cast<user_id *> (idb))
3341 op->substitutes.safe_splice (p->substitutes);
3342 else
3343 op->substitutes.safe_push (idb);
3346 if (op->substitutes.length () == 0)
3347 fatal_at (token, "operator-list cannot be empty");
3349 op->nargs = arity;
3350 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
3351 *slot = op;
3354 /* Parse an outer if expression.
3355 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
3357 void
3358 parser::parse_if (source_location loc)
3360 operand *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
3362 const cpp_token *token = peek ();
3363 if (token->type == CPP_CLOSE_PAREN)
3364 fatal_at (token, "no pattern defined in if");
3366 active_ifs.safe_push (if_or_with (ifexpr, loc, false));
3367 while (1)
3369 const cpp_token *token = peek ();
3370 if (token->type == CPP_CLOSE_PAREN)
3371 break;
3373 parse_pattern ();
3375 active_ifs.pop ();
3378 /* Parse a list of predefined predicate identifiers.
3379 preds = '(' 'define_predicates' <ident>... ')' */
3381 void
3382 parser::parse_predicates (source_location)
3386 const cpp_token *token = peek ();
3387 if (token->type != CPP_NAME)
3388 break;
3390 add_predicate (get_ident ());
3392 while (1);
3395 /* Parse outer control structures.
3396 pattern = <preds>|<for>|<if>|<simplify>|<match> */
3398 void
3399 parser::parse_pattern ()
3401 /* All clauses start with '('. */
3402 eat_token (CPP_OPEN_PAREN);
3403 const cpp_token *token = peek ();
3404 const char *id = get_ident ();
3405 if (strcmp (id, "simplify") == 0)
3406 parse_simplify (token->src_loc, simplifiers, NULL, NULL);
3407 else if (strcmp (id, "match") == 0)
3409 bool with_args = false;
3410 if (peek ()->type == CPP_OPEN_PAREN)
3412 eat_token (CPP_OPEN_PAREN);
3413 with_args = true;
3415 const char *name = get_ident ();
3416 id_base *id = get_operator (name);
3417 predicate_id *p;
3418 if (!id)
3420 p = add_predicate (name);
3421 user_predicates.safe_push (p);
3423 else if ((p = dyn_cast <predicate_id *> (id)))
3425 else
3426 fatal_at (token, "cannot add a match to a non-predicate ID");
3427 /* Parse (match <id> <arg>... (match-expr)) here. */
3428 expr *e = NULL;
3429 if (with_args)
3431 e = new expr (p);
3432 while (peek ()->type == CPP_ATSIGN)
3433 e->append_op (parse_capture (NULL));
3434 eat_token (CPP_CLOSE_PAREN);
3436 if (p->nargs != -1
3437 && ((e && e->ops.length () != (unsigned)p->nargs)
3438 || (!e && p->nargs != 0)))
3439 fatal_at (token, "non-matching number of match operands");
3440 p->nargs = e ? e->ops.length () : 0;
3441 parse_simplify (token->src_loc, p->matchers, p, e);
3443 else if (strcmp (id, "for") == 0)
3444 parse_for (token->src_loc);
3445 else if (strcmp (id, "if") == 0)
3446 parse_if (token->src_loc);
3447 else if (strcmp (id, "define_predicates") == 0)
3449 if (active_ifs.length () > 0
3450 || active_fors.length () > 0)
3451 fatal_at (token, "define_predicates inside if or for is not supported");
3452 parse_predicates (token->src_loc);
3454 else if (strcmp (id, "define_operator_list") == 0)
3456 if (active_ifs.length () > 0
3457 || active_fors.length () > 0)
3458 fatal_at (token, "operator-list inside if or for is not supported");
3459 parse_operator_list (token->src_loc);
3461 else
3462 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
3463 active_ifs.length () == 0 && active_fors.length () == 0
3464 ? "'define_predicates', " : "");
3466 eat_token (CPP_CLOSE_PAREN);
3469 /* Main entry of the parser. Repeatedly parse outer control structures. */
3471 parser::parser (cpp_reader *r_)
3473 r = r_;
3474 active_ifs = vNULL;
3475 active_fors = vNULL;
3476 simplifiers = vNULL;
3477 user_predicates = vNULL;
3478 parsing_match_operand = false;
3480 const cpp_token *token = next ();
3481 while (token->type != CPP_EOF)
3483 _cpp_backup_tokens (r, 1);
3484 parse_pattern ();
3485 token = next ();
3490 /* Helper for the linemap code. */
3492 static size_t
3493 round_alloc_size (size_t s)
3495 return s;
3499 /* The genmatch generator progam. It reads from a pattern description
3500 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
3503 main (int argc, char **argv)
3505 cpp_reader *r;
3507 progname = "genmatch";
3509 if (argc < 2)
3510 return 1;
3512 bool gimple = true;
3513 bool verbose = false;
3514 char *input = argv[argc-1];
3515 for (int i = 1; i < argc - 1; ++i)
3517 if (strcmp (argv[i], "--gimple") == 0)
3518 gimple = true;
3519 else if (strcmp (argv[i], "--generic") == 0)
3520 gimple = false;
3521 else if (strcmp (argv[i], "-v") == 0)
3522 verbose = true;
3523 else
3525 fprintf (stderr, "Usage: genmatch "
3526 "[--gimple] [--generic] [-v] input\n");
3527 return 1;
3531 line_table = XCNEW (struct line_maps);
3532 linemap_init (line_table, 0);
3533 line_table->reallocator = xrealloc;
3534 line_table->round_alloc_size = round_alloc_size;
3536 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
3537 cpp_callbacks *cb = cpp_get_callbacks (r);
3538 cb->error = error_cb;
3540 if (!cpp_read_main_file (r, input))
3541 return 1;
3542 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
3543 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
3545 /* Pre-seed operators. */
3546 operators = new hash_table<id_base> (1024);
3547 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
3548 add_operator (SYM, # SYM, # TYPE, NARGS);
3549 #define END_OF_BASE_TREE_CODES
3550 #include "tree.def"
3551 add_operator (CONVERT0, "CONVERT0", "tcc_unary", 1);
3552 add_operator (CONVERT1, "CONVERT1", "tcc_unary", 1);
3553 add_operator (CONVERT2, "CONVERT2", "tcc_unary", 1);
3554 #undef END_OF_BASE_TREE_CODES
3555 #undef DEFTREECODE
3557 /* Pre-seed builtin functions.
3558 ??? Cannot use N (name) as that is targetm.emultls.get_address
3559 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
3560 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
3561 add_builtin (ENUM, # ENUM);
3562 #include "builtins.def"
3563 #undef DEF_BUILTIN
3565 /* Parse ahead! */
3566 parser p (r);
3568 if (gimple)
3569 write_header (stdout, "gimple-match-head.c");
3570 else
3571 write_header (stdout, "generic-match-head.c");
3573 /* Go over all predicates defined with patterns and perform
3574 lowering and code generation. */
3575 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
3577 predicate_id *pred = p.user_predicates[i];
3578 lower (pred->matchers, gimple);
3580 if (verbose)
3581 for (unsigned i = 0; i < pred->matchers.length (); ++i)
3582 print_matches (pred->matchers[i]);
3584 decision_tree dt;
3585 for (unsigned i = 0; i < pred->matchers.length (); ++i)
3586 dt.insert (pred->matchers[i], i);
3588 if (verbose)
3589 dt.print (stderr);
3591 write_predicate (stdout, pred, dt, gimple);
3594 /* Lower the main simplifiers and generate code for them. */
3595 lower (p.simplifiers, gimple);
3597 if (verbose)
3598 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
3599 print_matches (p.simplifiers[i]);
3601 decision_tree dt;
3602 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
3603 dt.insert (p.simplifiers[i], i);
3605 if (verbose)
3606 dt.print (stderr);
3608 if (gimple)
3609 dt.gen_gimple (stdout);
3610 else
3611 dt.gen_generic (stdout);
3613 /* Finalize. */
3614 cpp_finish (r, NULL);
3615 cpp_destroy (r);
3617 delete operators;
3619 return 0;