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