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 /* Verboseness. 0 is quiet, 1 adds some warnings, 2 is for debugging. */
54 static struct line_maps *line_table;
57 #if GCC_VERSION >= 4001
58 __attribute__((format (printf, 6, 0)))
60 error_cb (cpp_reader *, int errtype, int, source_location location,
61 unsigned int, const char *msg, va_list *ap)
63 const line_map_ordinary *map;
64 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
65 expanded_location loc = linemap_expand_location (line_table, map, location);
66 fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
67 (errtype == CPP_DL_WARNING) ? "warning" : "error");
68 vfprintf (stderr, msg, *ap);
69 fprintf (stderr, "\n");
70 FILE *f = fopen (loc.file, "r");
76 if (!fgets (buf, 128, f))
78 if (buf[strlen (buf) - 1] != '\n')
85 fprintf (stderr, "%s", buf);
86 for (int i = 0; i < loc.column - 1; ++i)
94 if (errtype == CPP_DL_FATAL)
100 #if GCC_VERSION >= 4001
101 __attribute__((format (printf, 2, 3)))
103 fatal_at (const cpp_token *tk, const char *msg, ...)
107 error_cb (NULL, CPP_DL_FATAL, 0, tk->src_loc, 0, msg, &ap);
112 #if GCC_VERSION >= 4001
113 __attribute__((format (printf, 2, 3)))
115 fatal_at (source_location loc, const char *msg, ...)
119 error_cb (NULL, CPP_DL_FATAL, 0, loc, 0, msg, &ap);
124 #if GCC_VERSION >= 4001
125 __attribute__((format (printf, 2, 3)))
127 warning_at (const cpp_token *tk, const char *msg, ...)
131 error_cb (NULL, CPP_DL_WARNING, 0, tk->src_loc, 0, msg, &ap);
136 #if GCC_VERSION >= 4001
137 __attribute__((format (printf, 2, 3)))
139 warning_at (source_location loc, const char *msg, ...)
143 error_cb (NULL, CPP_DL_WARNING, 0, loc, 0, msg, &ap);
147 /* Like fprintf, but print INDENT spaces at the beginning. */
150 #if GCC_VERSION >= 4001
151 __attribute__((format (printf, 3, 4)))
153 fprintf_indent (FILE *f, unsigned int indent, const char *format, ...)
156 for (; indent >= 8; indent -= 8)
158 fprintf (f, "%*s", indent, "");
159 va_start (ap, format);
160 vfprintf (f, format, ap);
165 output_line_directive (FILE *f, source_location location,
166 bool dumpfile = false)
168 const line_map_ordinary *map;
169 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
170 expanded_location loc = linemap_expand_location (line_table, map, location);
173 /* When writing to a dumpfile only dump the filename. */
174 const char *file = strrchr (loc.file, DIR_SEPARATOR);
179 fprintf (f, "%s:%d", file, loc.line);
182 /* Other gen programs really output line directives here, at least for
183 development it's right now more convenient to have line information
184 from the generated file. Still keep the directives as comment for now
185 to easily back-point to the meta-description. */
186 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
190 /* Pull in tree codes and builtin function codes from their
193 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
206 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
207 enum built_in_function {
208 #include "builtins.def"
213 /* Return true if CODE represents a commutative tree code. Otherwise
216 commutative_tree_code (enum tree_code code)
222 case MULT_HIGHPART_EXPR:
237 case WIDEN_MULT_EXPR:
238 case VEC_WIDEN_MULT_HI_EXPR:
239 case VEC_WIDEN_MULT_LO_EXPR:
240 case VEC_WIDEN_MULT_EVEN_EXPR:
241 case VEC_WIDEN_MULT_ODD_EXPR:
250 /* Return true if CODE represents a ternary tree code for which the
251 first two operands are commutative. Otherwise return false. */
253 commutative_ternary_tree_code (enum tree_code code)
257 case WIDEN_MULT_PLUS_EXPR:
258 case WIDEN_MULT_MINUS_EXPR:
270 /* Base class for all identifiers the parser knows. */
272 struct id_base : nofree_ptr_hash<id_base>
274 enum id_kind { CODE, FN, PREDICATE, USER } kind;
276 id_base (id_kind, const char *, int = -1);
282 /* hash_table support. */
283 static inline hashval_t hash (const id_base *);
284 static inline int equal (const id_base *, const id_base *);
288 id_base::hash (const id_base *op)
294 id_base::equal (const id_base *op1,
297 return (op1->hashval == op2->hashval
298 && strcmp (op1->id, op2->id) == 0);
301 /* Hashtable of known pattern operators. This is pre-seeded from
302 all known tree codes and all known builtin function ids. */
303 static hash_table<id_base> *operators;
305 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
310 hashval = htab_hash_string (id);
313 /* Identifier that maps to a tree code. */
315 struct operator_id : public id_base
317 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
319 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
324 /* Identifier that maps to a builtin function code. */
326 struct fn_id : public id_base
328 fn_id (enum built_in_function fn_, const char *id_)
329 : id_base (id_base::FN, id_), fn (fn_) {}
330 enum built_in_function fn;
335 /* Identifier that maps to a user-defined predicate. */
337 struct predicate_id : public id_base
339 predicate_id (const char *id_)
340 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
341 vec<simplify *> matchers;
344 /* Identifier that maps to a operator defined by a 'for' directive. */
346 struct user_id : public id_base
348 user_id (const char *id_, bool is_oper_list_ = false)
349 : id_base (id_base::USER, id_), substitutes (vNULL),
350 used (false), is_oper_list (is_oper_list_) {}
351 vec<id_base *> substitutes;
359 is_a_helper <fn_id *>::test (id_base *id)
361 return id->kind == id_base::FN;
367 is_a_helper <operator_id *>::test (id_base *id)
369 return id->kind == id_base::CODE;
375 is_a_helper <predicate_id *>::test (id_base *id)
377 return id->kind == id_base::PREDICATE;
383 is_a_helper <user_id *>::test (id_base *id)
385 return id->kind == id_base::USER;
388 /* Add a predicate identifier to the hash. */
390 static predicate_id *
391 add_predicate (const char *id)
393 predicate_id *p = new predicate_id (id);
394 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
396 fatal ("duplicate id definition");
401 /* Add a tree code identifier to the hash. */
404 add_operator (enum tree_code code, const char *id,
405 const char *tcc, unsigned nargs)
407 if (strcmp (tcc, "tcc_unary") != 0
408 && strcmp (tcc, "tcc_binary") != 0
409 && strcmp (tcc, "tcc_comparison") != 0
410 && strcmp (tcc, "tcc_expression") != 0
411 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
412 && strcmp (tcc, "tcc_reference") != 0
413 /* To have INTEGER_CST and friends as "predicate operators". */
414 && strcmp (tcc, "tcc_constant") != 0
415 /* And allow CONSTRUCTOR for vector initializers. */
416 && !(code == CONSTRUCTOR)
417 /* Allow SSA_NAME as predicate operator. */
418 && !(code == SSA_NAME))
420 /* Treat ADDR_EXPR as atom, thus don't allow matching its operand. */
421 if (code == ADDR_EXPR)
423 operator_id *op = new operator_id (code, id, nargs, tcc);
424 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
426 fatal ("duplicate id definition");
430 /* Add a builtin identifier to the hash. */
433 add_builtin (enum built_in_function code, const char *id)
435 fn_id *fn = new fn_id (code, id);
436 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
438 fatal ("duplicate id definition");
442 /* Helper for easy comparing ID with tree code CODE. */
445 operator==(id_base &id, enum tree_code code)
447 if (operator_id *oid = dyn_cast <operator_id *> (&id))
448 return oid->code == code;
452 /* Lookup the identifier ID. */
455 get_operator (const char *id)
457 id_base tem (id_base::CODE, id);
459 id_base *op = operators->find_with_hash (&tem, tem.hashval);
462 /* If this is a user-defined identifier track whether it was used. */
463 if (user_id *uid = dyn_cast<user_id *> (op))
468 /* Try all-uppercase. */
469 char *id2 = xstrdup (id);
470 for (unsigned i = 0; i < strlen (id2); ++i)
471 id2[i] = TOUPPER (id2[i]);
472 new (&tem) id_base (id_base::CODE, id2);
473 op = operators->find_with_hash (&tem, tem.hashval);
480 /* Try _EXPR appended. */
481 id2 = (char *)xrealloc (id2, strlen (id2) + sizeof ("_EXPR") + 1);
482 strcat (id2, "_EXPR");
483 new (&tem) id_base (id_base::CODE, id2);
484 op = operators->find_with_hash (&tem, tem.hashval);
494 typedef hash_map<nofree_string_hash, unsigned> cid_map_t;
497 /* The AST produced by parsing of the pattern definitions. */
502 /* The base class for operands. */
505 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR, OP_IF, OP_WITH };
506 operand (enum op_type type_, source_location loc_)
507 : type (type_), location (loc_) {}
509 source_location location;
510 virtual void gen_transform (FILE *, int, const char *, bool, int,
511 const char *, capture_info *,
514 { gcc_unreachable (); }
517 /* A predicate operand. Predicates are leafs in the AST. */
519 struct predicate : public operand
521 predicate (predicate_id *p_, source_location loc)
522 : operand (OP_PREDICATE, loc), p (p_) {}
526 /* An operand that constitutes an expression. Expressions include
527 function calls and user-defined predicate invocations. */
529 struct expr : public operand
531 expr (id_base *operation_, source_location loc, bool is_commutative_ = false)
532 : operand (OP_EXPR, loc), operation (operation_),
533 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
534 is_generic (false), force_single_use (false) {}
536 : operand (OP_EXPR, e->location), operation (e->operation),
537 ops (vNULL), expr_type (e->expr_type), is_commutative (e->is_commutative),
538 is_generic (e->is_generic), force_single_use (e->force_single_use) {}
539 void append_op (operand *op) { ops.safe_push (op); }
540 /* The operator and its operands. */
543 /* An explicitely specified type - used exclusively for conversions. */
544 const char *expr_type;
545 /* Whether the operation is to be applied commutatively. This is
546 later lowered to two separate patterns. */
548 /* Whether the expression is expected to be in GENERIC form. */
550 /* Whether pushing any stmt to the sequence should be conditional
551 on this expression having a single-use. */
552 bool force_single_use;
553 virtual void gen_transform (FILE *f, int, const char *, bool, int,
554 const char *, capture_info *,
555 dt_operand ** = 0, bool = true);
558 /* An operator that is represented by native C code. This is always
559 a leaf operand in the AST. This class is also used to represent
560 the code to be generated for 'if' and 'with' expressions. */
562 struct c_expr : public operand
564 /* A mapping of an identifier and its replacement. Used to apply
569 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
572 c_expr (cpp_reader *r_, source_location loc,
573 vec<cpp_token> code_, unsigned nr_stmts_,
574 vec<id_tab> ids_, cid_map_t *capture_ids_)
575 : operand (OP_C_EXPR, loc), r (r_), code (code_),
576 capture_ids (capture_ids_), nr_stmts (nr_stmts_), ids (ids_) {}
577 /* cpplib tokens and state to transform this back to source. */
580 cid_map_t *capture_ids;
581 /* The number of statements parsed (well, the number of ';'s). */
583 /* The identifier replacement vector. */
585 virtual void gen_transform (FILE *f, int, const char *, bool, int,
586 const char *, capture_info *,
587 dt_operand ** = 0, bool = true);
590 /* A wrapper around another operand that captures its value. */
592 struct capture : public operand
594 capture (source_location loc, unsigned where_, operand *what_)
595 : operand (OP_CAPTURE, loc), where (where_), what (what_) {}
596 /* Identifier index for the value. */
598 /* The captured value. */
600 virtual void gen_transform (FILE *f, int, const char *, bool, int,
601 const char *, capture_info *,
602 dt_operand ** = 0, bool = true);
607 struct if_expr : public operand
609 if_expr (source_location loc)
610 : operand (OP_IF, loc), cond (NULL), trueexpr (NULL), falseexpr (NULL) {}
616 /* with expression. */
618 struct with_expr : public operand
620 with_expr (source_location loc)
621 : operand (OP_WITH, loc), with (NULL), subexpr (NULL) {}
629 is_a_helper <capture *>::test (operand *op)
631 return op->type == operand::OP_CAPTURE;
637 is_a_helper <predicate *>::test (operand *op)
639 return op->type == operand::OP_PREDICATE;
645 is_a_helper <c_expr *>::test (operand *op)
647 return op->type == operand::OP_C_EXPR;
653 is_a_helper <expr *>::test (operand *op)
655 return op->type == operand::OP_EXPR;
661 is_a_helper <if_expr *>::test (operand *op)
663 return op->type == operand::OP_IF;
669 is_a_helper <with_expr *>::test (operand *op)
671 return op->type == operand::OP_WITH;
674 /* The main class of a pattern and its transform. This is used to
675 represent both (simplify ...) and (match ...) kinds. The AST
676 duplicates all outer 'if' and 'for' expressions here so each
677 simplify can exist in isolation. */
681 enum simplify_kind { SIMPLIFY, MATCH };
683 simplify (simplify_kind kind_, operand *match_, operand *result_,
684 vec<vec<user_id *> > for_vec_, cid_map_t *capture_ids_)
685 : kind (kind_), match (match_), result (result_),
687 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
690 /* The expression that is matched against the GENERIC or GIMPLE IL. */
692 /* For a (simplify ...) an expression with ifs and withs with the expression
693 produced when the pattern applies in the leafs.
694 For a (match ...) the leafs are either empty if it is a simple predicate
695 or the single expression specifying the matched operands. */
696 struct operand *result;
697 /* Collected 'for' expression operators that have to be replaced
698 in the lowering phase. */
699 vec<vec<user_id *> > for_vec;
700 /* A map of capture identifiers to indexes. */
701 cid_map_t *capture_ids;
705 /* Debugging routines for dumping the AST. */
708 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
710 if (capture *c = dyn_cast<capture *> (o))
712 fprintf (f, "@%u", c->where);
713 if (c->what && flattened == false)
716 print_operand (c->what, f, flattened);
721 else if (predicate *p = dyn_cast<predicate *> (o))
722 fprintf (f, "%s", p->p->id);
724 else if (is_a<c_expr *> (o))
725 fprintf (f, "c_expr");
727 else if (expr *e = dyn_cast<expr *> (o))
729 fprintf (f, "(%s", e->operation->id);
731 if (flattened == false)
734 for (unsigned i = 0; i < e->ops.length (); ++i)
736 print_operand (e->ops[i], f, flattened);
748 print_matches (struct simplify *s, FILE *f = stderr)
750 fprintf (f, "for expression: ");
751 print_operand (s->match, f);
758 /* Lowering of commutative operators. */
761 cartesian_product (const vec< vec<operand *> >& ops_vector,
762 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
764 if (n == ops_vector.length ())
766 vec<operand *> xv = v.copy ();
767 result.safe_push (xv);
771 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
773 v[n] = ops_vector[n][i];
774 cartesian_product (ops_vector, result, v, n + 1);
778 /* Lower OP to two operands in case it is marked as commutative. */
780 static vec<operand *>
781 commutate (operand *op)
783 vec<operand *> ret = vNULL;
785 if (capture *c = dyn_cast <capture *> (op))
792 vec<operand *> v = commutate (c->what);
793 for (unsigned i = 0; i < v.length (); ++i)
795 capture *nc = new capture (c->location, c->where, v[i]);
801 expr *e = dyn_cast <expr *> (op);
802 if (!e || e->ops.length () == 0)
808 vec< vec<operand *> > ops_vector = vNULL;
809 for (unsigned i = 0; i < e->ops.length (); ++i)
810 ops_vector.safe_push (commutate (e->ops[i]));
812 auto_vec< vec<operand *> > result;
813 auto_vec<operand *> v (e->ops.length ());
814 v.quick_grow_cleared (e->ops.length ());
815 cartesian_product (ops_vector, result, v, 0);
818 for (unsigned i = 0; i < result.length (); ++i)
820 expr *ne = new expr (e);
821 ne->is_commutative = false;
822 for (unsigned j = 0; j < result[i].length (); ++j)
823 ne->append_op (result[i][j]);
827 if (!e->is_commutative)
830 for (unsigned i = 0; i < result.length (); ++i)
832 expr *ne = new expr (e);
833 ne->is_commutative = false;
834 // result[i].length () is 2 since e->operation is binary
835 for (unsigned j = result[i].length (); j; --j)
836 ne->append_op (result[i][j-1]);
843 /* Lower operations marked as commutative in the AST of S and push
844 the resulting patterns to SIMPLIFIERS. */
847 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
849 vec<operand *> matchers = commutate (s->match);
850 for (unsigned i = 0; i < matchers.length (); ++i)
852 simplify *ns = new simplify (s->kind, matchers[i], s->result,
853 s->for_vec, s->capture_ids);
854 simplifiers.safe_push (ns);
858 /* Strip conditional conversios using operator OPER from O and its
859 children if STRIP, else replace them with an unconditional convert. */
862 lower_opt_convert (operand *o, enum tree_code oper,
863 enum tree_code to_oper, bool strip)
865 if (capture *c = dyn_cast<capture *> (o))
868 return new capture (c->location, c->where,
869 lower_opt_convert (c->what, oper, to_oper, strip));
874 expr *e = dyn_cast<expr *> (o);
878 if (*e->operation == oper)
881 return lower_opt_convert (e->ops[0], oper, to_oper, strip);
883 expr *ne = new expr (e);
884 ne->operation = (to_oper == CONVERT_EXPR
885 ? get_operator ("CONVERT_EXPR")
886 : get_operator ("VIEW_CONVERT_EXPR"));
887 ne->append_op (lower_opt_convert (e->ops[0], oper, to_oper, strip));
891 expr *ne = new expr (e);
892 for (unsigned i = 0; i < e->ops.length (); ++i)
893 ne->append_op (lower_opt_convert (e->ops[i], oper, to_oper, strip));
898 /* Determine whether O or its children uses the conditional conversion
902 has_opt_convert (operand *o, enum tree_code oper)
904 if (capture *c = dyn_cast<capture *> (o))
907 return has_opt_convert (c->what, oper);
912 expr *e = dyn_cast<expr *> (o);
916 if (*e->operation == oper)
919 for (unsigned i = 0; i < e->ops.length (); ++i)
920 if (has_opt_convert (e->ops[i], oper))
926 /* Lower conditional convert operators in O, expanding it to a vector
929 static vec<operand *>
930 lower_opt_convert (operand *o)
932 vec<operand *> v1 = vNULL, v2;
936 enum tree_code opers[]
937 = { CONVERT0, CONVERT_EXPR,
938 CONVERT1, CONVERT_EXPR,
939 CONVERT2, CONVERT_EXPR,
940 VIEW_CONVERT0, VIEW_CONVERT_EXPR,
941 VIEW_CONVERT1, VIEW_CONVERT_EXPR,
942 VIEW_CONVERT2, VIEW_CONVERT_EXPR };
944 /* Conditional converts are lowered to a pattern with the
945 conversion and one without. The three different conditional
946 convert codes are lowered separately. */
948 for (unsigned i = 0; i < sizeof (opers) / sizeof (enum tree_code); i += 2)
951 for (unsigned j = 0; j < v1.length (); ++j)
952 if (has_opt_convert (v1[j], opers[i]))
954 v2.safe_push (lower_opt_convert (v1[j],
955 opers[i], opers[i+1], false));
956 v2.safe_push (lower_opt_convert (v1[j],
957 opers[i], opers[i+1], true));
963 for (unsigned j = 0; j < v2.length (); ++j)
964 v1.safe_push (v2[j]);
971 /* Lower conditional convert operators in the AST of S and push
972 the resulting multiple patterns to SIMPLIFIERS. */
975 lower_opt_convert (simplify *s, vec<simplify *>& simplifiers)
977 vec<operand *> matchers = lower_opt_convert (s->match);
978 for (unsigned i = 0; i < matchers.length (); ++i)
980 simplify *ns = new simplify (s->kind, matchers[i], s->result,
981 s->for_vec, s->capture_ids);
982 simplifiers.safe_push (ns);
986 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
987 GENERIC and a GIMPLE variant. */
989 static vec<operand *>
990 lower_cond (operand *o)
992 vec<operand *> ro = vNULL;
994 if (capture *c = dyn_cast<capture *> (o))
998 vec<operand *> lop = vNULL;
999 lop = lower_cond (c->what);
1001 for (unsigned i = 0; i < lop.length (); ++i)
1002 ro.safe_push (new capture (c->location, c->where, lop[i]));
1007 expr *e = dyn_cast<expr *> (o);
1008 if (!e || e->ops.length () == 0)
1014 vec< vec<operand *> > ops_vector = vNULL;
1015 for (unsigned i = 0; i < e->ops.length (); ++i)
1016 ops_vector.safe_push (lower_cond (e->ops[i]));
1018 auto_vec< vec<operand *> > result;
1019 auto_vec<operand *> v (e->ops.length ());
1020 v.quick_grow_cleared (e->ops.length ());
1021 cartesian_product (ops_vector, result, v, 0);
1023 for (unsigned i = 0; i < result.length (); ++i)
1025 expr *ne = new expr (e);
1026 for (unsigned j = 0; j < result[i].length (); ++j)
1027 ne->append_op (result[i][j]);
1029 /* If this is a COND with a captured expression or an
1030 expression with two operands then also match a GENERIC
1031 form on the compare. */
1032 if ((*e->operation == COND_EXPR
1033 || *e->operation == VEC_COND_EXPR)
1034 && ((is_a <capture *> (e->ops[0])
1035 && as_a <capture *> (e->ops[0])->what
1036 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
1038 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
1039 || (is_a <expr *> (e->ops[0])
1040 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
1042 expr *ne = new expr (e);
1043 for (unsigned j = 0; j < result[i].length (); ++j)
1044 ne->append_op (result[i][j]);
1045 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
1047 expr *ocmp = as_a <expr *> (c->what);
1048 expr *cmp = new expr (ocmp);
1049 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1050 cmp->append_op (ocmp->ops[j]);
1051 cmp->is_generic = true;
1052 ne->ops[0] = new capture (c->location, c->where, cmp);
1056 expr *ocmp = as_a <expr *> (ne->ops[0]);
1057 expr *cmp = new expr (ocmp);
1058 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1059 cmp->append_op (ocmp->ops[j]);
1060 cmp->is_generic = true;
1070 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1071 GENERIC and a GIMPLE variant. */
1074 lower_cond (simplify *s, vec<simplify *>& simplifiers)
1076 vec<operand *> matchers = lower_cond (s->match);
1077 for (unsigned i = 0; i < matchers.length (); ++i)
1079 simplify *ns = new simplify (s->kind, matchers[i], s->result,
1080 s->for_vec, s->capture_ids);
1081 simplifiers.safe_push (ns);
1085 /* In AST operand O replace operator ID with operator WITH. */
1088 replace_id (operand *o, user_id *id, id_base *with)
1090 /* Deep-copy captures and expressions, replacing operations as
1092 if (capture *c = dyn_cast<capture *> (o))
1096 return new capture (c->location, c->where,
1097 replace_id (c->what, id, with));
1099 else if (expr *e = dyn_cast<expr *> (o))
1101 expr *ne = new expr (e);
1102 if (e->operation == id)
1103 ne->operation = with;
1104 for (unsigned i = 0; i < e->ops.length (); ++i)
1105 ne->append_op (replace_id (e->ops[i], id, with));
1108 else if (with_expr *w = dyn_cast <with_expr *> (o))
1110 with_expr *nw = new with_expr (w->location);
1111 nw->with = as_a <c_expr *> (replace_id (w->with, id, with));
1112 nw->subexpr = replace_id (w->subexpr, id, with);
1115 else if (if_expr *ife = dyn_cast <if_expr *> (o))
1117 if_expr *nife = new if_expr (ife->location);
1118 nife->cond = as_a <c_expr *> (replace_id (ife->cond, id, with));
1119 nife->trueexpr = replace_id (ife->trueexpr, id, with);
1121 nife->falseexpr = replace_id (ife->falseexpr, id, with);
1125 /* For c_expr we simply record a string replacement table which is
1126 applied at code-generation time. */
1127 if (c_expr *ce = dyn_cast<c_expr *> (o))
1129 vec<c_expr::id_tab> ids = ce->ids.copy ();
1130 ids.safe_push (c_expr::id_tab (id->id, with->id));
1131 return new c_expr (ce->r, ce->location,
1132 ce->code, ce->nr_stmts, ids, ce->capture_ids);
1138 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
1141 lower_for (simplify *sin, vec<simplify *>& simplifiers)
1143 vec<vec<user_id *> >& for_vec = sin->for_vec;
1144 unsigned worklist_start = 0;
1145 auto_vec<simplify *> worklist;
1146 worklist.safe_push (sin);
1148 /* Lower each recorded for separately, operating on the
1149 set of simplifiers created by the previous one.
1150 Lower inner-to-outer so inner for substitutes can refer
1151 to operators replaced by outer fors. */
1152 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1154 vec<user_id *>& ids = for_vec[fi];
1155 unsigned n_ids = ids.length ();
1156 unsigned max_n_opers = 0;
1157 for (unsigned i = 0; i < n_ids; ++i)
1158 if (ids[i]->substitutes.length () > max_n_opers)
1159 max_n_opers = ids[i]->substitutes.length ();
1161 unsigned worklist_end = worklist.length ();
1162 for (unsigned si = worklist_start; si < worklist_end; ++si)
1164 simplify *s = worklist[si];
1165 for (unsigned j = 0; j < max_n_opers; ++j)
1167 operand *match_op = s->match;
1168 operand *result_op = s->result;
1169 for (unsigned i = 0; i < n_ids; ++i)
1171 user_id *id = ids[i];
1172 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1173 match_op = replace_id (match_op, id, oper);
1175 result_op = replace_id (result_op, id, oper);
1177 simplify *ns = new simplify (s->kind, match_op, result_op,
1178 vNULL, s->capture_ids);
1179 worklist.safe_push (ns);
1182 worklist_start = worklist_end;
1185 /* Copy out the result from the last for lowering. */
1186 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1187 simplifiers.safe_push (worklist[i]);
1190 /* Lower the AST for everything in SIMPLIFIERS. */
1193 lower (vec<simplify *>& simplifiers, bool gimple)
1195 auto_vec<simplify *> out_simplifiers;
1196 for (unsigned i = 0; i < simplifiers.length (); ++i)
1197 lower_opt_convert (simplifiers[i], out_simplifiers);
1199 simplifiers.truncate (0);
1200 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1201 lower_commutative (out_simplifiers[i], simplifiers);
1203 out_simplifiers.truncate (0);
1205 for (unsigned i = 0; i < simplifiers.length (); ++i)
1206 lower_cond (simplifiers[i], out_simplifiers);
1208 out_simplifiers.safe_splice (simplifiers);
1211 simplifiers.truncate (0);
1212 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1213 lower_for (out_simplifiers[i], simplifiers);
1219 /* The decision tree built for generating GIMPLE and GENERIC pattern
1220 matching code. It represents the 'match' expression of all
1221 simplifies and has those as its leafs. */
1223 /* Decision tree base class, used for DT_TRUE and DT_NODE. */
1227 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1231 vec<dt_node *> kids;
1235 unsigned total_size;
1238 dt_node (enum dt_type type_): type (type_), level (0), kids (vNULL) {}
1240 dt_node *append_node (dt_node *);
1241 dt_node *append_op (operand *, dt_node *parent = 0, unsigned pos = 0);
1242 dt_node *append_true_op (dt_node *parent = 0, unsigned pos = 0);
1243 dt_node *append_match_op (dt_operand *, dt_node *parent = 0, unsigned pos = 0);
1244 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1246 virtual void gen (FILE *, int, bool) {}
1248 void gen_kids (FILE *, int, bool);
1249 void gen_kids_1 (FILE *, int, bool,
1250 vec<dt_operand *>, vec<dt_operand *>, vec<dt_operand *>,
1251 vec<dt_operand *>, vec<dt_operand *>, vec<dt_node *>);
1256 /* Generic decision tree node used for DT_OPERAND and DT_MATCH. */
1258 struct dt_operand : public dt_node
1261 dt_operand *match_dop;
1265 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1266 dt_operand *parent_ = 0, unsigned pos_ = 0)
1267 : dt_node (type), op (op_), match_dop (match_dop_),
1268 parent (parent_), pos (pos_) {}
1270 void gen (FILE *, int, bool);
1271 unsigned gen_predicate (FILE *, int, const char *, bool);
1272 unsigned gen_match_op (FILE *, int, const char *);
1274 unsigned gen_gimple_expr (FILE *, int);
1275 unsigned gen_generic_expr (FILE *, int, const char *);
1277 char *get_name (char *);
1278 void gen_opname (char *, unsigned);
1281 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1283 struct dt_simplify : public dt_node
1286 unsigned pattern_no;
1287 dt_operand **indexes;
1289 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1290 : dt_node (DT_SIMPLIFY), s (s_), pattern_no (pattern_no_),
1291 indexes (indexes_) {}
1293 void gen_1 (FILE *, int, bool, operand *);
1294 void gen (FILE *f, int, bool);
1300 is_a_helper <dt_operand *>::test (dt_node *n)
1302 return (n->type == dt_node::DT_OPERAND
1303 || n->type == dt_node::DT_MATCH);
1306 /* A container for the actual decision tree. */
1308 struct decision_tree
1312 void insert (struct simplify *, unsigned);
1313 void gen (FILE *f, bool gimple);
1314 void print (FILE *f = stderr);
1316 decision_tree () { root = new dt_node (dt_node::DT_NODE); }
1318 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1319 unsigned pos = 0, dt_node *parent = 0);
1320 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1321 static bool cmp_node (dt_node *, dt_node *);
1322 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1325 /* Compare two AST operands O1 and O2 and return true if they are equal. */
1328 cmp_operand (operand *o1, operand *o2)
1330 if (!o1 || !o2 || o1->type != o2->type)
1333 if (o1->type == operand::OP_PREDICATE)
1335 predicate *p1 = as_a<predicate *>(o1);
1336 predicate *p2 = as_a<predicate *>(o2);
1337 return p1->p == p2->p;
1339 else if (o1->type == operand::OP_EXPR)
1341 expr *e1 = static_cast<expr *>(o1);
1342 expr *e2 = static_cast<expr *>(o2);
1343 return (e1->operation == e2->operation
1344 && e1->is_generic == e2->is_generic);
1350 /* Compare two decision tree nodes N1 and N2 and return true if they
1354 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1356 if (!n1 || !n2 || n1->type != n2->type)
1362 if (n1->type == dt_node::DT_TRUE)
1365 if (n1->type == dt_node::DT_OPERAND)
1366 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1367 (as_a<dt_operand *> (n2))->op);
1368 else if (n1->type == dt_node::DT_MATCH)
1369 return ((as_a<dt_operand *> (n1))->match_dop
1370 == (as_a<dt_operand *> (n2))->match_dop);
1374 /* Search OPS for a decision tree node like P and return it if found. */
1377 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1379 /* We can merge adjacent DT_TRUE. */
1380 if (p->type == dt_node::DT_TRUE
1382 && ops.last ()->type == dt_node::DT_TRUE)
1384 for (int i = ops.length () - 1; i >= 0; --i)
1386 /* But we can't merge across DT_TRUE nodes as they serve as
1387 pattern order barriers to make sure that patterns apply
1388 in order of appearance in case multiple matches are possible. */
1389 if (ops[i]->type == dt_node::DT_TRUE)
1391 if (decision_tree::cmp_node (ops[i], p))
1397 /* Append N to the decision tree if it there is not already an existing
1401 dt_node::append_node (dt_node *n)
1405 kid = decision_tree::find_node (kids, n);
1410 n->level = this->level + 1;
1415 /* Append OP to the decision tree. */
1418 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1420 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1421 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1422 return append_node (n);
1425 /* Append a DT_TRUE decision tree node. */
1428 dt_node::append_true_op (dt_node *parent, unsigned pos)
1430 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1431 dt_operand *n = new dt_operand (DT_TRUE, 0, 0, parent_, pos);
1432 return append_node (n);
1435 /* Append a DT_MATCH decision tree node. */
1438 dt_node::append_match_op (dt_operand *match_dop, dt_node *parent, unsigned pos)
1440 dt_operand *parent_ = as_a<dt_operand *> (parent);
1441 dt_operand *n = new dt_operand (DT_MATCH, 0, match_dop, parent_, pos);
1442 return append_node (n);
1445 /* Append S to the decision tree. */
1448 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1449 dt_operand **indexes)
1451 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1452 return append_node (n);
1455 /* Analyze the node and its children. */
1464 if (type == DT_SIMPLIFY)
1470 for (unsigned i = 0; i < kids.length (); ++i)
1472 kids[i]->analyze ();
1473 num_leafs += kids[i]->num_leafs;
1474 total_size += kids[i]->total_size;
1475 max_level = MAX (max_level, kids[i]->max_level);
1479 /* Insert O into the decision tree and return the decision tree node found
1483 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1484 unsigned pos, dt_node *parent)
1486 dt_node *q, *elm = 0;
1488 if (capture *c = dyn_cast<capture *> (o))
1490 unsigned capt_index = c->where;
1492 if (indexes[capt_index] == 0)
1495 q = insert_operand (p, c->what, indexes, pos, parent);
1498 q = elm = p->append_true_op (parent, pos);
1501 // get to the last capture
1502 for (operand *what = c->what;
1503 what && is_a<capture *> (what);
1504 c = as_a<capture *> (what), what = c->what)
1509 unsigned cc_index = c->where;
1510 dt_operand *match_op = indexes[cc_index];
1512 dt_operand temp (dt_node::DT_TRUE, 0, 0);
1513 elm = decision_tree::find_node (p->kids, &temp);
1517 dt_operand temp (dt_node::DT_MATCH, 0, match_op);
1518 elm = decision_tree::find_node (p->kids, &temp);
1523 dt_operand temp (dt_node::DT_OPERAND, c->what, 0);
1524 elm = decision_tree::find_node (p->kids, &temp);
1528 gcc_assert (elm->type == dt_node::DT_TRUE
1529 || elm->type == dt_node::DT_OPERAND
1530 || elm->type == dt_node::DT_MATCH);
1531 indexes[capt_index] = static_cast<dt_operand *> (elm);
1536 p = p->append_match_op (indexes[capt_index], parent, pos);
1538 return insert_operand (p, c->what, indexes, 0, p);
1543 p = p->append_op (o, parent, pos);
1546 if (expr *e = dyn_cast <expr *>(o))
1548 for (unsigned i = 0; i < e->ops.length (); ++i)
1549 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
1555 /* Insert S into the decision tree. */
1558 decision_tree::insert (struct simplify *s, unsigned pattern_no)
1560 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
1561 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
1562 p->append_simplify (s, pattern_no, indexes);
1565 /* Debug functions to dump the decision tree. */
1568 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
1570 if (p->type == dt_node::DT_NODE)
1571 fprintf (f, "root");
1575 for (unsigned i = 0; i < indent; i++)
1578 if (p->type == dt_node::DT_OPERAND)
1580 dt_operand *dop = static_cast<dt_operand *>(p);
1581 print_operand (dop->op, f, true);
1583 else if (p->type == dt_node::DT_TRUE)
1584 fprintf (f, "true");
1585 else if (p->type == dt_node::DT_MATCH)
1586 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
1587 else if (p->type == dt_node::DT_SIMPLIFY)
1589 dt_simplify *s = static_cast<dt_simplify *> (p);
1590 fprintf (f, "simplify_%u { ", s->pattern_no);
1591 for (int i = 0; i <= s->s->capture_max; ++i)
1592 fprintf (f, "%p, ", (void *) s->indexes[i]);
1597 fprintf (stderr, " (%p), %u, %u\n", (void *) p, p->level, p->kids.length ());
1599 for (unsigned i = 0; i < p->kids.length (); ++i)
1600 decision_tree::print_node (p->kids[i], f, indent + 2);
1604 decision_tree::print (FILE *f)
1606 return decision_tree::print_node (root, f);
1610 /* For GENERIC we have to take care of wrapping multiple-used
1611 expressions with side-effects in save_expr and preserve side-effects
1612 of expressions with omit_one_operand. Analyze captures in
1613 match, result and with expressions and perform early-outs
1614 on the outermost match expression operands for cases we cannot
1619 capture_info (simplify *s, operand *, bool);
1620 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
1621 bool walk_result (operand *o, bool, operand *);
1622 void walk_c_expr (c_expr *);
1628 bool force_no_side_effects_p;
1629 bool force_single_use;
1630 bool cond_expr_cond_p;
1631 unsigned long toplevel_msk;
1632 int result_use_count;
1637 auto_vec<cinfo> info;
1638 unsigned long force_no_side_effects;
1642 /* Analyze captures in S. */
1644 capture_info::capture_info (simplify *s, operand *result, bool gimple_)
1649 if (s->kind == simplify::MATCH)
1651 force_no_side_effects = -1;
1655 force_no_side_effects = 0;
1656 info.safe_grow_cleared (s->capture_max + 1);
1657 for (int i = 0; i <= s->capture_max; ++i)
1658 info[i].same_as = i;
1660 e = as_a <expr *> (s->match);
1661 for (unsigned i = 0; i < e->ops.length (); ++i)
1662 walk_match (e->ops[i], i,
1663 (i != 0 && *e->operation == COND_EXPR)
1664 || *e->operation == TRUTH_ANDIF_EXPR
1665 || *e->operation == TRUTH_ORIF_EXPR,
1667 && (*e->operation == COND_EXPR
1668 || *e->operation == VEC_COND_EXPR));
1670 walk_result (s->result, false, result);
1673 /* Analyze captures in the match expression piece O. */
1676 capture_info::walk_match (operand *o, unsigned toplevel_arg,
1677 bool conditional_p, bool cond_expr_cond_p)
1679 if (capture *c = dyn_cast <capture *> (o))
1681 unsigned where = c->where;
1682 info[where].toplevel_msk |= 1 << toplevel_arg;
1683 info[where].force_no_side_effects_p |= conditional_p;
1684 info[where].cond_expr_cond_p |= cond_expr_cond_p;
1689 /* Recurse to exprs and captures. */
1690 if (is_a <capture *> (c->what)
1691 || is_a <expr *> (c->what))
1692 walk_match (c->what, toplevel_arg, conditional_p, false);
1693 /* We need to look past multiple captures to find a captured
1694 expression as with conditional converts two captures
1695 can be collapsed onto the same expression. Also collect
1696 what captures capture the same thing. */
1697 while (c->what && is_a <capture *> (c->what))
1699 c = as_a <capture *> (c->what);
1700 if (info[c->where].same_as != c->where
1701 && info[c->where].same_as != info[where].same_as)
1702 fatal_at (c->location, "cannot handle this collapsed capture");
1703 info[c->where].same_as = info[where].same_as;
1705 /* Mark expr (non-leaf) captures and forced single-use exprs. */
1708 && (e = dyn_cast <expr *> (c->what)))
1710 info[where].expr_p = true;
1711 info[where].force_single_use |= e->force_single_use;
1714 else if (expr *e = dyn_cast <expr *> (o))
1716 for (unsigned i = 0; i < e->ops.length (); ++i)
1718 bool cond_p = conditional_p;
1719 bool cond_expr_cond_p = false;
1720 if (i != 0 && *e->operation == COND_EXPR)
1722 else if (*e->operation == TRUTH_ANDIF_EXPR
1723 || *e->operation == TRUTH_ORIF_EXPR)
1726 && (*e->operation == COND_EXPR
1727 || *e->operation == VEC_COND_EXPR))
1728 cond_expr_cond_p = true;
1729 walk_match (e->ops[i], toplevel_arg, cond_p, cond_expr_cond_p);
1732 else if (is_a <predicate *> (o))
1734 /* Mark non-captured leafs toplevel arg for checking. */
1735 force_no_side_effects |= 1 << toplevel_arg;
1738 warning_at (o->location,
1739 "forcing no side-effects on possibly lost leaf");
1745 /* Analyze captures in the result expression piece O. Return true
1746 if RESULT was visited in one of the children. Only visit
1747 non-if/with children if they are rooted on RESULT. */
1750 capture_info::walk_result (operand *o, bool conditional_p, operand *result)
1752 if (capture *c = dyn_cast <capture *> (o))
1754 unsigned where = info[c->where].same_as;
1755 info[where].result_use_count++;
1756 /* If we substitute an expression capture we don't know
1757 which captures this will end up using (well, we don't
1758 compute that). Force the uses to be side-effect free
1759 which means forcing the toplevels that reach the
1760 expression side-effect free. */
1761 if (info[where].expr_p)
1762 force_no_side_effects |= info[where].toplevel_msk;
1763 /* Mark CSE capture uses as forced to have no side-effects. */
1765 && is_a <expr *> (c->what))
1767 info[where].cse_p = true;
1768 walk_result (c->what, true, result);
1771 else if (expr *e = dyn_cast <expr *> (o))
1773 for (unsigned i = 0; i < e->ops.length (); ++i)
1775 bool cond_p = conditional_p;
1776 if (i != 0 && *e->operation == COND_EXPR)
1778 else if (*e->operation == TRUTH_ANDIF_EXPR
1779 || *e->operation == TRUTH_ORIF_EXPR)
1781 walk_result (e->ops[i], cond_p, result);
1784 else if (if_expr *e = dyn_cast <if_expr *> (o))
1786 /* 'if' conditions should be all fine. */
1787 if (e->trueexpr == result)
1789 walk_result (e->trueexpr, false, result);
1792 if (e->falseexpr == result)
1794 walk_result (e->falseexpr, false, result);
1798 if (is_a <if_expr *> (e->trueexpr)
1799 || is_a <with_expr *> (e->trueexpr))
1800 res |= walk_result (e->trueexpr, false, result);
1802 && (is_a <if_expr *> (e->falseexpr)
1803 || is_a <with_expr *> (e->falseexpr)))
1804 res |= walk_result (e->falseexpr, false, result);
1807 else if (with_expr *e = dyn_cast <with_expr *> (o))
1809 bool res = (e->subexpr == result);
1811 || is_a <if_expr *> (e->subexpr)
1812 || is_a <with_expr *> (e->subexpr))
1813 res |= walk_result (e->subexpr, false, result);
1815 walk_c_expr (e->with);
1818 else if (c_expr *e = dyn_cast <c_expr *> (o))
1826 /* Look for captures in the C expr E. */
1829 capture_info::walk_c_expr (c_expr *e)
1831 /* Give up for C exprs mentioning captures not inside TREE_TYPE,
1832 TREE_REAL_CST, TREE_CODE or a predicate where they cannot
1833 really escape through. */
1834 unsigned p_depth = 0;
1835 for (unsigned i = 0; i < e->code.length (); ++i)
1837 const cpp_token *t = &e->code[i];
1838 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
1840 if (t->type == CPP_NAME
1841 && (strcmp ((const char *)CPP_HASHNODE
1842 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
1843 || strcmp ((const char *)CPP_HASHNODE
1844 (t->val.node.node)->ident.str, "TREE_CODE") == 0
1845 || strcmp ((const char *)CPP_HASHNODE
1846 (t->val.node.node)->ident.str, "TREE_REAL_CST") == 0
1847 || ((id = get_operator ((const char *)CPP_HASHNODE
1848 (t->val.node.node)->ident.str))
1849 && is_a <predicate_id *> (id)))
1850 && n->type == CPP_OPEN_PAREN)
1852 else if (t->type == CPP_CLOSE_PAREN
1855 else if (p_depth == 0
1856 && t->type == CPP_ATSIGN
1857 && (n->type == CPP_NUMBER
1858 || n->type == CPP_NAME)
1859 && !(n->flags & PREV_WHITE))
1862 if (n->type == CPP_NUMBER)
1863 id = (const char *)n->val.str.text;
1865 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
1866 unsigned where = *e->capture_ids->get(id);
1867 info[info[where].same_as].force_no_side_effects_p = true;
1870 warning_at (t, "capture escapes");
1876 /* Code generation off the decision tree and the refered AST nodes. */
1879 is_conversion (id_base *op)
1881 return (*op == CONVERT_EXPR
1883 || *op == FLOAT_EXPR
1884 || *op == FIX_TRUNC_EXPR
1885 || *op == VIEW_CONVERT_EXPR);
1888 /* Get the type to be used for generating operands of OP from the
1892 get_operand_type (id_base *op, const char *in_type,
1893 const char *expr_type,
1894 const char *other_oprnd_type)
1896 /* Generally operands whose type does not match the type of the
1897 expression generated need to know their types but match and
1898 thus can fall back to 'other_oprnd_type'. */
1899 if (is_conversion (op))
1900 return other_oprnd_type;
1901 else if (*op == REALPART_EXPR
1902 || *op == IMAGPART_EXPR)
1903 return other_oprnd_type;
1904 else if (is_a <operator_id *> (op)
1905 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
1906 return other_oprnd_type;
1909 /* Otherwise all types should match - choose one in order of
1916 return other_oprnd_type;
1920 /* Generate transform code for an expression. */
1923 expr::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
1924 int depth, const char *in_type, capture_info *cinfo,
1925 dt_operand **indexes, bool)
1927 bool conversion_p = is_conversion (operation);
1928 const char *type = expr_type;
1931 /* If there was a type specification in the pattern use it. */
1933 else if (conversion_p)
1934 /* For conversions we need to build the expression using the
1935 outer type passed in. */
1937 else if (*operation == REALPART_EXPR
1938 || *operation == IMAGPART_EXPR)
1940 /* __real and __imag use the component type of its operand. */
1941 sprintf (optype, "TREE_TYPE (TREE_TYPE (ops%d[0]))", depth);
1944 else if (is_a <operator_id *> (operation)
1945 && !strcmp (as_a <operator_id *> (operation)->tcc, "tcc_comparison"))
1947 /* comparisons use boolean_type_node (or what gets in), but
1948 their operands need to figure out the types themselves. */
1949 sprintf (optype, "boolean_type_node");
1952 else if (*operation == COND_EXPR
1953 || *operation == VEC_COND_EXPR)
1955 /* Conditions are of the same type as their first alternative. */
1956 sprintf (optype, "TREE_TYPE (ops%d[1])", depth);
1961 /* Other operations are of the same type as their first operand. */
1962 sprintf (optype, "TREE_TYPE (ops%d[0])", depth);
1966 fatal_at (location, "cannot determine type of operand");
1968 fprintf_indent (f, indent, "{\n");
1970 fprintf_indent (f, indent, "tree ops%d[%u], res;\n", depth, ops.length ());
1972 snprintf (op0type, 64, "TREE_TYPE (ops%d[0])", depth);
1973 for (unsigned i = 0; i < ops.length (); ++i)
1976 snprintf (dest, 32, "ops%d[%u]", depth, i);
1978 = get_operand_type (operation, in_type, expr_type,
1979 i == 0 ? NULL : op0type);
1980 ops[i]->gen_transform (f, indent, dest, gimple, depth + 1, optype,
1982 ((!(*operation == COND_EXPR)
1983 && !(*operation == VEC_COND_EXPR))
1988 if (*operation == CONVERT_EXPR)
1991 opr = operation->id;
1995 if (*operation == CONVERT_EXPR)
1997 fprintf_indent (f, indent,
1998 "if (%s != TREE_TYPE (ops%d[0])\n",
2000 fprintf_indent (f, indent,
2001 " && !useless_type_conversion_p (%s, TREE_TYPE (ops%d[0])))\n",
2003 fprintf_indent (f, indent + 2, "{\n");
2006 /* ??? Building a stmt can fail for various reasons here, seq being
2007 NULL or the stmt referencing SSA names occuring in abnormal PHIs.
2008 So if we fail here we should continue matching other patterns. */
2009 fprintf_indent (f, indent, "code_helper tem_code = %s;\n", opr);
2010 fprintf_indent (f, indent, "tree tem_ops[3] = { ");
2011 for (unsigned i = 0; i < ops.length (); ++i)
2012 fprintf (f, "ops%d[%u]%s", depth, i,
2013 i == ops.length () - 1 ? " };\n" : ", ");
2014 fprintf_indent (f, indent,
2015 "gimple_resimplify%d (lseq, &tem_code, %s, tem_ops, valueize);\n",
2016 ops.length (), type);
2017 fprintf_indent (f, indent,
2018 "res = maybe_push_res_to_seq (tem_code, %s, tem_ops, lseq);\n",
2020 fprintf_indent (f, indent,
2021 "if (!res) return false;\n");
2022 if (*operation == CONVERT_EXPR)
2025 fprintf_indent (f, indent, " }\n");
2026 fprintf_indent (f, indent, "else\n");
2027 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
2032 if (*operation == CONVERT_EXPR)
2034 fprintf_indent (f, indent, "if (TREE_TYPE (ops%d[0]) != %s)\n",
2038 if (operation->kind == id_base::CODE)
2039 fprintf_indent (f, indent, "res = fold_build%d_loc (loc, %s, %s",
2040 ops.length(), opr, type);
2042 fprintf_indent (f, indent, "res = build_call_expr_loc (loc, "
2043 "builtin_decl_implicit (%s), %d", opr, ops.length());
2044 for (unsigned i = 0; i < ops.length (); ++i)
2045 fprintf (f, ", ops%d[%u]", depth, i);
2046 fprintf (f, ");\n");
2047 if (*operation == CONVERT_EXPR)
2050 fprintf_indent (f, indent, "else\n");
2051 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
2054 fprintf_indent (f, indent, "%s = res;\n", dest);
2056 fprintf_indent (f, indent, "}\n");
2059 /* Generate code for a c_expr which is either the expression inside
2060 an if statement or a sequence of statements which computes a
2061 result to be stored to DEST. */
2064 c_expr::gen_transform (FILE *f, int indent, const char *dest,
2065 bool, int, const char *, capture_info *,
2066 dt_operand **, bool)
2068 if (dest && nr_stmts == 1)
2069 fprintf_indent (f, indent, "%s = ", dest);
2071 unsigned stmt_nr = 1;
2072 for (unsigned i = 0; i < code.length (); ++i)
2074 const cpp_token *token = &code[i];
2076 /* Replace captures for code-gen. */
2077 if (token->type == CPP_ATSIGN)
2079 const cpp_token *n = &code[i+1];
2080 if ((n->type == CPP_NUMBER
2081 || n->type == CPP_NAME)
2082 && !(n->flags & PREV_WHITE))
2084 if (token->flags & PREV_WHITE)
2087 if (n->type == CPP_NUMBER)
2088 id = (const char *)n->val.str.text;
2090 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2091 unsigned *cid = capture_ids->get (id);
2093 fatal_at (token, "unknown capture id");
2094 fprintf (f, "captures[%u]", *cid);
2100 if (token->flags & PREV_WHITE)
2103 if (token->type == CPP_NAME)
2105 const char *id = (const char *) NODE_NAME (token->val.node.node);
2107 for (j = 0; j < ids.length (); ++j)
2109 if (strcmp (id, ids[j].id) == 0)
2111 fprintf (f, "%s", ids[j].oper);
2115 if (j < ids.length ())
2119 /* Output the token as string. */
2120 char *tk = (char *)cpp_token_as_text (r, token);
2123 if (token->type == CPP_SEMICOLON)
2127 if (dest && stmt_nr == nr_stmts)
2128 fprintf_indent (f, indent, "%s = ", dest);
2133 /* Generate transform code for a capture. */
2136 capture::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2137 int depth, const char *in_type, capture_info *cinfo,
2138 dt_operand **indexes, bool expand_compares)
2140 if (what && is_a<expr *> (what))
2142 if (indexes[where] == 0)
2145 sprintf (buf, "captures[%u]", where);
2146 what->gen_transform (f, indent, buf, gimple, depth, in_type,
2151 fprintf_indent (f, indent, "%s = captures[%u];\n", dest, where);
2153 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2154 with substituting a capture of that.
2155 ??? Returning false here will also not allow any other patterns
2157 if (gimple && expand_compares
2158 && cinfo->info[where].cond_expr_cond_p)
2160 fprintf_indent (f, indent, "if (COMPARISON_CLASS_P (%s))\n", dest);
2161 fprintf_indent (f, indent, " {\n");
2162 fprintf_indent (f, indent, " if (!seq) return false;\n");
2163 fprintf_indent (f, indent, " %s = gimple_build (seq, TREE_CODE (%s),"
2164 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
2165 " TREE_OPERAND (%s, 1));\n",
2166 dest, dest, dest, dest, dest);
2167 fprintf_indent (f, indent, " }\n");
2171 /* Return the name of the operand representing the decision tree node.
2172 Use NAME as space to generate it. */
2175 dt_operand::get_name (char *name)
2178 sprintf (name, "t");
2179 else if (parent->level == 1)
2180 sprintf (name, "op%u", pos);
2181 else if (parent->type == dt_node::DT_MATCH)
2182 return parent->get_name (name);
2184 sprintf (name, "o%u%u", parent->level, pos);
2188 /* Fill NAME with the operand name at position POS. */
2191 dt_operand::gen_opname (char *name, unsigned pos)
2194 sprintf (name, "op%u", pos);
2196 sprintf (name, "o%u%u", level, pos);
2199 /* Generate matching code for the decision tree operand which is
2203 dt_operand::gen_predicate (FILE *f, int indent, const char *opname, bool gimple)
2205 predicate *p = as_a <predicate *> (op);
2207 if (p->p->matchers.exists ())
2209 /* If this is a predicate generated from a pattern mangle its
2210 name and pass on the valueize hook. */
2212 fprintf_indent (f, indent, "if (gimple_%s (%s, valueize))\n",
2215 fprintf_indent (f, indent, "if (tree_%s (%s))\n", p->p->id, opname);
2218 fprintf_indent (f, indent, "if (%s (%s))\n", p->p->id, opname);
2219 fprintf_indent (f, indent + 2, "{\n");
2223 /* Generate matching code for the decision tree operand which is
2227 dt_operand::gen_match_op (FILE *f, int indent, const char *opname)
2229 char match_opname[20];
2230 match_dop->get_name (match_opname);
2231 fprintf_indent (f, indent, "if (%s == %s || operand_equal_p (%s, %s, 0))\n",
2232 opname, match_opname, opname, match_opname);
2233 fprintf_indent (f, indent + 2, "{\n");
2237 /* Generate GIMPLE matching code for the decision tree operand. */
2240 dt_operand::gen_gimple_expr (FILE *f, int indent)
2242 expr *e = static_cast<expr *> (op);
2243 id_base *id = e->operation;
2244 unsigned n_ops = e->ops.length ();
2246 for (unsigned i = 0; i < n_ops; ++i)
2248 char child_opname[20];
2249 gen_opname (child_opname, i);
2251 if (id->kind == id_base::CODE)
2254 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2255 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
2257 /* ??? If this is a memory operation we can't (and should not)
2258 match this. The only sensible operand types are
2259 SSA names and invariants. */
2260 fprintf_indent (f, indent,
2261 "tree %s = TREE_OPERAND (gimple_assign_rhs1 (def_stmt), %i);\n",
2263 fprintf_indent (f, indent,
2264 "if ((TREE_CODE (%s) == SSA_NAME\n",
2266 fprintf_indent (f, indent,
2267 " || is_gimple_min_invariant (%s))\n",
2269 fprintf_indent (f, indent,
2270 " && (%s = do_valueize (valueize, %s)))\n",
2271 child_opname, child_opname);
2272 fprintf_indent (f, indent,
2278 fprintf_indent (f, indent,
2279 "tree %s = gimple_assign_rhs%u (def_stmt);\n",
2280 child_opname, i + 1);
2283 fprintf_indent (f, indent,
2284 "tree %s = gimple_call_arg (def_stmt, %u);\n",
2286 fprintf_indent (f, indent,
2287 "if ((%s = do_valueize (valueize, %s)))\n",
2288 child_opname, child_opname);
2289 fprintf_indent (f, indent, " {\n");
2292 /* While the toplevel operands are canonicalized by the caller
2293 after valueizing operands of sub-expressions we have to
2294 re-canonicalize operand order. */
2295 if (operator_id *code = dyn_cast <operator_id *> (id))
2297 /* ??? We can't canonicalize tcc_comparison operands here
2298 because that requires changing the comparison code which
2299 we already matched... */
2300 if (commutative_tree_code (code->code)
2301 || commutative_ternary_tree_code (code->code))
2303 char child_opname0[20], child_opname1[20];
2304 gen_opname (child_opname0, 0);
2305 gen_opname (child_opname1, 1);
2306 fprintf_indent (f, indent,
2307 "if (tree_swap_operands_p (%s, %s, false))\n",
2308 child_opname0, child_opname1);
2309 fprintf_indent (f, indent,
2310 " std::swap (%s, %s);\n",
2311 child_opname0, child_opname1);
2318 /* Generate GENERIC matching code for the decision tree operand. */
2321 dt_operand::gen_generic_expr (FILE *f, int indent, const char *opname)
2323 expr *e = static_cast<expr *> (op);
2324 unsigned n_ops = e->ops.length ();
2326 for (unsigned i = 0; i < n_ops; ++i)
2328 char child_opname[20];
2329 gen_opname (child_opname, i);
2331 if (e->operation->kind == id_base::CODE)
2332 fprintf_indent (f, indent, "tree %s = TREE_OPERAND (%s, %u);\n",
2333 child_opname, opname, i);
2335 fprintf_indent (f, indent, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
2336 child_opname, opname, i);
2342 /* Generate matching code for the children of the decision tree node. */
2345 dt_node::gen_kids (FILE *f, int indent, bool gimple)
2347 auto_vec<dt_operand *> gimple_exprs;
2348 auto_vec<dt_operand *> generic_exprs;
2349 auto_vec<dt_operand *> fns;
2350 auto_vec<dt_operand *> generic_fns;
2351 auto_vec<dt_operand *> preds;
2352 auto_vec<dt_node *> others;
2354 for (unsigned i = 0; i < kids.length (); ++i)
2356 if (kids[i]->type == dt_node::DT_OPERAND)
2358 dt_operand *op = as_a<dt_operand *> (kids[i]);
2359 if (expr *e = dyn_cast <expr *> (op->op))
2361 if (e->ops.length () == 0
2362 && (!gimple || !(*e->operation == CONSTRUCTOR)))
2363 generic_exprs.safe_push (op);
2364 else if (e->operation->kind == id_base::FN)
2369 generic_fns.safe_push (op);
2371 else if (e->operation->kind == id_base::PREDICATE)
2372 preds.safe_push (op);
2376 gimple_exprs.safe_push (op);
2378 generic_exprs.safe_push (op);
2381 else if (op->op->type == operand::OP_PREDICATE)
2382 others.safe_push (kids[i]);
2386 else if (kids[i]->type == dt_node::DT_MATCH
2387 || kids[i]->type == dt_node::DT_SIMPLIFY)
2388 others.safe_push (kids[i]);
2389 else if (kids[i]->type == dt_node::DT_TRUE)
2391 /* A DT_TRUE operand serves as a barrier - generate code now
2392 for what we have collected sofar. */
2393 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2394 fns, generic_fns, preds, others);
2395 /* And output the true operand itself. */
2396 kids[i]->gen (f, indent, gimple);
2397 gimple_exprs.truncate (0);
2398 generic_exprs.truncate (0);
2400 generic_fns.truncate (0);
2402 others.truncate (0);
2408 /* Generate code for the remains. */
2409 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2410 fns, generic_fns, preds, others);
2413 /* Generate matching code for the children of the decision tree node. */
2416 dt_node::gen_kids_1 (FILE *f, int indent, bool gimple,
2417 vec<dt_operand *> gimple_exprs,
2418 vec<dt_operand *> generic_exprs,
2419 vec<dt_operand *> fns,
2420 vec<dt_operand *> generic_fns,
2421 vec<dt_operand *> preds,
2422 vec<dt_node *> others)
2425 char *kid_opname = buf;
2427 unsigned exprs_len = gimple_exprs.length ();
2428 unsigned gexprs_len = generic_exprs.length ();
2429 unsigned fns_len = fns.length ();
2430 unsigned gfns_len = generic_fns.length ();
2432 if (exprs_len || fns_len || gexprs_len || gfns_len)
2435 gimple_exprs[0]->get_name (kid_opname);
2437 fns[0]->get_name (kid_opname);
2439 generic_fns[0]->get_name (kid_opname);
2441 generic_exprs[0]->get_name (kid_opname);
2443 fprintf_indent (f, indent, "switch (TREE_CODE (%s))\n", kid_opname);
2444 fprintf_indent (f, indent, " {\n");
2448 if (exprs_len || fns_len)
2450 fprintf_indent (f, indent,
2451 "case SSA_NAME:\n");
2452 fprintf_indent (f, indent,
2453 " if (do_valueize (valueize, %s) != NULL_TREE)\n",
2455 fprintf_indent (f, indent,
2457 fprintf_indent (f, indent,
2458 " gimple def_stmt = SSA_NAME_DEF_STMT (%s);\n",
2464 fprintf_indent (f, indent,
2465 "if (is_gimple_assign (def_stmt))\n");
2466 fprintf_indent (f, indent,
2467 " switch (gimple_assign_rhs_code (def_stmt))\n");
2469 fprintf_indent (f, indent, "{\n");
2470 for (unsigned i = 0; i < exprs_len; ++i)
2472 expr *e = as_a <expr *> (gimple_exprs[i]->op);
2473 id_base *op = e->operation;
2474 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2475 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2477 fprintf_indent (f, indent, "case %s:\n", op->id);
2478 fprintf_indent (f, indent, " {\n");
2479 gimple_exprs[i]->gen (f, indent + 4, true);
2480 fprintf_indent (f, indent, " break;\n");
2481 fprintf_indent (f, indent, " }\n");
2483 fprintf_indent (f, indent, "default:;\n");
2484 fprintf_indent (f, indent, "}\n");
2491 fprintf_indent (f, indent, "else ");
2493 fprintf_indent (f, indent, " ");
2495 fprintf (f, "if (gimple_call_builtin_p (def_stmt, BUILT_IN_NORMAL))\n");
2496 fprintf_indent (f, indent,
2498 fprintf_indent (f, indent,
2499 " tree fndecl = gimple_call_fndecl (def_stmt);\n");
2500 fprintf_indent (f, indent,
2501 " switch (DECL_FUNCTION_CODE (fndecl))\n");
2502 fprintf_indent (f, indent,
2506 for (unsigned i = 0; i < fns_len; ++i)
2508 expr *e = as_a <expr *>(fns[i]->op);
2509 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2510 fprintf_indent (f, indent, " {\n");
2511 fns[i]->gen (f, indent + 4, true);
2512 fprintf_indent (f, indent, " break;\n");
2513 fprintf_indent (f, indent, " }\n");
2516 fprintf_indent (f, indent, "default:;\n");
2517 fprintf_indent (f, indent, "}\n");
2519 fprintf_indent (f, indent, " }\n");
2523 fprintf_indent (f, indent, " }\n");
2524 fprintf_indent (f, indent, " break;\n");
2527 for (unsigned i = 0; i < generic_exprs.length (); ++i)
2529 expr *e = as_a <expr *>(generic_exprs[i]->op);
2530 id_base *op = e->operation;
2531 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2532 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2534 fprintf_indent (f, indent, "case %s:\n", op->id);
2535 fprintf_indent (f, indent, " {\n");
2536 generic_exprs[i]->gen (f, indent + 4, gimple);
2537 fprintf_indent (f, indent, " break;\n");
2538 fprintf_indent (f, indent, " }\n");
2543 fprintf_indent (f, indent,
2544 "case CALL_EXPR:\n");
2545 fprintf_indent (f, indent,
2547 fprintf_indent (f, indent,
2548 " tree fndecl = get_callee_fndecl (%s);\n",
2550 fprintf_indent (f, indent,
2551 " if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)\n");
2552 fprintf_indent (f, indent,
2553 " switch (DECL_FUNCTION_CODE (fndecl))\n");
2554 fprintf_indent (f, indent,
2558 for (unsigned j = 0; j < generic_fns.length (); ++j)
2560 expr *e = as_a <expr *>(generic_fns[j]->op);
2561 gcc_assert (e->operation->kind == id_base::FN);
2563 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2564 fprintf_indent (f, indent, " {\n");
2565 generic_fns[j]->gen (f, indent + 4, false);
2566 fprintf_indent (f, indent, " break;\n");
2567 fprintf_indent (f, indent, " }\n");
2571 fprintf_indent (f, indent, " default:;\n");
2572 fprintf_indent (f, indent, " }\n");
2573 fprintf_indent (f, indent, " break;\n");
2574 fprintf_indent (f, indent, " }\n");
2577 /* Close switch (TREE_CODE ()). */
2578 if (exprs_len || fns_len || gexprs_len || gfns_len)
2581 fprintf_indent (f, indent, " default:;\n");
2582 fprintf_indent (f, indent, " }\n");
2585 for (unsigned i = 0; i < preds.length (); ++i)
2587 expr *e = as_a <expr *> (preds[i]->op);
2588 predicate_id *p = as_a <predicate_id *> (e->operation);
2589 preds[i]->get_name (kid_opname);
2590 fprintf_indent (f, indent, "tree %s_pops[%d];\n", kid_opname, p->nargs);
2591 fprintf_indent (f, indent, "if (%s_%s (%s, %s_pops%s))\n",
2592 gimple ? "gimple" : "tree",
2593 p->id, kid_opname, kid_opname,
2594 gimple ? ", valueize" : "");
2595 fprintf_indent (f, indent, " {\n");
2596 for (int j = 0; j < p->nargs; ++j)
2598 char child_opname[20];
2599 preds[i]->gen_opname (child_opname, j);
2600 fprintf_indent (f, indent + 4, "tree %s = %s_pops[%d];\n",
2601 child_opname, kid_opname, j);
2603 preds[i]->gen_kids (f, indent + 4, gimple);
2607 for (unsigned i = 0; i < others.length (); ++i)
2608 others[i]->gen (f, indent, gimple);
2611 /* Generate matching code for the decision tree operand. */
2614 dt_operand::gen (FILE *f, int indent, bool gimple)
2619 unsigned n_braces = 0;
2621 if (type == DT_OPERAND)
2624 case operand::OP_PREDICATE:
2625 n_braces = gen_predicate (f, indent, opname, gimple);
2628 case operand::OP_EXPR:
2630 n_braces = gen_gimple_expr (f, indent);
2632 n_braces = gen_generic_expr (f, indent, opname);
2638 else if (type == DT_TRUE)
2640 else if (type == DT_MATCH)
2641 n_braces = gen_match_op (f, indent, opname);
2645 indent += 4 * n_braces;
2646 gen_kids (f, indent, gimple);
2648 for (unsigned i = 0; i < n_braces; ++i)
2653 fprintf_indent (f, indent, " }\n");
2658 /* Generate code for the '(if ...)', '(with ..)' and actual transform
2659 step of a '(simplify ...)' or '(match ...)'. This handles everything
2660 that is not part of the decision tree (simplify->match).
2661 Main recursive worker. */
2664 dt_simplify::gen_1 (FILE *f, int indent, bool gimple, operand *result)
2668 if (with_expr *w = dyn_cast <with_expr *> (result))
2670 fprintf_indent (f, indent, "{\n");
2672 output_line_directive (f, w->location);
2673 w->with->gen_transform (f, indent, NULL, true, 1, "type", NULL);
2674 gen_1 (f, indent, gimple, w->subexpr);
2676 fprintf_indent (f, indent, "}\n");
2679 else if (if_expr *ife = dyn_cast <if_expr *> (result))
2681 output_line_directive (f, ife->location);
2682 fprintf_indent (f, indent, "if (");
2683 ife->cond->gen_transform (f, indent, NULL, true, 1, "type", NULL);
2685 fprintf_indent (f, indent + 2, "{\n");
2687 gen_1 (f, indent, gimple, ife->trueexpr);
2689 fprintf_indent (f, indent + 2, "}\n");
2692 fprintf_indent (f, indent, "else\n");
2693 fprintf_indent (f, indent + 2, "{\n");
2695 gen_1 (f, indent, gimple, ife->falseexpr);
2697 fprintf_indent (f, indent + 2, "}\n");
2703 /* Analyze captures and perform early-outs on the incoming arguments
2704 that cover cases we cannot handle. */
2705 capture_info cinfo (s, result, gimple);
2706 if (s->kind == simplify::SIMPLIFY)
2710 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
2711 if (cinfo.force_no_side_effects & (1 << i))
2713 fprintf_indent (f, indent,
2714 "if (TREE_SIDE_EFFECTS (op%d)) return NULL_TREE;\n",
2717 warning_at (as_a <expr *> (s->match)->ops[i]->location,
2718 "forcing toplevel operand to have no "
2721 for (int i = 0; i <= s->capture_max; ++i)
2722 if (cinfo.info[i].cse_p)
2724 else if (cinfo.info[i].force_no_side_effects_p
2725 && (cinfo.info[i].toplevel_msk
2726 & cinfo.force_no_side_effects) == 0)
2728 fprintf_indent (f, indent,
2729 "if (TREE_SIDE_EFFECTS (captures[%d])) "
2730 "return NULL_TREE;\n", i);
2732 warning_at (cinfo.info[i].c->location,
2733 "forcing captured operand to have no "
2736 else if ((cinfo.info[i].toplevel_msk
2737 & cinfo.force_no_side_effects) != 0)
2738 /* Mark capture as having no side-effects if we had to verify
2739 that via forced toplevel operand checks. */
2740 cinfo.info[i].force_no_side_effects_p = true;
2744 /* Force single-use restriction by only allowing simple
2745 results via setting seq to NULL. */
2746 fprintf_indent (f, indent, "gimple_seq *lseq = seq;\n");
2747 bool first_p = true;
2748 for (int i = 0; i <= s->capture_max; ++i)
2749 if (cinfo.info[i].force_single_use)
2753 fprintf_indent (f, indent, "if (lseq\n");
2754 fprintf_indent (f, indent, " && (");
2760 fprintf_indent (f, indent, " || ");
2762 fprintf (f, "!single_use (captures[%d])", i);
2766 fprintf (f, "))\n");
2767 fprintf_indent (f, indent, " lseq = NULL;\n");
2772 fprintf_indent (f, indent, "if (dump_file && (dump_flags & TDF_DETAILS)) "
2773 "fprintf (dump_file, \"Applying pattern ");
2774 output_line_directive (f,
2775 result ? result->location : s->match->location, true);
2776 fprintf (f, ", %%s:%%d\\n\", __FILE__, __LINE__);\n");
2780 /* If there is no result then this is a predicate implementation. */
2781 fprintf_indent (f, indent, "return true;\n");
2785 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
2786 in outermost position). */
2787 if (result->type == operand::OP_EXPR
2788 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
2789 result = as_a <expr *> (result)->ops[0];
2790 if (result->type == operand::OP_EXPR)
2792 expr *e = as_a <expr *> (result);
2793 bool is_predicate = is_a <predicate_id *> (e->operation);
2795 fprintf_indent (f, indent, "*res_code = %s;\n",
2796 *e->operation == CONVERT_EXPR
2797 ? "NOP_EXPR" : e->operation->id);
2798 for (unsigned j = 0; j < e->ops.length (); ++j)
2801 snprintf (dest, 32, "res_ops[%d]", j);
2803 = get_operand_type (e->operation,
2804 "type", e->expr_type,
2805 j == 0 ? NULL : "TREE_TYPE (res_ops[0])");
2806 /* We need to expand GENERIC conditions we captured from
2808 bool expand_generic_cond_exprs_p
2810 /* But avoid doing that if the GENERIC condition is
2811 valid - which it is in the first operand of COND_EXPRs
2812 and VEC_COND_EXRPs. */
2813 && ((!(*e->operation == COND_EXPR)
2814 && !(*e->operation == VEC_COND_EXPR))
2816 e->ops[j]->gen_transform (f, indent, dest, true, 1, optype,
2818 indexes, expand_generic_cond_exprs_p);
2821 /* Re-fold the toplevel result. It's basically an embedded
2822 gimple_build w/o actually building the stmt. */
2824 fprintf_indent (f, indent,
2825 "gimple_resimplify%d (lseq, res_code, type, "
2826 "res_ops, valueize);\n", e->ops.length ());
2828 else if (result->type == operand::OP_CAPTURE
2829 || result->type == operand::OP_C_EXPR)
2831 result->gen_transform (f, indent, "res_ops[0]", true, 1, "type",
2832 &cinfo, indexes, false);
2833 fprintf_indent (f, indent, "*res_code = TREE_CODE (res_ops[0]);\n");
2834 if (is_a <capture *> (result)
2835 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
2837 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2838 with substituting a capture of that. */
2839 fprintf_indent (f, indent,
2840 "if (COMPARISON_CLASS_P (res_ops[0]))\n");
2841 fprintf_indent (f, indent,
2843 fprintf_indent (f, indent,
2844 " tree tem = res_ops[0];\n");
2845 fprintf_indent (f, indent,
2846 " res_ops[0] = TREE_OPERAND (tem, 0);\n");
2847 fprintf_indent (f, indent,
2848 " res_ops[1] = TREE_OPERAND (tem, 1);\n");
2849 fprintf_indent (f, indent,
2855 fprintf_indent (f, indent, "return true;\n");
2859 bool is_predicate = false;
2860 if (result->type == operand::OP_EXPR)
2862 expr *e = as_a <expr *> (result);
2863 is_predicate = is_a <predicate_id *> (e->operation);
2864 /* Search for captures used multiple times in the result expression
2865 and dependent on TREE_SIDE_EFFECTS emit a SAVE_EXPR. */
2867 for (int i = 0; i < s->capture_max + 1; ++i)
2869 if (cinfo.info[i].same_as != (unsigned)i)
2871 if (!cinfo.info[i].force_no_side_effects_p
2872 && cinfo.info[i].result_use_count > 1)
2874 fprintf_indent (f, indent,
2875 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
2877 fprintf_indent (f, indent,
2878 " captures[%d] = save_expr (captures[%d]);\n",
2882 for (unsigned j = 0; j < e->ops.length (); ++j)
2886 snprintf (dest, 32, "res_ops[%d]", j);
2889 fprintf_indent (f, indent, "tree res_op%d;\n", j);
2890 snprintf (dest, 32, "res_op%d", j);
2893 = get_operand_type (e->operation,
2894 "type", e->expr_type,
2896 ? NULL : "TREE_TYPE (res_op0)");
2897 e->ops[j]->gen_transform (f, indent, dest, false, 1, optype,
2901 fprintf_indent (f, indent, "return true;\n");
2904 fprintf_indent (f, indent, "tree res;\n");
2905 /* Re-fold the toplevel result. Use non_lvalue to
2906 build NON_LVALUE_EXPRs so they get properly
2907 ignored when in GIMPLE form. */
2908 if (*e->operation == NON_LVALUE_EXPR)
2909 fprintf_indent (f, indent,
2910 "res = non_lvalue_loc (loc, res_op0);\n");
2913 if (e->operation->kind == id_base::CODE)
2914 fprintf_indent (f, indent,
2915 "res = fold_build%d_loc (loc, %s, type",
2917 *e->operation == CONVERT_EXPR
2918 ? "NOP_EXPR" : e->operation->id);
2920 fprintf_indent (f, indent,
2921 "res = build_call_expr_loc "
2922 "(loc, builtin_decl_implicit (%s), %d",
2923 e->operation->id, e->ops.length());
2924 for (unsigned j = 0; j < e->ops.length (); ++j)
2925 fprintf (f, ", res_op%d", j);
2926 fprintf (f, ");\n");
2930 else if (result->type == operand::OP_CAPTURE
2931 || result->type == operand::OP_C_EXPR)
2934 fprintf_indent (f, indent, "tree res;\n");
2935 result->gen_transform (f, indent, "res", false, 1, "type",
2942 /* Search for captures not used in the result expression and dependent
2943 on TREE_SIDE_EFFECTS emit omit_one_operand. */
2944 for (int i = 0; i < s->capture_max + 1; ++i)
2946 if (cinfo.info[i].same_as != (unsigned)i)
2948 if (!cinfo.info[i].force_no_side_effects_p
2949 && !cinfo.info[i].expr_p
2950 && cinfo.info[i].result_use_count == 0)
2952 fprintf_indent (f, indent,
2953 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
2955 fprintf_indent (f, indent + 2,
2956 "res = build2_loc (loc, COMPOUND_EXPR, type, "
2957 "fold_ignored_result (captures[%d]), res);\n",
2961 fprintf_indent (f, indent, "return res;\n");
2966 /* Generate code for the '(if ...)', '(with ..)' and actual transform
2967 step of a '(simplify ...)' or '(match ...)'. This handles everything
2968 that is not part of the decision tree (simplify->match). */
2971 dt_simplify::gen (FILE *f, int indent, bool gimple)
2973 fprintf_indent (f, indent, "{\n");
2975 output_line_directive (f,
2976 s->result ? s->result->location : s->match->location);
2977 if (s->capture_max >= 0)
2978 fprintf_indent (f, indent, "tree captures[%u] ATTRIBUTE_UNUSED = {};\n",
2979 s->capture_max + 1);
2981 for (int i = 0; i <= s->capture_max; ++i)
2985 fprintf_indent (f, indent, "captures[%u] = %s;\n",
2986 i, indexes[i]->get_name (opname));
2989 gen_1 (f, indent, gimple, s->result);
2992 fprintf_indent (f, indent, "}\n");
2995 /* Main entry to generate code for matching GIMPLE IL off the decision
2999 decision_tree::gen (FILE *f, bool gimple)
3003 fprintf (stderr, "%s decision tree has %u leafs, maximum depth %u and "
3004 "a total number of %u nodes\n",
3005 gimple ? "GIMPLE" : "GENERIC",
3006 root->num_leafs, root->max_level, root->total_size);
3008 for (unsigned n = 1; n <= 3; ++n)
3010 /* First generate split-out functions. */
3011 for (unsigned i = 0; i < root->kids.length (); i++)
3013 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3014 expr *e = static_cast<expr *>(dop->op);
3015 if (e->ops.length () != n
3016 /* Builtin simplifications are somewhat premature on
3017 GENERIC. The following drops patterns with outermost
3018 calls. It's easy to emit overloads for function code
3019 though if necessary. */
3021 && e->operation->kind != id_base::CODE))
3025 fprintf (f, "\nstatic bool\n"
3026 "gimple_simplify_%s (code_helper *res_code, tree *res_ops,\n"
3027 " gimple_seq *seq, tree (*valueize)(tree) "
3028 "ATTRIBUTE_UNUSED,\n"
3029 " code_helper ARG_UNUSED (code), tree "
3030 "ARG_UNUSED (type)\n",
3033 fprintf (f, "\nstatic tree\n"
3034 "generic_simplify_%s (location_t ARG_UNUSED (loc), enum "
3035 "tree_code ARG_UNUSED (code), tree ARG_UNUSED (type)",
3037 for (unsigned i = 0; i < n; ++i)
3038 fprintf (f, ", tree op%d", i);
3041 dop->gen_kids (f, 2, gimple);
3043 fprintf (f, " return false;\n");
3045 fprintf (f, " return NULL_TREE;\n");
3049 /* Then generate the main entry with the outermost switch and
3050 tail-calls to the split-out functions. */
3052 fprintf (f, "\nstatic bool\n"
3053 "gimple_simplify (code_helper *res_code, tree *res_ops,\n"
3054 " gimple_seq *seq, tree (*valueize)(tree),\n"
3055 " code_helper code, tree type");
3057 fprintf (f, "\ntree\n"
3058 "generic_simplify (location_t loc, enum tree_code code, "
3059 "tree type ATTRIBUTE_UNUSED");
3060 for (unsigned i = 0; i < n; ++i)
3061 fprintf (f, ", tree op%d", i);
3066 fprintf (f, " switch (code.get_rep())\n"
3069 fprintf (f, " switch (code)\n"
3071 for (unsigned i = 0; i < root->kids.length (); i++)
3073 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3074 expr *e = static_cast<expr *>(dop->op);
3075 if (e->ops.length () != n
3076 /* Builtin simplifications are somewhat premature on
3077 GENERIC. The following drops patterns with outermost
3078 calls. It's easy to emit overloads for function code
3079 though if necessary. */
3081 && e->operation->kind != id_base::CODE))
3084 if (*e->operation == CONVERT_EXPR
3085 || *e->operation == NOP_EXPR)
3086 fprintf (f, " CASE_CONVERT:\n");
3088 fprintf (f, " case %s%s:\n",
3089 is_a <fn_id *> (e->operation) ? "-" : "",
3092 fprintf (f, " return gimple_simplify_%s (res_code, res_ops, "
3093 "seq, valueize, code, type", e->operation->id);
3095 fprintf (f, " return generic_simplify_%s (loc, code, type",
3097 for (unsigned i = 0; i < n; ++i)
3098 fprintf (f, ", op%d", i);
3099 fprintf (f, ");\n");
3101 fprintf (f, " default:;\n"
3105 fprintf (f, " return false;\n");
3107 fprintf (f, " return NULL_TREE;\n");
3112 /* Output code to implement the predicate P from the decision tree DT. */
3115 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
3117 fprintf (f, "\nbool\n"
3118 "%s%s (tree t%s%s)\n"
3119 "{\n", gimple ? "gimple_" : "tree_", p->id,
3120 p->nargs > 0 ? ", tree *res_ops" : "",
3121 gimple ? ", tree (*valueize)(tree)" : "");
3122 /* Conveniently make 'type' available. */
3123 fprintf_indent (f, 2, "tree type = TREE_TYPE (t);\n");
3126 fprintf_indent (f, 2, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
3127 dt.root->gen_kids (f, 2, gimple);
3129 fprintf_indent (f, 2, "return false;\n"
3133 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
3136 write_header (FILE *f, const char *head)
3138 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
3139 fprintf (f, " a IL pattern matching and simplification description. */\n");
3141 /* Include the header instead of writing it awkwardly quoted here. */
3142 fprintf (f, "\n#include \"%s\"\n", head);
3152 parser (cpp_reader *);
3155 const cpp_token *next ();
3156 const cpp_token *peek (unsigned = 1);
3157 const cpp_token *peek_ident (const char * = NULL, unsigned = 1);
3158 const cpp_token *expect (enum cpp_ttype);
3159 const cpp_token *eat_token (enum cpp_ttype);
3160 const char *get_string ();
3161 const char *get_ident ();
3162 const cpp_token *eat_ident (const char *);
3163 const char *get_number ();
3165 id_base *parse_operation ();
3166 operand *parse_capture (operand *, bool);
3167 operand *parse_expr ();
3168 c_expr *parse_c_expr (cpp_ttype);
3169 operand *parse_op ();
3171 void record_operlist (source_location, user_id *);
3173 void parse_pattern ();
3174 operand *parse_result (operand *, predicate_id *);
3175 void push_simplify (simplify::simplify_kind,
3176 vec<simplify *>&, operand *, operand *);
3177 void parse_simplify (simplify::simplify_kind,
3178 vec<simplify *>&, predicate_id *, operand *);
3179 void parse_for (source_location);
3180 void parse_if (source_location);
3181 void parse_predicates (source_location);
3182 void parse_operator_list (source_location);
3185 vec<c_expr *> active_ifs;
3186 vec<vec<user_id *> > active_fors;
3187 hash_set<user_id *> *oper_lists_set;
3188 vec<user_id *> oper_lists;
3190 cid_map_t *capture_ids;
3193 vec<simplify *> simplifiers;
3194 vec<predicate_id *> user_predicates;
3195 bool parsing_match_operand;
3198 /* Lexing helpers. */
3200 /* Read the next non-whitespace token from R. */
3205 const cpp_token *token;
3208 token = cpp_get_token (r);
3210 while (token->type == CPP_PADDING
3211 && token->type != CPP_EOF);
3215 /* Peek at the next non-whitespace token from R. */
3218 parser::peek (unsigned num)
3220 const cpp_token *token;
3224 token = cpp_peek_token (r, i++);
3226 while ((token->type == CPP_PADDING
3227 && token->type != CPP_EOF)
3229 /* If we peek at EOF this is a fatal error as it leaves the
3230 cpp_reader in unusable state. Assume we really wanted a
3231 token and thus this EOF is unexpected. */
3232 if (token->type == CPP_EOF)
3233 fatal_at (token, "unexpected end of file");
3237 /* Peek at the next identifier token (or return NULL if the next
3238 token is not an identifier or equal to ID if supplied). */
3241 parser::peek_ident (const char *id, unsigned num)
3243 const cpp_token *token = peek (num);
3244 if (token->type != CPP_NAME)
3250 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
3251 if (strcmp (id, t) == 0)
3257 /* Read the next token from R and assert it is of type TK. */
3260 parser::expect (enum cpp_ttype tk)
3262 const cpp_token *token = next ();
3263 if (token->type != tk)
3264 fatal_at (token, "expected %s, got %s",
3265 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
3270 /* Consume the next token from R and assert it is of type TK. */
3273 parser::eat_token (enum cpp_ttype tk)
3278 /* Read the next token from R and assert it is of type CPP_STRING and
3279 return its value. */
3282 parser::get_string ()
3284 const cpp_token *token = expect (CPP_STRING);
3285 return (const char *)token->val.str.text;
3288 /* Read the next token from R and assert it is of type CPP_NAME and
3289 return its value. */
3292 parser::get_ident ()
3294 const cpp_token *token = expect (CPP_NAME);
3295 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
3298 /* Eat an identifier token with value S from R. */
3301 parser::eat_ident (const char *s)
3303 const cpp_token *token = peek ();
3304 const char *t = get_ident ();
3305 if (strcmp (s, t) != 0)
3306 fatal_at (token, "expected '%s' got '%s'\n", s, t);
3310 /* Read the next token from R and assert it is of type CPP_NUMBER and
3311 return its value. */
3314 parser::get_number ()
3316 const cpp_token *token = expect (CPP_NUMBER);
3317 return (const char *)token->val.str.text;
3321 /* Record an operator-list use for transparent for handling. */
3324 parser::record_operlist (source_location loc, user_id *p)
3326 if (!oper_lists_set->add (p))
3328 if (!oper_lists.is_empty ()
3329 && oper_lists[0]->substitutes.length () != p->substitutes.length ())
3330 fatal_at (loc, "User-defined operator list does not have the "
3331 "same number of entries as others used in the pattern");
3332 oper_lists.safe_push (p);
3336 /* Parse the operator ID, special-casing convert?, convert1? and
3340 parser::parse_operation ()
3342 const cpp_token *id_tok = peek ();
3343 const char *id = get_ident ();
3344 const cpp_token *token = peek ();
3345 if (strcmp (id, "convert0") == 0)
3346 fatal_at (id_tok, "use 'convert?' here");
3347 else if (strcmp (id, "view_convert0") == 0)
3348 fatal_at (id_tok, "use 'view_convert?' here");
3349 if (token->type == CPP_QUERY
3350 && !(token->flags & PREV_WHITE))
3352 if (strcmp (id, "convert") == 0)
3354 else if (strcmp (id, "convert1") == 0)
3356 else if (strcmp (id, "convert2") == 0)
3358 else if (strcmp (id, "view_convert") == 0)
3359 id = "view_convert0";
3360 else if (strcmp (id, "view_convert1") == 0)
3362 else if (strcmp (id, "view_convert2") == 0)
3365 fatal_at (id_tok, "non-convert operator conditionalized");
3367 if (!parsing_match_operand)
3368 fatal_at (id_tok, "conditional convert can only be used in "
3369 "match expression");
3370 eat_token (CPP_QUERY);
3372 else if (strcmp (id, "convert1") == 0
3373 || strcmp (id, "convert2") == 0
3374 || strcmp (id, "view_convert1") == 0
3375 || strcmp (id, "view_convert2") == 0)
3376 fatal_at (id_tok, "expected '?' after conditional operator");
3377 id_base *op = get_operator (id);
3379 fatal_at (id_tok, "unknown operator %s", id);
3381 user_id *p = dyn_cast<user_id *> (op);
3382 if (p && p->is_oper_list)
3384 if (active_fors.length() == 0)
3385 record_operlist (id_tok->src_loc, p);
3387 fatal_at (id_tok, "operator-list %s cannot be exapnded inside 'for'", id);
3393 capture = '@'<number> */
3396 parser::parse_capture (operand *op, bool require_existing)
3398 source_location src_loc = eat_token (CPP_ATSIGN)->src_loc;
3399 const cpp_token *token = peek ();
3400 const char *id = NULL;
3401 if (token->type == CPP_NUMBER)
3403 else if (token->type == CPP_NAME)
3406 fatal_at (token, "expected number or identifier");
3407 unsigned next_id = capture_ids->elements ();
3409 unsigned &num = capture_ids->get_or_insert (id, &existed);
3412 if (require_existing)
3413 fatal_at (src_loc, "unknown capture id");
3416 return new capture (src_loc, num, op);
3419 /* Parse an expression
3420 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
3423 parser::parse_expr ()
3425 const cpp_token *token = peek ();
3426 expr *e = new expr (parse_operation (), token->src_loc);
3429 bool is_commutative = false;
3430 bool force_capture = false;
3431 const char *expr_type = NULL;
3433 if (token->type == CPP_COLON
3434 && !(token->flags & PREV_WHITE))
3436 eat_token (CPP_COLON);
3438 if (token->type == CPP_NAME
3439 && !(token->flags & PREV_WHITE))
3441 const char *s = get_ident ();
3442 if (!parsing_match_operand)
3450 is_commutative = true;
3451 else if (*sp == 's')
3453 e->force_single_use = true;
3454 force_capture = true;
3457 fatal_at (token, "flag %c not recognized", *sp);
3464 fatal_at (token, "expected flag or type specifying identifier");
3467 if (token->type == CPP_ATSIGN
3468 && !(token->flags & PREV_WHITE))
3469 op = parse_capture (e, !parsing_match_operand);
3470 else if (force_capture)
3472 unsigned num = capture_ids->elements ();
3475 sprintf (id, "__%u", num);
3476 capture_ids->get_or_insert (xstrdup (id), &existed);
3478 fatal_at (token, "reserved capture id '%s' already used", id);
3479 op = new capture (token->src_loc, num, e);
3485 const cpp_token *token = peek ();
3486 if (token->type == CPP_CLOSE_PAREN)
3488 if (e->operation->nargs != -1
3489 && e->operation->nargs != (int) e->ops.length ())
3490 fatal_at (token, "'%s' expects %u operands, not %u",
3491 e->operation->id, e->operation->nargs, e->ops.length ());
3494 if (e->ops.length () == 2)
3495 e->is_commutative = true;
3497 fatal_at (token, "only binary operators or function with "
3498 "two arguments can be marked commutative");
3500 e->expr_type = expr_type;
3503 e->append_op (parse_op ());
3508 /* Lex native C code delimited by START recording the preprocessing tokens
3509 for later processing.
3510 c_expr = ('{'|'(') <pp token>... ('}'|')') */
3513 parser::parse_c_expr (cpp_ttype start)
3515 const cpp_token *token;
3518 vec<cpp_token> code = vNULL;
3519 unsigned nr_stmts = 0;
3520 source_location loc = eat_token (start)->src_loc;
3521 if (start == CPP_OPEN_PAREN)
3522 end = CPP_CLOSE_PAREN;
3523 else if (start == CPP_OPEN_BRACE)
3524 end = CPP_CLOSE_BRACE;
3532 /* Count brace pairs to find the end of the expr to match. */
3533 if (token->type == start)
3535 else if (token->type == end
3539 /* This is a lame way of counting the number of statements. */
3540 if (token->type == CPP_SEMICOLON)
3543 /* If this is possibly a user-defined identifier mark it used. */
3544 if (token->type == CPP_NAME)
3546 id_base *idb = get_operator ((const char *)CPP_HASHNODE
3547 (token->val.node.node)->ident.str);
3549 if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
3550 record_operlist (token->src_loc, p);
3553 /* Record the token. */
3554 code.safe_push (*token);
3557 return new c_expr (r, loc, code, nr_stmts, vNULL, capture_ids);
3560 /* Parse an operand which is either an expression, a predicate or
3561 a standalone capture.
3562 op = predicate | expr | c_expr | capture */
3567 const cpp_token *token = peek ();
3568 struct operand *op = NULL;
3569 if (token->type == CPP_OPEN_PAREN)
3571 eat_token (CPP_OPEN_PAREN);
3573 eat_token (CPP_CLOSE_PAREN);
3575 else if (token->type == CPP_OPEN_BRACE)
3577 op = parse_c_expr (CPP_OPEN_BRACE);
3581 /* Remaining ops are either empty or predicates */
3582 if (token->type == CPP_NAME)
3584 const char *id = get_ident ();
3585 id_base *opr = get_operator (id);
3587 fatal_at (token, "expected predicate name");
3588 if (operator_id *code = dyn_cast <operator_id *> (opr))
3590 if (code->nargs != 0)
3591 fatal_at (token, "using an operator with operands as predicate");
3592 /* Parse the zero-operand operator "predicates" as
3594 op = new expr (opr, token->src_loc);
3596 else if (user_id *code = dyn_cast <user_id *> (opr))
3598 if (code->nargs != 0)
3599 fatal_at (token, "using an operator with operands as predicate");
3600 /* Parse the zero-operand operator "predicates" as
3602 op = new expr (opr, token->src_loc);
3604 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
3605 op = new predicate (p, token->src_loc);
3607 fatal_at (token, "using an unsupported operator as predicate");
3608 if (!parsing_match_operand)
3609 fatal_at (token, "predicates are only allowed in match expression");
3611 if (token->flags & PREV_WHITE)
3614 else if (token->type != CPP_COLON
3615 && token->type != CPP_ATSIGN)
3616 fatal_at (token, "expected expression or predicate");
3617 /* optionally followed by a capture and a predicate. */
3618 if (token->type == CPP_COLON)
3619 fatal_at (token, "not implemented: predicate on leaf operand");
3620 if (token->type == CPP_ATSIGN)
3621 op = parse_capture (op, !parsing_match_operand);
3627 /* Create a new simplify from the current parsing state and MATCH,
3628 MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS. */
3631 parser::push_simplify (simplify::simplify_kind kind,
3632 vec<simplify *>& simplifiers,
3633 operand *match, operand *result)
3635 /* Build and push a temporary for operator list uses in expressions. */
3636 if (!oper_lists.is_empty ())
3637 active_fors.safe_push (oper_lists);
3639 simplifiers.safe_push
3640 (new simplify (kind, match, result,
3641 active_fors.copy (), capture_ids));
3643 if (!oper_lists.is_empty ())
3648 <result-op> = <op> | <if> | <with>
3649 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
3650 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
3654 parser::parse_result (operand *result, predicate_id *matcher)
3656 const cpp_token *token = peek ();
3657 if (token->type != CPP_OPEN_PAREN)
3660 eat_token (CPP_OPEN_PAREN);
3661 if (peek_ident ("if"))
3664 if_expr *ife = new if_expr (token->src_loc);
3665 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
3666 if (peek ()->type == CPP_OPEN_PAREN)
3668 ife->trueexpr = parse_result (result, matcher);
3669 if (peek ()->type == CPP_OPEN_PAREN)
3670 ife->falseexpr = parse_result (result, matcher);
3671 else if (peek ()->type != CPP_CLOSE_PAREN)
3672 ife->falseexpr = parse_op ();
3674 else if (peek ()->type != CPP_CLOSE_PAREN)
3676 ife->trueexpr = parse_op ();
3677 if (peek ()->type == CPP_OPEN_PAREN)
3678 ife->falseexpr = parse_result (result, matcher);
3679 else if (peek ()->type != CPP_CLOSE_PAREN)
3680 ife->falseexpr = parse_op ();
3682 /* If this if is immediately closed then it contains a
3683 manual matcher or is part of a predicate definition. */
3684 else /* if (peek ()->type == CPP_CLOSE_PAREN) */
3687 fatal_at (peek (), "manual transform not implemented");
3688 ife->trueexpr = result;
3690 eat_token (CPP_CLOSE_PAREN);
3693 else if (peek_ident ("with"))
3696 with_expr *withe = new with_expr (token->src_loc);
3697 /* Parse (with c-expr expr) as (if-with (true) expr). */
3698 withe->with = parse_c_expr (CPP_OPEN_BRACE);
3699 withe->with->nr_stmts = 0;
3700 withe->subexpr = parse_result (result, matcher);
3701 eat_token (CPP_CLOSE_PAREN);
3704 else if (peek_ident ("switch"))
3706 token = eat_ident ("switch");
3707 source_location ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
3709 if_expr *ife = new if_expr (ifloc);
3711 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
3712 if (peek ()->type == CPP_OPEN_PAREN)
3713 ife->trueexpr = parse_result (result, matcher);
3715 ife->trueexpr = parse_op ();
3716 eat_token (CPP_CLOSE_PAREN);
3717 if (peek ()->type != CPP_OPEN_PAREN
3718 || !peek_ident ("if", 2))
3719 fatal_at (token, "switch can be implemented with a single if");
3720 while (peek ()->type != CPP_CLOSE_PAREN)
3722 if (peek ()->type == CPP_OPEN_PAREN)
3724 if (peek_ident ("if", 2))
3726 ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
3728 ife->falseexpr = new if_expr (ifloc);
3729 ife = as_a <if_expr *> (ife->falseexpr);
3730 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
3731 if (peek ()->type == CPP_OPEN_PAREN)
3732 ife->trueexpr = parse_result (result, matcher);
3734 ife->trueexpr = parse_op ();
3735 eat_token (CPP_CLOSE_PAREN);
3739 /* switch default clause */
3740 ife->falseexpr = parse_result (result, matcher);
3741 eat_token (CPP_CLOSE_PAREN);
3747 /* switch default clause */
3748 ife->falseexpr = parse_op ();
3749 eat_token (CPP_CLOSE_PAREN);
3753 eat_token (CPP_CLOSE_PAREN);
3758 operand *op = result;
3761 eat_token (CPP_CLOSE_PAREN);
3767 simplify = 'simplify' <expr> <result-op>
3769 match = 'match' <ident> <expr> [<result-op>]
3770 and fill SIMPLIFIERS with the results. */
3773 parser::parse_simplify (simplify::simplify_kind kind,
3774 vec<simplify *>& simplifiers, predicate_id *matcher,
3777 /* Reset the capture map. */
3779 capture_ids = new cid_map_t;
3780 /* Reset oper_lists and set. */
3781 hash_set <user_id *> olist;
3782 oper_lists_set = &olist;
3785 const cpp_token *loc = peek ();
3786 parsing_match_operand = true;
3787 struct operand *match = parse_op ();
3788 parsing_match_operand = false;
3789 if (match->type == operand::OP_CAPTURE && !matcher)
3790 fatal_at (loc, "outermost expression cannot be captured");
3791 if (match->type == operand::OP_EXPR
3792 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
3793 fatal_at (loc, "outermost expression cannot be a predicate");
3795 /* Splice active_ifs onto result and continue parsing the
3797 if_expr *active_if = NULL;
3798 for (int i = active_ifs.length (); i > 0; --i)
3800 if_expr *ifc = new if_expr (active_ifs[i-1]->location);
3801 ifc->cond = active_ifs[i-1];
3802 ifc->trueexpr = active_if;
3805 if_expr *outermost_if = active_if;
3806 while (active_if && active_if->trueexpr)
3807 active_if = as_a <if_expr *> (active_if->trueexpr);
3809 const cpp_token *token = peek ();
3811 /* If this if is immediately closed then it is part of a predicate
3812 definition. Push it. */
3813 if (token->type == CPP_CLOSE_PAREN)
3816 fatal_at (token, "expected transform expression");
3819 active_if->trueexpr = result;
3820 result = outermost_if;
3822 push_simplify (kind, simplifiers, match, result);
3826 operand *tem = parse_result (result, matcher);
3829 active_if->trueexpr = tem;
3830 result = outermost_if;
3835 push_simplify (kind, simplifiers, match, result);
3838 /* Parsing of the outer control structures. */
3840 /* Parse a for expression
3841 for = '(' 'for' <subst>... <pattern> ')'
3842 subst = <ident> '(' <ident>... ')' */
3845 parser::parse_for (source_location)
3847 auto_vec<const cpp_token *> user_id_tokens;
3848 vec<user_id *> user_ids = vNULL;
3849 const cpp_token *token;
3850 unsigned min_n_opers = 0, max_n_opers = 0;
3855 if (token->type != CPP_NAME)
3858 /* Insert the user defined operators into the operator hash. */
3859 const char *id = get_ident ();
3860 if (get_operator (id) != NULL)
3861 fatal_at (token, "operator already defined");
3862 user_id *op = new user_id (id);
3863 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
3865 user_ids.safe_push (op);
3866 user_id_tokens.safe_push (token);
3868 eat_token (CPP_OPEN_PAREN);
3871 while ((token = peek_ident ()) != 0)
3873 const char *oper = get_ident ();
3874 id_base *idb = get_operator (oper);
3876 fatal_at (token, "no such operator '%s'", oper);
3877 if (*idb == CONVERT0 || *idb == CONVERT1 || *idb == CONVERT2
3878 || *idb == VIEW_CONVERT0 || *idb == VIEW_CONVERT1
3879 || *idb == VIEW_CONVERT2)
3880 fatal_at (token, "conditional operators cannot be used inside for");
3884 else if (idb->nargs == -1)
3886 else if (idb->nargs != arity)
3887 fatal_at (token, "operator '%s' with arity %d does not match "
3888 "others with arity %d", oper, idb->nargs, arity);
3890 user_id *p = dyn_cast<user_id *> (idb);
3893 if (p->is_oper_list)
3894 op->substitutes.safe_splice (p->substitutes);
3896 fatal_at (token, "iterator cannot be used as operator-list");
3899 op->substitutes.safe_push (idb);
3902 token = expect (CPP_CLOSE_PAREN);
3904 unsigned nsubstitutes = op->substitutes.length ();
3905 if (nsubstitutes == 0)
3906 fatal_at (token, "A user-defined operator must have at least "
3907 "one substitution");
3908 if (max_n_opers == 0)
3910 min_n_opers = nsubstitutes;
3911 max_n_opers = nsubstitutes;
3915 if (nsubstitutes % min_n_opers != 0
3916 && min_n_opers % nsubstitutes != 0)
3917 fatal_at (token, "All user-defined identifiers must have a "
3918 "multiple number of operator substitutions of the "
3919 "smallest number of substitutions");
3920 if (nsubstitutes < min_n_opers)
3921 min_n_opers = nsubstitutes;
3922 else if (nsubstitutes > max_n_opers)
3923 max_n_opers = nsubstitutes;
3927 unsigned n_ids = user_ids.length ();
3929 fatal_at (token, "for requires at least one user-defined identifier");
3932 if (token->type == CPP_CLOSE_PAREN)
3933 fatal_at (token, "no pattern defined in for");
3935 active_fors.safe_push (user_ids);
3939 if (token->type == CPP_CLOSE_PAREN)
3945 /* Remove user-defined operators from the hash again. */
3946 for (unsigned i = 0; i < user_ids.length (); ++i)
3948 if (!user_ids[i]->used)
3949 warning_at (user_id_tokens[i],
3950 "operator %s defined but not used", user_ids[i]->id);
3951 operators->remove_elt (user_ids[i]);
3955 /* Parse an identifier associated with a list of operators.
3956 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
3959 parser::parse_operator_list (source_location)
3961 const cpp_token *token = peek ();
3962 const char *id = get_ident ();
3964 if (get_operator (id) != 0)
3965 fatal_at (token, "operator %s already defined", id);
3967 user_id *op = new user_id (id, true);
3970 while ((token = peek_ident ()) != 0)
3973 const char *oper = get_ident ();
3974 id_base *idb = get_operator (oper);
3977 fatal_at (token, "no such operator '%s'", oper);
3981 else if (idb->nargs == -1)
3983 else if (arity != idb->nargs)
3984 fatal_at (token, "operator '%s' with arity %d does not match "
3985 "others with arity %d", oper, idb->nargs, arity);
3987 /* We allow composition of multiple operator lists. */
3988 if (user_id *p = dyn_cast<user_id *> (idb))
3989 op->substitutes.safe_splice (p->substitutes);
3991 op->substitutes.safe_push (idb);
3994 // Check that there is no junk after id-list
3996 if (token->type != CPP_CLOSE_PAREN)
3997 fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
3999 if (op->substitutes.length () == 0)
4000 fatal_at (token, "operator-list cannot be empty");
4003 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4007 /* Parse an outer if expression.
4008 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
4011 parser::parse_if (source_location)
4013 c_expr *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
4015 const cpp_token *token = peek ();
4016 if (token->type == CPP_CLOSE_PAREN)
4017 fatal_at (token, "no pattern defined in if");
4019 active_ifs.safe_push (ifexpr);
4022 const cpp_token *token = peek ();
4023 if (token->type == CPP_CLOSE_PAREN)
4031 /* Parse a list of predefined predicate identifiers.
4032 preds = '(' 'define_predicates' <ident>... ')' */
4035 parser::parse_predicates (source_location)
4039 const cpp_token *token = peek ();
4040 if (token->type != CPP_NAME)
4043 add_predicate (get_ident ());
4048 /* Parse outer control structures.
4049 pattern = <preds>|<for>|<if>|<simplify>|<match> */
4052 parser::parse_pattern ()
4054 /* All clauses start with '('. */
4055 eat_token (CPP_OPEN_PAREN);
4056 const cpp_token *token = peek ();
4057 const char *id = get_ident ();
4058 if (strcmp (id, "simplify") == 0)
4060 parse_simplify (simplify::SIMPLIFY, simplifiers, NULL, NULL);
4063 else if (strcmp (id, "match") == 0)
4065 bool with_args = false;
4066 source_location e_loc = peek ()->src_loc;
4067 if (peek ()->type == CPP_OPEN_PAREN)
4069 eat_token (CPP_OPEN_PAREN);
4072 const char *name = get_ident ();
4073 id_base *id = get_operator (name);
4077 p = add_predicate (name);
4078 user_predicates.safe_push (p);
4080 else if ((p = dyn_cast <predicate_id *> (id)))
4083 fatal_at (token, "cannot add a match to a non-predicate ID");
4084 /* Parse (match <id> <arg>... (match-expr)) here. */
4088 capture_ids = new cid_map_t;
4089 e = new expr (p, e_loc);
4090 while (peek ()->type == CPP_ATSIGN)
4091 e->append_op (parse_capture (NULL, false));
4092 eat_token (CPP_CLOSE_PAREN);
4095 && ((e && e->ops.length () != (unsigned)p->nargs)
4096 || (!e && p->nargs != 0)))
4097 fatal_at (token, "non-matching number of match operands");
4098 p->nargs = e ? e->ops.length () : 0;
4099 parse_simplify (simplify::MATCH, p->matchers, p, e);
4102 else if (strcmp (id, "for") == 0)
4103 parse_for (token->src_loc);
4104 else if (strcmp (id, "if") == 0)
4105 parse_if (token->src_loc);
4106 else if (strcmp (id, "define_predicates") == 0)
4108 if (active_ifs.length () > 0
4109 || active_fors.length () > 0)
4110 fatal_at (token, "define_predicates inside if or for is not supported");
4111 parse_predicates (token->src_loc);
4113 else if (strcmp (id, "define_operator_list") == 0)
4115 if (active_ifs.length () > 0
4116 || active_fors.length () > 0)
4117 fatal_at (token, "operator-list inside if or for is not supported");
4118 parse_operator_list (token->src_loc);
4121 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
4122 active_ifs.length () == 0 && active_fors.length () == 0
4123 ? "'define_predicates', " : "");
4125 eat_token (CPP_CLOSE_PAREN);
4128 /* Main entry of the parser. Repeatedly parse outer control structures. */
4130 parser::parser (cpp_reader *r_)
4134 active_fors = vNULL;
4135 simplifiers = vNULL;
4136 oper_lists_set = NULL;
4139 user_predicates = vNULL;
4140 parsing_match_operand = false;
4142 const cpp_token *token = next ();
4143 while (token->type != CPP_EOF)
4145 _cpp_backup_tokens (r, 1);
4152 /* Helper for the linemap code. */
4155 round_alloc_size (size_t s)
4161 /* The genmatch generator progam. It reads from a pattern description
4162 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
4165 main (int argc, char **argv)
4169 progname = "genmatch";
4175 char *input = argv[argc-1];
4176 for (int i = 1; i < argc - 1; ++i)
4178 if (strcmp (argv[i], "--gimple") == 0)
4180 else if (strcmp (argv[i], "--generic") == 0)
4182 else if (strcmp (argv[i], "-v") == 0)
4184 else if (strcmp (argv[i], "-vv") == 0)
4188 fprintf (stderr, "Usage: genmatch "
4189 "[--gimple] [--generic] [-v[v]] input\n");
4194 line_table = XCNEW (struct line_maps);
4195 linemap_init (line_table, 0);
4196 line_table->reallocator = xrealloc;
4197 line_table->round_alloc_size = round_alloc_size;
4199 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
4200 cpp_callbacks *cb = cpp_get_callbacks (r);
4201 cb->error = error_cb;
4203 if (!cpp_read_main_file (r, input))
4205 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
4206 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
4208 /* Pre-seed operators. */
4209 operators = new hash_table<id_base> (1024);
4210 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
4211 add_operator (SYM, # SYM, # TYPE, NARGS);
4212 #define END_OF_BASE_TREE_CODES
4214 add_operator (CONVERT0, "CONVERT0", "tcc_unary", 1);
4215 add_operator (CONVERT1, "CONVERT1", "tcc_unary", 1);
4216 add_operator (CONVERT2, "CONVERT2", "tcc_unary", 1);
4217 add_operator (VIEW_CONVERT0, "VIEW_CONVERT0", "tcc_unary", 1);
4218 add_operator (VIEW_CONVERT1, "VIEW_CONVERT1", "tcc_unary", 1);
4219 add_operator (VIEW_CONVERT2, "VIEW_CONVERT2", "tcc_unary", 1);
4220 #undef END_OF_BASE_TREE_CODES
4223 /* Pre-seed builtin functions.
4224 ??? Cannot use N (name) as that is targetm.emultls.get_address
4225 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
4226 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
4227 add_builtin (ENUM, # ENUM);
4228 #include "builtins.def"
4235 write_header (stdout, "gimple-match-head.c");
4237 write_header (stdout, "generic-match-head.c");
4239 /* Go over all predicates defined with patterns and perform
4240 lowering and code generation. */
4241 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
4243 predicate_id *pred = p.user_predicates[i];
4244 lower (pred->matchers, gimple);
4247 for (unsigned i = 0; i < pred->matchers.length (); ++i)
4248 print_matches (pred->matchers[i]);
4251 for (unsigned i = 0; i < pred->matchers.length (); ++i)
4252 dt.insert (pred->matchers[i], i);
4257 write_predicate (stdout, pred, dt, gimple);
4260 /* Lower the main simplifiers and generate code for them. */
4261 lower (p.simplifiers, gimple);
4264 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
4265 print_matches (p.simplifiers[i]);
4268 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
4269 dt.insert (p.simplifiers[i], i);
4274 dt.gen (stdout, gimple);
4277 cpp_finish (r, NULL);