genmatch.c (comparison_code_p): New predicate.
[platform/upstream/gcc.git] / gcc / genmatch.c
1 /* Generate pattern matching and transform code shared between
2    GENERIC and GIMPLE folding code from match-and-simplify description.
3
4    Copyright (C) 2014-2016 Free Software Foundation, Inc.
5    Contributed by Richard Biener <rguenther@suse.de>
6    and Prathamesh Kulkarni  <bilbotheelffriend@gmail.com>
7
8 This file is part of GCC.
9
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.
14
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.
19
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/>.  */
23
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"
32
33
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)
37 {
38   return NULL;
39 }
40 void ggc_free (void *)
41 {
42 }
43
44
45 /* Global state.  */
46
47 /* Verboseness.  0 is quiet, 1 adds some warnings, 2 is for debugging.  */
48 unsigned verbose;
49
50
51 /* libccp helpers.  */
52
53 static struct line_maps *line_table;
54
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.
60
61    This is the implementation for genmatch.  */
62
63 expanded_location
64 linemap_client_expand_location_to_spelling_point (source_location loc)
65 {
66   const struct line_map_ordinary *map;
67   loc = linemap_resolve_location (line_table, loc, LRK_SPELLING_LOCATION, &map);
68   return linemap_expand_location (line_table, map, loc);
69 }
70
71 static bool
72 #if GCC_VERSION >= 4001
73 __attribute__((format (printf, 5, 0)))
74 #endif
75 error_cb (cpp_reader *, int errtype, int, rich_location *richloc,
76           const char *msg, va_list *ap)
77 {
78   const line_map_ordinary *map;
79   source_location location = richloc->get_loc ();
80   linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
81   expanded_location loc = linemap_expand_location (line_table, map, location);
82   fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
83            (errtype == CPP_DL_WARNING) ? "warning" : "error");
84   vfprintf (stderr, msg, *ap);
85   fprintf (stderr, "\n");
86   FILE *f = fopen (loc.file, "r");
87   if (f)
88     {
89       char buf[128];
90       while (loc.line > 0)
91         {
92           if (!fgets (buf, 128, f))
93             goto notfound;
94           if (buf[strlen (buf) - 1] != '\n')
95             {
96               if (loc.line > 1)
97                 loc.line++;
98             }
99           loc.line--;
100         }
101       fprintf (stderr, "%s", buf);
102       for (int i = 0; i < loc.column - 1; ++i)
103         fputc (' ', stderr);
104       fputc ('^', stderr);
105       fputc ('\n', stderr);
106 notfound:
107       fclose (f);
108     }
109
110   if (errtype == CPP_DL_FATAL)
111     exit (1);
112   return false;
113 }
114
115 static void
116 #if GCC_VERSION >= 4001
117 __attribute__((format (printf, 2, 3)))
118 #endif
119 fatal_at (const cpp_token *tk, const char *msg, ...)
120 {
121   rich_location richloc (line_table, tk->src_loc);
122   va_list ap;
123   va_start (ap, msg);
124   error_cb (NULL, CPP_DL_FATAL, 0, &richloc, msg, &ap);
125   va_end (ap);
126 }
127
128 static void
129 #if GCC_VERSION >= 4001
130 __attribute__((format (printf, 2, 3)))
131 #endif
132 fatal_at (source_location loc, const char *msg, ...)
133 {
134   rich_location richloc (line_table, loc);
135   va_list ap;
136   va_start (ap, msg);
137   error_cb (NULL, CPP_DL_FATAL, 0, &richloc, msg, &ap);
138   va_end (ap);
139 }
140
141 static void
142 #if GCC_VERSION >= 4001
143 __attribute__((format (printf, 2, 3)))
144 #endif
145 warning_at (const cpp_token *tk, const char *msg, ...)
146 {
147   rich_location richloc (line_table, tk->src_loc);
148   va_list ap;
149   va_start (ap, msg);
150   error_cb (NULL, CPP_DL_WARNING, 0, &richloc, msg, &ap);
151   va_end (ap);
152 }
153
154 static void
155 #if GCC_VERSION >= 4001
156 __attribute__((format (printf, 2, 3)))
157 #endif
158 warning_at (source_location loc, const char *msg, ...)
159 {
160   rich_location richloc (line_table, loc);
161   va_list ap;
162   va_start (ap, msg);
163   error_cb (NULL, CPP_DL_WARNING, 0, &richloc, msg, &ap);
164   va_end (ap);
165 }
166
167 /* Like fprintf, but print INDENT spaces at the beginning.  */
168
169 static void
170 #if GCC_VERSION >= 4001
171 __attribute__((format (printf, 3, 4)))
172 #endif
173 fprintf_indent (FILE *f, unsigned int indent, const char *format, ...)
174 {
175   va_list ap;
176   for (; indent >= 8; indent -= 8)
177     fputc ('\t', f);
178   fprintf (f, "%*s", indent, "");
179   va_start (ap, format);
180   vfprintf (f, format, ap);
181   va_end (ap);
182 }
183
184 static void
185 output_line_directive (FILE *f, source_location location,
186                        bool dumpfile = false)
187 {
188   const line_map_ordinary *map;
189   linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
190   expanded_location loc = linemap_expand_location (line_table, map, location);
191   if (dumpfile)
192     {
193       /* When writing to a dumpfile only dump the filename.  */
194       const char *file = strrchr (loc.file, DIR_SEPARATOR);
195       if (!file)
196         file = loc.file;
197       else
198         ++file;
199       fprintf (f, "%s:%d", file, loc.line);
200     }
201   else
202     /* Other gen programs really output line directives here, at least for
203        development it's right now more convenient to have line information
204        from the generated file.  Still keep the directives as comment for now
205        to easily back-point to the meta-description.  */
206     fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
207 }
208
209
210 /* Pull in tree codes and builtin function codes from their
211    definition files.  */
212
213 #define DEFTREECODE(SYM, STRING, TYPE, NARGS)   SYM,
214 enum tree_code {
215 #include "tree.def"
216 CONVERT0,
217 CONVERT1,
218 CONVERT2,
219 VIEW_CONVERT0,
220 VIEW_CONVERT1,
221 VIEW_CONVERT2,
222 MAX_TREE_CODES
223 };
224 #undef DEFTREECODE
225
226 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
227 enum built_in_function {
228 #include "builtins.def"
229 END_BUILTINS
230 };
231
232 #define DEF_INTERNAL_FN(CODE, FLAGS, FNSPEC) IFN_##CODE,
233 enum internal_fn {
234 #include "internal-fn.def"
235   IFN_LAST
236 };
237
238 /* Return true if CODE represents a commutative tree code.  Otherwise
239    return false.  */
240 bool
241 commutative_tree_code (enum tree_code code)
242 {
243   switch (code)
244     {
245     case PLUS_EXPR:
246     case MULT_EXPR:
247     case MULT_HIGHPART_EXPR:
248     case MIN_EXPR:
249     case MAX_EXPR:
250     case BIT_IOR_EXPR:
251     case BIT_XOR_EXPR:
252     case BIT_AND_EXPR:
253     case NE_EXPR:
254     case EQ_EXPR:
255     case UNORDERED_EXPR:
256     case ORDERED_EXPR:
257     case UNEQ_EXPR:
258     case LTGT_EXPR:
259     case TRUTH_AND_EXPR:
260     case TRUTH_XOR_EXPR:
261     case TRUTH_OR_EXPR:
262     case WIDEN_MULT_EXPR:
263     case VEC_WIDEN_MULT_HI_EXPR:
264     case VEC_WIDEN_MULT_LO_EXPR:
265     case VEC_WIDEN_MULT_EVEN_EXPR:
266     case VEC_WIDEN_MULT_ODD_EXPR:
267       return true;
268
269     default:
270       break;
271     }
272   return false;
273 }
274
275 /* Return true if CODE represents a ternary tree code for which the
276    first two operands are commutative.  Otherwise return false.  */
277 bool
278 commutative_ternary_tree_code (enum tree_code code)
279 {
280   switch (code)
281     {
282     case WIDEN_MULT_PLUS_EXPR:
283     case WIDEN_MULT_MINUS_EXPR:
284     case DOT_PROD_EXPR:
285     case FMA_EXPR:
286       return true;
287
288     default:
289       break;
290     }
291   return false;
292 }
293
294 /* Return true if CODE is a comparison.  */
295
296 bool
297 comparison_code_p (enum tree_code code)
298 {
299   switch (code)
300     {
301     case EQ_EXPR:
302     case NE_EXPR:
303     case ORDERED_EXPR:
304     case UNORDERED_EXPR:
305     case LTGT_EXPR:
306     case UNEQ_EXPR:
307     case GT_EXPR:
308     case GE_EXPR:
309     case LT_EXPR:
310     case LE_EXPR:
311     case UNGT_EXPR:
312     case UNGE_EXPR:
313     case UNLT_EXPR:
314     case UNLE_EXPR:
315       return true;
316
317     default:
318       break;
319     }
320   return false;
321 }
322
323
324 /* Base class for all identifiers the parser knows.  */
325
326 struct id_base : nofree_ptr_hash<id_base>
327 {
328   enum id_kind { CODE, FN, PREDICATE, USER, NULL_ID } kind;
329
330   id_base (id_kind, const char *, int = -1);
331
332   hashval_t hashval;
333   int nargs;
334   const char *id;
335
336   /* hash_table support.  */
337   static inline hashval_t hash (const id_base *);
338   static inline int equal (const id_base *, const id_base *);
339 };
340
341 inline hashval_t
342 id_base::hash (const id_base *op)
343 {
344   return op->hashval;
345 }
346
347 inline int
348 id_base::equal (const id_base *op1,
349                         const id_base *op2)
350 {
351   return (op1->hashval == op2->hashval
352           && strcmp (op1->id, op2->id) == 0);
353 }
354
355 /* The special id "null", which matches nothing.  */
356 static id_base *null_id;
357
358 /* Hashtable of known pattern operators.  This is pre-seeded from
359    all known tree codes and all known builtin function ids.  */
360 static hash_table<id_base> *operators;
361
362 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
363 {
364   kind = kind_;
365   id = id_;
366   nargs = nargs_;
367   hashval = htab_hash_string (id);
368 }
369
370 /* Identifier that maps to a tree code.  */
371
372 struct operator_id : public id_base
373 {
374   operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
375                const char *tcc_)
376       : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
377   enum tree_code code;
378   const char *tcc;
379 };
380
381 /* Identifier that maps to a builtin or internal function code.  */
382
383 struct fn_id : public id_base
384 {
385   fn_id (enum built_in_function fn_, const char *id_)
386       : id_base (id_base::FN, id_), fn (fn_) {}
387   fn_id (enum internal_fn fn_, const char *id_)
388       : id_base (id_base::FN, id_), fn (int (END_BUILTINS) + int (fn_)) {}
389   unsigned int fn;
390 };
391
392 struct simplify;
393
394 /* Identifier that maps to a user-defined predicate.  */
395
396 struct predicate_id : public id_base
397 {
398   predicate_id (const char *id_)
399     : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
400   vec<simplify *> matchers;
401 };
402
403 /* Identifier that maps to a operator defined by a 'for' directive.  */
404
405 struct user_id : public id_base
406 {
407   user_id (const char *id_, bool is_oper_list_ = false)
408     : id_base (id_base::USER, id_), substitutes (vNULL),
409       used (false), is_oper_list (is_oper_list_) {}
410   vec<id_base *> substitutes;
411   bool used;
412   bool is_oper_list;
413 };
414
415 template<>
416 template<>
417 inline bool
418 is_a_helper <fn_id *>::test (id_base *id)
419 {
420   return id->kind == id_base::FN;
421 }
422
423 template<>
424 template<>
425 inline bool
426 is_a_helper <operator_id *>::test (id_base *id)
427 {
428   return id->kind == id_base::CODE;
429 }
430
431 template<>
432 template<>
433 inline bool
434 is_a_helper <predicate_id *>::test (id_base *id)
435 {
436   return id->kind == id_base::PREDICATE;
437 }
438
439 template<>
440 template<>
441 inline bool
442 is_a_helper <user_id *>::test (id_base *id)
443 {
444   return id->kind == id_base::USER;
445 }
446
447 /* Add a predicate identifier to the hash.  */
448
449 static predicate_id *
450 add_predicate (const char *id)
451 {
452   predicate_id *p = new predicate_id (id);
453   id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
454   if (*slot)
455     fatal ("duplicate id definition");
456   *slot = p;
457   return p;
458 }
459
460 /* Add a tree code identifier to the hash.  */
461
462 static void
463 add_operator (enum tree_code code, const char *id,
464               const char *tcc, unsigned nargs)
465 {
466   if (strcmp (tcc, "tcc_unary") != 0
467       && strcmp (tcc, "tcc_binary") != 0
468       && strcmp (tcc, "tcc_comparison") != 0
469       && strcmp (tcc, "tcc_expression") != 0
470       /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR.  */
471       && strcmp (tcc, "tcc_reference") != 0
472       /* To have INTEGER_CST and friends as "predicate operators".  */
473       && strcmp (tcc, "tcc_constant") != 0
474       /* And allow CONSTRUCTOR for vector initializers.  */
475       && !(code == CONSTRUCTOR)
476       /* Allow SSA_NAME as predicate operator.  */
477       && !(code == SSA_NAME))
478     return;
479   /* Treat ADDR_EXPR as atom, thus don't allow matching its operand.  */
480   if (code == ADDR_EXPR)
481     nargs = 0;
482   operator_id *op = new operator_id (code, id, nargs, tcc);
483   id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
484   if (*slot)
485     fatal ("duplicate id definition");
486   *slot = op;
487 }
488
489 /* Add a built-in or internal function identifier to the hash.  ID is
490    the name of its CFN_* enumeration value.  */
491
492 template <typename T>
493 static void
494 add_function (T code, const char *id)
495 {
496   fn_id *fn = new fn_id (code, id);
497   id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
498   if (*slot)
499     fatal ("duplicate id definition");
500   *slot = fn;
501 }
502
503 /* Helper for easy comparing ID with tree code CODE.  */
504
505 static bool
506 operator==(id_base &id, enum tree_code code)
507 {
508   if (operator_id *oid = dyn_cast <operator_id *> (&id))
509     return oid->code == code;
510   return false;
511 }
512
513 /* Lookup the identifier ID.  Allow "null" if ALLOW_NULL.  */
514
515 id_base *
516 get_operator (const char *id, bool allow_null = false)
517 {
518   if (allow_null && strcmp (id, "null") == 0)
519     return null_id;
520
521   id_base tem (id_base::CODE, id);
522
523   id_base *op = operators->find_with_hash (&tem, tem.hashval);
524   if (op)
525     {
526       /* If this is a user-defined identifier track whether it was used.  */
527       if (user_id *uid = dyn_cast<user_id *> (op))
528         uid->used = true;
529       return op;
530     }
531
532   char *id2;
533   bool all_upper = true;
534   bool all_lower = true;
535   for (unsigned int i = 0; id[i]; ++i)
536     if (ISUPPER (id[i]))
537       all_lower = false;
538     else if (ISLOWER (id[i]))
539       all_upper = false;
540   if (all_lower)
541     {
542       /* Try in caps with _EXPR appended.  */
543       id2 = ACONCAT ((id, "_EXPR", NULL));
544       for (unsigned int i = 0; id2[i]; ++i)
545         id2[i] = TOUPPER (id2[i]);
546     }
547   else if (all_upper && strncmp (id, "IFN_", 4) == 0)
548     /* Try CFN_ instead of IFN_.  */
549     id2 = ACONCAT (("CFN_", id + 4, NULL));
550   else if (all_upper && strncmp (id, "BUILT_IN_", 9) == 0)
551     /* Try prepending CFN_.  */
552     id2 = ACONCAT (("CFN_", id, NULL));
553   else
554     return NULL;
555
556   new (&tem) id_base (id_base::CODE, id2);
557   return operators->find_with_hash (&tem, tem.hashval);
558 }
559
560 /* Return the comparison operators that results if the operands are
561    swapped.  This is safe for floating-point.  */
562
563 id_base *
564 swap_tree_comparison (operator_id *p)
565 {
566   switch (p->code)
567     {
568     case EQ_EXPR:
569     case NE_EXPR:
570     case ORDERED_EXPR:
571     case UNORDERED_EXPR:
572     case LTGT_EXPR:
573     case UNEQ_EXPR:
574       return p;
575     case GT_EXPR:
576       return get_operator ("LT_EXPR");
577     case GE_EXPR:
578       return get_operator ("LE_EXPR");
579     case LT_EXPR:
580       return get_operator ("GT_EXPR");
581     case LE_EXPR:
582       return get_operator ("GE_EXPR");
583     case UNGT_EXPR:
584       return get_operator ("UNLT_EXPR");
585     case UNGE_EXPR:
586       return get_operator ("UNLE_EXPR");
587     case UNLT_EXPR:
588       return get_operator ("UNGT_EXPR");
589     case UNLE_EXPR:
590       return get_operator ("UNGE_EXPR");
591     default:
592       gcc_unreachable ();
593     }
594 }
595
596 typedef hash_map<nofree_string_hash, unsigned> cid_map_t;
597
598
599 /* The AST produced by parsing of the pattern definitions.  */
600
601 struct dt_operand;
602 struct capture_info;
603
604 /* The base class for operands.  */
605
606 struct operand {
607   enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR, OP_IF, OP_WITH };
608   operand (enum op_type type_, source_location loc_)
609     : type (type_), location (loc_) {}
610   enum op_type type;
611   source_location location;
612   virtual void gen_transform (FILE *, int, const char *, bool, int,
613                               const char *, capture_info *,
614                               dt_operand ** = 0,
615                               int = 0)
616     { gcc_unreachable  (); }
617 };
618
619 /* A predicate operand.  Predicates are leafs in the AST.  */
620
621 struct predicate : public operand
622 {
623   predicate (predicate_id *p_, source_location loc)
624     : operand (OP_PREDICATE, loc), p (p_) {}
625   predicate_id *p;
626 };
627
628 /* An operand that constitutes an expression.  Expressions include
629    function calls and user-defined predicate invocations.  */
630
631 struct expr : public operand
632 {
633   expr (id_base *operation_, source_location loc, bool is_commutative_ = false)
634     : operand (OP_EXPR, loc), operation (operation_),
635       ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
636       is_generic (false), force_single_use (false) {}
637   expr (expr *e)
638     : operand (OP_EXPR, e->location), operation (e->operation),
639       ops (vNULL), expr_type (e->expr_type), is_commutative (e->is_commutative),
640       is_generic (e->is_generic), force_single_use (e->force_single_use) {}
641   void append_op (operand *op) { ops.safe_push (op); }
642   /* The operator and its operands.  */
643   id_base *operation;
644   vec<operand *> ops;
645   /* An explicitely specified type - used exclusively for conversions.  */
646   const char *expr_type;
647   /* Whether the operation is to be applied commutatively.  This is
648      later lowered to two separate patterns.  */
649   bool is_commutative;
650   /* Whether the expression is expected to be in GENERIC form.  */
651   bool is_generic;
652   /* Whether pushing any stmt to the sequence should be conditional
653      on this expression having a single-use.  */
654   bool force_single_use;
655   virtual void gen_transform (FILE *f, int, const char *, bool, int,
656                               const char *, capture_info *,
657                               dt_operand ** = 0, int = 0);
658 };
659
660 /* An operator that is represented by native C code.  This is always
661    a leaf operand in the AST.  This class is also used to represent
662    the code to be generated for 'if' and 'with' expressions.  */
663
664 struct c_expr : public operand
665 {
666   /* A mapping of an identifier and its replacement.  Used to apply
667      'for' lowering.  */
668   struct id_tab {
669     const char *id;
670     const char *oper;
671     id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
672   };
673
674   c_expr (cpp_reader *r_, source_location loc,
675           vec<cpp_token> code_, unsigned nr_stmts_,
676           vec<id_tab> ids_, cid_map_t *capture_ids_)
677     : operand (OP_C_EXPR, loc), r (r_), code (code_),
678       capture_ids (capture_ids_), nr_stmts (nr_stmts_), ids (ids_) {}
679   /* cpplib tokens and state to transform this back to source.  */
680   cpp_reader *r;
681   vec<cpp_token> code;
682   cid_map_t *capture_ids;
683   /* The number of statements parsed (well, the number of ';'s).  */
684   unsigned nr_stmts;
685   /* The identifier replacement vector.  */
686   vec<id_tab> ids;
687   virtual void gen_transform (FILE *f, int, const char *, bool, int,
688                               const char *, capture_info *,
689                               dt_operand ** = 0, int = 0);
690 };
691
692 /* A wrapper around another operand that captures its value.  */
693
694 struct capture : public operand
695 {
696   capture (source_location loc, unsigned where_, operand *what_)
697       : operand (OP_CAPTURE, loc), where (where_), what (what_) {}
698   /* Identifier index for the value.  */
699   unsigned where;
700   /* The captured value.  */
701   operand *what;
702   virtual void gen_transform (FILE *f, int, const char *, bool, int,
703                               const char *, capture_info *,
704                               dt_operand ** = 0, int = 0);
705 };
706
707 /* if expression.  */
708
709 struct if_expr : public operand
710 {
711   if_expr (source_location loc)
712     : operand (OP_IF, loc), cond (NULL), trueexpr (NULL), falseexpr (NULL) {}
713   c_expr *cond;
714   operand *trueexpr;
715   operand *falseexpr;
716 };
717
718 /* with expression.  */
719
720 struct with_expr : public operand
721 {
722   with_expr (source_location loc)
723     : operand (OP_WITH, loc), with (NULL), subexpr (NULL) {}
724   c_expr *with;
725   operand *subexpr;
726 };
727
728 template<>
729 template<>
730 inline bool
731 is_a_helper <capture *>::test (operand *op)
732 {
733   return op->type == operand::OP_CAPTURE;
734 }
735
736 template<>
737 template<>
738 inline bool
739 is_a_helper <predicate *>::test (operand *op)
740 {
741   return op->type == operand::OP_PREDICATE;
742 }
743
744 template<>
745 template<>
746 inline bool
747 is_a_helper <c_expr *>::test (operand *op)
748 {
749   return op->type == operand::OP_C_EXPR;
750 }
751
752 template<>
753 template<>
754 inline bool
755 is_a_helper <expr *>::test (operand *op)
756 {
757   return op->type == operand::OP_EXPR;
758 }
759
760 template<>
761 template<>
762 inline bool
763 is_a_helper <if_expr *>::test (operand *op)
764 {
765   return op->type == operand::OP_IF;
766 }
767
768 template<>
769 template<>
770 inline bool
771 is_a_helper <with_expr *>::test (operand *op)
772 {
773   return op->type == operand::OP_WITH;
774 }
775
776 /* The main class of a pattern and its transform.  This is used to
777    represent both (simplify ...) and (match ...) kinds.  The AST
778    duplicates all outer 'if' and 'for' expressions here so each
779    simplify can exist in isolation.  */
780
781 struct simplify
782 {
783   enum simplify_kind { SIMPLIFY, MATCH };
784
785   simplify (simplify_kind kind_, operand *match_, operand *result_,
786             vec<vec<user_id *> > for_vec_, cid_map_t *capture_ids_)
787       : kind (kind_), match (match_), result (result_),
788       for_vec (for_vec_), for_subst_vec (vNULL),
789       capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
790
791   simplify_kind kind;
792   /* The expression that is matched against the GENERIC or GIMPLE IL.  */
793   operand *match;
794   /* For a (simplify ...) an expression with ifs and withs with the expression
795      produced when the pattern applies in the leafs.
796      For a (match ...) the leafs are either empty if it is a simple predicate
797      or the single expression specifying the matched operands.  */
798   struct operand *result;
799   /* Collected 'for' expression operators that have to be replaced
800      in the lowering phase.  */
801   vec<vec<user_id *> > for_vec;
802   vec<std::pair<user_id *, id_base *> > for_subst_vec;
803   /* A map of capture identifiers to indexes.  */
804   cid_map_t *capture_ids;
805   int capture_max;
806 };
807
808 /* Debugging routines for dumping the AST.  */
809
810 DEBUG_FUNCTION void
811 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
812 {
813   if (capture *c = dyn_cast<capture *> (o))
814     {
815       if (c->what && flattened == false)
816         print_operand (c->what, f, flattened);
817       fprintf (f, "@%u", c->where);
818     }
819
820   else if (predicate *p = dyn_cast<predicate *> (o))
821     fprintf (f, "%s", p->p->id);
822
823   else if (is_a<c_expr *> (o))
824     fprintf (f, "c_expr");
825
826   else if (expr *e = dyn_cast<expr *> (o))
827     {
828       if (e->ops.length () == 0)
829         fprintf (f, "%s", e->operation->id);
830       else
831         {
832           fprintf (f, "(%s", e->operation->id);
833
834           if (flattened == false)
835             {
836               for (unsigned i = 0; i < e->ops.length (); ++i)
837                 {
838                   putc (' ', f);
839                   print_operand (e->ops[i], f, flattened);
840                 }
841             }
842           putc (')', f);
843         }
844     }
845
846   else
847     gcc_unreachable ();
848 }
849
850 DEBUG_FUNCTION void
851 print_matches (struct simplify *s, FILE *f = stderr)
852 {
853   fprintf (f, "for expression: ");
854   print_operand (s->match, f);
855   putc ('\n', f);
856 }
857
858
859 /* AST lowering.  */
860
861 /* Lowering of commutative operators.  */
862
863 static void
864 cartesian_product (const vec< vec<operand *> >& ops_vector,
865                    vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
866 {
867   if (n == ops_vector.length ())
868     {
869       vec<operand *> xv = v.copy ();
870       result.safe_push (xv);
871       return;
872     }
873
874   for (unsigned i = 0; i < ops_vector[n].length (); ++i)
875     {
876       v[n] = ops_vector[n][i];
877       cartesian_product (ops_vector, result, v, n + 1);
878     }
879 }
880
881 /* Lower OP to two operands in case it is marked as commutative.  */
882
883 static vec<operand *>
884 commutate (operand *op, vec<vec<user_id *> > &for_vec)
885 {
886   vec<operand *> ret = vNULL;
887
888   if (capture *c = dyn_cast <capture *> (op))
889     {
890       if (!c->what)
891         {
892           ret.safe_push (op);
893           return ret;
894         }
895       vec<operand *> v = commutate (c->what, for_vec);
896       for (unsigned i = 0; i < v.length (); ++i)
897         {
898           capture *nc = new capture (c->location, c->where, v[i]);
899           ret.safe_push (nc);
900         }
901       return ret;
902     }
903
904   expr *e = dyn_cast <expr *> (op);
905   if (!e || e->ops.length () == 0)
906     {
907       ret.safe_push (op);
908       return ret;
909     }
910
911   vec< vec<operand *> > ops_vector = vNULL;
912   for (unsigned i = 0; i < e->ops.length (); ++i)
913     ops_vector.safe_push (commutate (e->ops[i], for_vec));
914
915   auto_vec< vec<operand *> > result;
916   auto_vec<operand *> v (e->ops.length ());
917   v.quick_grow_cleared (e->ops.length ());
918   cartesian_product (ops_vector, result, v, 0);
919
920
921   for (unsigned i = 0; i < result.length (); ++i)
922     {
923       expr *ne = new expr (e);
924       ne->is_commutative = false;
925       for (unsigned j = 0; j < result[i].length (); ++j)
926         ne->append_op (result[i][j]);
927       ret.safe_push (ne);
928     }
929
930   if (!e->is_commutative)
931     return ret;
932
933   for (unsigned i = 0; i < result.length (); ++i)
934     {
935       expr *ne = new expr (e);
936       if (operator_id *p = dyn_cast <operator_id *> (ne->operation))
937         {
938           if (comparison_code_p (p->code))
939             ne->operation = swap_tree_comparison (p);
940         }
941       else if (user_id *p = dyn_cast <user_id *> (ne->operation))
942         {
943           bool found_compare = false;
944           for (unsigned j = 0; j < p->substitutes.length (); ++j)
945             if (operator_id *q = dyn_cast <operator_id *> (p->substitutes[j]))
946               {
947                 if (comparison_code_p (q->code)
948                     && swap_tree_comparison (q) != q)
949                   {
950                     found_compare = true;
951                     break;
952                   }
953               }
954           if (found_compare)
955             {
956               user_id *newop = new user_id ("<internal>");
957               for (unsigned j = 0; j < p->substitutes.length (); ++j)
958                 {
959                   id_base *subst = p->substitutes[j];
960                   if (operator_id *q = dyn_cast <operator_id *> (subst))
961                     {
962                       if (comparison_code_p (q->code))
963                         subst = swap_tree_comparison (q);
964                     }
965                   newop->substitutes.safe_push (subst);
966                 }
967               ne->operation = newop;
968               /* Search for 'p' inside the for vector and push 'newop'
969                  to the same level.  */
970               for (unsigned j = 0; newop && j < for_vec.length (); ++j)
971                 for (unsigned k = 0; k < for_vec[j].length (); ++k)
972                   if (for_vec[j][k] == p)
973                     {
974                       for_vec[j].safe_push (newop);
975                       newop = NULL;
976                       break;
977                     }
978             }
979         }
980       ne->is_commutative = false;
981       // result[i].length () is 2 since e->operation is binary
982       for (unsigned j = result[i].length (); j; --j)
983         ne->append_op (result[i][j-1]);
984       ret.safe_push (ne);
985     }
986
987   return ret;
988 }
989
990 /* Lower operations marked as commutative in the AST of S and push
991    the resulting patterns to SIMPLIFIERS.  */
992
993 static void
994 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
995 {
996   vec<operand *> matchers = commutate (s->match, s->for_vec);
997   for (unsigned i = 0; i < matchers.length (); ++i)
998     {
999       simplify *ns = new simplify (s->kind, matchers[i], s->result,
1000                                    s->for_vec, s->capture_ids);
1001       simplifiers.safe_push (ns);
1002     }
1003 }
1004
1005 /* Strip conditional conversios using operator OPER from O and its
1006    children if STRIP, else replace them with an unconditional convert.  */
1007
1008 operand *
1009 lower_opt_convert (operand *o, enum tree_code oper,
1010                    enum tree_code to_oper, bool strip)
1011 {
1012   if (capture *c = dyn_cast<capture *> (o))
1013     {
1014       if (c->what)
1015         return new capture (c->location, c->where,
1016                             lower_opt_convert (c->what, oper, to_oper, strip));
1017       else
1018         return c;
1019     }
1020
1021   expr *e = dyn_cast<expr *> (o);
1022   if (!e)
1023     return o;
1024
1025   if (*e->operation == oper)
1026     {
1027       if (strip)
1028         return lower_opt_convert (e->ops[0], oper, to_oper, strip);
1029
1030       expr *ne = new expr (e);
1031       ne->operation = (to_oper == CONVERT_EXPR
1032                        ? get_operator ("CONVERT_EXPR")
1033                        : get_operator ("VIEW_CONVERT_EXPR"));
1034       ne->append_op (lower_opt_convert (e->ops[0], oper, to_oper, strip));
1035       return ne;
1036     }
1037
1038   expr *ne = new expr (e);
1039   for (unsigned i = 0; i < e->ops.length (); ++i)
1040     ne->append_op (lower_opt_convert (e->ops[i], oper, to_oper, strip));
1041
1042   return ne;
1043 }
1044
1045 /* Determine whether O or its children uses the conditional conversion
1046    operator OPER.  */
1047
1048 static bool
1049 has_opt_convert (operand *o, enum tree_code oper)
1050 {
1051   if (capture *c = dyn_cast<capture *> (o))
1052     {
1053       if (c->what)
1054         return has_opt_convert (c->what, oper);
1055       else
1056         return false;
1057     }
1058
1059   expr *e = dyn_cast<expr *> (o);
1060   if (!e)
1061     return false;
1062
1063   if (*e->operation == oper)
1064     return true;
1065
1066   for (unsigned i = 0; i < e->ops.length (); ++i)
1067     if (has_opt_convert (e->ops[i], oper))
1068       return true;
1069
1070   return false;
1071 }
1072
1073 /* Lower conditional convert operators in O, expanding it to a vector
1074    if required.  */
1075
1076 static vec<operand *>
1077 lower_opt_convert (operand *o)
1078 {
1079   vec<operand *> v1 = vNULL, v2;
1080
1081   v1.safe_push (o);
1082
1083   enum tree_code opers[]
1084     = { CONVERT0, CONVERT_EXPR,
1085         CONVERT1, CONVERT_EXPR,
1086         CONVERT2, CONVERT_EXPR,
1087         VIEW_CONVERT0, VIEW_CONVERT_EXPR,
1088         VIEW_CONVERT1, VIEW_CONVERT_EXPR,
1089         VIEW_CONVERT2, VIEW_CONVERT_EXPR };
1090
1091   /* Conditional converts are lowered to a pattern with the
1092      conversion and one without.  The three different conditional
1093      convert codes are lowered separately.  */
1094
1095   for (unsigned i = 0; i < sizeof (opers) / sizeof (enum tree_code); i += 2)
1096     {
1097       v2 = vNULL;
1098       for (unsigned j = 0; j < v1.length (); ++j)
1099         if (has_opt_convert (v1[j], opers[i]))
1100           {
1101             v2.safe_push (lower_opt_convert (v1[j],
1102                                              opers[i], opers[i+1], false));
1103             v2.safe_push (lower_opt_convert (v1[j],
1104                                              opers[i], opers[i+1], true));
1105           }
1106
1107       if (v2 != vNULL)
1108         {
1109           v1 = vNULL;
1110           for (unsigned j = 0; j < v2.length (); ++j)
1111             v1.safe_push (v2[j]);
1112         }
1113     }
1114
1115   return v1;
1116 }
1117
1118 /* Lower conditional convert operators in the AST of S and push
1119    the resulting multiple patterns to SIMPLIFIERS.  */
1120
1121 static void
1122 lower_opt_convert (simplify *s, vec<simplify *>& simplifiers)
1123 {
1124   vec<operand *> matchers = lower_opt_convert (s->match);
1125   for (unsigned i = 0; i < matchers.length (); ++i)
1126     {
1127       simplify *ns = new simplify (s->kind, matchers[i], s->result,
1128                                    s->for_vec, s->capture_ids);
1129       simplifiers.safe_push (ns);
1130     }
1131 }
1132
1133 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1134    GENERIC and a GIMPLE variant.  */
1135
1136 static vec<operand *>
1137 lower_cond (operand *o)
1138 {
1139   vec<operand *> ro = vNULL;
1140
1141   if (capture *c = dyn_cast<capture *> (o))
1142     {
1143       if (c->what)
1144         {
1145           vec<operand *> lop = vNULL;
1146           lop = lower_cond (c->what);
1147
1148           for (unsigned i = 0; i < lop.length (); ++i)
1149             ro.safe_push (new capture (c->location, c->where, lop[i]));
1150           return ro;
1151         }
1152     }
1153
1154   expr *e = dyn_cast<expr *> (o);
1155   if (!e || e->ops.length () == 0)
1156     {
1157       ro.safe_push (o);
1158       return ro;
1159     }
1160
1161   vec< vec<operand *> > ops_vector = vNULL;
1162   for (unsigned i = 0; i < e->ops.length (); ++i)
1163     ops_vector.safe_push (lower_cond (e->ops[i]));
1164
1165   auto_vec< vec<operand *> > result;
1166   auto_vec<operand *> v (e->ops.length ());
1167   v.quick_grow_cleared (e->ops.length ());
1168   cartesian_product (ops_vector, result, v, 0);
1169
1170   for (unsigned i = 0; i < result.length (); ++i)
1171     {
1172       expr *ne = new expr (e);
1173       for (unsigned j = 0; j < result[i].length (); ++j)
1174         ne->append_op (result[i][j]);
1175       ro.safe_push (ne);
1176       /* If this is a COND with a captured expression or an
1177          expression with two operands then also match a GENERIC
1178          form on the compare.  */
1179       if ((*e->operation == COND_EXPR
1180            || *e->operation == VEC_COND_EXPR)
1181           && ((is_a <capture *> (e->ops[0])
1182                && as_a <capture *> (e->ops[0])->what
1183                && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
1184                && as_a <expr *>
1185                     (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
1186               || (is_a <expr *> (e->ops[0])
1187                   && as_a <expr *> (e->ops[0])->ops.length () == 2)))
1188         {
1189           expr *ne = new expr (e);
1190           for (unsigned j = 0; j < result[i].length (); ++j)
1191             ne->append_op (result[i][j]);
1192           if (capture *c = dyn_cast <capture *> (ne->ops[0]))
1193             {
1194               expr *ocmp = as_a <expr *> (c->what);
1195               expr *cmp = new expr (ocmp);
1196               for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1197                 cmp->append_op (ocmp->ops[j]);
1198               cmp->is_generic = true;
1199               ne->ops[0] = new capture (c->location, c->where, cmp);
1200             }
1201           else
1202             {
1203               expr *ocmp = as_a <expr *> (ne->ops[0]);
1204               expr *cmp = new expr (ocmp);
1205               for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1206                 cmp->append_op (ocmp->ops[j]);
1207               cmp->is_generic = true;
1208               ne->ops[0] = cmp;
1209             }
1210           ro.safe_push (ne);
1211         }
1212     }
1213
1214   return ro;
1215 }
1216
1217 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1218    GENERIC and a GIMPLE variant.  */
1219
1220 static void
1221 lower_cond (simplify *s, vec<simplify *>& simplifiers)
1222 {
1223   vec<operand *> matchers = lower_cond (s->match);
1224   for (unsigned i = 0; i < matchers.length (); ++i)
1225     {
1226       simplify *ns = new simplify (s->kind, matchers[i], s->result,
1227                                    s->for_vec, s->capture_ids);
1228       simplifiers.safe_push (ns);
1229     }
1230 }
1231
1232 /* Return true if O refers to ID.  */
1233
1234 bool
1235 contains_id (operand *o, user_id *id)
1236 {
1237   if (capture *c = dyn_cast<capture *> (o))
1238     return c->what && contains_id (c->what, id);
1239
1240   if (expr *e = dyn_cast<expr *> (o))
1241     {
1242       if (e->operation == id)
1243         return true;
1244       for (unsigned i = 0; i < e->ops.length (); ++i)
1245         if (contains_id (e->ops[i], id))
1246           return true;
1247       return false;
1248     }
1249
1250   if (with_expr *w = dyn_cast <with_expr *> (o))
1251     return (contains_id (w->with, id)
1252             || contains_id (w->subexpr, id));
1253
1254   if (if_expr *ife = dyn_cast <if_expr *> (o))
1255     return (contains_id (ife->cond, id)
1256             || contains_id (ife->trueexpr, id)
1257             || (ife->falseexpr && contains_id (ife->falseexpr, id)));
1258
1259   if (c_expr *ce = dyn_cast<c_expr *> (o))
1260     return ce->capture_ids && ce->capture_ids->get (id->id);
1261
1262   return false;
1263 }
1264
1265
1266 /* In AST operand O replace operator ID with operator WITH.  */
1267
1268 operand *
1269 replace_id (operand *o, user_id *id, id_base *with)
1270 {
1271   /* Deep-copy captures and expressions, replacing operations as
1272      needed.  */
1273   if (capture *c = dyn_cast<capture *> (o))
1274     {
1275       if (!c->what)
1276         return c;
1277       return new capture (c->location, c->where,
1278                           replace_id (c->what, id, with));
1279     }
1280   else if (expr *e = dyn_cast<expr *> (o))
1281     {
1282       expr *ne = new expr (e);
1283       if (e->operation == id)
1284         ne->operation = with;
1285       for (unsigned i = 0; i < e->ops.length (); ++i)
1286         ne->append_op (replace_id (e->ops[i], id, with));
1287       return ne;
1288     }
1289   else if (with_expr *w = dyn_cast <with_expr *> (o))
1290     {
1291       with_expr *nw = new with_expr (w->location);
1292       nw->with = as_a <c_expr *> (replace_id (w->with, id, with));
1293       nw->subexpr = replace_id (w->subexpr, id, with);
1294       return nw;
1295     }
1296   else if (if_expr *ife = dyn_cast <if_expr *> (o))
1297     {
1298       if_expr *nife = new if_expr (ife->location);
1299       nife->cond = as_a <c_expr *> (replace_id (ife->cond, id, with));
1300       nife->trueexpr = replace_id (ife->trueexpr, id, with);
1301       if (ife->falseexpr)
1302         nife->falseexpr = replace_id (ife->falseexpr, id, with);
1303       return nife;
1304     }
1305
1306   /* For c_expr we simply record a string replacement table which is
1307      applied at code-generation time.  */
1308   if (c_expr *ce = dyn_cast<c_expr *> (o))
1309     {
1310       vec<c_expr::id_tab> ids = ce->ids.copy ();
1311       ids.safe_push (c_expr::id_tab (id->id, with->id));
1312       return new c_expr (ce->r, ce->location,
1313                          ce->code, ce->nr_stmts, ids, ce->capture_ids);
1314     }
1315
1316   return o;
1317 }
1318
1319 /* Return true if the binary operator OP is ok for delayed substitution
1320    during for lowering.  */
1321
1322 static bool
1323 binary_ok (operator_id *op)
1324 {
1325   switch (op->code)
1326     {
1327     case PLUS_EXPR:
1328     case MINUS_EXPR:
1329     case MULT_EXPR:
1330     case TRUNC_DIV_EXPR:
1331     case CEIL_DIV_EXPR:
1332     case FLOOR_DIV_EXPR:
1333     case ROUND_DIV_EXPR:
1334     case TRUNC_MOD_EXPR:
1335     case CEIL_MOD_EXPR:
1336     case FLOOR_MOD_EXPR:
1337     case ROUND_MOD_EXPR:
1338     case RDIV_EXPR:
1339     case EXACT_DIV_EXPR:
1340     case MIN_EXPR:
1341     case MAX_EXPR:
1342     case BIT_IOR_EXPR:
1343     case BIT_XOR_EXPR:
1344     case BIT_AND_EXPR:
1345       return true;
1346     default:
1347       return false;
1348     }
1349 }
1350
1351 /* Lower recorded fors for SIN and output to SIMPLIFIERS.  */
1352
1353 static void
1354 lower_for (simplify *sin, vec<simplify *>& simplifiers)
1355 {
1356   vec<vec<user_id *> >& for_vec = sin->for_vec;
1357   unsigned worklist_start = 0;
1358   auto_vec<simplify *> worklist;
1359   worklist.safe_push (sin);
1360
1361   /* Lower each recorded for separately, operating on the
1362      set of simplifiers created by the previous one.
1363      Lower inner-to-outer so inner for substitutes can refer
1364      to operators replaced by outer fors.  */
1365   for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1366     {
1367       vec<user_id *>& ids = for_vec[fi];
1368       unsigned n_ids = ids.length ();
1369       unsigned max_n_opers = 0;
1370       bool can_delay_subst = (sin->kind == simplify::SIMPLIFY);
1371       for (unsigned i = 0; i < n_ids; ++i)
1372         {
1373           if (ids[i]->substitutes.length () > max_n_opers)
1374             max_n_opers = ids[i]->substitutes.length ();
1375           /* Require that all substitutes are of the same kind so that
1376              if we delay substitution to the result op code generation
1377              can look at the first substitute for deciding things like
1378              types of operands.  */
1379           enum id_base::id_kind kind = ids[i]->substitutes[0]->kind;
1380           for (unsigned j = 0; j < ids[i]->substitutes.length (); ++j)
1381             if (ids[i]->substitutes[j]->kind != kind)
1382               can_delay_subst = false;
1383             else if (operator_id *op
1384                        = dyn_cast <operator_id *> (ids[i]->substitutes[j]))
1385               {
1386                 operator_id *op0
1387                   = as_a <operator_id *> (ids[i]->substitutes[0]);
1388                 if (strcmp (op->tcc, "tcc_comparison") == 0
1389                     && strcmp (op0->tcc, "tcc_comparison") == 0)
1390                   ;
1391                 /* Unfortunately we can't just allow all tcc_binary.  */
1392                 else if (strcmp (op->tcc, "tcc_binary") == 0
1393                          && strcmp (op0->tcc, "tcc_binary") == 0
1394                          && binary_ok (op)
1395                          && binary_ok (op0))
1396                   ;
1397                 else if ((strcmp (op->id + 1, "SHIFT_EXPR") == 0
1398                           || strcmp (op->id + 1, "ROTATE_EXPR") == 0)
1399                          && (strcmp (op0->id + 1, "SHIFT_EXPR") == 0
1400                              || strcmp (op0->id + 1, "ROTATE_EXPR") == 0))
1401                   ;
1402                 else
1403                   can_delay_subst = false;
1404               }
1405             else if (is_a <fn_id *> (ids[i]->substitutes[j]))
1406               ;
1407             else
1408               can_delay_subst = false;
1409         }
1410
1411       unsigned worklist_end = worklist.length ();
1412       for (unsigned si = worklist_start; si < worklist_end; ++si)
1413         {
1414           simplify *s = worklist[si];
1415           for (unsigned j = 0; j < max_n_opers; ++j)
1416             {
1417               operand *match_op = s->match;
1418               operand *result_op = s->result;
1419               vec<std::pair<user_id *, id_base *> > subst;
1420               subst.create (n_ids);
1421               bool skip = false;
1422               for (unsigned i = 0; i < n_ids; ++i)
1423                 {
1424                   user_id *id = ids[i];
1425                   id_base *oper = id->substitutes[j % id->substitutes.length ()];
1426                   if (oper == null_id
1427                       && (contains_id (match_op, id)
1428                           || contains_id (result_op, id)))
1429                     {
1430                       skip = true;
1431                       break;
1432                     }
1433                   subst.quick_push (std::make_pair (id, oper));
1434                   match_op = replace_id (match_op, id, oper);
1435                   if (result_op
1436                       && !can_delay_subst)
1437                     result_op = replace_id (result_op, id, oper);
1438                 }
1439               if (skip)
1440                 {
1441                   subst.release ();
1442                   continue;
1443                 }
1444               simplify *ns = new simplify (s->kind, match_op, result_op,
1445                                            vNULL, s->capture_ids);
1446               ns->for_subst_vec.safe_splice (s->for_subst_vec);
1447               if (result_op
1448                   && can_delay_subst)
1449                 ns->for_subst_vec.safe_splice (subst);
1450               else
1451                 subst.release ();
1452               worklist.safe_push (ns);
1453             }
1454         }
1455       worklist_start = worklist_end;
1456     }
1457
1458   /* Copy out the result from the last for lowering.  */
1459   for (unsigned i = worklist_start; i < worklist.length (); ++i)
1460     simplifiers.safe_push (worklist[i]);
1461 }
1462
1463 /* Lower the AST for everything in SIMPLIFIERS.  */
1464
1465 static void
1466 lower (vec<simplify *>& simplifiers, bool gimple)
1467 {
1468   auto_vec<simplify *> out_simplifiers;
1469   for (unsigned i = 0; i < simplifiers.length (); ++i)
1470     lower_opt_convert (simplifiers[i], out_simplifiers);
1471
1472   simplifiers.truncate (0);
1473   for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1474     lower_commutative (out_simplifiers[i], simplifiers);
1475
1476   out_simplifiers.truncate (0);
1477   if (gimple)
1478     for (unsigned i = 0; i < simplifiers.length (); ++i)
1479       lower_cond (simplifiers[i], out_simplifiers);
1480   else
1481     out_simplifiers.safe_splice (simplifiers);
1482
1483
1484   simplifiers.truncate (0);
1485   for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1486     lower_for (out_simplifiers[i], simplifiers);
1487 }
1488
1489
1490
1491
1492 /* The decision tree built for generating GIMPLE and GENERIC pattern
1493    matching code.  It represents the 'match' expression of all
1494    simplifies and has those as its leafs.  */
1495
1496 struct dt_simplify;
1497
1498 /* A hash-map collecting semantically equivalent leafs in the decision
1499    tree for splitting out to separate functions.  */
1500 struct sinfo
1501 {
1502   dt_simplify *s;
1503
1504   const char *fname;
1505   unsigned cnt;
1506 };
1507
1508 struct sinfo_hashmap_traits : simple_hashmap_traits<pointer_hash<dt_simplify>,
1509                                                     sinfo *>
1510 {
1511   static inline hashval_t hash (const key_type &);
1512   static inline bool equal_keys (const key_type &, const key_type &);
1513   template <typename T> static inline void remove (T &) {}
1514 };
1515
1516 typedef hash_map<void * /* unused */, sinfo *, sinfo_hashmap_traits>
1517   sinfo_map_t;
1518
1519
1520 /* Decision tree base class, used for DT_TRUE and DT_NODE.  */
1521
1522 struct dt_node
1523 {
1524   enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1525
1526   enum dt_type type;
1527   unsigned level;
1528   vec<dt_node *> kids;
1529
1530   /* Statistics.  */
1531   unsigned num_leafs;
1532   unsigned total_size;
1533   unsigned max_level;
1534
1535   dt_node (enum dt_type type_): type (type_), level (0), kids (vNULL) {}
1536
1537   dt_node *append_node (dt_node *);
1538   dt_node *append_op (operand *, dt_node *parent = 0, unsigned pos = 0);
1539   dt_node *append_true_op (dt_node *parent = 0, unsigned pos = 0);
1540   dt_node *append_match_op (dt_operand *, dt_node *parent = 0, unsigned pos = 0);
1541   dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1542
1543   virtual void gen (FILE *, int, bool) {}
1544
1545   void gen_kids (FILE *, int, bool);
1546   void gen_kids_1 (FILE *, int, bool,
1547                    vec<dt_operand *>, vec<dt_operand *>, vec<dt_operand *>,
1548                    vec<dt_operand *>, vec<dt_operand *>, vec<dt_node *>);
1549
1550   void analyze (sinfo_map_t &);
1551 };
1552
1553 /* Generic decision tree node used for DT_OPERAND and DT_MATCH.  */
1554
1555 struct dt_operand : public dt_node
1556 {
1557   operand *op;
1558   dt_operand *match_dop;
1559   dt_operand *parent;
1560   unsigned pos;
1561
1562   dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1563               dt_operand *parent_ = 0, unsigned pos_ = 0)
1564       : dt_node (type), op (op_), match_dop (match_dop_),
1565       parent (parent_), pos (pos_) {}
1566
1567   void gen (FILE *, int, bool);
1568   unsigned gen_predicate (FILE *, int, const char *, bool);
1569   unsigned gen_match_op (FILE *, int, const char *);
1570
1571   unsigned gen_gimple_expr (FILE *, int);
1572   unsigned gen_generic_expr (FILE *, int, const char *);
1573
1574   char *get_name (char *);
1575   void gen_opname (char *, unsigned);
1576 };
1577
1578 /* Leaf node of the decision tree, used for DT_SIMPLIFY.  */
1579
1580 struct dt_simplify : public dt_node
1581 {
1582   simplify *s;
1583   unsigned pattern_no;
1584   dt_operand **indexes;
1585   sinfo *info;
1586
1587   dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1588         : dt_node (DT_SIMPLIFY), s (s_), pattern_no (pattern_no_),
1589           indexes (indexes_), info (NULL)  {}
1590
1591   void gen_1 (FILE *, int, bool, operand *);
1592   void gen (FILE *f, int, bool);
1593 };
1594
1595 template<>
1596 template<>
1597 inline bool
1598 is_a_helper <dt_operand *>::test (dt_node *n)
1599 {
1600   return (n->type == dt_node::DT_OPERAND
1601           || n->type == dt_node::DT_MATCH);
1602 }
1603
1604 template<>
1605 template<>
1606 inline bool
1607 is_a_helper <dt_simplify *>::test (dt_node *n)
1608 {
1609   return n->type == dt_node::DT_SIMPLIFY;
1610 }
1611
1612
1613
1614 /* A container for the actual decision tree.  */
1615
1616 struct decision_tree
1617 {
1618   dt_node *root;
1619
1620   void insert (struct simplify *, unsigned);
1621   void gen (FILE *f, bool gimple);
1622   void print (FILE *f = stderr);
1623
1624   decision_tree () { root = new dt_node (dt_node::DT_NODE); }
1625
1626   static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1627                                   unsigned pos = 0, dt_node *parent = 0);
1628   static dt_node *find_node (vec<dt_node *>&, dt_node *);
1629   static bool cmp_node (dt_node *, dt_node *);
1630   static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1631 };
1632
1633 /* Compare two AST operands O1 and O2 and return true if they are equal.  */
1634
1635 bool
1636 cmp_operand (operand *o1, operand *o2)
1637 {
1638   if (!o1 || !o2 || o1->type != o2->type)
1639     return false;
1640
1641   if (o1->type == operand::OP_PREDICATE)
1642     {
1643       predicate *p1 = as_a<predicate *>(o1);
1644       predicate *p2 = as_a<predicate *>(o2);
1645       return p1->p == p2->p;
1646     }
1647   else if (o1->type == operand::OP_EXPR)
1648     {
1649       expr *e1 = static_cast<expr *>(o1);
1650       expr *e2 = static_cast<expr *>(o2);
1651       return (e1->operation == e2->operation
1652               && e1->is_generic == e2->is_generic);
1653     }
1654   else
1655     return false;
1656 }
1657
1658 /* Compare two decision tree nodes N1 and N2 and return true if they
1659    are equal.  */
1660
1661 bool
1662 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1663 {
1664   if (!n1 || !n2 || n1->type != n2->type)
1665     return false;
1666
1667   if (n1 == n2)
1668     return true;
1669
1670   if (n1->type == dt_node::DT_TRUE)
1671     return false;
1672
1673   if (n1->type == dt_node::DT_OPERAND)
1674     return cmp_operand ((as_a<dt_operand *> (n1))->op,
1675                         (as_a<dt_operand *> (n2))->op);
1676   else if (n1->type == dt_node::DT_MATCH)
1677     return ((as_a<dt_operand *> (n1))->match_dop
1678             == (as_a<dt_operand *> (n2))->match_dop);
1679   return false;
1680 }
1681
1682 /* Search OPS for a decision tree node like P and return it if found.  */
1683
1684 dt_node *
1685 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1686 {
1687   /* We can merge adjacent DT_TRUE.  */
1688   if (p->type == dt_node::DT_TRUE
1689       && !ops.is_empty ()
1690       && ops.last ()->type == dt_node::DT_TRUE)
1691     return ops.last ();
1692   for (int i = ops.length () - 1; i >= 0; --i)
1693     {
1694       /* But we can't merge across DT_TRUE nodes as they serve as
1695          pattern order barriers to make sure that patterns apply
1696          in order of appearance in case multiple matches are possible.  */
1697       if (ops[i]->type == dt_node::DT_TRUE)
1698         return NULL;
1699       if (decision_tree::cmp_node (ops[i], p))
1700         return ops[i];
1701     }
1702   return NULL;
1703 }
1704
1705 /* Append N to the decision tree if it there is not already an existing
1706    identical child.  */
1707
1708 dt_node *
1709 dt_node::append_node (dt_node *n)
1710 {
1711   dt_node *kid;
1712
1713   kid = decision_tree::find_node (kids, n);
1714   if (kid)
1715     return kid;
1716
1717   kids.safe_push (n);
1718   n->level = this->level + 1;
1719
1720   return n;
1721 }
1722
1723 /* Append OP to the decision tree.  */
1724
1725 dt_node *
1726 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1727 {
1728   dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1729   dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1730   return append_node (n);
1731 }
1732
1733 /* Append a DT_TRUE decision tree node.  */
1734
1735 dt_node *
1736 dt_node::append_true_op (dt_node *parent, unsigned pos)
1737 {
1738   dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1739   dt_operand *n = new dt_operand (DT_TRUE, 0, 0, parent_, pos);
1740   return append_node (n);
1741 }
1742
1743 /* Append a DT_MATCH decision tree node.  */
1744
1745 dt_node *
1746 dt_node::append_match_op (dt_operand *match_dop, dt_node *parent, unsigned pos)
1747 {
1748   dt_operand *parent_ = as_a<dt_operand *> (parent);
1749   dt_operand *n = new dt_operand (DT_MATCH, 0, match_dop, parent_, pos);
1750   return append_node (n);
1751 }
1752
1753 /* Append S to the decision tree.  */
1754
1755 dt_node *
1756 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1757                           dt_operand **indexes)
1758 {
1759   dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1760   for (unsigned i = 0; i < kids.length (); ++i)
1761     if (dt_simplify *s2 = dyn_cast <dt_simplify *> (kids[i]))
1762       {
1763         warning_at (s->match->location, "duplicate pattern");
1764         warning_at (s2->s->match->location, "previous pattern defined here");
1765         print_operand (s->match, stderr);
1766         fprintf (stderr, "\n");
1767       }
1768   return append_node (n);
1769 }
1770
1771 /* Analyze the node and its children.  */
1772
1773 void
1774 dt_node::analyze (sinfo_map_t &map)
1775 {
1776   num_leafs = 0;
1777   total_size = 1;
1778   max_level = level;
1779
1780   if (type == DT_SIMPLIFY)
1781     {
1782       /* Populate the map of equivalent simplifies.  */
1783       dt_simplify *s = as_a <dt_simplify *> (this);
1784       bool existed;
1785       sinfo *&si = map.get_or_insert (s, &existed);
1786       if (!existed)
1787         {
1788           si = new sinfo;
1789           si->s = s;
1790           si->cnt = 1;
1791           si->fname = NULL;
1792         }
1793       else
1794         si->cnt++;
1795       s->info = si;
1796       num_leafs = 1;
1797       return;
1798     }
1799
1800   for (unsigned i = 0; i < kids.length (); ++i)
1801     {
1802       kids[i]->analyze (map);
1803       num_leafs += kids[i]->num_leafs;
1804       total_size += kids[i]->total_size;
1805       max_level = MAX (max_level, kids[i]->max_level);
1806     }
1807 }
1808
1809 /* Insert O into the decision tree and return the decision tree node found
1810    or created.  */
1811
1812 dt_node *
1813 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1814                                unsigned pos, dt_node *parent)
1815 {
1816   dt_node *q, *elm = 0;
1817
1818   if (capture *c = dyn_cast<capture *> (o))
1819     {
1820       unsigned capt_index = c->where;
1821
1822       if (indexes[capt_index] == 0)
1823         {
1824           if (c->what)
1825             q = insert_operand (p, c->what, indexes, pos, parent);
1826           else
1827             {
1828               q = elm = p->append_true_op (parent, pos);
1829               goto at_assert_elm;
1830             }
1831           // get to the last capture
1832           for (operand *what = c->what;
1833                what && is_a<capture *> (what);
1834                c = as_a<capture *> (what), what = c->what)
1835             ;
1836
1837           if (!c->what)
1838             {
1839               unsigned cc_index = c->where;
1840               dt_operand *match_op = indexes[cc_index];
1841
1842               dt_operand temp (dt_node::DT_TRUE, 0, 0);
1843               elm = decision_tree::find_node (p->kids, &temp);
1844
1845               if (elm == 0)
1846                 {
1847                   dt_operand temp (dt_node::DT_MATCH, 0, match_op);
1848                   elm = decision_tree::find_node (p->kids, &temp);
1849                 }
1850             }
1851           else
1852             {
1853               dt_operand temp (dt_node::DT_OPERAND, c->what, 0);
1854               elm = decision_tree::find_node (p->kids, &temp);
1855             }
1856
1857 at_assert_elm:
1858           gcc_assert (elm->type == dt_node::DT_TRUE
1859                       || elm->type == dt_node::DT_OPERAND
1860                       || elm->type == dt_node::DT_MATCH);
1861           indexes[capt_index] = static_cast<dt_operand *> (elm);
1862           return q;
1863         }
1864       else
1865         {
1866           p = p->append_match_op (indexes[capt_index], parent, pos);
1867           if (c->what)
1868             return insert_operand (p, c->what, indexes, 0, p);
1869           else
1870             return p;
1871         }
1872     }
1873   p = p->append_op (o, parent, pos);
1874   q = p;
1875
1876   if (expr *e = dyn_cast <expr *>(o))
1877     {
1878       for (unsigned i = 0; i < e->ops.length (); ++i)
1879         q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
1880     }
1881
1882   return q;
1883 }
1884
1885 /* Insert S into the decision tree.  */
1886
1887 void
1888 decision_tree::insert (struct simplify *s, unsigned pattern_no)
1889 {
1890   dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
1891   dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
1892   p->append_simplify (s, pattern_no, indexes);
1893 }
1894
1895 /* Debug functions to dump the decision tree.  */
1896
1897 DEBUG_FUNCTION void
1898 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
1899 {
1900   if (p->type == dt_node::DT_NODE)
1901     fprintf (f, "root");
1902   else
1903     {
1904       fprintf (f, "|");
1905       for (unsigned i = 0; i < indent; i++)
1906         fprintf (f, "-");
1907
1908       if (p->type == dt_node::DT_OPERAND)
1909         {
1910           dt_operand *dop = static_cast<dt_operand *>(p);
1911           print_operand (dop->op, f, true);
1912         }
1913       else if (p->type == dt_node::DT_TRUE)
1914         fprintf (f, "true");
1915       else if (p->type == dt_node::DT_MATCH)
1916         fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
1917       else if (p->type == dt_node::DT_SIMPLIFY)
1918         {
1919           dt_simplify *s = static_cast<dt_simplify *> (p);
1920           fprintf (f, "simplify_%u { ", s->pattern_no);
1921           for (int i = 0; i <= s->s->capture_max; ++i)
1922             fprintf (f, "%p, ", (void *) s->indexes[i]);
1923           fprintf (f, " } ");
1924         }
1925     }
1926
1927   fprintf (stderr, " (%p), %u, %u\n", (void *) p, p->level, p->kids.length ());
1928
1929   for (unsigned i = 0; i < p->kids.length (); ++i)
1930     decision_tree::print_node (p->kids[i], f, indent + 2);
1931 }
1932
1933 DEBUG_FUNCTION void
1934 decision_tree::print (FILE *f)
1935 {
1936   return decision_tree::print_node (root, f);
1937 }
1938
1939
1940 /* For GENERIC we have to take care of wrapping multiple-used
1941    expressions with side-effects in save_expr and preserve side-effects
1942    of expressions with omit_one_operand.  Analyze captures in
1943    match, result and with expressions and perform early-outs
1944    on the outermost match expression operands for cases we cannot
1945    handle.  */
1946
1947 struct capture_info
1948 {
1949   capture_info (simplify *s, operand *, bool);
1950   void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
1951   bool walk_result (operand *o, bool, operand *);
1952   void walk_c_expr (c_expr *);
1953
1954   struct cinfo
1955     {
1956       bool expr_p;
1957       bool cse_p;
1958       bool force_no_side_effects_p;
1959       bool force_single_use;
1960       bool cond_expr_cond_p;
1961       unsigned long toplevel_msk;
1962       unsigned match_use_count;
1963       unsigned result_use_count;
1964       unsigned same_as;
1965       capture *c;
1966     };
1967
1968   auto_vec<cinfo> info;
1969   unsigned long force_no_side_effects;
1970   bool gimple;
1971 };
1972
1973 /* Analyze captures in S.  */
1974
1975 capture_info::capture_info (simplify *s, operand *result, bool gimple_)
1976 {
1977   gimple = gimple_;
1978
1979   expr *e;
1980   if (s->kind == simplify::MATCH)
1981     {
1982       force_no_side_effects = -1;
1983       return;
1984     }
1985
1986   force_no_side_effects = 0;
1987   info.safe_grow_cleared (s->capture_max + 1);
1988   for (int i = 0; i <= s->capture_max; ++i)
1989     info[i].same_as = i;
1990
1991   e = as_a <expr *> (s->match);
1992   for (unsigned i = 0; i < e->ops.length (); ++i)
1993     walk_match (e->ops[i], i,
1994                 (i != 0 && *e->operation == COND_EXPR)
1995                 || *e->operation == TRUTH_ANDIF_EXPR
1996                 || *e->operation == TRUTH_ORIF_EXPR,
1997                 i == 0
1998                 && (*e->operation == COND_EXPR
1999                     || *e->operation == VEC_COND_EXPR));
2000
2001   walk_result (s->result, false, result);
2002 }
2003
2004 /* Analyze captures in the match expression piece O.  */
2005
2006 void
2007 capture_info::walk_match (operand *o, unsigned toplevel_arg,
2008                           bool conditional_p, bool cond_expr_cond_p)
2009 {
2010   if (capture *c = dyn_cast <capture *> (o))
2011     {
2012       unsigned where = c->where;
2013       info[where].match_use_count++;
2014       info[where].toplevel_msk |= 1 << toplevel_arg;
2015       info[where].force_no_side_effects_p |= conditional_p;
2016       info[where].cond_expr_cond_p |= cond_expr_cond_p;
2017       if (!info[where].c)
2018         info[where].c = c;
2019       if (!c->what)
2020         return;
2021       /* Recurse to exprs and captures.  */
2022       if (is_a <capture *> (c->what)
2023           || is_a <expr *> (c->what))
2024         walk_match (c->what, toplevel_arg, conditional_p, false);
2025       /* We need to look past multiple captures to find a captured
2026          expression as with conditional converts two captures
2027          can be collapsed onto the same expression.  Also collect
2028          what captures capture the same thing.  */
2029       while (c->what && is_a <capture *> (c->what))
2030         {
2031           c = as_a <capture *> (c->what);
2032           if (info[c->where].same_as != c->where
2033               && info[c->where].same_as != info[where].same_as)
2034             fatal_at (c->location, "cannot handle this collapsed capture");
2035           info[c->where].same_as = info[where].same_as;
2036         }
2037       /* Mark expr (non-leaf) captures and forced single-use exprs.  */
2038       expr *e;
2039       if (c->what
2040           && (e = dyn_cast <expr *> (c->what)))
2041         {
2042           info[where].expr_p = true;
2043           info[where].force_single_use |= e->force_single_use;
2044         }
2045     }
2046   else if (expr *e = dyn_cast <expr *> (o))
2047     {
2048       for (unsigned i = 0; i < e->ops.length (); ++i)
2049         {
2050           bool cond_p = conditional_p;
2051           bool cond_expr_cond_p = false;
2052           if (i != 0 && *e->operation == COND_EXPR)
2053             cond_p = true;
2054           else if (*e->operation == TRUTH_ANDIF_EXPR
2055                    || *e->operation == TRUTH_ORIF_EXPR)
2056             cond_p = true;
2057           if (i == 0
2058               && (*e->operation == COND_EXPR
2059                   || *e->operation == VEC_COND_EXPR))
2060             cond_expr_cond_p = true;
2061           walk_match (e->ops[i], toplevel_arg, cond_p, cond_expr_cond_p);
2062         }
2063     }
2064   else if (is_a <predicate *> (o))
2065     {
2066       /* Mark non-captured leafs toplevel arg for checking.  */
2067       force_no_side_effects |= 1 << toplevel_arg;
2068       if (verbose >= 1
2069           && !gimple)
2070         warning_at (o->location,
2071                     "forcing no side-effects on possibly lost leaf");
2072     }
2073   else
2074     gcc_unreachable ();
2075 }
2076
2077 /* Analyze captures in the result expression piece O.  Return true
2078    if RESULT was visited in one of the children.  Only visit
2079    non-if/with children if they are rooted on RESULT.  */
2080
2081 bool
2082 capture_info::walk_result (operand *o, bool conditional_p, operand *result)
2083 {
2084   if (capture *c = dyn_cast <capture *> (o))
2085     {
2086       unsigned where = info[c->where].same_as;
2087       info[where].result_use_count++;
2088       /* If we substitute an expression capture we don't know
2089          which captures this will end up using (well, we don't
2090          compute that).  Force the uses to be side-effect free
2091          which means forcing the toplevels that reach the
2092          expression side-effect free.  */
2093       if (info[where].expr_p)
2094         force_no_side_effects |= info[where].toplevel_msk;
2095       /* Mark CSE capture uses as forced to have no side-effects. */
2096       if (c->what
2097           && is_a <expr *> (c->what))
2098         {
2099           info[where].cse_p = true;
2100           walk_result (c->what, true, result);
2101         }
2102     }
2103   else if (expr *e = dyn_cast <expr *> (o))
2104     {
2105       id_base *opr = e->operation;
2106       if (user_id *uid = dyn_cast <user_id *> (opr))
2107         opr = uid->substitutes[0];
2108       for (unsigned i = 0; i < e->ops.length (); ++i)
2109         {
2110           bool cond_p = conditional_p;
2111           if (i != 0 && *e->operation == COND_EXPR)
2112             cond_p = true;
2113           else if (*e->operation == TRUTH_ANDIF_EXPR
2114                    || *e->operation == TRUTH_ORIF_EXPR)
2115             cond_p = true;
2116           walk_result (e->ops[i], cond_p, result);
2117         }
2118     }
2119   else if (if_expr *e = dyn_cast <if_expr *> (o))
2120     {
2121       /* 'if' conditions should be all fine.  */
2122       if (e->trueexpr == result)
2123         {
2124           walk_result (e->trueexpr, false, result);
2125           return true;
2126         }
2127       if (e->falseexpr == result)
2128         {
2129           walk_result (e->falseexpr, false, result);
2130           return true;
2131         }
2132       bool res = false;
2133       if (is_a <if_expr *> (e->trueexpr)
2134           || is_a <with_expr *> (e->trueexpr))
2135         res |= walk_result (e->trueexpr, false, result);
2136       if (e->falseexpr
2137           && (is_a <if_expr *> (e->falseexpr)
2138               || is_a <with_expr *> (e->falseexpr)))
2139         res |= walk_result (e->falseexpr, false, result);
2140       return res;
2141     }
2142   else if (with_expr *e = dyn_cast <with_expr *> (o))
2143     {
2144       bool res = (e->subexpr == result);
2145       if (res
2146           || is_a <if_expr *> (e->subexpr)
2147           || is_a <with_expr *> (e->subexpr))
2148         res |= walk_result (e->subexpr, false, result);
2149       if (res)
2150         walk_c_expr (e->with);
2151       return res;
2152     }
2153   else if (c_expr *e = dyn_cast <c_expr *> (o))
2154     walk_c_expr (e);
2155   else
2156     gcc_unreachable ();
2157
2158   return false;
2159 }
2160
2161 /* Look for captures in the C expr E.  */
2162
2163 void
2164 capture_info::walk_c_expr (c_expr *e)
2165 {
2166   /* Give up for C exprs mentioning captures not inside TREE_TYPE,
2167      TREE_REAL_CST, TREE_CODE or a predicate where they cannot
2168      really escape through.  */
2169   unsigned p_depth = 0;
2170   for (unsigned i = 0; i < e->code.length (); ++i)
2171     {
2172       const cpp_token *t = &e->code[i];
2173       const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
2174       id_base *id;
2175       if (t->type == CPP_NAME
2176           && (strcmp ((const char *)CPP_HASHNODE
2177                       (t->val.node.node)->ident.str, "TREE_TYPE") == 0
2178               || strcmp ((const char *)CPP_HASHNODE
2179                          (t->val.node.node)->ident.str, "TREE_CODE") == 0
2180               || strcmp ((const char *)CPP_HASHNODE
2181                          (t->val.node.node)->ident.str, "TREE_REAL_CST") == 0
2182               || ((id = get_operator ((const char *)CPP_HASHNODE
2183                                       (t->val.node.node)->ident.str))
2184                   && is_a <predicate_id *> (id)))
2185           && n->type == CPP_OPEN_PAREN)
2186         p_depth++;
2187       else if (t->type == CPP_CLOSE_PAREN
2188                && p_depth > 0)
2189         p_depth--;
2190       else if (p_depth == 0
2191                && t->type == CPP_ATSIGN
2192                && (n->type == CPP_NUMBER
2193                    || n->type == CPP_NAME)
2194                && !(n->flags & PREV_WHITE))
2195         {
2196           const char *id;
2197           if (n->type == CPP_NUMBER)
2198             id = (const char *)n->val.str.text;
2199           else
2200             id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2201           unsigned where = *e->capture_ids->get(id);
2202           info[info[where].same_as].force_no_side_effects_p = true;
2203           if (verbose >= 1
2204               && !gimple)
2205             warning_at (t, "capture escapes");
2206         }
2207     }
2208 }
2209
2210
2211 /* Code generation off the decision tree and the refered AST nodes.  */
2212
2213 bool
2214 is_conversion (id_base *op)
2215 {
2216   return (*op == CONVERT_EXPR
2217           || *op == NOP_EXPR
2218           || *op == FLOAT_EXPR
2219           || *op == FIX_TRUNC_EXPR
2220           || *op == VIEW_CONVERT_EXPR);
2221 }
2222
2223 /* Get the type to be used for generating operands of OP from the
2224    various sources.  */
2225
2226 static const char *
2227 get_operand_type (id_base *op, const char *in_type,
2228                   const char *expr_type,
2229                   const char *other_oprnd_type)
2230 {
2231   /* Generally operands whose type does not match the type of the
2232      expression generated need to know their types but match and
2233      thus can fall back to 'other_oprnd_type'.  */
2234   if (is_conversion (op))
2235     return other_oprnd_type;
2236   else if (*op == REALPART_EXPR
2237            || *op == IMAGPART_EXPR)
2238     return other_oprnd_type;
2239   else if (is_a <operator_id *> (op)
2240            && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
2241     return other_oprnd_type;
2242   else
2243     {
2244       /* Otherwise all types should match - choose one in order of
2245          preference.  */
2246       if (expr_type)
2247         return expr_type;
2248       else if (in_type)
2249         return in_type;
2250       else
2251         return other_oprnd_type;
2252     }
2253 }
2254
2255 /* Generate transform code for an expression.  */
2256
2257 void
2258 expr::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2259                      int depth, const char *in_type, capture_info *cinfo,
2260                      dt_operand **indexes, int)
2261 {
2262   id_base *opr = operation;
2263   /* When we delay operator substituting during lowering of fors we
2264      make sure that for code-gen purposes the effects of each substitute
2265      are the same.  Thus just look at that.  */
2266   if (user_id *uid = dyn_cast <user_id *> (opr))
2267     opr = uid->substitutes[0];
2268
2269   bool conversion_p = is_conversion (opr);
2270   const char *type = expr_type;
2271   char optype[64];
2272   if (type)
2273     /* If there was a type specification in the pattern use it.  */
2274     ;
2275   else if (conversion_p)
2276     /* For conversions we need to build the expression using the
2277        outer type passed in.  */
2278     type = in_type;
2279   else if (*opr == REALPART_EXPR
2280            || *opr == IMAGPART_EXPR)
2281     {
2282       /* __real and __imag use the component type of its operand.  */
2283       sprintf (optype, "TREE_TYPE (TREE_TYPE (ops%d[0]))", depth);
2284       type = optype;
2285     }
2286   else if (is_a <operator_id *> (opr)
2287            && !strcmp (as_a <operator_id *> (opr)->tcc, "tcc_comparison"))
2288     {
2289       /* comparisons use boolean_type_node (or what gets in), but
2290          their operands need to figure out the types themselves.  */
2291       sprintf (optype, "boolean_type_node");
2292       type = optype;
2293     }
2294   else if (*opr == COND_EXPR
2295            || *opr == VEC_COND_EXPR)
2296     {
2297       /* Conditions are of the same type as their first alternative.  */
2298       sprintf (optype, "TREE_TYPE (ops%d[1])", depth);
2299       type = optype;
2300     }
2301   else
2302     {
2303       /* Other operations are of the same type as their first operand.  */
2304       sprintf (optype, "TREE_TYPE (ops%d[0])", depth);
2305       type = optype;
2306     }
2307   if (!type)
2308     fatal_at (location, "cannot determine type of operand");
2309
2310   fprintf_indent (f, indent, "{\n");
2311   indent += 2;
2312   fprintf_indent (f, indent, "tree ops%d[%u], res;\n", depth, ops.length ());
2313   char op0type[64];
2314   snprintf (op0type, 64, "TREE_TYPE (ops%d[0])", depth);
2315   for (unsigned i = 0; i < ops.length (); ++i)
2316     {
2317       char dest[32];
2318       snprintf (dest, 32, "ops%d[%u]", depth, i);
2319       const char *optype
2320         = get_operand_type (opr, in_type, expr_type,
2321                             i == 0 ? NULL : op0type);
2322       ops[i]->gen_transform (f, indent, dest, gimple, depth + 1, optype,
2323                              cinfo, indexes,
2324                              (*opr == COND_EXPR
2325                               || *opr == VEC_COND_EXPR) && i == 0 ? 1 : 2);
2326     }
2327
2328   const char *opr_name;
2329   if (*operation == CONVERT_EXPR)
2330     opr_name = "NOP_EXPR";
2331   else
2332     opr_name = operation->id;
2333
2334   if (gimple)
2335     {
2336       if (*opr == CONVERT_EXPR)
2337         {
2338           fprintf_indent (f, indent,
2339                           "if (%s != TREE_TYPE (ops%d[0])\n",
2340                           type, depth);
2341           fprintf_indent (f, indent,
2342                           "    && !useless_type_conversion_p (%s, TREE_TYPE (ops%d[0])))\n",
2343                           type, depth);
2344           fprintf_indent (f, indent + 2, "{\n");
2345           indent += 4;
2346         }
2347       /* ???  Building a stmt can fail for various reasons here, seq being
2348          NULL or the stmt referencing SSA names occuring in abnormal PHIs.
2349          So if we fail here we should continue matching other patterns.  */
2350       fprintf_indent (f, indent, "code_helper tem_code = %s;\n", opr_name);
2351       fprintf_indent (f, indent, "tree tem_ops[3] = { ");
2352       for (unsigned i = 0; i < ops.length (); ++i)
2353         fprintf (f, "ops%d[%u]%s", depth, i,
2354                  i == ops.length () - 1 ? " };\n" : ", ");
2355       fprintf_indent (f, indent,
2356                       "gimple_resimplify%d (lseq, &tem_code, %s, tem_ops, valueize);\n",
2357                       ops.length (), type);
2358       fprintf_indent (f, indent,
2359                       "res = maybe_push_res_to_seq (tem_code, %s, tem_ops, lseq);\n",
2360                       type);
2361       fprintf_indent (f, indent,
2362                       "if (!res) return false;\n");
2363       if (*opr == CONVERT_EXPR)
2364         {
2365           indent -= 4;
2366           fprintf_indent (f, indent, "  }\n");
2367           fprintf_indent (f, indent, "else\n");
2368           fprintf_indent (f, indent, "  res = ops%d[0];\n", depth);
2369         }
2370     }
2371   else
2372     {
2373       if (*opr == CONVERT_EXPR)
2374         {
2375           fprintf_indent (f, indent, "if (TREE_TYPE (ops%d[0]) != %s)\n",
2376                           depth, type);
2377           indent += 2;
2378         }
2379       if (opr->kind == id_base::CODE)
2380         fprintf_indent (f, indent, "res = fold_build%d_loc (loc, %s, %s",
2381                         ops.length(), opr_name, type);
2382       else
2383         {
2384           fprintf_indent (f, indent, "{\n");
2385           fprintf_indent (f, indent, "  res = maybe_build_call_expr_loc (loc, "
2386                           "%s, %s, %d", opr_name, type, ops.length());
2387         }
2388       for (unsigned i = 0; i < ops.length (); ++i)
2389         fprintf (f, ", ops%d[%u]", depth, i);
2390       fprintf (f, ");\n");
2391       if (opr->kind != id_base::CODE)
2392         {
2393           fprintf_indent (f, indent, "  if (!res)\n");
2394           fprintf_indent (f, indent, "    return NULL_TREE;\n");
2395           fprintf_indent (f, indent, "}\n");
2396         }
2397       if (*opr == CONVERT_EXPR)
2398         {
2399           indent -= 2;
2400           fprintf_indent (f, indent, "else\n");
2401           fprintf_indent (f, indent, "  res = ops%d[0];\n", depth);
2402         }
2403     }
2404   fprintf_indent (f, indent, "%s = res;\n", dest);
2405   indent -= 2;
2406   fprintf_indent (f, indent, "}\n");
2407 }
2408
2409 /* Generate code for a c_expr which is either the expression inside
2410    an if statement or a sequence of statements which computes a
2411    result to be stored to DEST.  */
2412
2413 void
2414 c_expr::gen_transform (FILE *f, int indent, const char *dest,
2415                        bool, int, const char *, capture_info *,
2416                        dt_operand **, int)
2417 {
2418   if (dest && nr_stmts == 1)
2419     fprintf_indent (f, indent, "%s = ", dest);
2420
2421   unsigned stmt_nr = 1;
2422   for (unsigned i = 0; i < code.length (); ++i)
2423     {
2424       const cpp_token *token = &code[i];
2425
2426       /* Replace captures for code-gen.  */
2427       if (token->type == CPP_ATSIGN)
2428         {
2429           const cpp_token *n = &code[i+1];
2430           if ((n->type == CPP_NUMBER
2431                || n->type == CPP_NAME)
2432               && !(n->flags & PREV_WHITE))
2433             {
2434               if (token->flags & PREV_WHITE)
2435                 fputc (' ', f);
2436               const char *id;
2437               if (n->type == CPP_NUMBER)
2438                 id = (const char *)n->val.str.text;
2439               else
2440                 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2441               unsigned *cid = capture_ids->get (id);
2442               if (!cid)
2443                 fatal_at (token, "unknown capture id");
2444               fprintf (f, "captures[%u]", *cid);
2445               ++i;
2446               continue;
2447             }
2448         }
2449
2450       if (token->flags & PREV_WHITE)
2451         fputc (' ', f);
2452
2453       if (token->type == CPP_NAME)
2454         {
2455           const char *id = (const char *) NODE_NAME (token->val.node.node);
2456           unsigned j;
2457           for (j = 0; j < ids.length (); ++j)
2458             {
2459             if (strcmp (id, ids[j].id) == 0)
2460               {
2461                 fprintf (f, "%s", ids[j].oper);
2462                 break;
2463               }
2464             }
2465           if (j < ids.length ())
2466             continue;
2467         }
2468
2469       /* Output the token as string.  */
2470       char *tk = (char *)cpp_token_as_text (r, token);
2471       fputs (tk, f);
2472
2473       if (token->type == CPP_SEMICOLON)
2474         {
2475           stmt_nr++;
2476           fputc ('\n', f);
2477           if (dest && stmt_nr == nr_stmts)
2478             fprintf_indent (f, indent, "%s = ", dest);
2479         }
2480     }
2481 }
2482
2483 /* Generate transform code for a capture.  */
2484
2485 void
2486 capture::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2487                         int depth, const char *in_type, capture_info *cinfo,
2488                         dt_operand **indexes, int cond_handling)
2489 {
2490   if (what && is_a<expr *> (what))
2491     {
2492       if (indexes[where] == 0)
2493         {
2494           char buf[20];
2495           sprintf (buf, "captures[%u]", where);
2496           what->gen_transform (f, indent, buf, gimple, depth, in_type,
2497                                cinfo, NULL);
2498         }
2499     }
2500
2501   fprintf_indent (f, indent, "%s = captures[%u];\n", dest, where);
2502
2503   /* ???  Stupid tcc_comparison GENERIC trees in COND_EXPRs.  Deal
2504      with substituting a capture of that.  */
2505   if (gimple
2506       && cond_handling != 0
2507       && cinfo->info[where].cond_expr_cond_p)
2508     {
2509       /* If substituting into a cond_expr condition, unshare.  */
2510       if (cond_handling == 1)
2511         fprintf_indent (f, indent, "%s = unshare_expr (%s);\n", dest, dest);
2512       /* If substituting elsewhere we might need to decompose it.  */
2513       else if (cond_handling == 2)
2514         {
2515           /* ???  Returning false here will also not allow any other patterns
2516              to match unless this generator was split out.  */
2517           fprintf_indent (f, indent, "if (COMPARISON_CLASS_P (%s))\n", dest);
2518           fprintf_indent (f, indent, "  {\n");
2519           fprintf_indent (f, indent, "    if (!seq) return false;\n");
2520           fprintf_indent (f, indent, "    %s = gimple_build (seq,"
2521                           " TREE_CODE (%s),"
2522                           " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
2523                           " TREE_OPERAND (%s, 1));\n",
2524                           dest, dest, dest, dest, dest);
2525           fprintf_indent (f, indent, "  }\n");
2526         }
2527     }
2528 }
2529
2530 /* Return the name of the operand representing the decision tree node.
2531    Use NAME as space to generate it.  */
2532
2533 char *
2534 dt_operand::get_name (char *name)
2535 {
2536   if (!parent)
2537     sprintf (name, "t");
2538   else if (parent->level == 1)
2539     sprintf (name, "op%u", pos);
2540   else if (parent->type == dt_node::DT_MATCH)
2541     return parent->get_name (name);
2542   else
2543     sprintf (name, "o%u%u", parent->level, pos);
2544   return name;
2545 }
2546
2547 /* Fill NAME with the operand name at position POS.  */
2548
2549 void
2550 dt_operand::gen_opname (char *name, unsigned pos)
2551 {
2552   if (!parent)
2553     sprintf (name, "op%u", pos);
2554   else
2555     sprintf (name, "o%u%u", level, pos);
2556 }
2557
2558 /* Generate matching code for the decision tree operand which is
2559    a predicate.  */
2560
2561 unsigned
2562 dt_operand::gen_predicate (FILE *f, int indent, const char *opname, bool gimple)
2563 {
2564   predicate *p = as_a <predicate *> (op);
2565
2566   if (p->p->matchers.exists ())
2567     {
2568       /* If this is a predicate generated from a pattern mangle its
2569          name and pass on the valueize hook.  */
2570       if (gimple)
2571         fprintf_indent (f, indent, "if (gimple_%s (%s, valueize))\n",
2572                         p->p->id, opname);
2573       else
2574         fprintf_indent (f, indent, "if (tree_%s (%s))\n", p->p->id, opname);
2575     }
2576   else
2577     fprintf_indent (f, indent, "if (%s (%s))\n", p->p->id, opname);
2578   fprintf_indent (f, indent + 2, "{\n");
2579   return 1;
2580 }
2581
2582 /* Generate matching code for the decision tree operand which is
2583    a capture-match.  */
2584
2585 unsigned
2586 dt_operand::gen_match_op (FILE *f, int indent, const char *opname)
2587 {
2588   char match_opname[20];
2589   match_dop->get_name (match_opname);
2590   fprintf_indent (f, indent, "if (%s == %s || operand_equal_p (%s, %s, 0))\n",
2591                   opname, match_opname, opname, match_opname);
2592   fprintf_indent (f, indent + 2, "{\n");
2593   return 1;
2594 }
2595
2596 /* Generate GIMPLE matching code for the decision tree operand.  */
2597
2598 unsigned
2599 dt_operand::gen_gimple_expr (FILE *f, int indent)
2600 {
2601   expr *e = static_cast<expr *> (op);
2602   id_base *id = e->operation;
2603   unsigned n_ops = e->ops.length ();
2604
2605   for (unsigned i = 0; i < n_ops; ++i)
2606     {
2607       char child_opname[20];
2608       gen_opname (child_opname, i);
2609
2610       if (id->kind == id_base::CODE)
2611         {
2612           if (e->is_generic
2613               || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2614               || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
2615             {
2616               /* ???  If this is a memory operation we can't (and should not)
2617                  match this.  The only sensible operand types are
2618                  SSA names and invariants.  */
2619               fprintf_indent (f, indent,
2620                               "tree %s = TREE_OPERAND (gimple_assign_rhs1 (def), %i);\n",
2621                               child_opname, i);
2622               fprintf_indent (f, indent,
2623                               "if ((TREE_CODE (%s) == SSA_NAME\n",
2624                               child_opname);
2625               fprintf_indent (f, indent,
2626                               "     || is_gimple_min_invariant (%s))\n",
2627                               child_opname);
2628               fprintf_indent (f, indent,
2629                               "    && (%s = do_valueize (valueize, %s)))\n",
2630                               child_opname, child_opname);
2631               fprintf_indent (f, indent,
2632                               "  {\n");
2633               indent += 4;
2634               continue;
2635             }
2636           else
2637             fprintf_indent (f, indent,
2638                             "tree %s = gimple_assign_rhs%u (def);\n",
2639                             child_opname, i + 1);
2640         }
2641       else
2642         fprintf_indent (f, indent,
2643                         "tree %s = gimple_call_arg (def, %u);\n",
2644                         child_opname, i);
2645       fprintf_indent (f, indent,
2646                       "if ((%s = do_valueize (valueize, %s)))\n",
2647                       child_opname, child_opname);
2648       fprintf_indent (f, indent, "  {\n");
2649       indent += 4;
2650     }
2651   /* While the toplevel operands are canonicalized by the caller
2652      after valueizing operands of sub-expressions we have to
2653      re-canonicalize operand order.  */
2654   if (operator_id *code = dyn_cast <operator_id *> (id))
2655     {
2656       /* ???  We can't canonicalize tcc_comparison operands here
2657          because that requires changing the comparison code which
2658          we already matched...  */
2659       if (commutative_tree_code (code->code)
2660           || commutative_ternary_tree_code (code->code))
2661         {
2662           char child_opname0[20], child_opname1[20];
2663           gen_opname (child_opname0, 0);
2664           gen_opname (child_opname1, 1);
2665           fprintf_indent (f, indent,
2666                           "if (tree_swap_operands_p (%s, %s, false))\n",
2667                           child_opname0, child_opname1);
2668           fprintf_indent (f, indent,
2669                           "  std::swap (%s, %s);\n",
2670                           child_opname0, child_opname1);
2671         }
2672     }
2673
2674   return n_ops;
2675 }
2676
2677 /* Generate GENERIC matching code for the decision tree operand.  */
2678
2679 unsigned
2680 dt_operand::gen_generic_expr (FILE *f, int indent, const char *opname)
2681 {
2682   expr *e = static_cast<expr *> (op);
2683   unsigned n_ops = e->ops.length ();
2684
2685   for (unsigned i = 0; i < n_ops; ++i)
2686     {
2687       char child_opname[20];
2688       gen_opname (child_opname, i);
2689
2690       if (e->operation->kind == id_base::CODE)
2691         fprintf_indent (f, indent, "tree %s = TREE_OPERAND (%s, %u);\n",
2692                         child_opname, opname, i);
2693       else
2694         fprintf_indent (f, indent, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
2695                         child_opname, opname, i);
2696     }
2697
2698   return 0;
2699 }
2700
2701 /* Generate matching code for the children of the decision tree node.  */
2702
2703 void
2704 dt_node::gen_kids (FILE *f, int indent, bool gimple)
2705 {
2706   auto_vec<dt_operand *> gimple_exprs;
2707   auto_vec<dt_operand *> generic_exprs;
2708   auto_vec<dt_operand *> fns;
2709   auto_vec<dt_operand *> generic_fns;
2710   auto_vec<dt_operand *> preds;
2711   auto_vec<dt_node *> others;
2712
2713   for (unsigned i = 0; i < kids.length (); ++i)
2714     {
2715       if (kids[i]->type == dt_node::DT_OPERAND)
2716         {
2717           dt_operand *op = as_a<dt_operand *> (kids[i]);
2718           if (expr *e = dyn_cast <expr *> (op->op))
2719             {
2720               if (e->ops.length () == 0
2721                   && (!gimple || !(*e->operation == CONSTRUCTOR)))
2722                 generic_exprs.safe_push (op);
2723               else if (e->operation->kind == id_base::FN)
2724                 {
2725                   if (gimple)
2726                     fns.safe_push (op);
2727                   else
2728                     generic_fns.safe_push (op);
2729                 }
2730               else if (e->operation->kind == id_base::PREDICATE)
2731                 preds.safe_push (op);
2732               else
2733                 {
2734                   if (gimple && !e->is_generic)
2735                     gimple_exprs.safe_push (op);
2736                   else
2737                     generic_exprs.safe_push (op);
2738                 }
2739             }
2740           else if (op->op->type == operand::OP_PREDICATE)
2741             others.safe_push (kids[i]);
2742           else
2743             gcc_unreachable ();
2744         }
2745       else if (kids[i]->type == dt_node::DT_SIMPLIFY)
2746         others.safe_push (kids[i]);
2747       else if (kids[i]->type == dt_node::DT_MATCH
2748                || kids[i]->type == dt_node::DT_TRUE)
2749         {
2750           /* A DT_TRUE operand serves as a barrier - generate code now
2751              for what we have collected sofar.
2752              Like DT_TRUE, DT_MATCH serves as a barrier as it can cause
2753              dependent matches to get out-of-order.  Generate code now
2754              for what we have collected sofar.  */
2755           gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2756                       fns, generic_fns, preds, others);
2757           /* And output the true operand itself.  */
2758           kids[i]->gen (f, indent, gimple);
2759           gimple_exprs.truncate (0);
2760           generic_exprs.truncate (0);
2761           fns.truncate (0);
2762           generic_fns.truncate (0);
2763           preds.truncate (0);
2764           others.truncate (0);
2765         }
2766       else
2767         gcc_unreachable ();
2768     }
2769
2770   /* Generate code for the remains.  */
2771   gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2772               fns, generic_fns, preds, others);
2773 }
2774
2775 /* Generate matching code for the children of the decision tree node.  */
2776
2777 void
2778 dt_node::gen_kids_1 (FILE *f, int indent, bool gimple,
2779                      vec<dt_operand *> gimple_exprs,
2780                      vec<dt_operand *> generic_exprs,
2781                      vec<dt_operand *> fns,
2782                      vec<dt_operand *> generic_fns,
2783                      vec<dt_operand *> preds,
2784                      vec<dt_node *> others)
2785 {
2786   char buf[128];
2787   char *kid_opname = buf;
2788
2789   unsigned exprs_len = gimple_exprs.length ();
2790   unsigned gexprs_len = generic_exprs.length ();
2791   unsigned fns_len = fns.length ();
2792   unsigned gfns_len = generic_fns.length ();
2793
2794   if (exprs_len || fns_len || gexprs_len || gfns_len)
2795     {
2796       if (exprs_len)
2797         gimple_exprs[0]->get_name (kid_opname);
2798       else if (fns_len)
2799         fns[0]->get_name (kid_opname);
2800       else if (gfns_len)
2801         generic_fns[0]->get_name (kid_opname);
2802       else
2803         generic_exprs[0]->get_name (kid_opname);
2804
2805       fprintf_indent (f, indent, "switch (TREE_CODE (%s))\n", kid_opname);
2806       fprintf_indent (f, indent, "  {\n");
2807       indent += 2;
2808     }
2809
2810   if (exprs_len || fns_len)
2811     {
2812       fprintf_indent (f, indent,
2813                       "case SSA_NAME:\n");
2814       fprintf_indent (f, indent,
2815                       "  if (do_valueize (valueize, %s) != NULL_TREE)\n",
2816                       kid_opname);
2817       fprintf_indent (f, indent,
2818                       "    {\n");
2819       fprintf_indent (f, indent,
2820                       "      gimple *def_stmt = SSA_NAME_DEF_STMT (%s);\n",
2821                       kid_opname);
2822
2823       indent += 6;
2824       if (exprs_len)
2825         {
2826           fprintf_indent (f, indent,
2827                           "if (gassign *def = dyn_cast <gassign *> (def_stmt))\n");
2828           fprintf_indent (f, indent,
2829                           "  switch (gimple_assign_rhs_code (def))\n");
2830           indent += 4;
2831           fprintf_indent (f, indent, "{\n");
2832           for (unsigned i = 0; i < exprs_len; ++i)
2833             {
2834               expr *e = as_a <expr *> (gimple_exprs[i]->op);
2835               id_base *op = e->operation;
2836               if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2837                 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2838               else
2839                 fprintf_indent (f, indent, "case %s:\n", op->id);
2840               fprintf_indent (f, indent, "  {\n");
2841               gimple_exprs[i]->gen (f, indent + 4, true);
2842               fprintf_indent (f, indent, "    break;\n");
2843               fprintf_indent (f, indent, "  }\n");
2844             }
2845           fprintf_indent (f, indent, "default:;\n");
2846           fprintf_indent (f, indent, "}\n");
2847           indent -= 4;
2848         }
2849
2850       if (fns_len)
2851         {
2852           fprintf_indent (f, indent,
2853                           "%sif (gcall *def = dyn_cast <gcall *>"
2854                           " (def_stmt))\n",
2855                           exprs_len ? "else " : "");
2856           fprintf_indent (f, indent,
2857                           "  switch (gimple_call_combined_fn (def))\n");
2858
2859           indent += 4;
2860           fprintf_indent (f, indent, "{\n");
2861           for (unsigned i = 0; i < fns_len; ++i)
2862             {
2863               expr *e = as_a <expr *>(fns[i]->op);
2864               fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2865               fprintf_indent (f, indent, "  {\n");
2866               fns[i]->gen (f, indent + 4, true);
2867               fprintf_indent (f, indent, "    break;\n");
2868               fprintf_indent (f, indent, "  }\n");
2869             }
2870
2871           fprintf_indent (f, indent, "default:;\n");
2872           fprintf_indent (f, indent, "}\n");
2873           indent -= 4;
2874         }
2875
2876       indent -= 6;
2877       fprintf_indent (f, indent, "    }\n");
2878       fprintf_indent (f, indent, "  break;\n");
2879     }
2880
2881   for (unsigned i = 0; i < generic_exprs.length (); ++i)
2882     {
2883       expr *e = as_a <expr *>(generic_exprs[i]->op);
2884       id_base *op = e->operation;
2885       if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2886         fprintf_indent (f, indent, "CASE_CONVERT:\n");
2887       else
2888         fprintf_indent (f, indent, "case %s:\n", op->id);
2889       fprintf_indent (f, indent, "  {\n");
2890       generic_exprs[i]->gen (f, indent + 4, gimple);
2891       fprintf_indent (f, indent, "    break;\n");
2892       fprintf_indent (f, indent, "  }\n");
2893     }
2894
2895   if (gfns_len)
2896     {
2897       fprintf_indent (f, indent,
2898                       "case CALL_EXPR:\n");
2899       fprintf_indent (f, indent,
2900                       "  switch (get_call_combined_fn (%s))\n",
2901                       kid_opname);
2902       fprintf_indent (f, indent,
2903                       "    {\n");
2904       indent += 4;
2905
2906       for (unsigned j = 0; j < generic_fns.length (); ++j)
2907         {
2908           expr *e = as_a <expr *>(generic_fns[j]->op);
2909           gcc_assert (e->operation->kind == id_base::FN);
2910
2911           fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2912           fprintf_indent (f, indent, "  {\n");
2913           generic_fns[j]->gen (f, indent + 4, false);
2914           fprintf_indent (f, indent, "    break;\n");
2915           fprintf_indent (f, indent, "  }\n");
2916         }
2917       fprintf_indent (f, indent, "default:;\n");
2918
2919       indent -= 4;
2920       fprintf_indent (f, indent, "    }\n");
2921       fprintf_indent (f, indent, "  break;\n");
2922     }
2923
2924   /* Close switch (TREE_CODE ()).  */
2925   if (exprs_len || fns_len || gexprs_len || gfns_len)
2926     {
2927       indent -= 4;
2928       fprintf_indent (f, indent, "    default:;\n");
2929       fprintf_indent (f, indent, "    }\n");
2930     }
2931
2932   for (unsigned i = 0; i < preds.length (); ++i)
2933     {
2934       expr *e = as_a <expr *> (preds[i]->op);
2935       predicate_id *p = as_a <predicate_id *> (e->operation);
2936       preds[i]->get_name (kid_opname);
2937       fprintf_indent (f, indent, "tree %s_pops[%d];\n", kid_opname, p->nargs);
2938       fprintf_indent (f, indent, "if (%s_%s (%s, %s_pops%s))\n",
2939                gimple ? "gimple" : "tree",
2940                p->id, kid_opname, kid_opname,
2941                gimple ? ", valueize" : "");
2942       fprintf_indent (f, indent, "  {\n");
2943       for (int j = 0; j < p->nargs; ++j)
2944         {
2945           char child_opname[20];
2946           preds[i]->gen_opname (child_opname, j);
2947           fprintf_indent (f, indent + 4, "tree %s = %s_pops[%d];\n",
2948                           child_opname, kid_opname, j);
2949         }
2950       preds[i]->gen_kids (f, indent + 4, gimple);
2951       fprintf (f, "}\n");
2952     }
2953
2954   for (unsigned i = 0; i < others.length (); ++i)
2955     others[i]->gen (f, indent, gimple);
2956 }
2957
2958 /* Generate matching code for the decision tree operand.  */
2959
2960 void
2961 dt_operand::gen (FILE *f, int indent, bool gimple)
2962 {
2963   char opname[20];
2964   get_name (opname);
2965
2966   unsigned n_braces = 0;
2967
2968   if (type == DT_OPERAND)
2969     switch (op->type)
2970       {
2971         case operand::OP_PREDICATE:
2972           n_braces = gen_predicate (f, indent, opname, gimple);
2973           break;
2974
2975         case operand::OP_EXPR:
2976           if (gimple)
2977             n_braces = gen_gimple_expr (f, indent);
2978           else
2979             n_braces = gen_generic_expr (f, indent, opname);
2980           break;
2981
2982         default:
2983           gcc_unreachable ();
2984       }
2985   else if (type == DT_TRUE)
2986     ;
2987   else if (type == DT_MATCH)
2988     n_braces = gen_match_op (f, indent, opname);
2989   else
2990     gcc_unreachable ();
2991
2992   indent += 4 * n_braces;
2993   gen_kids (f, indent, gimple);
2994
2995   for (unsigned i = 0; i < n_braces; ++i)
2996     {
2997       indent -= 4;
2998       if (indent < 0)
2999         indent = 0;
3000       fprintf_indent (f, indent, "  }\n");
3001     }
3002 }
3003
3004
3005 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3006    step of a '(simplify ...)' or '(match ...)'.  This handles everything
3007    that is not part of the decision tree (simplify->match).
3008    Main recursive worker.  */
3009
3010 void
3011 dt_simplify::gen_1 (FILE *f, int indent, bool gimple, operand *result)
3012 {
3013   if (result)
3014     {
3015       if (with_expr *w = dyn_cast <with_expr *> (result))
3016         {
3017           fprintf_indent (f, indent, "{\n");
3018           indent += 4;
3019           output_line_directive (f, w->location);
3020           w->with->gen_transform (f, indent, NULL, true, 1, "type", NULL);
3021           gen_1 (f, indent, gimple, w->subexpr);
3022           indent -= 4;
3023           fprintf_indent (f, indent, "}\n");
3024           return;
3025         }
3026       else if (if_expr *ife = dyn_cast <if_expr *> (result))
3027         {
3028           output_line_directive (f, ife->location);
3029           fprintf_indent (f, indent, "if (");
3030           ife->cond->gen_transform (f, indent, NULL, true, 1, "type", NULL);
3031           fprintf (f, ")\n");
3032           fprintf_indent (f, indent + 2, "{\n");
3033           indent += 4;
3034           gen_1 (f, indent, gimple, ife->trueexpr);
3035           indent -= 4;
3036           fprintf_indent (f, indent + 2, "}\n");
3037           if (ife->falseexpr)
3038             {
3039               fprintf_indent (f, indent, "else\n");
3040               fprintf_indent (f, indent + 2, "{\n");
3041               indent += 4;
3042               gen_1 (f, indent, gimple, ife->falseexpr);
3043               indent -= 4;
3044               fprintf_indent (f, indent + 2, "}\n");
3045             }
3046           return;
3047         }
3048     }
3049
3050   /* Analyze captures and perform early-outs on the incoming arguments
3051      that cover cases we cannot handle.  */
3052   capture_info cinfo (s, result, gimple);
3053   if (s->kind == simplify::SIMPLIFY)
3054     {
3055       if (!gimple)
3056         {
3057           for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3058             if (cinfo.force_no_side_effects & (1 << i))
3059               {
3060                 fprintf_indent (f, indent,
3061                                 "if (TREE_SIDE_EFFECTS (op%d)) return NULL_TREE;\n",
3062                                 i);
3063                 if (verbose >= 1)
3064                   warning_at (as_a <expr *> (s->match)->ops[i]->location,
3065                               "forcing toplevel operand to have no "
3066                               "side-effects");
3067               }
3068           for (int i = 0; i <= s->capture_max; ++i)
3069             if (cinfo.info[i].cse_p)
3070               ;
3071             else if (cinfo.info[i].force_no_side_effects_p
3072                      && (cinfo.info[i].toplevel_msk
3073                          & cinfo.force_no_side_effects) == 0)
3074               {
3075                 fprintf_indent (f, indent,
3076                                 "if (TREE_SIDE_EFFECTS (captures[%d])) "
3077                                 "return NULL_TREE;\n", i);
3078                 if (verbose >= 1)
3079                   warning_at (cinfo.info[i].c->location,
3080                               "forcing captured operand to have no "
3081                               "side-effects");
3082               }
3083             else if ((cinfo.info[i].toplevel_msk
3084                       & cinfo.force_no_side_effects) != 0)
3085               /* Mark capture as having no side-effects if we had to verify
3086                  that via forced toplevel operand checks.  */
3087               cinfo.info[i].force_no_side_effects_p = true;
3088         }
3089       if (gimple)
3090         {
3091           /* Force single-use restriction by only allowing simple
3092              results via setting seq to NULL.  */
3093           fprintf_indent (f, indent, "gimple_seq *lseq = seq;\n");
3094           bool first_p = true;
3095           for (int i = 0; i <= s->capture_max; ++i)
3096             if (cinfo.info[i].force_single_use)
3097               {
3098                 if (first_p)
3099                   {
3100                     fprintf_indent (f, indent, "if (lseq\n");
3101                     fprintf_indent (f, indent, "    && (");
3102                     first_p = false;
3103                   }
3104                 else
3105                   {
3106                     fprintf (f, "\n");
3107                     fprintf_indent (f, indent, "        || ");
3108                   }
3109                 fprintf (f, "!single_use (captures[%d])", i);
3110               }
3111           if (!first_p)
3112             {
3113               fprintf (f, "))\n");
3114               fprintf_indent (f, indent, "  lseq = NULL;\n");
3115             }
3116         }
3117     }
3118
3119   fprintf_indent (f, indent, "if (dump_file && (dump_flags & TDF_DETAILS)) "
3120            "fprintf (dump_file, \"Applying pattern ");
3121   output_line_directive (f,
3122                          result ? result->location : s->match->location, true);
3123   fprintf (f, ", %%s:%%d\\n\", __FILE__, __LINE__);\n");
3124
3125   if (!result)
3126     {
3127       /* If there is no result then this is a predicate implementation.  */
3128       fprintf_indent (f, indent, "return true;\n");
3129     }
3130   else if (gimple)
3131     {
3132       /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
3133          in outermost position).  */
3134       if (result->type == operand::OP_EXPR
3135           && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
3136         result = as_a <expr *> (result)->ops[0];
3137       if (result->type == operand::OP_EXPR)
3138         {
3139           expr *e = as_a <expr *> (result);
3140           id_base *opr = e->operation;
3141           bool is_predicate = false;
3142           /* When we delay operator substituting during lowering of fors we
3143              make sure that for code-gen purposes the effects of each substitute
3144              are the same.  Thus just look at that.  */
3145           if (user_id *uid = dyn_cast <user_id *> (opr))
3146             opr = uid->substitutes[0];
3147           else if (is_a <predicate_id *> (opr))
3148             is_predicate = true;
3149           if (!is_predicate)
3150             fprintf_indent (f, indent, "*res_code = %s;\n",
3151                             *e->operation == CONVERT_EXPR
3152                             ? "NOP_EXPR" : e->operation->id);
3153           for (unsigned j = 0; j < e->ops.length (); ++j)
3154             {
3155               char dest[32];
3156               snprintf (dest, 32, "res_ops[%d]", j);
3157               const char *optype
3158                 = get_operand_type (opr,
3159                                     "type", e->expr_type,
3160                                     j == 0 ? NULL : "TREE_TYPE (res_ops[0])");
3161               /* We need to expand GENERIC conditions we captured from
3162                  COND_EXPRs and we need to unshare them when substituting
3163                  into COND_EXPRs.  */
3164               int cond_handling = 0;
3165               if (!is_predicate)
3166                 cond_handling = ((*opr == COND_EXPR
3167                                   || *opr == VEC_COND_EXPR) && j == 0) ? 1 : 2;
3168               e->ops[j]->gen_transform (f, indent, dest, true, 1, optype,
3169                                         &cinfo, indexes, cond_handling);
3170             }
3171
3172           /* Re-fold the toplevel result.  It's basically an embedded
3173              gimple_build w/o actually building the stmt.  */
3174           if (!is_predicate)
3175             fprintf_indent (f, indent,
3176                             "gimple_resimplify%d (lseq, res_code, type, "
3177                             "res_ops, valueize);\n", e->ops.length ());
3178         }
3179       else if (result->type == operand::OP_CAPTURE
3180                || result->type == operand::OP_C_EXPR)
3181         {
3182           result->gen_transform (f, indent, "res_ops[0]", true, 1, "type",
3183                                  &cinfo, indexes);
3184           fprintf_indent (f, indent, "*res_code = TREE_CODE (res_ops[0]);\n");
3185           if (is_a <capture *> (result)
3186               && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
3187             {
3188               /* ???  Stupid tcc_comparison GENERIC trees in COND_EXPRs.  Deal
3189                  with substituting a capture of that.  */
3190               fprintf_indent (f, indent,
3191                               "if (COMPARISON_CLASS_P (res_ops[0]))\n");
3192               fprintf_indent (f, indent,
3193                               "  {\n");
3194               fprintf_indent (f, indent,
3195                               "    tree tem = res_ops[0];\n");
3196               fprintf_indent (f, indent,
3197                               "    res_ops[0] = TREE_OPERAND (tem, 0);\n");
3198               fprintf_indent (f, indent,
3199                               "    res_ops[1] = TREE_OPERAND (tem, 1);\n");
3200               fprintf_indent (f, indent,
3201                               "  }\n");
3202             }
3203         }
3204       else
3205         gcc_unreachable ();
3206       fprintf_indent (f, indent, "return true;\n");
3207     }
3208   else /* GENERIC */
3209     {
3210       bool is_predicate = false;
3211       if (result->type == operand::OP_EXPR)
3212         {
3213           expr *e = as_a <expr *> (result);
3214           id_base *opr = e->operation;
3215           /* When we delay operator substituting during lowering of fors we
3216              make sure that for code-gen purposes the effects of each substitute
3217              are the same.  Thus just look at that.  */
3218           if (user_id *uid = dyn_cast <user_id *> (opr))
3219             opr = uid->substitutes[0];
3220           else if (is_a <predicate_id *> (opr))
3221             is_predicate = true;
3222           /* Search for captures used multiple times in the result expression
3223              and wrap them in a SAVE_EXPR.  Allow as many uses as in the
3224              original expression.  */
3225           if (!is_predicate)
3226             for (int i = 0; i < s->capture_max + 1; ++i)
3227               {
3228                 if (cinfo.info[i].same_as != (unsigned)i
3229                     || cinfo.info[i].cse_p)
3230                   continue;
3231                 if (cinfo.info[i].result_use_count
3232                     > cinfo.info[i].match_use_count)
3233                   fprintf_indent (f, indent,
3234                                   "if (! tree_invariant_p (captures[%d])) "
3235                                   "return NULL_TREE;\n", i);
3236               }
3237           for (unsigned j = 0; j < e->ops.length (); ++j)
3238             {
3239               char dest[32];
3240               if (is_predicate)
3241                 snprintf (dest, 32, "res_ops[%d]", j);
3242               else
3243                 {
3244                   fprintf_indent (f, indent, "tree res_op%d;\n", j);
3245                   snprintf (dest, 32, "res_op%d", j);
3246                 }
3247               const char *optype
3248                 = get_operand_type (opr,
3249                                     "type", e->expr_type,
3250                                     j == 0
3251                                     ? NULL : "TREE_TYPE (res_op0)");
3252               e->ops[j]->gen_transform (f, indent, dest, false, 1, optype,
3253                                         &cinfo, indexes);
3254             }
3255           if (is_predicate)
3256             fprintf_indent (f, indent, "return true;\n");
3257           else
3258             {
3259               fprintf_indent (f, indent, "tree res;\n");
3260               /* Re-fold the toplevel result.  Use non_lvalue to
3261                  build NON_LVALUE_EXPRs so they get properly
3262                  ignored when in GIMPLE form.  */
3263               if (*opr == NON_LVALUE_EXPR)
3264                 fprintf_indent (f, indent,
3265                                 "res = non_lvalue_loc (loc, res_op0);\n");
3266               else
3267                 {
3268                   if (is_a <operator_id *> (opr))
3269                     fprintf_indent (f, indent,
3270                                     "res = fold_build%d_loc (loc, %s, type",
3271                                     e->ops.length (),
3272                                     *e->operation == CONVERT_EXPR
3273                                     ? "NOP_EXPR" : e->operation->id);
3274                   else
3275                     fprintf_indent (f, indent,
3276                                     "res = maybe_build_call_expr_loc (loc, "
3277                                     "%s, type, %d", e->operation->id,
3278                                     e->ops.length());
3279                   for (unsigned j = 0; j < e->ops.length (); ++j)
3280                     fprintf (f, ", res_op%d", j);
3281                   fprintf (f, ");\n");
3282                   if (!is_a <operator_id *> (opr))
3283                     {
3284                       fprintf_indent (f, indent, "if (!res)\n");
3285                       fprintf_indent (f, indent, "  return NULL_TREE;\n");
3286                     }
3287                 }
3288             }
3289         }
3290       else if (result->type == operand::OP_CAPTURE
3291                || result->type == operand::OP_C_EXPR)
3292
3293         {
3294           fprintf_indent (f, indent, "tree res;\n");
3295           result->gen_transform (f, indent, "res", false, 1, "type",
3296                                     &cinfo, indexes);
3297         }
3298       else
3299         gcc_unreachable ();
3300       if (!is_predicate)
3301         {
3302           /* Search for captures not used in the result expression and dependent
3303              on TREE_SIDE_EFFECTS emit omit_one_operand.  */
3304           for (int i = 0; i < s->capture_max + 1; ++i)
3305             {
3306               if (cinfo.info[i].same_as != (unsigned)i)
3307                 continue;
3308               if (!cinfo.info[i].force_no_side_effects_p
3309                   && !cinfo.info[i].expr_p
3310                   && cinfo.info[i].result_use_count == 0)
3311                 {
3312                   fprintf_indent (f, indent,
3313                                   "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
3314                                   i);
3315                   fprintf_indent (f, indent + 2,
3316                                   "res = build2_loc (loc, COMPOUND_EXPR, type, "
3317                                   "fold_ignored_result (captures[%d]), res);\n",
3318                                   i);
3319                 }
3320             }
3321           fprintf_indent (f, indent, "return res;\n");
3322         }
3323     }
3324 }
3325
3326 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3327    step of a '(simplify ...)' or '(match ...)'.  This handles everything
3328    that is not part of the decision tree (simplify->match).  */
3329
3330 void
3331 dt_simplify::gen (FILE *f, int indent, bool gimple)
3332 {
3333   fprintf_indent (f, indent, "{\n");
3334   indent += 2;
3335   output_line_directive (f,
3336                          s->result ? s->result->location : s->match->location);
3337   if (s->capture_max >= 0)
3338     {
3339       char opname[20];
3340       fprintf_indent (f, indent, "tree captures[%u] ATTRIBUTE_UNUSED = { %s",
3341                       s->capture_max + 1, indexes[0]->get_name (opname));
3342
3343       for (int i = 1; i <= s->capture_max; ++i)
3344         {
3345           if (!indexes[i])
3346             break;
3347           fprintf (f, ", %s", indexes[i]->get_name (opname));
3348         }
3349       fprintf (f, " };\n");
3350     }
3351
3352   /* If we have a split-out function for the actual transform, call it.  */
3353   if (info && info->fname)
3354     {
3355       if (gimple)
3356         {
3357           fprintf_indent (f, indent, "if (%s (res_code, res_ops, seq, "
3358                           "valueize, type, captures", info->fname);
3359           for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3360             if (s->for_subst_vec[i].first->used)
3361               fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3362           fprintf (f, "))\n");
3363           fprintf_indent (f, indent, "  return true;\n");
3364         }
3365       else
3366         {
3367           fprintf_indent (f, indent, "tree res = %s (loc, type",
3368                           info->fname);
3369           for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3370             fprintf (f, ", op%d", i);
3371           fprintf (f, ", captures");
3372           for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3373             {
3374               if (s->for_subst_vec[i].first->used)
3375                 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3376             }
3377           fprintf (f, ");\n");
3378           fprintf_indent (f, indent, "if (res) return res;\n");
3379         }
3380     }
3381   else
3382     {
3383       for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3384         {
3385           if (! s->for_subst_vec[i].first->used)
3386             continue;
3387           if (is_a <operator_id *> (s->for_subst_vec[i].second))
3388             fprintf_indent (f, indent, "enum tree_code %s = %s;\n",
3389                             s->for_subst_vec[i].first->id,
3390                             s->for_subst_vec[i].second->id);
3391           else if (is_a <fn_id *> (s->for_subst_vec[i].second))
3392             fprintf_indent (f, indent, "combined_fn %s = %s;\n",
3393                             s->for_subst_vec[i].first->id,
3394                             s->for_subst_vec[i].second->id);
3395           else
3396             gcc_unreachable ();
3397         }
3398       gen_1 (f, indent, gimple, s->result);
3399     }
3400
3401   indent -= 2;
3402   fprintf_indent (f, indent, "}\n");
3403 }
3404
3405
3406 /* Hash function for finding equivalent transforms.  */
3407
3408 hashval_t
3409 sinfo_hashmap_traits::hash (const key_type &v)
3410 {
3411   /* Only bother to compare those originating from the same source pattern.  */
3412   return v->s->result->location;
3413 }
3414
3415 /* Compare function for finding equivalent transforms.  */
3416
3417 static bool
3418 compare_op (operand *o1, simplify *s1, operand *o2, simplify *s2)
3419 {
3420   if (o1->type != o2->type)
3421     return false;
3422
3423   switch (o1->type)
3424     {
3425     case operand::OP_IF:
3426       {
3427         if_expr *if1 = as_a <if_expr *> (o1);
3428         if_expr *if2 = as_a <if_expr *> (o2);
3429         /* ???  Properly compare c-exprs.  */
3430         if (if1->cond != if2->cond)
3431           return false;
3432         if (!compare_op (if1->trueexpr, s1, if2->trueexpr, s2))
3433           return false;
3434         if (if1->falseexpr != if2->falseexpr
3435             || (if1->falseexpr
3436                 && !compare_op (if1->falseexpr, s1, if2->falseexpr, s2)))
3437           return false;
3438         return true;
3439       }
3440     case operand::OP_WITH:
3441       {
3442         with_expr *with1 = as_a <with_expr *> (o1);
3443         with_expr *with2 = as_a <with_expr *> (o2);
3444         if (with1->with != with2->with)
3445           return false;
3446         return compare_op (with1->subexpr, s1, with2->subexpr, s2);
3447       }
3448     default:;
3449     }
3450
3451   /* We've hit a result.  Time to compare capture-infos - this is required
3452      in addition to the conservative pointer-equivalency of the result IL.  */
3453   capture_info cinfo1 (s1, o1, true);
3454   capture_info cinfo2 (s2, o2, true);
3455
3456   if (cinfo1.force_no_side_effects != cinfo2.force_no_side_effects
3457       || cinfo1.info.length () != cinfo2.info.length ())
3458     return false;
3459
3460   for (unsigned i = 0; i < cinfo1.info.length (); ++i)
3461     {
3462       if (cinfo1.info[i].expr_p != cinfo2.info[i].expr_p
3463           || cinfo1.info[i].cse_p != cinfo2.info[i].cse_p
3464           || (cinfo1.info[i].force_no_side_effects_p
3465               != cinfo2.info[i].force_no_side_effects_p)
3466           || cinfo1.info[i].force_single_use != cinfo2.info[i].force_single_use
3467           || cinfo1.info[i].cond_expr_cond_p != cinfo2.info[i].cond_expr_cond_p
3468           /* toplevel_msk is an optimization */
3469           || cinfo1.info[i].result_use_count != cinfo2.info[i].result_use_count
3470           || cinfo1.info[i].same_as != cinfo2.info[i].same_as
3471           /* the pointer back to the capture is for diagnostics only */)
3472         return false;
3473     }
3474
3475   /* ???  Deep-compare the actual result.  */
3476   return o1 == o2;
3477 }
3478
3479 bool
3480 sinfo_hashmap_traits::equal_keys (const key_type &v,
3481                                   const key_type &candidate)
3482 {
3483   return compare_op (v->s->result, v->s, candidate->s->result, candidate->s);
3484 }
3485
3486
3487 /* Main entry to generate code for matching GIMPLE IL off the decision
3488    tree.  */
3489
3490 void
3491 decision_tree::gen (FILE *f, bool gimple)
3492 {
3493   sinfo_map_t si;
3494
3495   root->analyze (si);
3496
3497   fprintf (stderr, "%s decision tree has %u leafs, maximum depth %u and "
3498            "a total number of %u nodes\n",
3499            gimple ? "GIMPLE" : "GENERIC", 
3500            root->num_leafs, root->max_level, root->total_size);
3501
3502   /* First split out the transform part of equal leafs.  */
3503   unsigned rcnt = 0;
3504   unsigned fcnt = 1;
3505   for (sinfo_map_t::iterator iter = si.begin ();
3506        iter != si.end (); ++iter)
3507     {
3508       sinfo *s = (*iter).second;
3509       /* Do not split out single uses.  */
3510       if (s->cnt <= 1)
3511         continue;
3512
3513       rcnt += s->cnt - 1;
3514       if (verbose >= 1)
3515         {
3516           fprintf (stderr, "found %u uses of", s->cnt);
3517           output_line_directive (stderr, s->s->s->result->location);
3518         }
3519
3520       /* Generate a split out function with the leaf transform code.  */
3521       s->fname = xasprintf ("%s_simplify_%u", gimple ? "gimple" : "generic",
3522                             fcnt++);
3523       if (gimple)
3524         fprintf (f, "\nstatic bool\n"
3525                  "%s (code_helper *res_code, tree *res_ops,\n"
3526                  "                 gimple_seq *seq, tree (*valueize)(tree) "
3527                  "ATTRIBUTE_UNUSED,\n"
3528                  "                 tree ARG_UNUSED (type), tree *ARG_UNUSED "
3529                  "(captures)\n",
3530                  s->fname);
3531       else
3532         {
3533           fprintf (f, "\nstatic tree\n"
3534                    "%s (location_t ARG_UNUSED (loc), tree ARG_UNUSED (type),\n",
3535                    (*iter).second->fname);
3536           for (unsigned i = 0;
3537                i < as_a <expr *>(s->s->s->match)->ops.length (); ++i)
3538             fprintf (f, " tree ARG_UNUSED (op%d),", i);
3539           fprintf (f, " tree *captures\n");
3540         }
3541       for (unsigned i = 0; i < s->s->s->for_subst_vec.length (); ++i)
3542         {
3543           if (! s->s->s->for_subst_vec[i].first->used)
3544             continue;
3545           if (is_a <operator_id *> (s->s->s->for_subst_vec[i].second))
3546             fprintf (f, ", enum tree_code ARG_UNUSED (%s)",
3547                      s->s->s->for_subst_vec[i].first->id);
3548           else if (is_a <fn_id *> (s->s->s->for_subst_vec[i].second))
3549             fprintf (f, ", combined_fn ARG_UNUSED (%s)",
3550                      s->s->s->for_subst_vec[i].first->id);
3551         }
3552
3553       fprintf (f, ")\n{\n");
3554       s->s->gen_1 (f, 2, gimple, s->s->s->result);
3555       if (gimple)
3556         fprintf (f, "  return false;\n");
3557       else
3558         fprintf (f, "  return NULL_TREE;\n");
3559       fprintf (f, "}\n");
3560     }
3561   fprintf (stderr, "removed %u duplicate tails\n", rcnt);
3562
3563   for (unsigned n = 1; n <= 3; ++n)
3564     {
3565       /* First generate split-out functions.  */
3566       for (unsigned i = 0; i < root->kids.length (); i++)
3567         {
3568           dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3569           expr *e = static_cast<expr *>(dop->op);
3570           if (e->ops.length () != n
3571               /* Builtin simplifications are somewhat premature on
3572                  GENERIC.  The following drops patterns with outermost
3573                  calls.  It's easy to emit overloads for function code
3574                  though if necessary.  */
3575               || (!gimple
3576                   && e->operation->kind != id_base::CODE))
3577             continue;
3578
3579           if (gimple)
3580             fprintf (f, "\nstatic bool\n"
3581                      "gimple_simplify_%s (code_helper *res_code, tree *res_ops,\n"
3582                      "                 gimple_seq *seq, tree (*valueize)(tree) "
3583                      "ATTRIBUTE_UNUSED,\n"
3584                      "                 code_helper ARG_UNUSED (code), tree "
3585                      "ARG_UNUSED (type)\n",
3586                      e->operation->id);
3587           else
3588             fprintf (f, "\nstatic tree\n"
3589                      "generic_simplify_%s (location_t ARG_UNUSED (loc), enum "
3590                      "tree_code ARG_UNUSED (code), tree ARG_UNUSED (type)",
3591                      e->operation->id);
3592           for (unsigned i = 0; i < n; ++i)
3593             fprintf (f, ", tree op%d", i);
3594           fprintf (f, ")\n");
3595           fprintf (f, "{\n");
3596           dop->gen_kids (f, 2, gimple);
3597           if (gimple)
3598             fprintf (f, "  return false;\n");
3599           else
3600             fprintf (f, "  return NULL_TREE;\n");
3601           fprintf (f, "}\n");
3602         }
3603
3604       /* Then generate the main entry with the outermost switch and
3605          tail-calls to the split-out functions.  */
3606       if (gimple)
3607         fprintf (f, "\nstatic bool\n"
3608                  "gimple_simplify (code_helper *res_code, tree *res_ops,\n"
3609                  "                 gimple_seq *seq, tree (*valueize)(tree),\n"
3610                  "                 code_helper code, tree type");
3611       else
3612         fprintf (f, "\ntree\n"
3613                  "generic_simplify (location_t loc, enum tree_code code, "
3614                  "tree type ATTRIBUTE_UNUSED");
3615       for (unsigned i = 0; i < n; ++i)
3616         fprintf (f, ", tree op%d", i);
3617       fprintf (f, ")\n");
3618       fprintf (f, "{\n");
3619
3620       if (gimple)
3621         fprintf (f, "  switch (code.get_rep())\n"
3622                  "    {\n");
3623       else
3624         fprintf (f, "  switch (code)\n"
3625                  "    {\n");
3626       for (unsigned i = 0; i < root->kids.length (); i++)
3627         {
3628           dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3629           expr *e = static_cast<expr *>(dop->op);
3630           if (e->ops.length () != n
3631               /* Builtin simplifications are somewhat premature on
3632                  GENERIC.  The following drops patterns with outermost
3633                  calls.  It's easy to emit overloads for function code
3634                  though if necessary.  */
3635               || (!gimple
3636                   && e->operation->kind != id_base::CODE))
3637             continue;
3638
3639           if (*e->operation == CONVERT_EXPR
3640               || *e->operation == NOP_EXPR)
3641             fprintf (f, "    CASE_CONVERT:\n");
3642           else
3643             fprintf (f, "    case %s%s:\n",
3644                      is_a <fn_id *> (e->operation) ? "-" : "",
3645                      e->operation->id);
3646           if (gimple)
3647             fprintf (f, "      return gimple_simplify_%s (res_code, res_ops, "
3648                      "seq, valueize, code, type", e->operation->id);
3649           else
3650             fprintf (f, "      return generic_simplify_%s (loc, code, type",
3651                      e->operation->id);
3652           for (unsigned i = 0; i < n; ++i)
3653             fprintf (f, ", op%d", i);
3654           fprintf (f, ");\n");
3655         }
3656       fprintf (f,       "    default:;\n"
3657                         "    }\n");
3658
3659       if (gimple)
3660         fprintf (f, "  return false;\n");
3661       else
3662         fprintf (f, "  return NULL_TREE;\n");
3663       fprintf (f, "}\n");
3664     }
3665 }
3666
3667 /* Output code to implement the predicate P from the decision tree DT.  */
3668
3669 void
3670 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
3671 {
3672   fprintf (f, "\nbool\n"
3673            "%s%s (tree t%s%s)\n"
3674            "{\n", gimple ? "gimple_" : "tree_", p->id,
3675            p->nargs > 0 ? ", tree *res_ops" : "",
3676            gimple ? ", tree (*valueize)(tree) ATTRIBUTE_UNUSED" : "");
3677   /* Conveniently make 'type' available.  */
3678   fprintf_indent (f, 2, "tree type = TREE_TYPE (t);\n");
3679
3680   if (!gimple)
3681     fprintf_indent (f, 2, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
3682   dt.root->gen_kids (f, 2, gimple);
3683
3684   fprintf_indent (f, 2, "return false;\n"
3685            "}\n");
3686 }
3687
3688 /* Write the common header for the GIMPLE/GENERIC IL matching routines.  */
3689
3690 static void
3691 write_header (FILE *f, const char *head)
3692 {
3693   fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
3694   fprintf (f, "   a IL pattern matching and simplification description.  */\n");
3695
3696   /* Include the header instead of writing it awkwardly quoted here.  */
3697   fprintf (f, "\n#include \"%s\"\n", head);
3698 }
3699
3700
3701
3702 /* AST parsing.  */
3703
3704 class parser
3705 {
3706 public:
3707   parser (cpp_reader *);
3708
3709 private:
3710   const cpp_token *next ();
3711   const cpp_token *peek (unsigned = 1);
3712   const cpp_token *peek_ident (const char * = NULL, unsigned = 1);
3713   const cpp_token *expect (enum cpp_ttype);
3714   const cpp_token *eat_token (enum cpp_ttype);
3715   const char *get_string ();
3716   const char *get_ident ();
3717   const cpp_token *eat_ident (const char *);
3718   const char *get_number ();
3719
3720   id_base *parse_operation ();
3721   operand *parse_capture (operand *, bool);
3722   operand *parse_expr ();
3723   c_expr *parse_c_expr (cpp_ttype);
3724   operand *parse_op ();
3725
3726   void record_operlist (source_location, user_id *);
3727
3728   void parse_pattern ();
3729   operand *parse_result (operand *, predicate_id *);
3730   void push_simplify (simplify::simplify_kind,
3731                       vec<simplify *>&, operand *, operand *);
3732   void parse_simplify (simplify::simplify_kind,
3733                        vec<simplify *>&, predicate_id *, operand *);
3734   void parse_for (source_location);
3735   void parse_if (source_location);
3736   void parse_predicates (source_location);
3737   void parse_operator_list (source_location);
3738
3739   cpp_reader *r;
3740   vec<c_expr *> active_ifs;
3741   vec<vec<user_id *> > active_fors;
3742   hash_set<user_id *> *oper_lists_set;
3743   vec<user_id *> oper_lists;
3744
3745   cid_map_t *capture_ids;
3746
3747 public:
3748   vec<simplify *> simplifiers;
3749   vec<predicate_id *> user_predicates;
3750   bool parsing_match_operand;
3751 };
3752
3753 /* Lexing helpers.  */
3754
3755 /* Read the next non-whitespace token from R.  */
3756
3757 const cpp_token *
3758 parser::next ()
3759 {
3760   const cpp_token *token;
3761   do
3762     {
3763       token = cpp_get_token (r);
3764     }
3765   while (token->type == CPP_PADDING
3766          && token->type != CPP_EOF);
3767   return token;
3768 }
3769
3770 /* Peek at the next non-whitespace token from R.  */
3771
3772 const cpp_token *
3773 parser::peek (unsigned num)
3774 {
3775   const cpp_token *token;
3776   unsigned i = 0;
3777   do
3778     {
3779       token = cpp_peek_token (r, i++);
3780     }
3781   while ((token->type == CPP_PADDING
3782           && token->type != CPP_EOF)
3783          || (--num > 0));
3784   /* If we peek at EOF this is a fatal error as it leaves the
3785      cpp_reader in unusable state.  Assume we really wanted a
3786      token and thus this EOF is unexpected.  */
3787   if (token->type == CPP_EOF)
3788     fatal_at (token, "unexpected end of file");
3789   return token;
3790 }
3791
3792 /* Peek at the next identifier token (or return NULL if the next
3793    token is not an identifier or equal to ID if supplied).  */
3794
3795 const cpp_token *
3796 parser::peek_ident (const char *id, unsigned num)
3797 {
3798   const cpp_token *token = peek (num);
3799   if (token->type != CPP_NAME)
3800     return 0;
3801
3802   if (id == 0)
3803     return token;
3804
3805   const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
3806   if (strcmp (id, t) == 0)
3807     return token;
3808
3809   return 0;
3810 }
3811
3812 /* Read the next token from R and assert it is of type TK.  */
3813
3814 const cpp_token *
3815 parser::expect (enum cpp_ttype tk)
3816 {
3817   const cpp_token *token = next ();
3818   if (token->type != tk)
3819     fatal_at (token, "expected %s, got %s",
3820               cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
3821
3822   return token;
3823 }
3824
3825 /* Consume the next token from R and assert it is of type TK.  */
3826
3827 const cpp_token *
3828 parser::eat_token (enum cpp_ttype tk)
3829 {
3830   return expect (tk);
3831 }
3832
3833 /* Read the next token from R and assert it is of type CPP_STRING and
3834    return its value.  */
3835
3836 const char *
3837 parser::get_string ()
3838 {
3839   const cpp_token *token = expect (CPP_STRING);
3840   return (const char *)token->val.str.text;
3841 }
3842
3843 /* Read the next token from R and assert it is of type CPP_NAME and
3844    return its value.  */
3845
3846 const char *
3847 parser::get_ident ()
3848 {
3849   const cpp_token *token = expect (CPP_NAME);
3850   return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
3851 }
3852
3853 /* Eat an identifier token with value S from R.  */
3854
3855 const cpp_token *
3856 parser::eat_ident (const char *s)
3857 {
3858   const cpp_token *token = peek ();
3859   const char *t = get_ident ();
3860   if (strcmp (s, t) != 0)
3861     fatal_at (token, "expected '%s' got '%s'\n", s, t);
3862   return token;
3863 }
3864
3865 /* Read the next token from R and assert it is of type CPP_NUMBER and
3866    return its value.  */
3867
3868 const char *
3869 parser::get_number ()
3870 {
3871   const cpp_token *token = expect (CPP_NUMBER);
3872   return (const char *)token->val.str.text;
3873 }
3874
3875
3876 /* Record an operator-list use for transparent for handling.  */
3877
3878 void
3879 parser::record_operlist (source_location loc, user_id *p)
3880 {
3881   if (!oper_lists_set->add (p))
3882     {
3883       if (!oper_lists.is_empty ()
3884           && oper_lists[0]->substitutes.length () != p->substitutes.length ())
3885         fatal_at (loc, "User-defined operator list does not have the "
3886                   "same number of entries as others used in the pattern");
3887       oper_lists.safe_push (p);
3888     }
3889 }
3890
3891 /* Parse the operator ID, special-casing convert?, convert1? and
3892    convert2?  */
3893
3894 id_base *
3895 parser::parse_operation ()
3896 {
3897   const cpp_token *id_tok = peek ();
3898   const char *id = get_ident ();
3899   const cpp_token *token = peek ();
3900   if (strcmp (id, "convert0") == 0)
3901     fatal_at (id_tok, "use 'convert?' here");
3902   else if (strcmp (id, "view_convert0") == 0)
3903     fatal_at (id_tok, "use 'view_convert?' here");
3904   if (token->type == CPP_QUERY
3905       && !(token->flags & PREV_WHITE))
3906     {
3907       if (strcmp (id, "convert") == 0)
3908         id = "convert0";
3909       else if (strcmp (id, "convert1") == 0)
3910         ;
3911       else if (strcmp (id, "convert2") == 0)
3912         ;
3913       else if (strcmp (id, "view_convert") == 0)
3914         id = "view_convert0";
3915       else if (strcmp (id, "view_convert1") == 0)
3916         ;
3917       else if (strcmp (id, "view_convert2") == 0)
3918         ;
3919       else
3920         fatal_at (id_tok, "non-convert operator conditionalized");
3921
3922       if (!parsing_match_operand)
3923         fatal_at (id_tok, "conditional convert can only be used in "
3924                   "match expression");
3925       eat_token (CPP_QUERY);
3926     }
3927   else if (strcmp (id, "convert1") == 0
3928            || strcmp (id, "convert2") == 0
3929            || strcmp (id, "view_convert1") == 0
3930            || strcmp (id, "view_convert2") == 0)
3931     fatal_at (id_tok, "expected '?' after conditional operator");
3932   id_base *op = get_operator (id);
3933   if (!op)
3934     fatal_at (id_tok, "unknown operator %s", id);
3935
3936   user_id *p = dyn_cast<user_id *> (op);
3937   if (p && p->is_oper_list)
3938     {
3939       if (active_fors.length() == 0)
3940         record_operlist (id_tok->src_loc, p);
3941       else
3942         fatal_at (id_tok, "operator-list %s cannot be exapnded inside 'for'", id);
3943     }
3944   return op;
3945 }
3946
3947 /* Parse a capture.
3948      capture = '@'<number>  */
3949
3950 struct operand *
3951 parser::parse_capture (operand *op, bool require_existing)
3952 {
3953   source_location src_loc = eat_token (CPP_ATSIGN)->src_loc;
3954   const cpp_token *token = peek ();
3955   const char *id = NULL;
3956   if (token->type == CPP_NUMBER)
3957     id = get_number ();
3958   else if (token->type == CPP_NAME)
3959     id = get_ident ();
3960   else
3961     fatal_at (token, "expected number or identifier");
3962   unsigned next_id = capture_ids->elements ();
3963   bool existed;
3964   unsigned &num = capture_ids->get_or_insert (id, &existed);
3965   if (!existed)
3966     {
3967       if (require_existing)
3968         fatal_at (src_loc, "unknown capture id");
3969       num = next_id;
3970     }
3971   return new capture (src_loc, num, op);
3972 }
3973
3974 /* Parse an expression
3975      expr = '(' <operation>[capture][flag][type] <operand>... ')'  */
3976
3977 struct operand *
3978 parser::parse_expr ()
3979 {
3980   const cpp_token *token = peek ();
3981   expr *e = new expr (parse_operation (), token->src_loc);
3982   token = peek ();
3983   operand *op;
3984   bool is_commutative = false;
3985   bool force_capture = false;
3986   const char *expr_type = NULL;
3987
3988   if (token->type == CPP_COLON
3989       && !(token->flags & PREV_WHITE))
3990     {
3991       eat_token (CPP_COLON);
3992       token = peek ();
3993       if (token->type == CPP_NAME
3994           && !(token->flags & PREV_WHITE))
3995         {
3996           const char *s = get_ident ();
3997           if (!parsing_match_operand)
3998             expr_type = s;
3999           else
4000             {
4001               const char *sp = s;
4002               while (*sp)
4003                 {
4004                   if (*sp == 'c')
4005                     {
4006                       if (operator_id *p
4007                             = dyn_cast<operator_id *> (e->operation))
4008                         {
4009                           if (!commutative_tree_code (p->code)
4010                               && !comparison_code_p (p->code))
4011                             fatal_at (token, "operation is not commutative");
4012                         }
4013                       else if (user_id *p = dyn_cast<user_id *> (e->operation))
4014                         for (unsigned i = 0;
4015                              i < p->substitutes.length (); ++i)
4016                           {
4017                             if (operator_id *q
4018                                   = dyn_cast<operator_id *> (p->substitutes[i]))
4019                               {
4020                                 if (!commutative_tree_code (q->code)
4021                                     && !comparison_code_p (q->code))
4022                                   fatal_at (token, "operation %s is not "
4023                                             "commutative", q->id);
4024                               }
4025                           }
4026                       is_commutative = true;
4027                     }
4028                   else if (*sp == 'C')
4029                     is_commutative = true;
4030                   else if (*sp == 's')
4031                     {
4032                       e->force_single_use = true;
4033                       force_capture = true;
4034                     }
4035                   else
4036                     fatal_at (token, "flag %c not recognized", *sp);
4037                   sp++;
4038                 }
4039             }
4040           token = peek ();
4041         }
4042       else
4043         fatal_at (token, "expected flag or type specifying identifier");
4044     }
4045
4046   if (token->type == CPP_ATSIGN
4047       && !(token->flags & PREV_WHITE))
4048     op = parse_capture (e, false);
4049   else if (force_capture)
4050     {
4051       unsigned num = capture_ids->elements ();
4052       char id[8];
4053       bool existed;
4054       sprintf (id, "__%u", num);
4055       capture_ids->get_or_insert (xstrdup (id), &existed);
4056       if (existed)
4057         fatal_at (token, "reserved capture id '%s' already used", id);
4058       op = new capture (token->src_loc, num, e);
4059     }
4060   else
4061     op = e;
4062   do
4063     {
4064       const cpp_token *token = peek ();
4065       if (token->type == CPP_CLOSE_PAREN)
4066         {
4067           if (e->operation->nargs != -1
4068               && e->operation->nargs != (int) e->ops.length ())
4069             fatal_at (token, "'%s' expects %u operands, not %u",
4070                       e->operation->id, e->operation->nargs, e->ops.length ());
4071           if (is_commutative)
4072             {
4073               if (e->ops.length () == 2)
4074                 e->is_commutative = true;
4075               else
4076                 fatal_at (token, "only binary operators or function with "
4077                           "two arguments can be marked commutative");
4078             }
4079           e->expr_type = expr_type;
4080           return op;
4081         }
4082       else if (!(token->flags & PREV_WHITE))
4083         fatal_at (token, "expected expression operand");
4084
4085       e->append_op (parse_op ());
4086     }
4087   while (1);
4088 }
4089
4090 /* Lex native C code delimited by START recording the preprocessing tokens
4091    for later processing.
4092      c_expr = ('{'|'(') <pp token>... ('}'|')')  */
4093
4094 c_expr *
4095 parser::parse_c_expr (cpp_ttype start)
4096 {
4097   const cpp_token *token;
4098   cpp_ttype end;
4099   unsigned opencnt;
4100   vec<cpp_token> code = vNULL;
4101   unsigned nr_stmts = 0;
4102   source_location loc = eat_token (start)->src_loc;
4103   if (start == CPP_OPEN_PAREN)
4104     end = CPP_CLOSE_PAREN;
4105   else if (start == CPP_OPEN_BRACE)
4106     end = CPP_CLOSE_BRACE;
4107   else
4108     gcc_unreachable ();
4109   opencnt = 1;
4110   do
4111     {
4112       token = next ();
4113
4114       /* Count brace pairs to find the end of the expr to match.  */
4115       if (token->type == start)
4116         opencnt++;
4117       else if (token->type == end
4118                && --opencnt == 0)
4119         break;
4120
4121       /* This is a lame way of counting the number of statements.  */
4122       if (token->type == CPP_SEMICOLON)
4123         nr_stmts++;
4124
4125       /* If this is possibly a user-defined identifier mark it used.  */
4126       if (token->type == CPP_NAME)
4127         {
4128           id_base *idb = get_operator ((const char *)CPP_HASHNODE
4129                                       (token->val.node.node)->ident.str);
4130           user_id *p;
4131           if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
4132             record_operlist (token->src_loc, p);
4133         }
4134
4135       /* Record the token.  */
4136       code.safe_push (*token);
4137     }
4138   while (1);
4139   return new c_expr (r, loc, code, nr_stmts, vNULL, capture_ids);
4140 }
4141
4142 /* Parse an operand which is either an expression, a predicate or
4143    a standalone capture.
4144      op = predicate | expr | c_expr | capture  */
4145
4146 struct operand *
4147 parser::parse_op ()
4148 {
4149   const cpp_token *token = peek ();
4150   struct operand *op = NULL;
4151   if (token->type == CPP_OPEN_PAREN)
4152     {
4153       eat_token (CPP_OPEN_PAREN);
4154       op = parse_expr ();
4155       eat_token (CPP_CLOSE_PAREN);
4156     }
4157   else if (token->type == CPP_OPEN_BRACE)
4158     {
4159       op = parse_c_expr (CPP_OPEN_BRACE);
4160     }
4161   else
4162     {
4163       /* Remaining ops are either empty or predicates  */
4164       if (token->type == CPP_NAME)
4165         {
4166           const char *id = get_ident ();
4167           id_base *opr = get_operator (id);
4168           if (!opr)
4169             fatal_at (token, "expected predicate name");
4170           if (operator_id *code = dyn_cast <operator_id *> (opr))
4171             {
4172               if (code->nargs != 0)
4173                 fatal_at (token, "using an operator with operands as predicate");
4174               /* Parse the zero-operand operator "predicates" as
4175                  expression.  */
4176               op = new expr (opr, token->src_loc);
4177             }
4178           else if (user_id *code = dyn_cast <user_id *> (opr))
4179             {
4180               if (code->nargs != 0)
4181                 fatal_at (token, "using an operator with operands as predicate");
4182               /* Parse the zero-operand operator "predicates" as
4183                  expression.  */
4184               op = new expr (opr, token->src_loc);
4185             }
4186           else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
4187             op = new predicate (p, token->src_loc);
4188           else
4189             fatal_at (token, "using an unsupported operator as predicate");
4190           if (!parsing_match_operand)
4191             fatal_at (token, "predicates are only allowed in match expression");
4192           token = peek ();
4193           if (token->flags & PREV_WHITE)
4194             return op;
4195         }
4196       else if (token->type != CPP_COLON
4197                && token->type != CPP_ATSIGN)
4198         fatal_at (token, "expected expression or predicate");
4199       /* optionally followed by a capture and a predicate.  */
4200       if (token->type == CPP_COLON)
4201         fatal_at (token, "not implemented: predicate on leaf operand");
4202       if (token->type == CPP_ATSIGN)
4203         op = parse_capture (op, !parsing_match_operand);
4204     }
4205
4206   return op;
4207 }
4208
4209 /* Create a new simplify from the current parsing state and MATCH,
4210    MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS.  */
4211
4212 void
4213 parser::push_simplify (simplify::simplify_kind kind,
4214                        vec<simplify *>& simplifiers,
4215                        operand *match, operand *result)
4216 {
4217   /* Build and push a temporary for operator list uses in expressions.  */
4218   if (!oper_lists.is_empty ())
4219     active_fors.safe_push (oper_lists);
4220
4221   simplifiers.safe_push
4222     (new simplify (kind, match, result,
4223                    active_fors.copy (), capture_ids));
4224
4225   if (!oper_lists.is_empty ())
4226     active_fors.pop ();
4227 }
4228
4229 /* Parse
4230      <result-op> = <op> | <if> | <with>
4231      <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
4232      <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
4233    and return it.  */
4234
4235 operand *
4236 parser::parse_result (operand *result, predicate_id *matcher)
4237 {
4238   const cpp_token *token = peek ();
4239   if (token->type != CPP_OPEN_PAREN)
4240     return parse_op ();
4241
4242   eat_token (CPP_OPEN_PAREN);
4243   if (peek_ident ("if"))
4244     {
4245       eat_ident ("if");
4246       if_expr *ife = new if_expr (token->src_loc);
4247       ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4248       if (peek ()->type == CPP_OPEN_PAREN)
4249         {
4250           ife->trueexpr = parse_result (result, matcher);
4251           if (peek ()->type == CPP_OPEN_PAREN)
4252             ife->falseexpr = parse_result (result, matcher);
4253           else if (peek ()->type != CPP_CLOSE_PAREN)
4254             ife->falseexpr = parse_op ();
4255         }
4256       else if (peek ()->type != CPP_CLOSE_PAREN)
4257         {
4258           ife->trueexpr = parse_op ();
4259           if (peek ()->type == CPP_OPEN_PAREN)
4260             ife->falseexpr = parse_result (result, matcher);
4261           else if (peek ()->type != CPP_CLOSE_PAREN)
4262             ife->falseexpr = parse_op ();
4263         }
4264       /* If this if is immediately closed then it contains a
4265          manual matcher or is part of a predicate definition.  */
4266       else /* if (peek ()->type == CPP_CLOSE_PAREN) */
4267         {
4268           if (!matcher)
4269             fatal_at (peek (), "manual transform not implemented");
4270           ife->trueexpr = result;
4271         }
4272       eat_token (CPP_CLOSE_PAREN);
4273       return ife;
4274     }
4275   else if (peek_ident ("with"))
4276     {
4277       eat_ident ("with");
4278       with_expr *withe = new with_expr (token->src_loc);
4279       /* Parse (with c-expr expr) as (if-with (true) expr).  */
4280       withe->with = parse_c_expr (CPP_OPEN_BRACE);
4281       withe->with->nr_stmts = 0;
4282       withe->subexpr = parse_result (result, matcher);
4283       eat_token (CPP_CLOSE_PAREN);
4284       return withe;
4285     }
4286   else if (peek_ident ("switch"))
4287     {
4288       token = eat_ident ("switch");
4289       source_location ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4290       eat_ident ("if");
4291       if_expr *ife = new if_expr (ifloc);
4292       operand *res = ife;
4293       ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4294       if (peek ()->type == CPP_OPEN_PAREN)
4295         ife->trueexpr = parse_result (result, matcher);
4296       else
4297         ife->trueexpr = parse_op ();
4298       eat_token (CPP_CLOSE_PAREN);
4299       if (peek ()->type != CPP_OPEN_PAREN
4300           || !peek_ident ("if", 2))
4301         fatal_at (token, "switch can be implemented with a single if");
4302       while  (peek ()->type != CPP_CLOSE_PAREN)
4303         {
4304           if (peek ()->type == CPP_OPEN_PAREN)
4305             {
4306               if (peek_ident ("if", 2))
4307                 {
4308                   ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4309                   eat_ident ("if");
4310                   ife->falseexpr = new if_expr (ifloc);
4311                   ife = as_a <if_expr *> (ife->falseexpr);
4312                   ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4313                   if (peek ()->type == CPP_OPEN_PAREN)
4314                     ife->trueexpr = parse_result (result, matcher);
4315                   else
4316                     ife->trueexpr = parse_op ();
4317                   eat_token (CPP_CLOSE_PAREN);
4318                 }
4319               else
4320                 {
4321                   /* switch default clause */
4322                   ife->falseexpr = parse_result (result, matcher);
4323                   eat_token (CPP_CLOSE_PAREN);
4324                   return res;
4325                 }
4326             }
4327           else
4328             {
4329               /* switch default clause */
4330               ife->falseexpr = parse_op ();
4331               eat_token (CPP_CLOSE_PAREN);
4332               return res;
4333             }
4334         }
4335       eat_token (CPP_CLOSE_PAREN);
4336       return res;
4337     }
4338   else
4339     {
4340       operand *op = result;
4341       if (!matcher)
4342         op = parse_expr ();
4343       eat_token (CPP_CLOSE_PAREN);
4344       return op;
4345     }
4346 }
4347
4348 /* Parse
4349      simplify = 'simplify' <expr> <result-op>
4350    or
4351      match = 'match' <ident> <expr> [<result-op>]
4352    and fill SIMPLIFIERS with the results.  */
4353
4354 void
4355 parser::parse_simplify (simplify::simplify_kind kind,
4356                         vec<simplify *>& simplifiers, predicate_id *matcher,
4357                         operand *result)
4358 {
4359   /* Reset the capture map.  */
4360   if (!capture_ids)
4361     capture_ids = new cid_map_t;
4362   /* Reset oper_lists and set.  */
4363   hash_set <user_id *> olist;
4364   oper_lists_set = &olist;
4365   oper_lists = vNULL;
4366
4367   const cpp_token *loc = peek ();
4368   parsing_match_operand = true;
4369   struct operand *match = parse_op ();
4370   parsing_match_operand = false;
4371   if (match->type == operand::OP_CAPTURE && !matcher)
4372     fatal_at (loc, "outermost expression cannot be captured");
4373   if (match->type == operand::OP_EXPR
4374       && is_a <predicate_id *> (as_a <expr *> (match)->operation))
4375     fatal_at (loc, "outermost expression cannot be a predicate");
4376
4377   /* Splice active_ifs onto result and continue parsing the
4378      "then" expr.  */
4379   if_expr *active_if = NULL;
4380   for (int i = active_ifs.length (); i > 0; --i)
4381     {
4382       if_expr *ifc = new if_expr (active_ifs[i-1]->location);
4383       ifc->cond = active_ifs[i-1];
4384       ifc->trueexpr = active_if;
4385       active_if = ifc;
4386     }
4387   if_expr *outermost_if = active_if;
4388   while (active_if && active_if->trueexpr)
4389     active_if = as_a <if_expr *> (active_if->trueexpr);
4390
4391   const cpp_token *token = peek ();
4392
4393   /* If this if is immediately closed then it is part of a predicate
4394      definition.  Push it.  */
4395   if (token->type == CPP_CLOSE_PAREN)
4396     {
4397       if (!matcher)
4398         fatal_at (token, "expected transform expression");
4399       if (active_if)
4400         {
4401           active_if->trueexpr = result;
4402           result = outermost_if;
4403         }
4404       push_simplify (kind, simplifiers, match, result);
4405       return;
4406     }
4407
4408   operand *tem = parse_result (result, matcher);
4409   if (active_if)
4410     {
4411       active_if->trueexpr = tem;
4412       result = outermost_if;
4413     }
4414   else
4415     result = tem;
4416
4417   push_simplify (kind, simplifiers, match, result);
4418 }
4419
4420 /* Parsing of the outer control structures.  */
4421
4422 /* Parse a for expression
4423      for = '(' 'for' <subst>... <pattern> ')'
4424      subst = <ident> '(' <ident>... ')'  */
4425
4426 void
4427 parser::parse_for (source_location)
4428 {
4429   auto_vec<const cpp_token *> user_id_tokens;
4430   vec<user_id *> user_ids = vNULL;
4431   const cpp_token *token;
4432   unsigned min_n_opers = 0, max_n_opers = 0;
4433
4434   while (1)
4435     {
4436       token = peek ();
4437       if (token->type != CPP_NAME)
4438         break;
4439
4440       /* Insert the user defined operators into the operator hash.  */
4441       const char *id = get_ident ();
4442       if (get_operator (id, true) != NULL)
4443         fatal_at (token, "operator already defined");
4444       user_id *op = new user_id (id);
4445       id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4446       *slot = op;
4447       user_ids.safe_push (op);
4448       user_id_tokens.safe_push (token);
4449
4450       eat_token (CPP_OPEN_PAREN);
4451
4452       int arity = -1;
4453       while ((token = peek_ident ()) != 0)
4454         {
4455           const char *oper = get_ident ();
4456           id_base *idb = get_operator (oper, true);
4457           if (idb == NULL)
4458             fatal_at (token, "no such operator '%s'", oper);
4459           if (*idb == CONVERT0 || *idb == CONVERT1 || *idb == CONVERT2
4460               || *idb == VIEW_CONVERT0 || *idb == VIEW_CONVERT1
4461               || *idb == VIEW_CONVERT2)
4462             fatal_at (token, "conditional operators cannot be used inside for");
4463
4464           if (arity == -1)
4465             arity = idb->nargs;
4466           else if (idb->nargs == -1)
4467             ;
4468           else if (idb->nargs != arity)
4469             fatal_at (token, "operator '%s' with arity %d does not match "
4470                       "others with arity %d", oper, idb->nargs, arity);
4471
4472           user_id *p = dyn_cast<user_id *> (idb);
4473           if (p)
4474             {
4475               if (p->is_oper_list)
4476                 op->substitutes.safe_splice (p->substitutes);
4477               else
4478                 fatal_at (token, "iterator cannot be used as operator-list");
4479             }
4480           else 
4481             op->substitutes.safe_push (idb);
4482         }
4483       op->nargs = arity;
4484       token = expect (CPP_CLOSE_PAREN);
4485
4486       unsigned nsubstitutes = op->substitutes.length ();
4487       if (nsubstitutes == 0)
4488         fatal_at (token, "A user-defined operator must have at least "
4489                   "one substitution");
4490       if (max_n_opers == 0)
4491         {
4492           min_n_opers = nsubstitutes;
4493           max_n_opers = nsubstitutes;
4494         }
4495       else
4496         {
4497           if (nsubstitutes % min_n_opers != 0
4498               && min_n_opers % nsubstitutes != 0)
4499             fatal_at (token, "All user-defined identifiers must have a "
4500                       "multiple number of operator substitutions of the "
4501                       "smallest number of substitutions");
4502           if (nsubstitutes < min_n_opers)
4503             min_n_opers = nsubstitutes;
4504           else if (nsubstitutes > max_n_opers)
4505             max_n_opers = nsubstitutes;
4506         }
4507     }
4508
4509   unsigned n_ids = user_ids.length ();
4510   if (n_ids == 0)
4511     fatal_at (token, "for requires at least one user-defined identifier");
4512
4513   token = peek ();
4514   if (token->type == CPP_CLOSE_PAREN)
4515     fatal_at (token, "no pattern defined in for");
4516
4517   active_fors.safe_push (user_ids);
4518   while (1)
4519     {
4520       token = peek ();
4521       if (token->type == CPP_CLOSE_PAREN)
4522         break;
4523       parse_pattern ();
4524     }
4525   active_fors.pop ();
4526
4527   /* Remove user-defined operators from the hash again.  */
4528   for (unsigned i = 0; i < user_ids.length (); ++i)
4529     {
4530       if (!user_ids[i]->used)
4531         warning_at (user_id_tokens[i],
4532                     "operator %s defined but not used", user_ids[i]->id);
4533       operators->remove_elt (user_ids[i]);
4534     }
4535 }
4536
4537 /* Parse an identifier associated with a list of operators.
4538      oprs = '(' 'define_operator_list' <ident> <ident>... ')'  */
4539
4540 void
4541 parser::parse_operator_list (source_location)
4542 {
4543   const cpp_token *token = peek (); 
4544   const char *id = get_ident ();
4545
4546   if (get_operator (id, true) != 0)
4547     fatal_at (token, "operator %s already defined", id);
4548
4549   user_id *op = new user_id (id, true);
4550   int arity = -1;
4551   
4552   while ((token = peek_ident ()) != 0)
4553     {
4554       token = peek (); 
4555       const char *oper = get_ident ();
4556       id_base *idb = get_operator (oper, true);
4557       
4558       if (idb == 0)
4559         fatal_at (token, "no such operator '%s'", oper);
4560
4561       if (arity == -1)
4562         arity = idb->nargs;
4563       else if (idb->nargs == -1)
4564         ;
4565       else if (arity != idb->nargs)
4566         fatal_at (token, "operator '%s' with arity %d does not match "
4567                          "others with arity %d", oper, idb->nargs, arity);
4568
4569       /* We allow composition of multiple operator lists.  */
4570       if (user_id *p = dyn_cast<user_id *> (idb))
4571         op->substitutes.safe_splice (p->substitutes);
4572       else
4573         op->substitutes.safe_push (idb);
4574     }
4575
4576   // Check that there is no junk after id-list
4577   token = peek();
4578   if (token->type != CPP_CLOSE_PAREN)
4579     fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
4580
4581   if (op->substitutes.length () == 0)
4582     fatal_at (token, "operator-list cannot be empty");
4583
4584   op->nargs = arity;
4585   id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4586   *slot = op;
4587 }
4588
4589 /* Parse an outer if expression.
4590      if = '(' 'if' '(' <c-expr> ')' <pattern> ')'  */
4591
4592 void
4593 parser::parse_if (source_location)
4594 {
4595   c_expr *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
4596
4597   const cpp_token *token = peek ();
4598   if (token->type == CPP_CLOSE_PAREN)
4599     fatal_at (token, "no pattern defined in if");
4600
4601   active_ifs.safe_push (ifexpr);
4602   while (1)
4603     {
4604       const cpp_token *token = peek ();
4605       if (token->type == CPP_CLOSE_PAREN)
4606         break;
4607
4608       parse_pattern ();
4609     }
4610   active_ifs.pop ();
4611 }
4612
4613 /* Parse a list of predefined predicate identifiers.
4614      preds = '(' 'define_predicates' <ident>... ')'  */
4615
4616 void
4617 parser::parse_predicates (source_location)
4618 {
4619   do
4620     {
4621       const cpp_token *token = peek ();
4622       if (token->type != CPP_NAME)
4623         break;
4624
4625       add_predicate (get_ident ());
4626     }
4627   while (1);
4628 }
4629
4630 /* Parse outer control structures.
4631      pattern = <preds>|<for>|<if>|<simplify>|<match>  */
4632
4633 void
4634 parser::parse_pattern ()
4635 {
4636   /* All clauses start with '('.  */
4637   eat_token (CPP_OPEN_PAREN);
4638   const cpp_token *token = peek ();
4639   const char *id = get_ident ();
4640   if (strcmp (id, "simplify") == 0)
4641     {
4642       parse_simplify (simplify::SIMPLIFY, simplifiers, NULL, NULL);
4643       capture_ids = NULL;
4644     }
4645   else if (strcmp (id, "match") == 0)
4646     {
4647       bool with_args = false;
4648       source_location e_loc = peek ()->src_loc;
4649       if (peek ()->type == CPP_OPEN_PAREN)
4650         {
4651           eat_token (CPP_OPEN_PAREN);
4652           with_args = true;
4653         }
4654       const char *name = get_ident ();
4655       id_base *id = get_operator (name);
4656       predicate_id *p;
4657       if (!id)
4658         {
4659           p = add_predicate (name);
4660           user_predicates.safe_push (p);
4661         }
4662       else if ((p = dyn_cast <predicate_id *> (id)))
4663         ;
4664       else
4665         fatal_at (token, "cannot add a match to a non-predicate ID");
4666       /* Parse (match <id> <arg>... (match-expr)) here.  */
4667       expr *e = NULL;
4668       if (with_args)
4669         {
4670           capture_ids = new cid_map_t;
4671           e = new expr (p, e_loc);
4672           while (peek ()->type == CPP_ATSIGN)
4673             e->append_op (parse_capture (NULL, false));
4674           eat_token (CPP_CLOSE_PAREN);
4675         }
4676       if (p->nargs != -1
4677           && ((e && e->ops.length () != (unsigned)p->nargs)
4678               || (!e && p->nargs != 0)))
4679         fatal_at (token, "non-matching number of match operands");
4680       p->nargs = e ? e->ops.length () : 0;
4681       parse_simplify (simplify::MATCH, p->matchers, p, e);
4682       capture_ids = NULL;
4683     }
4684   else if (strcmp (id, "for") == 0)
4685     parse_for (token->src_loc);
4686   else if (strcmp (id, "if") == 0)
4687     parse_if (token->src_loc);
4688   else if (strcmp (id, "define_predicates") == 0)
4689     {
4690       if (active_ifs.length () > 0
4691           || active_fors.length () > 0)
4692         fatal_at (token, "define_predicates inside if or for is not supported");
4693       parse_predicates (token->src_loc);
4694     }
4695   else if (strcmp (id, "define_operator_list") == 0)
4696     {
4697       if (active_ifs.length () > 0
4698           || active_fors.length () > 0)
4699         fatal_at (token, "operator-list inside if or for is not supported");
4700       parse_operator_list (token->src_loc);
4701     }
4702   else
4703     fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
4704               active_ifs.length () == 0 && active_fors.length () == 0
4705               ? "'define_predicates', " : "");
4706
4707   eat_token (CPP_CLOSE_PAREN);
4708 }
4709
4710 /* Main entry of the parser.  Repeatedly parse outer control structures.  */
4711
4712 parser::parser (cpp_reader *r_)
4713 {
4714   r = r_;
4715   active_ifs = vNULL;
4716   active_fors = vNULL;
4717   simplifiers = vNULL;
4718   oper_lists_set = NULL;
4719   oper_lists = vNULL;
4720   capture_ids = NULL;
4721   user_predicates = vNULL;
4722   parsing_match_operand = false;
4723
4724   const cpp_token *token = next ();
4725   while (token->type != CPP_EOF)
4726     {
4727       _cpp_backup_tokens (r, 1);
4728       parse_pattern ();
4729       token = next ();
4730     }
4731 }
4732
4733
4734 /* Helper for the linemap code.  */
4735
4736 static size_t
4737 round_alloc_size (size_t s)
4738 {
4739   return s;
4740 }
4741
4742
4743 /* The genmatch generator progam.  It reads from a pattern description
4744    and outputs GIMPLE or GENERIC IL matching and simplification routines.  */
4745
4746 int
4747 main (int argc, char **argv)
4748 {
4749   cpp_reader *r;
4750
4751   progname = "genmatch";
4752
4753   if (argc < 2)
4754     return 1;
4755
4756   bool gimple = true;
4757   char *input = argv[argc-1];
4758   for (int i = 1; i < argc - 1; ++i)
4759     {
4760       if (strcmp (argv[i], "--gimple") == 0)
4761         gimple = true;
4762       else if (strcmp (argv[i], "--generic") == 0)
4763         gimple = false;
4764       else if (strcmp (argv[i], "-v") == 0)
4765         verbose = 1;
4766       else if (strcmp (argv[i], "-vv") == 0)
4767         verbose = 2;
4768       else
4769         {
4770           fprintf (stderr, "Usage: genmatch "
4771                    "[--gimple] [--generic] [-v[v]] input\n");
4772           return 1;
4773         }
4774     }
4775
4776   line_table = XCNEW (struct line_maps);
4777   linemap_init (line_table, 0);
4778   line_table->reallocator = xrealloc;
4779   line_table->round_alloc_size = round_alloc_size;
4780
4781   r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
4782   cpp_callbacks *cb = cpp_get_callbacks (r);
4783   cb->error = error_cb;
4784
4785   /* Add the build directory to the #include "" search path.  */
4786   cpp_dir *dir = XCNEW (cpp_dir);
4787   dir->name = getpwd ();
4788   if (!dir->name)
4789     dir->name = ASTRDUP (".");
4790   cpp_set_include_chains (r, dir, NULL, false);
4791
4792   if (!cpp_read_main_file (r, input))
4793     return 1;
4794   cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
4795   cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
4796
4797   null_id = new id_base (id_base::NULL_ID, "null");
4798
4799   /* Pre-seed operators.  */
4800   operators = new hash_table<id_base> (1024);
4801 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
4802   add_operator (SYM, # SYM, # TYPE, NARGS);
4803 #define END_OF_BASE_TREE_CODES
4804 #include "tree.def"
4805 add_operator (CONVERT0, "convert0", "tcc_unary", 1);
4806 add_operator (CONVERT1, "convert1", "tcc_unary", 1);
4807 add_operator (CONVERT2, "convert2", "tcc_unary", 1);
4808 add_operator (VIEW_CONVERT0, "view_convert0", "tcc_unary", 1);
4809 add_operator (VIEW_CONVERT1, "view_convert1", "tcc_unary", 1);
4810 add_operator (VIEW_CONVERT2, "view_convert2", "tcc_unary", 1);
4811 #undef END_OF_BASE_TREE_CODES
4812 #undef DEFTREECODE
4813
4814   /* Pre-seed builtin functions.
4815      ???  Cannot use N (name) as that is targetm.emultls.get_address
4816      for BUILT_IN_EMUTLS_GET_ADDRESS ... */
4817 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
4818   add_function (ENUM, "CFN_" # ENUM);
4819 #include "builtins.def"
4820
4821 #define DEF_INTERNAL_FN(CODE, NAME, FNSPEC) \
4822   add_function (IFN_##CODE, "CFN_" #CODE);
4823 #include "internal-fn.def"
4824
4825   /* Parse ahead!  */
4826   parser p (r);
4827
4828   if (gimple)
4829     write_header (stdout, "gimple-match-head.c");
4830   else
4831     write_header (stdout, "generic-match-head.c");
4832
4833   /* Go over all predicates defined with patterns and perform
4834      lowering and code generation.  */
4835   for (unsigned i = 0; i < p.user_predicates.length (); ++i)
4836     {
4837       predicate_id *pred = p.user_predicates[i];
4838       lower (pred->matchers, gimple);
4839
4840       if (verbose == 2)
4841         for (unsigned i = 0; i < pred->matchers.length (); ++i)
4842           print_matches (pred->matchers[i]);
4843
4844       decision_tree dt;
4845       for (unsigned i = 0; i < pred->matchers.length (); ++i)
4846         dt.insert (pred->matchers[i], i);
4847
4848       if (verbose == 2)
4849         dt.print (stderr);
4850
4851       write_predicate (stdout, pred, dt, gimple);
4852     }
4853
4854   /* Lower the main simplifiers and generate code for them.  */
4855   lower (p.simplifiers, gimple);
4856
4857   if (verbose == 2)
4858     for (unsigned i = 0; i < p.simplifiers.length (); ++i)
4859       print_matches (p.simplifiers[i]);
4860
4861   decision_tree dt;
4862   for (unsigned i = 0; i < p.simplifiers.length (); ++i)
4863     dt.insert (p.simplifiers[i], i);
4864
4865   if (verbose == 2)
4866     dt.print (stderr);
4867
4868   dt.gen (stdout, gimple);
4869
4870   /* Finalize.  */
4871   cpp_finish (r, NULL);
4872   cpp_destroy (r);
4873
4874   delete operators;
4875
4876   return 0;
4877 }