Daily bump.
[official-gcc.git] / gcc / genmatch.c
blob7045bb9103c24340ff0330edec8f66ada6b3e503
1 /* Generate pattern matching and transform code shared between
2 GENERIC and GIMPLE folding code from match-and-simplify description.
4 Copyright (C) 2014-2017 Free Software Foundation, Inc.
5 Contributed by Richard Biener <rguenther@suse.de>
6 and Prathamesh Kulkarni <bilbotheelffriend@gmail.com>
8 This file is part of GCC.
10 GCC is free software; you can redistribute it and/or modify it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 3, or (at your option) any later
13 version.
15 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 for more details.
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3. If not see
22 <http://www.gnu.org/licenses/>. */
24 #include "bconfig.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include <cpplib.h>
28 #include "errors.h"
29 #include "hash-table.h"
30 #include "hash-set.h"
31 #include "is-a.h"
34 /* Stubs for GGC referenced through instantiations triggered by hash-map. */
35 void *ggc_internal_cleared_alloc (size_t, void (*)(void *),
36 size_t, size_t MEM_STAT_DECL)
38 return NULL;
40 void ggc_free (void *)
45 /* Global state. */
47 /* Verboseness. 0 is quiet, 1 adds some warnings, 2 is for debugging. */
48 unsigned verbose;
51 /* libccp helpers. */
53 static struct line_maps *line_table;
55 /* The rich_location class within libcpp requires a way to expand
56 source_location instances, and relies on the client code
57 providing a symbol named
58 linemap_client_expand_location_to_spelling_point
59 to do this.
61 This is the implementation for genmatch. */
63 expanded_location
64 linemap_client_expand_location_to_spelling_point (source_location loc,
65 enum location_aspect)
67 const struct line_map_ordinary *map;
68 loc = linemap_resolve_location (line_table, loc, LRK_SPELLING_LOCATION, &map);
69 return linemap_expand_location (line_table, map, loc);
72 static bool
73 #if GCC_VERSION >= 4001
74 __attribute__((format (printf, 5, 0)))
75 #endif
76 error_cb (cpp_reader *, int errtype, int, rich_location *richloc,
77 const char *msg, va_list *ap)
79 const line_map_ordinary *map;
80 source_location location = richloc->get_loc ();
81 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
82 expanded_location loc = linemap_expand_location (line_table, map, location);
83 fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
84 (errtype == CPP_DL_WARNING) ? "warning" : "error");
85 vfprintf (stderr, msg, *ap);
86 fprintf (stderr, "\n");
87 FILE *f = fopen (loc.file, "r");
88 if (f)
90 char buf[128];
91 while (loc.line > 0)
93 if (!fgets (buf, 128, f))
94 goto notfound;
95 if (buf[strlen (buf) - 1] != '\n')
97 if (loc.line > 1)
98 loc.line++;
100 loc.line--;
102 fprintf (stderr, "%s", buf);
103 for (int i = 0; i < loc.column - 1; ++i)
104 fputc (' ', stderr);
105 fputc ('^', stderr);
106 fputc ('\n', stderr);
107 notfound:
108 fclose (f);
111 if (errtype == CPP_DL_FATAL)
112 exit (1);
113 return false;
116 static void
117 #if GCC_VERSION >= 4001
118 __attribute__((format (printf, 2, 3)))
119 #endif
120 fatal_at (const cpp_token *tk, const char *msg, ...)
122 rich_location richloc (line_table, tk->src_loc);
123 va_list ap;
124 va_start (ap, msg);
125 error_cb (NULL, CPP_DL_FATAL, 0, &richloc, msg, &ap);
126 va_end (ap);
129 static void
130 #if GCC_VERSION >= 4001
131 __attribute__((format (printf, 2, 3)))
132 #endif
133 fatal_at (source_location loc, const char *msg, ...)
135 rich_location richloc (line_table, loc);
136 va_list ap;
137 va_start (ap, msg);
138 error_cb (NULL, CPP_DL_FATAL, 0, &richloc, msg, &ap);
139 va_end (ap);
142 static void
143 #if GCC_VERSION >= 4001
144 __attribute__((format (printf, 2, 3)))
145 #endif
146 warning_at (const cpp_token *tk, const char *msg, ...)
148 rich_location richloc (line_table, tk->src_loc);
149 va_list ap;
150 va_start (ap, msg);
151 error_cb (NULL, CPP_DL_WARNING, 0, &richloc, msg, &ap);
152 va_end (ap);
155 static void
156 #if GCC_VERSION >= 4001
157 __attribute__((format (printf, 2, 3)))
158 #endif
159 warning_at (source_location loc, const char *msg, ...)
161 rich_location richloc (line_table, loc);
162 va_list ap;
163 va_start (ap, msg);
164 error_cb (NULL, CPP_DL_WARNING, 0, &richloc, msg, &ap);
165 va_end (ap);
168 /* Like fprintf, but print INDENT spaces at the beginning. */
170 static void
171 #if GCC_VERSION >= 4001
172 __attribute__((format (printf, 3, 4)))
173 #endif
174 fprintf_indent (FILE *f, unsigned int indent, const char *format, ...)
176 va_list ap;
177 for (; indent >= 8; indent -= 8)
178 fputc ('\t', f);
179 fprintf (f, "%*s", indent, "");
180 va_start (ap, format);
181 vfprintf (f, format, ap);
182 va_end (ap);
185 static void
186 output_line_directive (FILE *f, source_location location,
187 bool dumpfile = false)
189 const line_map_ordinary *map;
190 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
191 expanded_location loc = linemap_expand_location (line_table, map, location);
192 if (dumpfile)
194 /* When writing to a dumpfile only dump the filename. */
195 const char *file = strrchr (loc.file, DIR_SEPARATOR);
196 #if defined(DIR_SEPARATOR_2)
197 const char *pos2 = strrchr (loc.file, DIR_SEPARATOR_2);
198 if (pos2 && (!file || (pos2 > file)))
199 file = pos2;
200 #endif
201 if (!file)
202 file = loc.file;
203 else
204 ++file;
205 fprintf (f, "%s:%d", file, loc.line);
207 else
208 /* Other gen programs really output line directives here, at least for
209 development it's right now more convenient to have line information
210 from the generated file. Still keep the directives as comment for now
211 to easily back-point to the meta-description. */
212 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
216 /* Pull in tree codes and builtin function codes from their
217 definition files. */
219 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
220 enum tree_code {
221 #include "tree.def"
222 CONVERT0,
223 CONVERT1,
224 CONVERT2,
225 VIEW_CONVERT0,
226 VIEW_CONVERT1,
227 VIEW_CONVERT2,
228 MAX_TREE_CODES
230 #undef DEFTREECODE
232 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
233 enum built_in_function {
234 #include "builtins.def"
235 END_BUILTINS
238 #define DEF_INTERNAL_FN(CODE, FLAGS, FNSPEC) IFN_##CODE,
239 enum internal_fn {
240 #include "internal-fn.def"
241 IFN_LAST
244 /* Return true if CODE represents a commutative tree code. Otherwise
245 return false. */
246 bool
247 commutative_tree_code (enum tree_code code)
249 switch (code)
251 case PLUS_EXPR:
252 case MULT_EXPR:
253 case MULT_HIGHPART_EXPR:
254 case MIN_EXPR:
255 case MAX_EXPR:
256 case BIT_IOR_EXPR:
257 case BIT_XOR_EXPR:
258 case BIT_AND_EXPR:
259 case NE_EXPR:
260 case EQ_EXPR:
261 case UNORDERED_EXPR:
262 case ORDERED_EXPR:
263 case UNEQ_EXPR:
264 case LTGT_EXPR:
265 case TRUTH_AND_EXPR:
266 case TRUTH_XOR_EXPR:
267 case TRUTH_OR_EXPR:
268 case WIDEN_MULT_EXPR:
269 case VEC_WIDEN_MULT_HI_EXPR:
270 case VEC_WIDEN_MULT_LO_EXPR:
271 case VEC_WIDEN_MULT_EVEN_EXPR:
272 case VEC_WIDEN_MULT_ODD_EXPR:
273 return true;
275 default:
276 break;
278 return false;
281 /* Return true if CODE represents a ternary tree code for which the
282 first two operands are commutative. Otherwise return false. */
283 bool
284 commutative_ternary_tree_code (enum tree_code code)
286 switch (code)
288 case WIDEN_MULT_PLUS_EXPR:
289 case WIDEN_MULT_MINUS_EXPR:
290 case DOT_PROD_EXPR:
291 case FMA_EXPR:
292 return true;
294 default:
295 break;
297 return false;
300 /* Return true if CODE is a comparison. */
302 bool
303 comparison_code_p (enum tree_code code)
305 switch (code)
307 case EQ_EXPR:
308 case NE_EXPR:
309 case ORDERED_EXPR:
310 case UNORDERED_EXPR:
311 case LTGT_EXPR:
312 case UNEQ_EXPR:
313 case GT_EXPR:
314 case GE_EXPR:
315 case LT_EXPR:
316 case LE_EXPR:
317 case UNGT_EXPR:
318 case UNGE_EXPR:
319 case UNLT_EXPR:
320 case UNLE_EXPR:
321 return true;
323 default:
324 break;
326 return false;
330 /* Base class for all identifiers the parser knows. */
332 struct id_base : nofree_ptr_hash<id_base>
334 enum id_kind { CODE, FN, PREDICATE, USER, NULL_ID } kind;
336 id_base (id_kind, const char *, int = -1);
338 hashval_t hashval;
339 int nargs;
340 const char *id;
342 /* hash_table support. */
343 static inline hashval_t hash (const id_base *);
344 static inline int equal (const id_base *, const id_base *);
347 inline hashval_t
348 id_base::hash (const id_base *op)
350 return op->hashval;
353 inline int
354 id_base::equal (const id_base *op1,
355 const id_base *op2)
357 return (op1->hashval == op2->hashval
358 && strcmp (op1->id, op2->id) == 0);
361 /* The special id "null", which matches nothing. */
362 static id_base *null_id;
364 /* Hashtable of known pattern operators. This is pre-seeded from
365 all known tree codes and all known builtin function ids. */
366 static hash_table<id_base> *operators;
368 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
370 kind = kind_;
371 id = id_;
372 nargs = nargs_;
373 hashval = htab_hash_string (id);
376 /* Identifier that maps to a tree code. */
378 struct operator_id : public id_base
380 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
381 const char *tcc_)
382 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
383 enum tree_code code;
384 const char *tcc;
387 /* Identifier that maps to a builtin or internal function code. */
389 struct fn_id : public id_base
391 fn_id (enum built_in_function fn_, const char *id_)
392 : id_base (id_base::FN, id_), fn (fn_) {}
393 fn_id (enum internal_fn fn_, const char *id_)
394 : id_base (id_base::FN, id_), fn (int (END_BUILTINS) + int (fn_)) {}
395 unsigned int fn;
398 struct simplify;
400 /* Identifier that maps to a user-defined predicate. */
402 struct predicate_id : public id_base
404 predicate_id (const char *id_)
405 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
406 vec<simplify *> matchers;
409 /* Identifier that maps to a operator defined by a 'for' directive. */
411 struct user_id : public id_base
413 user_id (const char *id_, bool is_oper_list_ = false)
414 : id_base (id_base::USER, id_), substitutes (vNULL),
415 used (false), is_oper_list (is_oper_list_) {}
416 vec<id_base *> substitutes;
417 bool used;
418 bool is_oper_list;
421 template<>
422 template<>
423 inline bool
424 is_a_helper <fn_id *>::test (id_base *id)
426 return id->kind == id_base::FN;
429 template<>
430 template<>
431 inline bool
432 is_a_helper <operator_id *>::test (id_base *id)
434 return id->kind == id_base::CODE;
437 template<>
438 template<>
439 inline bool
440 is_a_helper <predicate_id *>::test (id_base *id)
442 return id->kind == id_base::PREDICATE;
445 template<>
446 template<>
447 inline bool
448 is_a_helper <user_id *>::test (id_base *id)
450 return id->kind == id_base::USER;
453 /* Add a predicate identifier to the hash. */
455 static predicate_id *
456 add_predicate (const char *id)
458 predicate_id *p = new predicate_id (id);
459 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
460 if (*slot)
461 fatal ("duplicate id definition");
462 *slot = p;
463 return p;
466 /* Add a tree code identifier to the hash. */
468 static void
469 add_operator (enum tree_code code, const char *id,
470 const char *tcc, unsigned nargs)
472 if (strcmp (tcc, "tcc_unary") != 0
473 && strcmp (tcc, "tcc_binary") != 0
474 && strcmp (tcc, "tcc_comparison") != 0
475 && strcmp (tcc, "tcc_expression") != 0
476 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
477 && strcmp (tcc, "tcc_reference") != 0
478 /* To have INTEGER_CST and friends as "predicate operators". */
479 && strcmp (tcc, "tcc_constant") != 0
480 /* And allow CONSTRUCTOR for vector initializers. */
481 && !(code == CONSTRUCTOR)
482 /* Allow SSA_NAME as predicate operator. */
483 && !(code == SSA_NAME))
484 return;
485 /* Treat ADDR_EXPR as atom, thus don't allow matching its operand. */
486 if (code == ADDR_EXPR)
487 nargs = 0;
488 operator_id *op = new operator_id (code, id, nargs, tcc);
489 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
490 if (*slot)
491 fatal ("duplicate id definition");
492 *slot = op;
495 /* Add a built-in or internal function identifier to the hash. ID is
496 the name of its CFN_* enumeration value. */
498 template <typename T>
499 static void
500 add_function (T code, const char *id)
502 fn_id *fn = new fn_id (code, id);
503 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
504 if (*slot)
505 fatal ("duplicate id definition");
506 *slot = fn;
509 /* Helper for easy comparing ID with tree code CODE. */
511 static bool
512 operator==(id_base &id, enum tree_code code)
514 if (operator_id *oid = dyn_cast <operator_id *> (&id))
515 return oid->code == code;
516 return false;
519 /* Lookup the identifier ID. Allow "null" if ALLOW_NULL. */
521 id_base *
522 get_operator (const char *id, bool allow_null = false)
524 if (allow_null && strcmp (id, "null") == 0)
525 return null_id;
527 id_base tem (id_base::CODE, id);
529 id_base *op = operators->find_with_hash (&tem, tem.hashval);
530 if (op)
532 /* If this is a user-defined identifier track whether it was used. */
533 if (user_id *uid = dyn_cast<user_id *> (op))
534 uid->used = true;
535 return op;
538 char *id2;
539 bool all_upper = true;
540 bool all_lower = true;
541 for (unsigned int i = 0; id[i]; ++i)
542 if (ISUPPER (id[i]))
543 all_lower = false;
544 else if (ISLOWER (id[i]))
545 all_upper = false;
546 if (all_lower)
548 /* Try in caps with _EXPR appended. */
549 id2 = ACONCAT ((id, "_EXPR", NULL));
550 for (unsigned int i = 0; id2[i]; ++i)
551 id2[i] = TOUPPER (id2[i]);
553 else if (all_upper && strncmp (id, "IFN_", 4) == 0)
554 /* Try CFN_ instead of IFN_. */
555 id2 = ACONCAT (("CFN_", id + 4, NULL));
556 else if (all_upper && strncmp (id, "BUILT_IN_", 9) == 0)
557 /* Try prepending CFN_. */
558 id2 = ACONCAT (("CFN_", id, NULL));
559 else
560 return NULL;
562 new (&tem) id_base (id_base::CODE, id2);
563 return operators->find_with_hash (&tem, tem.hashval);
566 /* Return the comparison operators that results if the operands are
567 swapped. This is safe for floating-point. */
569 id_base *
570 swap_tree_comparison (operator_id *p)
572 switch (p->code)
574 case EQ_EXPR:
575 case NE_EXPR:
576 case ORDERED_EXPR:
577 case UNORDERED_EXPR:
578 case LTGT_EXPR:
579 case UNEQ_EXPR:
580 return p;
581 case GT_EXPR:
582 return get_operator ("LT_EXPR");
583 case GE_EXPR:
584 return get_operator ("LE_EXPR");
585 case LT_EXPR:
586 return get_operator ("GT_EXPR");
587 case LE_EXPR:
588 return get_operator ("GE_EXPR");
589 case UNGT_EXPR:
590 return get_operator ("UNLT_EXPR");
591 case UNGE_EXPR:
592 return get_operator ("UNLE_EXPR");
593 case UNLT_EXPR:
594 return get_operator ("UNGT_EXPR");
595 case UNLE_EXPR:
596 return get_operator ("UNGE_EXPR");
597 default:
598 gcc_unreachable ();
602 typedef hash_map<nofree_string_hash, unsigned> cid_map_t;
605 /* The AST produced by parsing of the pattern definitions. */
607 struct dt_operand;
608 struct capture_info;
610 /* The base class for operands. */
612 struct operand {
613 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR, OP_IF, OP_WITH };
614 operand (enum op_type type_, source_location loc_)
615 : type (type_), location (loc_) {}
616 enum op_type type;
617 source_location location;
618 virtual void gen_transform (FILE *, int, const char *, bool, int,
619 const char *, capture_info *,
620 dt_operand ** = 0,
621 int = 0)
622 { gcc_unreachable (); }
625 /* A predicate operand. Predicates are leafs in the AST. */
627 struct predicate : public operand
629 predicate (predicate_id *p_, source_location loc)
630 : operand (OP_PREDICATE, loc), p (p_) {}
631 predicate_id *p;
634 /* An operand that constitutes an expression. Expressions include
635 function calls and user-defined predicate invocations. */
637 struct expr : public operand
639 expr (id_base *operation_, source_location loc, bool is_commutative_ = false)
640 : operand (OP_EXPR, loc), operation (operation_),
641 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
642 is_generic (false), force_single_use (false) {}
643 expr (expr *e)
644 : operand (OP_EXPR, e->location), operation (e->operation),
645 ops (vNULL), expr_type (e->expr_type), is_commutative (e->is_commutative),
646 is_generic (e->is_generic), force_single_use (e->force_single_use) {}
647 void append_op (operand *op) { ops.safe_push (op); }
648 /* The operator and its operands. */
649 id_base *operation;
650 vec<operand *> ops;
651 /* An explicitely specified type - used exclusively for conversions. */
652 const char *expr_type;
653 /* Whether the operation is to be applied commutatively. This is
654 later lowered to two separate patterns. */
655 bool is_commutative;
656 /* Whether the expression is expected to be in GENERIC form. */
657 bool is_generic;
658 /* Whether pushing any stmt to the sequence should be conditional
659 on this expression having a single-use. */
660 bool force_single_use;
661 virtual void gen_transform (FILE *f, int, const char *, bool, int,
662 const char *, capture_info *,
663 dt_operand ** = 0, int = 0);
666 /* An operator that is represented by native C code. This is always
667 a leaf operand in the AST. This class is also used to represent
668 the code to be generated for 'if' and 'with' expressions. */
670 struct c_expr : public operand
672 /* A mapping of an identifier and its replacement. Used to apply
673 'for' lowering. */
674 struct id_tab {
675 const char *id;
676 const char *oper;
677 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
680 c_expr (cpp_reader *r_, source_location loc,
681 vec<cpp_token> code_, unsigned nr_stmts_,
682 vec<id_tab> ids_, cid_map_t *capture_ids_)
683 : operand (OP_C_EXPR, loc), r (r_), code (code_),
684 capture_ids (capture_ids_), nr_stmts (nr_stmts_), ids (ids_) {}
685 /* cpplib tokens and state to transform this back to source. */
686 cpp_reader *r;
687 vec<cpp_token> code;
688 cid_map_t *capture_ids;
689 /* The number of statements parsed (well, the number of ';'s). */
690 unsigned nr_stmts;
691 /* The identifier replacement vector. */
692 vec<id_tab> ids;
693 virtual void gen_transform (FILE *f, int, const char *, bool, int,
694 const char *, capture_info *,
695 dt_operand ** = 0, int = 0);
698 /* A wrapper around another operand that captures its value. */
700 struct capture : public operand
702 capture (source_location loc, unsigned where_, operand *what_, bool value_)
703 : operand (OP_CAPTURE, loc), where (where_), value_match (value_),
704 what (what_) {}
705 /* Identifier index for the value. */
706 unsigned where;
707 /* Whether in a match of two operands the compare should be for
708 equal values rather than equal atoms (boils down to a type
709 check or not). */
710 bool value_match;
711 /* The captured value. */
712 operand *what;
713 virtual void gen_transform (FILE *f, int, const char *, bool, int,
714 const char *, capture_info *,
715 dt_operand ** = 0, int = 0);
718 /* if expression. */
720 struct if_expr : public operand
722 if_expr (source_location loc)
723 : operand (OP_IF, loc), cond (NULL), trueexpr (NULL), falseexpr (NULL) {}
724 c_expr *cond;
725 operand *trueexpr;
726 operand *falseexpr;
729 /* with expression. */
731 struct with_expr : public operand
733 with_expr (source_location loc)
734 : operand (OP_WITH, loc), with (NULL), subexpr (NULL) {}
735 c_expr *with;
736 operand *subexpr;
739 template<>
740 template<>
741 inline bool
742 is_a_helper <capture *>::test (operand *op)
744 return op->type == operand::OP_CAPTURE;
747 template<>
748 template<>
749 inline bool
750 is_a_helper <predicate *>::test (operand *op)
752 return op->type == operand::OP_PREDICATE;
755 template<>
756 template<>
757 inline bool
758 is_a_helper <c_expr *>::test (operand *op)
760 return op->type == operand::OP_C_EXPR;
763 template<>
764 template<>
765 inline bool
766 is_a_helper <expr *>::test (operand *op)
768 return op->type == operand::OP_EXPR;
771 template<>
772 template<>
773 inline bool
774 is_a_helper <if_expr *>::test (operand *op)
776 return op->type == operand::OP_IF;
779 template<>
780 template<>
781 inline bool
782 is_a_helper <with_expr *>::test (operand *op)
784 return op->type == operand::OP_WITH;
787 /* The main class of a pattern and its transform. This is used to
788 represent both (simplify ...) and (match ...) kinds. The AST
789 duplicates all outer 'if' and 'for' expressions here so each
790 simplify can exist in isolation. */
792 struct simplify
794 enum simplify_kind { SIMPLIFY, MATCH };
796 simplify (simplify_kind kind_, operand *match_, operand *result_,
797 vec<vec<user_id *> > for_vec_, cid_map_t *capture_ids_)
798 : kind (kind_), match (match_), result (result_),
799 for_vec (for_vec_), for_subst_vec (vNULL),
800 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
802 simplify_kind kind;
803 /* The expression that is matched against the GENERIC or GIMPLE IL. */
804 operand *match;
805 /* For a (simplify ...) an expression with ifs and withs with the expression
806 produced when the pattern applies in the leafs.
807 For a (match ...) the leafs are either empty if it is a simple predicate
808 or the single expression specifying the matched operands. */
809 struct operand *result;
810 /* Collected 'for' expression operators that have to be replaced
811 in the lowering phase. */
812 vec<vec<user_id *> > for_vec;
813 vec<std::pair<user_id *, id_base *> > for_subst_vec;
814 /* A map of capture identifiers to indexes. */
815 cid_map_t *capture_ids;
816 int capture_max;
819 /* Debugging routines for dumping the AST. */
821 DEBUG_FUNCTION void
822 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
824 if (capture *c = dyn_cast<capture *> (o))
826 if (c->what && flattened == false)
827 print_operand (c->what, f, flattened);
828 fprintf (f, "@%u", c->where);
831 else if (predicate *p = dyn_cast<predicate *> (o))
832 fprintf (f, "%s", p->p->id);
834 else if (is_a<c_expr *> (o))
835 fprintf (f, "c_expr");
837 else if (expr *e = dyn_cast<expr *> (o))
839 if (e->ops.length () == 0)
840 fprintf (f, "%s", e->operation->id);
841 else
843 fprintf (f, "(%s", e->operation->id);
845 if (flattened == false)
847 for (unsigned i = 0; i < e->ops.length (); ++i)
849 putc (' ', f);
850 print_operand (e->ops[i], f, flattened);
853 putc (')', f);
857 else
858 gcc_unreachable ();
861 DEBUG_FUNCTION void
862 print_matches (struct simplify *s, FILE *f = stderr)
864 fprintf (f, "for expression: ");
865 print_operand (s->match, f);
866 putc ('\n', f);
870 /* AST lowering. */
872 /* Lowering of commutative operators. */
874 static void
875 cartesian_product (const vec< vec<operand *> >& ops_vector,
876 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
878 if (n == ops_vector.length ())
880 vec<operand *> xv = v.copy ();
881 result.safe_push (xv);
882 return;
885 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
887 v[n] = ops_vector[n][i];
888 cartesian_product (ops_vector, result, v, n + 1);
892 /* Lower OP to two operands in case it is marked as commutative. */
894 static vec<operand *>
895 commutate (operand *op, vec<vec<user_id *> > &for_vec)
897 vec<operand *> ret = vNULL;
899 if (capture *c = dyn_cast <capture *> (op))
901 if (!c->what)
903 ret.safe_push (op);
904 return ret;
906 vec<operand *> v = commutate (c->what, for_vec);
907 for (unsigned i = 0; i < v.length (); ++i)
909 capture *nc = new capture (c->location, c->where, v[i],
910 c->value_match);
911 ret.safe_push (nc);
913 return ret;
916 expr *e = dyn_cast <expr *> (op);
917 if (!e || e->ops.length () == 0)
919 ret.safe_push (op);
920 return ret;
923 vec< vec<operand *> > ops_vector = vNULL;
924 for (unsigned i = 0; i < e->ops.length (); ++i)
925 ops_vector.safe_push (commutate (e->ops[i], for_vec));
927 auto_vec< vec<operand *> > result;
928 auto_vec<operand *> v (e->ops.length ());
929 v.quick_grow_cleared (e->ops.length ());
930 cartesian_product (ops_vector, result, v, 0);
933 for (unsigned i = 0; i < result.length (); ++i)
935 expr *ne = new expr (e);
936 ne->is_commutative = false;
937 for (unsigned j = 0; j < result[i].length (); ++j)
938 ne->append_op (result[i][j]);
939 ret.safe_push (ne);
942 if (!e->is_commutative)
943 return ret;
945 for (unsigned i = 0; i < result.length (); ++i)
947 expr *ne = new expr (e);
948 if (operator_id *p = dyn_cast <operator_id *> (ne->operation))
950 if (comparison_code_p (p->code))
951 ne->operation = swap_tree_comparison (p);
953 else if (user_id *p = dyn_cast <user_id *> (ne->operation))
955 bool found_compare = false;
956 for (unsigned j = 0; j < p->substitutes.length (); ++j)
957 if (operator_id *q = dyn_cast <operator_id *> (p->substitutes[j]))
959 if (comparison_code_p (q->code)
960 && swap_tree_comparison (q) != q)
962 found_compare = true;
963 break;
966 if (found_compare)
968 user_id *newop = new user_id ("<internal>");
969 for (unsigned j = 0; j < p->substitutes.length (); ++j)
971 id_base *subst = p->substitutes[j];
972 if (operator_id *q = dyn_cast <operator_id *> (subst))
974 if (comparison_code_p (q->code))
975 subst = swap_tree_comparison (q);
977 newop->substitutes.safe_push (subst);
979 ne->operation = newop;
980 /* Search for 'p' inside the for vector and push 'newop'
981 to the same level. */
982 for (unsigned j = 0; newop && j < for_vec.length (); ++j)
983 for (unsigned k = 0; k < for_vec[j].length (); ++k)
984 if (for_vec[j][k] == p)
986 for_vec[j].safe_push (newop);
987 newop = NULL;
988 break;
992 ne->is_commutative = false;
993 // result[i].length () is 2 since e->operation is binary
994 for (unsigned j = result[i].length (); j; --j)
995 ne->append_op (result[i][j-1]);
996 ret.safe_push (ne);
999 return ret;
1002 /* Lower operations marked as commutative in the AST of S and push
1003 the resulting patterns to SIMPLIFIERS. */
1005 static void
1006 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
1008 vec<operand *> matchers = commutate (s->match, s->for_vec);
1009 for (unsigned i = 0; i < matchers.length (); ++i)
1011 simplify *ns = new simplify (s->kind, matchers[i], s->result,
1012 s->for_vec, s->capture_ids);
1013 simplifiers.safe_push (ns);
1017 /* Strip conditional conversios using operator OPER from O and its
1018 children if STRIP, else replace them with an unconditional convert. */
1020 operand *
1021 lower_opt_convert (operand *o, enum tree_code oper,
1022 enum tree_code to_oper, bool strip)
1024 if (capture *c = dyn_cast<capture *> (o))
1026 if (c->what)
1027 return new capture (c->location, c->where,
1028 lower_opt_convert (c->what, oper, to_oper, strip),
1029 c->value_match);
1030 else
1031 return c;
1034 expr *e = dyn_cast<expr *> (o);
1035 if (!e)
1036 return o;
1038 if (*e->operation == oper)
1040 if (strip)
1041 return lower_opt_convert (e->ops[0], oper, to_oper, strip);
1043 expr *ne = new expr (e);
1044 ne->operation = (to_oper == CONVERT_EXPR
1045 ? get_operator ("CONVERT_EXPR")
1046 : get_operator ("VIEW_CONVERT_EXPR"));
1047 ne->append_op (lower_opt_convert (e->ops[0], oper, to_oper, strip));
1048 return ne;
1051 expr *ne = new expr (e);
1052 for (unsigned i = 0; i < e->ops.length (); ++i)
1053 ne->append_op (lower_opt_convert (e->ops[i], oper, to_oper, strip));
1055 return ne;
1058 /* Determine whether O or its children uses the conditional conversion
1059 operator OPER. */
1061 static bool
1062 has_opt_convert (operand *o, enum tree_code oper)
1064 if (capture *c = dyn_cast<capture *> (o))
1066 if (c->what)
1067 return has_opt_convert (c->what, oper);
1068 else
1069 return false;
1072 expr *e = dyn_cast<expr *> (o);
1073 if (!e)
1074 return false;
1076 if (*e->operation == oper)
1077 return true;
1079 for (unsigned i = 0; i < e->ops.length (); ++i)
1080 if (has_opt_convert (e->ops[i], oper))
1081 return true;
1083 return false;
1086 /* Lower conditional convert operators in O, expanding it to a vector
1087 if required. */
1089 static vec<operand *>
1090 lower_opt_convert (operand *o)
1092 vec<operand *> v1 = vNULL, v2;
1094 v1.safe_push (o);
1096 enum tree_code opers[]
1097 = { CONVERT0, CONVERT_EXPR,
1098 CONVERT1, CONVERT_EXPR,
1099 CONVERT2, CONVERT_EXPR,
1100 VIEW_CONVERT0, VIEW_CONVERT_EXPR,
1101 VIEW_CONVERT1, VIEW_CONVERT_EXPR,
1102 VIEW_CONVERT2, VIEW_CONVERT_EXPR };
1104 /* Conditional converts are lowered to a pattern with the
1105 conversion and one without. The three different conditional
1106 convert codes are lowered separately. */
1108 for (unsigned i = 0; i < sizeof (opers) / sizeof (enum tree_code); i += 2)
1110 v2 = vNULL;
1111 for (unsigned j = 0; j < v1.length (); ++j)
1112 if (has_opt_convert (v1[j], opers[i]))
1114 v2.safe_push (lower_opt_convert (v1[j],
1115 opers[i], opers[i+1], false));
1116 v2.safe_push (lower_opt_convert (v1[j],
1117 opers[i], opers[i+1], true));
1120 if (v2 != vNULL)
1122 v1 = vNULL;
1123 for (unsigned j = 0; j < v2.length (); ++j)
1124 v1.safe_push (v2[j]);
1128 return v1;
1131 /* Lower conditional convert operators in the AST of S and push
1132 the resulting multiple patterns to SIMPLIFIERS. */
1134 static void
1135 lower_opt_convert (simplify *s, vec<simplify *>& simplifiers)
1137 vec<operand *> matchers = lower_opt_convert (s->match);
1138 for (unsigned i = 0; i < matchers.length (); ++i)
1140 simplify *ns = new simplify (s->kind, matchers[i], s->result,
1141 s->for_vec, s->capture_ids);
1142 simplifiers.safe_push (ns);
1146 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1147 GENERIC and a GIMPLE variant. */
1149 static vec<operand *>
1150 lower_cond (operand *o)
1152 vec<operand *> ro = vNULL;
1154 if (capture *c = dyn_cast<capture *> (o))
1156 if (c->what)
1158 vec<operand *> lop = vNULL;
1159 lop = lower_cond (c->what);
1161 for (unsigned i = 0; i < lop.length (); ++i)
1162 ro.safe_push (new capture (c->location, c->where, lop[i],
1163 c->value_match));
1164 return ro;
1168 expr *e = dyn_cast<expr *> (o);
1169 if (!e || e->ops.length () == 0)
1171 ro.safe_push (o);
1172 return ro;
1175 vec< vec<operand *> > ops_vector = vNULL;
1176 for (unsigned i = 0; i < e->ops.length (); ++i)
1177 ops_vector.safe_push (lower_cond (e->ops[i]));
1179 auto_vec< vec<operand *> > result;
1180 auto_vec<operand *> v (e->ops.length ());
1181 v.quick_grow_cleared (e->ops.length ());
1182 cartesian_product (ops_vector, result, v, 0);
1184 for (unsigned i = 0; i < result.length (); ++i)
1186 expr *ne = new expr (e);
1187 for (unsigned j = 0; j < result[i].length (); ++j)
1188 ne->append_op (result[i][j]);
1189 ro.safe_push (ne);
1190 /* If this is a COND with a captured expression or an
1191 expression with two operands then also match a GENERIC
1192 form on the compare. */
1193 if ((*e->operation == COND_EXPR
1194 || *e->operation == VEC_COND_EXPR)
1195 && ((is_a <capture *> (e->ops[0])
1196 && as_a <capture *> (e->ops[0])->what
1197 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
1198 && as_a <expr *>
1199 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
1200 || (is_a <expr *> (e->ops[0])
1201 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
1203 expr *ne = new expr (e);
1204 for (unsigned j = 0; j < result[i].length (); ++j)
1205 ne->append_op (result[i][j]);
1206 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
1208 expr *ocmp = as_a <expr *> (c->what);
1209 expr *cmp = new expr (ocmp);
1210 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1211 cmp->append_op (ocmp->ops[j]);
1212 cmp->is_generic = true;
1213 ne->ops[0] = new capture (c->location, c->where, cmp,
1214 c->value_match);
1216 else
1218 expr *ocmp = as_a <expr *> (ne->ops[0]);
1219 expr *cmp = new expr (ocmp);
1220 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1221 cmp->append_op (ocmp->ops[j]);
1222 cmp->is_generic = true;
1223 ne->ops[0] = cmp;
1225 ro.safe_push (ne);
1229 return ro;
1232 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1233 GENERIC and a GIMPLE variant. */
1235 static void
1236 lower_cond (simplify *s, vec<simplify *>& simplifiers)
1238 vec<operand *> matchers = lower_cond (s->match);
1239 for (unsigned i = 0; i < matchers.length (); ++i)
1241 simplify *ns = new simplify (s->kind, matchers[i], s->result,
1242 s->for_vec, s->capture_ids);
1243 simplifiers.safe_push (ns);
1247 /* Return true if O refers to ID. */
1249 bool
1250 contains_id (operand *o, user_id *id)
1252 if (capture *c = dyn_cast<capture *> (o))
1253 return c->what && contains_id (c->what, id);
1255 if (expr *e = dyn_cast<expr *> (o))
1257 if (e->operation == id)
1258 return true;
1259 for (unsigned i = 0; i < e->ops.length (); ++i)
1260 if (contains_id (e->ops[i], id))
1261 return true;
1262 return false;
1265 if (with_expr *w = dyn_cast <with_expr *> (o))
1266 return (contains_id (w->with, id)
1267 || contains_id (w->subexpr, id));
1269 if (if_expr *ife = dyn_cast <if_expr *> (o))
1270 return (contains_id (ife->cond, id)
1271 || contains_id (ife->trueexpr, id)
1272 || (ife->falseexpr && contains_id (ife->falseexpr, id)));
1274 if (c_expr *ce = dyn_cast<c_expr *> (o))
1275 return ce->capture_ids && ce->capture_ids->get (id->id);
1277 return false;
1281 /* In AST operand O replace operator ID with operator WITH. */
1283 operand *
1284 replace_id (operand *o, user_id *id, id_base *with)
1286 /* Deep-copy captures and expressions, replacing operations as
1287 needed. */
1288 if (capture *c = dyn_cast<capture *> (o))
1290 if (!c->what)
1291 return c;
1292 return new capture (c->location, c->where,
1293 replace_id (c->what, id, with), c->value_match);
1295 else if (expr *e = dyn_cast<expr *> (o))
1297 expr *ne = new expr (e);
1298 if (e->operation == id)
1299 ne->operation = with;
1300 for (unsigned i = 0; i < e->ops.length (); ++i)
1301 ne->append_op (replace_id (e->ops[i], id, with));
1302 return ne;
1304 else if (with_expr *w = dyn_cast <with_expr *> (o))
1306 with_expr *nw = new with_expr (w->location);
1307 nw->with = as_a <c_expr *> (replace_id (w->with, id, with));
1308 nw->subexpr = replace_id (w->subexpr, id, with);
1309 return nw;
1311 else if (if_expr *ife = dyn_cast <if_expr *> (o))
1313 if_expr *nife = new if_expr (ife->location);
1314 nife->cond = as_a <c_expr *> (replace_id (ife->cond, id, with));
1315 nife->trueexpr = replace_id (ife->trueexpr, id, with);
1316 if (ife->falseexpr)
1317 nife->falseexpr = replace_id (ife->falseexpr, id, with);
1318 return nife;
1321 /* For c_expr we simply record a string replacement table which is
1322 applied at code-generation time. */
1323 if (c_expr *ce = dyn_cast<c_expr *> (o))
1325 vec<c_expr::id_tab> ids = ce->ids.copy ();
1326 ids.safe_push (c_expr::id_tab (id->id, with->id));
1327 return new c_expr (ce->r, ce->location,
1328 ce->code, ce->nr_stmts, ids, ce->capture_ids);
1331 return o;
1334 /* Return true if the binary operator OP is ok for delayed substitution
1335 during for lowering. */
1337 static bool
1338 binary_ok (operator_id *op)
1340 switch (op->code)
1342 case PLUS_EXPR:
1343 case MINUS_EXPR:
1344 case MULT_EXPR:
1345 case TRUNC_DIV_EXPR:
1346 case CEIL_DIV_EXPR:
1347 case FLOOR_DIV_EXPR:
1348 case ROUND_DIV_EXPR:
1349 case TRUNC_MOD_EXPR:
1350 case CEIL_MOD_EXPR:
1351 case FLOOR_MOD_EXPR:
1352 case ROUND_MOD_EXPR:
1353 case RDIV_EXPR:
1354 case EXACT_DIV_EXPR:
1355 case MIN_EXPR:
1356 case MAX_EXPR:
1357 case BIT_IOR_EXPR:
1358 case BIT_XOR_EXPR:
1359 case BIT_AND_EXPR:
1360 return true;
1361 default:
1362 return false;
1366 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
1368 static void
1369 lower_for (simplify *sin, vec<simplify *>& simplifiers)
1371 vec<vec<user_id *> >& for_vec = sin->for_vec;
1372 unsigned worklist_start = 0;
1373 auto_vec<simplify *> worklist;
1374 worklist.safe_push (sin);
1376 /* Lower each recorded for separately, operating on the
1377 set of simplifiers created by the previous one.
1378 Lower inner-to-outer so inner for substitutes can refer
1379 to operators replaced by outer fors. */
1380 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1382 vec<user_id *>& ids = for_vec[fi];
1383 unsigned n_ids = ids.length ();
1384 unsigned max_n_opers = 0;
1385 bool can_delay_subst = (sin->kind == simplify::SIMPLIFY);
1386 for (unsigned i = 0; i < n_ids; ++i)
1388 if (ids[i]->substitutes.length () > max_n_opers)
1389 max_n_opers = ids[i]->substitutes.length ();
1390 /* Require that all substitutes are of the same kind so that
1391 if we delay substitution to the result op code generation
1392 can look at the first substitute for deciding things like
1393 types of operands. */
1394 enum id_base::id_kind kind = ids[i]->substitutes[0]->kind;
1395 for (unsigned j = 0; j < ids[i]->substitutes.length (); ++j)
1396 if (ids[i]->substitutes[j]->kind != kind)
1397 can_delay_subst = false;
1398 else if (operator_id *op
1399 = dyn_cast <operator_id *> (ids[i]->substitutes[j]))
1401 operator_id *op0
1402 = as_a <operator_id *> (ids[i]->substitutes[0]);
1403 if (strcmp (op->tcc, "tcc_comparison") == 0
1404 && strcmp (op0->tcc, "tcc_comparison") == 0)
1406 /* Unfortunately we can't just allow all tcc_binary. */
1407 else if (strcmp (op->tcc, "tcc_binary") == 0
1408 && strcmp (op0->tcc, "tcc_binary") == 0
1409 && binary_ok (op)
1410 && binary_ok (op0))
1412 else if ((strcmp (op->id + 1, "SHIFT_EXPR") == 0
1413 || strcmp (op->id + 1, "ROTATE_EXPR") == 0)
1414 && (strcmp (op0->id + 1, "SHIFT_EXPR") == 0
1415 || strcmp (op0->id + 1, "ROTATE_EXPR") == 0))
1417 else
1418 can_delay_subst = false;
1420 else if (is_a <fn_id *> (ids[i]->substitutes[j]))
1422 else
1423 can_delay_subst = false;
1426 unsigned worklist_end = worklist.length ();
1427 for (unsigned si = worklist_start; si < worklist_end; ++si)
1429 simplify *s = worklist[si];
1430 for (unsigned j = 0; j < max_n_opers; ++j)
1432 operand *match_op = s->match;
1433 operand *result_op = s->result;
1434 auto_vec<std::pair<user_id *, id_base *> > subst (n_ids);
1435 bool skip = false;
1436 for (unsigned i = 0; i < n_ids; ++i)
1438 user_id *id = ids[i];
1439 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1440 if (oper == null_id
1441 && (contains_id (match_op, id)
1442 || contains_id (result_op, id)))
1444 skip = true;
1445 break;
1447 subst.quick_push (std::make_pair (id, oper));
1448 match_op = replace_id (match_op, id, oper);
1449 if (result_op
1450 && !can_delay_subst)
1451 result_op = replace_id (result_op, id, oper);
1453 if (skip)
1454 continue;
1456 simplify *ns = new simplify (s->kind, match_op, result_op,
1457 vNULL, s->capture_ids);
1458 ns->for_subst_vec.safe_splice (s->for_subst_vec);
1459 if (result_op
1460 && can_delay_subst)
1461 ns->for_subst_vec.safe_splice (subst);
1463 worklist.safe_push (ns);
1466 worklist_start = worklist_end;
1469 /* Copy out the result from the last for lowering. */
1470 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1471 simplifiers.safe_push (worklist[i]);
1474 /* Lower the AST for everything in SIMPLIFIERS. */
1476 static void
1477 lower (vec<simplify *>& simplifiers, bool gimple)
1479 auto_vec<simplify *> out_simplifiers;
1480 for (unsigned i = 0; i < simplifiers.length (); ++i)
1481 lower_opt_convert (simplifiers[i], out_simplifiers);
1483 simplifiers.truncate (0);
1484 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1485 lower_commutative (out_simplifiers[i], simplifiers);
1487 out_simplifiers.truncate (0);
1488 if (gimple)
1489 for (unsigned i = 0; i < simplifiers.length (); ++i)
1490 lower_cond (simplifiers[i], out_simplifiers);
1491 else
1492 out_simplifiers.safe_splice (simplifiers);
1495 simplifiers.truncate (0);
1496 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1497 lower_for (out_simplifiers[i], simplifiers);
1503 /* The decision tree built for generating GIMPLE and GENERIC pattern
1504 matching code. It represents the 'match' expression of all
1505 simplifies and has those as its leafs. */
1507 struct dt_simplify;
1509 /* A hash-map collecting semantically equivalent leafs in the decision
1510 tree for splitting out to separate functions. */
1511 struct sinfo
1513 dt_simplify *s;
1515 const char *fname;
1516 unsigned cnt;
1519 struct sinfo_hashmap_traits : simple_hashmap_traits<pointer_hash<dt_simplify>,
1520 sinfo *>
1522 static inline hashval_t hash (const key_type &);
1523 static inline bool equal_keys (const key_type &, const key_type &);
1524 template <typename T> static inline void remove (T &) {}
1527 typedef hash_map<void * /* unused */, sinfo *, sinfo_hashmap_traits>
1528 sinfo_map_t;
1531 /* Decision tree base class, used for DT_TRUE and DT_NODE. */
1533 struct dt_node
1535 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1537 enum dt_type type;
1538 unsigned level;
1539 vec<dt_node *> kids;
1541 /* Statistics. */
1542 unsigned num_leafs;
1543 unsigned total_size;
1544 unsigned max_level;
1546 dt_node (enum dt_type type_): type (type_), level (0), kids (vNULL) {}
1548 dt_node *append_node (dt_node *);
1549 dt_node *append_op (operand *, dt_node *parent = 0, unsigned pos = 0);
1550 dt_node *append_true_op (dt_node *parent = 0, unsigned pos = 0);
1551 dt_node *append_match_op (dt_operand *, dt_node *parent = 0, unsigned pos = 0);
1552 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1554 virtual void gen (FILE *, int, bool) {}
1556 void gen_kids (FILE *, int, bool);
1557 void gen_kids_1 (FILE *, int, bool,
1558 vec<dt_operand *>, vec<dt_operand *>, vec<dt_operand *>,
1559 vec<dt_operand *>, vec<dt_operand *>, vec<dt_node *>);
1561 void analyze (sinfo_map_t &);
1564 /* Generic decision tree node used for DT_OPERAND and DT_MATCH. */
1566 struct dt_operand : public dt_node
1568 operand *op;
1569 dt_operand *match_dop;
1570 dt_operand *parent;
1571 unsigned pos;
1572 bool value_match;
1574 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1575 dt_operand *parent_ = 0, unsigned pos_ = 0)
1576 : dt_node (type), op (op_), match_dop (match_dop_),
1577 parent (parent_), pos (pos_), value_match (false) {}
1579 void gen (FILE *, int, bool);
1580 unsigned gen_predicate (FILE *, int, const char *, bool);
1581 unsigned gen_match_op (FILE *, int, const char *, bool);
1583 unsigned gen_gimple_expr (FILE *, int);
1584 unsigned gen_generic_expr (FILE *, int, const char *);
1586 char *get_name (char *);
1587 void gen_opname (char *, unsigned);
1590 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1592 struct dt_simplify : public dt_node
1594 simplify *s;
1595 unsigned pattern_no;
1596 dt_operand **indexes;
1597 sinfo *info;
1599 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1600 : dt_node (DT_SIMPLIFY), s (s_), pattern_no (pattern_no_),
1601 indexes (indexes_), info (NULL) {}
1603 void gen_1 (FILE *, int, bool, operand *);
1604 void gen (FILE *f, int, bool);
1607 template<>
1608 template<>
1609 inline bool
1610 is_a_helper <dt_operand *>::test (dt_node *n)
1612 return (n->type == dt_node::DT_OPERAND
1613 || n->type == dt_node::DT_MATCH);
1616 template<>
1617 template<>
1618 inline bool
1619 is_a_helper <dt_simplify *>::test (dt_node *n)
1621 return n->type == dt_node::DT_SIMPLIFY;
1626 /* A container for the actual decision tree. */
1628 struct decision_tree
1630 dt_node *root;
1632 void insert (struct simplify *, unsigned);
1633 void gen (FILE *f, bool gimple);
1634 void print (FILE *f = stderr);
1636 decision_tree () { root = new dt_node (dt_node::DT_NODE); }
1638 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1639 unsigned pos = 0, dt_node *parent = 0);
1640 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1641 static bool cmp_node (dt_node *, dt_node *);
1642 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1645 /* Compare two AST operands O1 and O2 and return true if they are equal. */
1647 bool
1648 cmp_operand (operand *o1, operand *o2)
1650 if (!o1 || !o2 || o1->type != o2->type)
1651 return false;
1653 if (o1->type == operand::OP_PREDICATE)
1655 predicate *p1 = as_a<predicate *>(o1);
1656 predicate *p2 = as_a<predicate *>(o2);
1657 return p1->p == p2->p;
1659 else if (o1->type == operand::OP_EXPR)
1661 expr *e1 = static_cast<expr *>(o1);
1662 expr *e2 = static_cast<expr *>(o2);
1663 return (e1->operation == e2->operation
1664 && e1->is_generic == e2->is_generic);
1666 else
1667 return false;
1670 /* Compare two decision tree nodes N1 and N2 and return true if they
1671 are equal. */
1673 bool
1674 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1676 if (!n1 || !n2 || n1->type != n2->type)
1677 return false;
1679 if (n1 == n2)
1680 return true;
1682 if (n1->type == dt_node::DT_TRUE)
1683 return false;
1685 if (n1->type == dt_node::DT_OPERAND)
1686 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1687 (as_a<dt_operand *> (n2))->op);
1688 else if (n1->type == dt_node::DT_MATCH)
1689 return (((as_a<dt_operand *> (n1))->match_dop
1690 == (as_a<dt_operand *> (n2))->match_dop)
1691 && ((as_a<dt_operand *> (n1))->value_match
1692 == (as_a<dt_operand *> (n2))->value_match));
1693 return false;
1696 /* Search OPS for a decision tree node like P and return it if found. */
1698 dt_node *
1699 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1701 /* We can merge adjacent DT_TRUE. */
1702 if (p->type == dt_node::DT_TRUE
1703 && !ops.is_empty ()
1704 && ops.last ()->type == dt_node::DT_TRUE)
1705 return ops.last ();
1706 for (int i = ops.length () - 1; i >= 0; --i)
1708 /* But we can't merge across DT_TRUE nodes as they serve as
1709 pattern order barriers to make sure that patterns apply
1710 in order of appearance in case multiple matches are possible. */
1711 if (ops[i]->type == dt_node::DT_TRUE)
1712 return NULL;
1713 if (decision_tree::cmp_node (ops[i], p))
1714 return ops[i];
1716 return NULL;
1719 /* Append N to the decision tree if it there is not already an existing
1720 identical child. */
1722 dt_node *
1723 dt_node::append_node (dt_node *n)
1725 dt_node *kid;
1727 kid = decision_tree::find_node (kids, n);
1728 if (kid)
1729 return kid;
1731 kids.safe_push (n);
1732 n->level = this->level + 1;
1734 return n;
1737 /* Append OP to the decision tree. */
1739 dt_node *
1740 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1742 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1743 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1744 return append_node (n);
1747 /* Append a DT_TRUE decision tree node. */
1749 dt_node *
1750 dt_node::append_true_op (dt_node *parent, unsigned pos)
1752 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1753 dt_operand *n = new dt_operand (DT_TRUE, 0, 0, parent_, pos);
1754 return append_node (n);
1757 /* Append a DT_MATCH decision tree node. */
1759 dt_node *
1760 dt_node::append_match_op (dt_operand *match_dop, dt_node *parent, unsigned pos)
1762 dt_operand *parent_ = as_a<dt_operand *> (parent);
1763 dt_operand *n = new dt_operand (DT_MATCH, 0, match_dop, parent_, pos);
1764 return append_node (n);
1767 /* Append S to the decision tree. */
1769 dt_node *
1770 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1771 dt_operand **indexes)
1773 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1774 for (unsigned i = 0; i < kids.length (); ++i)
1775 if (dt_simplify *s2 = dyn_cast <dt_simplify *> (kids[i]))
1777 warning_at (s->match->location, "duplicate pattern");
1778 warning_at (s2->s->match->location, "previous pattern defined here");
1779 print_operand (s->match, stderr);
1780 fprintf (stderr, "\n");
1782 return append_node (n);
1785 /* Analyze the node and its children. */
1787 void
1788 dt_node::analyze (sinfo_map_t &map)
1790 num_leafs = 0;
1791 total_size = 1;
1792 max_level = level;
1794 if (type == DT_SIMPLIFY)
1796 /* Populate the map of equivalent simplifies. */
1797 dt_simplify *s = as_a <dt_simplify *> (this);
1798 bool existed;
1799 sinfo *&si = map.get_or_insert (s, &existed);
1800 if (!existed)
1802 si = new sinfo;
1803 si->s = s;
1804 si->cnt = 1;
1805 si->fname = NULL;
1807 else
1808 si->cnt++;
1809 s->info = si;
1810 num_leafs = 1;
1811 return;
1814 for (unsigned i = 0; i < kids.length (); ++i)
1816 kids[i]->analyze (map);
1817 num_leafs += kids[i]->num_leafs;
1818 total_size += kids[i]->total_size;
1819 max_level = MAX (max_level, kids[i]->max_level);
1823 /* Insert O into the decision tree and return the decision tree node found
1824 or created. */
1826 dt_node *
1827 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1828 unsigned pos, dt_node *parent)
1830 dt_node *q, *elm = 0;
1832 if (capture *c = dyn_cast<capture *> (o))
1834 unsigned capt_index = c->where;
1836 if (indexes[capt_index] == 0)
1838 if (c->what)
1839 q = insert_operand (p, c->what, indexes, pos, parent);
1840 else
1842 q = elm = p->append_true_op (parent, pos);
1843 goto at_assert_elm;
1845 // get to the last capture
1846 for (operand *what = c->what;
1847 what && is_a<capture *> (what);
1848 c = as_a<capture *> (what), what = c->what)
1851 if (!c->what)
1853 unsigned cc_index = c->where;
1854 dt_operand *match_op = indexes[cc_index];
1856 dt_operand temp (dt_node::DT_TRUE, 0, 0);
1857 elm = decision_tree::find_node (p->kids, &temp);
1859 if (elm == 0)
1861 dt_operand temp (dt_node::DT_MATCH, 0, match_op);
1862 temp.value_match = c->value_match;
1863 elm = decision_tree::find_node (p->kids, &temp);
1866 else
1868 dt_operand temp (dt_node::DT_OPERAND, c->what, 0);
1869 elm = decision_tree::find_node (p->kids, &temp);
1872 at_assert_elm:
1873 gcc_assert (elm->type == dt_node::DT_TRUE
1874 || elm->type == dt_node::DT_OPERAND
1875 || elm->type == dt_node::DT_MATCH);
1876 indexes[capt_index] = static_cast<dt_operand *> (elm);
1877 return q;
1879 else
1881 p = p->append_match_op (indexes[capt_index], parent, pos);
1882 as_a <dt_operand *>(p)->value_match = c->value_match;
1883 if (c->what)
1884 return insert_operand (p, c->what, indexes, 0, p);
1885 else
1886 return p;
1889 p = p->append_op (o, parent, pos);
1890 q = p;
1892 if (expr *e = dyn_cast <expr *>(o))
1894 for (unsigned i = 0; i < e->ops.length (); ++i)
1895 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
1898 return q;
1901 /* Insert S into the decision tree. */
1903 void
1904 decision_tree::insert (struct simplify *s, unsigned pattern_no)
1906 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
1907 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
1908 p->append_simplify (s, pattern_no, indexes);
1911 /* Debug functions to dump the decision tree. */
1913 DEBUG_FUNCTION void
1914 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
1916 if (p->type == dt_node::DT_NODE)
1917 fprintf (f, "root");
1918 else
1920 fprintf (f, "|");
1921 for (unsigned i = 0; i < indent; i++)
1922 fprintf (f, "-");
1924 if (p->type == dt_node::DT_OPERAND)
1926 dt_operand *dop = static_cast<dt_operand *>(p);
1927 print_operand (dop->op, f, true);
1929 else if (p->type == dt_node::DT_TRUE)
1930 fprintf (f, "true");
1931 else if (p->type == dt_node::DT_MATCH)
1932 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
1933 else if (p->type == dt_node::DT_SIMPLIFY)
1935 dt_simplify *s = static_cast<dt_simplify *> (p);
1936 fprintf (f, "simplify_%u { ", s->pattern_no);
1937 for (int i = 0; i <= s->s->capture_max; ++i)
1938 fprintf (f, "%p, ", (void *) s->indexes[i]);
1939 fprintf (f, " } ");
1943 fprintf (stderr, " (%p), %u, %u\n", (void *) p, p->level, p->kids.length ());
1945 for (unsigned i = 0; i < p->kids.length (); ++i)
1946 decision_tree::print_node (p->kids[i], f, indent + 2);
1949 DEBUG_FUNCTION void
1950 decision_tree::print (FILE *f)
1952 return decision_tree::print_node (root, f);
1956 /* For GENERIC we have to take care of wrapping multiple-used
1957 expressions with side-effects in save_expr and preserve side-effects
1958 of expressions with omit_one_operand. Analyze captures in
1959 match, result and with expressions and perform early-outs
1960 on the outermost match expression operands for cases we cannot
1961 handle. */
1963 struct capture_info
1965 capture_info (simplify *s, operand *, bool);
1966 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
1967 bool walk_result (operand *o, bool, operand *);
1968 void walk_c_expr (c_expr *);
1970 struct cinfo
1972 bool expr_p;
1973 bool cse_p;
1974 bool force_no_side_effects_p;
1975 bool force_single_use;
1976 bool cond_expr_cond_p;
1977 unsigned long toplevel_msk;
1978 unsigned match_use_count;
1979 unsigned result_use_count;
1980 unsigned same_as;
1981 capture *c;
1984 auto_vec<cinfo> info;
1985 unsigned long force_no_side_effects;
1986 bool gimple;
1989 /* Analyze captures in S. */
1991 capture_info::capture_info (simplify *s, operand *result, bool gimple_)
1993 gimple = gimple_;
1995 expr *e;
1996 if (s->kind == simplify::MATCH)
1998 force_no_side_effects = -1;
1999 return;
2002 force_no_side_effects = 0;
2003 info.safe_grow_cleared (s->capture_max + 1);
2004 for (int i = 0; i <= s->capture_max; ++i)
2005 info[i].same_as = i;
2007 e = as_a <expr *> (s->match);
2008 for (unsigned i = 0; i < e->ops.length (); ++i)
2009 walk_match (e->ops[i], i,
2010 (i != 0 && *e->operation == COND_EXPR)
2011 || *e->operation == TRUTH_ANDIF_EXPR
2012 || *e->operation == TRUTH_ORIF_EXPR,
2013 i == 0
2014 && (*e->operation == COND_EXPR
2015 || *e->operation == VEC_COND_EXPR));
2017 walk_result (s->result, false, result);
2020 /* Analyze captures in the match expression piece O. */
2022 void
2023 capture_info::walk_match (operand *o, unsigned toplevel_arg,
2024 bool conditional_p, bool cond_expr_cond_p)
2026 if (capture *c = dyn_cast <capture *> (o))
2028 unsigned where = c->where;
2029 info[where].match_use_count++;
2030 info[where].toplevel_msk |= 1 << toplevel_arg;
2031 info[where].force_no_side_effects_p |= conditional_p;
2032 info[where].cond_expr_cond_p |= cond_expr_cond_p;
2033 if (!info[where].c)
2034 info[where].c = c;
2035 if (!c->what)
2036 return;
2037 /* Recurse to exprs and captures. */
2038 if (is_a <capture *> (c->what)
2039 || is_a <expr *> (c->what))
2040 walk_match (c->what, toplevel_arg, conditional_p, false);
2041 /* We need to look past multiple captures to find a captured
2042 expression as with conditional converts two captures
2043 can be collapsed onto the same expression. Also collect
2044 what captures capture the same thing. */
2045 while (c->what && is_a <capture *> (c->what))
2047 c = as_a <capture *> (c->what);
2048 if (info[c->where].same_as != c->where
2049 && info[c->where].same_as != info[where].same_as)
2050 fatal_at (c->location, "cannot handle this collapsed capture");
2051 info[c->where].same_as = info[where].same_as;
2053 /* Mark expr (non-leaf) captures and forced single-use exprs. */
2054 expr *e;
2055 if (c->what
2056 && (e = dyn_cast <expr *> (c->what)))
2058 info[where].expr_p = true;
2059 info[where].force_single_use |= e->force_single_use;
2062 else if (expr *e = dyn_cast <expr *> (o))
2064 for (unsigned i = 0; i < e->ops.length (); ++i)
2066 bool cond_p = conditional_p;
2067 bool cond_expr_cond_p = false;
2068 if (i != 0 && *e->operation == COND_EXPR)
2069 cond_p = true;
2070 else if (*e->operation == TRUTH_ANDIF_EXPR
2071 || *e->operation == TRUTH_ORIF_EXPR)
2072 cond_p = true;
2073 if (i == 0
2074 && (*e->operation == COND_EXPR
2075 || *e->operation == VEC_COND_EXPR))
2076 cond_expr_cond_p = true;
2077 walk_match (e->ops[i], toplevel_arg, cond_p, cond_expr_cond_p);
2080 else if (is_a <predicate *> (o))
2082 /* Mark non-captured leafs toplevel arg for checking. */
2083 force_no_side_effects |= 1 << toplevel_arg;
2084 if (verbose >= 1
2085 && !gimple)
2086 warning_at (o->location,
2087 "forcing no side-effects on possibly lost leaf");
2089 else
2090 gcc_unreachable ();
2093 /* Analyze captures in the result expression piece O. Return true
2094 if RESULT was visited in one of the children. Only visit
2095 non-if/with children if they are rooted on RESULT. */
2097 bool
2098 capture_info::walk_result (operand *o, bool conditional_p, operand *result)
2100 if (capture *c = dyn_cast <capture *> (o))
2102 unsigned where = info[c->where].same_as;
2103 info[where].result_use_count++;
2104 /* If we substitute an expression capture we don't know
2105 which captures this will end up using (well, we don't
2106 compute that). Force the uses to be side-effect free
2107 which means forcing the toplevels that reach the
2108 expression side-effect free. */
2109 if (info[where].expr_p)
2110 force_no_side_effects |= info[where].toplevel_msk;
2111 /* Mark CSE capture uses as forced to have no side-effects. */
2112 if (c->what
2113 && is_a <expr *> (c->what))
2115 info[where].cse_p = true;
2116 walk_result (c->what, true, result);
2119 else if (expr *e = dyn_cast <expr *> (o))
2121 id_base *opr = e->operation;
2122 if (user_id *uid = dyn_cast <user_id *> (opr))
2123 opr = uid->substitutes[0];
2124 for (unsigned i = 0; i < e->ops.length (); ++i)
2126 bool cond_p = conditional_p;
2127 if (i != 0 && *e->operation == COND_EXPR)
2128 cond_p = true;
2129 else if (*e->operation == TRUTH_ANDIF_EXPR
2130 || *e->operation == TRUTH_ORIF_EXPR)
2131 cond_p = true;
2132 walk_result (e->ops[i], cond_p, result);
2135 else if (if_expr *e = dyn_cast <if_expr *> (o))
2137 /* 'if' conditions should be all fine. */
2138 if (e->trueexpr == result)
2140 walk_result (e->trueexpr, false, result);
2141 return true;
2143 if (e->falseexpr == result)
2145 walk_result (e->falseexpr, false, result);
2146 return true;
2148 bool res = false;
2149 if (is_a <if_expr *> (e->trueexpr)
2150 || is_a <with_expr *> (e->trueexpr))
2151 res |= walk_result (e->trueexpr, false, result);
2152 if (e->falseexpr
2153 && (is_a <if_expr *> (e->falseexpr)
2154 || is_a <with_expr *> (e->falseexpr)))
2155 res |= walk_result (e->falseexpr, false, result);
2156 return res;
2158 else if (with_expr *e = dyn_cast <with_expr *> (o))
2160 bool res = (e->subexpr == result);
2161 if (res
2162 || is_a <if_expr *> (e->subexpr)
2163 || is_a <with_expr *> (e->subexpr))
2164 res |= walk_result (e->subexpr, false, result);
2165 if (res)
2166 walk_c_expr (e->with);
2167 return res;
2169 else if (c_expr *e = dyn_cast <c_expr *> (o))
2170 walk_c_expr (e);
2171 else
2172 gcc_unreachable ();
2174 return false;
2177 /* Look for captures in the C expr E. */
2179 void
2180 capture_info::walk_c_expr (c_expr *e)
2182 /* Give up for C exprs mentioning captures not inside TREE_TYPE,
2183 TREE_REAL_CST, TREE_CODE or a predicate where they cannot
2184 really escape through. */
2185 unsigned p_depth = 0;
2186 for (unsigned i = 0; i < e->code.length (); ++i)
2188 const cpp_token *t = &e->code[i];
2189 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
2190 id_base *id;
2191 if (t->type == CPP_NAME
2192 && (strcmp ((const char *)CPP_HASHNODE
2193 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
2194 || strcmp ((const char *)CPP_HASHNODE
2195 (t->val.node.node)->ident.str, "TREE_CODE") == 0
2196 || strcmp ((const char *)CPP_HASHNODE
2197 (t->val.node.node)->ident.str, "TREE_REAL_CST") == 0
2198 || ((id = get_operator ((const char *)CPP_HASHNODE
2199 (t->val.node.node)->ident.str))
2200 && is_a <predicate_id *> (id)))
2201 && n->type == CPP_OPEN_PAREN)
2202 p_depth++;
2203 else if (t->type == CPP_CLOSE_PAREN
2204 && p_depth > 0)
2205 p_depth--;
2206 else if (p_depth == 0
2207 && t->type == CPP_ATSIGN
2208 && (n->type == CPP_NUMBER
2209 || n->type == CPP_NAME)
2210 && !(n->flags & PREV_WHITE))
2212 const char *id;
2213 if (n->type == CPP_NUMBER)
2214 id = (const char *)n->val.str.text;
2215 else
2216 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2217 unsigned *where = e->capture_ids->get(id);
2218 if (! where)
2219 fatal_at (n, "unknown capture id '%s'", id);
2220 info[info[*where].same_as].force_no_side_effects_p = true;
2221 if (verbose >= 1
2222 && !gimple)
2223 warning_at (t, "capture escapes");
2229 /* Code generation off the decision tree and the refered AST nodes. */
2231 bool
2232 is_conversion (id_base *op)
2234 return (*op == CONVERT_EXPR
2235 || *op == NOP_EXPR
2236 || *op == FLOAT_EXPR
2237 || *op == FIX_TRUNC_EXPR
2238 || *op == VIEW_CONVERT_EXPR);
2241 /* Get the type to be used for generating operand POS of OP from the
2242 various sources. */
2244 static const char *
2245 get_operand_type (id_base *op, unsigned pos,
2246 const char *in_type,
2247 const char *expr_type,
2248 const char *other_oprnd_type)
2250 /* Generally operands whose type does not match the type of the
2251 expression generated need to know their types but match and
2252 thus can fall back to 'other_oprnd_type'. */
2253 if (is_conversion (op))
2254 return other_oprnd_type;
2255 else if (*op == REALPART_EXPR
2256 || *op == IMAGPART_EXPR)
2257 return other_oprnd_type;
2258 else if (is_a <operator_id *> (op)
2259 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
2260 return other_oprnd_type;
2261 else if (*op == COND_EXPR
2262 && pos == 0)
2263 return "boolean_type_node";
2264 else
2266 /* Otherwise all types should match - choose one in order of
2267 preference. */
2268 if (expr_type)
2269 return expr_type;
2270 else if (in_type)
2271 return in_type;
2272 else
2273 return other_oprnd_type;
2277 /* Generate transform code for an expression. */
2279 void
2280 expr::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2281 int depth, const char *in_type, capture_info *cinfo,
2282 dt_operand **indexes, int)
2284 id_base *opr = operation;
2285 /* When we delay operator substituting during lowering of fors we
2286 make sure that for code-gen purposes the effects of each substitute
2287 are the same. Thus just look at that. */
2288 if (user_id *uid = dyn_cast <user_id *> (opr))
2289 opr = uid->substitutes[0];
2291 bool conversion_p = is_conversion (opr);
2292 const char *type = expr_type;
2293 char optype[64];
2294 if (type)
2295 /* If there was a type specification in the pattern use it. */
2297 else if (conversion_p)
2298 /* For conversions we need to build the expression using the
2299 outer type passed in. */
2300 type = in_type;
2301 else if (*opr == REALPART_EXPR
2302 || *opr == IMAGPART_EXPR)
2304 /* __real and __imag use the component type of its operand. */
2305 sprintf (optype, "TREE_TYPE (TREE_TYPE (ops%d[0]))", depth);
2306 type = optype;
2308 else if (is_a <operator_id *> (opr)
2309 && !strcmp (as_a <operator_id *> (opr)->tcc, "tcc_comparison"))
2311 /* comparisons use boolean_type_node (or what gets in), but
2312 their operands need to figure out the types themselves. */
2313 if (in_type)
2314 type = in_type;
2315 else
2317 sprintf (optype, "boolean_type_node");
2318 type = optype;
2320 in_type = NULL;
2322 else if (*opr == COND_EXPR
2323 || *opr == VEC_COND_EXPR)
2325 /* Conditions are of the same type as their first alternative. */
2326 sprintf (optype, "TREE_TYPE (ops%d[1])", depth);
2327 type = optype;
2329 else
2331 /* Other operations are of the same type as their first operand. */
2332 sprintf (optype, "TREE_TYPE (ops%d[0])", depth);
2333 type = optype;
2335 if (!type)
2336 fatal_at (location, "cannot determine type of operand");
2338 fprintf_indent (f, indent, "{\n");
2339 indent += 2;
2340 fprintf_indent (f, indent, "tree ops%d[%u], res;\n", depth, ops.length ());
2341 char op0type[64];
2342 snprintf (op0type, 64, "TREE_TYPE (ops%d[0])", depth);
2343 for (unsigned i = 0; i < ops.length (); ++i)
2345 char dest[32];
2346 snprintf (dest, 32, "ops%d[%u]", depth, i);
2347 const char *optype
2348 = get_operand_type (opr, i, in_type, expr_type,
2349 i == 0 ? NULL : op0type);
2350 ops[i]->gen_transform (f, indent, dest, gimple, depth + 1, optype,
2351 cinfo, indexes,
2352 (*opr == COND_EXPR
2353 || *opr == VEC_COND_EXPR) && i == 0 ? 1 : 2);
2356 const char *opr_name;
2357 if (*operation == CONVERT_EXPR)
2358 opr_name = "NOP_EXPR";
2359 else
2360 opr_name = operation->id;
2362 if (gimple)
2364 if (*opr == CONVERT_EXPR)
2366 fprintf_indent (f, indent,
2367 "if (%s != TREE_TYPE (ops%d[0])\n",
2368 type, depth);
2369 fprintf_indent (f, indent,
2370 " && !useless_type_conversion_p (%s, TREE_TYPE (ops%d[0])))\n",
2371 type, depth);
2372 fprintf_indent (f, indent + 2, "{\n");
2373 indent += 4;
2375 /* ??? Building a stmt can fail for various reasons here, seq being
2376 NULL or the stmt referencing SSA names occuring in abnormal PHIs.
2377 So if we fail here we should continue matching other patterns. */
2378 fprintf_indent (f, indent, "code_helper tem_code = %s;\n", opr_name);
2379 fprintf_indent (f, indent, "tree tem_ops[3] = { ");
2380 for (unsigned i = 0; i < ops.length (); ++i)
2381 fprintf (f, "ops%d[%u]%s", depth, i,
2382 i == ops.length () - 1 ? " };\n" : ", ");
2383 fprintf_indent (f, indent,
2384 "gimple_resimplify%d (lseq, &tem_code, %s, tem_ops, valueize);\n",
2385 ops.length (), type);
2386 fprintf_indent (f, indent,
2387 "res = maybe_push_res_to_seq (tem_code, %s, tem_ops, lseq);\n",
2388 type);
2389 fprintf_indent (f, indent,
2390 "if (!res) return false;\n");
2391 if (*opr == CONVERT_EXPR)
2393 indent -= 4;
2394 fprintf_indent (f, indent, " }\n");
2395 fprintf_indent (f, indent, "else\n");
2396 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
2399 else
2401 if (*opr == CONVERT_EXPR)
2403 fprintf_indent (f, indent, "if (TREE_TYPE (ops%d[0]) != %s)\n",
2404 depth, type);
2405 indent += 2;
2407 if (opr->kind == id_base::CODE)
2408 fprintf_indent (f, indent, "res = fold_build%d_loc (loc, %s, %s",
2409 ops.length(), opr_name, type);
2410 else
2412 fprintf_indent (f, indent, "{\n");
2413 fprintf_indent (f, indent, " res = maybe_build_call_expr_loc (loc, "
2414 "%s, %s, %d", opr_name, type, ops.length());
2416 for (unsigned i = 0; i < ops.length (); ++i)
2417 fprintf (f, ", ops%d[%u]", depth, i);
2418 fprintf (f, ");\n");
2419 if (opr->kind != id_base::CODE)
2421 fprintf_indent (f, indent, " if (!res)\n");
2422 fprintf_indent (f, indent, " return NULL_TREE;\n");
2423 fprintf_indent (f, indent, "}\n");
2425 if (*opr == CONVERT_EXPR)
2427 indent -= 2;
2428 fprintf_indent (f, indent, "else\n");
2429 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
2432 fprintf_indent (f, indent, "%s = res;\n", dest);
2433 indent -= 2;
2434 fprintf_indent (f, indent, "}\n");
2437 /* Generate code for a c_expr which is either the expression inside
2438 an if statement or a sequence of statements which computes a
2439 result to be stored to DEST. */
2441 void
2442 c_expr::gen_transform (FILE *f, int indent, const char *dest,
2443 bool, int, const char *, capture_info *,
2444 dt_operand **, int)
2446 if (dest && nr_stmts == 1)
2447 fprintf_indent (f, indent, "%s = ", dest);
2449 unsigned stmt_nr = 1;
2450 for (unsigned i = 0; i < code.length (); ++i)
2452 const cpp_token *token = &code[i];
2454 /* Replace captures for code-gen. */
2455 if (token->type == CPP_ATSIGN)
2457 const cpp_token *n = &code[i+1];
2458 if ((n->type == CPP_NUMBER
2459 || n->type == CPP_NAME)
2460 && !(n->flags & PREV_WHITE))
2462 if (token->flags & PREV_WHITE)
2463 fputc (' ', f);
2464 const char *id;
2465 if (n->type == CPP_NUMBER)
2466 id = (const char *)n->val.str.text;
2467 else
2468 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2469 unsigned *cid = capture_ids->get (id);
2470 if (!cid)
2471 fatal_at (token, "unknown capture id");
2472 fprintf (f, "captures[%u]", *cid);
2473 ++i;
2474 continue;
2478 if (token->flags & PREV_WHITE)
2479 fputc (' ', f);
2481 if (token->type == CPP_NAME)
2483 const char *id = (const char *) NODE_NAME (token->val.node.node);
2484 unsigned j;
2485 for (j = 0; j < ids.length (); ++j)
2487 if (strcmp (id, ids[j].id) == 0)
2489 fprintf (f, "%s", ids[j].oper);
2490 break;
2493 if (j < ids.length ())
2494 continue;
2497 /* Output the token as string. */
2498 char *tk = (char *)cpp_token_as_text (r, token);
2499 fputs (tk, f);
2501 if (token->type == CPP_SEMICOLON)
2503 stmt_nr++;
2504 fputc ('\n', f);
2505 if (dest && stmt_nr == nr_stmts)
2506 fprintf_indent (f, indent, "%s = ", dest);
2511 /* Generate transform code for a capture. */
2513 void
2514 capture::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2515 int depth, const char *in_type, capture_info *cinfo,
2516 dt_operand **indexes, int cond_handling)
2518 if (what && is_a<expr *> (what))
2520 if (indexes[where] == 0)
2522 char buf[20];
2523 sprintf (buf, "captures[%u]", where);
2524 what->gen_transform (f, indent, buf, gimple, depth, in_type,
2525 cinfo, NULL);
2529 /* If in GENERIC some capture is used multiple times, unshare it except
2530 when emitting the last use. */
2531 if (!gimple
2532 && cinfo->info.exists ()
2533 && cinfo->info[cinfo->info[where].same_as].result_use_count > 1)
2535 fprintf_indent (f, indent, "%s = unshare_expr (captures[%u]);\n",
2536 dest, where);
2537 cinfo->info[cinfo->info[where].same_as].result_use_count--;
2539 else
2540 fprintf_indent (f, indent, "%s = captures[%u];\n", dest, where);
2542 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2543 with substituting a capture of that. */
2544 if (gimple
2545 && cond_handling != 0
2546 && cinfo->info[where].cond_expr_cond_p)
2548 /* If substituting into a cond_expr condition, unshare. */
2549 if (cond_handling == 1)
2550 fprintf_indent (f, indent, "%s = unshare_expr (%s);\n", dest, dest);
2551 /* If substituting elsewhere we might need to decompose it. */
2552 else if (cond_handling == 2)
2554 /* ??? Returning false here will also not allow any other patterns
2555 to match unless this generator was split out. */
2556 fprintf_indent (f, indent, "if (COMPARISON_CLASS_P (%s))\n", dest);
2557 fprintf_indent (f, indent, " {\n");
2558 fprintf_indent (f, indent, " if (!seq) return false;\n");
2559 fprintf_indent (f, indent, " %s = gimple_build (seq,"
2560 " TREE_CODE (%s),"
2561 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
2562 " TREE_OPERAND (%s, 1));\n",
2563 dest, dest, dest, dest, dest);
2564 fprintf_indent (f, indent, " }\n");
2569 /* Return the name of the operand representing the decision tree node.
2570 Use NAME as space to generate it. */
2572 char *
2573 dt_operand::get_name (char *name)
2575 if (!parent)
2576 sprintf (name, "t");
2577 else if (parent->level == 1)
2578 sprintf (name, "op%u", pos);
2579 else if (parent->type == dt_node::DT_MATCH)
2580 return parent->get_name (name);
2581 else
2582 sprintf (name, "o%u%u", parent->level, pos);
2583 return name;
2586 /* Fill NAME with the operand name at position POS. */
2588 void
2589 dt_operand::gen_opname (char *name, unsigned pos)
2591 if (!parent)
2592 sprintf (name, "op%u", pos);
2593 else
2594 sprintf (name, "o%u%u", level, pos);
2597 /* Generate matching code for the decision tree operand which is
2598 a predicate. */
2600 unsigned
2601 dt_operand::gen_predicate (FILE *f, int indent, const char *opname, bool gimple)
2603 predicate *p = as_a <predicate *> (op);
2605 if (p->p->matchers.exists ())
2607 /* If this is a predicate generated from a pattern mangle its
2608 name and pass on the valueize hook. */
2609 if (gimple)
2610 fprintf_indent (f, indent, "if (gimple_%s (%s, valueize))\n",
2611 p->p->id, opname);
2612 else
2613 fprintf_indent (f, indent, "if (tree_%s (%s))\n", p->p->id, opname);
2615 else
2616 fprintf_indent (f, indent, "if (%s (%s))\n", p->p->id, opname);
2617 fprintf_indent (f, indent + 2, "{\n");
2618 return 1;
2621 /* Generate matching code for the decision tree operand which is
2622 a capture-match. */
2624 unsigned
2625 dt_operand::gen_match_op (FILE *f, int indent, const char *opname, bool)
2627 char match_opname[20];
2628 match_dop->get_name (match_opname);
2629 if (value_match)
2630 fprintf_indent (f, indent, "if (%s == %s || operand_equal_p (%s, %s, 0))\n",
2631 opname, match_opname, opname, match_opname);
2632 else
2633 fprintf_indent (f, indent, "if (%s == %s || (operand_equal_p (%s, %s, 0) "
2634 "&& types_match (%s, %s)))\n",
2635 opname, match_opname, opname, match_opname,
2636 opname, match_opname);
2637 fprintf_indent (f, indent + 2, "{\n");
2638 return 1;
2641 /* Generate GIMPLE matching code for the decision tree operand. */
2643 unsigned
2644 dt_operand::gen_gimple_expr (FILE *f, int indent)
2646 expr *e = static_cast<expr *> (op);
2647 id_base *id = e->operation;
2648 unsigned n_ops = e->ops.length ();
2650 for (unsigned i = 0; i < n_ops; ++i)
2652 char child_opname[20];
2653 gen_opname (child_opname, i);
2655 if (id->kind == id_base::CODE)
2657 if (e->is_generic
2658 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2659 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
2661 /* ??? If this is a memory operation we can't (and should not)
2662 match this. The only sensible operand types are
2663 SSA names and invariants. */
2664 if (e->is_generic)
2666 char opname[20];
2667 get_name (opname);
2668 fprintf_indent (f, indent,
2669 "tree %s = TREE_OPERAND (%s, %i);\n",
2670 child_opname, opname, i);
2672 else
2673 fprintf_indent (f, indent,
2674 "tree %s = TREE_OPERAND "
2675 "(gimple_assign_rhs1 (def), %i);\n",
2676 child_opname, i);
2677 fprintf_indent (f, indent,
2678 "if ((TREE_CODE (%s) == SSA_NAME\n",
2679 child_opname);
2680 fprintf_indent (f, indent,
2681 " || is_gimple_min_invariant (%s))\n",
2682 child_opname);
2683 fprintf_indent (f, indent,
2684 " && (%s = do_valueize (valueize, %s)))\n",
2685 child_opname, child_opname);
2686 fprintf_indent (f, indent,
2687 " {\n");
2688 indent += 4;
2689 continue;
2691 else
2692 fprintf_indent (f, indent,
2693 "tree %s = gimple_assign_rhs%u (def);\n",
2694 child_opname, i + 1);
2696 else
2697 fprintf_indent (f, indent,
2698 "tree %s = gimple_call_arg (def, %u);\n",
2699 child_opname, i);
2700 fprintf_indent (f, indent,
2701 "if ((%s = do_valueize (valueize, %s)))\n",
2702 child_opname, child_opname);
2703 fprintf_indent (f, indent, " {\n");
2704 indent += 4;
2706 /* While the toplevel operands are canonicalized by the caller
2707 after valueizing operands of sub-expressions we have to
2708 re-canonicalize operand order. */
2709 if (operator_id *code = dyn_cast <operator_id *> (id))
2711 /* ??? We can't canonicalize tcc_comparison operands here
2712 because that requires changing the comparison code which
2713 we already matched... */
2714 if (commutative_tree_code (code->code)
2715 || commutative_ternary_tree_code (code->code))
2717 char child_opname0[20], child_opname1[20];
2718 gen_opname (child_opname0, 0);
2719 gen_opname (child_opname1, 1);
2720 fprintf_indent (f, indent,
2721 "if (tree_swap_operands_p (%s, %s))\n",
2722 child_opname0, child_opname1);
2723 fprintf_indent (f, indent,
2724 " std::swap (%s, %s);\n",
2725 child_opname0, child_opname1);
2729 return n_ops;
2732 /* Generate GENERIC matching code for the decision tree operand. */
2734 unsigned
2735 dt_operand::gen_generic_expr (FILE *f, int indent, const char *opname)
2737 expr *e = static_cast<expr *> (op);
2738 unsigned n_ops = e->ops.length ();
2740 for (unsigned i = 0; i < n_ops; ++i)
2742 char child_opname[20];
2743 gen_opname (child_opname, i);
2745 if (e->operation->kind == id_base::CODE)
2746 fprintf_indent (f, indent, "tree %s = TREE_OPERAND (%s, %u);\n",
2747 child_opname, opname, i);
2748 else
2749 fprintf_indent (f, indent, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
2750 child_opname, opname, i);
2753 return 0;
2756 /* Generate matching code for the children of the decision tree node. */
2758 void
2759 dt_node::gen_kids (FILE *f, int indent, bool gimple)
2761 auto_vec<dt_operand *> gimple_exprs;
2762 auto_vec<dt_operand *> generic_exprs;
2763 auto_vec<dt_operand *> fns;
2764 auto_vec<dt_operand *> generic_fns;
2765 auto_vec<dt_operand *> preds;
2766 auto_vec<dt_node *> others;
2768 for (unsigned i = 0; i < kids.length (); ++i)
2770 if (kids[i]->type == dt_node::DT_OPERAND)
2772 dt_operand *op = as_a<dt_operand *> (kids[i]);
2773 if (expr *e = dyn_cast <expr *> (op->op))
2775 if (e->ops.length () == 0
2776 && (!gimple || !(*e->operation == CONSTRUCTOR)))
2777 generic_exprs.safe_push (op);
2778 else if (e->operation->kind == id_base::FN)
2780 if (gimple)
2781 fns.safe_push (op);
2782 else
2783 generic_fns.safe_push (op);
2785 else if (e->operation->kind == id_base::PREDICATE)
2786 preds.safe_push (op);
2787 else
2789 if (gimple && !e->is_generic)
2790 gimple_exprs.safe_push (op);
2791 else
2792 generic_exprs.safe_push (op);
2795 else if (op->op->type == operand::OP_PREDICATE)
2796 others.safe_push (kids[i]);
2797 else
2798 gcc_unreachable ();
2800 else if (kids[i]->type == dt_node::DT_SIMPLIFY)
2801 others.safe_push (kids[i]);
2802 else if (kids[i]->type == dt_node::DT_MATCH
2803 || kids[i]->type == dt_node::DT_TRUE)
2805 /* A DT_TRUE operand serves as a barrier - generate code now
2806 for what we have collected sofar.
2807 Like DT_TRUE, DT_MATCH serves as a barrier as it can cause
2808 dependent matches to get out-of-order. Generate code now
2809 for what we have collected sofar. */
2810 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2811 fns, generic_fns, preds, others);
2812 /* And output the true operand itself. */
2813 kids[i]->gen (f, indent, gimple);
2814 gimple_exprs.truncate (0);
2815 generic_exprs.truncate (0);
2816 fns.truncate (0);
2817 generic_fns.truncate (0);
2818 preds.truncate (0);
2819 others.truncate (0);
2821 else
2822 gcc_unreachable ();
2825 /* Generate code for the remains. */
2826 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2827 fns, generic_fns, preds, others);
2830 /* Generate matching code for the children of the decision tree node. */
2832 void
2833 dt_node::gen_kids_1 (FILE *f, int indent, bool gimple,
2834 vec<dt_operand *> gimple_exprs,
2835 vec<dt_operand *> generic_exprs,
2836 vec<dt_operand *> fns,
2837 vec<dt_operand *> generic_fns,
2838 vec<dt_operand *> preds,
2839 vec<dt_node *> others)
2841 char buf[128];
2842 char *kid_opname = buf;
2844 unsigned exprs_len = gimple_exprs.length ();
2845 unsigned gexprs_len = generic_exprs.length ();
2846 unsigned fns_len = fns.length ();
2847 unsigned gfns_len = generic_fns.length ();
2849 if (exprs_len || fns_len || gexprs_len || gfns_len)
2851 if (exprs_len)
2852 gimple_exprs[0]->get_name (kid_opname);
2853 else if (fns_len)
2854 fns[0]->get_name (kid_opname);
2855 else if (gfns_len)
2856 generic_fns[0]->get_name (kid_opname);
2857 else
2858 generic_exprs[0]->get_name (kid_opname);
2860 fprintf_indent (f, indent, "switch (TREE_CODE (%s))\n", kid_opname);
2861 fprintf_indent (f, indent, " {\n");
2862 indent += 2;
2865 if (exprs_len || fns_len)
2867 fprintf_indent (f, indent,
2868 "case SSA_NAME:\n");
2869 fprintf_indent (f, indent,
2870 " if (do_valueize (valueize, %s) != NULL_TREE)\n",
2871 kid_opname);
2872 fprintf_indent (f, indent,
2873 " {\n");
2874 fprintf_indent (f, indent,
2875 " gimple *def_stmt = SSA_NAME_DEF_STMT (%s);\n",
2876 kid_opname);
2878 indent += 6;
2879 if (exprs_len)
2881 fprintf_indent (f, indent,
2882 "if (gassign *def = dyn_cast <gassign *> (def_stmt))\n");
2883 fprintf_indent (f, indent,
2884 " switch (gimple_assign_rhs_code (def))\n");
2885 indent += 4;
2886 fprintf_indent (f, indent, "{\n");
2887 for (unsigned i = 0; i < exprs_len; ++i)
2889 expr *e = as_a <expr *> (gimple_exprs[i]->op);
2890 id_base *op = e->operation;
2891 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2892 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2893 else
2894 fprintf_indent (f, indent, "case %s:\n", op->id);
2895 fprintf_indent (f, indent, " {\n");
2896 gimple_exprs[i]->gen (f, indent + 4, true);
2897 fprintf_indent (f, indent, " break;\n");
2898 fprintf_indent (f, indent, " }\n");
2900 fprintf_indent (f, indent, "default:;\n");
2901 fprintf_indent (f, indent, "}\n");
2902 indent -= 4;
2905 if (fns_len)
2907 fprintf_indent (f, indent,
2908 "%sif (gcall *def = dyn_cast <gcall *>"
2909 " (def_stmt))\n",
2910 exprs_len ? "else " : "");
2911 fprintf_indent (f, indent,
2912 " switch (gimple_call_combined_fn (def))\n");
2914 indent += 4;
2915 fprintf_indent (f, indent, "{\n");
2916 for (unsigned i = 0; i < fns_len; ++i)
2918 expr *e = as_a <expr *>(fns[i]->op);
2919 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2920 fprintf_indent (f, indent, " {\n");
2921 fns[i]->gen (f, indent + 4, true);
2922 fprintf_indent (f, indent, " break;\n");
2923 fprintf_indent (f, indent, " }\n");
2926 fprintf_indent (f, indent, "default:;\n");
2927 fprintf_indent (f, indent, "}\n");
2928 indent -= 4;
2931 indent -= 6;
2932 fprintf_indent (f, indent, " }\n");
2933 /* See if there is SSA_NAME among generic_exprs and if yes, emit it
2934 here rather than in the next loop. */
2935 for (unsigned i = 0; i < generic_exprs.length (); ++i)
2937 expr *e = as_a <expr *>(generic_exprs[i]->op);
2938 id_base *op = e->operation;
2939 if (*op == SSA_NAME && (exprs_len || fns_len))
2941 fprintf_indent (f, indent + 4, "{\n");
2942 generic_exprs[i]->gen (f, indent + 6, gimple);
2943 fprintf_indent (f, indent + 4, "}\n");
2947 fprintf_indent (f, indent, " break;\n");
2950 for (unsigned i = 0; i < generic_exprs.length (); ++i)
2952 expr *e = as_a <expr *>(generic_exprs[i]->op);
2953 id_base *op = e->operation;
2954 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2955 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2956 else if (*op == SSA_NAME && (exprs_len || fns_len))
2957 /* Already handled above. */
2958 continue;
2959 else
2960 fprintf_indent (f, indent, "case %s:\n", op->id);
2961 fprintf_indent (f, indent, " {\n");
2962 generic_exprs[i]->gen (f, indent + 4, gimple);
2963 fprintf_indent (f, indent, " break;\n");
2964 fprintf_indent (f, indent, " }\n");
2967 if (gfns_len)
2969 fprintf_indent (f, indent,
2970 "case CALL_EXPR:\n");
2971 fprintf_indent (f, indent,
2972 " switch (get_call_combined_fn (%s))\n",
2973 kid_opname);
2974 fprintf_indent (f, indent,
2975 " {\n");
2976 indent += 4;
2978 for (unsigned j = 0; j < generic_fns.length (); ++j)
2980 expr *e = as_a <expr *>(generic_fns[j]->op);
2981 gcc_assert (e->operation->kind == id_base::FN);
2983 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2984 fprintf_indent (f, indent, " {\n");
2985 generic_fns[j]->gen (f, indent + 4, false);
2986 fprintf_indent (f, indent, " break;\n");
2987 fprintf_indent (f, indent, " }\n");
2989 fprintf_indent (f, indent, "default:;\n");
2991 indent -= 4;
2992 fprintf_indent (f, indent, " }\n");
2993 fprintf_indent (f, indent, " break;\n");
2996 /* Close switch (TREE_CODE ()). */
2997 if (exprs_len || fns_len || gexprs_len || gfns_len)
2999 indent -= 4;
3000 fprintf_indent (f, indent, " default:;\n");
3001 fprintf_indent (f, indent, " }\n");
3004 for (unsigned i = 0; i < preds.length (); ++i)
3006 expr *e = as_a <expr *> (preds[i]->op);
3007 predicate_id *p = as_a <predicate_id *> (e->operation);
3008 preds[i]->get_name (kid_opname);
3009 fprintf_indent (f, indent, "{\n");
3010 indent += 2;
3011 fprintf_indent (f, indent, "tree %s_pops[%d];\n", kid_opname, p->nargs);
3012 fprintf_indent (f, indent, "if (%s_%s (%s, %s_pops%s))\n",
3013 gimple ? "gimple" : "tree",
3014 p->id, kid_opname, kid_opname,
3015 gimple ? ", valueize" : "");
3016 fprintf_indent (f, indent, " {\n");
3017 for (int j = 0; j < p->nargs; ++j)
3019 char child_opname[20];
3020 preds[i]->gen_opname (child_opname, j);
3021 fprintf_indent (f, indent + 4, "tree %s = %s_pops[%d];\n",
3022 child_opname, kid_opname, j);
3024 preds[i]->gen_kids (f, indent + 4, gimple);
3025 fprintf (f, "}\n");
3026 indent -= 2;
3027 fprintf_indent (f, indent, "}\n");
3030 for (unsigned i = 0; i < others.length (); ++i)
3031 others[i]->gen (f, indent, gimple);
3034 /* Generate matching code for the decision tree operand. */
3036 void
3037 dt_operand::gen (FILE *f, int indent, bool gimple)
3039 char opname[20];
3040 get_name (opname);
3042 unsigned n_braces = 0;
3044 if (type == DT_OPERAND)
3045 switch (op->type)
3047 case operand::OP_PREDICATE:
3048 n_braces = gen_predicate (f, indent, opname, gimple);
3049 break;
3051 case operand::OP_EXPR:
3052 if (gimple)
3053 n_braces = gen_gimple_expr (f, indent);
3054 else
3055 n_braces = gen_generic_expr (f, indent, opname);
3056 break;
3058 default:
3059 gcc_unreachable ();
3061 else if (type == DT_TRUE)
3063 else if (type == DT_MATCH)
3064 n_braces = gen_match_op (f, indent, opname, gimple);
3065 else
3066 gcc_unreachable ();
3068 indent += 4 * n_braces;
3069 gen_kids (f, indent, gimple);
3071 for (unsigned i = 0; i < n_braces; ++i)
3073 indent -= 4;
3074 if (indent < 0)
3075 indent = 0;
3076 fprintf_indent (f, indent, " }\n");
3081 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3082 step of a '(simplify ...)' or '(match ...)'. This handles everything
3083 that is not part of the decision tree (simplify->match).
3084 Main recursive worker. */
3086 void
3087 dt_simplify::gen_1 (FILE *f, int indent, bool gimple, operand *result)
3089 if (result)
3091 if (with_expr *w = dyn_cast <with_expr *> (result))
3093 fprintf_indent (f, indent, "{\n");
3094 indent += 4;
3095 output_line_directive (f, w->location);
3096 w->with->gen_transform (f, indent, NULL, true, 1, "type", NULL);
3097 gen_1 (f, indent, gimple, w->subexpr);
3098 indent -= 4;
3099 fprintf_indent (f, indent, "}\n");
3100 return;
3102 else if (if_expr *ife = dyn_cast <if_expr *> (result))
3104 output_line_directive (f, ife->location);
3105 fprintf_indent (f, indent, "if (");
3106 ife->cond->gen_transform (f, indent, NULL, true, 1, "type", NULL);
3107 fprintf (f, ")\n");
3108 fprintf_indent (f, indent + 2, "{\n");
3109 indent += 4;
3110 gen_1 (f, indent, gimple, ife->trueexpr);
3111 indent -= 4;
3112 fprintf_indent (f, indent + 2, "}\n");
3113 if (ife->falseexpr)
3115 fprintf_indent (f, indent, "else\n");
3116 fprintf_indent (f, indent + 2, "{\n");
3117 indent += 4;
3118 gen_1 (f, indent, gimple, ife->falseexpr);
3119 indent -= 4;
3120 fprintf_indent (f, indent + 2, "}\n");
3122 return;
3126 /* Analyze captures and perform early-outs on the incoming arguments
3127 that cover cases we cannot handle. */
3128 capture_info cinfo (s, result, gimple);
3129 if (s->kind == simplify::SIMPLIFY)
3131 if (!gimple)
3133 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3134 if (cinfo.force_no_side_effects & (1 << i))
3136 fprintf_indent (f, indent,
3137 "if (TREE_SIDE_EFFECTS (op%d)) return NULL_TREE;\n",
3139 if (verbose >= 1)
3140 warning_at (as_a <expr *> (s->match)->ops[i]->location,
3141 "forcing toplevel operand to have no "
3142 "side-effects");
3144 for (int i = 0; i <= s->capture_max; ++i)
3145 if (cinfo.info[i].cse_p)
3147 else if (cinfo.info[i].force_no_side_effects_p
3148 && (cinfo.info[i].toplevel_msk
3149 & cinfo.force_no_side_effects) == 0)
3151 fprintf_indent (f, indent,
3152 "if (TREE_SIDE_EFFECTS (captures[%d])) "
3153 "return NULL_TREE;\n", i);
3154 if (verbose >= 1)
3155 warning_at (cinfo.info[i].c->location,
3156 "forcing captured operand to have no "
3157 "side-effects");
3159 else if ((cinfo.info[i].toplevel_msk
3160 & cinfo.force_no_side_effects) != 0)
3161 /* Mark capture as having no side-effects if we had to verify
3162 that via forced toplevel operand checks. */
3163 cinfo.info[i].force_no_side_effects_p = true;
3165 if (gimple)
3167 /* Force single-use restriction by only allowing simple
3168 results via setting seq to NULL. */
3169 fprintf_indent (f, indent, "gimple_seq *lseq = seq;\n");
3170 bool first_p = true;
3171 for (int i = 0; i <= s->capture_max; ++i)
3172 if (cinfo.info[i].force_single_use)
3174 if (first_p)
3176 fprintf_indent (f, indent, "if (lseq\n");
3177 fprintf_indent (f, indent, " && (");
3178 first_p = false;
3180 else
3182 fprintf (f, "\n");
3183 fprintf_indent (f, indent, " || ");
3185 fprintf (f, "!single_use (captures[%d])", i);
3187 if (!first_p)
3189 fprintf (f, "))\n");
3190 fprintf_indent (f, indent, " lseq = NULL;\n");
3195 fprintf_indent (f, indent, "if (dump_file && (dump_flags & TDF_FOLDING)) "
3196 "fprintf (dump_file, \"Applying pattern ");
3197 output_line_directive (f,
3198 result ? result->location : s->match->location, true);
3199 fprintf (f, ", %%s:%%d\\n\", __FILE__, __LINE__);\n");
3201 if (!result)
3203 /* If there is no result then this is a predicate implementation. */
3204 fprintf_indent (f, indent, "return true;\n");
3206 else if (gimple)
3208 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
3209 in outermost position). */
3210 if (result->type == operand::OP_EXPR
3211 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
3212 result = as_a <expr *> (result)->ops[0];
3213 if (result->type == operand::OP_EXPR)
3215 expr *e = as_a <expr *> (result);
3216 id_base *opr = e->operation;
3217 bool is_predicate = false;
3218 /* When we delay operator substituting during lowering of fors we
3219 make sure that for code-gen purposes the effects of each substitute
3220 are the same. Thus just look at that. */
3221 if (user_id *uid = dyn_cast <user_id *> (opr))
3222 opr = uid->substitutes[0];
3223 else if (is_a <predicate_id *> (opr))
3224 is_predicate = true;
3225 if (!is_predicate)
3226 fprintf_indent (f, indent, "*res_code = %s;\n",
3227 *e->operation == CONVERT_EXPR
3228 ? "NOP_EXPR" : e->operation->id);
3229 for (unsigned j = 0; j < e->ops.length (); ++j)
3231 char dest[32];
3232 snprintf (dest, 32, "res_ops[%d]", j);
3233 const char *optype
3234 = get_operand_type (opr, j,
3235 "type", e->expr_type,
3236 j == 0 ? NULL : "TREE_TYPE (res_ops[0])");
3237 /* We need to expand GENERIC conditions we captured from
3238 COND_EXPRs and we need to unshare them when substituting
3239 into COND_EXPRs. */
3240 int cond_handling = 0;
3241 if (!is_predicate)
3242 cond_handling = ((*opr == COND_EXPR
3243 || *opr == VEC_COND_EXPR) && j == 0) ? 1 : 2;
3244 e->ops[j]->gen_transform (f, indent, dest, true, 1, optype,
3245 &cinfo, indexes, cond_handling);
3248 /* Re-fold the toplevel result. It's basically an embedded
3249 gimple_build w/o actually building the stmt. */
3250 if (!is_predicate)
3251 fprintf_indent (f, indent,
3252 "gimple_resimplify%d (lseq, res_code, type, "
3253 "res_ops, valueize);\n", e->ops.length ());
3255 else if (result->type == operand::OP_CAPTURE
3256 || result->type == operand::OP_C_EXPR)
3258 result->gen_transform (f, indent, "res_ops[0]", true, 1, "type",
3259 &cinfo, indexes);
3260 fprintf_indent (f, indent, "*res_code = TREE_CODE (res_ops[0]);\n");
3261 if (is_a <capture *> (result)
3262 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
3264 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
3265 with substituting a capture of that. */
3266 fprintf_indent (f, indent,
3267 "if (COMPARISON_CLASS_P (res_ops[0]))\n");
3268 fprintf_indent (f, indent,
3269 " {\n");
3270 fprintf_indent (f, indent,
3271 " tree tem = res_ops[0];\n");
3272 fprintf_indent (f, indent,
3273 " res_ops[0] = TREE_OPERAND (tem, 0);\n");
3274 fprintf_indent (f, indent,
3275 " res_ops[1] = TREE_OPERAND (tem, 1);\n");
3276 fprintf_indent (f, indent,
3277 " }\n");
3280 else
3281 gcc_unreachable ();
3282 fprintf_indent (f, indent, "return true;\n");
3284 else /* GENERIC */
3286 bool is_predicate = false;
3287 if (result->type == operand::OP_EXPR)
3289 expr *e = as_a <expr *> (result);
3290 id_base *opr = e->operation;
3291 /* When we delay operator substituting during lowering of fors we
3292 make sure that for code-gen purposes the effects of each substitute
3293 are the same. Thus just look at that. */
3294 if (user_id *uid = dyn_cast <user_id *> (opr))
3295 opr = uid->substitutes[0];
3296 else if (is_a <predicate_id *> (opr))
3297 is_predicate = true;
3298 /* Search for captures used multiple times in the result expression
3299 and wrap them in a SAVE_EXPR. Allow as many uses as in the
3300 original expression. */
3301 if (!is_predicate)
3302 for (int i = 0; i < s->capture_max + 1; ++i)
3304 if (cinfo.info[i].same_as != (unsigned)i
3305 || cinfo.info[i].cse_p)
3306 continue;
3307 if (cinfo.info[i].result_use_count
3308 > cinfo.info[i].match_use_count)
3309 fprintf_indent (f, indent,
3310 "if (! tree_invariant_p (captures[%d])) "
3311 "return NULL_TREE;\n", i);
3313 for (unsigned j = 0; j < e->ops.length (); ++j)
3315 char dest[32];
3316 if (is_predicate)
3317 snprintf (dest, 32, "res_ops[%d]", j);
3318 else
3320 fprintf_indent (f, indent, "tree res_op%d;\n", j);
3321 snprintf (dest, 32, "res_op%d", j);
3323 const char *optype
3324 = get_operand_type (opr, j,
3325 "type", e->expr_type,
3326 j == 0
3327 ? NULL : "TREE_TYPE (res_op0)");
3328 e->ops[j]->gen_transform (f, indent, dest, false, 1, optype,
3329 &cinfo, indexes);
3331 if (is_predicate)
3332 fprintf_indent (f, indent, "return true;\n");
3333 else
3335 fprintf_indent (f, indent, "tree res;\n");
3336 /* Re-fold the toplevel result. Use non_lvalue to
3337 build NON_LVALUE_EXPRs so they get properly
3338 ignored when in GIMPLE form. */
3339 if (*opr == NON_LVALUE_EXPR)
3340 fprintf_indent (f, indent,
3341 "res = non_lvalue_loc (loc, res_op0);\n");
3342 else
3344 if (is_a <operator_id *> (opr))
3345 fprintf_indent (f, indent,
3346 "res = fold_build%d_loc (loc, %s, type",
3347 e->ops.length (),
3348 *e->operation == CONVERT_EXPR
3349 ? "NOP_EXPR" : e->operation->id);
3350 else
3351 fprintf_indent (f, indent,
3352 "res = maybe_build_call_expr_loc (loc, "
3353 "%s, type, %d", e->operation->id,
3354 e->ops.length());
3355 for (unsigned j = 0; j < e->ops.length (); ++j)
3356 fprintf (f, ", res_op%d", j);
3357 fprintf (f, ");\n");
3358 if (!is_a <operator_id *> (opr))
3360 fprintf_indent (f, indent, "if (!res)\n");
3361 fprintf_indent (f, indent, " return NULL_TREE;\n");
3366 else if (result->type == operand::OP_CAPTURE
3367 || result->type == operand::OP_C_EXPR)
3370 fprintf_indent (f, indent, "tree res;\n");
3371 result->gen_transform (f, indent, "res", false, 1, "type",
3372 &cinfo, indexes);
3374 else
3375 gcc_unreachable ();
3376 if (!is_predicate)
3378 /* Search for captures not used in the result expression and dependent
3379 on TREE_SIDE_EFFECTS emit omit_one_operand. */
3380 for (int i = 0; i < s->capture_max + 1; ++i)
3382 if (cinfo.info[i].same_as != (unsigned)i)
3383 continue;
3384 if (!cinfo.info[i].force_no_side_effects_p
3385 && !cinfo.info[i].expr_p
3386 && cinfo.info[i].result_use_count == 0)
3388 fprintf_indent (f, indent,
3389 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
3391 fprintf_indent (f, indent + 2,
3392 "res = build2_loc (loc, COMPOUND_EXPR, type, "
3393 "fold_ignored_result (captures[%d]), res);\n",
3397 fprintf_indent (f, indent, "return res;\n");
3402 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3403 step of a '(simplify ...)' or '(match ...)'. This handles everything
3404 that is not part of the decision tree (simplify->match). */
3406 void
3407 dt_simplify::gen (FILE *f, int indent, bool gimple)
3409 fprintf_indent (f, indent, "{\n");
3410 indent += 2;
3411 output_line_directive (f,
3412 s->result ? s->result->location : s->match->location);
3413 if (s->capture_max >= 0)
3415 char opname[20];
3416 fprintf_indent (f, indent, "tree captures[%u] ATTRIBUTE_UNUSED = { %s",
3417 s->capture_max + 1, indexes[0]->get_name (opname));
3419 for (int i = 1; i <= s->capture_max; ++i)
3421 if (!indexes[i])
3422 break;
3423 fprintf (f, ", %s", indexes[i]->get_name (opname));
3425 fprintf (f, " };\n");
3428 /* If we have a split-out function for the actual transform, call it. */
3429 if (info && info->fname)
3431 if (gimple)
3433 fprintf_indent (f, indent, "if (%s (res_code, res_ops, seq, "
3434 "valueize, type, captures", info->fname);
3435 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3436 if (s->for_subst_vec[i].first->used)
3437 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3438 fprintf (f, "))\n");
3439 fprintf_indent (f, indent, " return true;\n");
3441 else
3443 fprintf_indent (f, indent, "tree res = %s (loc, type",
3444 info->fname);
3445 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3446 fprintf (f, ", op%d", i);
3447 fprintf (f, ", captures");
3448 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3450 if (s->for_subst_vec[i].first->used)
3451 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3453 fprintf (f, ");\n");
3454 fprintf_indent (f, indent, "if (res) return res;\n");
3457 else
3459 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3461 if (! s->for_subst_vec[i].first->used)
3462 continue;
3463 if (is_a <operator_id *> (s->for_subst_vec[i].second))
3464 fprintf_indent (f, indent, "enum tree_code %s = %s;\n",
3465 s->for_subst_vec[i].first->id,
3466 s->for_subst_vec[i].second->id);
3467 else if (is_a <fn_id *> (s->for_subst_vec[i].second))
3468 fprintf_indent (f, indent, "combined_fn %s = %s;\n",
3469 s->for_subst_vec[i].first->id,
3470 s->for_subst_vec[i].second->id);
3471 else
3472 gcc_unreachable ();
3474 gen_1 (f, indent, gimple, s->result);
3477 indent -= 2;
3478 fprintf_indent (f, indent, "}\n");
3482 /* Hash function for finding equivalent transforms. */
3484 hashval_t
3485 sinfo_hashmap_traits::hash (const key_type &v)
3487 /* Only bother to compare those originating from the same source pattern. */
3488 return v->s->result->location;
3491 /* Compare function for finding equivalent transforms. */
3493 static bool
3494 compare_op (operand *o1, simplify *s1, operand *o2, simplify *s2)
3496 if (o1->type != o2->type)
3497 return false;
3499 switch (o1->type)
3501 case operand::OP_IF:
3503 if_expr *if1 = as_a <if_expr *> (o1);
3504 if_expr *if2 = as_a <if_expr *> (o2);
3505 /* ??? Properly compare c-exprs. */
3506 if (if1->cond != if2->cond)
3507 return false;
3508 if (!compare_op (if1->trueexpr, s1, if2->trueexpr, s2))
3509 return false;
3510 if (if1->falseexpr != if2->falseexpr
3511 || (if1->falseexpr
3512 && !compare_op (if1->falseexpr, s1, if2->falseexpr, s2)))
3513 return false;
3514 return true;
3516 case operand::OP_WITH:
3518 with_expr *with1 = as_a <with_expr *> (o1);
3519 with_expr *with2 = as_a <with_expr *> (o2);
3520 if (with1->with != with2->with)
3521 return false;
3522 return compare_op (with1->subexpr, s1, with2->subexpr, s2);
3524 default:;
3527 /* We've hit a result. Time to compare capture-infos - this is required
3528 in addition to the conservative pointer-equivalency of the result IL. */
3529 capture_info cinfo1 (s1, o1, true);
3530 capture_info cinfo2 (s2, o2, true);
3532 if (cinfo1.force_no_side_effects != cinfo2.force_no_side_effects
3533 || cinfo1.info.length () != cinfo2.info.length ())
3534 return false;
3536 for (unsigned i = 0; i < cinfo1.info.length (); ++i)
3538 if (cinfo1.info[i].expr_p != cinfo2.info[i].expr_p
3539 || cinfo1.info[i].cse_p != cinfo2.info[i].cse_p
3540 || (cinfo1.info[i].force_no_side_effects_p
3541 != cinfo2.info[i].force_no_side_effects_p)
3542 || cinfo1.info[i].force_single_use != cinfo2.info[i].force_single_use
3543 || cinfo1.info[i].cond_expr_cond_p != cinfo2.info[i].cond_expr_cond_p
3544 /* toplevel_msk is an optimization */
3545 || cinfo1.info[i].result_use_count != cinfo2.info[i].result_use_count
3546 || cinfo1.info[i].same_as != cinfo2.info[i].same_as
3547 /* the pointer back to the capture is for diagnostics only */)
3548 return false;
3551 /* ??? Deep-compare the actual result. */
3552 return o1 == o2;
3555 bool
3556 sinfo_hashmap_traits::equal_keys (const key_type &v,
3557 const key_type &candidate)
3559 return compare_op (v->s->result, v->s, candidate->s->result, candidate->s);
3563 /* Main entry to generate code for matching GIMPLE IL off the decision
3564 tree. */
3566 void
3567 decision_tree::gen (FILE *f, bool gimple)
3569 sinfo_map_t si;
3571 root->analyze (si);
3573 fprintf (stderr, "%s decision tree has %u leafs, maximum depth %u and "
3574 "a total number of %u nodes\n",
3575 gimple ? "GIMPLE" : "GENERIC",
3576 root->num_leafs, root->max_level, root->total_size);
3578 /* First split out the transform part of equal leafs. */
3579 unsigned rcnt = 0;
3580 unsigned fcnt = 1;
3581 for (sinfo_map_t::iterator iter = si.begin ();
3582 iter != si.end (); ++iter)
3584 sinfo *s = (*iter).second;
3585 /* Do not split out single uses. */
3586 if (s->cnt <= 1)
3587 continue;
3589 rcnt += s->cnt - 1;
3590 if (verbose >= 1)
3592 fprintf (stderr, "found %u uses of", s->cnt);
3593 output_line_directive (stderr, s->s->s->result->location);
3596 /* Generate a split out function with the leaf transform code. */
3597 s->fname = xasprintf ("%s_simplify_%u", gimple ? "gimple" : "generic",
3598 fcnt++);
3599 if (gimple)
3600 fprintf (f, "\nstatic bool\n"
3601 "%s (code_helper *res_code, tree *res_ops,\n"
3602 " gimple_seq *seq, tree (*valueize)(tree) "
3603 "ATTRIBUTE_UNUSED,\n"
3604 " tree ARG_UNUSED (type), tree *ARG_UNUSED "
3605 "(captures)\n",
3606 s->fname);
3607 else
3609 fprintf (f, "\nstatic tree\n"
3610 "%s (location_t ARG_UNUSED (loc), tree ARG_UNUSED (type),\n",
3611 (*iter).second->fname);
3612 for (unsigned i = 0;
3613 i < as_a <expr *>(s->s->s->match)->ops.length (); ++i)
3614 fprintf (f, " tree ARG_UNUSED (op%d),", i);
3615 fprintf (f, " tree *captures\n");
3617 for (unsigned i = 0; i < s->s->s->for_subst_vec.length (); ++i)
3619 if (! s->s->s->for_subst_vec[i].first->used)
3620 continue;
3621 if (is_a <operator_id *> (s->s->s->for_subst_vec[i].second))
3622 fprintf (f, ", enum tree_code ARG_UNUSED (%s)",
3623 s->s->s->for_subst_vec[i].first->id);
3624 else if (is_a <fn_id *> (s->s->s->for_subst_vec[i].second))
3625 fprintf (f, ", combined_fn ARG_UNUSED (%s)",
3626 s->s->s->for_subst_vec[i].first->id);
3629 fprintf (f, ")\n{\n");
3630 s->s->gen_1 (f, 2, gimple, s->s->s->result);
3631 if (gimple)
3632 fprintf (f, " return false;\n");
3633 else
3634 fprintf (f, " return NULL_TREE;\n");
3635 fprintf (f, "}\n");
3637 fprintf (stderr, "removed %u duplicate tails\n", rcnt);
3639 for (unsigned n = 1; n <= 3; ++n)
3641 /* First generate split-out functions. */
3642 for (unsigned i = 0; i < root->kids.length (); i++)
3644 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3645 expr *e = static_cast<expr *>(dop->op);
3646 if (e->ops.length () != n
3647 /* Builtin simplifications are somewhat premature on
3648 GENERIC. The following drops patterns with outermost
3649 calls. It's easy to emit overloads for function code
3650 though if necessary. */
3651 || (!gimple
3652 && e->operation->kind != id_base::CODE))
3653 continue;
3655 if (gimple)
3656 fprintf (f, "\nstatic bool\n"
3657 "gimple_simplify_%s (code_helper *res_code, tree *res_ops,\n"
3658 " gimple_seq *seq, tree (*valueize)(tree) "
3659 "ATTRIBUTE_UNUSED,\n"
3660 " code_helper ARG_UNUSED (code), tree "
3661 "ARG_UNUSED (type)\n",
3662 e->operation->id);
3663 else
3664 fprintf (f, "\nstatic tree\n"
3665 "generic_simplify_%s (location_t ARG_UNUSED (loc), enum "
3666 "tree_code ARG_UNUSED (code), tree ARG_UNUSED (type)",
3667 e->operation->id);
3668 for (unsigned i = 0; i < n; ++i)
3669 fprintf (f, ", tree op%d", i);
3670 fprintf (f, ")\n");
3671 fprintf (f, "{\n");
3672 dop->gen_kids (f, 2, gimple);
3673 if (gimple)
3674 fprintf (f, " return false;\n");
3675 else
3676 fprintf (f, " return NULL_TREE;\n");
3677 fprintf (f, "}\n");
3680 /* Then generate the main entry with the outermost switch and
3681 tail-calls to the split-out functions. */
3682 if (gimple)
3683 fprintf (f, "\nstatic bool\n"
3684 "gimple_simplify (code_helper *res_code, tree *res_ops,\n"
3685 " gimple_seq *seq, tree (*valueize)(tree),\n"
3686 " code_helper code, tree type");
3687 else
3688 fprintf (f, "\ntree\n"
3689 "generic_simplify (location_t loc, enum tree_code code, "
3690 "tree type ATTRIBUTE_UNUSED");
3691 for (unsigned i = 0; i < n; ++i)
3692 fprintf (f, ", tree op%d", i);
3693 fprintf (f, ")\n");
3694 fprintf (f, "{\n");
3696 if (gimple)
3697 fprintf (f, " switch (code.get_rep())\n"
3698 " {\n");
3699 else
3700 fprintf (f, " switch (code)\n"
3701 " {\n");
3702 for (unsigned i = 0; i < root->kids.length (); i++)
3704 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3705 expr *e = static_cast<expr *>(dop->op);
3706 if (e->ops.length () != n
3707 /* Builtin simplifications are somewhat premature on
3708 GENERIC. The following drops patterns with outermost
3709 calls. It's easy to emit overloads for function code
3710 though if necessary. */
3711 || (!gimple
3712 && e->operation->kind != id_base::CODE))
3713 continue;
3715 if (*e->operation == CONVERT_EXPR
3716 || *e->operation == NOP_EXPR)
3717 fprintf (f, " CASE_CONVERT:\n");
3718 else
3719 fprintf (f, " case %s%s:\n",
3720 is_a <fn_id *> (e->operation) ? "-" : "",
3721 e->operation->id);
3722 if (gimple)
3723 fprintf (f, " return gimple_simplify_%s (res_code, res_ops, "
3724 "seq, valueize, code, type", e->operation->id);
3725 else
3726 fprintf (f, " return generic_simplify_%s (loc, code, type",
3727 e->operation->id);
3728 for (unsigned i = 0; i < n; ++i)
3729 fprintf (f, ", op%d", i);
3730 fprintf (f, ");\n");
3732 fprintf (f, " default:;\n"
3733 " }\n");
3735 if (gimple)
3736 fprintf (f, " return false;\n");
3737 else
3738 fprintf (f, " return NULL_TREE;\n");
3739 fprintf (f, "}\n");
3743 /* Output code to implement the predicate P from the decision tree DT. */
3745 void
3746 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
3748 fprintf (f, "\nbool\n"
3749 "%s%s (tree t%s%s)\n"
3750 "{\n", gimple ? "gimple_" : "tree_", p->id,
3751 p->nargs > 0 ? ", tree *res_ops" : "",
3752 gimple ? ", tree (*valueize)(tree) ATTRIBUTE_UNUSED" : "");
3753 /* Conveniently make 'type' available. */
3754 fprintf_indent (f, 2, "tree type = TREE_TYPE (t);\n");
3756 if (!gimple)
3757 fprintf_indent (f, 2, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
3758 dt.root->gen_kids (f, 2, gimple);
3760 fprintf_indent (f, 2, "return false;\n"
3761 "}\n");
3764 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
3766 static void
3767 write_header (FILE *f, const char *head)
3769 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
3770 fprintf (f, " a IL pattern matching and simplification description. */\n");
3772 /* Include the header instead of writing it awkwardly quoted here. */
3773 fprintf (f, "\n#include \"%s\"\n", head);
3778 /* AST parsing. */
3780 class parser
3782 public:
3783 parser (cpp_reader *);
3785 private:
3786 const cpp_token *next ();
3787 const cpp_token *peek (unsigned = 1);
3788 const cpp_token *peek_ident (const char * = NULL, unsigned = 1);
3789 const cpp_token *expect (enum cpp_ttype);
3790 const cpp_token *eat_token (enum cpp_ttype);
3791 const char *get_string ();
3792 const char *get_ident ();
3793 const cpp_token *eat_ident (const char *);
3794 const char *get_number ();
3796 unsigned get_internal_capture_id ();
3798 id_base *parse_operation ();
3799 operand *parse_capture (operand *, bool);
3800 operand *parse_expr ();
3801 c_expr *parse_c_expr (cpp_ttype);
3802 operand *parse_op ();
3804 void record_operlist (source_location, user_id *);
3806 void parse_pattern ();
3807 operand *parse_result (operand *, predicate_id *);
3808 void push_simplify (simplify::simplify_kind,
3809 vec<simplify *>&, operand *, operand *);
3810 void parse_simplify (simplify::simplify_kind,
3811 vec<simplify *>&, predicate_id *, operand *);
3812 void parse_for (source_location);
3813 void parse_if (source_location);
3814 void parse_predicates (source_location);
3815 void parse_operator_list (source_location);
3817 void finish_match_operand (operand *);
3819 cpp_reader *r;
3820 vec<c_expr *> active_ifs;
3821 vec<vec<user_id *> > active_fors;
3822 hash_set<user_id *> *oper_lists_set;
3823 vec<user_id *> oper_lists;
3825 cid_map_t *capture_ids;
3827 public:
3828 vec<simplify *> simplifiers;
3829 vec<predicate_id *> user_predicates;
3830 bool parsing_match_operand;
3833 /* Lexing helpers. */
3835 /* Read the next non-whitespace token from R. */
3837 const cpp_token *
3838 parser::next ()
3840 const cpp_token *token;
3843 token = cpp_get_token (r);
3845 while (token->type == CPP_PADDING);
3846 return token;
3849 /* Peek at the next non-whitespace token from R. */
3851 const cpp_token *
3852 parser::peek (unsigned num)
3854 const cpp_token *token;
3855 unsigned i = 0;
3858 token = cpp_peek_token (r, i++);
3860 while (token->type == CPP_PADDING
3861 || (--num > 0));
3862 /* If we peek at EOF this is a fatal error as it leaves the
3863 cpp_reader in unusable state. Assume we really wanted a
3864 token and thus this EOF is unexpected. */
3865 if (token->type == CPP_EOF)
3866 fatal_at (token, "unexpected end of file");
3867 return token;
3870 /* Peek at the next identifier token (or return NULL if the next
3871 token is not an identifier or equal to ID if supplied). */
3873 const cpp_token *
3874 parser::peek_ident (const char *id, unsigned num)
3876 const cpp_token *token = peek (num);
3877 if (token->type != CPP_NAME)
3878 return 0;
3880 if (id == 0)
3881 return token;
3883 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
3884 if (strcmp (id, t) == 0)
3885 return token;
3887 return 0;
3890 /* Read the next token from R and assert it is of type TK. */
3892 const cpp_token *
3893 parser::expect (enum cpp_ttype tk)
3895 const cpp_token *token = next ();
3896 if (token->type != tk)
3897 fatal_at (token, "expected %s, got %s",
3898 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
3900 return token;
3903 /* Consume the next token from R and assert it is of type TK. */
3905 const cpp_token *
3906 parser::eat_token (enum cpp_ttype tk)
3908 return expect (tk);
3911 /* Read the next token from R and assert it is of type CPP_STRING and
3912 return its value. */
3914 const char *
3915 parser::get_string ()
3917 const cpp_token *token = expect (CPP_STRING);
3918 return (const char *)token->val.str.text;
3921 /* Read the next token from R and assert it is of type CPP_NAME and
3922 return its value. */
3924 const char *
3925 parser::get_ident ()
3927 const cpp_token *token = expect (CPP_NAME);
3928 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
3931 /* Eat an identifier token with value S from R. */
3933 const cpp_token *
3934 parser::eat_ident (const char *s)
3936 const cpp_token *token = peek ();
3937 const char *t = get_ident ();
3938 if (strcmp (s, t) != 0)
3939 fatal_at (token, "expected '%s' got '%s'\n", s, t);
3940 return token;
3943 /* Read the next token from R and assert it is of type CPP_NUMBER and
3944 return its value. */
3946 const char *
3947 parser::get_number ()
3949 const cpp_token *token = expect (CPP_NUMBER);
3950 return (const char *)token->val.str.text;
3953 /* Return a capture ID that can be used internally. */
3955 unsigned
3956 parser::get_internal_capture_id ()
3958 unsigned newid = capture_ids->elements ();
3959 /* Big enough for a 32-bit UINT_MAX plus prefix. */
3960 char id[13];
3961 bool existed;
3962 sprintf (id, "__%u", newid);
3963 capture_ids->get_or_insert (xstrdup (id), &existed);
3964 if (existed)
3965 fatal ("reserved capture id '%s' already used", id);
3966 return newid;
3969 /* Record an operator-list use for transparent for handling. */
3971 void
3972 parser::record_operlist (source_location loc, user_id *p)
3974 if (!oper_lists_set->add (p))
3976 if (!oper_lists.is_empty ()
3977 && oper_lists[0]->substitutes.length () != p->substitutes.length ())
3978 fatal_at (loc, "User-defined operator list does not have the "
3979 "same number of entries as others used in the pattern");
3980 oper_lists.safe_push (p);
3984 /* Parse the operator ID, special-casing convert?, convert1? and
3985 convert2? */
3987 id_base *
3988 parser::parse_operation ()
3990 const cpp_token *id_tok = peek ();
3991 const char *id = get_ident ();
3992 const cpp_token *token = peek ();
3993 if (strcmp (id, "convert0") == 0)
3994 fatal_at (id_tok, "use 'convert?' here");
3995 else if (strcmp (id, "view_convert0") == 0)
3996 fatal_at (id_tok, "use 'view_convert?' here");
3997 if (token->type == CPP_QUERY
3998 && !(token->flags & PREV_WHITE))
4000 if (strcmp (id, "convert") == 0)
4001 id = "convert0";
4002 else if (strcmp (id, "convert1") == 0)
4004 else if (strcmp (id, "convert2") == 0)
4006 else if (strcmp (id, "view_convert") == 0)
4007 id = "view_convert0";
4008 else if (strcmp (id, "view_convert1") == 0)
4010 else if (strcmp (id, "view_convert2") == 0)
4012 else
4013 fatal_at (id_tok, "non-convert operator conditionalized");
4015 if (!parsing_match_operand)
4016 fatal_at (id_tok, "conditional convert can only be used in "
4017 "match expression");
4018 eat_token (CPP_QUERY);
4020 else if (strcmp (id, "convert1") == 0
4021 || strcmp (id, "convert2") == 0
4022 || strcmp (id, "view_convert1") == 0
4023 || strcmp (id, "view_convert2") == 0)
4024 fatal_at (id_tok, "expected '?' after conditional operator");
4025 id_base *op = get_operator (id);
4026 if (!op)
4027 fatal_at (id_tok, "unknown operator %s", id);
4029 user_id *p = dyn_cast<user_id *> (op);
4030 if (p && p->is_oper_list)
4032 if (active_fors.length() == 0)
4033 record_operlist (id_tok->src_loc, p);
4034 else
4035 fatal_at (id_tok, "operator-list %s cannot be exapnded inside 'for'", id);
4037 return op;
4040 /* Parse a capture.
4041 capture = '@'<number> */
4043 struct operand *
4044 parser::parse_capture (operand *op, bool require_existing)
4046 source_location src_loc = eat_token (CPP_ATSIGN)->src_loc;
4047 const cpp_token *token = peek ();
4048 const char *id = NULL;
4049 bool value_match = false;
4050 /* For matches parse @@ as a value-match denoting the prevailing operand. */
4051 if (token->type == CPP_ATSIGN
4052 && ! (token->flags & PREV_WHITE)
4053 && parsing_match_operand)
4055 eat_token (CPP_ATSIGN);
4056 token = peek ();
4057 value_match = true;
4059 if (token->type == CPP_NUMBER)
4060 id = get_number ();
4061 else if (token->type == CPP_NAME)
4062 id = get_ident ();
4063 else
4064 fatal_at (token, "expected number or identifier");
4065 unsigned next_id = capture_ids->elements ();
4066 bool existed;
4067 unsigned &num = capture_ids->get_or_insert (id, &existed);
4068 if (!existed)
4070 if (require_existing)
4071 fatal_at (src_loc, "unknown capture id");
4072 num = next_id;
4074 return new capture (src_loc, num, op, value_match);
4077 /* Parse an expression
4078 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
4080 struct operand *
4081 parser::parse_expr ()
4083 const cpp_token *token = peek ();
4084 expr *e = new expr (parse_operation (), token->src_loc);
4085 token = peek ();
4086 operand *op;
4087 bool is_commutative = false;
4088 bool force_capture = false;
4089 const char *expr_type = NULL;
4091 if (token->type == CPP_COLON
4092 && !(token->flags & PREV_WHITE))
4094 eat_token (CPP_COLON);
4095 token = peek ();
4096 if (token->type == CPP_NAME
4097 && !(token->flags & PREV_WHITE))
4099 const char *s = get_ident ();
4100 if (!parsing_match_operand)
4101 expr_type = s;
4102 else
4104 const char *sp = s;
4105 while (*sp)
4107 if (*sp == 'c')
4109 if (operator_id *p
4110 = dyn_cast<operator_id *> (e->operation))
4112 if (!commutative_tree_code (p->code)
4113 && !comparison_code_p (p->code))
4114 fatal_at (token, "operation is not commutative");
4116 else if (user_id *p = dyn_cast<user_id *> (e->operation))
4117 for (unsigned i = 0;
4118 i < p->substitutes.length (); ++i)
4120 if (operator_id *q
4121 = dyn_cast<operator_id *> (p->substitutes[i]))
4123 if (!commutative_tree_code (q->code)
4124 && !comparison_code_p (q->code))
4125 fatal_at (token, "operation %s is not "
4126 "commutative", q->id);
4129 is_commutative = true;
4131 else if (*sp == 'C')
4132 is_commutative = true;
4133 else if (*sp == 's')
4135 e->force_single_use = true;
4136 force_capture = true;
4138 else
4139 fatal_at (token, "flag %c not recognized", *sp);
4140 sp++;
4143 token = peek ();
4145 else
4146 fatal_at (token, "expected flag or type specifying identifier");
4149 if (token->type == CPP_ATSIGN
4150 && !(token->flags & PREV_WHITE))
4151 op = parse_capture (e, false);
4152 else if (force_capture)
4154 unsigned num = get_internal_capture_id ();
4155 op = new capture (token->src_loc, num, e, false);
4157 else
4158 op = e;
4161 const cpp_token *token = peek ();
4162 if (token->type == CPP_CLOSE_PAREN)
4164 if (e->operation->nargs != -1
4165 && e->operation->nargs != (int) e->ops.length ())
4166 fatal_at (token, "'%s' expects %u operands, not %u",
4167 e->operation->id, e->operation->nargs, e->ops.length ());
4168 if (is_commutative)
4170 if (e->ops.length () == 2)
4171 e->is_commutative = true;
4172 else
4173 fatal_at (token, "only binary operators or function with "
4174 "two arguments can be marked commutative");
4176 e->expr_type = expr_type;
4177 return op;
4179 else if (!(token->flags & PREV_WHITE))
4180 fatal_at (token, "expected expression operand");
4182 e->append_op (parse_op ());
4184 while (1);
4187 /* Lex native C code delimited by START recording the preprocessing tokens
4188 for later processing.
4189 c_expr = ('{'|'(') <pp token>... ('}'|')') */
4191 c_expr *
4192 parser::parse_c_expr (cpp_ttype start)
4194 const cpp_token *token;
4195 cpp_ttype end;
4196 unsigned opencnt;
4197 vec<cpp_token> code = vNULL;
4198 unsigned nr_stmts = 0;
4199 source_location loc = eat_token (start)->src_loc;
4200 if (start == CPP_OPEN_PAREN)
4201 end = CPP_CLOSE_PAREN;
4202 else if (start == CPP_OPEN_BRACE)
4203 end = CPP_CLOSE_BRACE;
4204 else
4205 gcc_unreachable ();
4206 opencnt = 1;
4209 token = next ();
4211 /* Count brace pairs to find the end of the expr to match. */
4212 if (token->type == start)
4213 opencnt++;
4214 else if (token->type == end
4215 && --opencnt == 0)
4216 break;
4217 else if (token->type == CPP_EOF)
4218 fatal_at (token, "unexpected end of file");
4220 /* This is a lame way of counting the number of statements. */
4221 if (token->type == CPP_SEMICOLON)
4222 nr_stmts++;
4224 /* If this is possibly a user-defined identifier mark it used. */
4225 if (token->type == CPP_NAME)
4227 id_base *idb = get_operator ((const char *)CPP_HASHNODE
4228 (token->val.node.node)->ident.str);
4229 user_id *p;
4230 if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
4231 record_operlist (token->src_loc, p);
4234 /* Record the token. */
4235 code.safe_push (*token);
4237 while (1);
4238 return new c_expr (r, loc, code, nr_stmts, vNULL, capture_ids);
4241 /* Parse an operand which is either an expression, a predicate or
4242 a standalone capture.
4243 op = predicate | expr | c_expr | capture */
4245 struct operand *
4246 parser::parse_op ()
4248 const cpp_token *token = peek ();
4249 struct operand *op = NULL;
4250 if (token->type == CPP_OPEN_PAREN)
4252 eat_token (CPP_OPEN_PAREN);
4253 op = parse_expr ();
4254 eat_token (CPP_CLOSE_PAREN);
4256 else if (token->type == CPP_OPEN_BRACE)
4258 op = parse_c_expr (CPP_OPEN_BRACE);
4260 else
4262 /* Remaining ops are either empty or predicates */
4263 if (token->type == CPP_NAME)
4265 const char *id = get_ident ();
4266 id_base *opr = get_operator (id);
4267 if (!opr)
4268 fatal_at (token, "expected predicate name");
4269 if (operator_id *code = dyn_cast <operator_id *> (opr))
4271 if (code->nargs != 0)
4272 fatal_at (token, "using an operator with operands as predicate");
4273 /* Parse the zero-operand operator "predicates" as
4274 expression. */
4275 op = new expr (opr, token->src_loc);
4277 else if (user_id *code = dyn_cast <user_id *> (opr))
4279 if (code->nargs != 0)
4280 fatal_at (token, "using an operator with operands as predicate");
4281 /* Parse the zero-operand operator "predicates" as
4282 expression. */
4283 op = new expr (opr, token->src_loc);
4285 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
4286 op = new predicate (p, token->src_loc);
4287 else
4288 fatal_at (token, "using an unsupported operator as predicate");
4289 if (!parsing_match_operand)
4290 fatal_at (token, "predicates are only allowed in match expression");
4291 token = peek ();
4292 if (token->flags & PREV_WHITE)
4293 return op;
4295 else if (token->type != CPP_COLON
4296 && token->type != CPP_ATSIGN)
4297 fatal_at (token, "expected expression or predicate");
4298 /* optionally followed by a capture and a predicate. */
4299 if (token->type == CPP_COLON)
4300 fatal_at (token, "not implemented: predicate on leaf operand");
4301 if (token->type == CPP_ATSIGN)
4302 op = parse_capture (op, !parsing_match_operand);
4305 return op;
4308 /* Create a new simplify from the current parsing state and MATCH,
4309 MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS. */
4311 void
4312 parser::push_simplify (simplify::simplify_kind kind,
4313 vec<simplify *>& simplifiers,
4314 operand *match, operand *result)
4316 /* Build and push a temporary for operator list uses in expressions. */
4317 if (!oper_lists.is_empty ())
4318 active_fors.safe_push (oper_lists);
4320 simplifiers.safe_push
4321 (new simplify (kind, match, result,
4322 active_fors.copy (), capture_ids));
4324 if (!oper_lists.is_empty ())
4325 active_fors.pop ();
4328 /* Parse
4329 <result-op> = <op> | <if> | <with>
4330 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
4331 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
4332 and return it. */
4334 operand *
4335 parser::parse_result (operand *result, predicate_id *matcher)
4337 const cpp_token *token = peek ();
4338 if (token->type != CPP_OPEN_PAREN)
4339 return parse_op ();
4341 eat_token (CPP_OPEN_PAREN);
4342 if (peek_ident ("if"))
4344 eat_ident ("if");
4345 if_expr *ife = new if_expr (token->src_loc);
4346 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4347 if (peek ()->type == CPP_OPEN_PAREN)
4349 ife->trueexpr = parse_result (result, matcher);
4350 if (peek ()->type == CPP_OPEN_PAREN)
4351 ife->falseexpr = parse_result (result, matcher);
4352 else if (peek ()->type != CPP_CLOSE_PAREN)
4353 ife->falseexpr = parse_op ();
4355 else if (peek ()->type != CPP_CLOSE_PAREN)
4357 ife->trueexpr = parse_op ();
4358 if (peek ()->type == CPP_OPEN_PAREN)
4359 ife->falseexpr = parse_result (result, matcher);
4360 else if (peek ()->type != CPP_CLOSE_PAREN)
4361 ife->falseexpr = parse_op ();
4363 /* If this if is immediately closed then it contains a
4364 manual matcher or is part of a predicate definition. */
4365 else /* if (peek ()->type == CPP_CLOSE_PAREN) */
4367 if (!matcher)
4368 fatal_at (peek (), "manual transform not implemented");
4369 ife->trueexpr = result;
4371 eat_token (CPP_CLOSE_PAREN);
4372 return ife;
4374 else if (peek_ident ("with"))
4376 eat_ident ("with");
4377 with_expr *withe = new with_expr (token->src_loc);
4378 /* Parse (with c-expr expr) as (if-with (true) expr). */
4379 withe->with = parse_c_expr (CPP_OPEN_BRACE);
4380 withe->with->nr_stmts = 0;
4381 withe->subexpr = parse_result (result, matcher);
4382 eat_token (CPP_CLOSE_PAREN);
4383 return withe;
4385 else if (peek_ident ("switch"))
4387 token = eat_ident ("switch");
4388 source_location ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4389 eat_ident ("if");
4390 if_expr *ife = new if_expr (ifloc);
4391 operand *res = ife;
4392 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4393 if (peek ()->type == CPP_OPEN_PAREN)
4394 ife->trueexpr = parse_result (result, matcher);
4395 else
4396 ife->trueexpr = parse_op ();
4397 eat_token (CPP_CLOSE_PAREN);
4398 if (peek ()->type != CPP_OPEN_PAREN
4399 || !peek_ident ("if", 2))
4400 fatal_at (token, "switch can be implemented with a single if");
4401 while (peek ()->type != CPP_CLOSE_PAREN)
4403 if (peek ()->type == CPP_OPEN_PAREN)
4405 if (peek_ident ("if", 2))
4407 ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4408 eat_ident ("if");
4409 ife->falseexpr = new if_expr (ifloc);
4410 ife = as_a <if_expr *> (ife->falseexpr);
4411 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4412 if (peek ()->type == CPP_OPEN_PAREN)
4413 ife->trueexpr = parse_result (result, matcher);
4414 else
4415 ife->trueexpr = parse_op ();
4416 eat_token (CPP_CLOSE_PAREN);
4418 else
4420 /* switch default clause */
4421 ife->falseexpr = parse_result (result, matcher);
4422 eat_token (CPP_CLOSE_PAREN);
4423 return res;
4426 else
4428 /* switch default clause */
4429 ife->falseexpr = parse_op ();
4430 eat_token (CPP_CLOSE_PAREN);
4431 return res;
4434 eat_token (CPP_CLOSE_PAREN);
4435 return res;
4437 else
4439 operand *op = result;
4440 if (!matcher)
4441 op = parse_expr ();
4442 eat_token (CPP_CLOSE_PAREN);
4443 return op;
4447 /* Parse
4448 simplify = 'simplify' <expr> <result-op>
4450 match = 'match' <ident> <expr> [<result-op>]
4451 and fill SIMPLIFIERS with the results. */
4453 void
4454 parser::parse_simplify (simplify::simplify_kind kind,
4455 vec<simplify *>& simplifiers, predicate_id *matcher,
4456 operand *result)
4458 /* Reset the capture map. */
4459 if (!capture_ids)
4460 capture_ids = new cid_map_t;
4461 /* Reset oper_lists and set. */
4462 hash_set <user_id *> olist;
4463 oper_lists_set = &olist;
4464 oper_lists = vNULL;
4466 const cpp_token *loc = peek ();
4467 parsing_match_operand = true;
4468 struct operand *match = parse_op ();
4469 finish_match_operand (match);
4470 parsing_match_operand = false;
4471 if (match->type == operand::OP_CAPTURE && !matcher)
4472 fatal_at (loc, "outermost expression cannot be captured");
4473 if (match->type == operand::OP_EXPR
4474 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
4475 fatal_at (loc, "outermost expression cannot be a predicate");
4477 /* Splice active_ifs onto result and continue parsing the
4478 "then" expr. */
4479 if_expr *active_if = NULL;
4480 for (int i = active_ifs.length (); i > 0; --i)
4482 if_expr *ifc = new if_expr (active_ifs[i-1]->location);
4483 ifc->cond = active_ifs[i-1];
4484 ifc->trueexpr = active_if;
4485 active_if = ifc;
4487 if_expr *outermost_if = active_if;
4488 while (active_if && active_if->trueexpr)
4489 active_if = as_a <if_expr *> (active_if->trueexpr);
4491 const cpp_token *token = peek ();
4493 /* If this if is immediately closed then it is part of a predicate
4494 definition. Push it. */
4495 if (token->type == CPP_CLOSE_PAREN)
4497 if (!matcher)
4498 fatal_at (token, "expected transform expression");
4499 if (active_if)
4501 active_if->trueexpr = result;
4502 result = outermost_if;
4504 push_simplify (kind, simplifiers, match, result);
4505 return;
4508 operand *tem = parse_result (result, matcher);
4509 if (active_if)
4511 active_if->trueexpr = tem;
4512 result = outermost_if;
4514 else
4515 result = tem;
4517 push_simplify (kind, simplifiers, match, result);
4520 /* Parsing of the outer control structures. */
4522 /* Parse a for expression
4523 for = '(' 'for' <subst>... <pattern> ')'
4524 subst = <ident> '(' <ident>... ')' */
4526 void
4527 parser::parse_for (source_location)
4529 auto_vec<const cpp_token *> user_id_tokens;
4530 vec<user_id *> user_ids = vNULL;
4531 const cpp_token *token;
4532 unsigned min_n_opers = 0, max_n_opers = 0;
4534 while (1)
4536 token = peek ();
4537 if (token->type != CPP_NAME)
4538 break;
4540 /* Insert the user defined operators into the operator hash. */
4541 const char *id = get_ident ();
4542 if (get_operator (id, true) != NULL)
4543 fatal_at (token, "operator already defined");
4544 user_id *op = new user_id (id);
4545 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4546 *slot = op;
4547 user_ids.safe_push (op);
4548 user_id_tokens.safe_push (token);
4550 eat_token (CPP_OPEN_PAREN);
4552 int arity = -1;
4553 while ((token = peek_ident ()) != 0)
4555 const char *oper = get_ident ();
4556 id_base *idb = get_operator (oper, true);
4557 if (idb == NULL)
4558 fatal_at (token, "no such operator '%s'", oper);
4559 if (*idb == CONVERT0 || *idb == CONVERT1 || *idb == CONVERT2
4560 || *idb == VIEW_CONVERT0 || *idb == VIEW_CONVERT1
4561 || *idb == VIEW_CONVERT2)
4562 fatal_at (token, "conditional operators cannot be used inside for");
4564 if (arity == -1)
4565 arity = idb->nargs;
4566 else if (idb->nargs == -1)
4568 else if (idb->nargs != arity)
4569 fatal_at (token, "operator '%s' with arity %d does not match "
4570 "others with arity %d", oper, idb->nargs, arity);
4572 user_id *p = dyn_cast<user_id *> (idb);
4573 if (p)
4575 if (p->is_oper_list)
4576 op->substitutes.safe_splice (p->substitutes);
4577 else
4578 fatal_at (token, "iterator cannot be used as operator-list");
4580 else
4581 op->substitutes.safe_push (idb);
4583 op->nargs = arity;
4584 token = expect (CPP_CLOSE_PAREN);
4586 unsigned nsubstitutes = op->substitutes.length ();
4587 if (nsubstitutes == 0)
4588 fatal_at (token, "A user-defined operator must have at least "
4589 "one substitution");
4590 if (max_n_opers == 0)
4592 min_n_opers = nsubstitutes;
4593 max_n_opers = nsubstitutes;
4595 else
4597 if (nsubstitutes % min_n_opers != 0
4598 && min_n_opers % nsubstitutes != 0)
4599 fatal_at (token, "All user-defined identifiers must have a "
4600 "multiple number of operator substitutions of the "
4601 "smallest number of substitutions");
4602 if (nsubstitutes < min_n_opers)
4603 min_n_opers = nsubstitutes;
4604 else if (nsubstitutes > max_n_opers)
4605 max_n_opers = nsubstitutes;
4609 unsigned n_ids = user_ids.length ();
4610 if (n_ids == 0)
4611 fatal_at (token, "for requires at least one user-defined identifier");
4613 token = peek ();
4614 if (token->type == CPP_CLOSE_PAREN)
4615 fatal_at (token, "no pattern defined in for");
4617 active_fors.safe_push (user_ids);
4618 while (1)
4620 token = peek ();
4621 if (token->type == CPP_CLOSE_PAREN)
4622 break;
4623 parse_pattern ();
4625 active_fors.pop ();
4627 /* Remove user-defined operators from the hash again. */
4628 for (unsigned i = 0; i < user_ids.length (); ++i)
4630 if (!user_ids[i]->used)
4631 warning_at (user_id_tokens[i],
4632 "operator %s defined but not used", user_ids[i]->id);
4633 operators->remove_elt (user_ids[i]);
4637 /* Parse an identifier associated with a list of operators.
4638 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
4640 void
4641 parser::parse_operator_list (source_location)
4643 const cpp_token *token = peek ();
4644 const char *id = get_ident ();
4646 if (get_operator (id, true) != 0)
4647 fatal_at (token, "operator %s already defined", id);
4649 user_id *op = new user_id (id, true);
4650 int arity = -1;
4652 while ((token = peek_ident ()) != 0)
4654 token = peek ();
4655 const char *oper = get_ident ();
4656 id_base *idb = get_operator (oper, true);
4658 if (idb == 0)
4659 fatal_at (token, "no such operator '%s'", oper);
4661 if (arity == -1)
4662 arity = idb->nargs;
4663 else if (idb->nargs == -1)
4665 else if (arity != idb->nargs)
4666 fatal_at (token, "operator '%s' with arity %d does not match "
4667 "others with arity %d", oper, idb->nargs, arity);
4669 /* We allow composition of multiple operator lists. */
4670 if (user_id *p = dyn_cast<user_id *> (idb))
4671 op->substitutes.safe_splice (p->substitutes);
4672 else
4673 op->substitutes.safe_push (idb);
4676 // Check that there is no junk after id-list
4677 token = peek();
4678 if (token->type != CPP_CLOSE_PAREN)
4679 fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
4681 if (op->substitutes.length () == 0)
4682 fatal_at (token, "operator-list cannot be empty");
4684 op->nargs = arity;
4685 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4686 *slot = op;
4689 /* Parse an outer if expression.
4690 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
4692 void
4693 parser::parse_if (source_location)
4695 c_expr *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
4697 const cpp_token *token = peek ();
4698 if (token->type == CPP_CLOSE_PAREN)
4699 fatal_at (token, "no pattern defined in if");
4701 active_ifs.safe_push (ifexpr);
4702 while (1)
4704 const cpp_token *token = peek ();
4705 if (token->type == CPP_CLOSE_PAREN)
4706 break;
4708 parse_pattern ();
4710 active_ifs.pop ();
4713 /* Parse a list of predefined predicate identifiers.
4714 preds = '(' 'define_predicates' <ident>... ')' */
4716 void
4717 parser::parse_predicates (source_location)
4721 const cpp_token *token = peek ();
4722 if (token->type != CPP_NAME)
4723 break;
4725 add_predicate (get_ident ());
4727 while (1);
4730 /* Parse outer control structures.
4731 pattern = <preds>|<for>|<if>|<simplify>|<match> */
4733 void
4734 parser::parse_pattern ()
4736 /* All clauses start with '('. */
4737 eat_token (CPP_OPEN_PAREN);
4738 const cpp_token *token = peek ();
4739 const char *id = get_ident ();
4740 if (strcmp (id, "simplify") == 0)
4742 parse_simplify (simplify::SIMPLIFY, simplifiers, NULL, NULL);
4743 capture_ids = NULL;
4745 else if (strcmp (id, "match") == 0)
4747 bool with_args = false;
4748 source_location e_loc = peek ()->src_loc;
4749 if (peek ()->type == CPP_OPEN_PAREN)
4751 eat_token (CPP_OPEN_PAREN);
4752 with_args = true;
4754 const char *name = get_ident ();
4755 id_base *id = get_operator (name);
4756 predicate_id *p;
4757 if (!id)
4759 p = add_predicate (name);
4760 user_predicates.safe_push (p);
4762 else if ((p = dyn_cast <predicate_id *> (id)))
4764 else
4765 fatal_at (token, "cannot add a match to a non-predicate ID");
4766 /* Parse (match <id> <arg>... (match-expr)) here. */
4767 expr *e = NULL;
4768 if (with_args)
4770 capture_ids = new cid_map_t;
4771 e = new expr (p, e_loc);
4772 while (peek ()->type == CPP_ATSIGN)
4773 e->append_op (parse_capture (NULL, false));
4774 eat_token (CPP_CLOSE_PAREN);
4776 if (p->nargs != -1
4777 && ((e && e->ops.length () != (unsigned)p->nargs)
4778 || (!e && p->nargs != 0)))
4779 fatal_at (token, "non-matching number of match operands");
4780 p->nargs = e ? e->ops.length () : 0;
4781 parse_simplify (simplify::MATCH, p->matchers, p, e);
4782 capture_ids = NULL;
4784 else if (strcmp (id, "for") == 0)
4785 parse_for (token->src_loc);
4786 else if (strcmp (id, "if") == 0)
4787 parse_if (token->src_loc);
4788 else if (strcmp (id, "define_predicates") == 0)
4790 if (active_ifs.length () > 0
4791 || active_fors.length () > 0)
4792 fatal_at (token, "define_predicates inside if or for is not supported");
4793 parse_predicates (token->src_loc);
4795 else if (strcmp (id, "define_operator_list") == 0)
4797 if (active_ifs.length () > 0
4798 || active_fors.length () > 0)
4799 fatal_at (token, "operator-list inside if or for is not supported");
4800 parse_operator_list (token->src_loc);
4802 else
4803 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
4804 active_ifs.length () == 0 && active_fors.length () == 0
4805 ? "'define_predicates', " : "");
4807 eat_token (CPP_CLOSE_PAREN);
4810 /* Helper for finish_match_operand, collecting captures of OP in CPTS
4811 recursively. */
4813 static void
4814 walk_captures (operand *op, vec<vec<capture *> > cpts)
4816 if (! op)
4817 return;
4819 if (capture *c = dyn_cast <capture *> (op))
4821 cpts[c->where].safe_push (c);
4822 walk_captures (c->what, cpts);
4824 else if (expr *e = dyn_cast <expr *> (op))
4825 for (unsigned i = 0; i < e->ops.length (); ++i)
4826 walk_captures (e->ops[i], cpts);
4829 /* Finish up OP which is a match operand. */
4831 void
4832 parser::finish_match_operand (operand *op)
4834 /* Look for matching captures, diagnose mis-uses of @@ and apply
4835 early lowering and distribution of value_match. */
4836 auto_vec<vec<capture *> > cpts;
4837 cpts.safe_grow_cleared (capture_ids->elements ());
4838 walk_captures (op, cpts);
4839 for (unsigned i = 0; i < cpts.length (); ++i)
4841 capture *value_match = NULL;
4842 for (unsigned j = 0; j < cpts[i].length (); ++j)
4844 if (cpts[i][j]->value_match)
4846 if (value_match)
4847 fatal_at (cpts[i][j]->location, "duplicate @@");
4848 value_match = cpts[i][j];
4851 if (cpts[i].length () == 1 && value_match)
4852 fatal_at (value_match->location, "@@ without a matching capture");
4853 if (value_match)
4855 /* Duplicate prevailing capture with the existing ID, create
4856 a fake ID and rewrite all captures to use it. This turns
4857 @@1 into @__<newid>@1 and @1 into @__<newid>. */
4858 value_match->what = new capture (value_match->location,
4859 value_match->where,
4860 value_match->what, false);
4861 /* Create a fake ID and rewrite all captures to use it. */
4862 unsigned newid = get_internal_capture_id ();
4863 for (unsigned j = 0; j < cpts[i].length (); ++j)
4865 cpts[i][j]->where = newid;
4866 cpts[i][j]->value_match = true;
4869 cpts[i].release ();
4873 /* Main entry of the parser. Repeatedly parse outer control structures. */
4875 parser::parser (cpp_reader *r_)
4877 r = r_;
4878 active_ifs = vNULL;
4879 active_fors = vNULL;
4880 simplifiers = vNULL;
4881 oper_lists_set = NULL;
4882 oper_lists = vNULL;
4883 capture_ids = NULL;
4884 user_predicates = vNULL;
4885 parsing_match_operand = false;
4887 const cpp_token *token = next ();
4888 while (token->type != CPP_EOF)
4890 _cpp_backup_tokens (r, 1);
4891 parse_pattern ();
4892 token = next ();
4897 /* Helper for the linemap code. */
4899 static size_t
4900 round_alloc_size (size_t s)
4902 return s;
4906 /* The genmatch generator progam. It reads from a pattern description
4907 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
4910 main (int argc, char **argv)
4912 cpp_reader *r;
4914 progname = "genmatch";
4916 if (argc < 2)
4917 return 1;
4919 bool gimple = true;
4920 char *input = argv[argc-1];
4921 for (int i = 1; i < argc - 1; ++i)
4923 if (strcmp (argv[i], "--gimple") == 0)
4924 gimple = true;
4925 else if (strcmp (argv[i], "--generic") == 0)
4926 gimple = false;
4927 else if (strcmp (argv[i], "-v") == 0)
4928 verbose = 1;
4929 else if (strcmp (argv[i], "-vv") == 0)
4930 verbose = 2;
4931 else
4933 fprintf (stderr, "Usage: genmatch "
4934 "[--gimple] [--generic] [-v[v]] input\n");
4935 return 1;
4939 line_table = XCNEW (struct line_maps);
4940 linemap_init (line_table, 0);
4941 line_table->reallocator = xrealloc;
4942 line_table->round_alloc_size = round_alloc_size;
4944 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
4945 cpp_callbacks *cb = cpp_get_callbacks (r);
4946 cb->error = error_cb;
4948 /* Add the build directory to the #include "" search path. */
4949 cpp_dir *dir = XCNEW (cpp_dir);
4950 dir->name = getpwd ();
4951 if (!dir->name)
4952 dir->name = ASTRDUP (".");
4953 cpp_set_include_chains (r, dir, NULL, false);
4955 if (!cpp_read_main_file (r, input))
4956 return 1;
4957 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
4958 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
4960 null_id = new id_base (id_base::NULL_ID, "null");
4962 /* Pre-seed operators. */
4963 operators = new hash_table<id_base> (1024);
4964 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
4965 add_operator (SYM, # SYM, # TYPE, NARGS);
4966 #define END_OF_BASE_TREE_CODES
4967 #include "tree.def"
4968 add_operator (CONVERT0, "convert0", "tcc_unary", 1);
4969 add_operator (CONVERT1, "convert1", "tcc_unary", 1);
4970 add_operator (CONVERT2, "convert2", "tcc_unary", 1);
4971 add_operator (VIEW_CONVERT0, "view_convert0", "tcc_unary", 1);
4972 add_operator (VIEW_CONVERT1, "view_convert1", "tcc_unary", 1);
4973 add_operator (VIEW_CONVERT2, "view_convert2", "tcc_unary", 1);
4974 #undef END_OF_BASE_TREE_CODES
4975 #undef DEFTREECODE
4977 /* Pre-seed builtin functions.
4978 ??? Cannot use N (name) as that is targetm.emultls.get_address
4979 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
4980 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
4981 add_function (ENUM, "CFN_" # ENUM);
4982 #include "builtins.def"
4984 #define DEF_INTERNAL_FN(CODE, NAME, FNSPEC) \
4985 add_function (IFN_##CODE, "CFN_" #CODE);
4986 #include "internal-fn.def"
4988 /* Parse ahead! */
4989 parser p (r);
4991 if (gimple)
4992 write_header (stdout, "gimple-match-head.c");
4993 else
4994 write_header (stdout, "generic-match-head.c");
4996 /* Go over all predicates defined with patterns and perform
4997 lowering and code generation. */
4998 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
5000 predicate_id *pred = p.user_predicates[i];
5001 lower (pred->matchers, gimple);
5003 if (verbose == 2)
5004 for (unsigned i = 0; i < pred->matchers.length (); ++i)
5005 print_matches (pred->matchers[i]);
5007 decision_tree dt;
5008 for (unsigned i = 0; i < pred->matchers.length (); ++i)
5009 dt.insert (pred->matchers[i], i);
5011 if (verbose == 2)
5012 dt.print (stderr);
5014 write_predicate (stdout, pred, dt, gimple);
5017 /* Lower the main simplifiers and generate code for them. */
5018 lower (p.simplifiers, gimple);
5020 if (verbose == 2)
5021 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
5022 print_matches (p.simplifiers[i]);
5024 decision_tree dt;
5025 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
5026 dt.insert (p.simplifiers[i], i);
5028 if (verbose == 2)
5029 dt.print (stderr);
5031 dt.gen (stdout, gimple);
5033 /* Finalize. */
5034 cpp_finish (r, NULL);
5035 cpp_destroy (r);
5037 delete operators;
5039 return 0;