genmatch.c (capture_info::walk_c_expr): Ignore capture uses inside TREE_TYPE ().
[gcc.git] / gcc / genmatch.c
1 /* Generate pattern matching and transform code shared between
2 GENERIC and GIMPLE folding code from match-and-simplify description.
3
4 Copyright (C) 2014 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 <new>
26 #include <map>
27 #include <utility>
28 #include <string>
29 #include "system.h"
30 #include "coretypes.h"
31 #include <cpplib.h>
32 #include "errors.h"
33 #include "hashtab.h"
34 #include "hash-table.h"
35 #include "vec.h"
36 #include "is-a.h"
37
38
39 /* libccp helpers. */
40
41 static struct line_maps *line_table;
42
43 static bool
44 #if GCC_VERSION >= 4001
45 __attribute__((format (printf, 6, 0)))
46 #endif
47 error_cb (cpp_reader *, int, int, source_location location,
48 unsigned int, const char *msg, va_list *ap)
49 {
50 const line_map *map;
51 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
52 expanded_location loc = linemap_expand_location (line_table, map, location);
53 fprintf (stderr, "%s:%d:%d error: ", loc.file, loc.line, loc.column);
54 vfprintf (stderr, msg, *ap);
55 fprintf (stderr, "\n");
56 FILE *f = fopen (loc.file, "r");
57 if (f)
58 {
59 char buf[128];
60 while (loc.line > 0)
61 {
62 if (!fgets (buf, 128, f))
63 goto notfound;
64 if (buf[strlen (buf) - 1] != '\n')
65 {
66 if (loc.line > 1)
67 loc.line++;
68 }
69 loc.line--;
70 }
71 fprintf (stderr, "%s", buf);
72 for (int i = 0; i < loc.column - 1; ++i)
73 fputc (' ', stderr);
74 fputc ('^', stderr);
75 fputc ('\n', stderr);
76 notfound:
77 fclose (f);
78 }
79 exit (1);
80 }
81
82 static void
83 #if GCC_VERSION >= 4001
84 __attribute__((format (printf, 2, 3)))
85 #endif
86 fatal_at (const cpp_token *tk, const char *msg, ...)
87 {
88 va_list ap;
89 va_start (ap, msg);
90 error_cb (NULL, CPP_DL_FATAL, 0, tk->src_loc, 0, msg, &ap);
91 va_end (ap);
92 }
93
94 static void
95 output_line_directive (FILE *f, source_location location,
96 bool dumpfile = false)
97 {
98 const line_map *map;
99 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
100 expanded_location loc = linemap_expand_location (line_table, map, location);
101 if (dumpfile)
102 {
103 /* When writing to a dumpfile only dump the filename. */
104 const char *file = strrchr (loc.file, DIR_SEPARATOR);
105 if (!file)
106 file = loc.file;
107 else
108 ++file;
109 fprintf (f, "%s:%d", file, loc.line);
110 }
111 else
112 /* Other gen programs really output line directives here, at least for
113 development it's right now more convenient to have line information
114 from the generated file. Still keep the directives as comment for now
115 to easily back-point to the meta-description. */
116 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
117 }
118
119
120 /* Pull in tree codes and builtin function codes from their
121 definition files. */
122
123 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
124 enum tree_code {
125 #include "tree.def"
126 CONVERT0,
127 CONVERT1,
128 CONVERT2,
129 MAX_TREE_CODES
130 };
131 #undef DEFTREECODE
132
133 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
134 enum built_in_function {
135 #include "builtins.def"
136 END_BUILTINS
137 };
138 #undef DEF_BUILTIN
139
140
141 /* Base class for all identifiers the parser knows. */
142
143 struct id_base : typed_noop_remove<id_base>
144 {
145 enum id_kind { CODE, FN, PREDICATE, USER } kind;
146
147 id_base (id_kind, const char *, int = -1);
148
149 hashval_t hashval;
150 int nargs;
151 const char *id;
152
153 /* hash_table support. */
154 typedef id_base value_type;
155 typedef id_base compare_type;
156 static inline hashval_t hash (const value_type *);
157 static inline int equal (const value_type *, const compare_type *);
158 };
159
160 inline hashval_t
161 id_base::hash (const value_type *op)
162 {
163 return op->hashval;
164 }
165
166 inline int
167 id_base::equal (const value_type *op1,
168 const compare_type *op2)
169 {
170 return (op1->hashval == op2->hashval
171 && strcmp (op1->id, op2->id) == 0);
172 }
173
174 /* Hashtable of known pattern operators. This is pre-seeded from
175 all known tree codes and all known builtin function ids. */
176 static hash_table<id_base> *operators;
177
178 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
179 {
180 kind = kind_;
181 id = id_;
182 nargs = nargs_;
183 hashval = htab_hash_string (id);
184 }
185
186 /* Identifier that maps to a tree code. */
187
188 struct operator_id : public id_base
189 {
190 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
191 const char *tcc_)
192 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
193 enum tree_code code;
194 const char *tcc;
195 };
196
197 /* Identifier that maps to a builtin function code. */
198
199 struct fn_id : public id_base
200 {
201 fn_id (enum built_in_function fn_, const char *id_)
202 : id_base (id_base::FN, id_), fn (fn_) {}
203 enum built_in_function fn;
204 };
205
206 struct simplify;
207
208 /* Identifier that maps to a user-defined predicate. */
209
210 struct predicate_id : public id_base
211 {
212 predicate_id (const char *id_)
213 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
214 vec<simplify *> matchers;
215 };
216
217 /* Identifier that maps to a operator defined by a 'for' directive. */
218
219 struct user_id : public id_base
220 {
221 user_id (const char *id_)
222 : id_base (id_base::USER, id_), substitutes (vNULL) {}
223 vec<id_base *> substitutes;
224 };
225
226 template<>
227 template<>
228 inline bool
229 is_a_helper <fn_id *>::test (id_base *id)
230 {
231 return id->kind == id_base::FN;
232 }
233
234 template<>
235 template<>
236 inline bool
237 is_a_helper <operator_id *>::test (id_base *id)
238 {
239 return id->kind == id_base::CODE;
240 }
241
242 template<>
243 template<>
244 inline bool
245 is_a_helper <predicate_id *>::test (id_base *id)
246 {
247 return id->kind == id_base::PREDICATE;
248 }
249
250 template<>
251 template<>
252 inline bool
253 is_a_helper <user_id *>::test (id_base *id)
254 {
255 return id->kind == id_base::USER;
256 }
257
258 /* Add a predicate identifier to the hash. */
259
260 static predicate_id *
261 add_predicate (const char *id)
262 {
263 predicate_id *p = new predicate_id (id);
264 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
265 if (*slot)
266 fatal ("duplicate id definition");
267 *slot = p;
268 return p;
269 }
270
271 /* Add a tree code identifier to the hash. */
272
273 static void
274 add_operator (enum tree_code code, const char *id,
275 const char *tcc, unsigned nargs)
276 {
277 if (strcmp (tcc, "tcc_unary") != 0
278 && strcmp (tcc, "tcc_binary") != 0
279 && strcmp (tcc, "tcc_comparison") != 0
280 && strcmp (tcc, "tcc_expression") != 0
281 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
282 && strcmp (tcc, "tcc_reference") != 0
283 /* To have INTEGER_CST and friends as "predicate operators". */
284 && strcmp (tcc, "tcc_constant") != 0)
285 return;
286 operator_id *op = new operator_id (code, id, nargs, tcc);
287 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
288 if (*slot)
289 fatal ("duplicate id definition");
290 *slot = op;
291 }
292
293 /* Add a builtin identifier to the hash. */
294
295 static void
296 add_builtin (enum built_in_function code, const char *id)
297 {
298 fn_id *fn = new fn_id (code, id);
299 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
300 if (*slot)
301 fatal ("duplicate id definition");
302 *slot = fn;
303 }
304
305 /* Helper for easy comparing ID with tree code CODE. */
306
307 static bool
308 operator==(id_base &id, enum tree_code code)
309 {
310 if (operator_id *oid = dyn_cast <operator_id *> (&id))
311 return oid->code == code;
312 return false;
313 }
314
315 /* Lookup the identifier ID. */
316
317 id_base *
318 get_operator (const char *id)
319 {
320 id_base tem (id_base::CODE, id);
321
322 id_base *op = operators->find_with_hash (&tem, tem.hashval);
323 if (op)
324 return op;
325
326 /* Try all-uppercase. */
327 char *id2 = xstrdup (id);
328 for (unsigned i = 0; i < strlen (id2); ++i)
329 id2[i] = TOUPPER (id2[i]);
330 new (&tem) id_base (id_base::CODE, id2);
331 op = operators->find_with_hash (&tem, tem.hashval);
332 if (op)
333 {
334 free (id2);
335 return op;
336 }
337
338 /* Try _EXPR appended. */
339 id2 = (char *)xrealloc (id2, strlen (id2) + sizeof ("_EXPR") + 1);
340 strcat (id2, "_EXPR");
341 new (&tem) id_base (id_base::CODE, id2);
342 op = operators->find_with_hash (&tem, tem.hashval);
343 if (op)
344 {
345 free (id2);
346 return op;
347 }
348
349 return 0;
350 }
351
352
353
354 /* The AST produced by parsing of the pattern definitions. */
355
356 struct dt_operand;
357
358 /* The base class for operands. */
359
360 struct operand {
361 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR };
362 operand (enum op_type type_) : type (type_) {}
363 enum op_type type;
364 virtual void gen_transform (FILE *, const char *, bool, int,
365 const char *, dt_operand ** = 0)
366 { gcc_unreachable (); }
367 };
368
369 /* A predicate operand. Predicates are leafs in the AST. */
370
371 struct predicate : public operand
372 {
373 predicate (predicate_id *p_) : operand (OP_PREDICATE), p (p_) {}
374 predicate_id *p;
375 };
376
377 /* An operand that constitutes an expression. Expressions include
378 function calls and user-defined predicate invocations. */
379
380 struct expr : public operand
381 {
382 expr (id_base *operation_, bool is_commutative_ = false)
383 : operand (OP_EXPR), operation (operation_),
384 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_) {}
385 void append_op (operand *op) { ops.safe_push (op); }
386 /* The operator and its operands. */
387 id_base *operation;
388 vec<operand *> ops;
389 /* An explicitely specified type - used exclusively for conversions. */
390 const char *expr_type;
391 /* Whether the operation is to be applied commutatively. This is
392 later lowered to two separate patterns. */
393 bool is_commutative;
394 virtual void gen_transform (FILE *f, const char *, bool, int,
395 const char *, dt_operand ** = 0);
396 };
397
398 /* An operator that is represented by native C code. This is always
399 a leaf operand in the AST. This class is also used to represent
400 the code to be generated for 'if' and 'with' expressions. */
401
402 struct c_expr : public operand
403 {
404 /* A mapping of an identifier and its replacement. Used to apply
405 'for' lowering. */
406 struct id_tab {
407 const char *id;
408 const char *oper;
409 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
410 };
411
412 c_expr (cpp_reader *r_, vec<cpp_token> code_, unsigned nr_stmts_,
413 vec<id_tab> ids_, std::map<std::string, unsigned> *capture_ids_)
414 : operand (OP_C_EXPR), r (r_), code (code_), capture_ids (capture_ids_),
415 nr_stmts (nr_stmts_), ids (ids_) {}
416 /* cpplib tokens and state to transform this back to source. */
417 cpp_reader *r;
418 vec<cpp_token> code;
419 std::map<std::string, unsigned> *capture_ids;
420 /* The number of statements parsed (well, the number of ';'s). */
421 unsigned nr_stmts;
422 /* The identifier replacement vector. */
423 vec<id_tab> ids;
424 virtual void gen_transform (FILE *f, const char *, bool, int,
425 const char *, dt_operand **);
426 };
427
428 /* A wrapper around another operand that captures its value. */
429
430 struct capture : public operand
431 {
432 capture (unsigned where_, operand *what_)
433 : operand (OP_CAPTURE), where (where_), what (what_) {}
434 /* Identifier index for the value. */
435 unsigned where;
436 /* The captured value. */
437 operand *what;
438 virtual void gen_transform (FILE *f, const char *, bool, int,
439 const char *, dt_operand ** = 0);
440 };
441
442 template<>
443 template<>
444 inline bool
445 is_a_helper <capture *>::test (operand *op)
446 {
447 return op->type == operand::OP_CAPTURE;
448 }
449
450 template<>
451 template<>
452 inline bool
453 is_a_helper <predicate *>::test (operand *op)
454 {
455 return op->type == operand::OP_PREDICATE;
456 }
457
458 template<>
459 template<>
460 inline bool
461 is_a_helper <c_expr *>::test (operand *op)
462 {
463 return op->type == operand::OP_C_EXPR;
464 }
465
466 template<>
467 template<>
468 inline bool
469 is_a_helper <expr *>::test (operand *op)
470 {
471 return op->type == operand::OP_EXPR;
472 }
473
474 /* Helper to distinguish 'if' from 'with' expressions. */
475
476 struct if_or_with
477 {
478 if_or_with (operand *cexpr_, source_location location_, bool is_with_)
479 : location (location_), cexpr (cexpr_), is_with (is_with_) {}
480 source_location location;
481 operand *cexpr;
482 bool is_with;
483 };
484
485 /* The main class of a pattern and its transform. This is used to
486 represent both (simplify ...) and (match ...) kinds. The AST
487 duplicates all outer 'if' and 'for' expressions here so each
488 simplify can exist in isolation. */
489
490 struct simplify
491 {
492 simplify (operand *match_, source_location match_location_,
493 struct operand *result_, source_location result_location_,
494 vec<if_or_with> ifexpr_vec_, vec<vec<user_id *> > for_vec_,
495 std::map<std::string, unsigned> *capture_ids_)
496 : match (match_), match_location (match_location_),
497 result (result_), result_location (result_location_),
498 ifexpr_vec (ifexpr_vec_), for_vec (for_vec_),
499 capture_ids (capture_ids_), capture_max (capture_ids_->size () - 1) {}
500
501 /* The expression that is matched against the GENERIC or GIMPLE IL. */
502 operand *match;
503 source_location match_location;
504 /* For a (simplify ...) the expression produced when the pattern applies.
505 For a (match ...) either NULL if it is a simple predicate or the
506 single expression specifying the matched operands. */
507 struct operand *result;
508 source_location result_location;
509 /* Collected 'if' expressions that need to evaluate to true to make
510 the pattern apply. */
511 vec<if_or_with> ifexpr_vec;
512 /* Collected 'for' expression operators that have to be replaced
513 in the lowering phase. */
514 vec<vec<user_id *> > for_vec;
515 /* A map of capture identifiers to indexes. */
516 std::map<std::string, unsigned> *capture_ids;
517 int capture_max;
518 };
519
520 /* Debugging routines for dumping the AST. */
521
522 DEBUG_FUNCTION void
523 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
524 {
525 if (capture *c = dyn_cast<capture *> (o))
526 {
527 fprintf (f, "@%u", c->where);
528 if (c->what && flattened == false)
529 {
530 putc (':', f);
531 print_operand (c->what, f, flattened);
532 putc (' ', f);
533 }
534 }
535
536 else if (predicate *p = dyn_cast<predicate *> (o))
537 fprintf (f, "%s", p->p->id);
538
539 else if (is_a<c_expr *> (o))
540 fprintf (f, "c_expr");
541
542 else if (expr *e = dyn_cast<expr *> (o))
543 {
544 fprintf (f, "(%s", e->operation->id);
545
546 if (flattened == false)
547 {
548 putc (' ', f);
549 for (unsigned i = 0; i < e->ops.length (); ++i)
550 {
551 print_operand (e->ops[i], f, flattened);
552 putc (' ', f);
553 }
554 }
555 putc (')', f);
556 }
557
558 else
559 gcc_unreachable ();
560 }
561
562 DEBUG_FUNCTION void
563 print_matches (struct simplify *s, FILE *f = stderr)
564 {
565 fprintf (f, "for expression: ");
566 print_operand (s->match, f);
567 putc ('\n', f);
568 }
569
570
571 /* AST lowering. */
572
573 /* Lowering of commutative operators. */
574
575 static void
576 cartesian_product (const vec< vec<operand *> >& ops_vector,
577 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
578 {
579 if (n == ops_vector.length ())
580 {
581 vec<operand *> xv = v.copy ();
582 result.safe_push (xv);
583 return;
584 }
585
586 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
587 {
588 v[n] = ops_vector[n][i];
589 cartesian_product (ops_vector, result, v, n + 1);
590 }
591 }
592
593 /* Lower OP to two operands in case it is marked as commutative. */
594
595 static vec<operand *>
596 commutate (operand *op)
597 {
598 vec<operand *> ret = vNULL;
599
600 if (capture *c = dyn_cast <capture *> (op))
601 {
602 if (!c->what)
603 {
604 ret.safe_push (op);
605 return ret;
606 }
607 vec<operand *> v = commutate (c->what);
608 for (unsigned i = 0; i < v.length (); ++i)
609 {
610 capture *nc = new capture (c->where, v[i]);
611 ret.safe_push (nc);
612 }
613 return ret;
614 }
615
616 expr *e = dyn_cast <expr *> (op);
617 if (!e || e->ops.length () == 0)
618 {
619 ret.safe_push (op);
620 return ret;
621 }
622
623 vec< vec<operand *> > ops_vector = vNULL;
624 for (unsigned i = 0; i < e->ops.length (); ++i)
625 ops_vector.safe_push (commutate (e->ops[i]));
626
627 auto_vec< vec<operand *> > result;
628 auto_vec<operand *> v (e->ops.length ());
629 v.quick_grow_cleared (e->ops.length ());
630 cartesian_product (ops_vector, result, v, 0);
631
632
633 for (unsigned i = 0; i < result.length (); ++i)
634 {
635 expr *ne = new expr (e->operation);
636 for (unsigned j = 0; j < result[i].length (); ++j)
637 ne->append_op (result[i][j]);
638 ret.safe_push (ne);
639 }
640
641 if (!e->is_commutative)
642 return ret;
643
644 for (unsigned i = 0; i < result.length (); ++i)
645 {
646 expr *ne = new expr (e->operation);
647 // result[i].length () is 2 since e->operation is binary
648 for (unsigned j = result[i].length (); j; --j)
649 ne->append_op (result[i][j-1]);
650 ret.safe_push (ne);
651 }
652
653 return ret;
654 }
655
656 /* Lower operations marked as commutative in the AST of S and push
657 the resulting patterns to SIMPLIFIERS. */
658
659 static void
660 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
661 {
662 vec<operand *> matchers = commutate (s->match);
663 for (unsigned i = 0; i < matchers.length (); ++i)
664 {
665 simplify *ns = new simplify (matchers[i], s->match_location,
666 s->result, s->result_location, s->ifexpr_vec,
667 s->for_vec, s->capture_ids);
668 simplifiers.safe_push (ns);
669 }
670 }
671
672 /* Strip conditional conversios using operator OPER from O and its
673 children if STRIP, else replace them with an unconditional convert. */
674
675 operand *
676 lower_opt_convert (operand *o, enum tree_code oper, bool strip)
677 {
678 if (capture *c = dyn_cast<capture *> (o))
679 {
680 if (c->what)
681 return new capture (c->where, lower_opt_convert (c->what, oper, strip));
682 else
683 return c;
684 }
685
686 expr *e = dyn_cast<expr *> (o);
687 if (!e)
688 return o;
689
690 if (*e->operation == oper)
691 {
692 if (strip)
693 return lower_opt_convert (e->ops[0], oper, strip);
694
695 expr *ne = new expr (get_operator ("CONVERT_EXPR"));
696 ne->append_op (lower_opt_convert (e->ops[0], oper, strip));
697 return ne;
698 }
699
700 expr *ne = new expr (e->operation, e->is_commutative);
701 for (unsigned i = 0; i < e->ops.length (); ++i)
702 ne->append_op (lower_opt_convert (e->ops[i], oper, strip));
703
704 return ne;
705 }
706
707 /* Determine whether O or its children uses the conditional conversion
708 operator OPER. */
709
710 static bool
711 has_opt_convert (operand *o, enum tree_code oper)
712 {
713 if (capture *c = dyn_cast<capture *> (o))
714 {
715 if (c->what)
716 return has_opt_convert (c->what, oper);
717 else
718 return false;
719 }
720
721 expr *e = dyn_cast<expr *> (o);
722 if (!e)
723 return false;
724
725 if (*e->operation == oper)
726 return true;
727
728 for (unsigned i = 0; i < e->ops.length (); ++i)
729 if (has_opt_convert (e->ops[i], oper))
730 return true;
731
732 return false;
733 }
734
735 /* Lower conditional convert operators in O, expanding it to a vector
736 if required. */
737
738 static vec<operand *>
739 lower_opt_convert (operand *o)
740 {
741 vec<operand *> v1 = vNULL, v2;
742
743 v1.safe_push (o);
744
745 enum tree_code opers[] = { CONVERT0, CONVERT1, CONVERT2 };
746
747 /* Conditional converts are lowered to a pattern with the
748 conversion and one without. The three different conditional
749 convert codes are lowered separately. */
750
751 for (unsigned i = 0; i < 3; ++i)
752 {
753 v2 = vNULL;
754 for (unsigned j = 0; j < v1.length (); ++j)
755 if (has_opt_convert (v1[j], opers[i]))
756 {
757 v2.safe_push (lower_opt_convert (v1[j], opers[i], false));
758 v2.safe_push (lower_opt_convert (v1[j], opers[i], true));
759 }
760
761 if (v2 != vNULL)
762 {
763 v1 = vNULL;
764 for (unsigned j = 0; j < v2.length (); ++j)
765 v1.safe_push (v2[j]);
766 }
767 }
768
769 return v1;
770 }
771
772 /* Lower conditional convert operators in the AST of S and push
773 the resulting multiple patterns to SIMPLIFIERS. */
774
775 static void
776 lower_opt_convert (simplify *s, vec<simplify *>& simplifiers)
777 {
778 vec<operand *> matchers = lower_opt_convert (s->match);
779 for (unsigned i = 0; i < matchers.length (); ++i)
780 {
781 simplify *ns = new simplify (matchers[i], s->match_location,
782 s->result, s->result_location, s->ifexpr_vec,
783 s->for_vec, s->capture_ids);
784 simplifiers.safe_push (ns);
785 }
786 }
787
788 /* In AST operand O replace operator ID with operator WITH. */
789
790 operand *
791 replace_id (operand *o, user_id *id, id_base *with)
792 {
793 /* Deep-copy captures and expressions, replacing operations as
794 needed. */
795 if (capture *c = dyn_cast<capture *> (o))
796 {
797 if (!c->what)
798 return c;
799 return new capture (c->where, replace_id (c->what, id, with));
800 }
801 else if (expr *e = dyn_cast<expr *> (o))
802 {
803 expr *ne = new expr (e->operation == id ? with : e->operation,
804 e->is_commutative);
805 for (unsigned i = 0; i < e->ops.length (); ++i)
806 ne->append_op (replace_id (e->ops[i], id, with));
807 return ne;
808 }
809
810 /* For c_expr we simply record a string replacement table which is
811 applied at code-generation time. */
812 if (c_expr *ce = dyn_cast<c_expr *> (o))
813 {
814 vec<c_expr::id_tab> ids = ce->ids.copy ();
815 ids.safe_push (c_expr::id_tab (id->id, with->id));
816 return new c_expr (ce->r, ce->code, ce->nr_stmts, ids, ce->capture_ids);
817 }
818
819 return o;
820 }
821
822 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
823
824 static void
825 lower_for (simplify *sin, vec<simplify *>& simplifiers)
826 {
827 vec<vec<user_id *> >& for_vec = sin->for_vec;
828 unsigned worklist_start = 0;
829 auto_vec<simplify *> worklist;
830 worklist.safe_push (sin);
831
832 /* Lower each recorded for separately, operating on the
833 set of simplifiers created by the previous one.
834 Lower inner-to-outer so inner for substitutes can refer
835 to operators replaced by outer fors. */
836 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
837 {
838 vec<user_id *>& ids = for_vec[fi];
839 unsigned n_ids = ids.length ();
840 unsigned max_n_opers = 0;
841 for (unsigned i = 0; i < n_ids; ++i)
842 if (ids[i]->substitutes.length () > max_n_opers)
843 max_n_opers = ids[i]->substitutes.length ();
844
845 unsigned worklist_end = worklist.length ();
846 for (unsigned si = worklist_start; si < worklist_end; ++si)
847 {
848 simplify *s = worklist[si];
849 for (unsigned j = 0; j < max_n_opers; ++j)
850 {
851 operand *match_op = s->match;
852 operand *result_op = s->result;
853 vec<if_or_with> ifexpr_vec = s->ifexpr_vec.copy ();
854
855 for (unsigned i = 0; i < n_ids; ++i)
856 {
857 user_id *id = ids[i];
858 id_base *oper = id->substitutes[j % id->substitutes.length ()];
859 match_op = replace_id (match_op, id, oper);
860 if (result_op)
861 result_op = replace_id (result_op, id, oper);
862 for (unsigned k = 0; k < s->ifexpr_vec.length (); ++k)
863 ifexpr_vec[k].cexpr = replace_id (ifexpr_vec[k].cexpr,
864 id, oper);
865 }
866 simplify *ns = new simplify (match_op, s->match_location,
867 result_op, s->result_location,
868 ifexpr_vec, vNULL, s->capture_ids);
869 worklist.safe_push (ns);
870 }
871 }
872 worklist_start = worklist_end;
873 }
874
875 /* Copy out the result from the last for lowering. */
876 for (unsigned i = worklist_start; i < worklist.length (); ++i)
877 simplifiers.safe_push (worklist[i]);
878 }
879
880 /* Lower the AST for everything in SIMPLIFIERS. */
881
882 static void
883 lower (vec<simplify *>& simplifiers)
884 {
885 auto_vec<simplify *> out_simplifiers0;
886 for (unsigned i = 0; i < simplifiers.length (); ++i)
887 lower_opt_convert (simplifiers[i], out_simplifiers0);
888
889 auto_vec<simplify *> out_simplifiers1;
890 for (unsigned i = 0; i < out_simplifiers0.length (); ++i)
891 lower_commutative (out_simplifiers0[i], out_simplifiers1);
892
893 simplifiers.truncate (0);
894 for (unsigned i = 0; i < out_simplifiers1.length (); ++i)
895 lower_for (out_simplifiers1[i], simplifiers);
896 }
897
898
899
900
901 /* The decision tree built for generating GIMPLE and GENERIC pattern
902 matching code. It represents the 'match' expression of all
903 simplifies and has those as its leafs. */
904
905 /* Decision tree base class, used for DT_TRUE and DT_NODE. */
906
907 struct dt_node
908 {
909 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
910
911 enum dt_type type;
912 unsigned level;
913 vec<dt_node *> kids;
914
915 dt_node (enum dt_type type_): type (type_), level (0), kids (vNULL) {}
916
917 dt_node *append_node (dt_node *);
918 dt_node *append_op (operand *, dt_node *parent = 0, unsigned pos = 0);
919 dt_node *append_true_op (dt_node *parent = 0, unsigned pos = 0);
920 dt_node *append_match_op (dt_operand *, dt_node *parent = 0, unsigned pos = 0);
921 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
922
923 virtual void gen (FILE *, bool) {}
924
925 void gen_kids (FILE *, bool);
926 };
927
928 /* Generic decision tree node used for DT_OPERAND and DT_MATCH. */
929
930 struct dt_operand : public dt_node
931 {
932 operand *op;
933 dt_operand *match_dop;
934 dt_operand *parent;
935 unsigned pos;
936
937 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
938 dt_operand *parent_ = 0, unsigned pos_ = 0)
939 : dt_node (type), op (op_), match_dop (match_dop_),
940 parent (parent_), pos (pos_) {}
941
942 void gen (FILE *, bool);
943 unsigned gen_predicate (FILE *, const char *, bool);
944 unsigned gen_match_op (FILE *, const char *);
945
946 unsigned gen_gimple_expr (FILE *);
947 unsigned gen_generic_expr (FILE *, const char *);
948
949 char *get_name (char *);
950 void gen_opname (char *, unsigned);
951 };
952
953 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
954
955 struct dt_simplify : public dt_node
956 {
957 simplify *s;
958 unsigned pattern_no;
959 dt_operand **indexes;
960
961 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
962 : dt_node (DT_SIMPLIFY), s (s_), pattern_no (pattern_no_),
963 indexes (indexes_) {}
964
965 void gen (FILE *f, bool);
966 };
967
968 template<>
969 template<>
970 inline bool
971 is_a_helper <dt_operand *>::test (dt_node *n)
972 {
973 return (n->type == dt_node::DT_OPERAND
974 || n->type == dt_node::DT_MATCH);
975 }
976
977 /* A container for the actual decision tree. */
978
979 struct decision_tree
980 {
981 dt_node *root;
982
983 void insert (struct simplify *, unsigned);
984 void gen_gimple (FILE *f = stderr);
985 void gen_generic (FILE *f = stderr);
986 void print (FILE *f = stderr);
987
988 decision_tree () { root = new dt_node (dt_node::DT_NODE); }
989
990 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
991 unsigned pos = 0, dt_node *parent = 0);
992 static dt_node *find_node (vec<dt_node *>&, dt_node *);
993 static bool cmp_node (dt_node *, dt_node *);
994 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
995 };
996
997 /* Compare two AST operands O1 and O2 and return true if they are equal. */
998
999 bool
1000 cmp_operand (operand *o1, operand *o2)
1001 {
1002 if (!o1 || !o2 || o1->type != o2->type)
1003 return false;
1004
1005 if (o1->type == operand::OP_PREDICATE)
1006 {
1007 predicate *p1 = as_a<predicate *>(o1);
1008 predicate *p2 = as_a<predicate *>(o2);
1009 return p1->p == p2->p;
1010 }
1011 else if (o1->type == operand::OP_EXPR)
1012 {
1013 expr *e1 = static_cast<expr *>(o1);
1014 expr *e2 = static_cast<expr *>(o2);
1015 return e1->operation == e2->operation;
1016 }
1017 else
1018 return false;
1019 }
1020
1021 /* Compare two decision tree nodes N1 and N2 and return true if they
1022 are equal. */
1023
1024 bool
1025 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1026 {
1027 if (!n1 || !n2 || n1->type != n2->type)
1028 return false;
1029
1030 if (n1 == n2 || n1->type == dt_node::DT_TRUE)
1031 return true;
1032
1033 if (n1->type == dt_node::DT_OPERAND)
1034 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1035 (as_a<dt_operand *> (n2))->op);
1036 else if (n1->type == dt_node::DT_MATCH)
1037 return ((as_a<dt_operand *> (n1))->match_dop
1038 == (as_a<dt_operand *> (n2))->match_dop);
1039 return false;
1040 }
1041
1042 /* Search OPS for a decision tree node like P and return it if found. */
1043
1044 dt_node *
1045 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1046 {
1047 for (unsigned i = 0; i < ops.length (); ++i)
1048 if (decision_tree::cmp_node (ops[i], p))
1049 return ops[i];
1050
1051 return NULL;
1052 }
1053
1054 /* Append N to the decision tree if it there is not already an existing
1055 identical child. */
1056
1057 dt_node *
1058 dt_node::append_node (dt_node *n)
1059 {
1060 dt_node *kid;
1061
1062 kid = decision_tree::find_node (kids, n);
1063 if (kid)
1064 return kid;
1065
1066 kids.safe_push (n);
1067 n->level = this->level + 1;
1068
1069 unsigned len = kids.length ();
1070
1071 if (len > 1 && kids[len - 2]->type == dt_node::DT_TRUE)
1072 {
1073 dt_node *p = kids[len - 2];
1074 kids[len - 2] = kids[len - 1];
1075 kids[len - 1] = p;
1076 }
1077
1078 return n;
1079 }
1080
1081 /* Append OP to the decision tree. */
1082
1083 dt_node *
1084 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1085 {
1086 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1087 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1088 return append_node (n);
1089 }
1090
1091 /* Append a DT_TRUE decision tree node. */
1092
1093 dt_node *
1094 dt_node::append_true_op (dt_node *parent, unsigned pos)
1095 {
1096 dt_operand *parent_ = as_a<dt_operand *> (parent);
1097 dt_operand *n = new dt_operand (DT_TRUE, 0, 0, parent_, pos);
1098 return append_node (n);
1099 }
1100
1101 /* Append a DT_MATCH decision tree node. */
1102
1103 dt_node *
1104 dt_node::append_match_op (dt_operand *match_dop, dt_node *parent, unsigned pos)
1105 {
1106 dt_operand *parent_ = as_a<dt_operand *> (parent);
1107 dt_operand *n = new dt_operand (DT_MATCH, 0, match_dop, parent_, pos);
1108 return append_node (n);
1109 }
1110
1111 /* Append S to the decision tree. */
1112
1113 dt_node *
1114 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1115 dt_operand **indexes)
1116 {
1117 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1118 return append_node (n);
1119 }
1120
1121 /* Insert O into the decision tree and return the decision tree node found
1122 or created. */
1123
1124 dt_node *
1125 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1126 unsigned pos, dt_node *parent)
1127 {
1128 dt_node *q, *elm = 0;
1129
1130 if (capture *c = dyn_cast<capture *> (o))
1131 {
1132 unsigned capt_index = c->where;
1133
1134 if (indexes[capt_index] == 0)
1135 {
1136 if (c->what)
1137 q = insert_operand (p, c->what, indexes, pos, parent);
1138 else
1139 {
1140 q = elm = p->append_true_op (parent, pos);
1141 goto at_assert_elm;
1142 }
1143 // get to the last capture
1144 for (operand *what = c->what;
1145 what && is_a<capture *> (what);
1146 c = as_a<capture *> (what), what = c->what)
1147 ;
1148
1149 if (!c->what)
1150 {
1151 unsigned cc_index = c->where;
1152 dt_operand *match_op = indexes[cc_index];
1153
1154 dt_operand temp (dt_node::DT_TRUE, 0, 0);
1155 elm = decision_tree::find_node (p->kids, &temp);
1156
1157 if (elm == 0)
1158 {
1159 dt_operand temp (dt_node::DT_MATCH, 0, match_op);
1160 elm = decision_tree::find_node (p->kids, &temp);
1161 }
1162 }
1163 else
1164 {
1165 dt_operand temp (dt_node::DT_OPERAND, c->what, 0);
1166 elm = decision_tree::find_node (p->kids, &temp);
1167 }
1168
1169 at_assert_elm:
1170 gcc_assert (elm->type == dt_node::DT_TRUE
1171 || elm->type == dt_node::DT_OPERAND
1172 || elm->type == dt_node::DT_MATCH);
1173 indexes[capt_index] = static_cast<dt_operand *> (elm);
1174 return q;
1175 }
1176 else
1177 {
1178 p = p->append_match_op (indexes[capt_index], parent, pos);
1179 if (c->what)
1180 return insert_operand (p, c->what, indexes, 0, p);
1181 else
1182 return p;
1183 }
1184 }
1185 p = p->append_op (o, parent, pos);
1186 q = p;
1187
1188 if (expr *e = dyn_cast <expr *>(o))
1189 {
1190 for (unsigned i = 0; i < e->ops.length (); ++i)
1191 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
1192 }
1193
1194 return q;
1195 }
1196
1197 /* Insert S into the decision tree. */
1198
1199 void
1200 decision_tree::insert (struct simplify *s, unsigned pattern_no)
1201 {
1202 if (s->match->type != operand::OP_EXPR)
1203 return;
1204
1205 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
1206 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
1207 p->append_simplify (s, pattern_no, indexes);
1208 }
1209
1210 /* Debug functions to dump the decision tree. */
1211
1212 DEBUG_FUNCTION void
1213 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
1214 {
1215 if (p->type == dt_node::DT_NODE)
1216 fprintf (f, "root");
1217 else
1218 {
1219 fprintf (f, "|");
1220 for (unsigned i = 0; i < indent; i++)
1221 fprintf (f, "-");
1222
1223 if (p->type == dt_node::DT_OPERAND)
1224 {
1225 dt_operand *dop = static_cast<dt_operand *>(p);
1226 print_operand (dop->op, f, true);
1227 }
1228 else if (p->type == dt_node::DT_TRUE)
1229 fprintf (f, "true");
1230 else if (p->type == dt_node::DT_MATCH)
1231 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
1232 else if (p->type == dt_node::DT_SIMPLIFY)
1233 {
1234 dt_simplify *s = static_cast<dt_simplify *> (p);
1235 fprintf (f, "simplify_%u { ", s->pattern_no);
1236 for (int i = 0; i <= s->s->capture_max; ++i)
1237 fprintf (f, "%p, ", (void *) s->indexes[i]);
1238 fprintf (f, " } ");
1239 }
1240 }
1241
1242 fprintf (stderr, " (%p), %u, %u\n", (void *) p, p->level, p->kids.length ());
1243
1244 for (unsigned i = 0; i < p->kids.length (); ++i)
1245 decision_tree::print_node (p->kids[i], f, indent + 2);
1246 }
1247
1248 DEBUG_FUNCTION void
1249 decision_tree::print (FILE *f)
1250 {
1251 return decision_tree::print_node (root, f);
1252 }
1253
1254
1255
1256 /* Code generation off the decision tree and the refered AST nodes. */
1257
1258 bool
1259 is_conversion (id_base *op)
1260 {
1261 return (*op == CONVERT_EXPR
1262 || *op == NOP_EXPR
1263 || *op == FLOAT_EXPR
1264 || *op == FIX_TRUNC_EXPR
1265 || *op == VIEW_CONVERT_EXPR);
1266 }
1267
1268 /* Get the type to be used for generating operands of OP from the
1269 various sources. */
1270
1271 static const char *
1272 get_operand_type (id_base *op, const char *in_type,
1273 const char *expr_type,
1274 const char *other_oprnd_type)
1275 {
1276 /* Generally operands whose type does not match the type of the
1277 expression generated need to know their types but match and
1278 thus can fall back to 'other_oprnd_type'. */
1279 if (is_conversion (op))
1280 return other_oprnd_type;
1281 else if (*op == REALPART_EXPR
1282 || *op == IMAGPART_EXPR)
1283 return other_oprnd_type;
1284 else if (is_a <operator_id *> (op)
1285 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
1286 return other_oprnd_type;
1287 else
1288 {
1289 /* Otherwise all types should match - choose one in order of
1290 preference. */
1291 if (expr_type)
1292 return expr_type;
1293 else if (in_type)
1294 return in_type;
1295 else
1296 return other_oprnd_type;
1297 }
1298 }
1299
1300 /* Generate transform code for an expression. */
1301
1302 void
1303 expr::gen_transform (FILE *f, const char *dest, bool gimple, int depth,
1304 const char *in_type, dt_operand **indexes)
1305 {
1306 bool conversion_p = is_conversion (operation);
1307 const char *type = expr_type;
1308 char optype[64];
1309 if (type)
1310 /* If there was a type specification in the pattern use it. */
1311 ;
1312 else if (conversion_p)
1313 /* For conversions we need to build the expression using the
1314 outer type passed in. */
1315 type = in_type;
1316 else if (*operation == REALPART_EXPR
1317 || *operation == IMAGPART_EXPR)
1318 {
1319 /* __real and __imag use the component type of its operand. */
1320 sprintf (optype, "TREE_TYPE (TREE_TYPE (ops%d[0]))", depth);
1321 type = optype;
1322 }
1323 else if (is_a <operator_id *> (operation)
1324 && !strcmp (as_a <operator_id *> (operation)->tcc, "tcc_comparison"))
1325 {
1326 /* comparisons use boolean_type_node (or what gets in), but
1327 their operands need to figure out the types themselves. */
1328 sprintf (optype, "boolean_type_node");
1329 type = optype;
1330 }
1331 else
1332 {
1333 /* Other operations are of the same type as their first operand. */
1334 sprintf (optype, "TREE_TYPE (ops%d[0])", depth);
1335 type = optype;
1336 }
1337 if (!type)
1338 fatal ("two conversions in a row");
1339
1340 fprintf (f, "{\n");
1341 fprintf (f, " tree ops%d[%u], res;\n", depth, ops.length ());
1342 char op0type[64];
1343 snprintf (op0type, 64, "TREE_TYPE (ops%d[0])", depth);
1344 for (unsigned i = 0; i < ops.length (); ++i)
1345 {
1346 char dest[32];
1347 snprintf (dest, 32, " ops%d[%u]", depth, i);
1348 const char *optype
1349 = get_operand_type (operation, in_type, expr_type,
1350 i == 0 ? NULL : op0type);
1351 ops[i]->gen_transform (f, dest, gimple, depth + 1, optype, indexes);
1352 }
1353
1354 if (gimple)
1355 {
1356 /* ??? Have another helper that is like gimple_build but may
1357 fail if seq == NULL. */
1358 fprintf (f, " if (!seq)\n"
1359 " {\n"
1360 " res = gimple_simplify (%s, %s",
1361 operation->id, type);
1362 for (unsigned i = 0; i < ops.length (); ++i)
1363 fprintf (f, ", ops%d[%u]", depth, i);
1364 fprintf (f, ", seq, valueize);\n");
1365 fprintf (f, " if (!res) return false;\n");
1366 fprintf (f, " }\n");
1367 fprintf (f, " else\n");
1368 fprintf (f, " res = gimple_build (seq, UNKNOWN_LOCATION, %s, %s",
1369 operation->id, type);
1370 for (unsigned i = 0; i < ops.length (); ++i)
1371 fprintf (f, ", ops%d[%u]", depth, i);
1372 fprintf (f, ", valueize);\n");
1373 }
1374 else
1375 {
1376 if (operation->kind == id_base::CODE)
1377 fprintf (f, " res = fold_build%d_loc (loc, %s, %s",
1378 ops.length(), operation->id, type);
1379 else
1380 fprintf (f, " res = build_call_expr_loc (loc, "
1381 "builtin_decl_implicit (%s), %d",
1382 operation->id, ops.length());
1383 for (unsigned i = 0; i < ops.length (); ++i)
1384 fprintf (f, ", ops%d[%u]", depth, i);
1385 fprintf (f, ");\n");
1386 }
1387 fprintf (f, " %s = res;\n", dest);
1388 fprintf (f, "}\n");
1389 }
1390
1391 /* Generate code for a c_expr which is either the expression inside
1392 an if statement or a sequence of statements which computes a
1393 result to be stored to DEST. */
1394
1395 void
1396 c_expr::gen_transform (FILE *f, const char *dest,
1397 bool, int, const char *, dt_operand **)
1398 {
1399 if (dest && nr_stmts == 1)
1400 fprintf (f, "%s = ", dest);
1401
1402 unsigned stmt_nr = 1;
1403 for (unsigned i = 0; i < code.length (); ++i)
1404 {
1405 const cpp_token *token = &code[i];
1406
1407 /* Replace captures for code-gen. */
1408 if (token->type == CPP_ATSIGN)
1409 {
1410 const cpp_token *n = &code[i+1];
1411 if ((n->type == CPP_NUMBER
1412 || n->type == CPP_NAME)
1413 && !(n->flags & PREV_WHITE))
1414 {
1415 if (token->flags & PREV_WHITE)
1416 fputc (' ', f);
1417 const char *id;
1418 if (n->type == CPP_NUMBER)
1419 id = (const char *)n->val.str.text;
1420 else
1421 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
1422 fprintf (f, "captures[%u]", (*capture_ids)[id]);
1423 ++i;
1424 continue;
1425 }
1426 }
1427
1428 if (token->flags & PREV_WHITE)
1429 fputc (' ', f);
1430
1431 if (token->type == CPP_NAME)
1432 {
1433 const char *id = (const char *) NODE_NAME (token->val.node.node);
1434 unsigned j;
1435 for (j = 0; j < ids.length (); ++j)
1436 {
1437 if (strcmp (id, ids[j].id) == 0)
1438 {
1439 fprintf (f, "%s", ids[j].oper);
1440 break;
1441 }
1442 }
1443 if (j < ids.length ())
1444 continue;
1445 }
1446
1447 /* Output the token as string. */
1448 char *tk = (char *)cpp_token_as_text (r, token);
1449 fputs (tk, f);
1450
1451 if (token->type == CPP_SEMICOLON)
1452 {
1453 stmt_nr++;
1454 if (dest && stmt_nr == nr_stmts)
1455 fprintf (f, "\n %s = ", dest);
1456 else
1457 fputc ('\n', f);
1458 }
1459 }
1460 }
1461
1462 /* Generate transform code for a capture. */
1463
1464 void
1465 capture::gen_transform (FILE *f, const char *dest, bool gimple, int depth,
1466 const char *in_type, dt_operand **indexes)
1467 {
1468 if (what && is_a<expr *> (what))
1469 {
1470 if (indexes[where] == 0)
1471 {
1472 char buf[20];
1473 sprintf (buf, "captures[%u]", where);
1474 what->gen_transform (f, buf, gimple, depth, in_type, NULL);
1475 }
1476 }
1477
1478 fprintf (f, "%s = captures[%u];\n", dest, where);
1479 }
1480
1481 /* Return the name of the operand representing the decision tree node.
1482 Use NAME as space to generate it. */
1483
1484 char *
1485 dt_operand::get_name (char *name)
1486 {
1487 if (!parent)
1488 sprintf (name, "t");
1489 else if (parent->level == 1)
1490 sprintf (name, "op%u", pos);
1491 else if (parent->type == dt_node::DT_MATCH)
1492 return parent->get_name (name);
1493 else
1494 sprintf (name, "o%u%u", parent->level, pos);
1495 return name;
1496 }
1497
1498 /* Fill NAME with the operand name at position POS. */
1499
1500 void
1501 dt_operand::gen_opname (char *name, unsigned pos)
1502 {
1503 if (!parent)
1504 sprintf (name, "op%u", pos);
1505 else
1506 sprintf (name, "o%u%u", level, pos);
1507 }
1508
1509 /* Generate matching code for the decision tree operand which is
1510 a predicate. */
1511
1512 unsigned
1513 dt_operand::gen_predicate (FILE *f, const char *opname, bool gimple)
1514 {
1515 predicate *p = as_a <predicate *> (op);
1516
1517 if (p->p->matchers.exists ())
1518 {
1519 /* If this is a predicate generated from a pattern mangle its
1520 name and pass on the valueize hook. */
1521 if (gimple)
1522 fprintf (f, "if (gimple_%s (%s, valueize))\n", p->p->id, opname);
1523 else
1524 fprintf (f, "if (tree_%s (%s))\n", p->p->id, opname);
1525 }
1526 else
1527 fprintf (f, "if (%s (%s))\n", p->p->id, opname);
1528 fprintf (f, "{\n");
1529 return 1;
1530 }
1531
1532 /* Generate matching code for the decision tree operand which is
1533 a capture-match. */
1534
1535 unsigned
1536 dt_operand::gen_match_op (FILE *f, const char *opname)
1537 {
1538 char match_opname[20];
1539 match_dop->get_name (match_opname);
1540 fprintf (f, "if (%s == %s || operand_equal_p (%s, %s, 0))\n",
1541 opname, match_opname, opname, match_opname);
1542 fprintf (f, "{\n");
1543 return 1;
1544 }
1545
1546 /* Generate GIMPLE matching code for the decision tree operand. */
1547
1548 unsigned
1549 dt_operand::gen_gimple_expr (FILE *f)
1550 {
1551 expr *e = static_cast<expr *> (op);
1552 id_base *id = e->operation;
1553 unsigned n_ops = e->ops.length ();
1554
1555 for (unsigned i = 0; i < n_ops; ++i)
1556 {
1557 char child_opname[20];
1558 gen_opname (child_opname, i);
1559
1560 if (id->kind == id_base::CODE)
1561 {
1562 if (*id == REALPART_EXPR || *id == IMAGPART_EXPR
1563 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
1564 {
1565 /* ??? If this is a memory operation we can't (and should not)
1566 match this. The only sensible operand types are
1567 SSA names and invariants. */
1568 fprintf (f, "tree %s = TREE_OPERAND (gimple_assign_rhs1 (def_stmt), %i);\n",
1569 child_opname, i);
1570 fprintf (f, "if ((TREE_CODE (%s) == SSA_NAME\n"
1571 "|| is_gimple_min_invariant (%s))\n"
1572 "&& (%s = do_valueize (valueize, %s)))\n"
1573 "{\n", child_opname, child_opname, child_opname,
1574 child_opname);
1575 continue;
1576 }
1577 else
1578 fprintf (f, "tree %s = gimple_assign_rhs%u (def_stmt);\n",
1579 child_opname, i + 1);
1580 }
1581 else
1582 fprintf (f, "tree %s = gimple_call_arg (def_stmt, %u);\n",
1583 child_opname, i);
1584 fprintf (f, "if ((%s = do_valueize (valueize, %s)) != 0)\n",
1585 child_opname, child_opname);
1586 fprintf (f, "{\n");
1587 }
1588
1589 return n_ops;
1590 }
1591
1592 /* Generate GENERIC matching code for the decision tree operand. */
1593
1594 unsigned
1595 dt_operand::gen_generic_expr (FILE *f, const char *opname)
1596 {
1597 expr *e = static_cast<expr *> (op);
1598 unsigned n_ops = e->ops.length ();
1599
1600 for (unsigned i = 0; i < n_ops; ++i)
1601 {
1602 char child_opname[20];
1603 gen_opname (child_opname, i);
1604
1605 if (e->operation->kind == id_base::CODE)
1606 fprintf (f, "tree %s = TREE_OPERAND (%s, %u);\n",
1607 child_opname, opname, i);
1608 else
1609 fprintf (f, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
1610 child_opname, opname, i);
1611 }
1612
1613 return 0;
1614 }
1615
1616 /* Generate matching code for the children of the decision tree node. */
1617
1618 void
1619 dt_node::gen_kids (FILE *f, bool gimple)
1620 {
1621 auto_vec<dt_operand *> gimple_exprs;
1622 auto_vec<dt_operand *> generic_exprs;
1623 auto_vec<dt_operand *> fns;
1624 auto_vec<dt_operand *> generic_fns;
1625 auto_vec<dt_operand *> preds;
1626 auto_vec<dt_node *> others;
1627 dt_node *true_operand = NULL;
1628
1629 for (unsigned i = 0; i < kids.length (); ++i)
1630 {
1631 if (kids[i]->type == dt_node::DT_OPERAND)
1632 {
1633 dt_operand *op = as_a<dt_operand *> (kids[i]);
1634 if (expr *e = dyn_cast <expr *> (op->op))
1635 {
1636 if (e->ops.length () == 0)
1637 generic_exprs.safe_push (op);
1638 else if (e->operation->kind == id_base::FN)
1639 {
1640 if (gimple)
1641 fns.safe_push (op);
1642 else
1643 generic_fns.safe_push (op);
1644 }
1645 else if (e->operation->kind == id_base::PREDICATE)
1646 preds.safe_push (op);
1647 else
1648 {
1649 if (gimple)
1650 gimple_exprs.safe_push (op);
1651 else
1652 generic_exprs.safe_push (op);
1653 }
1654 }
1655 else if (op->op->type == operand::OP_PREDICATE)
1656 others.safe_push (kids[i]);
1657 else
1658 gcc_unreachable ();
1659 }
1660 else if (kids[i]->type == dt_node::DT_MATCH
1661 || kids[i]->type == dt_node::DT_SIMPLIFY)
1662 others.safe_push (kids[i]);
1663 else if (kids[i]->type == dt_node::DT_TRUE)
1664 true_operand = kids[i];
1665 else
1666 gcc_unreachable ();
1667 }
1668
1669 char buf[128];
1670 char *kid_opname = buf;
1671
1672 unsigned exprs_len = gimple_exprs.length ();
1673 unsigned gexprs_len = generic_exprs.length ();
1674 unsigned fns_len = fns.length ();
1675 unsigned gfns_len = generic_fns.length ();
1676
1677 if (exprs_len || fns_len || gexprs_len || gfns_len)
1678 {
1679 if (exprs_len)
1680 gimple_exprs[0]->get_name (kid_opname);
1681 else if (fns_len)
1682 fns[0]->get_name (kid_opname);
1683 else if (gfns_len)
1684 generic_fns[0]->get_name (kid_opname);
1685 else
1686 generic_exprs[0]->get_name (kid_opname);
1687
1688 fprintf (f, "switch (TREE_CODE (%s))\n"
1689 "{\n", kid_opname);
1690 }
1691
1692 if (exprs_len || fns_len)
1693 {
1694 fprintf (f, "case SSA_NAME:\n");
1695 fprintf (f, "{\n");
1696 fprintf (f, "gimple def_stmt = SSA_NAME_DEF_STMT (%s);\n", kid_opname);
1697
1698 if (exprs_len)
1699 {
1700 fprintf (f, "if (is_gimple_assign (def_stmt))\n");
1701 fprintf (f, "switch (gimple_assign_rhs_code (def_stmt))\n"
1702 "{\n");
1703 for (unsigned i = 0; i < exprs_len; ++i)
1704 {
1705 expr *e = as_a <expr *> (gimple_exprs[i]->op);
1706 id_base *op = e->operation;
1707 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
1708 fprintf (f, "CASE_CONVERT:\n");
1709 else
1710 fprintf (f, "case %s:\n", op->id);
1711 fprintf (f, "{\n");
1712 gimple_exprs[i]->gen (f, true);
1713 fprintf (f, "break;\n"
1714 "}\n");
1715 }
1716 fprintf (f, "default:;\n"
1717 "}\n");
1718 }
1719
1720 if (fns_len)
1721 {
1722 if (exprs_len)
1723 fprintf (f, "else ");
1724
1725 fprintf (f, "if (gimple_call_builtin_p (def_stmt, BUILT_IN_NORMAL))\n"
1726 "{\n"
1727 "tree fndecl = gimple_call_fndecl (def_stmt);\n"
1728 "switch (DECL_FUNCTION_CODE (fndecl))\n"
1729 "{\n");
1730
1731 for (unsigned i = 0; i < fns_len; ++i)
1732 {
1733 expr *e = as_a <expr *>(fns[i]->op);
1734 fprintf (f, "case %s:\n"
1735 "{\n", e->operation->id);
1736 fns[i]->gen (f, true);
1737 fprintf (f, "break;\n"
1738 "}\n");
1739 }
1740
1741 fprintf (f, "default:;\n"
1742 "}\n"
1743 "}\n");
1744 }
1745
1746 fprintf (f, "break;\n"
1747 "}\n");
1748 }
1749
1750 for (unsigned i = 0; i < generic_exprs.length (); ++i)
1751 {
1752 expr *e = as_a <expr *>(generic_exprs[i]->op);
1753 id_base *op = e->operation;
1754 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
1755 fprintf (f, "CASE_CONVERT:\n");
1756 else
1757 fprintf (f, "case %s:\n", op->id);
1758 fprintf (f, "{\n");
1759 generic_exprs[i]->gen (f, gimple);
1760 fprintf (f, "break;\n"
1761 "}\n");
1762 }
1763
1764 if (gfns_len)
1765 {
1766 fprintf (f, "case CALL_EXPR:\n"
1767 "{\n"
1768 "tree fndecl = get_callee_fndecl (%s);\n"
1769 "if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)\n"
1770 "switch (DECL_FUNCTION_CODE (fndecl))\n"
1771 "{\n", kid_opname);
1772
1773 for (unsigned j = 0; j < generic_fns.length (); ++j)
1774 {
1775 expr *e = as_a <expr *>(generic_fns[j]->op);
1776 gcc_assert (e->operation->kind == id_base::FN);
1777
1778 fprintf (f, "case %s:\n"
1779 "{\n", e->operation->id);
1780 generic_fns[j]->gen (f, false);
1781 fprintf (f, "break;\n"
1782 "}\n");
1783 }
1784
1785 fprintf (f, "default:;\n"
1786 "}\n"
1787 "break;\n"
1788 "}\n");
1789 }
1790
1791 /* Close switch (TREE_CODE ()). */
1792 if (exprs_len || fns_len || gexprs_len || gfns_len)
1793 fprintf (f, "default:;\n"
1794 "}\n");
1795
1796 for (unsigned i = 0; i < preds.length (); ++i)
1797 {
1798 expr *e = as_a <expr *> (preds[i]->op);
1799 predicate_id *p = as_a <predicate_id *> (e->operation);
1800 preds[i]->get_name (kid_opname);
1801 fprintf (f, "tree %s_pops[%d];\n", kid_opname, p->nargs);
1802 fprintf (f, "if (%s_%s (%s, %s_pops%s))\n",
1803 gimple ? "gimple" : "tree",
1804 p->id, kid_opname, kid_opname,
1805 gimple ? ", valueize" : "");
1806 fprintf (f, "{\n");
1807 for (int j = 0; j < p->nargs; ++j)
1808 {
1809 char child_opname[20];
1810 preds[i]->gen_opname (child_opname, j);
1811 fprintf (f, "tree %s = %s_pops[%d];\n", child_opname, kid_opname, j);
1812 }
1813 preds[i]->gen_kids (f, gimple);
1814 fprintf (f, "}\n");
1815 }
1816
1817 for (unsigned i = 0; i < others.length (); ++i)
1818 others[i]->gen (f, gimple);
1819
1820 if (true_operand)
1821 true_operand->gen (f, gimple);
1822 }
1823
1824 /* Generate matching code for the decision tree operand. */
1825
1826 void
1827 dt_operand::gen (FILE *f, bool gimple)
1828 {
1829 char opname[20];
1830 get_name (opname);
1831
1832 unsigned n_braces = 0;
1833
1834 if (type == DT_OPERAND)
1835 switch (op->type)
1836 {
1837 case operand::OP_PREDICATE:
1838 n_braces = gen_predicate (f, opname, gimple);
1839 break;
1840
1841 case operand::OP_EXPR:
1842 if (gimple)
1843 n_braces = gen_gimple_expr (f);
1844 else
1845 n_braces = gen_generic_expr (f, opname);
1846 break;
1847
1848 default:
1849 gcc_unreachable ();
1850 }
1851 else if (type == DT_TRUE)
1852 ;
1853 else if (type == DT_MATCH)
1854 n_braces = gen_match_op (f, opname);
1855 else
1856 gcc_unreachable ();
1857
1858 gen_kids (f, gimple);
1859
1860 for (unsigned i = 0; i < n_braces; ++i)
1861 fprintf (f, "}\n");
1862 }
1863
1864
1865 /* For GENERIC we have to take care of wrapping multiple-used
1866 expressions with side-effects in save_expr and preserve side-effects
1867 of expressions with omit_one_operand. Analyze captures in
1868 match, result and with expressions and perform early-outs
1869 on the outermost match expression operands for cases we cannot
1870 handle. */
1871
1872 struct capture_info
1873 {
1874 capture_info (simplify *s);
1875 void walk_match (operand *o, unsigned toplevel_arg, bool);
1876 void walk_result (operand *o, bool);
1877 void walk_c_expr (c_expr *);
1878
1879 struct cinfo
1880 {
1881 bool expr_p;
1882 bool cse_p;
1883 bool force_no_side_effects_p;
1884 unsigned long toplevel_msk;
1885 int result_use_count;
1886 };
1887
1888 auto_vec<cinfo> info;
1889 unsigned long force_no_side_effects;
1890 };
1891
1892 /* Analyze captures in S. */
1893
1894 capture_info::capture_info (simplify *s)
1895 {
1896 expr *e;
1897 if (!s->result
1898 || ((e = dyn_cast <expr *> (s->result))
1899 && is_a <predicate_id *> (e->operation)))
1900 {
1901 force_no_side_effects = -1;
1902 return;
1903 }
1904
1905 force_no_side_effects = 0;
1906 info.safe_grow_cleared (s->capture_max + 1);
1907 e = as_a <expr *> (s->match);
1908 for (unsigned i = 0; i < e->ops.length (); ++i)
1909 walk_match (e->ops[i], i, false);
1910
1911 walk_result (s->result, false);
1912
1913 for (unsigned i = 0; i < s->ifexpr_vec.length (); ++i)
1914 if (s->ifexpr_vec[i].is_with)
1915 walk_c_expr (as_a <c_expr *>(s->ifexpr_vec[i].cexpr));
1916 }
1917
1918 /* Analyze captures in the match expression piece O. */
1919
1920 void
1921 capture_info::walk_match (operand *o, unsigned toplevel_arg, bool conditional_p)
1922 {
1923 if (capture *c = dyn_cast <capture *> (o))
1924 {
1925 info[c->where].toplevel_msk |= 1 << toplevel_arg;
1926 info[c->where].force_no_side_effects_p |= conditional_p;
1927 /* Mark expr (non-leaf) captures and recurse. */
1928 if (c->what
1929 && is_a <expr *> (c->what))
1930 {
1931 info[c->where].expr_p = true;
1932 walk_match (c->what, toplevel_arg, conditional_p);
1933 }
1934 }
1935 else if (expr *e = dyn_cast <expr *> (o))
1936 {
1937 for (unsigned i = 0; i < e->ops.length (); ++i)
1938 {
1939 bool cond_p = conditional_p;
1940 if (i == 0
1941 && *e->operation == COND_EXPR)
1942 cond_p = true;
1943 else if (*e->operation == TRUTH_ANDIF_EXPR
1944 || *e->operation == TRUTH_ORIF_EXPR)
1945 cond_p = true;
1946 walk_match (e->ops[i], toplevel_arg, cond_p);
1947 }
1948 }
1949 else if (is_a <predicate *> (o))
1950 {
1951 /* Mark non-captured leafs toplevel arg for checking. */
1952 force_no_side_effects |= 1 << toplevel_arg;
1953 }
1954 else
1955 gcc_unreachable ();
1956 }
1957
1958 /* Analyze captures in the result expression piece O. */
1959
1960 void
1961 capture_info::walk_result (operand *o, bool conditional_p)
1962 {
1963 if (capture *c = dyn_cast <capture *> (o))
1964 {
1965 info[c->where].result_use_count++;
1966 /* If we substitute an expression capture we don't know
1967 which captures this will end up using (well, we don't
1968 compute that). Force the uses to be side-effect free
1969 which means forcing the toplevels that reach the
1970 expression side-effect free. */
1971 if (info[c->where].expr_p)
1972 force_no_side_effects |= info[c->where].toplevel_msk;
1973 /* Mark CSE capture capture uses as forced to have
1974 no side-effects. */
1975 if (c->what
1976 && is_a <expr *> (c->what))
1977 {
1978 info[c->where].cse_p = true;
1979 walk_result (c->what, true);
1980 }
1981 }
1982 else if (expr *e = dyn_cast <expr *> (o))
1983 {
1984 for (unsigned i = 0; i < e->ops.length (); ++i)
1985 {
1986 bool cond_p = conditional_p;
1987 if (i == 0
1988 && *e->operation == COND_EXPR)
1989 cond_p = true;
1990 else if (*e->operation == TRUTH_ANDIF_EXPR
1991 || *e->operation == TRUTH_ORIF_EXPR)
1992 cond_p = true;
1993 walk_result (e->ops[i], cond_p);
1994 }
1995 }
1996 else if (c_expr *e = dyn_cast <c_expr *> (o))
1997 walk_c_expr (e);
1998 else
1999 gcc_unreachable ();
2000 }
2001
2002 /* Look for captures in the C expr E. */
2003
2004 void
2005 capture_info::walk_c_expr (c_expr *e)
2006 {
2007 /* Give up for C exprs mentioning captures not inside TREE_TYPE (). */
2008 unsigned p_depth = 0;
2009 for (unsigned i = 0; i < e->code.length (); ++i)
2010 {
2011 const cpp_token *t = &e->code[i];
2012 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
2013 if (t->type == CPP_NAME
2014 && strcmp ((const char *)CPP_HASHNODE
2015 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
2016 && n->type == CPP_OPEN_PAREN)
2017 p_depth++;
2018 else if (t->type == CPP_CLOSE_PAREN
2019 && p_depth > 0)
2020 p_depth--;
2021 else if (p_depth == 0
2022 && t->type == CPP_ATSIGN
2023 && (n->type == CPP_NUMBER
2024 || n->type == CPP_NAME)
2025 && !(n->flags & PREV_WHITE))
2026 {
2027 const char *id;
2028 if (n->type == CPP_NUMBER)
2029 id = (const char *)n->val.str.text;
2030 else
2031 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2032 info[(*e->capture_ids)[id]].force_no_side_effects_p = true;
2033 }
2034 }
2035 }
2036
2037
2038 /* Generate code for the '(if ...)', '(with ..)' and actual transform
2039 step of a '(simplify ...)' or '(match ...)'. This handles everything
2040 that is not part of the decision tree (simplify->match). */
2041
2042 void
2043 dt_simplify::gen (FILE *f, bool gimple)
2044 {
2045 fprintf (f, "{\n");
2046 output_line_directive (f, s->result_location);
2047 if (s->capture_max >= 0)
2048 fprintf (f, "tree captures[%u] ATTRIBUTE_UNUSED = {};\n",
2049 s->capture_max + 1);
2050
2051 for (int i = 0; i <= s->capture_max; ++i)
2052 if (indexes[i])
2053 {
2054 char opname[20];
2055 fprintf (f, "captures[%u] = %s;\n", i, indexes[i]->get_name (opname));
2056 }
2057
2058 unsigned n_braces = 0;
2059 if (s->ifexpr_vec != vNULL)
2060 {
2061 for (unsigned i = 0; i < s->ifexpr_vec.length (); ++i)
2062 {
2063 if_or_with &w = s->ifexpr_vec[i];
2064 if (w.is_with)
2065 {
2066 fprintf (f, "{\n");
2067 output_line_directive (f, w.location);
2068 w.cexpr->gen_transform (f, NULL, true, 1, "type");
2069 n_braces++;
2070 }
2071 else
2072 {
2073 output_line_directive (f, w.location);
2074 fprintf (f, "if (");
2075 if (i == s->ifexpr_vec.length () - 1
2076 || s->ifexpr_vec[i+1].is_with)
2077 w.cexpr->gen_transform (f, NULL, true, 1, "type");
2078 else
2079 {
2080 unsigned j = i;
2081 do
2082 {
2083 if (j != i)
2084 {
2085 fprintf (f, "\n");
2086 output_line_directive (f, s->ifexpr_vec[j].location);
2087 fprintf (f, "&& ");
2088 }
2089 fprintf (f, "(");
2090 s->ifexpr_vec[j].cexpr->gen_transform (f, NULL,
2091 true, 1, "type");
2092 fprintf (f, ")");
2093 ++j;
2094 }
2095 while (j < s->ifexpr_vec.length ()
2096 && !s->ifexpr_vec[j].is_with);
2097 i = j - 1;
2098 }
2099 fprintf (f, ")\n");
2100 }
2101 }
2102 fprintf (f, "{\n");
2103 n_braces++;
2104 }
2105
2106 /* Analyze captures and perform early-outs on the incoming arguments
2107 that cover cases we cannot handle. */
2108 capture_info cinfo (s);
2109 expr *e;
2110 if (!gimple
2111 && s->result
2112 && !((e = dyn_cast <expr *> (s->result))
2113 && is_a <predicate_id *> (e->operation)))
2114 {
2115 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
2116 if (cinfo.force_no_side_effects & (1 << i))
2117 fprintf (f, "if (TREE_SIDE_EFFECTS (op%d)) return NULL_TREE;\n", i);
2118 for (int i = 0; i <= s->capture_max; ++i)
2119 if (cinfo.info[i].cse_p)
2120 ;
2121 else if (cinfo.info[i].force_no_side_effects_p
2122 && (cinfo.info[i].toplevel_msk
2123 & cinfo.force_no_side_effects) == 0)
2124 fprintf (f, "if (TREE_SIDE_EFFECTS (captures[%d])) "
2125 "return NULL_TREE;\n", i);
2126 else if ((cinfo.info[i].toplevel_msk
2127 & cinfo.force_no_side_effects) != 0)
2128 /* Mark capture as having no side-effects if we had to verify
2129 that via forced toplevel operand checks. */
2130 cinfo.info[i].force_no_side_effects_p = true;
2131 }
2132
2133 fprintf (f, "if (dump_file && (dump_flags & TDF_DETAILS)) "
2134 "fprintf (dump_file, \"Applying pattern ");
2135 output_line_directive (f, s->result_location, true);
2136 fprintf (f, ", %%s:%%d\\n\", __FILE__, __LINE__);\n");
2137
2138 operand *result = s->result;
2139 if (!result)
2140 {
2141 /* If there is no result then this is a predicate implementation. */
2142 fprintf (f, "return true;\n");
2143 }
2144 else if (gimple)
2145 {
2146 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
2147 in outermost position). */
2148 if (result->type == operand::OP_EXPR
2149 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
2150 result = as_a <expr *> (result)->ops[0];
2151 if (result->type == operand::OP_EXPR)
2152 {
2153 expr *e = as_a <expr *> (result);
2154 bool is_predicate = is_a <predicate_id *> (e->operation);
2155 if (!is_predicate)
2156 fprintf (f, "*res_code = %s;\n", e->operation->id);
2157 for (unsigned j = 0; j < e->ops.length (); ++j)
2158 {
2159 char dest[32];
2160 snprintf (dest, 32, " res_ops[%d]", j);
2161 const char *optype
2162 = get_operand_type (e->operation,
2163 "type", e->expr_type,
2164 j == 0
2165 ? NULL : "TREE_TYPE (res_ops[0])");
2166 e->ops[j]->gen_transform (f, dest, true, 1, optype, indexes);
2167 }
2168
2169 /* Re-fold the toplevel result. It's basically an embedded
2170 gimple_build w/o actually building the stmt. */
2171 if (!is_predicate)
2172 fprintf (f, "gimple_resimplify%d (seq, res_code, type, "
2173 "res_ops, valueize);\n", e->ops.length ());
2174 }
2175 else if (result->type == operand::OP_CAPTURE
2176 || result->type == operand::OP_C_EXPR)
2177 {
2178 result->gen_transform (f, "res_ops[0]", true, 1, "type", indexes);
2179 fprintf (f, "*res_code = TREE_CODE (res_ops[0]);\n");
2180 }
2181 else
2182 gcc_unreachable ();
2183 fprintf (f, "return true;\n");
2184 }
2185 else /* GENERIC */
2186 {
2187 bool is_predicate = false;
2188 if (result->type == operand::OP_EXPR)
2189 {
2190 expr *e = as_a <expr *> (result);
2191 is_predicate = is_a <predicate_id *> (e->operation);
2192 /* Search for captures used multiple times in the result expression
2193 and dependent on TREE_SIDE_EFFECTS emit a SAVE_EXPR. */
2194 if (!is_predicate)
2195 for (int i = 0; i < s->capture_max + 1; ++i)
2196 {
2197 if (!cinfo.info[i].force_no_side_effects_p
2198 && cinfo.info[i].result_use_count > 1)
2199 fprintf (f, " if (TREE_SIDE_EFFECTS (captures[%d]))\n"
2200 " captures[%d] = save_expr (captures[%d]);\n",
2201 i, i, i);
2202 }
2203 for (unsigned j = 0; j < e->ops.length (); ++j)
2204 {
2205 char dest[32];
2206 if (is_predicate)
2207 snprintf (dest, 32, "res_ops[%d]", j);
2208 else
2209 {
2210 fprintf (f, " tree res_op%d;\n", j);
2211 snprintf (dest, 32, " res_op%d", j);
2212 }
2213 const char *optype
2214 = get_operand_type (e->operation,
2215 "type", e->expr_type,
2216 j == 0
2217 ? NULL : "TREE_TYPE (res_op0)");
2218 e->ops[j]->gen_transform (f, dest, false, 1, optype, indexes);
2219 }
2220 if (is_predicate)
2221 fprintf (f, "return true;\n");
2222 else
2223 {
2224 fprintf (f, " tree res;\n");
2225 /* Re-fold the toplevel result. Use non_lvalue to
2226 build NON_LVALUE_EXPRs so they get properly
2227 ignored when in GIMPLE form. */
2228 if (*e->operation == NON_LVALUE_EXPR)
2229 fprintf (f, " res = non_lvalue_loc (loc, res_op0);\n");
2230 else
2231 {
2232 if (e->operation->kind == id_base::CODE)
2233 fprintf (f, " res = fold_build%d_loc (loc, %s, type",
2234 e->ops.length (), e->operation->id);
2235 else
2236 fprintf (f, " res = build_call_expr_loc "
2237 "(loc, builtin_decl_implicit (%s), %d",
2238 e->operation->id, e->ops.length());
2239 for (unsigned j = 0; j < e->ops.length (); ++j)
2240 fprintf (f, ", res_op%d", j);
2241 fprintf (f, ");\n");
2242 }
2243 }
2244 }
2245 else if (result->type == operand::OP_CAPTURE
2246 || result->type == operand::OP_C_EXPR)
2247
2248 {
2249 fprintf (f, " tree res;\n");
2250 s->result->gen_transform (f, " res", false, 1, "type", indexes);
2251 }
2252 else
2253 gcc_unreachable ();
2254 if (!is_predicate)
2255 {
2256 /* Search for captures not used in the result expression and dependent
2257 on TREE_SIDE_EFFECTS emit omit_one_operand. */
2258 for (int i = 0; i < s->capture_max + 1; ++i)
2259 {
2260 if (!cinfo.info[i].force_no_side_effects_p
2261 && !cinfo.info[i].expr_p
2262 && cinfo.info[i].result_use_count == 0)
2263 fprintf (f, " if (TREE_SIDE_EFFECTS (captures[%d]))\n"
2264 " res = build2_loc (loc, COMPOUND_EXPR, type,"
2265 " fold_ignored_result (captures[%d]), res);\n",
2266 i, i);
2267 }
2268 fprintf (f, " return res;\n");
2269 }
2270 }
2271
2272 for (unsigned i = 0; i < n_braces; ++i)
2273 fprintf (f, "}\n");
2274
2275 fprintf (f, "}\n");
2276 }
2277
2278 /* Main entry to generate code for matching GIMPLE IL off the decision
2279 tree. */
2280
2281 void
2282 decision_tree::gen_gimple (FILE *f)
2283 {
2284 for (unsigned n = 1; n <= 3; ++n)
2285 {
2286 fprintf (f, "\nstatic bool\n"
2287 "gimple_simplify (code_helper *res_code, tree *res_ops,\n"
2288 " gimple_seq *seq, tree (*valueize)(tree),\n"
2289 " code_helper code, tree type");
2290 for (unsigned i = 0; i < n; ++i)
2291 fprintf (f, ", tree op%d", i);
2292 fprintf (f, ")\n");
2293 fprintf (f, "{\n");
2294
2295 fprintf (f, "switch (code.get_rep())\n"
2296 "{\n");
2297 for (unsigned i = 0; i < root->kids.length (); i++)
2298 {
2299 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
2300 expr *e = static_cast<expr *>(dop->op);
2301 if (e->ops.length () != n)
2302 continue;
2303
2304 if (*e->operation == CONVERT_EXPR
2305 || *e->operation == NOP_EXPR)
2306 fprintf (f, "CASE_CONVERT:\n");
2307 else
2308 fprintf (f, "case %s%s:\n",
2309 is_a <fn_id *> (e->operation) ? "-" : "",
2310 e->operation->id);
2311 fprintf (f, "{\n");
2312 dop->gen_kids (f, true);
2313 fprintf (f, "break;\n");
2314 fprintf (f, "}\n");
2315 }
2316 fprintf (f, "default:;\n"
2317 "}\n");
2318
2319 fprintf (f, "return false;\n");
2320 fprintf (f, "}\n");
2321 }
2322 }
2323
2324 /* Main entry to generate code for matching GENERIC IL off the decision
2325 tree. */
2326
2327 void
2328 decision_tree::gen_generic (FILE *f)
2329 {
2330 for (unsigned n = 1; n <= 3; ++n)
2331 {
2332 fprintf (f, "\ntree\n"
2333 "generic_simplify (location_t loc, enum tree_code code, "
2334 "tree type ATTRIBUTE_UNUSED");
2335 for (unsigned i = 0; i < n; ++i)
2336 fprintf (f, ", tree op%d", i);
2337 fprintf (f, ")\n");
2338 fprintf (f, "{\n");
2339
2340 fprintf (f, "switch (code)\n"
2341 "{\n");
2342 for (unsigned i = 0; i < root->kids.length (); i++)
2343 {
2344 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
2345 expr *e = static_cast<expr *>(dop->op);
2346 if (e->ops.length () != n
2347 /* Builtin simplifications are somewhat premature on
2348 GENERIC. The following drops patterns with outermost
2349 calls. It's easy to emit overloads for function code
2350 though if necessary. */
2351 || e->operation->kind != id_base::CODE)
2352 continue;
2353
2354 operator_id *op_id = static_cast <operator_id *> (e->operation);
2355 if (op_id->code == NOP_EXPR || op_id->code == CONVERT_EXPR)
2356 fprintf (f, "CASE_CONVERT:\n");
2357 else
2358 fprintf (f, "case %s:\n", e->operation->id);
2359 fprintf (f, "{\n");
2360 dop->gen_kids (f, false);
2361 fprintf (f, "break;\n"
2362 "}\n");
2363 }
2364 fprintf (f, "default:;\n"
2365 "}\n");
2366
2367 fprintf (f, "return NULL_TREE;\n");
2368 fprintf (f, "}\n");
2369 }
2370 }
2371
2372 /* Output code to implement the predicate P from the decision tree DT. */
2373
2374 void
2375 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
2376 {
2377 fprintf (f, "\nbool\n"
2378 "%s%s (tree t%s%s)\n"
2379 "{\n", gimple ? "gimple_" : "tree_", p->id,
2380 p->nargs > 0 ? ", tree *res_ops" : "",
2381 gimple ? ", tree (*valueize)(tree)" : "");
2382 /* Conveniently make 'type' available. */
2383 fprintf (f, "tree type = TREE_TYPE (t);\n");
2384
2385 if (!gimple)
2386 fprintf (f, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
2387 dt.root->gen_kids (f, gimple);
2388
2389 fprintf (f, "return false;\n"
2390 "}\n");
2391 }
2392
2393 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
2394
2395 static void
2396 write_header (FILE *f, const char *head)
2397 {
2398 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
2399 fprintf (f, " a IL pattern matching and simplification description. */\n");
2400
2401 /* Include the header instead of writing it awkwardly quoted here. */
2402 fprintf (f, "\n#include \"%s\"\n", head);
2403 }
2404
2405
2406
2407 /* AST parsing. */
2408
2409 class parser
2410 {
2411 public:
2412 parser (cpp_reader *);
2413
2414 private:
2415 const cpp_token *next ();
2416 const cpp_token *peek ();
2417 const cpp_token *peek_ident (const char * = NULL);
2418 const cpp_token *expect (enum cpp_ttype);
2419 void eat_token (enum cpp_ttype);
2420 const char *get_string ();
2421 const char *get_ident ();
2422 void eat_ident (const char *);
2423 const char *get_number ();
2424
2425 id_base *parse_operation ();
2426 operand *parse_capture (operand *);
2427 operand *parse_expr ();
2428 c_expr *parse_c_expr (cpp_ttype);
2429 operand *parse_op ();
2430
2431 void parse_pattern ();
2432 void parse_simplify (source_location, vec<simplify *>&, predicate_id *,
2433 expr *);
2434 void parse_for (source_location);
2435 void parse_if (source_location);
2436 void parse_predicates (source_location);
2437
2438 cpp_reader *r;
2439 vec<if_or_with> active_ifs;
2440 vec<vec<user_id *> > active_fors;
2441
2442 std::map<std::string, unsigned> *capture_ids;
2443
2444 public:
2445 vec<simplify *> simplifiers;
2446 vec<predicate_id *> user_predicates;
2447 };
2448
2449 /* Lexing helpers. */
2450
2451 /* Read the next non-whitespace token from R. */
2452
2453 const cpp_token *
2454 parser::next ()
2455 {
2456 const cpp_token *token;
2457 do
2458 {
2459 token = cpp_get_token (r);
2460 }
2461 while (token->type == CPP_PADDING
2462 && token->type != CPP_EOF);
2463 return token;
2464 }
2465
2466 /* Peek at the next non-whitespace token from R. */
2467
2468 const cpp_token *
2469 parser::peek ()
2470 {
2471 const cpp_token *token;
2472 unsigned i = 0;
2473 do
2474 {
2475 token = cpp_peek_token (r, i++);
2476 }
2477 while (token->type == CPP_PADDING
2478 && token->type != CPP_EOF);
2479 /* If we peek at EOF this is a fatal error as it leaves the
2480 cpp_reader in unusable state. Assume we really wanted a
2481 token and thus this EOF is unexpected. */
2482 if (token->type == CPP_EOF)
2483 fatal_at (token, "unexpected end of file");
2484 return token;
2485 }
2486
2487 /* Peek at the next identifier token (or return NULL if the next
2488 token is not an identifier or equal to ID if supplied). */
2489
2490 const cpp_token *
2491 parser::peek_ident (const char *id)
2492 {
2493 const cpp_token *token = peek ();
2494 if (token->type != CPP_NAME)
2495 return 0;
2496
2497 if (id == 0)
2498 return token;
2499
2500 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
2501 if (strcmp (id, t) == 0)
2502 return token;
2503
2504 return 0;
2505 }
2506
2507 /* Read the next token from R and assert it is of type TK. */
2508
2509 const cpp_token *
2510 parser::expect (enum cpp_ttype tk)
2511 {
2512 const cpp_token *token = next ();
2513 if (token->type != tk)
2514 fatal_at (token, "expected %s, got %s",
2515 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
2516
2517 return token;
2518 }
2519
2520 /* Consume the next token from R and assert it is of type TK. */
2521
2522 void
2523 parser::eat_token (enum cpp_ttype tk)
2524 {
2525 expect (tk);
2526 }
2527
2528 /* Read the next token from R and assert it is of type CPP_STRING and
2529 return its value. */
2530
2531 const char *
2532 parser::get_string ()
2533 {
2534 const cpp_token *token = expect (CPP_STRING);
2535 return (const char *)token->val.str.text;
2536 }
2537
2538 /* Read the next token from R and assert it is of type CPP_NAME and
2539 return its value. */
2540
2541 const char *
2542 parser::get_ident ()
2543 {
2544 const cpp_token *token = expect (CPP_NAME);
2545 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
2546 }
2547
2548 /* Eat an identifier token with value S from R. */
2549
2550 void
2551 parser::eat_ident (const char *s)
2552 {
2553 const cpp_token *token = peek ();
2554 const char *t = get_ident ();
2555 if (strcmp (s, t) != 0)
2556 fatal_at (token, "expected '%s' got '%s'\n", s, t);
2557 }
2558
2559 /* Read the next token from R and assert it is of type CPP_NUMBER and
2560 return its value. */
2561
2562 const char *
2563 parser::get_number ()
2564 {
2565 const cpp_token *token = expect (CPP_NUMBER);
2566 return (const char *)token->val.str.text;
2567 }
2568
2569
2570 /* Parse the operator ID, special-casing convert?, convert1? and
2571 convert2? */
2572
2573 id_base *
2574 parser::parse_operation ()
2575 {
2576 const cpp_token *id_tok = peek ();
2577 const char *id = get_ident ();
2578 const cpp_token *token = peek ();
2579 if (strcmp (id, "convert0") == 0)
2580 fatal_at (id_tok, "use 'convert?' here");
2581 if (token->type == CPP_QUERY
2582 && !(token->flags & PREV_WHITE))
2583 {
2584 if (strcmp (id, "convert") == 0)
2585 id = "convert0";
2586 else if (strcmp (id, "convert1") == 0)
2587 ;
2588 else if (strcmp (id, "convert2") == 0)
2589 ;
2590 else
2591 fatal_at (id_tok, "non-convert operator conditionalized");
2592 eat_token (CPP_QUERY);
2593 }
2594 else if (strcmp (id, "convert1") == 0
2595 || strcmp (id, "convert2") == 0)
2596 fatal_at (id_tok, "expected '?' after conditional operator");
2597 id_base *op = get_operator (id);
2598 if (!op)
2599 fatal_at (id_tok, "unknown operator %s", id);
2600 return op;
2601 }
2602
2603 /* Parse a capture.
2604 capture = '@'<number> */
2605
2606 struct operand *
2607 parser::parse_capture (operand *op)
2608 {
2609 eat_token (CPP_ATSIGN);
2610 const cpp_token *token = peek ();
2611 const char *id;
2612 if (token->type == CPP_NUMBER)
2613 id = get_number ();
2614 else if (token->type == CPP_NAME)
2615 id = get_ident ();
2616 else
2617 fatal_at (token, "expected number or identifier");
2618 unsigned next_id = capture_ids->size ();
2619 std::pair<std::map<std::string, unsigned>::iterator, bool> res
2620 = capture_ids->insert (std::pair<std::string, unsigned>(id, next_id));
2621 return new capture ((*res.first).second, op);
2622 }
2623
2624 /* Parse an expression
2625 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
2626
2627 struct operand *
2628 parser::parse_expr ()
2629 {
2630 expr *e = new expr (parse_operation ());
2631 const cpp_token *token = peek ();
2632 operand *op;
2633 bool is_commutative = false;
2634 const char *expr_type = NULL;
2635
2636 if (token->type == CPP_COLON
2637 && !(token->flags & PREV_WHITE))
2638 {
2639 eat_token (CPP_COLON);
2640 token = peek ();
2641 if (token->type == CPP_NAME
2642 && !(token->flags & PREV_WHITE))
2643 {
2644 const char *s = get_ident ();
2645 if (s[0] == 'c' && !s[1])
2646 is_commutative = true;
2647 else if (s[1] != '\0')
2648 expr_type = s;
2649 else
2650 fatal_at (token, "flag %s not recognized", s);
2651 token = peek ();
2652 }
2653 else
2654 fatal_at (token, "expected flag or type specifying identifier");
2655 }
2656
2657 if (token->type == CPP_ATSIGN
2658 && !(token->flags & PREV_WHITE))
2659 op = parse_capture (e);
2660 else
2661 op = e;
2662 do
2663 {
2664 const cpp_token *token = peek ();
2665 if (token->type == CPP_CLOSE_PAREN)
2666 {
2667 if (e->operation->nargs != -1
2668 && e->operation->nargs != (int) e->ops.length ())
2669 fatal_at (token, "'%s' expects %u operands, not %u",
2670 e->operation->id, e->operation->nargs, e->ops.length ());
2671 if (is_commutative)
2672 {
2673 if (e->ops.length () == 2)
2674 e->is_commutative = true;
2675 else
2676 fatal_at (token, "only binary operators or function with "
2677 "two arguments can be marked commutative");
2678 }
2679 e->expr_type = expr_type;
2680 return op;
2681 }
2682 e->append_op (parse_op ());
2683 }
2684 while (1);
2685 }
2686
2687 /* Lex native C code delimited by START recording the preprocessing tokens
2688 for later processing.
2689 c_expr = ('{'|'(') <pp token>... ('}'|')') */
2690
2691 c_expr *
2692 parser::parse_c_expr (cpp_ttype start)
2693 {
2694 const cpp_token *token;
2695 cpp_ttype end;
2696 unsigned opencnt;
2697 vec<cpp_token> code = vNULL;
2698 unsigned nr_stmts = 0;
2699 eat_token (start);
2700 if (start == CPP_OPEN_PAREN)
2701 end = CPP_CLOSE_PAREN;
2702 else if (start == CPP_OPEN_BRACE)
2703 end = CPP_CLOSE_BRACE;
2704 else
2705 gcc_unreachable ();
2706 opencnt = 1;
2707 do
2708 {
2709 token = next ();
2710
2711 /* Count brace pairs to find the end of the expr to match. */
2712 if (token->type == start)
2713 opencnt++;
2714 else if (token->type == end
2715 && --opencnt == 0)
2716 break;
2717
2718 /* This is a lame way of counting the number of statements. */
2719 if (token->type == CPP_SEMICOLON)
2720 nr_stmts++;
2721
2722 /* Record the token. */
2723 code.safe_push (*token);
2724 }
2725 while (1);
2726 return new c_expr (r, code, nr_stmts, vNULL, capture_ids);
2727 }
2728
2729 /* Parse an operand which is either an expression, a predicate or
2730 a standalone capture.
2731 op = predicate | expr | c_expr | capture */
2732
2733 struct operand *
2734 parser::parse_op ()
2735 {
2736 const cpp_token *token = peek ();
2737 struct operand *op = NULL;
2738 if (token->type == CPP_OPEN_PAREN)
2739 {
2740 eat_token (CPP_OPEN_PAREN);
2741 op = parse_expr ();
2742 eat_token (CPP_CLOSE_PAREN);
2743 }
2744 else if (token->type == CPP_OPEN_BRACE)
2745 {
2746 op = parse_c_expr (CPP_OPEN_BRACE);
2747 }
2748 else
2749 {
2750 /* Remaining ops are either empty or predicates */
2751 if (token->type == CPP_NAME)
2752 {
2753 const char *id = get_ident ();
2754 id_base *opr = get_operator (id);
2755 if (!opr)
2756 fatal_at (token, "expected predicate name");
2757 if (operator_id *code = dyn_cast <operator_id *> (opr))
2758 {
2759 if (code->nargs != 0)
2760 fatal_at (token, "using an operator with operands as predicate");
2761 /* Parse the zero-operand operator "predicates" as
2762 expression. */
2763 op = new expr (opr);
2764 }
2765 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
2766 op = new predicate (p);
2767 else
2768 fatal_at (token, "using an unsupported operator as predicate");
2769 token = peek ();
2770 if (token->flags & PREV_WHITE)
2771 return op;
2772 }
2773 else if (token->type != CPP_COLON
2774 && token->type != CPP_ATSIGN)
2775 fatal_at (token, "expected expression or predicate");
2776 /* optionally followed by a capture and a predicate. */
2777 if (token->type == CPP_COLON)
2778 fatal_at (token, "not implemented: predicate on leaf operand");
2779 if (token->type == CPP_ATSIGN)
2780 op = parse_capture (op);
2781 }
2782
2783 return op;
2784 }
2785
2786 /* Parse
2787 simplify = 'simplify' <expr> <result-op>
2788 or
2789 match = 'match' <ident> <expr> [<result-op>]
2790 with
2791 <result-op> = <op> | <if> | <with>
2792 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
2793 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
2794 and fill SIMPLIFIERS with the results. */
2795
2796 void
2797 parser::parse_simplify (source_location match_location,
2798 vec<simplify *>& simplifiers, predicate_id *matcher,
2799 expr *result)
2800 {
2801 /* Reset the capture map. */
2802 capture_ids = new std::map<std::string, unsigned>;
2803
2804 const cpp_token *loc = peek ();
2805 struct operand *match = parse_op ();
2806 if (match->type == operand::OP_CAPTURE && !matcher)
2807 fatal_at (loc, "outermost expression cannot be captured");
2808 if (match->type == operand::OP_EXPR
2809 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
2810 fatal_at (loc, "outermost expression cannot be a predicate");
2811
2812 const cpp_token *token = peek ();
2813
2814 /* If this if is immediately closed then it is part of a predicate
2815 definition. Push it. */
2816 if (token->type == CPP_CLOSE_PAREN)
2817 {
2818 if (!matcher)
2819 fatal_at (token, "expected transform expression");
2820 simplifiers.safe_push
2821 (new simplify (match, match_location, result, token->src_loc,
2822 active_ifs.copy (), active_fors.copy (),
2823 capture_ids));
2824 return;
2825 }
2826
2827 unsigned active_ifs_len = active_ifs.length ();
2828 while (1)
2829 {
2830 if (token->type == CPP_OPEN_PAREN)
2831 {
2832 source_location paren_loc = token->src_loc;
2833 eat_token (CPP_OPEN_PAREN);
2834 if (peek_ident ("if"))
2835 {
2836 eat_ident ("if");
2837 active_ifs.safe_push (if_or_with (parse_c_expr (CPP_OPEN_PAREN),
2838 token->src_loc, false));
2839 /* If this if is immediately closed then it contains a
2840 manual matcher or is part of a predicate definition.
2841 Push it. */
2842 if (peek ()->type == CPP_CLOSE_PAREN)
2843 {
2844 if (!matcher)
2845 fatal_at (token, "manual transform not implemented");
2846 simplifiers.safe_push
2847 (new simplify (match, match_location, result,
2848 paren_loc, active_ifs.copy (),
2849 active_fors.copy (), capture_ids));
2850 }
2851 }
2852 else if (peek_ident ("with"))
2853 {
2854 eat_ident ("with");
2855 /* Parse (with c-expr expr) as (if-with (true) expr). */
2856 c_expr *e = parse_c_expr (CPP_OPEN_BRACE);
2857 e->nr_stmts = 0;
2858 active_ifs.safe_push (if_or_with (e, token->src_loc, true));
2859 }
2860 else
2861 {
2862 operand *op = result;
2863 if (!matcher)
2864 op = parse_expr ();
2865 simplifiers.safe_push
2866 (new simplify (match, match_location, op,
2867 token->src_loc, active_ifs.copy (),
2868 active_fors.copy (), capture_ids));
2869 eat_token (CPP_CLOSE_PAREN);
2870 /* A "default" result closes the enclosing scope. */
2871 if (active_ifs.length () > active_ifs_len)
2872 {
2873 eat_token (CPP_CLOSE_PAREN);
2874 active_ifs.pop ();
2875 }
2876 else
2877 return;
2878 }
2879 }
2880 else if (token->type == CPP_CLOSE_PAREN)
2881 {
2882 /* Close a scope if requested. */
2883 if (active_ifs.length () > active_ifs_len)
2884 {
2885 eat_token (CPP_CLOSE_PAREN);
2886 active_ifs.pop ();
2887 token = peek ();
2888 }
2889 else
2890 return;
2891 }
2892 else
2893 {
2894 if (matcher)
2895 fatal_at (token, "expected match operand expression");
2896 simplifiers.safe_push
2897 (new simplify (match, match_location,
2898 matcher ? result : parse_op (),
2899 token->src_loc, active_ifs.copy (),
2900 active_fors.copy (), capture_ids));
2901 /* A "default" result closes the enclosing scope. */
2902 if (active_ifs.length () > active_ifs_len)
2903 {
2904 eat_token (CPP_CLOSE_PAREN);
2905 active_ifs.pop ();
2906 }
2907 else
2908 return;
2909 }
2910 token = peek ();
2911 }
2912 }
2913
2914 /* Parsing of the outer control structures. */
2915
2916 /* Parse a for expression
2917 for = '(' 'for' <subst>... <pattern> ')'
2918 subst = <ident> '(' <ident>... ')' */
2919
2920 void
2921 parser::parse_for (source_location)
2922 {
2923 vec<user_id *> user_ids = vNULL;
2924 const cpp_token *token;
2925 unsigned min_n_opers = 0, max_n_opers = 0;
2926
2927 while (1)
2928 {
2929 token = peek_ident ();
2930 if (token == 0)
2931 break;
2932
2933 /* Insert the user defined operators into the operator hash. */
2934 const char *id = get_ident ();
2935 user_id *op = new user_id (id);
2936 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
2937 if (*slot)
2938 fatal_at (token, "operator already defined");
2939 *slot = op;
2940 user_ids.safe_push (op);
2941
2942 eat_token (CPP_OPEN_PAREN);
2943
2944 int arity = -1;
2945 while ((token = peek_ident ()) != 0)
2946 {
2947 const char *oper = get_ident ();
2948 id_base *idb = get_operator (oper);
2949 if (idb == NULL)
2950 fatal_at (token, "no such operator '%s'", oper);
2951 if (*idb == CONVERT0 || *idb == CONVERT1 || *idb == CONVERT2)
2952 fatal_at (token, "conditional operators cannot be used inside for");
2953
2954 if (arity == -1)
2955 arity = idb->nargs;
2956 else if (idb->nargs == -1)
2957 ;
2958 else if (idb->nargs != arity)
2959 fatal_at (token, "operator '%s' with arity %d does not match "
2960 "others with arity %d", oper, idb->nargs, arity);
2961
2962 op->substitutes.safe_push (idb);
2963 }
2964 op->nargs = arity;
2965 token = expect (CPP_CLOSE_PAREN);
2966
2967 unsigned nsubstitutes = op->substitutes.length ();
2968 if (nsubstitutes == 0)
2969 fatal_at (token, "A user-defined operator must have at least "
2970 "one substitution");
2971 if (max_n_opers == 0)
2972 {
2973 min_n_opers = nsubstitutes;
2974 max_n_opers = nsubstitutes;
2975 }
2976 else
2977 {
2978 if (nsubstitutes % min_n_opers != 0
2979 && min_n_opers % nsubstitutes != 0)
2980 fatal_at (token, "All user-defined identifiers must have a "
2981 "multiple number of operator substitutions of the "
2982 "smallest number of substitutions");
2983 if (nsubstitutes < min_n_opers)
2984 min_n_opers = nsubstitutes;
2985 else if (nsubstitutes > max_n_opers)
2986 max_n_opers = nsubstitutes;
2987 }
2988 }
2989
2990 unsigned n_ids = user_ids.length ();
2991 if (n_ids == 0)
2992 fatal_at (token, "for requires at least one user-defined identifier");
2993
2994 token = peek ();
2995 if (token->type == CPP_CLOSE_PAREN)
2996 fatal_at (token, "no pattern defined in for");
2997
2998 active_fors.safe_push (user_ids);
2999 while (1)
3000 {
3001 token = peek ();
3002 if (token->type == CPP_CLOSE_PAREN)
3003 break;
3004 parse_pattern ();
3005 }
3006 active_fors.pop ();
3007
3008 /* Remove user-defined operators from the hash again. */
3009 for (unsigned i = 0; i < user_ids.length (); ++i)
3010 operators->remove_elt (user_ids[i]);
3011 }
3012
3013 /* Parse an outer if expression.
3014 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
3015
3016 void
3017 parser::parse_if (source_location loc)
3018 {
3019 operand *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
3020
3021 const cpp_token *token = peek ();
3022 if (token->type == CPP_CLOSE_PAREN)
3023 fatal_at (token, "no pattern defined in if");
3024
3025 active_ifs.safe_push (if_or_with (ifexpr, loc, false));
3026 while (1)
3027 {
3028 const cpp_token *token = peek ();
3029 if (token->type == CPP_CLOSE_PAREN)
3030 break;
3031
3032 parse_pattern ();
3033 }
3034 active_ifs.pop ();
3035 }
3036
3037 /* Parse a list of predefined predicate identifiers.
3038 preds = '(' 'define_predicates' <ident>... ')' */
3039
3040 void
3041 parser::parse_predicates (source_location)
3042 {
3043 do
3044 {
3045 const cpp_token *token = peek ();
3046 if (token->type != CPP_NAME)
3047 break;
3048
3049 add_predicate (get_ident ());
3050 }
3051 while (1);
3052 }
3053
3054 /* Parse outer control structures.
3055 pattern = <preds>|<for>|<if>|<simplify>|<match> */
3056
3057 void
3058 parser::parse_pattern ()
3059 {
3060 /* All clauses start with '('. */
3061 eat_token (CPP_OPEN_PAREN);
3062 const cpp_token *token = peek ();
3063 const char *id = get_ident ();
3064 if (strcmp (id, "simplify") == 0)
3065 parse_simplify (token->src_loc, simplifiers, NULL, NULL);
3066 else if (strcmp (id, "match") == 0)
3067 {
3068 bool with_args = false;
3069 if (peek ()->type == CPP_OPEN_PAREN)
3070 {
3071 eat_token (CPP_OPEN_PAREN);
3072 with_args = true;
3073 }
3074 const char *name = get_ident ();
3075 id_base *id = get_operator (name);
3076 predicate_id *p;
3077 if (!id)
3078 {
3079 p = add_predicate (name);
3080 user_predicates.safe_push (p);
3081 }
3082 else if ((p = dyn_cast <predicate_id *> (id)))
3083 ;
3084 else
3085 fatal_at (token, "cannot add a match to a non-predicate ID");
3086 /* Parse (match <id> <arg>... (match-expr)) here. */
3087 expr *e = NULL;
3088 if (with_args)
3089 {
3090 e = new expr (p);
3091 while (peek ()->type == CPP_ATSIGN)
3092 e->append_op (parse_capture (NULL));
3093 eat_token (CPP_CLOSE_PAREN);
3094 }
3095 if (p->nargs != -1
3096 && ((e && e->ops.length () != (unsigned)p->nargs)
3097 || (!e && p->nargs != 0)))
3098 fatal_at (token, "non-matching number of match operands");
3099 p->nargs = e ? e->ops.length () : 0;
3100 parse_simplify (token->src_loc, p->matchers, p, e);
3101 }
3102 else if (strcmp (id, "for") == 0)
3103 parse_for (token->src_loc);
3104 else if (strcmp (id, "if") == 0)
3105 parse_if (token->src_loc);
3106 else if (strcmp (id, "define_predicates") == 0)
3107 {
3108 if (active_ifs.length () > 0
3109 || active_fors.length () > 0)
3110 fatal_at (token, "define_predicates inside if or for is not supported");
3111 parse_predicates (token->src_loc);
3112 }
3113 else
3114 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
3115 active_ifs.length () == 0 && active_fors.length () == 0
3116 ? "'define_predicates', " : "");
3117
3118 eat_token (CPP_CLOSE_PAREN);
3119 }
3120
3121 /* Main entry of the parser. Repeatedly parse outer control structures. */
3122
3123 parser::parser (cpp_reader *r_)
3124 {
3125 r = r_;
3126 active_ifs = vNULL;
3127 active_fors = vNULL;
3128 simplifiers = vNULL;
3129 user_predicates = vNULL;
3130
3131 const cpp_token *token = next ();
3132 while (token->type != CPP_EOF)
3133 {
3134 _cpp_backup_tokens (r, 1);
3135 parse_pattern ();
3136 token = next ();
3137 }
3138 }
3139
3140
3141 /* Helper for the linemap code. */
3142
3143 static size_t
3144 round_alloc_size (size_t s)
3145 {
3146 return s;
3147 }
3148
3149
3150 /* The genmatch generator progam. It reads from a pattern description
3151 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
3152
3153 int
3154 main (int argc, char **argv)
3155 {
3156 cpp_reader *r;
3157
3158 progname = "genmatch";
3159
3160 if (argc < 2)
3161 return 1;
3162
3163 bool gimple = true;
3164 bool verbose = false;
3165 char *input = argv[argc-1];
3166 for (int i = 1; i < argc - 1; ++i)
3167 {
3168 if (strcmp (argv[i], "--gimple") == 0)
3169 gimple = true;
3170 else if (strcmp (argv[i], "--generic") == 0)
3171 gimple = false;
3172 else if (strcmp (argv[i], "-v") == 0)
3173 verbose = true;
3174 else
3175 {
3176 fprintf (stderr, "Usage: genmatch "
3177 "[--gimple] [--generic] [-v] input\n");
3178 return 1;
3179 }
3180 }
3181
3182 line_table = XCNEW (struct line_maps);
3183 linemap_init (line_table, 0);
3184 line_table->reallocator = xrealloc;
3185 line_table->round_alloc_size = round_alloc_size;
3186
3187 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
3188 cpp_callbacks *cb = cpp_get_callbacks (r);
3189 cb->error = error_cb;
3190
3191 if (!cpp_read_main_file (r, input))
3192 return 1;
3193 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
3194 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
3195
3196 /* Pre-seed operators. */
3197 operators = new hash_table<id_base> (1024);
3198 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
3199 add_operator (SYM, # SYM, # TYPE, NARGS);
3200 #define END_OF_BASE_TREE_CODES
3201 #include "tree.def"
3202 add_operator (CONVERT0, "CONVERT0", "tcc_unary", 1);
3203 add_operator (CONVERT1, "CONVERT1", "tcc_unary", 1);
3204 add_operator (CONVERT2, "CONVERT2", "tcc_unary", 1);
3205 #undef END_OF_BASE_TREE_CODES
3206 #undef DEFTREECODE
3207
3208 /* Pre-seed builtin functions.
3209 ??? Cannot use N (name) as that is targetm.emultls.get_address
3210 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
3211 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
3212 add_builtin (ENUM, # ENUM);
3213 #include "builtins.def"
3214 #undef DEF_BUILTIN
3215
3216 /* Parse ahead! */
3217 parser p (r);
3218
3219 if (gimple)
3220 write_header (stdout, "gimple-match-head.c");
3221 else
3222 write_header (stdout, "generic-match-head.c");
3223
3224 /* Go over all predicates defined with patterns and perform
3225 lowering and code generation. */
3226 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
3227 {
3228 predicate_id *pred = p.user_predicates[i];
3229 lower (pred->matchers);
3230
3231 if (verbose)
3232 for (unsigned i = 0; i < pred->matchers.length (); ++i)
3233 print_matches (pred->matchers[i]);
3234
3235 decision_tree dt;
3236 for (unsigned i = 0; i < pred->matchers.length (); ++i)
3237 dt.insert (pred->matchers[i], i);
3238
3239 if (verbose)
3240 dt.print (stderr);
3241
3242 write_predicate (stdout, pred, dt, gimple);
3243 }
3244
3245 /* Lower the main simplifiers and generate code for them. */
3246 lower (p.simplifiers);
3247
3248 if (verbose)
3249 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
3250 print_matches (p.simplifiers[i]);
3251
3252 decision_tree dt;
3253 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
3254 dt.insert (p.simplifiers[i], i);
3255
3256 if (verbose)
3257 dt.print (stderr);
3258
3259 if (gimple)
3260 dt.gen_gimple (stdout);
3261 else
3262 dt.gen_generic (stdout);
3263
3264 /* Finalize. */
3265 cpp_finish (r, NULL);
3266 cpp_destroy (r);
3267
3268 delete operators;
3269
3270 return 0;
3271 }