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