1 /* Generate pattern matching and transform code shared between
2 GENERIC and GIMPLE folding code from match-and-simplify description.
4 Copyright (C) 2014-2015 Free Software Foundation, Inc.
5 Contributed by Richard Biener <rguenther@suse.de>
6 and Prathamesh Kulkarni <bilbotheelffriend@gmail.com>
8 This file is part of GCC.
10 GCC is free software; you can redistribute it and/or modify it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 3, or (at your option) any later
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
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/>. */
27 #include "coretypes.h"
30 #include "hash-table.h"
35 /* Stubs for GGC referenced through instantiations triggered by hash-map. */
36 void *ggc_internal_cleared_alloc (size_t, void (*)(void *),
37 size_t, size_t MEM_STAT_DECL)
41 void ggc_free (void *)
48 static struct line_maps *line_table;
51 #if GCC_VERSION >= 4001
52 __attribute__((format (printf, 6, 0)))
54 error_cb (cpp_reader *, int errtype, int, source_location location,
55 unsigned int, const char *msg, va_list *ap)
57 const line_map_ordinary *map;
58 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
59 expanded_location loc = linemap_expand_location (line_table, map, location);
60 fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
61 (errtype == CPP_DL_WARNING) ? "warning" : "error");
62 vfprintf (stderr, msg, *ap);
63 fprintf (stderr, "\n");
64 FILE *f = fopen (loc.file, "r");
70 if (!fgets (buf, 128, f))
72 if (buf[strlen (buf) - 1] != '\n')
79 fprintf (stderr, "%s", buf);
80 for (int i = 0; i < loc.column - 1; ++i)
88 if (errtype == CPP_DL_FATAL)
94 #if GCC_VERSION >= 4001
95 __attribute__((format (printf, 2, 3)))
97 fatal_at (const cpp_token *tk, const char *msg, ...)
101 error_cb (NULL, CPP_DL_FATAL, 0, tk->src_loc, 0, msg, &ap);
106 #if GCC_VERSION >= 4001
107 __attribute__((format (printf, 2, 3)))
109 fatal_at (source_location loc, const char *msg, ...)
113 error_cb (NULL, CPP_DL_FATAL, 0, loc, 0, msg, &ap);
118 #if GCC_VERSION >= 4001
119 __attribute__((format (printf, 2, 3)))
121 warning_at (const cpp_token *tk, const char *msg, ...)
125 error_cb (NULL, CPP_DL_WARNING, 0, tk->src_loc, 0, msg, &ap);
129 /* Like fprintf, but print INDENT spaces at the beginning. */
132 #if GCC_VERSION >= 4001
133 __attribute__((format (printf, 3, 4)))
135 fprintf_indent (FILE *f, unsigned int indent, const char *format, ...)
138 for (; indent >= 8; indent -= 8)
140 fprintf (f, "%*s", indent, "");
141 va_start (ap, format);
142 vfprintf (f, format, ap);
147 output_line_directive (FILE *f, source_location location,
148 bool dumpfile = false)
150 const line_map_ordinary *map;
151 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
152 expanded_location loc = linemap_expand_location (line_table, map, location);
155 /* When writing to a dumpfile only dump the filename. */
156 const char *file = strrchr (loc.file, DIR_SEPARATOR);
161 fprintf (f, "%s:%d", file, loc.line);
164 /* Other gen programs really output line directives here, at least for
165 development it's right now more convenient to have line information
166 from the generated file. Still keep the directives as comment for now
167 to easily back-point to the meta-description. */
168 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
172 /* Pull in tree codes and builtin function codes from their
175 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
188 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
189 enum built_in_function {
190 #include "builtins.def"
195 /* Return true if CODE represents a commutative tree code. Otherwise
198 commutative_tree_code (enum tree_code code)
204 case MULT_HIGHPART_EXPR:
219 case WIDEN_MULT_EXPR:
220 case VEC_WIDEN_MULT_HI_EXPR:
221 case VEC_WIDEN_MULT_LO_EXPR:
222 case VEC_WIDEN_MULT_EVEN_EXPR:
223 case VEC_WIDEN_MULT_ODD_EXPR:
232 /* Return true if CODE represents a ternary tree code for which the
233 first two operands are commutative. Otherwise return false. */
235 commutative_ternary_tree_code (enum tree_code code)
239 case WIDEN_MULT_PLUS_EXPR:
240 case WIDEN_MULT_MINUS_EXPR:
252 /* Base class for all identifiers the parser knows. */
254 struct id_base : nofree_ptr_hash<id_base>
256 enum id_kind { CODE, FN, PREDICATE, USER } kind;
258 id_base (id_kind, const char *, int = -1);
264 /* hash_table support. */
265 static inline hashval_t hash (const id_base *);
266 static inline int equal (const id_base *, const id_base *);
270 id_base::hash (const id_base *op)
276 id_base::equal (const id_base *op1,
279 return (op1->hashval == op2->hashval
280 && strcmp (op1->id, op2->id) == 0);
283 /* Hashtable of known pattern operators. This is pre-seeded from
284 all known tree codes and all known builtin function ids. */
285 static hash_table<id_base> *operators;
287 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
292 hashval = htab_hash_string (id);
295 /* Identifier that maps to a tree code. */
297 struct operator_id : public id_base
299 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
301 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
306 /* Identifier that maps to a builtin function code. */
308 struct fn_id : public id_base
310 fn_id (enum built_in_function fn_, const char *id_)
311 : id_base (id_base::FN, id_), fn (fn_) {}
312 enum built_in_function fn;
317 /* Identifier that maps to a user-defined predicate. */
319 struct predicate_id : public id_base
321 predicate_id (const char *id_)
322 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
323 vec<simplify *> matchers;
326 /* Identifier that maps to a operator defined by a 'for' directive. */
328 struct user_id : public id_base
330 user_id (const char *id_, bool is_oper_list_ = false)
331 : id_base (id_base::USER, id_), substitutes (vNULL),
332 used (false), is_oper_list (is_oper_list_) {}
333 vec<id_base *> substitutes;
341 is_a_helper <fn_id *>::test (id_base *id)
343 return id->kind == id_base::FN;
349 is_a_helper <operator_id *>::test (id_base *id)
351 return id->kind == id_base::CODE;
357 is_a_helper <predicate_id *>::test (id_base *id)
359 return id->kind == id_base::PREDICATE;
365 is_a_helper <user_id *>::test (id_base *id)
367 return id->kind == id_base::USER;
370 /* Add a predicate identifier to the hash. */
372 static predicate_id *
373 add_predicate (const char *id)
375 predicate_id *p = new predicate_id (id);
376 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
378 fatal ("duplicate id definition");
383 /* Add a tree code identifier to the hash. */
386 add_operator (enum tree_code code, const char *id,
387 const char *tcc, unsigned nargs)
389 if (strcmp (tcc, "tcc_unary") != 0
390 && strcmp (tcc, "tcc_binary") != 0
391 && strcmp (tcc, "tcc_comparison") != 0
392 && strcmp (tcc, "tcc_expression") != 0
393 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
394 && strcmp (tcc, "tcc_reference") != 0
395 /* To have INTEGER_CST and friends as "predicate operators". */
396 && strcmp (tcc, "tcc_constant") != 0
397 /* And allow CONSTRUCTOR for vector initializers. */
398 && !(code == CONSTRUCTOR))
400 /* Treat ADDR_EXPR as atom, thus don't allow matching its operand. */
401 if (code == ADDR_EXPR)
403 operator_id *op = new operator_id (code, id, nargs, tcc);
404 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
406 fatal ("duplicate id definition");
410 /* Add a builtin identifier to the hash. */
413 add_builtin (enum built_in_function code, const char *id)
415 fn_id *fn = new fn_id (code, id);
416 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
418 fatal ("duplicate id definition");
422 /* Helper for easy comparing ID with tree code CODE. */
425 operator==(id_base &id, enum tree_code code)
427 if (operator_id *oid = dyn_cast <operator_id *> (&id))
428 return oid->code == code;
432 /* Lookup the identifier ID. */
435 get_operator (const char *id)
437 id_base tem (id_base::CODE, id);
439 id_base *op = operators->find_with_hash (&tem, tem.hashval);
442 /* If this is a user-defined identifier track whether it was used. */
443 if (user_id *uid = dyn_cast<user_id *> (op))
448 /* Try all-uppercase. */
449 char *id2 = xstrdup (id);
450 for (unsigned i = 0; i < strlen (id2); ++i)
451 id2[i] = TOUPPER (id2[i]);
452 new (&tem) id_base (id_base::CODE, id2);
453 op = operators->find_with_hash (&tem, tem.hashval);
460 /* Try _EXPR appended. */
461 id2 = (char *)xrealloc (id2, strlen (id2) + sizeof ("_EXPR") + 1);
462 strcat (id2, "_EXPR");
463 new (&tem) id_base (id_base::CODE, id2);
464 op = operators->find_with_hash (&tem, tem.hashval);
474 typedef hash_map<nofree_string_hash, unsigned> cid_map_t;
477 /* The AST produced by parsing of the pattern definitions. */
482 /* The base class for operands. */
485 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR };
486 operand (enum op_type type_) : type (type_) {}
488 virtual void gen_transform (FILE *, int, const char *, bool, int,
489 const char *, capture_info *,
492 { gcc_unreachable (); }
495 /* A predicate operand. Predicates are leafs in the AST. */
497 struct predicate : public operand
499 predicate (predicate_id *p_) : operand (OP_PREDICATE), p (p_) {}
503 /* An operand that constitutes an expression. Expressions include
504 function calls and user-defined predicate invocations. */
506 struct expr : public operand
508 expr (id_base *operation_, bool is_commutative_ = false)
509 : operand (OP_EXPR), operation (operation_),
510 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
511 is_generic (false), force_single_use (false) {}
513 : operand (OP_EXPR), operation (e->operation),
514 ops (vNULL), expr_type (e->expr_type), is_commutative (e->is_commutative),
515 is_generic (e->is_generic), force_single_use (e->force_single_use) {}
516 void append_op (operand *op) { ops.safe_push (op); }
517 /* The operator and its operands. */
520 /* An explicitely specified type - used exclusively for conversions. */
521 const char *expr_type;
522 /* Whether the operation is to be applied commutatively. This is
523 later lowered to two separate patterns. */
525 /* Whether the expression is expected to be in GENERIC form. */
527 /* Whether pushing any stmt to the sequence should be conditional
528 on this expression having a single-use. */
529 bool force_single_use;
530 virtual void gen_transform (FILE *f, int, const char *, bool, int,
531 const char *, capture_info *,
532 dt_operand ** = 0, bool = true);
535 /* An operator that is represented by native C code. This is always
536 a leaf operand in the AST. This class is also used to represent
537 the code to be generated for 'if' and 'with' expressions. */
539 struct c_expr : public operand
541 /* A mapping of an identifier and its replacement. Used to apply
546 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
549 c_expr (cpp_reader *r_, vec<cpp_token> code_, unsigned nr_stmts_,
550 vec<id_tab> ids_, cid_map_t *capture_ids_)
551 : operand (OP_C_EXPR), r (r_), code (code_), capture_ids (capture_ids_),
552 nr_stmts (nr_stmts_), ids (ids_) {}
553 /* cpplib tokens and state to transform this back to source. */
556 cid_map_t *capture_ids;
557 /* The number of statements parsed (well, the number of ';'s). */
559 /* The identifier replacement vector. */
561 virtual void gen_transform (FILE *f, int, const char *, bool, int,
562 const char *, capture_info *,
563 dt_operand ** = 0, bool = true);
566 /* A wrapper around another operand that captures its value. */
568 struct capture : public operand
570 capture (unsigned where_, operand *what_)
571 : operand (OP_CAPTURE), where (where_), what (what_) {}
572 /* Identifier index for the value. */
574 /* The captured value. */
576 virtual void gen_transform (FILE *f, int, const char *, bool, int,
577 const char *, capture_info *,
578 dt_operand ** = 0, bool = true);
584 is_a_helper <capture *>::test (operand *op)
586 return op->type == operand::OP_CAPTURE;
592 is_a_helper <predicate *>::test (operand *op)
594 return op->type == operand::OP_PREDICATE;
600 is_a_helper <c_expr *>::test (operand *op)
602 return op->type == operand::OP_C_EXPR;
608 is_a_helper <expr *>::test (operand *op)
610 return op->type == operand::OP_EXPR;
613 /* Helper to distinguish 'if' from 'with' expressions. */
617 if_or_with (operand *cexpr_, source_location location_, bool is_with_)
618 : location (location_), cexpr (cexpr_), is_with (is_with_) {}
619 source_location location;
624 /* The main class of a pattern and its transform. This is used to
625 represent both (simplify ...) and (match ...) kinds. The AST
626 duplicates all outer 'if' and 'for' expressions here so each
627 simplify can exist in isolation. */
631 simplify (operand *match_, source_location match_location_,
632 struct operand *result_, source_location result_location_,
633 vec<if_or_with> ifexpr_vec_, vec<vec<user_id *> > for_vec_,
634 cid_map_t *capture_ids_)
635 : match (match_), match_location (match_location_),
636 result (result_), result_location (result_location_),
637 ifexpr_vec (ifexpr_vec_), for_vec (for_vec_),
638 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
640 /* The expression that is matched against the GENERIC or GIMPLE IL. */
642 source_location match_location;
643 /* For a (simplify ...) the expression produced when the pattern applies.
644 For a (match ...) either NULL if it is a simple predicate or the
645 single expression specifying the matched operands. */
646 struct operand *result;
647 source_location result_location;
648 /* Collected 'if' expressions that need to evaluate to true to make
649 the pattern apply. */
650 vec<if_or_with> ifexpr_vec;
651 /* Collected 'for' expression operators that have to be replaced
652 in the lowering phase. */
653 vec<vec<user_id *> > for_vec;
654 /* A map of capture identifiers to indexes. */
655 cid_map_t *capture_ids;
659 /* Debugging routines for dumping the AST. */
662 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
664 if (capture *c = dyn_cast<capture *> (o))
666 fprintf (f, "@%u", c->where);
667 if (c->what && flattened == false)
670 print_operand (c->what, f, flattened);
675 else if (predicate *p = dyn_cast<predicate *> (o))
676 fprintf (f, "%s", p->p->id);
678 else if (is_a<c_expr *> (o))
679 fprintf (f, "c_expr");
681 else if (expr *e = dyn_cast<expr *> (o))
683 fprintf (f, "(%s", e->operation->id);
685 if (flattened == false)
688 for (unsigned i = 0; i < e->ops.length (); ++i)
690 print_operand (e->ops[i], f, flattened);
702 print_matches (struct simplify *s, FILE *f = stderr)
704 fprintf (f, "for expression: ");
705 print_operand (s->match, f);
712 /* Lowering of commutative operators. */
715 cartesian_product (const vec< vec<operand *> >& ops_vector,
716 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
718 if (n == ops_vector.length ())
720 vec<operand *> xv = v.copy ();
721 result.safe_push (xv);
725 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
727 v[n] = ops_vector[n][i];
728 cartesian_product (ops_vector, result, v, n + 1);
732 /* Lower OP to two operands in case it is marked as commutative. */
734 static vec<operand *>
735 commutate (operand *op)
737 vec<operand *> ret = vNULL;
739 if (capture *c = dyn_cast <capture *> (op))
746 vec<operand *> v = commutate (c->what);
747 for (unsigned i = 0; i < v.length (); ++i)
749 capture *nc = new capture (c->where, v[i]);
755 expr *e = dyn_cast <expr *> (op);
756 if (!e || e->ops.length () == 0)
762 vec< vec<operand *> > ops_vector = vNULL;
763 for (unsigned i = 0; i < e->ops.length (); ++i)
764 ops_vector.safe_push (commutate (e->ops[i]));
766 auto_vec< vec<operand *> > result;
767 auto_vec<operand *> v (e->ops.length ());
768 v.quick_grow_cleared (e->ops.length ());
769 cartesian_product (ops_vector, result, v, 0);
772 for (unsigned i = 0; i < result.length (); ++i)
774 expr *ne = new expr (e);
775 ne->is_commutative = false;
776 for (unsigned j = 0; j < result[i].length (); ++j)
777 ne->append_op (result[i][j]);
781 if (!e->is_commutative)
784 for (unsigned i = 0; i < result.length (); ++i)
786 expr *ne = new expr (e);
787 ne->is_commutative = false;
788 // result[i].length () is 2 since e->operation is binary
789 for (unsigned j = result[i].length (); j; --j)
790 ne->append_op (result[i][j-1]);
797 /* Lower operations marked as commutative in the AST of S and push
798 the resulting patterns to SIMPLIFIERS. */
801 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
803 vec<operand *> matchers = commutate (s->match);
804 for (unsigned i = 0; i < matchers.length (); ++i)
806 simplify *ns = new simplify (matchers[i], s->match_location,
807 s->result, s->result_location, s->ifexpr_vec,
808 s->for_vec, s->capture_ids);
809 simplifiers.safe_push (ns);
813 /* Strip conditional conversios using operator OPER from O and its
814 children if STRIP, else replace them with an unconditional convert. */
817 lower_opt_convert (operand *o, enum tree_code oper,
818 enum tree_code to_oper, bool strip)
820 if (capture *c = dyn_cast<capture *> (o))
823 return new capture (c->where,
824 lower_opt_convert (c->what, oper, to_oper, strip));
829 expr *e = dyn_cast<expr *> (o);
833 if (*e->operation == oper)
836 return lower_opt_convert (e->ops[0], oper, to_oper, strip);
838 expr *ne = new expr (e);
839 ne->operation = (to_oper == CONVERT_EXPR
840 ? get_operator ("CONVERT_EXPR")
841 : get_operator ("VIEW_CONVERT_EXPR"));
842 ne->append_op (lower_opt_convert (e->ops[0], oper, to_oper, strip));
846 expr *ne = new expr (e);
847 for (unsigned i = 0; i < e->ops.length (); ++i)
848 ne->append_op (lower_opt_convert (e->ops[i], oper, to_oper, strip));
853 /* Determine whether O or its children uses the conditional conversion
857 has_opt_convert (operand *o, enum tree_code oper)
859 if (capture *c = dyn_cast<capture *> (o))
862 return has_opt_convert (c->what, oper);
867 expr *e = dyn_cast<expr *> (o);
871 if (*e->operation == oper)
874 for (unsigned i = 0; i < e->ops.length (); ++i)
875 if (has_opt_convert (e->ops[i], oper))
881 /* Lower conditional convert operators in O, expanding it to a vector
884 static vec<operand *>
885 lower_opt_convert (operand *o)
887 vec<operand *> v1 = vNULL, v2;
891 enum tree_code opers[]
892 = { CONVERT0, CONVERT_EXPR,
893 CONVERT1, CONVERT_EXPR,
894 CONVERT2, CONVERT_EXPR,
895 VIEW_CONVERT0, VIEW_CONVERT_EXPR,
896 VIEW_CONVERT1, VIEW_CONVERT_EXPR,
897 VIEW_CONVERT2, VIEW_CONVERT_EXPR };
899 /* Conditional converts are lowered to a pattern with the
900 conversion and one without. The three different conditional
901 convert codes are lowered separately. */
903 for (unsigned i = 0; i < sizeof (opers) / sizeof (enum tree_code); i += 2)
906 for (unsigned j = 0; j < v1.length (); ++j)
907 if (has_opt_convert (v1[j], opers[i]))
909 v2.safe_push (lower_opt_convert (v1[j],
910 opers[i], opers[i+1], false));
911 v2.safe_push (lower_opt_convert (v1[j],
912 opers[i], opers[i+1], true));
918 for (unsigned j = 0; j < v2.length (); ++j)
919 v1.safe_push (v2[j]);
926 /* Lower conditional convert operators in the AST of S and push
927 the resulting multiple patterns to SIMPLIFIERS. */
930 lower_opt_convert (simplify *s, vec<simplify *>& simplifiers)
932 vec<operand *> matchers = lower_opt_convert (s->match);
933 for (unsigned i = 0; i < matchers.length (); ++i)
935 simplify *ns = new simplify (matchers[i], s->match_location,
936 s->result, s->result_location, s->ifexpr_vec,
937 s->for_vec, s->capture_ids);
938 simplifiers.safe_push (ns);
942 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
943 GENERIC and a GIMPLE variant. */
945 static vec<operand *>
946 lower_cond (operand *o)
948 vec<operand *> ro = vNULL;
950 if (capture *c = dyn_cast<capture *> (o))
954 vec<operand *> lop = vNULL;
955 lop = lower_cond (c->what);
957 for (unsigned i = 0; i < lop.length (); ++i)
958 ro.safe_push (new capture (c->where, lop[i]));
963 expr *e = dyn_cast<expr *> (o);
964 if (!e || e->ops.length () == 0)
970 vec< vec<operand *> > ops_vector = vNULL;
971 for (unsigned i = 0; i < e->ops.length (); ++i)
972 ops_vector.safe_push (lower_cond (e->ops[i]));
974 auto_vec< vec<operand *> > result;
975 auto_vec<operand *> v (e->ops.length ());
976 v.quick_grow_cleared (e->ops.length ());
977 cartesian_product (ops_vector, result, v, 0);
979 for (unsigned i = 0; i < result.length (); ++i)
981 expr *ne = new expr (e);
982 for (unsigned j = 0; j < result[i].length (); ++j)
983 ne->append_op (result[i][j]);
985 /* If this is a COND with a captured expression or an
986 expression with two operands then also match a GENERIC
987 form on the compare. */
988 if ((*e->operation == COND_EXPR
989 || *e->operation == VEC_COND_EXPR)
990 && ((is_a <capture *> (e->ops[0])
991 && as_a <capture *> (e->ops[0])->what
992 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
994 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
995 || (is_a <expr *> (e->ops[0])
996 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
998 expr *ne = new expr (e);
999 for (unsigned j = 0; j < result[i].length (); ++j)
1000 ne->append_op (result[i][j]);
1001 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
1003 expr *ocmp = as_a <expr *> (c->what);
1004 expr *cmp = new expr (ocmp);
1005 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1006 cmp->append_op (ocmp->ops[j]);
1007 cmp->is_generic = true;
1008 ne->ops[0] = new capture (c->where, cmp);
1012 expr *ocmp = as_a <expr *> (ne->ops[0]);
1013 expr *cmp = new expr (ocmp);
1014 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1015 cmp->append_op (ocmp->ops[j]);
1016 cmp->is_generic = true;
1026 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1027 GENERIC and a GIMPLE variant. */
1030 lower_cond (simplify *s, vec<simplify *>& simplifiers)
1032 vec<operand *> matchers = lower_cond (s->match);
1033 for (unsigned i = 0; i < matchers.length (); ++i)
1035 simplify *ns = new simplify (matchers[i], s->match_location,
1036 s->result, s->result_location, s->ifexpr_vec,
1037 s->for_vec, s->capture_ids);
1038 simplifiers.safe_push (ns);
1042 /* In AST operand O replace operator ID with operator WITH. */
1045 replace_id (operand *o, user_id *id, id_base *with)
1047 /* Deep-copy captures and expressions, replacing operations as
1049 if (capture *c = dyn_cast<capture *> (o))
1053 return new capture (c->where, replace_id (c->what, id, with));
1055 else if (expr *e = dyn_cast<expr *> (o))
1057 expr *ne = new expr (e);
1058 if (e->operation == id)
1059 ne->operation = with;
1060 for (unsigned i = 0; i < e->ops.length (); ++i)
1061 ne->append_op (replace_id (e->ops[i], id, with));
1065 /* For c_expr we simply record a string replacement table which is
1066 applied at code-generation time. */
1067 if (c_expr *ce = dyn_cast<c_expr *> (o))
1069 vec<c_expr::id_tab> ids = ce->ids.copy ();
1070 ids.safe_push (c_expr::id_tab (id->id, with->id));
1071 return new c_expr (ce->r, ce->code, ce->nr_stmts, ids, ce->capture_ids);
1077 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
1080 lower_for (simplify *sin, vec<simplify *>& simplifiers)
1082 vec<vec<user_id *> >& for_vec = sin->for_vec;
1083 unsigned worklist_start = 0;
1084 auto_vec<simplify *> worklist;
1085 worklist.safe_push (sin);
1087 /* Lower each recorded for separately, operating on the
1088 set of simplifiers created by the previous one.
1089 Lower inner-to-outer so inner for substitutes can refer
1090 to operators replaced by outer fors. */
1091 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1093 vec<user_id *>& ids = for_vec[fi];
1094 unsigned n_ids = ids.length ();
1095 unsigned max_n_opers = 0;
1096 for (unsigned i = 0; i < n_ids; ++i)
1097 if (ids[i]->substitutes.length () > max_n_opers)
1098 max_n_opers = ids[i]->substitutes.length ();
1100 unsigned worklist_end = worklist.length ();
1101 for (unsigned si = worklist_start; si < worklist_end; ++si)
1103 simplify *s = worklist[si];
1104 for (unsigned j = 0; j < max_n_opers; ++j)
1106 operand *match_op = s->match;
1107 operand *result_op = s->result;
1108 vec<if_or_with> ifexpr_vec = s->ifexpr_vec.copy ();
1110 for (unsigned i = 0; i < n_ids; ++i)
1112 user_id *id = ids[i];
1113 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1114 match_op = replace_id (match_op, id, oper);
1116 result_op = replace_id (result_op, id, oper);
1117 for (unsigned k = 0; k < s->ifexpr_vec.length (); ++k)
1118 ifexpr_vec[k].cexpr = replace_id (ifexpr_vec[k].cexpr,
1121 simplify *ns = new simplify (match_op, s->match_location,
1122 result_op, s->result_location,
1123 ifexpr_vec, vNULL, s->capture_ids);
1124 worklist.safe_push (ns);
1127 worklist_start = worklist_end;
1130 /* Copy out the result from the last for lowering. */
1131 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1132 simplifiers.safe_push (worklist[i]);
1135 /* Lower the AST for everything in SIMPLIFIERS. */
1138 lower (vec<simplify *>& simplifiers, bool gimple)
1140 auto_vec<simplify *> out_simplifiers;
1141 for (unsigned i = 0; i < simplifiers.length (); ++i)
1142 lower_opt_convert (simplifiers[i], out_simplifiers);
1144 simplifiers.truncate (0);
1145 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1146 lower_commutative (out_simplifiers[i], simplifiers);
1148 out_simplifiers.truncate (0);
1150 for (unsigned i = 0; i < simplifiers.length (); ++i)
1151 lower_cond (simplifiers[i], out_simplifiers);
1153 out_simplifiers.safe_splice (simplifiers);
1156 simplifiers.truncate (0);
1157 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1158 lower_for (out_simplifiers[i], simplifiers);
1164 /* The decision tree built for generating GIMPLE and GENERIC pattern
1165 matching code. It represents the 'match' expression of all
1166 simplifies and has those as its leafs. */
1168 /* Decision tree base class, used for DT_TRUE and DT_NODE. */
1172 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1176 vec<dt_node *> kids;
1178 dt_node (enum dt_type type_): type (type_), level (0), kids (vNULL) {}
1180 dt_node *append_node (dt_node *);
1181 dt_node *append_op (operand *, dt_node *parent = 0, unsigned pos = 0);
1182 dt_node *append_true_op (dt_node *parent = 0, unsigned pos = 0);
1183 dt_node *append_match_op (dt_operand *, dt_node *parent = 0, unsigned pos = 0);
1184 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1186 virtual void gen (FILE *, int, bool) {}
1188 void gen_kids (FILE *, int, bool);
1189 void gen_kids_1 (FILE *, int, bool,
1190 vec<dt_operand *>, vec<dt_operand *>, vec<dt_operand *>,
1191 vec<dt_operand *>, vec<dt_operand *>, vec<dt_node *>);
1194 /* Generic decision tree node used for DT_OPERAND and DT_MATCH. */
1196 struct dt_operand : public dt_node
1199 dt_operand *match_dop;
1203 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1204 dt_operand *parent_ = 0, unsigned pos_ = 0)
1205 : dt_node (type), op (op_), match_dop (match_dop_),
1206 parent (parent_), pos (pos_) {}
1208 void gen (FILE *, int, bool);
1209 unsigned gen_predicate (FILE *, int, const char *, bool);
1210 unsigned gen_match_op (FILE *, int, const char *);
1212 unsigned gen_gimple_expr (FILE *, int);
1213 unsigned gen_generic_expr (FILE *, int, const char *);
1215 char *get_name (char *);
1216 void gen_opname (char *, unsigned);
1219 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1221 struct dt_simplify : public dt_node
1224 unsigned pattern_no;
1225 dt_operand **indexes;
1227 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1228 : dt_node (DT_SIMPLIFY), s (s_), pattern_no (pattern_no_),
1229 indexes (indexes_) {}
1231 void gen (FILE *f, int, bool);
1237 is_a_helper <dt_operand *>::test (dt_node *n)
1239 return (n->type == dt_node::DT_OPERAND
1240 || n->type == dt_node::DT_MATCH);
1243 /* A container for the actual decision tree. */
1245 struct decision_tree
1249 void insert (struct simplify *, unsigned);
1250 void gen_gimple (FILE *f = stderr);
1251 void gen_generic (FILE *f = stderr);
1252 void print (FILE *f = stderr);
1254 decision_tree () { root = new dt_node (dt_node::DT_NODE); }
1256 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1257 unsigned pos = 0, dt_node *parent = 0);
1258 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1259 static bool cmp_node (dt_node *, dt_node *);
1260 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1263 /* Compare two AST operands O1 and O2 and return true if they are equal. */
1266 cmp_operand (operand *o1, operand *o2)
1268 if (!o1 || !o2 || o1->type != o2->type)
1271 if (o1->type == operand::OP_PREDICATE)
1273 predicate *p1 = as_a<predicate *>(o1);
1274 predicate *p2 = as_a<predicate *>(o2);
1275 return p1->p == p2->p;
1277 else if (o1->type == operand::OP_EXPR)
1279 expr *e1 = static_cast<expr *>(o1);
1280 expr *e2 = static_cast<expr *>(o2);
1281 return (e1->operation == e2->operation
1282 && e1->is_generic == e2->is_generic);
1288 /* Compare two decision tree nodes N1 and N2 and return true if they
1292 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1294 if (!n1 || !n2 || n1->type != n2->type)
1300 if (n1->type == dt_node::DT_TRUE)
1303 if (n1->type == dt_node::DT_OPERAND)
1304 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1305 (as_a<dt_operand *> (n2))->op);
1306 else if (n1->type == dt_node::DT_MATCH)
1307 return ((as_a<dt_operand *> (n1))->match_dop
1308 == (as_a<dt_operand *> (n2))->match_dop);
1312 /* Search OPS for a decision tree node like P and return it if found. */
1315 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1317 /* We can merge adjacent DT_TRUE. */
1318 if (p->type == dt_node::DT_TRUE
1320 && ops.last ()->type == dt_node::DT_TRUE)
1322 for (int i = ops.length () - 1; i >= 0; --i)
1324 /* But we can't merge across DT_TRUE nodes as they serve as
1325 pattern order barriers to make sure that patterns apply
1326 in order of appearance in case multiple matches are possible. */
1327 if (ops[i]->type == dt_node::DT_TRUE)
1329 if (decision_tree::cmp_node (ops[i], p))
1335 /* Append N to the decision tree if it there is not already an existing
1339 dt_node::append_node (dt_node *n)
1343 kid = decision_tree::find_node (kids, n);
1348 n->level = this->level + 1;
1353 /* Append OP to the decision tree. */
1356 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1358 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1359 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1360 return append_node (n);
1363 /* Append a DT_TRUE decision tree node. */
1366 dt_node::append_true_op (dt_node *parent, unsigned pos)
1368 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1369 dt_operand *n = new dt_operand (DT_TRUE, 0, 0, parent_, pos);
1370 return append_node (n);
1373 /* Append a DT_MATCH decision tree node. */
1376 dt_node::append_match_op (dt_operand *match_dop, dt_node *parent, unsigned pos)
1378 dt_operand *parent_ = as_a<dt_operand *> (parent);
1379 dt_operand *n = new dt_operand (DT_MATCH, 0, match_dop, parent_, pos);
1380 return append_node (n);
1383 /* Append S to the decision tree. */
1386 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1387 dt_operand **indexes)
1389 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1390 return append_node (n);
1393 /* Insert O into the decision tree and return the decision tree node found
1397 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1398 unsigned pos, dt_node *parent)
1400 dt_node *q, *elm = 0;
1402 if (capture *c = dyn_cast<capture *> (o))
1404 unsigned capt_index = c->where;
1406 if (indexes[capt_index] == 0)
1409 q = insert_operand (p, c->what, indexes, pos, parent);
1412 q = elm = p->append_true_op (parent, pos);
1415 // get to the last capture
1416 for (operand *what = c->what;
1417 what && is_a<capture *> (what);
1418 c = as_a<capture *> (what), what = c->what)
1423 unsigned cc_index = c->where;
1424 dt_operand *match_op = indexes[cc_index];
1426 dt_operand temp (dt_node::DT_TRUE, 0, 0);
1427 elm = decision_tree::find_node (p->kids, &temp);
1431 dt_operand temp (dt_node::DT_MATCH, 0, match_op);
1432 elm = decision_tree::find_node (p->kids, &temp);
1437 dt_operand temp (dt_node::DT_OPERAND, c->what, 0);
1438 elm = decision_tree::find_node (p->kids, &temp);
1442 gcc_assert (elm->type == dt_node::DT_TRUE
1443 || elm->type == dt_node::DT_OPERAND
1444 || elm->type == dt_node::DT_MATCH);
1445 indexes[capt_index] = static_cast<dt_operand *> (elm);
1450 p = p->append_match_op (indexes[capt_index], parent, pos);
1452 return insert_operand (p, c->what, indexes, 0, p);
1457 p = p->append_op (o, parent, pos);
1460 if (expr *e = dyn_cast <expr *>(o))
1462 for (unsigned i = 0; i < e->ops.length (); ++i)
1463 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
1469 /* Insert S into the decision tree. */
1472 decision_tree::insert (struct simplify *s, unsigned pattern_no)
1474 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
1475 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
1476 p->append_simplify (s, pattern_no, indexes);
1479 /* Debug functions to dump the decision tree. */
1482 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
1484 if (p->type == dt_node::DT_NODE)
1485 fprintf (f, "root");
1489 for (unsigned i = 0; i < indent; i++)
1492 if (p->type == dt_node::DT_OPERAND)
1494 dt_operand *dop = static_cast<dt_operand *>(p);
1495 print_operand (dop->op, f, true);
1497 else if (p->type == dt_node::DT_TRUE)
1498 fprintf (f, "true");
1499 else if (p->type == dt_node::DT_MATCH)
1500 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
1501 else if (p->type == dt_node::DT_SIMPLIFY)
1503 dt_simplify *s = static_cast<dt_simplify *> (p);
1504 fprintf (f, "simplify_%u { ", s->pattern_no);
1505 for (int i = 0; i <= s->s->capture_max; ++i)
1506 fprintf (f, "%p, ", (void *) s->indexes[i]);
1511 fprintf (stderr, " (%p), %u, %u\n", (void *) p, p->level, p->kids.length ());
1513 for (unsigned i = 0; i < p->kids.length (); ++i)
1514 decision_tree::print_node (p->kids[i], f, indent + 2);
1518 decision_tree::print (FILE *f)
1520 return decision_tree::print_node (root, f);
1524 /* For GENERIC we have to take care of wrapping multiple-used
1525 expressions with side-effects in save_expr and preserve side-effects
1526 of expressions with omit_one_operand. Analyze captures in
1527 match, result and with expressions and perform early-outs
1528 on the outermost match expression operands for cases we cannot
1533 capture_info (simplify *s);
1534 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
1535 void walk_result (operand *o, bool);
1536 void walk_c_expr (c_expr *);
1542 bool force_no_side_effects_p;
1543 bool force_single_use;
1544 bool cond_expr_cond_p;
1545 unsigned long toplevel_msk;
1546 int result_use_count;
1549 auto_vec<cinfo> info;
1550 unsigned long force_no_side_effects;
1553 /* Analyze captures in S. */
1555 capture_info::capture_info (simplify *s)
1559 || ((e = dyn_cast <expr *> (s->result))
1560 && is_a <predicate_id *> (e->operation)))
1562 force_no_side_effects = -1;
1566 force_no_side_effects = 0;
1567 info.safe_grow_cleared (s->capture_max + 1);
1568 e = as_a <expr *> (s->match);
1569 for (unsigned i = 0; i < e->ops.length (); ++i)
1570 walk_match (e->ops[i], i,
1571 (i != 0 && *e->operation == COND_EXPR)
1572 || *e->operation == TRUTH_ANDIF_EXPR
1573 || *e->operation == TRUTH_ORIF_EXPR,
1575 && (*e->operation == COND_EXPR
1576 || *e->operation == VEC_COND_EXPR));
1578 walk_result (s->result, false);
1580 for (unsigned i = 0; i < s->ifexpr_vec.length (); ++i)
1581 if (s->ifexpr_vec[i].is_with)
1582 walk_c_expr (as_a <c_expr *>(s->ifexpr_vec[i].cexpr));
1585 /* Analyze captures in the match expression piece O. */
1588 capture_info::walk_match (operand *o, unsigned toplevel_arg,
1589 bool conditional_p, bool cond_expr_cond_p)
1591 if (capture *c = dyn_cast <capture *> (o))
1593 info[c->where].toplevel_msk |= 1 << toplevel_arg;
1594 info[c->where].force_no_side_effects_p |= conditional_p;
1595 info[c->where].cond_expr_cond_p |= cond_expr_cond_p;
1596 /* Mark expr (non-leaf) captures and recurse. */
1599 && (e = dyn_cast <expr *> (c->what)))
1601 info[c->where].expr_p = true;
1602 info[c->where].force_single_use |= e->force_single_use;
1603 walk_match (c->what, toplevel_arg, conditional_p, false);
1606 else if (expr *e = dyn_cast <expr *> (o))
1608 for (unsigned i = 0; i < e->ops.length (); ++i)
1610 bool cond_p = conditional_p;
1611 bool cond_expr_cond_p = false;
1612 if (i != 0 && *e->operation == COND_EXPR)
1614 else if (*e->operation == TRUTH_ANDIF_EXPR
1615 || *e->operation == TRUTH_ORIF_EXPR)
1618 && (*e->operation == COND_EXPR
1619 || *e->operation == VEC_COND_EXPR))
1620 cond_expr_cond_p = true;
1621 walk_match (e->ops[i], toplevel_arg, cond_p, cond_expr_cond_p);
1624 else if (is_a <predicate *> (o))
1626 /* Mark non-captured leafs toplevel arg for checking. */
1627 force_no_side_effects |= 1 << toplevel_arg;
1633 /* Analyze captures in the result expression piece O. */
1636 capture_info::walk_result (operand *o, bool conditional_p)
1638 if (capture *c = dyn_cast <capture *> (o))
1640 info[c->where].result_use_count++;
1641 /* If we substitute an expression capture we don't know
1642 which captures this will end up using (well, we don't
1643 compute that). Force the uses to be side-effect free
1644 which means forcing the toplevels that reach the
1645 expression side-effect free. */
1646 if (info[c->where].expr_p)
1647 force_no_side_effects |= info[c->where].toplevel_msk;
1648 /* Mark CSE capture uses as forced to have no side-effects. */
1650 && is_a <expr *> (c->what))
1652 info[c->where].cse_p = true;
1653 walk_result (c->what, true);
1656 else if (expr *e = dyn_cast <expr *> (o))
1658 for (unsigned i = 0; i < e->ops.length (); ++i)
1660 bool cond_p = conditional_p;
1661 if (i != 0 && *e->operation == COND_EXPR)
1663 else if (*e->operation == TRUTH_ANDIF_EXPR
1664 || *e->operation == TRUTH_ORIF_EXPR)
1666 walk_result (e->ops[i], cond_p);
1669 else if (c_expr *e = dyn_cast <c_expr *> (o))
1675 /* Look for captures in the C expr E. */
1678 capture_info::walk_c_expr (c_expr *e)
1680 /* Give up for C exprs mentioning captures not inside TREE_TYPE (). */
1681 unsigned p_depth = 0;
1682 for (unsigned i = 0; i < e->code.length (); ++i)
1684 const cpp_token *t = &e->code[i];
1685 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
1686 if (t->type == CPP_NAME
1687 && strcmp ((const char *)CPP_HASHNODE
1688 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
1689 && n->type == CPP_OPEN_PAREN)
1691 else if (t->type == CPP_CLOSE_PAREN
1694 else if (p_depth == 0
1695 && t->type == CPP_ATSIGN
1696 && (n->type == CPP_NUMBER
1697 || n->type == CPP_NAME)
1698 && !(n->flags & PREV_WHITE))
1701 if (n->type == CPP_NUMBER)
1702 id = (const char *)n->val.str.text;
1704 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
1705 info[*e->capture_ids->get(id)].force_no_side_effects_p = true;
1711 /* Code generation off the decision tree and the refered AST nodes. */
1714 is_conversion (id_base *op)
1716 return (*op == CONVERT_EXPR
1718 || *op == FLOAT_EXPR
1719 || *op == FIX_TRUNC_EXPR
1720 || *op == VIEW_CONVERT_EXPR);
1723 /* Get the type to be used for generating operands of OP from the
1727 get_operand_type (id_base *op, const char *in_type,
1728 const char *expr_type,
1729 const char *other_oprnd_type)
1731 /* Generally operands whose type does not match the type of the
1732 expression generated need to know their types but match and
1733 thus can fall back to 'other_oprnd_type'. */
1734 if (is_conversion (op))
1735 return other_oprnd_type;
1736 else if (*op == REALPART_EXPR
1737 || *op == IMAGPART_EXPR)
1738 return other_oprnd_type;
1739 else if (is_a <operator_id *> (op)
1740 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
1741 return other_oprnd_type;
1744 /* Otherwise all types should match - choose one in order of
1751 return other_oprnd_type;
1755 /* Generate transform code for an expression. */
1758 expr::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
1759 int depth, const char *in_type, capture_info *cinfo,
1760 dt_operand **indexes, bool)
1762 bool conversion_p = is_conversion (operation);
1763 const char *type = expr_type;
1766 /* If there was a type specification in the pattern use it. */
1768 else if (conversion_p)
1769 /* For conversions we need to build the expression using the
1770 outer type passed in. */
1772 else if (*operation == REALPART_EXPR
1773 || *operation == IMAGPART_EXPR)
1775 /* __real and __imag use the component type of its operand. */
1776 sprintf (optype, "TREE_TYPE (TREE_TYPE (ops%d[0]))", depth);
1779 else if (is_a <operator_id *> (operation)
1780 && !strcmp (as_a <operator_id *> (operation)->tcc, "tcc_comparison"))
1782 /* comparisons use boolean_type_node (or what gets in), but
1783 their operands need to figure out the types themselves. */
1784 sprintf (optype, "boolean_type_node");
1787 else if (*operation == COND_EXPR
1788 || *operation == VEC_COND_EXPR)
1790 /* Conditions are of the same type as their first alternative. */
1791 sprintf (optype, "TREE_TYPE (ops%d[1])", depth);
1796 /* Other operations are of the same type as their first operand. */
1797 sprintf (optype, "TREE_TYPE (ops%d[0])", depth);
1801 fatal ("two conversions in a row");
1803 fprintf_indent (f, indent, "{\n");
1805 fprintf_indent (f, indent, "tree ops%d[%u], res;\n", depth, ops.length ());
1807 snprintf (op0type, 64, "TREE_TYPE (ops%d[0])", depth);
1808 for (unsigned i = 0; i < ops.length (); ++i)
1811 snprintf (dest, 32, "ops%d[%u]", depth, i);
1813 = get_operand_type (operation, in_type, expr_type,
1814 i == 0 ? NULL : op0type);
1815 ops[i]->gen_transform (f, indent, dest, gimple, depth + 1, optype,
1817 ((!(*operation == COND_EXPR)
1818 && !(*operation == VEC_COND_EXPR))
1823 if (*operation == CONVERT_EXPR)
1826 opr = operation->id;
1830 if (*operation == CONVERT_EXPR)
1832 fprintf_indent (f, indent,
1833 "if (%s != TREE_TYPE (ops%d[0])\n",
1835 fprintf_indent (f, indent,
1836 " && !useless_type_conversion_p (%s, TREE_TYPE (ops%d[0])))\n",
1838 fprintf_indent (f, indent + 2, "{\n");
1841 /* ??? Building a stmt can fail for various reasons here, seq being
1842 NULL or the stmt referencing SSA names occuring in abnormal PHIs.
1843 So if we fail here we should continue matching other patterns. */
1844 fprintf_indent (f, indent, "code_helper tem_code = %s;\n", opr);
1845 fprintf_indent (f, indent, "tree tem_ops[3] = { ");
1846 for (unsigned i = 0; i < ops.length (); ++i)
1847 fprintf (f, "ops%d[%u]%s", depth, i,
1848 i == ops.length () - 1 ? " };\n" : ", ");
1849 fprintf_indent (f, indent,
1850 "gimple_resimplify%d (lseq, &tem_code, %s, tem_ops, valueize);\n",
1851 ops.length (), type);
1852 fprintf_indent (f, indent,
1853 "res = maybe_push_res_to_seq (tem_code, %s, tem_ops, lseq);\n",
1855 fprintf_indent (f, indent,
1856 "if (!res) return false;\n");
1857 if (*operation == CONVERT_EXPR)
1860 fprintf_indent (f, indent, " }\n");
1861 fprintf_indent (f, indent, "else\n");
1862 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
1867 if (*operation == CONVERT_EXPR)
1869 fprintf_indent (f, indent, "if (TREE_TYPE (ops%d[0]) != %s)\n",
1873 if (operation->kind == id_base::CODE)
1874 fprintf_indent (f, indent, "res = fold_build%d_loc (loc, %s, %s",
1875 ops.length(), opr, type);
1877 fprintf_indent (f, indent, "res = build_call_expr_loc (loc, "
1878 "builtin_decl_implicit (%s), %d", opr, ops.length());
1879 for (unsigned i = 0; i < ops.length (); ++i)
1880 fprintf (f, ", ops%d[%u]", depth, i);
1881 fprintf (f, ");\n");
1882 if (*operation == CONVERT_EXPR)
1885 fprintf_indent (f, indent, "else\n");
1886 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
1889 fprintf_indent (f, indent, "%s = res;\n", dest);
1891 fprintf_indent (f, indent, "}\n");
1894 /* Generate code for a c_expr which is either the expression inside
1895 an if statement or a sequence of statements which computes a
1896 result to be stored to DEST. */
1899 c_expr::gen_transform (FILE *f, int indent, const char *dest,
1900 bool, int, const char *, capture_info *,
1901 dt_operand **, bool)
1903 if (dest && nr_stmts == 1)
1904 fprintf_indent (f, indent, "%s = ", dest);
1906 unsigned stmt_nr = 1;
1907 for (unsigned i = 0; i < code.length (); ++i)
1909 const cpp_token *token = &code[i];
1911 /* Replace captures for code-gen. */
1912 if (token->type == CPP_ATSIGN)
1914 const cpp_token *n = &code[i+1];
1915 if ((n->type == CPP_NUMBER
1916 || n->type == CPP_NAME)
1917 && !(n->flags & PREV_WHITE))
1919 if (token->flags & PREV_WHITE)
1922 if (n->type == CPP_NUMBER)
1923 id = (const char *)n->val.str.text;
1925 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
1926 fprintf (f, "captures[%u]", *capture_ids->get(id));
1932 if (token->flags & PREV_WHITE)
1935 if (token->type == CPP_NAME)
1937 const char *id = (const char *) NODE_NAME (token->val.node.node);
1939 for (j = 0; j < ids.length (); ++j)
1941 if (strcmp (id, ids[j].id) == 0)
1943 fprintf (f, "%s", ids[j].oper);
1947 if (j < ids.length ())
1951 /* Output the token as string. */
1952 char *tk = (char *)cpp_token_as_text (r, token);
1955 if (token->type == CPP_SEMICOLON)
1959 if (dest && stmt_nr == nr_stmts)
1960 fprintf_indent (f, indent, "%s = ", dest);
1965 /* Generate transform code for a capture. */
1968 capture::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
1969 int depth, const char *in_type, capture_info *cinfo,
1970 dt_operand **indexes, bool expand_compares)
1972 if (what && is_a<expr *> (what))
1974 if (indexes[where] == 0)
1977 sprintf (buf, "captures[%u]", where);
1978 what->gen_transform (f, indent, buf, gimple, depth, in_type,
1983 fprintf_indent (f, indent, "%s = captures[%u];\n", dest, where);
1985 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
1986 with substituting a capture of that.
1987 ??? Returning false here will also not allow any other patterns
1989 if (gimple && expand_compares
1990 && cinfo->info[where].cond_expr_cond_p)
1992 fprintf_indent (f, indent, "if (COMPARISON_CLASS_P (%s))\n", dest);
1993 fprintf_indent (f, indent, " {\n");
1994 fprintf_indent (f, indent, " if (!seq) return false;\n");
1995 fprintf_indent (f, indent, " %s = gimple_build (seq, TREE_CODE (%s),"
1996 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
1997 " TREE_OPERAND (%s, 1));\n",
1998 dest, dest, dest, dest, dest);
1999 fprintf_indent (f, indent, " }\n");
2003 /* Return the name of the operand representing the decision tree node.
2004 Use NAME as space to generate it. */
2007 dt_operand::get_name (char *name)
2010 sprintf (name, "t");
2011 else if (parent->level == 1)
2012 sprintf (name, "op%u", pos);
2013 else if (parent->type == dt_node::DT_MATCH)
2014 return parent->get_name (name);
2016 sprintf (name, "o%u%u", parent->level, pos);
2020 /* Fill NAME with the operand name at position POS. */
2023 dt_operand::gen_opname (char *name, unsigned pos)
2026 sprintf (name, "op%u", pos);
2028 sprintf (name, "o%u%u", level, pos);
2031 /* Generate matching code for the decision tree operand which is
2035 dt_operand::gen_predicate (FILE *f, int indent, const char *opname, bool gimple)
2037 predicate *p = as_a <predicate *> (op);
2039 if (p->p->matchers.exists ())
2041 /* If this is a predicate generated from a pattern mangle its
2042 name and pass on the valueize hook. */
2044 fprintf_indent (f, indent, "if (gimple_%s (%s, valueize))\n",
2047 fprintf_indent (f, indent, "if (tree_%s (%s))\n", p->p->id, opname);
2050 fprintf_indent (f, indent, "if (%s (%s))\n", p->p->id, opname);
2051 fprintf_indent (f, indent + 2, "{\n");
2055 /* Generate matching code for the decision tree operand which is
2059 dt_operand::gen_match_op (FILE *f, int indent, const char *opname)
2061 char match_opname[20];
2062 match_dop->get_name (match_opname);
2063 fprintf_indent (f, indent, "if (%s == %s || operand_equal_p (%s, %s, 0))\n",
2064 opname, match_opname, opname, match_opname);
2065 fprintf_indent (f, indent + 2, "{\n");
2069 /* Generate GIMPLE matching code for the decision tree operand. */
2072 dt_operand::gen_gimple_expr (FILE *f, int indent)
2074 expr *e = static_cast<expr *> (op);
2075 id_base *id = e->operation;
2076 unsigned n_ops = e->ops.length ();
2078 for (unsigned i = 0; i < n_ops; ++i)
2080 char child_opname[20];
2081 gen_opname (child_opname, i);
2083 if (id->kind == id_base::CODE)
2086 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2087 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
2089 /* ??? If this is a memory operation we can't (and should not)
2090 match this. The only sensible operand types are
2091 SSA names and invariants. */
2092 fprintf_indent (f, indent,
2093 "tree %s = TREE_OPERAND (gimple_assign_rhs1 (def_stmt), %i);\n",
2095 fprintf_indent (f, indent,
2096 "if ((TREE_CODE (%s) == SSA_NAME\n",
2098 fprintf_indent (f, indent,
2099 " || is_gimple_min_invariant (%s))\n",
2101 fprintf_indent (f, indent,
2102 " && (%s = do_valueize (valueize, %s)))\n",
2103 child_opname, child_opname);
2104 fprintf_indent (f, indent,
2110 fprintf_indent (f, indent,
2111 "tree %s = gimple_assign_rhs%u (def_stmt);\n",
2112 child_opname, i + 1);
2115 fprintf_indent (f, indent,
2116 "tree %s = gimple_call_arg (def_stmt, %u);\n",
2118 fprintf_indent (f, indent,
2119 "if ((%s = do_valueize (valueize, %s)))\n",
2120 child_opname, child_opname);
2121 fprintf_indent (f, indent, " {\n");
2124 /* While the toplevel operands are canonicalized by the caller
2125 after valueizing operands of sub-expressions we have to
2126 re-canonicalize operand order. */
2127 if (operator_id *code = dyn_cast <operator_id *> (id))
2129 /* ??? We can't canonicalize tcc_comparison operands here
2130 because that requires changing the comparison code which
2131 we already matched... */
2132 if (commutative_tree_code (code->code)
2133 || commutative_ternary_tree_code (code->code))
2135 char child_opname0[20], child_opname1[20];
2136 gen_opname (child_opname0, 0);
2137 gen_opname (child_opname1, 1);
2138 fprintf_indent (f, indent,
2139 "if (tree_swap_operands_p (%s, %s, false))\n",
2140 child_opname0, child_opname1);
2141 fprintf_indent (f, indent,
2142 " std::swap (%s, %s);\n",
2143 child_opname0, child_opname1);
2150 /* Generate GENERIC matching code for the decision tree operand. */
2153 dt_operand::gen_generic_expr (FILE *f, int indent, const char *opname)
2155 expr *e = static_cast<expr *> (op);
2156 unsigned n_ops = e->ops.length ();
2158 for (unsigned i = 0; i < n_ops; ++i)
2160 char child_opname[20];
2161 gen_opname (child_opname, i);
2163 if (e->operation->kind == id_base::CODE)
2164 fprintf_indent (f, indent, "tree %s = TREE_OPERAND (%s, %u);\n",
2165 child_opname, opname, i);
2167 fprintf_indent (f, indent, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
2168 child_opname, opname, i);
2174 /* Generate matching code for the children of the decision tree node. */
2177 dt_node::gen_kids (FILE *f, int indent, bool gimple)
2179 auto_vec<dt_operand *> gimple_exprs;
2180 auto_vec<dt_operand *> generic_exprs;
2181 auto_vec<dt_operand *> fns;
2182 auto_vec<dt_operand *> generic_fns;
2183 auto_vec<dt_operand *> preds;
2184 auto_vec<dt_node *> others;
2186 for (unsigned i = 0; i < kids.length (); ++i)
2188 if (kids[i]->type == dt_node::DT_OPERAND)
2190 dt_operand *op = as_a<dt_operand *> (kids[i]);
2191 if (expr *e = dyn_cast <expr *> (op->op))
2193 if (e->ops.length () == 0
2194 && (!gimple || !(*e->operation == CONSTRUCTOR)))
2195 generic_exprs.safe_push (op);
2196 else if (e->operation->kind == id_base::FN)
2201 generic_fns.safe_push (op);
2203 else if (e->operation->kind == id_base::PREDICATE)
2204 preds.safe_push (op);
2208 gimple_exprs.safe_push (op);
2210 generic_exprs.safe_push (op);
2213 else if (op->op->type == operand::OP_PREDICATE)
2214 others.safe_push (kids[i]);
2218 else if (kids[i]->type == dt_node::DT_MATCH
2219 || kids[i]->type == dt_node::DT_SIMPLIFY)
2220 others.safe_push (kids[i]);
2221 else if (kids[i]->type == dt_node::DT_TRUE)
2223 /* A DT_TRUE operand serves as a barrier - generate code now
2224 for what we have collected sofar. */
2225 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2226 fns, generic_fns, preds, others);
2227 /* And output the true operand itself. */
2228 kids[i]->gen (f, indent, gimple);
2229 gimple_exprs.truncate (0);
2230 generic_exprs.truncate (0);
2232 generic_fns.truncate (0);
2234 others.truncate (0);
2240 /* Generate code for the remains. */
2241 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2242 fns, generic_fns, preds, others);
2245 /* Generate matching code for the children of the decision tree node. */
2248 dt_node::gen_kids_1 (FILE *f, int indent, bool gimple,
2249 vec<dt_operand *> gimple_exprs,
2250 vec<dt_operand *> generic_exprs,
2251 vec<dt_operand *> fns,
2252 vec<dt_operand *> generic_fns,
2253 vec<dt_operand *> preds,
2254 vec<dt_node *> others)
2257 char *kid_opname = buf;
2259 unsigned exprs_len = gimple_exprs.length ();
2260 unsigned gexprs_len = generic_exprs.length ();
2261 unsigned fns_len = fns.length ();
2262 unsigned gfns_len = generic_fns.length ();
2264 if (exprs_len || fns_len || gexprs_len || gfns_len)
2267 gimple_exprs[0]->get_name (kid_opname);
2269 fns[0]->get_name (kid_opname);
2271 generic_fns[0]->get_name (kid_opname);
2273 generic_exprs[0]->get_name (kid_opname);
2275 fprintf_indent (f, indent, "switch (TREE_CODE (%s))\n", kid_opname);
2276 fprintf_indent (f, indent, " {\n");
2280 if (exprs_len || fns_len)
2282 fprintf_indent (f, indent,
2283 "case SSA_NAME:\n");
2284 fprintf_indent (f, indent,
2285 " if (do_valueize (valueize, %s) != NULL_TREE)\n",
2287 fprintf_indent (f, indent,
2289 fprintf_indent (f, indent,
2290 " gimple def_stmt = SSA_NAME_DEF_STMT (%s);\n",
2296 fprintf_indent (f, indent,
2297 "if (is_gimple_assign (def_stmt))\n");
2298 fprintf_indent (f, indent,
2299 " switch (gimple_assign_rhs_code (def_stmt))\n");
2301 fprintf_indent (f, indent, "{\n");
2302 for (unsigned i = 0; i < exprs_len; ++i)
2304 expr *e = as_a <expr *> (gimple_exprs[i]->op);
2305 id_base *op = e->operation;
2306 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2307 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2309 fprintf_indent (f, indent, "case %s:\n", op->id);
2310 fprintf_indent (f, indent, " {\n");
2311 gimple_exprs[i]->gen (f, indent + 4, true);
2312 fprintf_indent (f, indent, " break;\n");
2313 fprintf_indent (f, indent, " }\n");
2315 fprintf_indent (f, indent, "default:;\n");
2317 fprintf_indent (f, indent, "}\n");
2323 fprintf_indent (f, indent, "else ");
2325 fprintf_indent (f, indent, " ");
2327 fprintf (f, "if (gimple_call_builtin_p (def_stmt, BUILT_IN_NORMAL))\n");
2328 fprintf_indent (f, indent,
2330 fprintf_indent (f, indent,
2331 " tree fndecl = gimple_call_fndecl (def_stmt);\n");
2332 fprintf_indent (f, indent,
2333 " switch (DECL_FUNCTION_CODE (fndecl))\n");
2334 fprintf_indent (f, indent,
2338 for (unsigned i = 0; i < fns_len; ++i)
2340 expr *e = as_a <expr *>(fns[i]->op);
2341 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2342 fprintf_indent (f, indent, " {\n");
2343 fns[i]->gen (f, indent + 4, true);
2344 fprintf_indent (f, indent, " break;\n");
2345 fprintf_indent (f, indent, " }\n");
2348 fprintf_indent (f, indent, "default:;\n");
2350 fprintf_indent (f, indent, " }\n");
2351 fprintf_indent (f, indent, " }\n");
2355 fprintf_indent (f, indent, " }\n");
2356 fprintf_indent (f, indent, " break;\n");
2359 for (unsigned i = 0; i < generic_exprs.length (); ++i)
2361 expr *e = as_a <expr *>(generic_exprs[i]->op);
2362 id_base *op = e->operation;
2363 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2364 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2366 fprintf_indent (f, indent, "case %s:\n", op->id);
2367 fprintf_indent (f, indent, " {\n");
2368 generic_exprs[i]->gen (f, indent + 4, gimple);
2369 fprintf_indent (f, indent, " break;\n");
2370 fprintf_indent (f, indent, " }\n");
2375 fprintf_indent (f, indent,
2376 "case CALL_EXPR:\n");
2377 fprintf_indent (f, indent,
2379 fprintf_indent (f, indent,
2380 " tree fndecl = get_callee_fndecl (%s);\n",
2382 fprintf_indent (f, indent,
2383 " if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)\n");
2384 fprintf_indent (f, indent,
2385 " switch (DECL_FUNCTION_CODE (fndecl))\n");
2386 fprintf_indent (f, indent,
2390 for (unsigned j = 0; j < generic_fns.length (); ++j)
2392 expr *e = as_a <expr *>(generic_fns[j]->op);
2393 gcc_assert (e->operation->kind == id_base::FN);
2395 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2396 fprintf_indent (f, indent, " {\n");
2397 generic_fns[j]->gen (f, indent + 4, false);
2398 fprintf_indent (f, indent, " break;\n");
2399 fprintf_indent (f, indent, " }\n");
2403 fprintf_indent (f, indent, " default:;\n");
2404 fprintf_indent (f, indent, " }\n");
2405 fprintf_indent (f, indent, " break;\n");
2406 fprintf_indent (f, indent, " }\n");
2409 /* Close switch (TREE_CODE ()). */
2410 if (exprs_len || fns_len || gexprs_len || gfns_len)
2413 fprintf_indent (f, indent, " default:;\n");
2414 fprintf_indent (f, indent, " }\n");
2417 for (unsigned i = 0; i < preds.length (); ++i)
2419 expr *e = as_a <expr *> (preds[i]->op);
2420 predicate_id *p = as_a <predicate_id *> (e->operation);
2421 preds[i]->get_name (kid_opname);
2422 fprintf_indent (f, indent, "tree %s_pops[%d];\n", kid_opname, p->nargs);
2423 fprintf_indent (f, indent, "if (%s_%s (%s, %s_pops%s))\n",
2424 gimple ? "gimple" : "tree",
2425 p->id, kid_opname, kid_opname,
2426 gimple ? ", valueize" : "");
2427 fprintf_indent (f, indent, " {\n");
2428 for (int j = 0; j < p->nargs; ++j)
2430 char child_opname[20];
2431 preds[i]->gen_opname (child_opname, j);
2432 fprintf_indent (f, indent + 4, "tree %s = %s_pops[%d];\n",
2433 child_opname, kid_opname, j);
2435 preds[i]->gen_kids (f, indent + 4, gimple);
2439 for (unsigned i = 0; i < others.length (); ++i)
2440 others[i]->gen (f, indent, gimple);
2443 /* Generate matching code for the decision tree operand. */
2446 dt_operand::gen (FILE *f, int indent, bool gimple)
2451 unsigned n_braces = 0;
2453 if (type == DT_OPERAND)
2456 case operand::OP_PREDICATE:
2457 n_braces = gen_predicate (f, indent, opname, gimple);
2460 case operand::OP_EXPR:
2462 n_braces = gen_gimple_expr (f, indent);
2464 n_braces = gen_generic_expr (f, indent, opname);
2470 else if (type == DT_TRUE)
2472 else if (type == DT_MATCH)
2473 n_braces = gen_match_op (f, indent, opname);
2477 indent += 4 * n_braces;
2478 gen_kids (f, indent, gimple);
2480 for (unsigned i = 0; i < n_braces; ++i)
2485 fprintf_indent (f, indent, " }\n");
2491 /* Generate code for the '(if ...)', '(with ..)' and actual transform
2492 step of a '(simplify ...)' or '(match ...)'. This handles everything
2493 that is not part of the decision tree (simplify->match). */
2496 dt_simplify::gen (FILE *f, int indent, bool gimple)
2498 fprintf_indent (f, indent, "{\n");
2500 output_line_directive (f, s->result_location);
2501 if (s->capture_max >= 0)
2502 fprintf_indent (f, indent, "tree captures[%u] ATTRIBUTE_UNUSED = {};\n",
2503 s->capture_max + 1);
2505 for (int i = 0; i <= s->capture_max; ++i)
2509 fprintf_indent (f, indent, "captures[%u] = %s;\n",
2510 i, indexes[i]->get_name (opname));
2513 unsigned n_braces = 0;
2514 if (s->ifexpr_vec != vNULL)
2516 for (unsigned i = 0; i < s->ifexpr_vec.length (); ++i)
2518 if_or_with &w = s->ifexpr_vec[i];
2521 fprintf_indent (f, indent, "{\n");
2523 output_line_directive (f, w.location);
2524 w.cexpr->gen_transform (f, indent, NULL, true, 1, "type", NULL);
2529 output_line_directive (f, w.location);
2530 fprintf_indent (f, indent, "if (");
2531 if (i == s->ifexpr_vec.length () - 1
2532 || s->ifexpr_vec[i+1].is_with)
2533 w.cexpr->gen_transform (f, indent, NULL, true, 1, "type", NULL);
2542 output_line_directive (f, s->ifexpr_vec[j].location);
2543 fprintf_indent (f, indent + 4, "&& ");
2546 s->ifexpr_vec[j].cexpr->gen_transform (f, 0, NULL,
2552 while (j < s->ifexpr_vec.length ()
2553 && !s->ifexpr_vec[j].is_with);
2559 fprintf_indent (f, indent + 2, "{\n");
2564 /* Analyze captures and perform early-outs on the incoming arguments
2565 that cover cases we cannot handle. */
2566 capture_info cinfo (s);
2569 && !((e = dyn_cast <expr *> (s->result))
2570 && is_a <predicate_id *> (e->operation)))
2574 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
2575 if (cinfo.force_no_side_effects & (1 << i))
2576 fprintf_indent (f, indent,
2577 "if (TREE_SIDE_EFFECTS (op%d)) return NULL_TREE;\n",
2579 for (int i = 0; i <= s->capture_max; ++i)
2580 if (cinfo.info[i].cse_p)
2582 else if (cinfo.info[i].force_no_side_effects_p
2583 && (cinfo.info[i].toplevel_msk
2584 & cinfo.force_no_side_effects) == 0)
2585 fprintf_indent (f, indent,
2586 "if (TREE_SIDE_EFFECTS (captures[%d])) "
2587 "return NULL_TREE;\n", i);
2588 else if ((cinfo.info[i].toplevel_msk
2589 & cinfo.force_no_side_effects) != 0)
2590 /* Mark capture as having no side-effects if we had to verify
2591 that via forced toplevel operand checks. */
2592 cinfo.info[i].force_no_side_effects_p = true;
2596 /* Force single-use restriction by only allowing simple
2597 results via setting seq to NULL. */
2598 fprintf_indent (f, indent, "gimple_seq *lseq = seq;\n");
2599 bool first_p = true;
2600 for (int i = 0; i <= s->capture_max; ++i)
2601 if (cinfo.info[i].force_single_use)
2605 fprintf_indent (f, indent, "if (lseq\n");
2606 fprintf_indent (f, indent, " && (");
2612 fprintf_indent (f, indent, " || ");
2614 fprintf (f, "!single_use (captures[%d])", i);
2618 fprintf (f, "))\n");
2619 fprintf_indent (f, indent, " lseq = NULL;\n");
2624 fprintf_indent (f, indent, "if (dump_file && (dump_flags & TDF_DETAILS)) "
2625 "fprintf (dump_file, \"Applying pattern ");
2626 output_line_directive (f, s->result_location, true);
2627 fprintf (f, ", %%s:%%d\\n\", __FILE__, __LINE__);\n");
2629 operand *result = s->result;
2632 /* If there is no result then this is a predicate implementation. */
2633 fprintf_indent (f, indent, "return true;\n");
2637 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
2638 in outermost position). */
2639 if (result->type == operand::OP_EXPR
2640 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
2641 result = as_a <expr *> (result)->ops[0];
2642 if (result->type == operand::OP_EXPR)
2644 expr *e = as_a <expr *> (result);
2645 bool is_predicate = is_a <predicate_id *> (e->operation);
2647 fprintf_indent (f, indent, "*res_code = %s;\n",
2648 *e->operation == CONVERT_EXPR
2649 ? "NOP_EXPR" : e->operation->id);
2650 for (unsigned j = 0; j < e->ops.length (); ++j)
2653 snprintf (dest, 32, "res_ops[%d]", j);
2655 = get_operand_type (e->operation,
2656 "type", e->expr_type,
2657 j == 0 ? NULL : "TREE_TYPE (res_ops[0])");
2658 /* We need to expand GENERIC conditions we captured from
2660 bool expand_generic_cond_exprs_p
2662 /* But avoid doing that if the GENERIC condition is
2663 valid - which it is in the first operand of COND_EXPRs
2664 and VEC_COND_EXRPs. */
2665 && ((!(*e->operation == COND_EXPR)
2666 && !(*e->operation == VEC_COND_EXPR))
2668 e->ops[j]->gen_transform (f, indent, dest, true, 1, optype,
2670 indexes, expand_generic_cond_exprs_p);
2673 /* Re-fold the toplevel result. It's basically an embedded
2674 gimple_build w/o actually building the stmt. */
2676 fprintf_indent (f, indent,
2677 "gimple_resimplify%d (lseq, res_code, type, "
2678 "res_ops, valueize);\n", e->ops.length ());
2680 else if (result->type == operand::OP_CAPTURE
2681 || result->type == operand::OP_C_EXPR)
2683 result->gen_transform (f, indent, "res_ops[0]", true, 1, "type",
2684 &cinfo, indexes, false);
2685 fprintf_indent (f, indent, "*res_code = TREE_CODE (res_ops[0]);\n");
2686 if (is_a <capture *> (result)
2687 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
2689 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2690 with substituting a capture of that. */
2691 fprintf_indent (f, indent,
2692 "if (COMPARISON_CLASS_P (res_ops[0]))\n");
2693 fprintf_indent (f, indent,
2695 fprintf_indent (f, indent,
2696 " tree tem = res_ops[0];\n");
2697 fprintf_indent (f, indent,
2698 " res_ops[0] = TREE_OPERAND (tem, 0);\n");
2699 fprintf_indent (f, indent,
2700 " res_ops[1] = TREE_OPERAND (tem, 1);\n");
2701 fprintf_indent (f, indent,
2707 fprintf_indent (f, indent, "return true;\n");
2711 bool is_predicate = false;
2712 if (result->type == operand::OP_EXPR)
2714 expr *e = as_a <expr *> (result);
2715 is_predicate = is_a <predicate_id *> (e->operation);
2716 /* Search for captures used multiple times in the result expression
2717 and dependent on TREE_SIDE_EFFECTS emit a SAVE_EXPR. */
2719 for (int i = 0; i < s->capture_max + 1; ++i)
2721 if (!cinfo.info[i].force_no_side_effects_p
2722 && cinfo.info[i].result_use_count > 1)
2724 fprintf_indent (f, indent,
2725 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
2727 fprintf_indent (f, indent,
2728 " captures[%d] = save_expr (captures[%d]);\n",
2732 for (unsigned j = 0; j < e->ops.length (); ++j)
2736 snprintf (dest, 32, "res_ops[%d]", j);
2739 fprintf_indent (f, indent, "tree res_op%d;\n", j);
2740 snprintf (dest, 32, "res_op%d", j);
2743 = get_operand_type (e->operation,
2744 "type", e->expr_type,
2746 ? NULL : "TREE_TYPE (res_op0)");
2747 e->ops[j]->gen_transform (f, indent, dest, false, 1, optype,
2751 fprintf_indent (f, indent, "return true;\n");
2754 fprintf_indent (f, indent, "tree res;\n");
2755 /* Re-fold the toplevel result. Use non_lvalue to
2756 build NON_LVALUE_EXPRs so they get properly
2757 ignored when in GIMPLE form. */
2758 if (*e->operation == NON_LVALUE_EXPR)
2759 fprintf_indent (f, indent,
2760 "res = non_lvalue_loc (loc, res_op0);\n");
2763 if (e->operation->kind == id_base::CODE)
2764 fprintf_indent (f, indent,
2765 "res = fold_build%d_loc (loc, %s, type",
2767 *e->operation == CONVERT_EXPR
2768 ? "NOP_EXPR" : e->operation->id);
2770 fprintf_indent (f, indent,
2771 "res = build_call_expr_loc "
2772 "(loc, builtin_decl_implicit (%s), %d",
2773 e->operation->id, e->ops.length());
2774 for (unsigned j = 0; j < e->ops.length (); ++j)
2775 fprintf (f, ", res_op%d", j);
2776 fprintf (f, ");\n");
2780 else if (result->type == operand::OP_CAPTURE
2781 || result->type == operand::OP_C_EXPR)
2784 fprintf_indent (f, indent, "tree res;\n");
2785 s->result->gen_transform (f, indent, "res", false, 1, "type",
2792 /* Search for captures not used in the result expression and dependent
2793 on TREE_SIDE_EFFECTS emit omit_one_operand. */
2794 for (int i = 0; i < s->capture_max + 1; ++i)
2796 if (!cinfo.info[i].force_no_side_effects_p
2797 && !cinfo.info[i].expr_p
2798 && cinfo.info[i].result_use_count == 0)
2800 fprintf_indent (f, indent,
2801 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
2803 fprintf_indent (f, indent + 2,
2804 "res = build2_loc (loc, COMPOUND_EXPR, type, "
2805 "fold_ignored_result (captures[%d]), res);\n",
2809 fprintf_indent (f, indent, "return res;\n");
2813 for (unsigned i = 0; i < n_braces; ++i)
2815 fprintf_indent (f, indent - 2, "}\n");
2820 fprintf_indent (f, indent, "}\n");
2823 /* Main entry to generate code for matching GIMPLE IL off the decision
2827 decision_tree::gen_gimple (FILE *f)
2829 for (unsigned n = 1; n <= 3; ++n)
2831 fprintf (f, "\nstatic bool\n"
2832 "gimple_simplify (code_helper *res_code, tree *res_ops,\n"
2833 " gimple_seq *seq, tree (*valueize)(tree),\n"
2834 " code_helper code, tree type");
2835 for (unsigned i = 0; i < n; ++i)
2836 fprintf (f, ", tree op%d", i);
2840 fprintf (f, " switch (code.get_rep())\n"
2842 for (unsigned i = 0; i < root->kids.length (); i++)
2844 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
2845 expr *e = static_cast<expr *>(dop->op);
2846 if (e->ops.length () != n)
2849 if (*e->operation == CONVERT_EXPR
2850 || *e->operation == NOP_EXPR)
2851 fprintf (f, " CASE_CONVERT:\n");
2853 fprintf (f, " case %s%s:\n",
2854 is_a <fn_id *> (e->operation) ? "-" : "",
2856 fprintf (f, " {\n");
2857 dop->gen_kids (f, 8, true);
2858 fprintf (f, " break;\n");
2859 fprintf (f, " }\n");
2861 fprintf (f, " default:;\n"
2864 fprintf (f, " return false;\n");
2869 /* Main entry to generate code for matching GENERIC IL off the decision
2873 decision_tree::gen_generic (FILE *f)
2875 for (unsigned n = 1; n <= 3; ++n)
2877 fprintf (f, "\ntree\n"
2878 "generic_simplify (location_t loc, enum tree_code code, "
2879 "tree type ATTRIBUTE_UNUSED");
2880 for (unsigned i = 0; i < n; ++i)
2881 fprintf (f, ", tree op%d", i);
2885 fprintf (f, " switch (code)\n"
2887 for (unsigned i = 0; i < root->kids.length (); i++)
2889 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
2890 expr *e = static_cast<expr *>(dop->op);
2891 if (e->ops.length () != n
2892 /* Builtin simplifications are somewhat premature on
2893 GENERIC. The following drops patterns with outermost
2894 calls. It's easy to emit overloads for function code
2895 though if necessary. */
2896 || e->operation->kind != id_base::CODE)
2899 operator_id *op_id = static_cast <operator_id *> (e->operation);
2900 if (op_id->code == NOP_EXPR || op_id->code == CONVERT_EXPR)
2901 fprintf (f, " CASE_CONVERT:\n");
2903 fprintf (f, " case %s:\n", e->operation->id);
2904 fprintf (f, " {\n");
2905 dop->gen_kids (f, 8, false);
2906 fprintf (f, " break;\n"
2909 fprintf (f, " default:;\n"
2912 fprintf (f, " return NULL_TREE;\n");
2917 /* Output code to implement the predicate P from the decision tree DT. */
2920 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
2922 fprintf (f, "\nbool\n"
2923 "%s%s (tree t%s%s)\n"
2924 "{\n", gimple ? "gimple_" : "tree_", p->id,
2925 p->nargs > 0 ? ", tree *res_ops" : "",
2926 gimple ? ", tree (*valueize)(tree)" : "");
2927 /* Conveniently make 'type' available. */
2928 fprintf_indent (f, 2, "tree type = TREE_TYPE (t);\n");
2931 fprintf_indent (f, 2, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
2932 dt.root->gen_kids (f, 2, gimple);
2934 fprintf_indent (f, 2, "return false;\n"
2938 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
2941 write_header (FILE *f, const char *head)
2943 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
2944 fprintf (f, " a IL pattern matching and simplification description. */\n");
2946 /* Include the header instead of writing it awkwardly quoted here. */
2947 fprintf (f, "\n#include \"%s\"\n", head);
2957 parser (cpp_reader *);
2960 const cpp_token *next ();
2961 const cpp_token *peek ();
2962 const cpp_token *peek_ident (const char * = NULL);
2963 const cpp_token *expect (enum cpp_ttype);
2964 void eat_token (enum cpp_ttype);
2965 const char *get_string ();
2966 const char *get_ident ();
2967 void eat_ident (const char *);
2968 const char *get_number ();
2970 id_base *parse_operation ();
2971 operand *parse_capture (operand *);
2972 operand *parse_expr ();
2973 c_expr *parse_c_expr (cpp_ttype);
2974 operand *parse_op ();
2976 void record_operlist (source_location, user_id *);
2978 void parse_pattern ();
2979 void push_simplify (vec<simplify *>&, operand *, source_location,
2980 operand *, source_location);
2981 void parse_simplify (source_location, vec<simplify *>&, predicate_id *,
2983 void parse_for (source_location);
2984 void parse_if (source_location);
2985 void parse_predicates (source_location);
2986 void parse_operator_list (source_location);
2989 vec<if_or_with> active_ifs;
2990 vec<vec<user_id *> > active_fors;
2991 hash_set<user_id *> *oper_lists_set;
2992 vec<user_id *> oper_lists;
2994 cid_map_t *capture_ids;
2997 vec<simplify *> simplifiers;
2998 vec<predicate_id *> user_predicates;
2999 bool parsing_match_operand;
3002 /* Lexing helpers. */
3004 /* Read the next non-whitespace token from R. */
3009 const cpp_token *token;
3012 token = cpp_get_token (r);
3014 while (token->type == CPP_PADDING
3015 && token->type != CPP_EOF);
3019 /* Peek at the next non-whitespace token from R. */
3024 const cpp_token *token;
3028 token = cpp_peek_token (r, i++);
3030 while (token->type == CPP_PADDING
3031 && token->type != CPP_EOF);
3032 /* If we peek at EOF this is a fatal error as it leaves the
3033 cpp_reader in unusable state. Assume we really wanted a
3034 token and thus this EOF is unexpected. */
3035 if (token->type == CPP_EOF)
3036 fatal_at (token, "unexpected end of file");
3040 /* Peek at the next identifier token (or return NULL if the next
3041 token is not an identifier or equal to ID if supplied). */
3044 parser::peek_ident (const char *id)
3046 const cpp_token *token = peek ();
3047 if (token->type != CPP_NAME)
3053 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
3054 if (strcmp (id, t) == 0)
3060 /* Read the next token from R and assert it is of type TK. */
3063 parser::expect (enum cpp_ttype tk)
3065 const cpp_token *token = next ();
3066 if (token->type != tk)
3067 fatal_at (token, "expected %s, got %s",
3068 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
3073 /* Consume the next token from R and assert it is of type TK. */
3076 parser::eat_token (enum cpp_ttype tk)
3081 /* Read the next token from R and assert it is of type CPP_STRING and
3082 return its value. */
3085 parser::get_string ()
3087 const cpp_token *token = expect (CPP_STRING);
3088 return (const char *)token->val.str.text;
3091 /* Read the next token from R and assert it is of type CPP_NAME and
3092 return its value. */
3095 parser::get_ident ()
3097 const cpp_token *token = expect (CPP_NAME);
3098 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
3101 /* Eat an identifier token with value S from R. */
3104 parser::eat_ident (const char *s)
3106 const cpp_token *token = peek ();
3107 const char *t = get_ident ();
3108 if (strcmp (s, t) != 0)
3109 fatal_at (token, "expected '%s' got '%s'\n", s, t);
3112 /* Read the next token from R and assert it is of type CPP_NUMBER and
3113 return its value. */
3116 parser::get_number ()
3118 const cpp_token *token = expect (CPP_NUMBER);
3119 return (const char *)token->val.str.text;
3123 /* Record an operator-list use for transparent for handling. */
3126 parser::record_operlist (source_location loc, user_id *p)
3128 if (!oper_lists_set->add (p))
3130 if (!oper_lists.is_empty ()
3131 && oper_lists[0]->substitutes.length () != p->substitutes.length ())
3132 fatal_at (loc, "User-defined operator list does not have the "
3133 "same number of entries as others used in the pattern");
3134 oper_lists.safe_push (p);
3138 /* Parse the operator ID, special-casing convert?, convert1? and
3142 parser::parse_operation ()
3144 const cpp_token *id_tok = peek ();
3145 const char *id = get_ident ();
3146 const cpp_token *token = peek ();
3147 if (strcmp (id, "convert0") == 0)
3148 fatal_at (id_tok, "use 'convert?' here");
3149 else if (strcmp (id, "view_convert0") == 0)
3150 fatal_at (id_tok, "use 'view_convert?' here");
3151 if (token->type == CPP_QUERY
3152 && !(token->flags & PREV_WHITE))
3154 if (strcmp (id, "convert") == 0)
3156 else if (strcmp (id, "convert1") == 0)
3158 else if (strcmp (id, "convert2") == 0)
3160 else if (strcmp (id, "view_convert") == 0)
3161 id = "view_convert0";
3162 else if (strcmp (id, "view_convert1") == 0)
3164 else if (strcmp (id, "view_convert2") == 0)
3167 fatal_at (id_tok, "non-convert operator conditionalized");
3169 if (!parsing_match_operand)
3170 fatal_at (id_tok, "conditional convert can only be used in "
3171 "match expression");
3172 eat_token (CPP_QUERY);
3174 else if (strcmp (id, "convert1") == 0
3175 || strcmp (id, "convert2") == 0
3176 || strcmp (id, "view_convert1") == 0
3177 || strcmp (id, "view_convert2") == 0)
3178 fatal_at (id_tok, "expected '?' after conditional operator");
3179 id_base *op = get_operator (id);
3181 fatal_at (id_tok, "unknown operator %s", id);
3183 user_id *p = dyn_cast<user_id *> (op);
3184 if (p && p->is_oper_list)
3186 if (active_fors.length() == 0)
3187 record_operlist (id_tok->src_loc, p);
3189 fatal_at (id_tok, "operator-list %s cannot be exapnded inside 'for'", id);
3195 capture = '@'<number> */
3198 parser::parse_capture (operand *op)
3200 eat_token (CPP_ATSIGN);
3201 const cpp_token *token = peek ();
3202 const char *id = NULL;
3203 if (token->type == CPP_NUMBER)
3205 else if (token->type == CPP_NAME)
3208 fatal_at (token, "expected number or identifier");
3209 unsigned next_id = capture_ids->elements ();
3211 unsigned &num = capture_ids->get_or_insert (id, &existed);
3214 return new capture (num, op);
3217 /* Parse an expression
3218 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
3221 parser::parse_expr ()
3223 expr *e = new expr (parse_operation ());
3224 const cpp_token *token = peek ();
3226 bool is_commutative = false;
3227 bool force_capture = false;
3228 const char *expr_type = NULL;
3230 if (token->type == CPP_COLON
3231 && !(token->flags & PREV_WHITE))
3233 eat_token (CPP_COLON);
3235 if (token->type == CPP_NAME
3236 && !(token->flags & PREV_WHITE))
3238 const char *s = get_ident ();
3239 if (!parsing_match_operand)
3247 is_commutative = true;
3248 else if (*sp == 's')
3250 e->force_single_use = true;
3251 force_capture = true;
3254 fatal_at (token, "flag %c not recognized", *sp);
3261 fatal_at (token, "expected flag or type specifying identifier");
3264 if (token->type == CPP_ATSIGN
3265 && !(token->flags & PREV_WHITE))
3266 op = parse_capture (e);
3267 else if (force_capture)
3269 unsigned num = capture_ids->elements ();
3272 sprintf (id, "__%u", num);
3273 capture_ids->get_or_insert (xstrdup (id), &existed);
3275 fatal_at (token, "reserved capture id '%s' already used", id);
3276 op = new capture (num, e);
3282 const cpp_token *token = peek ();
3283 if (token->type == CPP_CLOSE_PAREN)
3285 if (e->operation->nargs != -1
3286 && e->operation->nargs != (int) e->ops.length ())
3287 fatal_at (token, "'%s' expects %u operands, not %u",
3288 e->operation->id, e->operation->nargs, e->ops.length ());
3291 if (e->ops.length () == 2)
3292 e->is_commutative = true;
3294 fatal_at (token, "only binary operators or function with "
3295 "two arguments can be marked commutative");
3297 e->expr_type = expr_type;
3300 e->append_op (parse_op ());
3305 /* Lex native C code delimited by START recording the preprocessing tokens
3306 for later processing.
3307 c_expr = ('{'|'(') <pp token>... ('}'|')') */
3310 parser::parse_c_expr (cpp_ttype start)
3312 const cpp_token *token;
3315 vec<cpp_token> code = vNULL;
3316 unsigned nr_stmts = 0;
3318 if (start == CPP_OPEN_PAREN)
3319 end = CPP_CLOSE_PAREN;
3320 else if (start == CPP_OPEN_BRACE)
3321 end = CPP_CLOSE_BRACE;
3329 /* Count brace pairs to find the end of the expr to match. */
3330 if (token->type == start)
3332 else if (token->type == end
3336 /* This is a lame way of counting the number of statements. */
3337 if (token->type == CPP_SEMICOLON)
3340 /* If this is possibly a user-defined identifier mark it used. */
3341 if (token->type == CPP_NAME)
3343 id_base *idb = get_operator ((const char *)CPP_HASHNODE
3344 (token->val.node.node)->ident.str);
3346 if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
3347 record_operlist (token->src_loc, p);
3350 /* Record the token. */
3351 code.safe_push (*token);
3354 return new c_expr (r, code, nr_stmts, vNULL, capture_ids);
3357 /* Parse an operand which is either an expression, a predicate or
3358 a standalone capture.
3359 op = predicate | expr | c_expr | capture */
3364 const cpp_token *token = peek ();
3365 struct operand *op = NULL;
3366 if (token->type == CPP_OPEN_PAREN)
3368 eat_token (CPP_OPEN_PAREN);
3370 eat_token (CPP_CLOSE_PAREN);
3372 else if (token->type == CPP_OPEN_BRACE)
3374 op = parse_c_expr (CPP_OPEN_BRACE);
3378 /* Remaining ops are either empty or predicates */
3379 if (token->type == CPP_NAME)
3381 const char *id = get_ident ();
3382 id_base *opr = get_operator (id);
3384 fatal_at (token, "expected predicate name");
3385 if (operator_id *code = dyn_cast <operator_id *> (opr))
3387 if (code->nargs != 0)
3388 fatal_at (token, "using an operator with operands as predicate");
3389 /* Parse the zero-operand operator "predicates" as
3391 op = new expr (opr);
3393 else if (user_id *code = dyn_cast <user_id *> (opr))
3395 if (code->nargs != 0)
3396 fatal_at (token, "using an operator with operands as predicate");
3397 /* Parse the zero-operand operator "predicates" as
3399 op = new expr (opr);
3401 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
3402 op = new predicate (p);
3404 fatal_at (token, "using an unsupported operator as predicate");
3405 if (!parsing_match_operand)
3406 fatal_at (token, "predicates are only allowed in match expression");
3408 if (token->flags & PREV_WHITE)
3411 else if (token->type != CPP_COLON
3412 && token->type != CPP_ATSIGN)
3413 fatal_at (token, "expected expression or predicate");
3414 /* optionally followed by a capture and a predicate. */
3415 if (token->type == CPP_COLON)
3416 fatal_at (token, "not implemented: predicate on leaf operand");
3417 if (token->type == CPP_ATSIGN)
3418 op = parse_capture (op);
3424 /* Create a new simplify from the current parsing state and MATCH,
3425 MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS. */
3428 parser::push_simplify (vec<simplify *>& simplifiers,
3429 operand *match, source_location match_loc,
3430 operand *result, source_location result_loc)
3432 /* Build and push a temporary for operator list uses in expressions. */
3433 if (!oper_lists.is_empty ())
3434 active_fors.safe_push (oper_lists);
3436 simplifiers.safe_push
3437 (new simplify (match, match_loc, result, result_loc,
3438 active_ifs.copy (), active_fors.copy (), capture_ids));
3440 if (!oper_lists.is_empty ())
3445 simplify = 'simplify' <expr> <result-op>
3447 match = 'match' <ident> <expr> [<result-op>]
3449 <result-op> = <op> | <if> | <with>
3450 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
3451 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
3452 and fill SIMPLIFIERS with the results. */
3455 parser::parse_simplify (source_location match_location,
3456 vec<simplify *>& simplifiers, predicate_id *matcher,
3459 /* Reset the capture map. */
3461 capture_ids = new cid_map_t;
3462 /* Reset oper_lists and set. */
3463 hash_set <user_id *> olist;
3464 oper_lists_set = &olist;
3467 const cpp_token *loc = peek ();
3468 parsing_match_operand = true;
3469 struct operand *match = parse_op ();
3470 parsing_match_operand = false;
3471 if (match->type == operand::OP_CAPTURE && !matcher)
3472 fatal_at (loc, "outermost expression cannot be captured");
3473 if (match->type == operand::OP_EXPR
3474 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
3475 fatal_at (loc, "outermost expression cannot be a predicate");
3477 const cpp_token *token = peek ();
3479 /* If this if is immediately closed then it is part of a predicate
3480 definition. Push it. */
3481 if (token->type == CPP_CLOSE_PAREN)
3484 fatal_at (token, "expected transform expression");
3485 push_simplify (simplifiers, match, match_location,
3486 result, token->src_loc);
3490 unsigned active_ifs_len = active_ifs.length ();
3493 if (token->type == CPP_OPEN_PAREN)
3495 source_location paren_loc = token->src_loc;
3496 eat_token (CPP_OPEN_PAREN);
3497 if (peek_ident ("if"))
3500 active_ifs.safe_push (if_or_with (parse_c_expr (CPP_OPEN_PAREN),
3501 token->src_loc, false));
3502 /* If this if is immediately closed then it contains a
3503 manual matcher or is part of a predicate definition.
3505 if (peek ()->type == CPP_CLOSE_PAREN)
3508 fatal_at (token, "manual transform not implemented");
3509 push_simplify (simplifiers, match, match_location,
3513 else if (peek_ident ("with"))
3516 /* Parse (with c-expr expr) as (if-with (true) expr). */
3517 c_expr *e = parse_c_expr (CPP_OPEN_BRACE);
3519 active_ifs.safe_push (if_or_with (e, token->src_loc, true));
3523 operand *op = result;
3526 push_simplify (simplifiers, match, match_location,
3527 op, token->src_loc);
3528 eat_token (CPP_CLOSE_PAREN);
3529 /* A "default" result closes the enclosing scope. */
3530 if (active_ifs.length () > active_ifs_len)
3532 eat_token (CPP_CLOSE_PAREN);
3539 else if (token->type == CPP_CLOSE_PAREN)
3541 /* Close a scope if requested. */
3542 if (active_ifs.length () > active_ifs_len)
3544 eat_token (CPP_CLOSE_PAREN);
3554 fatal_at (token, "expected match operand expression");
3555 push_simplify (simplifiers, match, match_location,
3556 matcher ? result : parse_op (), token->src_loc);
3557 /* A "default" result closes the enclosing scope. */
3558 if (active_ifs.length () > active_ifs_len)
3560 eat_token (CPP_CLOSE_PAREN);
3570 /* Parsing of the outer control structures. */
3572 /* Parse a for expression
3573 for = '(' 'for' <subst>... <pattern> ')'
3574 subst = <ident> '(' <ident>... ')' */
3577 parser::parse_for (source_location)
3579 auto_vec<const cpp_token *> user_id_tokens;
3580 vec<user_id *> user_ids = vNULL;
3581 const cpp_token *token;
3582 unsigned min_n_opers = 0, max_n_opers = 0;
3587 if (token->type != CPP_NAME)
3590 /* Insert the user defined operators into the operator hash. */
3591 const char *id = get_ident ();
3592 if (get_operator (id) != NULL)
3593 fatal_at (token, "operator already defined");
3594 user_id *op = new user_id (id);
3595 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
3597 user_ids.safe_push (op);
3598 user_id_tokens.safe_push (token);
3600 eat_token (CPP_OPEN_PAREN);
3603 while ((token = peek_ident ()) != 0)
3605 const char *oper = get_ident ();
3606 id_base *idb = get_operator (oper);
3608 fatal_at (token, "no such operator '%s'", oper);
3609 if (*idb == CONVERT0 || *idb == CONVERT1 || *idb == CONVERT2
3610 || *idb == VIEW_CONVERT0 || *idb == VIEW_CONVERT1
3611 || *idb == VIEW_CONVERT2)
3612 fatal_at (token, "conditional operators cannot be used inside for");
3616 else if (idb->nargs == -1)
3618 else if (idb->nargs != arity)
3619 fatal_at (token, "operator '%s' with arity %d does not match "
3620 "others with arity %d", oper, idb->nargs, arity);
3622 user_id *p = dyn_cast<user_id *> (idb);
3625 if (p->is_oper_list)
3626 op->substitutes.safe_splice (p->substitutes);
3628 fatal_at (token, "iterator cannot be used as operator-list");
3631 op->substitutes.safe_push (idb);
3634 token = expect (CPP_CLOSE_PAREN);
3636 unsigned nsubstitutes = op->substitutes.length ();
3637 if (nsubstitutes == 0)
3638 fatal_at (token, "A user-defined operator must have at least "
3639 "one substitution");
3640 if (max_n_opers == 0)
3642 min_n_opers = nsubstitutes;
3643 max_n_opers = nsubstitutes;
3647 if (nsubstitutes % min_n_opers != 0
3648 && min_n_opers % nsubstitutes != 0)
3649 fatal_at (token, "All user-defined identifiers must have a "
3650 "multiple number of operator substitutions of the "
3651 "smallest number of substitutions");
3652 if (nsubstitutes < min_n_opers)
3653 min_n_opers = nsubstitutes;
3654 else if (nsubstitutes > max_n_opers)
3655 max_n_opers = nsubstitutes;
3659 unsigned n_ids = user_ids.length ();
3661 fatal_at (token, "for requires at least one user-defined identifier");
3664 if (token->type == CPP_CLOSE_PAREN)
3665 fatal_at (token, "no pattern defined in for");
3667 active_fors.safe_push (user_ids);
3671 if (token->type == CPP_CLOSE_PAREN)
3677 /* Remove user-defined operators from the hash again. */
3678 for (unsigned i = 0; i < user_ids.length (); ++i)
3680 if (!user_ids[i]->used)
3681 warning_at (user_id_tokens[i],
3682 "operator %s defined but not used", user_ids[i]->id);
3683 operators->remove_elt (user_ids[i]);
3687 /* Parse an identifier associated with a list of operators.
3688 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
3691 parser::parse_operator_list (source_location)
3693 const cpp_token *token = peek ();
3694 const char *id = get_ident ();
3696 if (get_operator (id) != 0)
3697 fatal_at (token, "operator %s already defined", id);
3699 user_id *op = new user_id (id, true);
3702 while ((token = peek_ident ()) != 0)
3705 const char *oper = get_ident ();
3706 id_base *idb = get_operator (oper);
3709 fatal_at (token, "no such operator '%s'", oper);
3713 else if (idb->nargs == -1)
3715 else if (arity != idb->nargs)
3716 fatal_at (token, "operator '%s' with arity %d does not match "
3717 "others with arity %d", oper, idb->nargs, arity);
3719 /* We allow composition of multiple operator lists. */
3720 if (user_id *p = dyn_cast<user_id *> (idb))
3721 op->substitutes.safe_splice (p->substitutes);
3723 op->substitutes.safe_push (idb);
3726 // Check that there is no junk after id-list
3728 if (token->type != CPP_CLOSE_PAREN)
3729 fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
3731 if (op->substitutes.length () == 0)
3732 fatal_at (token, "operator-list cannot be empty");
3735 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
3739 /* Parse an outer if expression.
3740 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
3743 parser::parse_if (source_location loc)
3745 operand *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
3747 const cpp_token *token = peek ();
3748 if (token->type == CPP_CLOSE_PAREN)
3749 fatal_at (token, "no pattern defined in if");
3751 active_ifs.safe_push (if_or_with (ifexpr, loc, false));
3754 const cpp_token *token = peek ();
3755 if (token->type == CPP_CLOSE_PAREN)
3763 /* Parse a list of predefined predicate identifiers.
3764 preds = '(' 'define_predicates' <ident>... ')' */
3767 parser::parse_predicates (source_location)
3771 const cpp_token *token = peek ();
3772 if (token->type != CPP_NAME)
3775 add_predicate (get_ident ());
3780 /* Parse outer control structures.
3781 pattern = <preds>|<for>|<if>|<simplify>|<match> */
3784 parser::parse_pattern ()
3786 /* All clauses start with '('. */
3787 eat_token (CPP_OPEN_PAREN);
3788 const cpp_token *token = peek ();
3789 const char *id = get_ident ();
3790 if (strcmp (id, "simplify") == 0)
3792 parse_simplify (token->src_loc, simplifiers, NULL, NULL);
3795 else if (strcmp (id, "match") == 0)
3797 bool with_args = false;
3798 if (peek ()->type == CPP_OPEN_PAREN)
3800 eat_token (CPP_OPEN_PAREN);
3803 const char *name = get_ident ();
3804 id_base *id = get_operator (name);
3808 p = add_predicate (name);
3809 user_predicates.safe_push (p);
3811 else if ((p = dyn_cast <predicate_id *> (id)))
3814 fatal_at (token, "cannot add a match to a non-predicate ID");
3815 /* Parse (match <id> <arg>... (match-expr)) here. */
3819 capture_ids = new cid_map_t;
3821 while (peek ()->type == CPP_ATSIGN)
3822 e->append_op (parse_capture (NULL));
3823 eat_token (CPP_CLOSE_PAREN);
3826 && ((e && e->ops.length () != (unsigned)p->nargs)
3827 || (!e && p->nargs != 0)))
3828 fatal_at (token, "non-matching number of match operands");
3829 p->nargs = e ? e->ops.length () : 0;
3830 parse_simplify (token->src_loc, p->matchers, p, e);
3833 else if (strcmp (id, "for") == 0)
3834 parse_for (token->src_loc);
3835 else if (strcmp (id, "if") == 0)
3836 parse_if (token->src_loc);
3837 else if (strcmp (id, "define_predicates") == 0)
3839 if (active_ifs.length () > 0
3840 || active_fors.length () > 0)
3841 fatal_at (token, "define_predicates inside if or for is not supported");
3842 parse_predicates (token->src_loc);
3844 else if (strcmp (id, "define_operator_list") == 0)
3846 if (active_ifs.length () > 0
3847 || active_fors.length () > 0)
3848 fatal_at (token, "operator-list inside if or for is not supported");
3849 parse_operator_list (token->src_loc);
3852 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
3853 active_ifs.length () == 0 && active_fors.length () == 0
3854 ? "'define_predicates', " : "");
3856 eat_token (CPP_CLOSE_PAREN);
3859 /* Main entry of the parser. Repeatedly parse outer control structures. */
3861 parser::parser (cpp_reader *r_)
3865 active_fors = vNULL;
3866 simplifiers = vNULL;
3867 oper_lists_set = NULL;
3870 user_predicates = vNULL;
3871 parsing_match_operand = false;
3873 const cpp_token *token = next ();
3874 while (token->type != CPP_EOF)
3876 _cpp_backup_tokens (r, 1);
3883 /* Helper for the linemap code. */
3886 round_alloc_size (size_t s)
3892 /* The genmatch generator progam. It reads from a pattern description
3893 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
3896 main (int argc, char **argv)
3900 progname = "genmatch";
3906 bool verbose = false;
3907 char *input = argv[argc-1];
3908 for (int i = 1; i < argc - 1; ++i)
3910 if (strcmp (argv[i], "--gimple") == 0)
3912 else if (strcmp (argv[i], "--generic") == 0)
3914 else if (strcmp (argv[i], "-v") == 0)
3918 fprintf (stderr, "Usage: genmatch "
3919 "[--gimple] [--generic] [-v] input\n");
3924 line_table = XCNEW (struct line_maps);
3925 linemap_init (line_table, 0);
3926 line_table->reallocator = xrealloc;
3927 line_table->round_alloc_size = round_alloc_size;
3929 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
3930 cpp_callbacks *cb = cpp_get_callbacks (r);
3931 cb->error = error_cb;
3933 if (!cpp_read_main_file (r, input))
3935 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
3936 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
3938 /* Pre-seed operators. */
3939 operators = new hash_table<id_base> (1024);
3940 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
3941 add_operator (SYM, # SYM, # TYPE, NARGS);
3942 #define END_OF_BASE_TREE_CODES
3944 add_operator (CONVERT0, "CONVERT0", "tcc_unary", 1);
3945 add_operator (CONVERT1, "CONVERT1", "tcc_unary", 1);
3946 add_operator (CONVERT2, "CONVERT2", "tcc_unary", 1);
3947 add_operator (VIEW_CONVERT0, "VIEW_CONVERT0", "tcc_unary", 1);
3948 add_operator (VIEW_CONVERT1, "VIEW_CONVERT1", "tcc_unary", 1);
3949 add_operator (VIEW_CONVERT2, "VIEW_CONVERT2", "tcc_unary", 1);
3950 #undef END_OF_BASE_TREE_CODES
3953 /* Pre-seed builtin functions.
3954 ??? Cannot use N (name) as that is targetm.emultls.get_address
3955 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
3956 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
3957 add_builtin (ENUM, # ENUM);
3958 #include "builtins.def"
3965 write_header (stdout, "gimple-match-head.c");
3967 write_header (stdout, "generic-match-head.c");
3969 /* Go over all predicates defined with patterns and perform
3970 lowering and code generation. */
3971 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
3973 predicate_id *pred = p.user_predicates[i];
3974 lower (pred->matchers, gimple);
3977 for (unsigned i = 0; i < pred->matchers.length (); ++i)
3978 print_matches (pred->matchers[i]);
3981 for (unsigned i = 0; i < pred->matchers.length (); ++i)
3982 dt.insert (pred->matchers[i], i);
3987 write_predicate (stdout, pred, dt, gimple);
3990 /* Lower the main simplifiers and generate code for them. */
3991 lower (p.simplifiers, gimple);
3994 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
3995 print_matches (p.simplifiers[i]);
3998 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
3999 dt.insert (p.simplifiers[i], i);
4005 dt.gen_gimple (stdout);
4007 dt.gen_generic (stdout);
4010 cpp_finish (r, NULL);