RISC-V: Fix more splitters accidentally calling gen_reg_rtx.
[official-gcc.git] / gcc / genrecog.c
blobf20089eeee8e9d66b3e9b58213783c66616c6306
1 /* Generate code from machine description to recognize rtl as insns.
2 Copyright (C) 1987-2019 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
21 /* This program is used to produce insn-recog.c, which contains a
22 function called `recog' plus its subroutines. These functions
23 contain a decision tree that recognizes whether an rtx, the
24 argument given to recog, is a valid instruction.
26 recog returns -1 if the rtx is not valid. If the rtx is valid,
27 recog returns a nonnegative number which is the insn code number
28 for the pattern that matched. This is the same as the order in the
29 machine description of the entry that matched. This number can be
30 used as an index into various insn_* tables, such as insn_template,
31 insn_outfun, and insn_n_operands (found in insn-output.c).
33 The third argument to recog is an optional pointer to an int. If
34 present, recog will accept a pattern if it matches except for
35 missing CLOBBER expressions at the end. In that case, the value
36 pointed to by the optional pointer will be set to the number of
37 CLOBBERs that need to be added (it should be initialized to zero by
38 the caller). If it is set nonzero, the caller should allocate a
39 PARALLEL of the appropriate size, copy the initial entries, and
40 call add_clobbers (found in insn-emit.c) to fill in the CLOBBERs.
42 This program also generates the function `split_insns', which
43 returns 0 if the rtl could not be split, or it returns the split
44 rtl as an INSN list.
46 This program also generates the function `peephole2_insns', which
47 returns 0 if the rtl could not be matched. If there was a match,
48 the new rtl is returned in an INSN list, and LAST_INSN will point
49 to the last recognized insn in the old sequence.
52 At a high level, the algorithm used in this file is as follows:
54 1. Build up a decision tree for each routine, using the following
55 approach to matching an rtx:
57 - First determine the "shape" of the rtx, based on GET_CODE,
58 XVECLEN and XINT. This phase examines SET_SRCs before SET_DESTs
59 since SET_SRCs tend to be more distinctive. It examines other
60 operands in numerical order, since the canonicalization rules
61 prefer putting complex operands of commutative operators first.
63 - Next check modes and predicates. This phase examines all
64 operands in numerical order, even for SETs, since the mode of a
65 SET_DEST is exact while the mode of a SET_SRC can be VOIDmode
66 for constant integers.
68 - Next check match_dups.
70 - Finally check the C condition and (where appropriate) pnum_clobbers.
72 2. Try to optimize the tree by removing redundant tests, CSEing tests,
73 folding tests together, etc.
75 3. Look for common subtrees and split them out into "pattern" routines.
76 These common subtrees can be identical or they can differ in mode,
77 code, or integer (usually an UNSPEC or UNSPEC_VOLATILE code).
78 In the latter case the users of the pattern routine pass the
79 appropriate mode, etc., as argument. For example, if two patterns
80 contain:
82 (plus:SI (match_operand:SI 1 "register_operand")
83 (match_operand:SI 2 "register_operand"))
85 we can split the associated matching code out into a subroutine.
86 If a pattern contains:
88 (minus:DI (match_operand:DI 1 "register_operand")
89 (match_operand:DI 2 "register_operand"))
91 then we can consider using the same matching routine for both
92 the plus and minus expressions, passing PLUS and SImode in the
93 former case and MINUS and DImode in the latter case.
95 The main aim of this phase is to reduce the compile time of the
96 insn-recog.c code and to reduce the amount of object code in
97 insn-recog.o.
99 4. Split the matching trees into functions, trying to limit the
100 size of each function to a sensible amount.
102 Again, the main aim of this phase is to reduce the compile time
103 of insn-recog.c. (It doesn't help with the size of insn-recog.o.)
105 5. Write out C++ code for each function. */
107 #include "bconfig.h"
108 #define INCLUDE_ALGORITHM
109 #include "system.h"
110 #include "coretypes.h"
111 #include "tm.h"
112 #include "rtl.h"
113 #include "errors.h"
114 #include "read-md.h"
115 #include "gensupport.h"
117 #undef GENERATOR_FILE
118 enum true_rtx_doe {
119 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS) TRUE_##ENUM,
120 #include "rtl.def"
121 #undef DEF_RTL_EXPR
122 FIRST_GENERATOR_RTX_CODE
124 #define NUM_TRUE_RTX_CODE ((int) FIRST_GENERATOR_RTX_CODE)
125 #define GENERATOR_FILE 1
127 /* Debugging variables to control which optimizations are performed.
128 Note that disabling merge_states_p leads to very large output. */
129 static const bool merge_states_p = true;
130 static const bool collapse_optional_decisions_p = true;
131 static const bool cse_tests_p = true;
132 static const bool simplify_tests_p = true;
133 static const bool use_operand_variables_p = true;
134 static const bool use_subroutines_p = true;
135 static const bool use_pattern_routines_p = true;
137 /* Whether to add comments for optional tests that we decided to keep.
138 Can be useful when debugging the generator itself but is noise when
139 debugging the generated code. */
140 static const bool mark_optional_transitions_p = false;
142 /* Whether pattern routines should calculate positions relative to their
143 rtx parameter rather than use absolute positions. This e.g. allows
144 a pattern routine to be shared between a plain SET and a PARALLEL
145 that includes a SET.
147 In principle it sounds like this should be useful, especially for
148 recog_for_combine, where the plain SET form is generated automatically
149 from a PARALLEL of a single SET and some CLOBBERs. In practice it doesn't
150 seem to help much and leads to slightly bigger object files. */
151 static const bool relative_patterns_p = false;
153 /* Whether pattern routines should be allowed to test whether pnum_clobbers
154 is null. This requires passing pnum_clobbers around as a parameter. */
155 static const bool pattern_have_num_clobbers_p = true;
157 /* Whether pattern routines should be allowed to test .md file C conditions.
158 This requires passing insn around as a parameter, in case the C
159 condition refers to it. In practice this tends to lead to bigger
160 object files. */
161 static const bool pattern_c_test_p = false;
163 /* Whether to require each parameter passed to a pattern routine to be
164 unique. Disabling this check for example allows unary operators with
165 matching modes (like NEG) and unary operators with mismatched modes
166 (like ZERO_EXTEND) to be matched by a single pattern. However, we then
167 often have cases where the same value is passed too many times. */
168 static const bool force_unique_params_p = true;
170 /* The maximum (approximate) depth of block nesting that an individual
171 routine or subroutine should have. This limit is about keeping the
172 output readable rather than reducing compile time. */
173 static const unsigned int MAX_DEPTH = 6;
175 /* The minimum number of pseudo-statements that a state must have before
176 we split it out into a subroutine. */
177 static const unsigned int MIN_NUM_STATEMENTS = 5;
179 /* The number of pseudo-statements a state can have before we consider
180 splitting out substates into subroutines. This limit is about avoiding
181 compile-time problems with very big functions (and also about keeping
182 functions within --param optimization limits, etc.). */
183 static const unsigned int MAX_NUM_STATEMENTS = 200;
185 /* The minimum number of pseudo-statements that can be used in a pattern
186 routine. */
187 static const unsigned int MIN_COMBINE_COST = 4;
189 /* The maximum number of arguments that a pattern routine can have.
190 The idea is to prevent one pattern getting a ridiculous number of
191 arguments when it would be more beneficial to have a separate pattern
192 routine instead. */
193 static const unsigned int MAX_PATTERN_PARAMS = 5;
195 /* The maximum operand number plus one. */
196 int num_operands;
198 /* Ways of obtaining an rtx to be tested. */
199 enum position_type {
200 /* PATTERN (peep2_next_insn (ARG)). */
201 POS_PEEP2_INSN,
203 /* XEXP (BASE, ARG). */
204 POS_XEXP,
206 /* XVECEXP (BASE, 0, ARG). */
207 POS_XVECEXP0
210 /* The position of an rtx relative to X0. Each useful position is
211 represented by exactly one instance of this structure. */
212 struct position
214 /* The parent rtx. This is the root position for POS_PEEP2_INSNs. */
215 struct position *base;
217 /* A position with the same BASE and TYPE, but with the next value
218 of ARG. */
219 struct position *next;
221 /* A list of all POS_XEXP positions that use this one as their base,
222 chained by NEXT fields. The first entry represents XEXP (this, 0),
223 the second represents XEXP (this, 1), and so on. */
224 struct position *xexps;
226 /* A list of POS_XVECEXP0 positions that use this one as their base,
227 chained by NEXT fields. The first entry represents XVECEXP (this, 0, 0),
228 the second represents XVECEXP (this, 0, 1), and so on. */
229 struct position *xvecexp0s;
231 /* The type of position. */
232 enum position_type type;
234 /* The argument to TYPE (shown as ARG in the position_type comments). */
235 int arg;
237 /* The instruction to which the position belongs. */
238 unsigned int insn_id;
240 /* The depth of this position relative to the instruction pattern.
241 E.g. if the instruction pattern is a SET, the SET itself has a
242 depth of 0 while the SET_DEST and SET_SRC have depths of 1. */
243 unsigned int depth;
245 /* A unique identifier for this position. */
246 unsigned int id;
249 enum routine_type {
250 SUBPATTERN, RECOG, SPLIT, PEEPHOLE2
253 /* The root position (x0). */
254 static struct position root_pos;
256 /* The number of positions created. Also one higher than the maximum
257 position id. */
258 static unsigned int num_positions = 1;
260 /* A list of all POS_PEEP2_INSNs. The entry for insn 0 is the root position,
261 since we are given that instruction's pattern as x0. */
262 static struct position *peep2_insn_pos_list = &root_pos;
264 /* Return a position with the given BASE, TYPE and ARG. NEXT_PTR
265 points to where the unique object that represents the position
266 should be stored. Create the object if it doesn't already exist,
267 otherwise reuse the object that is already there. */
269 static struct position *
270 next_position (struct position **next_ptr, struct position *base,
271 enum position_type type, int arg)
273 struct position *pos;
275 pos = *next_ptr;
276 if (!pos)
278 pos = XCNEW (struct position);
279 pos->type = type;
280 pos->arg = arg;
281 if (type == POS_PEEP2_INSN)
283 pos->base = 0;
284 pos->insn_id = arg;
285 pos->depth = base->depth;
287 else
289 pos->base = base;
290 pos->insn_id = base->insn_id;
291 pos->depth = base->depth + 1;
293 pos->id = num_positions++;
294 *next_ptr = pos;
296 return pos;
299 /* Compare positions POS1 and POS2 lexicographically. */
301 static int
302 compare_positions (struct position *pos1, struct position *pos2)
304 int diff;
306 diff = pos1->depth - pos2->depth;
307 if (diff < 0)
309 pos2 = pos2->base;
310 while (pos1->depth != pos2->depth);
311 else if (diff > 0)
313 pos1 = pos1->base;
314 while (pos1->depth != pos2->depth);
315 while (pos1 != pos2)
317 diff = (int) pos1->type - (int) pos2->type;
318 if (diff == 0)
319 diff = pos1->arg - pos2->arg;
320 pos1 = pos1->base;
321 pos2 = pos2->base;
323 return diff;
326 /* Return the most deeply-nested position that is common to both
327 POS1 and POS2. If the positions are from different instructions,
328 return the one with the lowest insn_id. */
330 static struct position *
331 common_position (struct position *pos1, struct position *pos2)
333 if (pos1->insn_id != pos2->insn_id)
334 return pos1->insn_id < pos2->insn_id ? pos1 : pos2;
335 if (pos1->depth > pos2->depth)
336 std::swap (pos1, pos2);
337 while (pos1->depth != pos2->depth)
338 pos2 = pos2->base;
339 while (pos1 != pos2)
341 pos1 = pos1->base;
342 pos2 = pos2->base;
344 return pos1;
347 /* Search for and return operand N, stop when reaching node STOP. */
349 static rtx
350 find_operand (rtx pattern, int n, rtx stop)
352 const char *fmt;
353 RTX_CODE code;
354 int i, j, len;
355 rtx r;
357 if (pattern == stop)
358 return stop;
360 code = GET_CODE (pattern);
361 if ((code == MATCH_SCRATCH
362 || code == MATCH_OPERAND
363 || code == MATCH_OPERATOR
364 || code == MATCH_PARALLEL)
365 && XINT (pattern, 0) == n)
366 return pattern;
368 fmt = GET_RTX_FORMAT (code);
369 len = GET_RTX_LENGTH (code);
370 for (i = 0; i < len; i++)
372 switch (fmt[i])
374 case 'e': case 'u':
375 if ((r = find_operand (XEXP (pattern, i), n, stop)) != NULL_RTX)
376 return r;
377 break;
379 case 'V':
380 if (! XVEC (pattern, i))
381 break;
382 /* Fall through. */
384 case 'E':
385 for (j = 0; j < XVECLEN (pattern, i); j++)
386 if ((r = find_operand (XVECEXP (pattern, i, j), n, stop))
387 != NULL_RTX)
388 return r;
389 break;
391 case 'r': case 'p': case 'i': case 'w': case '0': case 's':
392 break;
394 default:
395 gcc_unreachable ();
399 return NULL;
402 /* Search for and return operand M, such that it has a matching
403 constraint for operand N. */
405 static rtx
406 find_matching_operand (rtx pattern, int n)
408 const char *fmt;
409 RTX_CODE code;
410 int i, j, len;
411 rtx r;
413 code = GET_CODE (pattern);
414 if (code == MATCH_OPERAND
415 && (XSTR (pattern, 2)[0] == '0' + n
416 || (XSTR (pattern, 2)[0] == '%'
417 && XSTR (pattern, 2)[1] == '0' + n)))
418 return pattern;
420 fmt = GET_RTX_FORMAT (code);
421 len = GET_RTX_LENGTH (code);
422 for (i = 0; i < len; i++)
424 switch (fmt[i])
426 case 'e': case 'u':
427 if ((r = find_matching_operand (XEXP (pattern, i), n)))
428 return r;
429 break;
431 case 'V':
432 if (! XVEC (pattern, i))
433 break;
434 /* Fall through. */
436 case 'E':
437 for (j = 0; j < XVECLEN (pattern, i); j++)
438 if ((r = find_matching_operand (XVECEXP (pattern, i, j), n)))
439 return r;
440 break;
442 case 'r': case 'p': case 'i': case 'w': case '0': case 's':
443 break;
445 default:
446 gcc_unreachable ();
450 return NULL;
453 /* In DEFINE_EXPAND, DEFINE_SPLIT, and DEFINE_PEEPHOLE2, we
454 don't use the MATCH_OPERAND constraint, only the predicate.
455 This is confusing to folks doing new ports, so help them
456 not make the mistake. */
458 static bool
459 constraints_supported_in_insn_p (rtx insn)
461 return !(GET_CODE (insn) == DEFINE_EXPAND
462 || GET_CODE (insn) == DEFINE_SPLIT
463 || GET_CODE (insn) == DEFINE_PEEPHOLE2);
466 /* Return the name of the predicate matched by MATCH_RTX. */
468 static const char *
469 predicate_name (rtx match_rtx)
471 if (GET_CODE (match_rtx) == MATCH_SCRATCH)
472 return "scratch_operand";
473 else
474 return XSTR (match_rtx, 1);
477 /* Return true if OPERAND is a MATCH_OPERAND using a special predicate
478 function. */
480 static bool
481 special_predicate_operand_p (rtx operand)
483 if (GET_CODE (operand) == MATCH_OPERAND)
485 const char *pred_name = predicate_name (operand);
486 if (pred_name[0] != 0)
488 const struct pred_data *pred;
490 pred = lookup_predicate (pred_name);
491 return pred != NULL && pred->special;
495 return false;
498 /* Check for various errors in PATTERN, which is part of INFO.
499 SET is nonnull for a destination, and is the complete set pattern.
500 SET_CODE is '=' for normal sets, and '+' within a context that
501 requires in-out constraints. */
503 static void
504 validate_pattern (rtx pattern, md_rtx_info *info, rtx set, int set_code)
506 const char *fmt;
507 RTX_CODE code;
508 size_t i, len;
509 int j;
511 code = GET_CODE (pattern);
512 switch (code)
514 case MATCH_SCRATCH:
516 const char constraints0 = XSTR (pattern, 1)[0];
518 if (!constraints_supported_in_insn_p (info->def))
520 if (constraints0)
522 error_at (info->loc, "constraints not supported in %s",
523 GET_RTX_NAME (GET_CODE (info->def)));
525 return;
528 /* If a MATCH_SCRATCH is used in a context requiring an write-only
529 or read/write register, validate that. */
530 if (set_code == '='
531 && constraints0
532 && constraints0 != '='
533 && constraints0 != '+')
535 error_at (info->loc, "operand %d missing output reload",
536 XINT (pattern, 0));
538 return;
540 case MATCH_DUP:
541 case MATCH_OP_DUP:
542 case MATCH_PAR_DUP:
543 if (find_operand (info->def, XINT (pattern, 0), pattern) == pattern)
544 error_at (info->loc, "operand %i duplicated before defined",
545 XINT (pattern, 0));
546 break;
547 case MATCH_OPERAND:
548 case MATCH_OPERATOR:
550 const char *pred_name = XSTR (pattern, 1);
551 const struct pred_data *pred;
552 const char *c_test;
554 c_test = get_c_test (info->def);
556 if (pred_name[0] != 0)
558 pred = lookup_predicate (pred_name);
559 if (!pred)
560 error_at (info->loc, "unknown predicate '%s'", pred_name);
562 else
563 pred = 0;
565 if (code == MATCH_OPERAND)
567 const char *constraints = XSTR (pattern, 2);
568 const char constraints0 = constraints[0];
570 if (!constraints_supported_in_insn_p (info->def))
572 if (constraints0)
574 error_at (info->loc, "constraints not supported in %s",
575 GET_RTX_NAME (GET_CODE (info->def)));
579 /* A MATCH_OPERAND that is a SET should have an output reload. */
580 else if (set && constraints0)
582 if (set_code == '+')
584 if (constraints0 == '+')
586 /* If we've only got an output reload for this operand,
587 we'd better have a matching input operand. */
588 else if (constraints0 == '='
589 && find_matching_operand (info->def,
590 XINT (pattern, 0)))
592 else
593 error_at (info->loc, "operand %d missing in-out reload",
594 XINT (pattern, 0));
596 else if (constraints0 != '=' && constraints0 != '+')
597 error_at (info->loc, "operand %d missing output reload",
598 XINT (pattern, 0));
601 /* For matching constraint in MATCH_OPERAND, the digit must be a
602 smaller number than the number of the operand that uses it in the
603 constraint. */
604 while (1)
606 while (constraints[0]
607 && (constraints[0] == ' ' || constraints[0] == ','))
608 constraints++;
609 if (!constraints[0])
610 break;
612 if (constraints[0] >= '0' && constraints[0] <= '9')
614 int val;
616 sscanf (constraints, "%d", &val);
617 if (val >= XINT (pattern, 0))
618 error_at (info->loc, "constraint digit %d is not"
619 " smaller than operand %d",
620 val, XINT (pattern, 0));
623 while (constraints[0] && constraints[0] != ',')
624 constraints++;
628 /* Allowing non-lvalues in destinations -- particularly CONST_INT --
629 while not likely to occur at runtime, results in less efficient
630 code from insn-recog.c. */
631 if (set && pred && pred->allows_non_lvalue)
632 error_at (info->loc, "destination operand %d allows non-lvalue",
633 XINT (pattern, 0));
635 /* A modeless MATCH_OPERAND can be handy when we can check for
636 multiple modes in the c_test. In most other cases, it is a
637 mistake. Only DEFINE_INSN is eligible, since SPLIT and
638 PEEP2 can FAIL within the output pattern. Exclude special
639 predicates, which check the mode themselves. Also exclude
640 predicates that allow only constants. Exclude the SET_DEST
641 of a call instruction, as that is a common idiom. */
643 if (GET_MODE (pattern) == VOIDmode
644 && code == MATCH_OPERAND
645 && GET_CODE (info->def) == DEFINE_INSN
646 && pred
647 && !pred->special
648 && pred->allows_non_const
649 && strstr (c_test, "operands") == NULL
650 && ! (set
651 && GET_CODE (set) == SET
652 && GET_CODE (SET_SRC (set)) == CALL))
653 message_at (info->loc, "warning: operand %d missing mode?",
654 XINT (pattern, 0));
655 return;
658 case SET:
660 machine_mode dmode, smode;
661 rtx dest, src;
663 dest = SET_DEST (pattern);
664 src = SET_SRC (pattern);
666 /* STRICT_LOW_PART is a wrapper. Its argument is the real
667 destination, and it's mode should match the source. */
668 if (GET_CODE (dest) == STRICT_LOW_PART)
669 dest = XEXP (dest, 0);
671 /* Find the referent for a DUP. */
673 if (GET_CODE (dest) == MATCH_DUP
674 || GET_CODE (dest) == MATCH_OP_DUP
675 || GET_CODE (dest) == MATCH_PAR_DUP)
676 dest = find_operand (info->def, XINT (dest, 0), NULL);
678 if (GET_CODE (src) == MATCH_DUP
679 || GET_CODE (src) == MATCH_OP_DUP
680 || GET_CODE (src) == MATCH_PAR_DUP)
681 src = find_operand (info->def, XINT (src, 0), NULL);
683 dmode = GET_MODE (dest);
684 smode = GET_MODE (src);
686 /* Mode checking is not performed for special predicates. */
687 if (special_predicate_operand_p (src)
688 || special_predicate_operand_p (dest))
691 /* The operands of a SET must have the same mode unless one
692 is VOIDmode. */
693 else if (dmode != VOIDmode && smode != VOIDmode && dmode != smode)
694 error_at (info->loc, "mode mismatch in set: %smode vs %smode",
695 GET_MODE_NAME (dmode), GET_MODE_NAME (smode));
697 /* If only one of the operands is VOIDmode, and PC or CC0 is
698 not involved, it's probably a mistake. */
699 else if (dmode != smode
700 && GET_CODE (dest) != PC
701 && GET_CODE (dest) != CC0
702 && GET_CODE (src) != PC
703 && GET_CODE (src) != CC0
704 && !CONST_INT_P (src)
705 && !CONST_WIDE_INT_P (src)
706 && GET_CODE (src) != CALL)
708 const char *which;
709 which = (dmode == VOIDmode ? "destination" : "source");
710 message_at (info->loc, "warning: %s missing a mode?", which);
713 if (dest != SET_DEST (pattern))
714 validate_pattern (dest, info, pattern, '=');
715 validate_pattern (SET_DEST (pattern), info, pattern, '=');
716 validate_pattern (SET_SRC (pattern), info, NULL_RTX, 0);
717 return;
720 case CLOBBER:
721 case CLOBBER_HIGH:
722 validate_pattern (SET_DEST (pattern), info, pattern, '=');
723 return;
725 case ZERO_EXTRACT:
726 validate_pattern (XEXP (pattern, 0), info, set, set ? '+' : 0);
727 validate_pattern (XEXP (pattern, 1), info, NULL_RTX, 0);
728 validate_pattern (XEXP (pattern, 2), info, NULL_RTX, 0);
729 return;
731 case STRICT_LOW_PART:
732 validate_pattern (XEXP (pattern, 0), info, set, set ? '+' : 0);
733 return;
735 case LABEL_REF:
736 if (GET_MODE (XEXP (pattern, 0)) != VOIDmode)
737 error_at (info->loc, "operand to label_ref %smode not VOIDmode",
738 GET_MODE_NAME (GET_MODE (XEXP (pattern, 0))));
739 break;
741 case VEC_SELECT:
742 if (GET_MODE (pattern) != VOIDmode)
744 machine_mode mode = GET_MODE (pattern);
745 machine_mode imode = GET_MODE (XEXP (pattern, 0));
746 machine_mode emode
747 = VECTOR_MODE_P (mode) ? GET_MODE_INNER (mode) : mode;
748 if (GET_CODE (XEXP (pattern, 1)) == PARALLEL)
750 int expected = 1;
751 unsigned int nelems;
752 if (VECTOR_MODE_P (mode)
753 && !GET_MODE_NUNITS (mode).is_constant (&expected))
754 error_at (info->loc,
755 "vec_select with variable-sized mode %s",
756 GET_MODE_NAME (mode));
757 else if (XVECLEN (XEXP (pattern, 1), 0) != expected)
758 error_at (info->loc,
759 "vec_select parallel with %d elements, expected %d",
760 XVECLEN (XEXP (pattern, 1), 0), expected);
761 else if (VECTOR_MODE_P (imode)
762 && GET_MODE_NUNITS (imode).is_constant (&nelems))
764 int i;
765 for (i = 0; i < expected; ++i)
766 if (CONST_INT_P (XVECEXP (XEXP (pattern, 1), 0, i))
767 && (UINTVAL (XVECEXP (XEXP (pattern, 1), 0, i))
768 >= nelems))
769 error_at (info->loc,
770 "out of bounds selector %u in vec_select, "
771 "expected at most %u",
772 (unsigned)
773 UINTVAL (XVECEXP (XEXP (pattern, 1), 0, i)),
774 nelems - 1);
777 if (imode != VOIDmode && !VECTOR_MODE_P (imode))
778 error_at (info->loc, "%smode of first vec_select operand is not a "
779 "vector mode", GET_MODE_NAME (imode));
780 else if (imode != VOIDmode && GET_MODE_INNER (imode) != emode)
781 error_at (info->loc, "element mode mismatch between vec_select "
782 "%smode and its operand %smode",
783 GET_MODE_NAME (emode),
784 GET_MODE_NAME (GET_MODE_INNER (imode)));
786 break;
788 default:
789 break;
792 fmt = GET_RTX_FORMAT (code);
793 len = GET_RTX_LENGTH (code);
794 for (i = 0; i < len; i++)
796 switch (fmt[i])
798 case 'e': case 'u':
799 validate_pattern (XEXP (pattern, i), info, NULL_RTX, 0);
800 break;
802 case 'E':
803 for (j = 0; j < XVECLEN (pattern, i); j++)
804 validate_pattern (XVECEXP (pattern, i, j), info, NULL_RTX, 0);
805 break;
807 case 'r': case 'p': case 'i': case 'w': case '0': case 's':
808 break;
810 default:
811 gcc_unreachable ();
816 /* Simple list structure for items of type T, for use when being part
817 of a list is an inherent property of T. T must have members equivalent
818 to "T *prev, *next;" and a function "void set_parent (list_head <T> *)"
819 to set the parent list. */
820 template <typename T>
821 class list_head
823 public:
824 /* A range of linked items. */
825 class range
827 public:
828 range (T *);
829 range (T *, T *);
831 T *start, *end;
832 void set_parent (list_head *);
835 list_head ();
836 range release ();
837 void push_back (range);
838 range remove (range);
839 void replace (range, range);
840 T *singleton () const;
842 T *first, *last;
845 /* Create a range [START_IN, START_IN]. */
847 template <typename T>
848 list_head <T>::range::range (T *start_in) : start (start_in), end (start_in) {}
850 /* Create a range [START_IN, END_IN], linked by next and prev fields. */
852 template <typename T>
853 list_head <T>::range::range (T *start_in, T *end_in)
854 : start (start_in), end (end_in) {}
856 template <typename T>
857 void
858 list_head <T>::range::set_parent (list_head <T> *owner)
860 for (T *item = start; item != end; item = item->next)
861 item->set_parent (owner);
862 end->set_parent (owner);
865 template <typename T>
866 list_head <T>::list_head () : first (0), last (0) {}
868 /* Add R to the end of the list. */
870 template <typename T>
871 void
872 list_head <T>::push_back (range r)
874 if (last)
875 last->next = r.start;
876 else
877 first = r.start;
878 r.start->prev = last;
879 last = r.end;
880 r.set_parent (this);
883 /* Remove R from the list. R remains valid and can be inserted into
884 other lists. */
886 template <typename T>
887 typename list_head <T>::range
888 list_head <T>::remove (range r)
890 if (r.start->prev)
891 r.start->prev->next = r.end->next;
892 else
893 first = r.end->next;
894 if (r.end->next)
895 r.end->next->prev = r.start->prev;
896 else
897 last = r.start->prev;
898 r.start->prev = 0;
899 r.end->next = 0;
900 r.set_parent (0);
901 return r;
904 /* Replace OLDR with NEWR. OLDR remains valid and can be inserted into
905 other lists. */
907 template <typename T>
908 void
909 list_head <T>::replace (range oldr, range newr)
911 newr.start->prev = oldr.start->prev;
912 newr.end->next = oldr.end->next;
914 oldr.start->prev = 0;
915 oldr.end->next = 0;
916 oldr.set_parent (0);
918 if (newr.start->prev)
919 newr.start->prev->next = newr.start;
920 else
921 first = newr.start;
922 if (newr.end->next)
923 newr.end->next->prev = newr.end;
924 else
925 last = newr.end;
926 newr.set_parent (this);
929 /* Empty the list and return the previous contents as a range that can
930 be inserted into other lists. */
932 template <typename T>
933 typename list_head <T>::range
934 list_head <T>::release ()
936 range r (first, last);
937 first = 0;
938 last = 0;
939 r.set_parent (0);
940 return r;
943 /* If the list contains a single item, return that item, otherwise return
944 null. */
946 template <typename T>
948 list_head <T>::singleton () const
950 return first == last ? first : 0;
953 class state;
955 /* Describes a possible successful return from a routine. */
956 struct acceptance_type
958 /* The type of routine we're returning from. */
959 routine_type type : 16;
961 /* True if this structure only really represents a partial match,
962 and if we must call a subroutine of type TYPE to complete the match.
963 In this case we'll call the subroutine and, if it succeeds, return
964 whatever the subroutine returned.
966 False if this structure presents a full match. */
967 unsigned int partial_p : 1;
969 union
971 /* If PARTIAL_P, this is the number of the subroutine to call. */
972 int subroutine_id;
974 /* Valid if !PARTIAL_P. */
975 struct
977 /* The identifier of the matching pattern. For SUBPATTERNs this
978 value belongs to an ad-hoc routine-specific enum. For the
979 others it's the number of an .md file pattern. */
980 int code;
981 union
983 /* For RECOG, the number of clobbers that must be added to the
984 pattern in order for it to match CODE. */
985 int num_clobbers;
987 /* For PEEPHOLE2, the number of additional instructions that were
988 included in the optimization. */
989 int match_len;
990 } u;
991 } full;
992 } u;
995 bool
996 operator == (const acceptance_type &a, const acceptance_type &b)
998 if (a.partial_p != b.partial_p)
999 return false;
1000 if (a.partial_p)
1001 return a.u.subroutine_id == b.u.subroutine_id;
1002 else
1003 return a.u.full.code == b.u.full.code;
1006 bool
1007 operator != (const acceptance_type &a, const acceptance_type &b)
1009 return !operator == (a, b);
1012 /* Represents a parameter to a pattern routine. */
1013 class parameter
1015 public:
1016 /* The C type of parameter. */
1017 enum type_enum {
1018 /* Represents an invalid parameter. */
1019 UNSET,
1021 /* A machine_mode parameter. */
1022 MODE,
1024 /* An rtx_code parameter. */
1025 CODE,
1027 /* An int parameter. */
1028 INT,
1030 /* An unsigned int parameter. */
1031 UINT,
1033 /* A HOST_WIDE_INT parameter. */
1034 WIDE_INT
1037 parameter ();
1038 parameter (type_enum, bool, uint64_t);
1040 /* The type of the parameter. */
1041 type_enum type;
1043 /* True if the value passed is variable, false if it is constant. */
1044 bool is_param;
1046 /* If IS_PARAM, this is the number of the variable passed, for an "i%d"
1047 format string. If !IS_PARAM, this is the constant value passed. */
1048 uint64_t value;
1051 parameter::parameter ()
1052 : type (UNSET), is_param (false), value (0) {}
1054 parameter::parameter (type_enum type_in, bool is_param_in, uint64_t value_in)
1055 : type (type_in), is_param (is_param_in), value (value_in) {}
1057 bool
1058 operator == (const parameter &param1, const parameter &param2)
1060 return (param1.type == param2.type
1061 && param1.is_param == param2.is_param
1062 && param1.value == param2.value);
1065 bool
1066 operator != (const parameter &param1, const parameter &param2)
1068 return !operator == (param1, param2);
1071 /* Represents a routine that matches a partial rtx pattern, returning
1072 an ad-hoc enum value on success and -1 on failure. The routine can
1073 be used by any subroutine type. The match can be parameterized by
1074 things like mode, code and UNSPEC number. */
1075 class pattern_routine
1077 public:
1078 /* The state that implements the pattern. */
1079 state *s;
1081 /* The deepest root position from which S can access all the rtxes it needs.
1082 This is NULL if the pattern doesn't need an rtx input, usually because
1083 all matching is done on operands[] instead. */
1084 position *pos;
1086 /* A unique identifier for the routine. */
1087 unsigned int pattern_id;
1089 /* True if the routine takes pnum_clobbers as argument. */
1090 bool pnum_clobbers_p;
1092 /* True if the routine takes the enclosing instruction as argument. */
1093 bool insn_p;
1095 /* The types of the other parameters to the routine, if any. */
1096 auto_vec <parameter::type_enum, MAX_PATTERN_PARAMS> param_types;
1099 /* All defined patterns. */
1100 static vec <pattern_routine *> patterns;
1102 /* Represents one use of a pattern routine. */
1103 class pattern_use
1105 public:
1106 /* The pattern routine to use. */
1107 pattern_routine *routine;
1109 /* The values to pass as parameters. This vector has the same length
1110 as ROUTINE->PARAM_TYPES. */
1111 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
1114 /* Represents a test performed by a decision. */
1115 class rtx_test
1117 public:
1118 rtx_test ();
1120 /* The types of test that can be performed. Most of them take as input
1121 an rtx X. Some also take as input a transition label LABEL; the others
1122 are booleans for which the transition label is always "true".
1124 The order of the enum isn't important. */
1125 enum kind_enum {
1126 /* Check GET_CODE (X) == LABEL. */
1127 CODE,
1129 /* Check GET_MODE (X) == LABEL. */
1130 MODE,
1132 /* Check REGNO (X) == LABEL. */
1133 REGNO_FIELD,
1135 /* Check known_eq (SUBREG_BYTE (X), LABEL). */
1136 SUBREG_FIELD,
1138 /* Check XINT (X, u.opno) == LABEL. */
1139 INT_FIELD,
1141 /* Check XWINT (X, u.opno) == LABEL. */
1142 WIDE_INT_FIELD,
1144 /* Check XVECLEN (X, 0) == LABEL. */
1145 VECLEN,
1147 /* Check peep2_current_count >= u.min_len. */
1148 PEEP2_COUNT,
1150 /* Check XVECLEN (X, 0) >= u.min_len. */
1151 VECLEN_GE,
1153 /* Check whether X is a cached const_int with value u.integer. */
1154 SAVED_CONST_INT,
1156 /* Check u.predicate.data (X, u.predicate.mode). */
1157 PREDICATE,
1159 /* Check rtx_equal_p (X, operands[u.opno]). */
1160 DUPLICATE,
1162 /* Check whether X matches pattern u.pattern. */
1163 PATTERN,
1165 /* Check whether pnum_clobbers is nonnull (RECOG only). */
1166 HAVE_NUM_CLOBBERS,
1168 /* Check whether general C test u.string holds. In general the condition
1169 needs access to "insn" and the full operand list. */
1170 C_TEST,
1172 /* Execute operands[u.opno] = X. (Always succeeds.) */
1173 SET_OP,
1175 /* Accept u.acceptance. Always succeeds for SUBPATTERN, RECOG and SPLIT.
1176 May fail for PEEPHOLE2 if the define_peephole2 C code executes FAIL. */
1177 ACCEPT
1180 /* The position of rtx X in the above description, relative to the
1181 incoming instruction "insn". The position is null if the test
1182 doesn't take an X as input. */
1183 position *pos;
1185 /* Which element of operands[] already contains POS, or -1 if no element
1186 is known to hold POS. */
1187 int pos_operand;
1189 /* The type of test and its parameters, as described above. */
1190 kind_enum kind;
1191 union
1193 int opno;
1194 int min_len;
1195 struct
1197 bool is_param;
1198 int value;
1199 } integer;
1200 struct
1202 const struct pred_data *data;
1203 /* True if the mode is taken from a machine_mode parameter
1204 to the routine rather than a constant machine_mode. If true,
1205 MODE is the number of the parameter (for an "i%d" format string),
1206 otherwise it is the mode itself. */
1207 bool mode_is_param;
1208 unsigned int mode;
1209 } predicate;
1210 pattern_use *pattern;
1211 const char *string;
1212 acceptance_type acceptance;
1213 } u;
1215 static rtx_test code (position *);
1216 static rtx_test mode (position *);
1217 static rtx_test regno_field (position *);
1218 static rtx_test subreg_field (position *);
1219 static rtx_test int_field (position *, int);
1220 static rtx_test wide_int_field (position *, int);
1221 static rtx_test veclen (position *);
1222 static rtx_test peep2_count (int);
1223 static rtx_test veclen_ge (position *, int);
1224 static rtx_test predicate (position *, const pred_data *, machine_mode);
1225 static rtx_test duplicate (position *, int);
1226 static rtx_test pattern (position *, pattern_use *);
1227 static rtx_test have_num_clobbers ();
1228 static rtx_test c_test (const char *);
1229 static rtx_test set_op (position *, int);
1230 static rtx_test accept (const acceptance_type &);
1232 bool terminal_p () const;
1233 bool single_outcome_p () const;
1235 private:
1236 rtx_test (position *, kind_enum);
1239 rtx_test::rtx_test () {}
1241 rtx_test::rtx_test (position *pos_in, kind_enum kind_in)
1242 : pos (pos_in), pos_operand (-1), kind (kind_in) {}
1244 rtx_test
1245 rtx_test::code (position *pos)
1247 return rtx_test (pos, rtx_test::CODE);
1250 rtx_test
1251 rtx_test::mode (position *pos)
1253 return rtx_test (pos, rtx_test::MODE);
1256 rtx_test
1257 rtx_test::regno_field (position *pos)
1259 rtx_test res (pos, rtx_test::REGNO_FIELD);
1260 return res;
1263 rtx_test
1264 rtx_test::subreg_field (position *pos)
1266 rtx_test res (pos, rtx_test::SUBREG_FIELD);
1267 return res;
1270 rtx_test
1271 rtx_test::int_field (position *pos, int opno)
1273 rtx_test res (pos, rtx_test::INT_FIELD);
1274 res.u.opno = opno;
1275 return res;
1278 rtx_test
1279 rtx_test::wide_int_field (position *pos, int opno)
1281 rtx_test res (pos, rtx_test::WIDE_INT_FIELD);
1282 res.u.opno = opno;
1283 return res;
1286 rtx_test
1287 rtx_test::veclen (position *pos)
1289 return rtx_test (pos, rtx_test::VECLEN);
1292 rtx_test
1293 rtx_test::peep2_count (int min_len)
1295 rtx_test res (0, rtx_test::PEEP2_COUNT);
1296 res.u.min_len = min_len;
1297 return res;
1300 rtx_test
1301 rtx_test::veclen_ge (position *pos, int min_len)
1303 rtx_test res (pos, rtx_test::VECLEN_GE);
1304 res.u.min_len = min_len;
1305 return res;
1308 rtx_test
1309 rtx_test::predicate (position *pos, const struct pred_data *data,
1310 machine_mode mode)
1312 rtx_test res (pos, rtx_test::PREDICATE);
1313 res.u.predicate.data = data;
1314 res.u.predicate.mode_is_param = false;
1315 res.u.predicate.mode = mode;
1316 return res;
1319 rtx_test
1320 rtx_test::duplicate (position *pos, int opno)
1322 rtx_test res (pos, rtx_test::DUPLICATE);
1323 res.u.opno = opno;
1324 return res;
1327 rtx_test
1328 rtx_test::pattern (position *pos, pattern_use *pattern)
1330 rtx_test res (pos, rtx_test::PATTERN);
1331 res.u.pattern = pattern;
1332 return res;
1335 rtx_test
1336 rtx_test::have_num_clobbers ()
1338 return rtx_test (0, rtx_test::HAVE_NUM_CLOBBERS);
1341 rtx_test
1342 rtx_test::c_test (const char *string)
1344 rtx_test res (0, rtx_test::C_TEST);
1345 res.u.string = string;
1346 return res;
1349 rtx_test
1350 rtx_test::set_op (position *pos, int opno)
1352 rtx_test res (pos, rtx_test::SET_OP);
1353 res.u.opno = opno;
1354 return res;
1357 rtx_test
1358 rtx_test::accept (const acceptance_type &acceptance)
1360 rtx_test res (0, rtx_test::ACCEPT);
1361 res.u.acceptance = acceptance;
1362 return res;
1365 /* Return true if the test represents an unconditionally successful match. */
1367 bool
1368 rtx_test::terminal_p () const
1370 return kind == rtx_test::ACCEPT && u.acceptance.type != PEEPHOLE2;
1373 /* Return true if the test is a boolean that is always true. */
1375 bool
1376 rtx_test::single_outcome_p () const
1378 return terminal_p () || kind == rtx_test::SET_OP;
1381 bool
1382 operator == (const rtx_test &a, const rtx_test &b)
1384 if (a.pos != b.pos || a.kind != b.kind)
1385 return false;
1386 switch (a.kind)
1388 case rtx_test::CODE:
1389 case rtx_test::MODE:
1390 case rtx_test::REGNO_FIELD:
1391 case rtx_test::SUBREG_FIELD:
1392 case rtx_test::VECLEN:
1393 case rtx_test::HAVE_NUM_CLOBBERS:
1394 return true;
1396 case rtx_test::PEEP2_COUNT:
1397 case rtx_test::VECLEN_GE:
1398 return a.u.min_len == b.u.min_len;
1400 case rtx_test::INT_FIELD:
1401 case rtx_test::WIDE_INT_FIELD:
1402 case rtx_test::DUPLICATE:
1403 case rtx_test::SET_OP:
1404 return a.u.opno == b.u.opno;
1406 case rtx_test::SAVED_CONST_INT:
1407 return (a.u.integer.is_param == b.u.integer.is_param
1408 && a.u.integer.value == b.u.integer.value);
1410 case rtx_test::PREDICATE:
1411 return (a.u.predicate.data == b.u.predicate.data
1412 && a.u.predicate.mode_is_param == b.u.predicate.mode_is_param
1413 && a.u.predicate.mode == b.u.predicate.mode);
1415 case rtx_test::PATTERN:
1416 return (a.u.pattern->routine == b.u.pattern->routine
1417 && a.u.pattern->params == b.u.pattern->params);
1419 case rtx_test::C_TEST:
1420 return strcmp (a.u.string, b.u.string) == 0;
1422 case rtx_test::ACCEPT:
1423 return a.u.acceptance == b.u.acceptance;
1425 gcc_unreachable ();
1428 bool
1429 operator != (const rtx_test &a, const rtx_test &b)
1431 return !operator == (a, b);
1434 /* A simple set of transition labels. Most transitions have a singleton
1435 label, so try to make that case as efficient as possible. */
1436 class int_set : public auto_vec <uint64_t, 1>
1438 public:
1439 typedef uint64_t *iterator;
1441 int_set ();
1442 int_set (uint64_t);
1443 int_set (const int_set &);
1445 int_set &operator = (const int_set &);
1447 iterator begin ();
1448 iterator end ();
1451 int_set::int_set () : auto_vec<uint64_t, 1> () {}
1453 int_set::int_set (uint64_t label) :
1454 auto_vec<uint64_t, 1> ()
1456 safe_push (label);
1459 int_set::int_set (const int_set &other) :
1460 auto_vec<uint64_t, 1> ()
1462 safe_splice (other);
1465 int_set &
1466 int_set::operator = (const int_set &other)
1468 truncate (0);
1469 safe_splice (other);
1470 return *this;
1473 int_set::iterator
1474 int_set::begin ()
1476 return address ();
1479 int_set::iterator
1480 int_set::end ()
1482 return address () + length ();
1485 bool
1486 operator == (const int_set &a, const int_set &b)
1488 if (a.length () != b.length ())
1489 return false;
1490 for (unsigned int i = 0; i < a.length (); ++i)
1491 if (a[i] != b[i])
1492 return false;
1493 return true;
1496 bool
1497 operator != (const int_set &a, const int_set &b)
1499 return !operator == (a, b);
1502 class decision;
1504 /* Represents a transition between states, dependent on the result of
1505 a test T. */
1506 class transition
1508 public:
1509 transition (const int_set &, state *, bool);
1511 void set_parent (list_head <transition> *);
1513 /* Links to other transitions for T. Always null for boolean tests. */
1514 transition *prev, *next;
1516 /* The transition should be taken when T has one of these values.
1517 E.g. for rtx_test::CODE this is a set of codes, while for booleans like
1518 rtx_test::PREDICATE it is always a singleton "true". The labels are
1519 sorted in ascending order. */
1520 int_set labels;
1522 /* The source decision. */
1523 decision *from;
1525 /* The target state. */
1526 state *to;
1528 /* True if TO would function correctly even if TEST wasn't performed.
1529 E.g. it isn't necessary to check whether GET_MODE (x1) is SImode
1530 before calling register_operand (x1, SImode), since register_operand
1531 performs its own mode check. However, checking GET_MODE can be a cheap
1532 way of disambiguating SImode and DImode register operands. */
1533 bool optional;
1535 /* True if LABELS contains parameter numbers rather than constants.
1536 E.g. if this is true for a rtx_test::CODE, the label is the number
1537 of an rtx_code parameter rather than an rtx_code itself.
1538 LABELS is always a singleton when this variable is true. */
1539 bool is_param;
1542 /* Represents a test and the action that should be taken on the result.
1543 If a transition exists for the test outcome, the machine switches
1544 to the transition's target state. If no suitable transition exists,
1545 the machine either falls through to the next decision or, if there are no
1546 more decisions to try, fails the match. */
1547 class decision : public list_head <transition>
1549 public:
1550 decision (const rtx_test &);
1552 void set_parent (list_head <decision> *s);
1553 bool if_statement_p (uint64_t * = 0) const;
1555 /* The state to which this decision belongs. */
1556 state *s;
1558 /* Links to other decisions in the same state. */
1559 decision *prev, *next;
1561 /* The test to perform. */
1562 rtx_test test;
1565 /* Represents one machine state. For each state the machine tries a list
1566 of decisions, in order, and acts on the first match. It fails without
1567 further backtracking if no decisions match. */
1568 class state : public list_head <decision>
1570 public:
1571 void set_parent (list_head <state> *) {}
1574 transition::transition (const int_set &labels_in, state *to_in,
1575 bool optional_in)
1576 : prev (0), next (0), labels (labels_in), from (0), to (to_in),
1577 optional (optional_in), is_param (false) {}
1579 /* Set the source decision of the transition. */
1581 void
1582 transition::set_parent (list_head <transition> *from_in)
1584 from = static_cast <decision *> (from_in);
1587 decision::decision (const rtx_test &test_in)
1588 : prev (0), next (0), test (test_in) {}
1590 /* Set the state to which this decision belongs. */
1592 void
1593 decision::set_parent (list_head <decision> *s_in)
1595 s = static_cast <state *> (s_in);
1598 /* Return true if the decision has a single transition with a single label.
1599 If so, return the label in *LABEL if nonnull. */
1601 inline bool
1602 decision::if_statement_p (uint64_t *label) const
1604 if (singleton () && first->labels.length () == 1)
1606 if (label)
1607 *label = first->labels[0];
1608 return true;
1610 return false;
1613 /* Add to FROM a decision that performs TEST and has a single transition
1614 TRANS. */
1616 static void
1617 add_decision (state *from, const rtx_test &test, transition *trans)
1619 decision *d = new decision (test);
1620 from->push_back (d);
1621 d->push_back (trans);
1624 /* Add a transition from FROM to a new, empty state that is taken
1625 when TEST == LABELS. OPTIONAL says whether the new transition
1626 should be optional. Return the new state. */
1628 static state *
1629 add_decision (state *from, const rtx_test &test, int_set labels, bool optional)
1631 state *to = new state;
1632 add_decision (from, test, new transition (labels, to, optional));
1633 return to;
1636 /* Insert a decision before decisions R to make them dependent on
1637 TEST == LABELS. OPTIONAL says whether the new transition should be
1638 optional. */
1640 static decision *
1641 insert_decision_before (state::range r, const rtx_test &test,
1642 const int_set &labels, bool optional)
1644 decision *newd = new decision (test);
1645 state *news = new state;
1646 newd->push_back (new transition (labels, news, optional));
1647 r.start->s->replace (r, newd);
1648 news->push_back (r);
1649 return newd;
1652 /* Remove any optional transitions from S that turned out not to be useful. */
1654 static void
1655 collapse_optional_decisions (state *s)
1657 decision *d = s->first;
1658 while (d)
1660 decision *next = d->next;
1661 for (transition *trans = d->first; trans; trans = trans->next)
1662 collapse_optional_decisions (trans->to);
1663 /* A decision with a single optional transition doesn't help
1664 partition the potential matches and so is unlikely to be
1665 worthwhile. In particular, if the decision that performs the
1666 test is the last in the state, the best it could do is reject
1667 an invalid pattern slightly earlier. If instead the decision
1668 is not the last in the state, the condition it tests could hold
1669 even for the later decisions in the state. The best it can do
1670 is save work in some cases where only the later decisions can
1671 succeed.
1673 In both cases the optional transition would add extra work to
1674 successful matches when the tested condition holds. */
1675 if (transition *trans = d->singleton ())
1676 if (trans->optional)
1677 s->replace (d, trans->to->release ());
1678 d = next;
1682 /* Try to squash several separate tests into simpler ones. */
1684 static void
1685 simplify_tests (state *s)
1687 for (decision *d = s->first; d; d = d->next)
1689 uint64_t label;
1690 /* Convert checks for GET_CODE (x) == CONST_INT and XWINT (x, 0) == N
1691 into checks for const_int_rtx[N'], if N is suitably small. */
1692 if (d->test.kind == rtx_test::CODE
1693 && d->if_statement_p (&label)
1694 && label == CONST_INT)
1695 if (decision *second = d->first->to->singleton ())
1696 if (d->test.pos == second->test.pos
1697 && second->test.kind == rtx_test::WIDE_INT_FIELD
1698 && second->test.u.opno == 0
1699 && second->if_statement_p (&label)
1700 && IN_RANGE (int64_t (label),
1701 -MAX_SAVED_CONST_INT, MAX_SAVED_CONST_INT))
1703 d->test.kind = rtx_test::SAVED_CONST_INT;
1704 d->test.u.integer.is_param = false;
1705 d->test.u.integer.value = label;
1706 d->replace (d->first, second->release ());
1707 d->first->labels[0] = true;
1709 /* If we have a CODE test followed by a PREDICATE test, rely on
1710 the predicate to test the code.
1712 This case exists for match_operators. We initially treat the
1713 CODE test for a match_operator as non-optional so that we can
1714 safely move down to its operands. It may turn out that all
1715 paths that reach that code test require the same predicate
1716 to be true. cse_tests will then put the predicate test in
1717 series with the code test. */
1718 if (d->test.kind == rtx_test::CODE)
1719 if (transition *trans = d->singleton ())
1721 state *s = trans->to;
1722 while (decision *d2 = s->singleton ())
1724 if (d->test.pos != d2->test.pos)
1725 break;
1726 transition *trans2 = d2->singleton ();
1727 if (!trans2)
1728 break;
1729 if (d2->test.kind == rtx_test::PREDICATE)
1731 d->test = d2->test;
1732 trans->labels = int_set (true);
1733 s->replace (d2, trans2->to->release ());
1734 break;
1736 s = trans2->to;
1739 for (transition *trans = d->first; trans; trans = trans->next)
1740 simplify_tests (trans->to);
1744 /* Return true if all successful returns passing through D require the
1745 condition tested by COMMON to be true.
1747 When returning true, add all transitions like COMMON in D to WHERE.
1748 WHERE may contain a partial result on failure. */
1750 static bool
1751 common_test_p (decision *d, transition *common, vec <transition *> *where)
1753 if (d->test.kind == rtx_test::ACCEPT)
1754 /* We found a successful return that didn't require COMMON. */
1755 return false;
1756 if (d->test == common->from->test)
1758 transition *trans = d->singleton ();
1759 if (!trans
1760 || trans->optional != common->optional
1761 || trans->labels != common->labels)
1762 return false;
1763 where->safe_push (trans);
1764 return true;
1766 for (transition *trans = d->first; trans; trans = trans->next)
1767 for (decision *subd = trans->to->first; subd; subd = subd->next)
1768 if (!common_test_p (subd, common, where))
1769 return false;
1770 return true;
1773 /* Indicates that we have tested GET_CODE (X) for a particular rtx X. */
1774 const unsigned char TESTED_CODE = 1;
1776 /* Indicates that we have tested XVECLEN (X, 0) for a particular rtx X. */
1777 const unsigned char TESTED_VECLEN = 2;
1779 /* Represents a set of conditions that are known to hold. */
1780 class known_conditions
1782 public:
1783 /* A mask of TESTED_ values for each position, indexed by the position's
1784 id field. */
1785 auto_vec <unsigned char> position_tests;
1787 /* Index N says whether operands[N] has been set. */
1788 auto_vec <bool> set_operands;
1790 /* A guranteed lower bound on the value of peep2_current_count. */
1791 int peep2_count;
1794 /* Return true if TEST can safely be performed at D, where
1795 the conditions in KC hold. TEST is known to occur along the
1796 first path from D (i.e. always following the first transition
1797 of the first decision). Any intervening tests can be used as
1798 negative proof that hoisting isn't safe, but only KC can be used
1799 as positive proof. */
1801 static bool
1802 safe_to_hoist_p (decision *d, const rtx_test &test, known_conditions *kc)
1804 switch (test.kind)
1806 case rtx_test::C_TEST:
1807 /* In general, C tests require everything else to have been
1808 verified and all operands to have been set up. */
1809 return false;
1811 case rtx_test::ACCEPT:
1812 /* Don't accept something before all conditions have been tested. */
1813 return false;
1815 case rtx_test::PREDICATE:
1816 /* Don't move a predicate over a test for VECLEN_GE, since the
1817 predicate used in a match_parallel can legitimately expect the
1818 length to be checked first. */
1819 for (decision *subd = d;
1820 subd->test != test;
1821 subd = subd->first->to->first)
1822 if (subd->test.pos == test.pos
1823 && subd->test.kind == rtx_test::VECLEN_GE)
1824 return false;
1825 goto any_rtx;
1827 case rtx_test::DUPLICATE:
1828 /* Don't test for a match_dup until the associated operand has
1829 been set. */
1830 if (!kc->set_operands[test.u.opno])
1831 return false;
1832 goto any_rtx;
1834 case rtx_test::CODE:
1835 case rtx_test::MODE:
1836 case rtx_test::SAVED_CONST_INT:
1837 case rtx_test::SET_OP:
1838 any_rtx:
1839 /* Check whether it is safe to access the rtx under test. */
1840 switch (test.pos->type)
1842 case POS_PEEP2_INSN:
1843 return test.pos->arg < kc->peep2_count;
1845 case POS_XEXP:
1846 return kc->position_tests[test.pos->base->id] & TESTED_CODE;
1848 case POS_XVECEXP0:
1849 return kc->position_tests[test.pos->base->id] & TESTED_VECLEN;
1851 gcc_unreachable ();
1853 case rtx_test::REGNO_FIELD:
1854 case rtx_test::SUBREG_FIELD:
1855 case rtx_test::INT_FIELD:
1856 case rtx_test::WIDE_INT_FIELD:
1857 case rtx_test::VECLEN:
1858 case rtx_test::VECLEN_GE:
1859 /* These tests access a specific part of an rtx, so are only safe
1860 once we know what the rtx is. */
1861 return kc->position_tests[test.pos->id] & TESTED_CODE;
1863 case rtx_test::PEEP2_COUNT:
1864 case rtx_test::HAVE_NUM_CLOBBERS:
1865 /* These tests can be performed anywhere. */
1866 return true;
1868 case rtx_test::PATTERN:
1869 gcc_unreachable ();
1871 gcc_unreachable ();
1874 /* Look for a transition that is taken by all successful returns from a range
1875 of decisions starting at OUTER and that would be better performed by
1876 OUTER's state instead. On success, store all instances of that transition
1877 in WHERE and return the last decision in the range. The range could
1878 just be OUTER, or it could include later decisions as well.
1880 WITH_POSITION_P is true if only tests with position POS should be tried,
1881 false if any test should be tried. WORTHWHILE_SINGLE_P is true if the
1882 result is useful even when the range contains just a single decision
1883 with a single transition. KC are the conditions that are known to
1884 hold at OUTER. */
1886 static decision *
1887 find_common_test (decision *outer, bool with_position_p,
1888 position *pos, bool worthwhile_single_p,
1889 known_conditions *kc, vec <transition *> *where)
1891 /* After this, WORTHWHILE_SINGLE_P indicates whether a range that contains
1892 just a single decision is useful, regardless of the number of
1893 transitions it has. */
1894 if (!outer->singleton ())
1895 worthwhile_single_p = true;
1896 /* Quick exit if we don't have enough decisions to form a worthwhile
1897 range. */
1898 if (!worthwhile_single_p && !outer->next)
1899 return 0;
1900 /* Follow the first chain down, as one example of a path that needs
1901 to contain the common test. */
1902 for (decision *d = outer; d; d = d->first->to->first)
1904 transition *trans = d->singleton ();
1905 if (trans
1906 && (!with_position_p || d->test.pos == pos)
1907 && safe_to_hoist_p (outer, d->test, kc))
1909 if (common_test_p (outer, trans, where))
1911 if (!outer->next)
1912 /* We checked above whether the move is worthwhile. */
1913 return outer;
1914 /* See how many decisions in OUTER's chain could reuse
1915 the same test. */
1916 decision *outer_end = outer;
1919 unsigned int length = where->length ();
1920 if (!common_test_p (outer_end->next, trans, where))
1922 where->truncate (length);
1923 break;
1925 outer_end = outer_end->next;
1927 while (outer_end->next);
1928 /* It is worth moving TRANS if it can be shared by more than
1929 one decision. */
1930 if (outer_end != outer || worthwhile_single_p)
1931 return outer_end;
1933 where->truncate (0);
1936 return 0;
1939 /* Try to promote common subtests in S to a single, shared decision.
1940 Also try to bunch tests for the same position together. POS is the
1941 position of the rtx tested before reaching S. KC are the conditions
1942 that are known to hold on entry to S. */
1944 static void
1945 cse_tests (position *pos, state *s, known_conditions *kc)
1947 for (decision *d = s->first; d; d = d->next)
1949 auto_vec <transition *, 16> where;
1950 if (d->test.pos)
1952 /* Try to find conditions that don't depend on a particular rtx,
1953 such as pnum_clobbers != NULL or peep2_current_count >= X.
1954 It's usually better to check these conditions as soon as
1955 possible, so the change is worthwhile even if there is
1956 only one copy of the test. */
1957 decision *endd = find_common_test (d, true, 0, true, kc, &where);
1958 if (!endd && d->test.pos != pos)
1959 /* Try to find other conditions related to position POS
1960 before moving to the new position. Again, this is
1961 worthwhile even if there is only one copy of the test,
1962 since it means that fewer position variables are live
1963 at a given time. */
1964 endd = find_common_test (d, true, pos, true, kc, &where);
1965 if (!endd)
1966 /* Try to find any condition that is used more than once. */
1967 endd = find_common_test (d, false, 0, false, kc, &where);
1968 if (endd)
1970 transition *common = where[0];
1971 /* Replace [D, ENDD] with a test like COMMON. We'll recurse
1972 on the common test and see the original D again next time. */
1973 d = insert_decision_before (state::range (d, endd),
1974 common->from->test,
1975 common->labels,
1976 common->optional);
1977 /* Remove the old tests. */
1978 while (!where.is_empty ())
1980 transition *trans = where.pop ();
1981 trans->from->s->replace (trans->from, trans->to->release ());
1986 /* Make sure that safe_to_hoist_p isn't being overly conservative.
1987 It should realize that D's test is safe in the current
1988 environment. */
1989 gcc_assert (d->test.kind == rtx_test::C_TEST
1990 || d->test.kind == rtx_test::ACCEPT
1991 || safe_to_hoist_p (d, d->test, kc));
1993 /* D won't be changed any further by the current optimization.
1994 Recurse with the state temporarily updated to include D. */
1995 int prev = 0;
1996 switch (d->test.kind)
1998 case rtx_test::CODE:
1999 prev = kc->position_tests[d->test.pos->id];
2000 kc->position_tests[d->test.pos->id] |= TESTED_CODE;
2001 break;
2003 case rtx_test::VECLEN:
2004 case rtx_test::VECLEN_GE:
2005 prev = kc->position_tests[d->test.pos->id];
2006 kc->position_tests[d->test.pos->id] |= TESTED_VECLEN;
2007 break;
2009 case rtx_test::SET_OP:
2010 prev = kc->set_operands[d->test.u.opno];
2011 gcc_assert (!prev);
2012 kc->set_operands[d->test.u.opno] = true;
2013 break;
2015 case rtx_test::PEEP2_COUNT:
2016 prev = kc->peep2_count;
2017 kc->peep2_count = MAX (prev, d->test.u.min_len);
2018 break;
2020 default:
2021 break;
2023 for (transition *trans = d->first; trans; trans = trans->next)
2024 cse_tests (d->test.pos ? d->test.pos : pos, trans->to, kc);
2025 switch (d->test.kind)
2027 case rtx_test::CODE:
2028 case rtx_test::VECLEN:
2029 case rtx_test::VECLEN_GE:
2030 kc->position_tests[d->test.pos->id] = prev;
2031 break;
2033 case rtx_test::SET_OP:
2034 kc->set_operands[d->test.u.opno] = prev;
2035 break;
2037 case rtx_test::PEEP2_COUNT:
2038 kc->peep2_count = prev;
2039 break;
2041 default:
2042 break;
2047 /* Return the type of value that can be used to parameterize test KIND,
2048 or parameter::UNSET if none. */
2050 parameter::type_enum
2051 transition_parameter_type (rtx_test::kind_enum kind)
2053 switch (kind)
2055 case rtx_test::CODE:
2056 return parameter::CODE;
2058 case rtx_test::MODE:
2059 return parameter::MODE;
2061 case rtx_test::REGNO_FIELD:
2062 case rtx_test::SUBREG_FIELD:
2063 return parameter::UINT;
2065 case rtx_test::INT_FIELD:
2066 case rtx_test::VECLEN:
2067 case rtx_test::PATTERN:
2068 return parameter::INT;
2070 case rtx_test::WIDE_INT_FIELD:
2071 return parameter::WIDE_INT;
2073 case rtx_test::PEEP2_COUNT:
2074 case rtx_test::VECLEN_GE:
2075 case rtx_test::SAVED_CONST_INT:
2076 case rtx_test::PREDICATE:
2077 case rtx_test::DUPLICATE:
2078 case rtx_test::HAVE_NUM_CLOBBERS:
2079 case rtx_test::C_TEST:
2080 case rtx_test::SET_OP:
2081 case rtx_test::ACCEPT:
2082 return parameter::UNSET;
2084 gcc_unreachable ();
2087 /* Initialize the pos_operand fields of each state reachable from S.
2088 If OPERAND_POS[ID] >= 0, the position with id ID is stored in
2089 operands[OPERAND_POS[ID]] on entry to S. */
2091 static void
2092 find_operand_positions (state *s, vec <int> &operand_pos)
2094 for (decision *d = s->first; d; d = d->next)
2096 int this_operand = (d->test.pos ? operand_pos[d->test.pos->id] : -1);
2097 if (this_operand >= 0)
2098 d->test.pos_operand = this_operand;
2099 if (d->test.kind == rtx_test::SET_OP)
2100 operand_pos[d->test.pos->id] = d->test.u.opno;
2101 for (transition *trans = d->first; trans; trans = trans->next)
2102 find_operand_positions (trans->to, operand_pos);
2103 if (d->test.kind == rtx_test::SET_OP)
2104 operand_pos[d->test.pos->id] = this_operand;
2108 /* Statistics about a matching routine. */
2109 class stats
2111 public:
2112 stats ();
2114 /* The total number of decisions in the routine, excluding trivial
2115 ones that never fail. */
2116 unsigned int num_decisions;
2118 /* The number of non-trivial decisions on the longest path through
2119 the routine, and the return value that contributes most to that
2120 long path. */
2121 unsigned int longest_path;
2122 int longest_path_code;
2124 /* The maximum number of times that a single call to the routine
2125 can backtrack, and the value returned at the end of that path.
2126 "Backtracking" here means failing one decision in state and
2127 going onto to the next. */
2128 unsigned int longest_backtrack;
2129 int longest_backtrack_code;
2132 stats::stats ()
2133 : num_decisions (0), longest_path (0), longest_path_code (-1),
2134 longest_backtrack (0), longest_backtrack_code (-1) {}
2136 /* Return statistics about S. */
2138 static stats
2139 get_stats (state *s)
2141 stats for_s;
2142 unsigned int longest_path = 0;
2143 for (decision *d = s->first; d; d = d->next)
2145 /* Work out the statistics for D. */
2146 stats for_d;
2147 for (transition *trans = d->first; trans; trans = trans->next)
2149 stats for_trans = get_stats (trans->to);
2150 for_d.num_decisions += for_trans.num_decisions;
2151 /* Each transition is mutually-exclusive, so just pick the
2152 longest of the individual paths. */
2153 if (for_d.longest_path <= for_trans.longest_path)
2155 for_d.longest_path = for_trans.longest_path;
2156 for_d.longest_path_code = for_trans.longest_path_code;
2158 /* Likewise for backtracking. */
2159 if (for_d.longest_backtrack <= for_trans.longest_backtrack)
2161 for_d.longest_backtrack = for_trans.longest_backtrack;
2162 for_d.longest_backtrack_code = for_trans.longest_backtrack_code;
2166 /* Account for D's test in its statistics. */
2167 if (!d->test.single_outcome_p ())
2169 for_d.num_decisions += 1;
2170 for_d.longest_path += 1;
2172 if (d->test.kind == rtx_test::ACCEPT)
2174 for_d.longest_path_code = d->test.u.acceptance.u.full.code;
2175 for_d.longest_backtrack_code = d->test.u.acceptance.u.full.code;
2178 /* Keep a running count of the number of backtracks. */
2179 if (d->prev)
2180 for_s.longest_backtrack += 1;
2182 /* Accumulate D's statistics into S's. */
2183 for_s.num_decisions += for_d.num_decisions;
2184 for_s.longest_path += for_d.longest_path;
2185 for_s.longest_backtrack += for_d.longest_backtrack;
2187 /* Use the code from the decision with the longest individual path,
2188 since that's more likely to be useful if trying to make the
2189 path shorter. In the event of a tie, pick the later decision,
2190 since that's closer to the end of the path. */
2191 if (longest_path <= for_d.longest_path)
2193 longest_path = for_d.longest_path;
2194 for_s.longest_path_code = for_d.longest_path_code;
2197 /* Later decisions in a state are necessarily in a longer backtrack
2198 than earlier decisions. */
2199 for_s.longest_backtrack_code = for_d.longest_backtrack_code;
2201 return for_s;
2204 /* Optimize ROOT. Use TYPE to describe ROOT in status messages. */
2206 static void
2207 optimize_subroutine_group (const char *type, state *root)
2209 /* Remove optional transitions that turned out not to be worthwhile. */
2210 if (collapse_optional_decisions_p)
2211 collapse_optional_decisions (root);
2213 /* Try to remove duplicated tests and to rearrange tests into a more
2214 logical order. */
2215 if (cse_tests_p)
2217 known_conditions kc;
2218 kc.position_tests.safe_grow_cleared (num_positions);
2219 kc.set_operands.safe_grow_cleared (num_operands);
2220 kc.peep2_count = 1;
2221 cse_tests (&root_pos, root, &kc);
2224 /* Try to simplify two or more tests into one. */
2225 if (simplify_tests_p)
2226 simplify_tests (root);
2228 /* Try to use operands[] instead of xN variables. */
2229 if (use_operand_variables_p)
2231 auto_vec <int> operand_pos (num_positions);
2232 for (unsigned int i = 0; i < num_positions; ++i)
2233 operand_pos.quick_push (-1);
2234 find_operand_positions (root, operand_pos);
2237 /* Print a summary of the new state. */
2238 stats st = get_stats (root);
2239 fprintf (stderr, "Statistics for %s:\n", type);
2240 fprintf (stderr, " Number of decisions: %6d\n", st.num_decisions);
2241 fprintf (stderr, " longest path: %6d (code: %6d)\n",
2242 st.longest_path, st.longest_path_code);
2243 fprintf (stderr, " longest backtrack: %6d (code: %6d)\n",
2244 st.longest_backtrack, st.longest_backtrack_code);
2247 class merge_pattern_info;
2249 /* Represents a transition from one pattern to another. */
2250 class merge_pattern_transition
2252 public:
2253 merge_pattern_transition (merge_pattern_info *);
2255 /* The target pattern. */
2256 merge_pattern_info *to;
2258 /* The parameters that the source pattern passes to the target pattern.
2259 "parameter (TYPE, true, I)" represents parameter I of the source
2260 pattern. */
2261 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
2264 merge_pattern_transition::merge_pattern_transition (merge_pattern_info *to_in)
2265 : to (to_in)
2269 /* Represents a pattern that can might match several states. The pattern
2270 may replace parts of the test with a parameter value. It may also
2271 replace transition labels with parameters. */
2272 class merge_pattern_info
2274 public:
2275 merge_pattern_info (unsigned int);
2277 /* If PARAM_TEST_P, the state's singleton test should be generalized
2278 to use the runtime value of PARAMS[PARAM_TEST]. */
2279 unsigned int param_test : 8;
2281 /* If PARAM_TRANSITION_P, the state's single transition label should
2282 be replaced by the runtime value of PARAMS[PARAM_TRANSITION]. */
2283 unsigned int param_transition : 8;
2285 /* True if we have decided to generalize the root decision's test,
2286 as per PARAM_TEST. */
2287 unsigned int param_test_p : 1;
2289 /* Likewise for the root decision's transition, as per PARAM_TRANSITION. */
2290 unsigned int param_transition_p : 1;
2292 /* True if the contents of the structure are completely filled in. */
2293 unsigned int complete_p : 1;
2295 /* The number of pseudo-statements in the pattern. Used to decide
2296 whether it's big enough to break out into a subroutine. */
2297 unsigned int num_statements;
2299 /* The number of states that use this pattern. */
2300 unsigned int num_users;
2302 /* The number of distinct success values that the pattern returns. */
2303 unsigned int num_results;
2305 /* This array has one element for each runtime parameter to the pattern.
2306 PARAMS[I] gives the default value of parameter I, which is always
2307 constant.
2309 These default parameters are used in cases where we match the
2310 pattern against some state S1, then add more parameters while
2311 matching against some state S2. S1 is then left passing fewer
2312 parameters than S2. The array gives us enough informatino to
2313 construct a full parameter list for S1 (see update_parameters).
2315 If we decide to create a subroutine for this pattern,
2316 PARAMS[I].type determines the C type of parameter I. */
2317 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
2319 /* All states that match this pattern must have the same number of
2320 transitions. TRANSITIONS[I] describes the subpattern for transition
2321 number I; it is null if transition I represents a successful return
2322 from the pattern. */
2323 auto_vec <merge_pattern_transition *, 1> transitions;
2325 /* The routine associated with the pattern, or null if we haven't generated
2326 one yet. */
2327 pattern_routine *routine;
2330 merge_pattern_info::merge_pattern_info (unsigned int num_transitions)
2331 : param_test (0),
2332 param_transition (0),
2333 param_test_p (false),
2334 param_transition_p (false),
2335 complete_p (false),
2336 num_statements (0),
2337 num_users (0),
2338 num_results (0),
2339 routine (0)
2341 transitions.safe_grow_cleared (num_transitions);
2344 /* Describes one way of matching a particular state to a particular
2345 pattern. */
2346 class merge_state_result
2348 public:
2349 merge_state_result (merge_pattern_info *, position *, merge_state_result *);
2351 /* A pattern that matches the state. */
2352 merge_pattern_info *pattern;
2354 /* If we decide to use this match and create a subroutine for PATTERN,
2355 the state should pass the rtx at position ROOT to the pattern's
2356 rtx parameter. A null root means that the pattern doesn't need
2357 an rtx parameter; all the rtxes it matches come from elsewhere. */
2358 position *root;
2360 /* The parameters that should be passed to PATTERN for this state.
2361 If the array is shorter than PATTERN->params, the missing entries
2362 should be taken from the corresponding element of PATTERN->params. */
2363 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
2365 /* An earlier match for the same state, or null if none. Patterns
2366 matched by earlier entries are smaller than PATTERN. */
2367 merge_state_result *prev;
2370 merge_state_result::merge_state_result (merge_pattern_info *pattern_in,
2371 position *root_in,
2372 merge_state_result *prev_in)
2373 : pattern (pattern_in), root (root_in), prev (prev_in)
2376 /* Information about a state, used while trying to match it against
2377 a pattern. */
2378 class merge_state_info
2380 public:
2381 merge_state_info (state *);
2383 /* The state itself. */
2384 state *s;
2386 /* Index I gives information about the target of transition I. */
2387 merge_state_info *to_states;
2389 /* The number of transitions in S. */
2390 unsigned int num_transitions;
2392 /* True if the state has been deleted in favor of a call to a
2393 pattern routine. */
2394 bool merged_p;
2396 /* The previous state that might be a merge candidate for S, or null
2397 if no previous states could be merged with S. */
2398 merge_state_info *prev_same_test;
2400 /* A list of pattern matches for this state. */
2401 merge_state_result *res;
2404 merge_state_info::merge_state_info (state *s_in)
2405 : s (s_in),
2406 to_states (0),
2407 num_transitions (0),
2408 merged_p (false),
2409 prev_same_test (0),
2410 res (0) {}
2412 /* True if PAT would be useful as a subroutine. */
2414 static bool
2415 useful_pattern_p (merge_pattern_info *pat)
2417 return pat->num_statements >= MIN_COMBINE_COST;
2420 /* PAT2 is a subpattern of PAT1. Return true if PAT2 should be inlined
2421 into PAT1's C routine. */
2423 static bool
2424 same_pattern_p (merge_pattern_info *pat1, merge_pattern_info *pat2)
2426 return pat1->num_users == pat2->num_users || !useful_pattern_p (pat2);
2429 /* PAT was previously matched against SINFO based on tentative matches
2430 for the target states of SINFO's state. Return true if the match
2431 still holds; that is, if the target states of SINFO's state still
2432 match the corresponding transitions of PAT. */
2434 static bool
2435 valid_result_p (merge_pattern_info *pat, merge_state_info *sinfo)
2437 for (unsigned int j = 0; j < sinfo->num_transitions; ++j)
2438 if (merge_pattern_transition *ptrans = pat->transitions[j])
2440 merge_state_result *to_res = sinfo->to_states[j].res;
2441 if (!to_res || to_res->pattern != ptrans->to)
2442 return false;
2444 return true;
2447 /* Remove any matches that are no longer valid from the head of SINFO's
2448 list of matches. */
2450 static void
2451 prune_invalid_results (merge_state_info *sinfo)
2453 while (sinfo->res && !valid_result_p (sinfo->res->pattern, sinfo))
2455 sinfo->res = sinfo->res->prev;
2456 gcc_assert (sinfo->res);
2460 /* Return true if PAT represents the biggest posssible match for SINFO;
2461 that is, if the next action of SINFO's state on return from PAT will
2462 be something that cannot be merged with any other state. */
2464 static bool
2465 complete_result_p (merge_pattern_info *pat, merge_state_info *sinfo)
2467 for (unsigned int j = 0; j < sinfo->num_transitions; ++j)
2468 if (sinfo->to_states[j].res && !pat->transitions[j])
2469 return false;
2470 return true;
2473 /* Update TO for any parameters that have been added to FROM since TO
2474 was last set. The extra parameters in FROM will be constants or
2475 instructions to duplicate earlier parameters. */
2477 static void
2478 update_parameters (vec <parameter> &to, const vec <parameter> &from)
2480 for (unsigned int i = to.length (); i < from.length (); ++i)
2481 to.quick_push (from[i]);
2484 /* Return true if A and B can be tested by a single test. If the test
2485 can be parameterised, store the parameter value for A in *PARAMA and
2486 the parameter value for B in *PARAMB, otherwise leave PARAMA and
2487 PARAMB alone. */
2489 static bool
2490 compatible_tests_p (const rtx_test &a, const rtx_test &b,
2491 parameter *parama, parameter *paramb)
2493 if (a.kind != b.kind)
2494 return false;
2495 switch (a.kind)
2497 case rtx_test::PREDICATE:
2498 if (a.u.predicate.data != b.u.predicate.data)
2499 return false;
2500 *parama = parameter (parameter::MODE, false, a.u.predicate.mode);
2501 *paramb = parameter (parameter::MODE, false, b.u.predicate.mode);
2502 return true;
2504 case rtx_test::SAVED_CONST_INT:
2505 *parama = parameter (parameter::INT, false, a.u.integer.value);
2506 *paramb = parameter (parameter::INT, false, b.u.integer.value);
2507 return true;
2509 default:
2510 return a == b;
2514 /* PARAMS is an array of the parameters that a state is going to pass
2515 to a pattern routine. It is still incomplete; index I has a kind of
2516 parameter::UNSET if we don't yet know what the state will pass
2517 as parameter I. Try to make parameter ID equal VALUE, returning
2518 true on success. */
2520 static bool
2521 set_parameter (vec <parameter> &params, unsigned int id,
2522 const parameter &value)
2524 if (params[id].type == parameter::UNSET)
2526 if (force_unique_params_p)
2527 for (unsigned int i = 0; i < params.length (); ++i)
2528 if (params[i] == value)
2529 return false;
2530 params[id] = value;
2531 return true;
2533 return params[id] == value;
2536 /* PARAMS2 is the "params" array for a pattern and PARAMS1 is the
2537 set of parameters that a particular state is going to pass to
2538 that pattern.
2540 Try to extend PARAMS1 and PARAMS2 so that there is a parameter
2541 that is equal to PARAM1 for the state and has a default value of
2542 PARAM2. Parameters beginning at START were added as part of the
2543 same match and so may be reused. */
2545 static bool
2546 add_parameter (vec <parameter> &params1, vec <parameter> &params2,
2547 const parameter &param1, const parameter &param2,
2548 unsigned int start, unsigned int *res)
2550 gcc_assert (params1.length () == params2.length ());
2551 gcc_assert (!param1.is_param && !param2.is_param);
2553 for (unsigned int i = start; i < params2.length (); ++i)
2554 if (params1[i] == param1 && params2[i] == param2)
2556 *res = i;
2557 return true;
2560 if (force_unique_params_p)
2561 for (unsigned int i = 0; i < params2.length (); ++i)
2562 if (params1[i] == param1 || params2[i] == param2)
2563 return false;
2565 if (params2.length () >= MAX_PATTERN_PARAMS)
2566 return false;
2568 *res = params2.length ();
2569 params1.quick_push (param1);
2570 params2.quick_push (param2);
2571 return true;
2574 /* If *ROOTA is nonnull, return true if the same sequence of steps are
2575 required to reach A from *ROOTA as to reach B from ROOTB. If *ROOTA
2576 is null, update it if necessary in order to make the condition hold. */
2578 static bool
2579 merge_relative_positions (position **roota, position *a,
2580 position *rootb, position *b)
2582 if (!relative_patterns_p)
2584 if (a != b)
2585 return false;
2586 if (!*roota)
2588 *roota = rootb;
2589 return true;
2591 return *roota == rootb;
2593 /* If B does not belong to the same instruction as ROOTB, we don't
2594 start with ROOTB but instead start with a call to peep2_next_insn.
2595 In that case the sequences for B and A are identical iff B and A
2596 are themselves identical. */
2597 if (rootb->insn_id != b->insn_id)
2598 return a == b;
2599 while (rootb != b)
2601 if (!a || b->type != a->type || b->arg != a->arg)
2602 return false;
2603 b = b->base;
2604 a = a->base;
2606 if (!*roota)
2607 *roota = a;
2608 return *roota == a;
2611 /* A hasher of states that treats two states as "equal" if they might be
2612 merged (but trying to be more discriminating than "return true"). */
2613 struct test_pattern_hasher : nofree_ptr_hash <merge_state_info>
2615 static inline hashval_t hash (const value_type &);
2616 static inline bool equal (const value_type &, const compare_type &);
2619 hashval_t
2620 test_pattern_hasher::hash (merge_state_info *const &sinfo)
2622 inchash::hash h;
2623 decision *d = sinfo->s->singleton ();
2624 h.add_int (d->test.pos_operand + 1);
2625 if (!relative_patterns_p)
2626 h.add_int (d->test.pos ? d->test.pos->id + 1 : 0);
2627 h.add_int (d->test.kind);
2628 h.add_int (sinfo->num_transitions);
2629 return h.end ();
2632 bool
2633 test_pattern_hasher::equal (merge_state_info *const &sinfo1,
2634 merge_state_info *const &sinfo2)
2636 decision *d1 = sinfo1->s->singleton ();
2637 decision *d2 = sinfo2->s->singleton ();
2638 gcc_assert (d1 && d2);
2640 parameter new_param1, new_param2;
2641 return (d1->test.pos_operand == d2->test.pos_operand
2642 && (relative_patterns_p || d1->test.pos == d2->test.pos)
2643 && compatible_tests_p (d1->test, d2->test, &new_param1, &new_param2)
2644 && sinfo1->num_transitions == sinfo2->num_transitions);
2647 /* Try to make the state described by SINFO1 use the same pattern as the
2648 state described by SINFO2. Return true on success.
2650 SINFO1 and SINFO2 are known to have the same hash value. */
2652 static bool
2653 merge_patterns (merge_state_info *sinfo1, merge_state_info *sinfo2)
2655 merge_state_result *res2 = sinfo2->res;
2656 merge_pattern_info *pat = res2->pattern;
2658 /* Write to temporary arrays while matching, in case we have to abort
2659 half way through. */
2660 auto_vec <parameter, MAX_PATTERN_PARAMS> params1;
2661 auto_vec <parameter, MAX_PATTERN_PARAMS> params2;
2662 params1.quick_grow_cleared (pat->params.length ());
2663 params2.splice (pat->params);
2664 unsigned int start_param = params2.length ();
2666 /* An array for recording changes to PAT->transitions[?].params.
2667 All changes involve replacing a constant parameter with some
2668 PAT->params[N], where N is the second element of the pending_param. */
2669 typedef std::pair <parameter *, unsigned int> pending_param;
2670 auto_vec <pending_param, 32> pending_params;
2672 decision *d1 = sinfo1->s->singleton ();
2673 decision *d2 = sinfo2->s->singleton ();
2674 gcc_assert (d1 && d2);
2676 /* If D2 tests a position, SINFO1's root relative to D1 is the same
2677 as SINFO2's root relative to D2. */
2678 position *root1 = 0;
2679 position *root2 = res2->root;
2680 if (d2->test.pos_operand < 0
2681 && d1->test.pos
2682 && !merge_relative_positions (&root1, d1->test.pos,
2683 root2, d2->test.pos))
2684 return false;
2686 /* Check whether the patterns have the same shape. */
2687 unsigned int num_transitions = sinfo1->num_transitions;
2688 gcc_assert (num_transitions == sinfo2->num_transitions);
2689 for (unsigned int i = 0; i < num_transitions; ++i)
2690 if (merge_pattern_transition *ptrans = pat->transitions[i])
2692 merge_state_result *to1_res = sinfo1->to_states[i].res;
2693 merge_state_result *to2_res = sinfo2->to_states[i].res;
2694 merge_pattern_info *to_pat = ptrans->to;
2695 gcc_assert (to2_res && to2_res->pattern == to_pat);
2696 if (!to1_res || to1_res->pattern != to_pat)
2697 return false;
2698 if (to2_res->root
2699 && !merge_relative_positions (&root1, to1_res->root,
2700 root2, to2_res->root))
2701 return false;
2702 /* Match the parameters that TO1_RES passes to TO_PAT with the
2703 parameters that PAT passes to TO_PAT. */
2704 update_parameters (to1_res->params, to_pat->params);
2705 for (unsigned int j = 0; j < to1_res->params.length (); ++j)
2707 const parameter &param1 = to1_res->params[j];
2708 const parameter &param2 = ptrans->params[j];
2709 gcc_assert (!param1.is_param);
2710 if (param2.is_param)
2712 if (!set_parameter (params1, param2.value, param1))
2713 return false;
2715 else if (param1 != param2)
2717 unsigned int id;
2718 if (!add_parameter (params1, params2,
2719 param1, param2, start_param, &id))
2720 return false;
2721 /* Record that PAT should now pass parameter ID to TO_PAT,
2722 instead of the current contents of *PARAM2. We only
2723 make the change if the rest of the match succeeds. */
2724 pending_params.safe_push
2725 (pending_param (&ptrans->params[j], id));
2730 unsigned int param_test = pat->param_test;
2731 unsigned int param_transition = pat->param_transition;
2732 bool param_test_p = pat->param_test_p;
2733 bool param_transition_p = pat->param_transition_p;
2735 /* If the tests don't match exactly, try to parameterize them. */
2736 parameter new_param1, new_param2;
2737 if (!compatible_tests_p (d1->test, d2->test, &new_param1, &new_param2))
2738 gcc_unreachable ();
2739 if (new_param1.type != parameter::UNSET)
2741 /* If the test has not already been parameterized, all existing
2742 matches use constant NEW_PARAM2. */
2743 if (param_test_p)
2745 if (!set_parameter (params1, param_test, new_param1))
2746 return false;
2748 else if (new_param1 != new_param2)
2750 if (!add_parameter (params1, params2, new_param1, new_param2,
2751 start_param, &param_test))
2752 return false;
2753 param_test_p = true;
2757 /* Match the transitions. */
2758 transition *trans1 = d1->first;
2759 transition *trans2 = d2->first;
2760 for (unsigned int i = 0; i < num_transitions; ++i)
2762 if (param_transition_p || trans1->labels != trans2->labels)
2764 /* We can only generalize a single transition with a single
2765 label. */
2766 if (num_transitions != 1
2767 || trans1->labels.length () != 1
2768 || trans2->labels.length () != 1)
2769 return false;
2771 /* Although we can match wide-int fields, in practice it leads
2772 to some odd results for const_vectors. We end up
2773 parameterizing the first N const_ints of the vector
2774 and then (once we reach the maximum number of parameters)
2775 we go on to match the other elements exactly. */
2776 if (d1->test.kind == rtx_test::WIDE_INT_FIELD)
2777 return false;
2779 /* See whether the label has a generalizable type. */
2780 parameter::type_enum param_type
2781 = transition_parameter_type (d1->test.kind);
2782 if (param_type == parameter::UNSET)
2783 return false;
2785 /* Match the labels using parameters. */
2786 new_param1 = parameter (param_type, false, trans1->labels[0]);
2787 if (param_transition_p)
2789 if (!set_parameter (params1, param_transition, new_param1))
2790 return false;
2792 else
2794 new_param2 = parameter (param_type, false, trans2->labels[0]);
2795 if (!add_parameter (params1, params2, new_param1, new_param2,
2796 start_param, &param_transition))
2797 return false;
2798 param_transition_p = true;
2801 trans1 = trans1->next;
2802 trans2 = trans2->next;
2805 /* Set any unset parameters to their default values. This occurs if some
2806 other state needed something to be parameterized in order to match SINFO2,
2807 but SINFO1 on its own does not. */
2808 for (unsigned int i = 0; i < params1.length (); ++i)
2809 if (params1[i].type == parameter::UNSET)
2810 params1[i] = params2[i];
2812 /* The match was successful. Commit all pending changes to PAT. */
2813 update_parameters (pat->params, params2);
2815 pending_param *pp;
2816 unsigned int i;
2817 FOR_EACH_VEC_ELT (pending_params, i, pp)
2818 *pp->first = parameter (pp->first->type, true, pp->second);
2820 pat->param_test = param_test;
2821 pat->param_transition = param_transition;
2822 pat->param_test_p = param_test_p;
2823 pat->param_transition_p = param_transition_p;
2825 /* Record the match of SINFO1. */
2826 merge_state_result *new_res1 = new merge_state_result (pat, root1,
2827 sinfo1->res);
2828 new_res1->params.splice (params1);
2829 sinfo1->res = new_res1;
2830 return true;
2833 /* The number of states that were removed by calling pattern routines. */
2834 static unsigned int pattern_use_states;
2836 /* The number of states used while defining pattern routines. */
2837 static unsigned int pattern_def_states;
2839 /* Information used while constructing a use or definition of a pattern
2840 routine. */
2841 struct create_pattern_info
2843 /* The routine itself. */
2844 pattern_routine *routine;
2846 /* The first unclaimed return value for this particular use or definition.
2847 We walk the substates of uses and definitions in the same order
2848 so each return value always refers to the same position within
2849 the pattern. */
2850 unsigned int next_result;
2853 static void populate_pattern_routine (create_pattern_info *,
2854 merge_state_info *, state *,
2855 const vec <parameter> &);
2857 /* SINFO matches a pattern for which we've decided to create a C routine.
2858 Return a decision that performs a call to the pattern routine,
2859 but leave the caller to add the transitions to it. Initialize CPI
2860 for this purpose. Also create a definition for the pattern routine,
2861 if it doesn't already have one.
2863 PARAMS are the parameters that SINFO passes to its pattern. */
2865 static decision *
2866 init_pattern_use (create_pattern_info *cpi, merge_state_info *sinfo,
2867 const vec <parameter> &params)
2869 state *s = sinfo->s;
2870 merge_state_result *res = sinfo->res;
2871 merge_pattern_info *pat = res->pattern;
2872 cpi->routine = pat->routine;
2873 if (!cpi->routine)
2875 /* We haven't defined the pattern routine yet, so create
2876 a definition now. */
2877 pattern_routine *routine = new pattern_routine;
2878 pat->routine = routine;
2879 cpi->routine = routine;
2880 routine->s = new state;
2881 routine->insn_p = false;
2882 routine->pnum_clobbers_p = false;
2884 /* Create an "idempotent" mapping of parameter I to parameter I.
2885 Also record the C type of each parameter to the routine. */
2886 auto_vec <parameter, MAX_PATTERN_PARAMS> def_params;
2887 for (unsigned int i = 0; i < pat->params.length (); ++i)
2889 def_params.quick_push (parameter (pat->params[i].type, true, i));
2890 routine->param_types.quick_push (pat->params[i].type);
2893 /* Any of the states that match the pattern could be used to
2894 create the routine definition. We might as well use SINFO
2895 since it's already to hand. This means that all positions
2896 in the definition will be relative to RES->root. */
2897 routine->pos = res->root;
2898 cpi->next_result = 0;
2899 populate_pattern_routine (cpi, sinfo, routine->s, def_params);
2900 gcc_assert (cpi->next_result == pat->num_results);
2902 /* Add the routine to the global list, after the subroutines
2903 that it calls. */
2904 routine->pattern_id = patterns.length ();
2905 patterns.safe_push (routine);
2908 /* Create a decision to call the routine, passing PARAMS to it. */
2909 pattern_use *use = new pattern_use;
2910 use->routine = pat->routine;
2911 use->params.splice (params);
2912 decision *d = new decision (rtx_test::pattern (res->root, use));
2914 /* If the original decision could use an element of operands[] instead
2915 of an rtx variable, try to transfer it to the new decision. */
2916 if (s->first->test.pos && res->root == s->first->test.pos)
2917 d->test.pos_operand = s->first->test.pos_operand;
2919 cpi->next_result = 0;
2920 return d;
2923 /* Make S return the next unclaimed pattern routine result for CPI. */
2925 static void
2926 add_pattern_acceptance (create_pattern_info *cpi, state *s)
2928 acceptance_type acceptance;
2929 acceptance.type = SUBPATTERN;
2930 acceptance.partial_p = false;
2931 acceptance.u.full.code = cpi->next_result;
2932 add_decision (s, rtx_test::accept (acceptance), true, false);
2933 cpi->next_result += 1;
2936 /* Initialize new empty state NEWS so that it implements SINFO's pattern
2937 (here referred to as "P"). P may be the top level of a pattern routine
2938 or a subpattern that should be inlined into its parent pattern's routine
2939 (as per same_pattern_p). The choice of SINFO for a top-level pattern is
2940 arbitrary; it could be any of the states that use P. The choice for
2941 subpatterns follows the choice for the parent pattern.
2943 PARAMS gives the value of each parameter to P in terms of the parameters
2944 to the top-level pattern. If P itself is the top level pattern, PARAMS[I]
2945 is always "parameter (TYPE, true, I)". */
2947 static void
2948 populate_pattern_routine (create_pattern_info *cpi, merge_state_info *sinfo,
2949 state *news, const vec <parameter> &params)
2951 pattern_def_states += 1;
2953 decision *d = sinfo->s->singleton ();
2954 merge_pattern_info *pat = sinfo->res->pattern;
2955 pattern_routine *routine = cpi->routine;
2957 /* Create a copy of D's test for the pattern routine and generalize it
2958 as appropriate. */
2959 decision *newd = new decision (d->test);
2960 gcc_assert (newd->test.pos_operand >= 0
2961 || !newd->test.pos
2962 || common_position (newd->test.pos,
2963 routine->pos) == routine->pos);
2964 if (pat->param_test_p)
2966 const parameter &param = params[pat->param_test];
2967 switch (newd->test.kind)
2969 case rtx_test::PREDICATE:
2970 newd->test.u.predicate.mode_is_param = param.is_param;
2971 newd->test.u.predicate.mode = param.value;
2972 break;
2974 case rtx_test::SAVED_CONST_INT:
2975 newd->test.u.integer.is_param = param.is_param;
2976 newd->test.u.integer.value = param.value;
2977 break;
2979 default:
2980 gcc_unreachable ();
2981 break;
2984 if (d->test.kind == rtx_test::C_TEST)
2985 routine->insn_p = true;
2986 else if (d->test.kind == rtx_test::HAVE_NUM_CLOBBERS)
2987 routine->pnum_clobbers_p = true;
2988 news->push_back (newd);
2990 /* Fill in the transitions of NEWD. */
2991 unsigned int i = 0;
2992 for (transition *trans = d->first; trans; trans = trans->next)
2994 /* Create a new state to act as the target of the new transition. */
2995 state *to_news = new state;
2996 if (merge_pattern_transition *ptrans = pat->transitions[i])
2998 /* The pattern hasn't finished matching yet. Get the target
2999 pattern and the corresponding target state of SINFO. */
3000 merge_pattern_info *to_pat = ptrans->to;
3001 merge_state_info *to = sinfo->to_states + i;
3002 gcc_assert (to->res->pattern == to_pat);
3003 gcc_assert (ptrans->params.length () == to_pat->params.length ());
3005 /* Express the parameters to TO_PAT in terms of the parameters
3006 to the top-level pattern. */
3007 auto_vec <parameter, MAX_PATTERN_PARAMS> to_params;
3008 for (unsigned int j = 0; j < ptrans->params.length (); ++j)
3010 const parameter &param = ptrans->params[j];
3011 to_params.quick_push (param.is_param
3012 ? params[param.value]
3013 : param);
3016 if (same_pattern_p (pat, to_pat))
3017 /* TO_PAT is part of the current routine, so just recurse. */
3018 populate_pattern_routine (cpi, to, to_news, to_params);
3019 else
3021 /* TO_PAT should be matched by calling a separate routine. */
3022 create_pattern_info sub_cpi;
3023 decision *subd = init_pattern_use (&sub_cpi, to, to_params);
3024 routine->insn_p |= sub_cpi.routine->insn_p;
3025 routine->pnum_clobbers_p |= sub_cpi.routine->pnum_clobbers_p;
3027 /* Add the pattern routine call to the new target state. */
3028 to_news->push_back (subd);
3030 /* Add a transition for each successful call result. */
3031 for (unsigned int j = 0; j < to_pat->num_results; ++j)
3033 state *res = new state;
3034 add_pattern_acceptance (cpi, res);
3035 subd->push_back (new transition (j, res, false));
3039 else
3040 /* This transition corresponds to a successful match. */
3041 add_pattern_acceptance (cpi, to_news);
3043 /* Create the transition itself, generalizing as necessary. */
3044 transition *new_trans = new transition (trans->labels, to_news,
3045 trans->optional);
3046 if (pat->param_transition_p)
3048 const parameter &param = params[pat->param_transition];
3049 new_trans->is_param = param.is_param;
3050 new_trans->labels[0] = param.value;
3052 newd->push_back (new_trans);
3053 i += 1;
3057 /* USE is a decision that calls a pattern routine and SINFO is part of the
3058 original state tree that the call is supposed to replace. Add the
3059 transitions for SINFO and its substates to USE. */
3061 static void
3062 populate_pattern_use (create_pattern_info *cpi, decision *use,
3063 merge_state_info *sinfo)
3065 pattern_use_states += 1;
3066 gcc_assert (!sinfo->merged_p);
3067 sinfo->merged_p = true;
3068 merge_state_result *res = sinfo->res;
3069 merge_pattern_info *pat = res->pattern;
3070 decision *d = sinfo->s->singleton ();
3071 unsigned int i = 0;
3072 for (transition *trans = d->first; trans; trans = trans->next)
3074 if (pat->transitions[i])
3075 /* The target state is also part of the pattern. */
3076 populate_pattern_use (cpi, use, sinfo->to_states + i);
3077 else
3079 /* The transition corresponds to a successful return from the
3080 pattern routine. */
3081 use->push_back (new transition (cpi->next_result, trans->to, false));
3082 cpi->next_result += 1;
3084 i += 1;
3088 /* We have decided to replace SINFO's state with a call to a pattern
3089 routine. Make the change, creating a definition of the pattern routine
3090 if it doesn't have one already. */
3092 static void
3093 use_pattern (merge_state_info *sinfo)
3095 merge_state_result *res = sinfo->res;
3096 merge_pattern_info *pat = res->pattern;
3097 state *s = sinfo->s;
3099 /* The pattern may have acquired new parameters after it was matched
3100 against SINFO. Update the parameters that SINFO passes accordingly. */
3101 update_parameters (res->params, pat->params);
3103 create_pattern_info cpi;
3104 decision *d = init_pattern_use (&cpi, sinfo, res->params);
3105 populate_pattern_use (&cpi, d, sinfo);
3106 s->release ();
3107 s->push_back (d);
3110 /* Look through the state trees in STATES for common patterns and
3111 split them into subroutines. */
3113 static void
3114 split_out_patterns (vec <merge_state_info> &states)
3116 unsigned int first_transition = states.length ();
3117 hash_table <test_pattern_hasher> hashtab (128);
3118 /* Stage 1: Create an order in which parent states come before their child
3119 states and in which sibling states are at consecutive locations.
3120 Having consecutive sibling states allows merge_state_info to have
3121 a single to_states pointer. */
3122 for (unsigned int i = 0; i < states.length (); ++i)
3123 for (decision *d = states[i].s->first; d; d = d->next)
3124 for (transition *trans = d->first; trans; trans = trans->next)
3126 states.safe_push (trans->to);
3127 states[i].num_transitions += 1;
3129 /* Stage 2: Now that the addresses are stable, set up the to_states
3130 pointers. Look for states that might be merged and enter them
3131 into the hash table. */
3132 for (unsigned int i = 0; i < states.length (); ++i)
3134 merge_state_info *sinfo = &states[i];
3135 if (sinfo->num_transitions)
3137 sinfo->to_states = &states[first_transition];
3138 first_transition += sinfo->num_transitions;
3140 /* For simplicity, we only try to merge states that have a single
3141 decision. This is in any case the best we can do for peephole2,
3142 since whether a peephole2 ACCEPT succeeds or not depends on the
3143 specific peephole2 pattern (which is unique to each ACCEPT
3144 and so couldn't be shared between states). */
3145 if (decision *d = sinfo->s->singleton ())
3146 /* ACCEPT states are unique, so don't even try to merge them. */
3147 if (d->test.kind != rtx_test::ACCEPT
3148 && (pattern_have_num_clobbers_p
3149 || d->test.kind != rtx_test::HAVE_NUM_CLOBBERS)
3150 && (pattern_c_test_p
3151 || d->test.kind != rtx_test::C_TEST))
3153 merge_state_info **slot = hashtab.find_slot (sinfo, INSERT);
3154 sinfo->prev_same_test = *slot;
3155 *slot = sinfo;
3158 /* Stage 3: Walk backwards through the list of states and try to merge
3159 them. This is a greedy, bottom-up match; parent nodes can only start
3160 a new leaf pattern if they fail to match when combined with all child
3161 nodes that have matching patterns.
3163 For each state we keep a list of potential matches, with each
3164 potential match being larger (and deeper) than the next match in
3165 the list. The final element in the list is a leaf pattern that
3166 matches just a single state.
3168 Each candidate pattern created in this loop is unique -- it won't
3169 have been seen by an earlier iteration. We try to match each pattern
3170 with every state that appears earlier in STATES.
3172 Because the patterns created in the loop are unique, any state
3173 that already has a match must have a final potential match that
3174 is different from any new leaf pattern. Therefore, when matching
3175 leaf patterns, we need only consider states whose list of matches
3176 is empty.
3178 The non-leaf patterns that we try are as deep as possible
3179 and are an extension of the state's previous best candidate match (PB).
3180 We need only consider states whose current potential match is also PB;
3181 any states that don't match as much as PB cannnot match the new pattern,
3182 while any states that already match more than PB must be different from
3183 the new pattern. */
3184 for (unsigned int i2 = states.length (); i2-- > 0; )
3186 merge_state_info *sinfo2 = &states[i2];
3188 /* Enforce the bottom-upness of the match: remove matches with later
3189 states if SINFO2's child states ended up finding a better match. */
3190 prune_invalid_results (sinfo2);
3192 /* Do nothing if the state doesn't match a later one and if there are
3193 no earlier states it could match. */
3194 if (!sinfo2->res && !sinfo2->prev_same_test)
3195 continue;
3197 merge_state_result *res2 = sinfo2->res;
3198 decision *d2 = sinfo2->s->singleton ();
3199 position *root2 = (d2->test.pos_operand < 0 ? d2->test.pos : 0);
3200 unsigned int num_transitions = sinfo2->num_transitions;
3202 /* If RES2 is null then SINFO2's test in isolation has not been seen
3203 before. First try matching that on its own. */
3204 if (!res2)
3206 merge_pattern_info *new_pat
3207 = new merge_pattern_info (num_transitions);
3208 merge_state_result *new_res2
3209 = new merge_state_result (new_pat, root2, res2);
3210 sinfo2->res = new_res2;
3212 new_pat->num_statements = !d2->test.single_outcome_p ();
3213 new_pat->num_results = num_transitions;
3214 bool matched_p = false;
3215 /* Look for states that don't currently match anything but
3216 can be made to match SINFO2 on its own. */
3217 for (merge_state_info *sinfo1 = sinfo2->prev_same_test; sinfo1;
3218 sinfo1 = sinfo1->prev_same_test)
3219 if (!sinfo1->res && merge_patterns (sinfo1, sinfo2))
3220 matched_p = true;
3221 if (!matched_p)
3223 /* No other states match. */
3224 sinfo2->res = res2;
3225 delete new_pat;
3226 delete new_res2;
3227 continue;
3229 else
3230 res2 = new_res2;
3233 /* Keep the existing pattern if it's as good as anything we'd
3234 create for SINFO2. */
3235 if (complete_result_p (res2->pattern, sinfo2))
3237 res2->pattern->num_users += 1;
3238 continue;
3241 /* Create a new pattern for SINFO2. */
3242 merge_pattern_info *new_pat = new merge_pattern_info (num_transitions);
3243 merge_state_result *new_res2
3244 = new merge_state_result (new_pat, root2, res2);
3245 sinfo2->res = new_res2;
3247 /* Fill in details about the pattern. */
3248 new_pat->num_statements = !d2->test.single_outcome_p ();
3249 new_pat->num_results = 0;
3250 for (unsigned int j = 0; j < num_transitions; ++j)
3251 if (merge_state_result *to_res = sinfo2->to_states[j].res)
3253 /* Count the target state as part of this pattern.
3254 First update the root position so that it can reach
3255 the target state's root. */
3256 if (to_res->root)
3258 if (new_res2->root)
3259 new_res2->root = common_position (new_res2->root,
3260 to_res->root);
3261 else
3262 new_res2->root = to_res->root;
3264 merge_pattern_info *to_pat = to_res->pattern;
3265 merge_pattern_transition *ptrans
3266 = new merge_pattern_transition (to_pat);
3268 /* TO_PAT may have acquired more parameters when matching
3269 states earlier in STATES than TO_RES's, but the list is
3270 now final. Make sure that TO_RES is up to date. */
3271 update_parameters (to_res->params, to_pat->params);
3273 /* Start out by assuming that every user of NEW_PAT will
3274 want to pass the same (constant) parameters as TO_RES. */
3275 update_parameters (ptrans->params, to_res->params);
3277 new_pat->transitions[j] = ptrans;
3278 new_pat->num_statements += to_pat->num_statements;
3279 new_pat->num_results += to_pat->num_results;
3281 else
3282 /* The target state doesn't match anything and so is not part
3283 of the pattern. */
3284 new_pat->num_results += 1;
3286 /* See if any earlier states that match RES2's pattern also match
3287 NEW_PAT. */
3288 bool matched_p = false;
3289 for (merge_state_info *sinfo1 = sinfo2->prev_same_test; sinfo1;
3290 sinfo1 = sinfo1->prev_same_test)
3292 prune_invalid_results (sinfo1);
3293 if (sinfo1->res
3294 && sinfo1->res->pattern == res2->pattern
3295 && merge_patterns (sinfo1, sinfo2))
3296 matched_p = true;
3298 if (!matched_p)
3300 /* Nothing else matches NEW_PAT, so go back to the previous
3301 pattern (possibly just a single-state one). */
3302 sinfo2->res = res2;
3303 delete new_pat;
3304 delete new_res2;
3306 /* Assume that SINFO2 will use RES. At this point we don't know
3307 whether earlier states that match the same pattern will use
3308 that match or a different one. */
3309 sinfo2->res->pattern->num_users += 1;
3311 /* Step 4: Finalize the choice of pattern for each state, ignoring
3312 patterns that were only used once. Update each pattern's size
3313 so that it doesn't include subpatterns that are going to be split
3314 out into subroutines. */
3315 for (unsigned int i = 0; i < states.length (); ++i)
3317 merge_state_info *sinfo = &states[i];
3318 merge_state_result *res = sinfo->res;
3319 /* Wind past patterns that are only used by SINFO. */
3320 while (res && res->pattern->num_users == 1)
3322 res = res->prev;
3323 sinfo->res = res;
3324 if (res)
3325 res->pattern->num_users += 1;
3327 if (!res)
3328 continue;
3330 /* We have a shared pattern and are now committed to the match. */
3331 merge_pattern_info *pat = res->pattern;
3332 gcc_assert (valid_result_p (pat, sinfo));
3334 if (!pat->complete_p)
3336 /* Look for subpatterns that are going to be split out and remove
3337 them from the number of statements. */
3338 for (unsigned int j = 0; j < sinfo->num_transitions; ++j)
3339 if (merge_pattern_transition *ptrans = pat->transitions[j])
3341 merge_pattern_info *to_pat = ptrans->to;
3342 if (!same_pattern_p (pat, to_pat))
3343 pat->num_statements -= to_pat->num_statements;
3345 pat->complete_p = true;
3348 /* Step 5: Split out the patterns. */
3349 for (unsigned int i = 0; i < states.length (); ++i)
3351 merge_state_info *sinfo = &states[i];
3352 merge_state_result *res = sinfo->res;
3353 if (!sinfo->merged_p && res && useful_pattern_p (res->pattern))
3354 use_pattern (sinfo);
3356 fprintf (stderr, "Shared %d out of %d states by creating %d new states,"
3357 " saving %d\n",
3358 pattern_use_states, states.length (), pattern_def_states,
3359 pattern_use_states - pattern_def_states);
3362 /* Information about a state tree that we're considering splitting into a
3363 subroutine. */
3364 struct state_size
3366 /* The number of pseudo-statements in the state tree. */
3367 unsigned int num_statements;
3369 /* The approximate number of nested "if" and "switch" statements that
3370 would be required if control could fall through to a later state. */
3371 unsigned int depth;
3374 /* Pairs a transition with information about its target state. */
3375 typedef std::pair <transition *, state_size> subroutine_candidate;
3377 /* Sort two subroutine_candidates so that the one with the largest
3378 number of statements comes last. */
3380 static int
3381 subroutine_candidate_cmp (const void *a, const void *b)
3383 return int (((const subroutine_candidate *) a)->second.num_statements
3384 - ((const subroutine_candidate *) b)->second.num_statements);
3387 /* Turn S into a subroutine of type TYPE and add it to PROCS. Return a new
3388 state that performs a subroutine call to S. */
3390 static state *
3391 create_subroutine (routine_type type, state *s, vec <state *> &procs)
3393 procs.safe_push (s);
3394 acceptance_type acceptance;
3395 acceptance.type = type;
3396 acceptance.partial_p = true;
3397 acceptance.u.subroutine_id = procs.length ();
3398 state *news = new state;
3399 add_decision (news, rtx_test::accept (acceptance), true, false);
3400 return news;
3403 /* Walk state tree S, of type TYPE, and look for subtrees that would be
3404 better split into subroutines. Accumulate all such subroutines in PROCS.
3405 Return the size of the new state tree (excluding subroutines). */
3407 static state_size
3408 find_subroutines (routine_type type, state *s, vec <state *> &procs)
3410 auto_vec <subroutine_candidate, 16> candidates;
3411 state_size size;
3412 size.num_statements = 0;
3413 size.depth = 0;
3414 for (decision *d = s->first; d; d = d->next)
3416 if (!d->test.single_outcome_p ())
3417 size.num_statements += 1;
3418 for (transition *trans = d->first; trans; trans = trans->next)
3420 /* Keep chains of simple decisions together if we know that no
3421 change of position is required. We'll output this chain as a
3422 single "if" statement, so it counts as a single nesting level. */
3423 if (d->test.pos && d->if_statement_p ())
3424 for (;;)
3426 decision *newd = trans->to->singleton ();
3427 if (!newd
3428 || (newd->test.pos
3429 && newd->test.pos_operand < 0
3430 && newd->test.pos != d->test.pos)
3431 || !newd->if_statement_p ())
3432 break;
3433 if (!newd->test.single_outcome_p ())
3434 size.num_statements += 1;
3435 trans = newd->singleton ();
3436 if (newd->test.kind == rtx_test::SET_OP
3437 || newd->test.kind == rtx_test::ACCEPT)
3438 break;
3440 /* The target of TRANS is a subroutine candidate. First recurse
3441 on it to see how big it is after subroutines have been
3442 split out. */
3443 state_size to_size = find_subroutines (type, trans->to, procs);
3444 if (d->next && to_size.depth > MAX_DEPTH)
3445 /* Keeping the target state in the same routine would lead
3446 to an excessive nesting of "if" and "switch" statements.
3447 Split it out into a subroutine so that it can use
3448 inverted tests that return early on failure. */
3449 trans->to = create_subroutine (type, trans->to, procs);
3450 else
3452 size.num_statements += to_size.num_statements;
3453 if (to_size.num_statements < MIN_NUM_STATEMENTS)
3454 /* The target state is too small to be worth splitting.
3455 Keep it in the same routine as S. */
3456 size.depth = MAX (size.depth, to_size.depth);
3457 else
3458 /* Assume for now that we'll keep the target state in the
3459 same routine as S, but record it as a subroutine candidate
3460 if S grows too big. */
3461 candidates.safe_push (subroutine_candidate (trans, to_size));
3465 if (size.num_statements > MAX_NUM_STATEMENTS)
3467 /* S is too big. Sort the subroutine candidates so that bigger ones
3468 are nearer the end. */
3469 candidates.qsort (subroutine_candidate_cmp);
3470 while (!candidates.is_empty ()
3471 && size.num_statements > MAX_NUM_STATEMENTS)
3473 /* Peel off a candidate and force it into a subroutine. */
3474 subroutine_candidate cand = candidates.pop ();
3475 size.num_statements -= cand.second.num_statements;
3476 cand.first->to = create_subroutine (type, cand.first->to, procs);
3479 /* Update the depth for subroutine candidates that we decided not to
3480 split out. */
3481 for (unsigned int i = 0; i < candidates.length (); ++i)
3482 size.depth = MAX (size.depth, candidates[i].second.depth);
3483 size.depth += 1;
3484 return size;
3487 /* Return true if, for all X, PRED (X, MODE) implies that X has mode MODE. */
3489 static bool
3490 safe_predicate_mode (const struct pred_data *pred, machine_mode mode)
3492 /* Scalar integer constants have VOIDmode. */
3493 if (GET_MODE_CLASS (mode) == MODE_INT
3494 && (pred->codes[CONST_INT]
3495 || pred->codes[CONST_DOUBLE]
3496 || pred->codes[CONST_WIDE_INT]
3497 || pred->codes[LABEL_REF]))
3498 return false;
3500 return !pred->special && mode != VOIDmode;
3503 /* Fill CODES with the set of codes that could be matched by PRED. */
3505 static void
3506 get_predicate_codes (const struct pred_data *pred, int_set *codes)
3508 for (int i = 0; i < NUM_TRUE_RTX_CODE; ++i)
3509 if (!pred || pred->codes[i])
3510 codes->safe_push (i);
3513 /* Return true if the first path through D1 tests the same thing as D2. */
3515 static bool
3516 has_same_test_p (decision *d1, decision *d2)
3520 if (d1->test == d2->test)
3521 return true;
3522 d1 = d1->first->to->first;
3524 while (d1);
3525 return false;
3528 /* Return true if D1 and D2 cannot match the same rtx. All states reachable
3529 from D2 have single decisions and all those decisions have single
3530 transitions. */
3532 static bool
3533 mutually_exclusive_p (decision *d1, decision *d2)
3535 /* If one path through D1 fails to test the same thing as D2, assume
3536 that D2's test could be true for D1 and look for a later, more useful,
3537 test. This isn't as expensive as it looks in practice. */
3538 while (!has_same_test_p (d1, d2))
3540 d2 = d2->singleton ()->to->singleton ();
3541 if (!d2)
3542 return false;
3544 if (d1->test == d2->test)
3546 /* Look for any transitions from D1 that have the same labels as
3547 the transition from D2. */
3548 transition *trans2 = d2->singleton ();
3549 for (transition *trans1 = d1->first; trans1; trans1 = trans1->next)
3551 int_set::iterator i1 = trans1->labels.begin ();
3552 int_set::iterator end1 = trans1->labels.end ();
3553 int_set::iterator i2 = trans2->labels.begin ();
3554 int_set::iterator end2 = trans2->labels.end ();
3555 while (i1 != end1 && i2 != end2)
3556 if (*i1 < *i2)
3557 ++i1;
3558 else if (*i2 < *i1)
3559 ++i2;
3560 else
3562 /* TRANS1 has some labels in common with TRANS2. Assume
3563 that D1 and D2 could match the same rtx if the target
3564 of TRANS1 could match the same rtx as D2. */
3565 for (decision *subd1 = trans1->to->first;
3566 subd1; subd1 = subd1->next)
3567 if (!mutually_exclusive_p (subd1, d2))
3568 return false;
3569 break;
3572 return true;
3574 for (transition *trans1 = d1->first; trans1; trans1 = trans1->next)
3575 for (decision *subd1 = trans1->to->first; subd1; subd1 = subd1->next)
3576 if (!mutually_exclusive_p (subd1, d2))
3577 return false;
3578 return true;
3581 /* Try to merge S2's decision into D1, given that they have the same test.
3582 Fail only if EXCLUDE is nonnull and the new transition would have the
3583 same labels as *EXCLUDE. When returning true, set *NEXT_S1, *NEXT_S2
3584 and *NEXT_EXCLUDE as for merge_into_state_1, or set *NEXT_S2 to null
3585 if the merge is complete. */
3587 static bool
3588 merge_into_decision (decision *d1, state *s2, const int_set *exclude,
3589 state **next_s1, state **next_s2,
3590 const int_set **next_exclude)
3592 decision *d2 = s2->singleton ();
3593 transition *trans2 = d2->singleton ();
3595 /* Get a list of the transitions that intersect TRANS2. */
3596 auto_vec <transition *, 32> intersecting;
3597 for (transition *trans1 = d1->first; trans1; trans1 = trans1->next)
3599 int_set::iterator i1 = trans1->labels.begin ();
3600 int_set::iterator end1 = trans1->labels.end ();
3601 int_set::iterator i2 = trans2->labels.begin ();
3602 int_set::iterator end2 = trans2->labels.end ();
3603 bool trans1_is_subset = true;
3604 bool trans2_is_subset = true;
3605 bool intersect_p = false;
3606 while (i1 != end1 && i2 != end2)
3607 if (*i1 < *i2)
3609 trans1_is_subset = false;
3610 ++i1;
3612 else if (*i2 < *i1)
3614 trans2_is_subset = false;
3615 ++i2;
3617 else
3619 intersect_p = true;
3620 ++i1;
3621 ++i2;
3623 if (i1 != end1)
3624 trans1_is_subset = false;
3625 if (i2 != end2)
3626 trans2_is_subset = false;
3627 if (trans1_is_subset && trans2_is_subset)
3629 /* There's already a transition that matches exactly.
3630 Merge the target states. */
3631 trans1->optional &= trans2->optional;
3632 *next_s1 = trans1->to;
3633 *next_s2 = trans2->to;
3634 *next_exclude = 0;
3635 return true;
3637 if (trans2_is_subset)
3639 /* TRANS1 has all the labels that TRANS2 needs. Merge S2 into
3640 the target of TRANS1, but (to avoid infinite recursion)
3641 make sure that we don't end up creating another transition
3642 like TRANS1. */
3643 *next_s1 = trans1->to;
3644 *next_s2 = s2;
3645 *next_exclude = &trans1->labels;
3646 return true;
3648 if (intersect_p)
3649 intersecting.safe_push (trans1);
3652 if (intersecting.is_empty ())
3654 /* No existing labels intersect the new ones. We can just add
3655 TRANS2 itself. */
3656 d1->push_back (d2->release ());
3657 *next_s1 = 0;
3658 *next_s2 = 0;
3659 *next_exclude = 0;
3660 return true;
3663 /* Take the union of the labels in INTERSECTING and TRANS2. Store the
3664 result in COMBINED and use NEXT as a temporary. */
3665 int_set tmp1 = trans2->labels, tmp2;
3666 int_set *combined = &tmp1, *next = &tmp2;
3667 for (unsigned int i = 0; i < intersecting.length (); ++i)
3669 transition *trans1 = intersecting[i];
3670 next->truncate (0);
3671 next->safe_grow (trans1->labels.length () + combined->length ());
3672 int_set::iterator end
3673 = std::set_union (trans1->labels.begin (), trans1->labels.end (),
3674 combined->begin (), combined->end (),
3675 next->begin ());
3676 next->truncate (end - next->begin ());
3677 std::swap (next, combined);
3680 /* Stop now if we've been told not to create a transition with these
3681 labels. */
3682 if (exclude && *combined == *exclude)
3683 return false;
3685 /* Get the transition that should carry the new labels. */
3686 transition *new_trans = intersecting[0];
3687 if (intersecting.length () == 1)
3689 /* We're merging with one existing transition whose labels are a
3690 subset of those required. If both transitions are optional,
3691 we can just expand the set of labels so that it's suitable
3692 for both transitions. It isn't worth preserving the original
3693 transitions since we know that they can't be merged; we would
3694 need to backtrack to S2 if TRANS1->to fails. In contrast,
3695 we might be able to merge the targets of the transitions
3696 without any backtracking.
3698 If instead the existing transition is not optional, ensure that
3699 all target decisions are suitably protected. Some decisions
3700 might already have a more specific requirement than NEW_TRANS,
3701 in which case there's no point testing NEW_TRANS as well. E.g. this
3702 would have happened if a test for an (eq ...) rtx had been
3703 added to a decision that tested whether the code is suitable
3704 for comparison_operator. The original comparison_operator
3705 transition would have been non-optional and the (eq ...) test
3706 would be performed by a second decision in the target of that
3707 transition.
3709 The remaining case -- keeping the original optional transition
3710 when adding a non-optional TRANS2 -- is a wash. Preserving
3711 the optional transition only helps if we later merge another
3712 state S3 that is mutually exclusive with S2 and whose labels
3713 belong to *COMBINED - TRANS1->labels. We can then test the
3714 original NEW_TRANS and S3 in the same decision. We keep the
3715 optional transition around for that case, but it occurs very
3716 rarely. */
3717 gcc_assert (new_trans->labels != *combined);
3718 if (!new_trans->optional || !trans2->optional)
3720 decision *start = 0;
3721 for (decision *end = new_trans->to->first; end; end = end->next)
3723 if (!start && end->test != d1->test)
3724 /* END belongs to a range of decisions that need to be
3725 protected by NEW_TRANS. */
3726 start = end;
3727 if (start && (!end->next || end->next->test == d1->test))
3729 /* Protect [START, END] with NEW_TRANS. The decisions
3730 move to NEW_S and NEW_D becomes part of NEW_TRANS->to. */
3731 state *new_s = new state;
3732 decision *new_d = new decision (d1->test);
3733 new_d->push_back (new transition (new_trans->labels, new_s,
3734 new_trans->optional));
3735 state::range r (start, end);
3736 new_trans->to->replace (r, new_d);
3737 new_s->push_back (r);
3739 /* Continue with an empty range. */
3740 start = 0;
3742 /* Continue from the decision after NEW_D. */
3743 end = new_d;
3747 new_trans->optional = true;
3748 new_trans->labels = *combined;
3750 else
3752 /* We're merging more than one existing transition together.
3753 Those transitions are successfully dividing the matching space
3754 and so we want to preserve them, even if they're optional.
3756 Create a new transition with the union set of labels and make
3757 it go to a state that has the original transitions. */
3758 decision *new_d = new decision (d1->test);
3759 for (unsigned int i = 0; i < intersecting.length (); ++i)
3760 new_d->push_back (d1->remove (intersecting[i]));
3762 state *new_s = new state;
3763 new_s->push_back (new_d);
3765 new_trans = new transition (*combined, new_s, true);
3766 d1->push_back (new_trans);
3769 /* We now have an optional transition with labels *COMBINED. Decide
3770 whether we can use it as TRANS2 or whether we need to merge S2
3771 into the target of NEW_TRANS. */
3772 gcc_assert (new_trans->optional);
3773 if (new_trans->labels == trans2->labels)
3775 /* NEW_TRANS matches TRANS2. Just merge the target states. */
3776 new_trans->optional = trans2->optional;
3777 *next_s1 = new_trans->to;
3778 *next_s2 = trans2->to;
3779 *next_exclude = 0;
3781 else
3783 /* Try to merge TRANS2 into the target of the overlapping transition,
3784 but (to prevent infinite recursion or excessive redundancy) without
3785 creating another transition of the same type. */
3786 *next_s1 = new_trans->to;
3787 *next_s2 = s2;
3788 *next_exclude = &new_trans->labels;
3790 return true;
3793 /* Make progress in merging S2 into S1, given that each state in S2
3794 has a single decision. If EXCLUDE is nonnull, avoid creating a new
3795 transition with the same test as S2's decision and with the labels
3796 in *EXCLUDE.
3798 Return true if there is still work to do. When returning true,
3799 set *NEXT_S1, *NEXT_S2 and *NEXT_EXCLUDE to the values that
3800 S1, S2 and EXCLUDE should have next time round.
3802 If S1 and S2 both match a particular rtx, give priority to S1. */
3804 static bool
3805 merge_into_state_1 (state *s1, state *s2, const int_set *exclude,
3806 state **next_s1, state **next_s2,
3807 const int_set **next_exclude)
3809 decision *d2 = s2->singleton ();
3810 if (decision *d1 = s1->last)
3812 if (d1->test.terminal_p ())
3813 /* D1 is an unconditional return, so S2 can never match. This can
3814 sometimes be a bug in the .md description, but might also happen
3815 if genconditions forces some conditions to true for certain
3816 configurations. */
3817 return false;
3819 /* Go backwards through the decisions in S1, stopping once we find one
3820 that could match the same thing as S2. */
3821 while (d1->prev && mutually_exclusive_p (d1, d2))
3822 d1 = d1->prev;
3824 /* Search forwards from that point, merging D2 into the first
3825 decision we can. */
3826 for (; d1; d1 = d1->next)
3828 /* If S2 performs some optional tests before testing the same thing
3829 as D1, those tests do not help to distinguish D1 and S2, so it's
3830 better to drop them. Search through such optional decisions
3831 until we find something that tests the same thing as D1. */
3832 state *sub_s2 = s2;
3833 for (;;)
3835 decision *sub_d2 = sub_s2->singleton ();
3836 if (d1->test == sub_d2->test)
3838 /* Only apply EXCLUDE if we're testing the same thing
3839 as D2. */
3840 const int_set *sub_exclude = (d2 == sub_d2 ? exclude : 0);
3842 /* Try to merge SUB_S2 into D1. This can only fail if
3843 it would involve creating a new transition with
3844 labels SUB_EXCLUDE. */
3845 if (merge_into_decision (d1, sub_s2, sub_exclude,
3846 next_s1, next_s2, next_exclude))
3847 return *next_s2 != 0;
3849 /* Can't merge with D1; try a later decision. */
3850 break;
3852 transition *sub_trans2 = sub_d2->singleton ();
3853 if (!sub_trans2->optional)
3854 /* Can't merge with D1; try a later decision. */
3855 break;
3856 sub_s2 = sub_trans2->to;
3861 /* We can't merge D2 with any existing decision. Just add it to the end. */
3862 s1->push_back (s2->release ());
3863 return false;
3866 /* Merge S2 into S1. If they both match a particular rtx, give
3867 priority to S1. Each state in S2 has a single decision. */
3869 static void
3870 merge_into_state (state *s1, state *s2)
3872 const int_set *exclude = 0;
3873 while (s2 && merge_into_state_1 (s1, s2, exclude, &s1, &s2, &exclude))
3874 continue;
3877 /* Pairs a pattern that needs to be matched with the rtx position at
3878 which the pattern should occur. */
3879 class pattern_pos {
3880 public:
3881 pattern_pos () {}
3882 pattern_pos (rtx, position *);
3884 rtx pattern;
3885 position *pos;
3888 pattern_pos::pattern_pos (rtx pattern_in, position *pos_in)
3889 : pattern (pattern_in), pos (pos_in)
3892 /* Compare entries according to their depth-first order. There shouldn't
3893 be two entries at the same position. */
3895 bool
3896 operator < (const pattern_pos &e1, const pattern_pos &e2)
3898 int diff = compare_positions (e1.pos, e2.pos);
3899 gcc_assert (diff != 0 || e1.pattern == e2.pattern);
3900 return diff < 0;
3903 /* Add new decisions to S that check whether the rtx at position POS
3904 matches PATTERN. Return the state that is reached in that case.
3905 TOP_PATTERN is the overall pattern, as passed to match_pattern_1. */
3907 static state *
3908 match_pattern_2 (state *s, md_rtx_info *info, position *pos, rtx pattern)
3910 auto_vec <pattern_pos, 32> worklist;
3911 auto_vec <pattern_pos, 32> pred_and_mode_tests;
3912 auto_vec <pattern_pos, 32> dup_tests;
3914 worklist.safe_push (pattern_pos (pattern, pos));
3915 while (!worklist.is_empty ())
3917 pattern_pos next = worklist.pop ();
3918 pattern = next.pattern;
3919 pos = next.pos;
3920 unsigned int reverse_s = worklist.length ();
3922 enum rtx_code code = GET_CODE (pattern);
3923 switch (code)
3925 case MATCH_OP_DUP:
3926 case MATCH_DUP:
3927 case MATCH_PAR_DUP:
3928 /* Add a test that the rtx matches the earlier one, but only
3929 after the structure and predicates have been checked. */
3930 dup_tests.safe_push (pattern_pos (pattern, pos));
3932 /* Use the same code check as the original operand. */
3933 pattern = find_operand (info->def, XINT (pattern, 0), NULL_RTX);
3934 /* Fall through. */
3936 case MATCH_PARALLEL:
3937 case MATCH_OPERAND:
3938 case MATCH_SCRATCH:
3939 case MATCH_OPERATOR:
3941 const char *pred_name = predicate_name (pattern);
3942 const struct pred_data *pred = 0;
3943 if (pred_name[0] != 0)
3945 pred = lookup_predicate (pred_name);
3946 /* Only report errors once per rtx. */
3947 if (code == GET_CODE (pattern))
3949 if (!pred)
3950 error_at (info->loc, "unknown predicate '%s' used in %s",
3951 pred_name, GET_RTX_NAME (code));
3952 else if (code == MATCH_PARALLEL
3953 && pred->singleton != PARALLEL)
3954 error_at (info->loc, "predicate '%s' used in"
3955 " match_parallel does not allow only PARALLEL",
3956 pred->name);
3960 if (code == MATCH_PARALLEL || code == MATCH_PAR_DUP)
3962 /* Check that we have a parallel with enough elements. */
3963 s = add_decision (s, rtx_test::code (pos), PARALLEL, false);
3964 int min_len = XVECLEN (pattern, 2);
3965 s = add_decision (s, rtx_test::veclen_ge (pos, min_len),
3966 true, false);
3968 else
3970 /* Check that the rtx has one of codes accepted by the
3971 predicate. This is necessary when matching suboperands
3972 of a MATCH_OPERATOR or MATCH_OP_DUP, since we can't
3973 call XEXP (X, N) without checking that X has at least
3974 N+1 operands. */
3975 int_set codes;
3976 get_predicate_codes (pred, &codes);
3977 bool need_codes = (pred
3978 && (code == MATCH_OPERATOR
3979 || code == MATCH_OP_DUP));
3980 s = add_decision (s, rtx_test::code (pos), codes, !need_codes);
3983 /* Postpone the predicate check until we've checked the rest
3984 of the rtx structure. */
3985 if (code == GET_CODE (pattern))
3986 pred_and_mode_tests.safe_push (pattern_pos (pattern, pos));
3988 /* If we need to match suboperands, add them to the worklist. */
3989 if (code == MATCH_OPERATOR || code == MATCH_PARALLEL)
3991 position **subpos_ptr;
3992 enum position_type pos_type;
3993 int i;
3994 if (code == MATCH_OPERATOR || code == MATCH_OP_DUP)
3996 pos_type = POS_XEXP;
3997 subpos_ptr = &pos->xexps;
3998 i = (code == MATCH_OPERATOR ? 2 : 1);
4000 else
4002 pos_type = POS_XVECEXP0;
4003 subpos_ptr = &pos->xvecexp0s;
4004 i = 2;
4006 for (int j = 0; j < XVECLEN (pattern, i); ++j)
4008 position *subpos = next_position (subpos_ptr, pos,
4009 pos_type, j);
4010 worklist.safe_push (pattern_pos (XVECEXP (pattern, i, j),
4011 subpos));
4012 subpos_ptr = &subpos->next;
4015 break;
4018 default:
4020 /* Check that the rtx has the right code. */
4021 s = add_decision (s, rtx_test::code (pos), code, false);
4023 /* Queue a test for the mode if one is specified. */
4024 if (GET_MODE (pattern) != VOIDmode)
4025 pred_and_mode_tests.safe_push (pattern_pos (pattern, pos));
4027 /* Push subrtxes onto the worklist. Match nonrtx operands now. */
4028 const char *fmt = GET_RTX_FORMAT (code);
4029 position **subpos_ptr = &pos->xexps;
4030 for (size_t i = 0; fmt[i]; ++i)
4032 position *subpos = next_position (subpos_ptr, pos,
4033 POS_XEXP, i);
4034 switch (fmt[i])
4036 case 'e': case 'u':
4037 worklist.safe_push (pattern_pos (XEXP (pattern, i),
4038 subpos));
4039 break;
4041 case 'E':
4043 /* Make sure the vector has the right number of
4044 elements. */
4045 int length = XVECLEN (pattern, i);
4046 s = add_decision (s, rtx_test::veclen (pos),
4047 length, false);
4049 position **subpos2_ptr = &pos->xvecexp0s;
4050 for (int j = 0; j < length; j++)
4052 position *subpos2 = next_position (subpos2_ptr, pos,
4053 POS_XVECEXP0, j);
4054 rtx x = XVECEXP (pattern, i, j);
4055 worklist.safe_push (pattern_pos (x, subpos2));
4056 subpos2_ptr = &subpos2->next;
4058 break;
4061 case 'i':
4062 /* Make sure that XINT (X, I) has the right value. */
4063 s = add_decision (s, rtx_test::int_field (pos, i),
4064 XINT (pattern, i), false);
4065 break;
4067 case 'r':
4068 /* Make sure that REGNO (X) has the right value. */
4069 gcc_assert (i == 0);
4070 s = add_decision (s, rtx_test::regno_field (pos),
4071 REGNO (pattern), false);
4072 break;
4074 case 'w':
4075 /* Make sure that XWINT (X, I) has the right value. */
4076 s = add_decision (s, rtx_test::wide_int_field (pos, i),
4077 XWINT (pattern, 0), false);
4078 break;
4080 case 'p':
4081 /* We don't have a way of parsing polynomial offsets yet,
4082 and hopefully never will. */
4083 s = add_decision (s, rtx_test::subreg_field (pos),
4084 SUBREG_BYTE (pattern).to_constant (),
4085 false);
4086 break;
4088 case '0':
4089 break;
4091 default:
4092 gcc_unreachable ();
4094 subpos_ptr = &subpos->next;
4097 break;
4099 /* Operands are pushed onto the worklist so that later indices are
4100 nearer the top. That's what we want for SETs, since a SET_SRC
4101 is a better discriminator than a SET_DEST. In other cases it's
4102 usually better to match earlier indices first. This is especially
4103 true of PARALLELs, where the first element tends to be the most
4104 individual. It's also true for commutative operators, where the
4105 canonicalization rules say that the more complex operand should
4106 come first. */
4107 if (code != SET && worklist.length () > reverse_s)
4108 std::reverse (&worklist[0] + reverse_s,
4109 &worklist[0] + worklist.length ());
4112 /* Sort the predicate and mode tests so that they're in depth-first order.
4113 The main goal of this is to put SET_SRC match_operands after SET_DEST
4114 match_operands and after mode checks for the enclosing SET_SRC operators
4115 (such as the mode of a PLUS in an addition instruction). The latter
4116 two types of test can determine the mode exactly, whereas a SET_SRC
4117 match_operand often has to cope with the possibility of the operand
4118 being a modeless constant integer. E.g. something that matches
4119 register_operand (x, SImode) never matches register_operand (x, DImode),
4120 but a const_int that matches immediate_operand (x, SImode) also matches
4121 immediate_operand (x, DImode). The register_operand cases can therefore
4122 be distinguished by a switch on the mode, but the immediate_operand
4123 cases can't. */
4124 if (pred_and_mode_tests.length () > 1)
4125 std::sort (&pred_and_mode_tests[0],
4126 &pred_and_mode_tests[0] + pred_and_mode_tests.length ());
4128 /* Add the mode and predicate tests. */
4129 pattern_pos *e;
4130 unsigned int i;
4131 FOR_EACH_VEC_ELT (pred_and_mode_tests, i, e)
4133 switch (GET_CODE (e->pattern))
4135 case MATCH_PARALLEL:
4136 case MATCH_OPERAND:
4137 case MATCH_SCRATCH:
4138 case MATCH_OPERATOR:
4140 int opno = XINT (e->pattern, 0);
4141 num_operands = MAX (num_operands, opno + 1);
4142 const char *pred_name = predicate_name (e->pattern);
4143 if (pred_name[0])
4145 const struct pred_data *pred = lookup_predicate (pred_name);
4146 /* Check the mode first, to distinguish things like SImode
4147 and DImode register_operands, as described above. */
4148 machine_mode mode = GET_MODE (e->pattern);
4149 if (pred && safe_predicate_mode (pred, mode))
4150 s = add_decision (s, rtx_test::mode (e->pos), mode, true);
4152 /* Assign to operands[] first, so that the rtx usually doesn't
4153 need to be live across the call to the predicate.
4155 This shouldn't cause a problem with dirtying the page,
4156 since we fully expect to assign to operands[] at some point,
4157 and since the caller usually writes to other parts of
4158 recog_data anyway. */
4159 s = add_decision (s, rtx_test::set_op (e->pos, opno),
4160 true, false);
4161 s = add_decision (s, rtx_test::predicate (e->pos, pred, mode),
4162 true, false);
4164 else
4165 /* Historically we've ignored the mode when there's no
4166 predicate. Just set up operands[] unconditionally. */
4167 s = add_decision (s, rtx_test::set_op (e->pos, opno),
4168 true, false);
4169 break;
4172 default:
4173 s = add_decision (s, rtx_test::mode (e->pos),
4174 GET_MODE (e->pattern), false);
4175 break;
4179 /* Finally add rtx_equal_p checks for duplicated operands. */
4180 FOR_EACH_VEC_ELT (dup_tests, i, e)
4181 s = add_decision (s, rtx_test::duplicate (e->pos, XINT (e->pattern, 0)),
4182 true, false);
4183 return s;
4186 /* Add new decisions to S that make it return ACCEPTANCE if:
4188 (1) the rtx doesn't match anything already matched by S
4189 (2) the rtx matches TOP_PATTERN and
4190 (3) the C test required by INFO->def is true
4192 For peephole2, TOP_PATTERN is a SEQUENCE of the instruction patterns
4193 to match, otherwise it is a single instruction pattern. */
4195 static void
4196 match_pattern_1 (state *s, md_rtx_info *info, rtx pattern,
4197 acceptance_type acceptance)
4199 if (acceptance.type == PEEPHOLE2)
4201 /* Match each individual instruction. */
4202 position **subpos_ptr = &peep2_insn_pos_list;
4203 int count = 0;
4204 for (int i = 0; i < XVECLEN (pattern, 0); ++i)
4206 rtx x = XVECEXP (pattern, 0, i);
4207 position *subpos = next_position (subpos_ptr, &root_pos,
4208 POS_PEEP2_INSN, count);
4209 if (count > 0)
4210 s = add_decision (s, rtx_test::peep2_count (count + 1),
4211 true, false);
4212 s = match_pattern_2 (s, info, subpos, x);
4213 subpos_ptr = &subpos->next;
4214 count += 1;
4216 acceptance.u.full.u.match_len = count - 1;
4218 else
4220 /* Make the rtx itself. */
4221 s = match_pattern_2 (s, info, &root_pos, pattern);
4223 /* If the match is only valid when extra clobbers are added,
4224 make sure we're able to pass that information to the caller. */
4225 if (acceptance.type == RECOG && acceptance.u.full.u.num_clobbers)
4226 s = add_decision (s, rtx_test::have_num_clobbers (), true, false);
4229 /* Make sure that the C test is true. */
4230 const char *c_test = get_c_test (info->def);
4231 if (maybe_eval_c_test (c_test) != 1)
4232 s = add_decision (s, rtx_test::c_test (c_test), true, false);
4234 /* Accept the pattern. */
4235 add_decision (s, rtx_test::accept (acceptance), true, false);
4238 /* Like match_pattern_1, but (if merge_states_p) try to merge the
4239 decisions with what's already in S, to reduce the amount of
4240 backtracking. */
4242 static void
4243 match_pattern (state *s, md_rtx_info *info, rtx pattern,
4244 acceptance_type acceptance)
4246 if (merge_states_p)
4248 state root;
4249 /* Add the decisions to a fresh state and then merge the full tree
4250 into the existing one. */
4251 match_pattern_1 (&root, info, pattern, acceptance);
4252 merge_into_state (s, &root);
4254 else
4255 match_pattern_1 (s, info, pattern, acceptance);
4258 /* Begin the output file. */
4260 static void
4261 write_header (void)
4263 puts ("\
4264 /* Generated automatically by the program `genrecog' from the target\n\
4265 machine description file. */\n\
4267 #define IN_TARGET_CODE 1\n\
4269 #include \"config.h\"\n\
4270 #include \"system.h\"\n\
4271 #include \"coretypes.h\"\n\
4272 #include \"backend.h\"\n\
4273 #include \"predict.h\"\n\
4274 #include \"rtl.h\"\n\
4275 #include \"memmodel.h\"\n\
4276 #include \"tm_p.h\"\n\
4277 #include \"emit-rtl.h\"\n\
4278 #include \"insn-config.h\"\n\
4279 #include \"recog.h\"\n\
4280 #include \"output.h\"\n\
4281 #include \"flags.h\"\n\
4282 #include \"df.h\"\n\
4283 #include \"resource.h\"\n\
4284 #include \"diagnostic-core.h\"\n\
4285 #include \"reload.h\"\n\
4286 #include \"regs.h\"\n\
4287 #include \"tm-constrs.h\"\n\
4288 \n");
4290 puts ("\n\
4291 /* `recog' contains a decision tree that recognizes whether the rtx\n\
4292 X0 is a valid instruction.\n\
4294 recog returns -1 if the rtx is not valid. If the rtx is valid, recog\n\
4295 returns a nonnegative number which is the insn code number for the\n\
4296 pattern that matched. This is the same as the order in the machine\n\
4297 description of the entry that matched. This number can be used as an\n\
4298 index into `insn_data' and other tables.\n");
4299 puts ("\
4300 The third parameter to recog is an optional pointer to an int. If\n\
4301 present, recog will accept a pattern if it matches except for missing\n\
4302 CLOBBER expressions at the end. In that case, the value pointed to by\n\
4303 the optional pointer will be set to the number of CLOBBERs that need\n\
4304 to be added (it should be initialized to zero by the caller). If it");
4305 puts ("\
4306 is set nonzero, the caller should allocate a PARALLEL of the\n\
4307 appropriate size, copy the initial entries, and call add_clobbers\n\
4308 (found in insn-emit.c) to fill in the CLOBBERs.\n\
4311 puts ("\n\
4312 The function split_insns returns 0 if the rtl could not\n\
4313 be split or the split rtl as an INSN list if it can be.\n\
4315 The function peephole2_insns returns 0 if the rtl could not\n\
4316 be matched. If there was a match, the new rtl is returned in an INSN list,\n\
4317 and LAST_INSN will point to the last recognized insn in the old sequence.\n\
4318 */\n\n");
4321 /* Return the C type of a parameter with type TYPE. */
4323 static const char *
4324 parameter_type_string (parameter::type_enum type)
4326 switch (type)
4328 case parameter::UNSET:
4329 break;
4331 case parameter::CODE:
4332 return "rtx_code";
4334 case parameter::MODE:
4335 return "machine_mode";
4337 case parameter::INT:
4338 return "int";
4340 case parameter::UINT:
4341 return "unsigned int";
4343 case parameter::WIDE_INT:
4344 return "HOST_WIDE_INT";
4346 gcc_unreachable ();
4349 /* Return true if ACCEPTANCE requires only a single C statement even in
4350 a backtracking context. */
4352 static bool
4353 single_statement_p (const acceptance_type &acceptance)
4355 if (acceptance.partial_p)
4356 /* We need to handle failures of the subroutine. */
4357 return false;
4358 switch (acceptance.type)
4360 case SUBPATTERN:
4361 case SPLIT:
4362 return true;
4364 case RECOG:
4365 /* False if we need to assign to pnum_clobbers. */
4366 return acceptance.u.full.u.num_clobbers == 0;
4368 case PEEPHOLE2:
4369 /* We need to assign to pmatch_len_ and handle null returns from the
4370 peephole2 routine. */
4371 return false;
4373 gcc_unreachable ();
4376 /* Return the C failure value for a routine of type TYPE. */
4378 static const char *
4379 get_failure_return (routine_type type)
4381 switch (type)
4383 case SUBPATTERN:
4384 case RECOG:
4385 return "-1";
4387 case SPLIT:
4388 case PEEPHOLE2:
4389 return "NULL";
4391 gcc_unreachable ();
4394 /* Indicates whether a block of code always returns or whether it can fall
4395 through. */
4397 enum exit_state {
4398 ES_RETURNED,
4399 ES_FALLTHROUGH
4402 /* Information used while writing out code. */
4404 class output_state
4406 public:
4407 /* The type of routine that we're generating. */
4408 routine_type type;
4410 /* Maps position ids to xN variable numbers. The entry is only valid if
4411 it is less than the length of VAR_TO_ID, but this holds for every position
4412 tested by a state when writing out that state. */
4413 auto_vec <unsigned int> id_to_var;
4415 /* Maps xN variable numbers to position ids. */
4416 auto_vec <unsigned int> var_to_id;
4418 /* Index N is true if variable xN has already been set. */
4419 auto_vec <bool> seen_vars;
4422 /* Return true if D is a call to a pattern routine and if there is some X
4423 such that the transition for pattern result N goes to a successful return
4424 with code X+N. When returning true, set *BASE_OUT to this X and *COUNT_OUT
4425 to the number of return values. (We know that every PATTERN decision has
4426 a transition for every successful return.) */
4428 static bool
4429 terminal_pattern_p (decision *d, unsigned int *base_out,
4430 unsigned int *count_out)
4432 if (d->test.kind != rtx_test::PATTERN)
4433 return false;
4434 unsigned int base = 0;
4435 unsigned int count = 0;
4436 for (transition *trans = d->first; trans; trans = trans->next)
4438 if (trans->is_param || trans->labels.length () != 1)
4439 return false;
4440 decision *subd = trans->to->singleton ();
4441 if (!subd || subd->test.kind != rtx_test::ACCEPT)
4442 return false;
4443 unsigned int this_base = (subd->test.u.acceptance.u.full.code
4444 - trans->labels[0]);
4445 if (trans == d->first)
4446 base = this_base;
4447 else if (base != this_base)
4448 return false;
4449 count += 1;
4451 *base_out = base;
4452 *count_out = count;
4453 return true;
4456 /* Return true if TEST doesn't test an rtx or if the rtx it tests is
4457 already available in state OS. */
4459 static bool
4460 test_position_available_p (output_state *os, const rtx_test &test)
4462 return (!test.pos
4463 || test.pos_operand >= 0
4464 || os->seen_vars[os->id_to_var[test.pos->id]]);
4467 /* Like printf, but print INDENT spaces at the beginning. */
4469 static void ATTRIBUTE_PRINTF_2
4470 printf_indent (unsigned int indent, const char *format, ...)
4472 va_list ap;
4473 va_start (ap, format);
4474 printf ("%*s", indent, "");
4475 vprintf (format, ap);
4476 va_end (ap);
4479 /* Emit code to initialize the variable associated with POS, if it isn't
4480 already valid in state OS. Indent each line by INDENT spaces. Update
4481 OS with the new state. */
4483 static void
4484 change_state (output_state *os, position *pos, unsigned int indent)
4486 unsigned int var = os->id_to_var[pos->id];
4487 gcc_assert (var < os->var_to_id.length () && os->var_to_id[var] == pos->id);
4488 if (os->seen_vars[var])
4489 return;
4490 switch (pos->type)
4492 case POS_PEEP2_INSN:
4493 printf_indent (indent, "x%d = PATTERN (peep2_next_insn (%d));\n",
4494 var, pos->arg);
4495 break;
4497 case POS_XEXP:
4498 change_state (os, pos->base, indent);
4499 printf_indent (indent, "x%d = XEXP (x%d, %d);\n",
4500 var, os->id_to_var[pos->base->id], pos->arg);
4501 break;
4503 case POS_XVECEXP0:
4504 change_state (os, pos->base, indent);
4505 printf_indent (indent, "x%d = XVECEXP (x%d, 0, %d);\n",
4506 var, os->id_to_var[pos->base->id], pos->arg);
4507 break;
4509 os->seen_vars[var] = true;
4512 /* Print the enumerator constant for CODE -- the upcase version of
4513 the name. */
4515 static void
4516 print_code (enum rtx_code code)
4518 const char *p;
4519 for (p = GET_RTX_NAME (code); *p; p++)
4520 putchar (TOUPPER (*p));
4523 /* Emit a uint64_t as an integer constant expression. We need to take
4524 special care to avoid "decimal constant is so large that it is unsigned"
4525 warnings in the resulting code. */
4527 static void
4528 print_host_wide_int (uint64_t val)
4530 uint64_t min = uint64_t (1) << (HOST_BITS_PER_WIDE_INT - 1);
4531 if (val == min)
4532 printf ("(" HOST_WIDE_INT_PRINT_DEC_C " - 1)", val + 1);
4533 else
4534 printf (HOST_WIDE_INT_PRINT_DEC_C, val);
4537 /* Print the C expression for actual parameter PARAM. */
4539 static void
4540 print_parameter_value (const parameter &param)
4542 if (param.is_param)
4543 printf ("i%d", (int) param.value + 1);
4544 else
4545 switch (param.type)
4547 case parameter::UNSET:
4548 gcc_unreachable ();
4549 break;
4551 case parameter::CODE:
4552 print_code ((enum rtx_code) param.value);
4553 break;
4555 case parameter::MODE:
4556 printf ("E_%smode", GET_MODE_NAME ((machine_mode) param.value));
4557 break;
4559 case parameter::INT:
4560 printf ("%d", (int) param.value);
4561 break;
4563 case parameter::UINT:
4564 printf ("%u", (unsigned int) param.value);
4565 break;
4567 case parameter::WIDE_INT:
4568 print_host_wide_int (param.value);
4569 break;
4573 /* Print the C expression for the rtx tested by TEST. */
4575 static void
4576 print_test_rtx (output_state *os, const rtx_test &test)
4578 if (test.pos_operand >= 0)
4579 printf ("operands[%d]", test.pos_operand);
4580 else
4581 printf ("x%d", os->id_to_var[test.pos->id]);
4584 /* Print the C expression for non-boolean test TEST. */
4586 static void
4587 print_nonbool_test (output_state *os, const rtx_test &test)
4589 switch (test.kind)
4591 case rtx_test::CODE:
4592 printf ("GET_CODE (");
4593 print_test_rtx (os, test);
4594 printf (")");
4595 break;
4597 case rtx_test::MODE:
4598 printf ("GET_MODE (");
4599 print_test_rtx (os, test);
4600 printf (")");
4601 break;
4603 case rtx_test::VECLEN:
4604 printf ("XVECLEN (");
4605 print_test_rtx (os, test);
4606 printf (", 0)");
4607 break;
4609 case rtx_test::INT_FIELD:
4610 printf ("XINT (");
4611 print_test_rtx (os, test);
4612 printf (", %d)", test.u.opno);
4613 break;
4615 case rtx_test::REGNO_FIELD:
4616 printf ("REGNO (");
4617 print_test_rtx (os, test);
4618 printf (")");
4619 break;
4621 case rtx_test::SUBREG_FIELD:
4622 printf ("SUBREG_BYTE (");
4623 print_test_rtx (os, test);
4624 printf (")");
4625 break;
4627 case rtx_test::WIDE_INT_FIELD:
4628 printf ("XWINT (");
4629 print_test_rtx (os, test);
4630 printf (", %d)", test.u.opno);
4631 break;
4633 case rtx_test::PATTERN:
4635 pattern_routine *routine = test.u.pattern->routine;
4636 printf ("pattern%d (", routine->pattern_id);
4637 const char *sep = "";
4638 if (test.pos)
4640 print_test_rtx (os, test);
4641 sep = ", ";
4643 if (routine->insn_p)
4645 printf ("%sinsn", sep);
4646 sep = ", ";
4648 if (routine->pnum_clobbers_p)
4650 printf ("%spnum_clobbers", sep);
4651 sep = ", ";
4653 for (unsigned int i = 0; i < test.u.pattern->params.length (); ++i)
4655 fputs (sep, stdout);
4656 print_parameter_value (test.u.pattern->params[i]);
4657 sep = ", ";
4659 printf (")");
4660 break;
4663 case rtx_test::PEEP2_COUNT:
4664 case rtx_test::VECLEN_GE:
4665 case rtx_test::SAVED_CONST_INT:
4666 case rtx_test::DUPLICATE:
4667 case rtx_test::PREDICATE:
4668 case rtx_test::SET_OP:
4669 case rtx_test::HAVE_NUM_CLOBBERS:
4670 case rtx_test::C_TEST:
4671 case rtx_test::ACCEPT:
4672 gcc_unreachable ();
4676 /* IS_PARAM and LABEL are taken from a transition whose source
4677 decision performs TEST. Print the C code for the label. */
4679 static void
4680 print_label_value (const rtx_test &test, bool is_param, uint64_t value)
4682 print_parameter_value (parameter (transition_parameter_type (test.kind),
4683 is_param, value));
4686 /* If IS_PARAM, print code to compare TEST with the C variable i<VALUE+1>.
4687 If !IS_PARAM, print code to compare TEST with the C constant VALUE.
4688 Test for inequality if INVERT_P, otherwise test for equality. */
4690 static void
4691 print_test (output_state *os, const rtx_test &test, bool is_param,
4692 uint64_t value, bool invert_p)
4694 switch (test.kind)
4696 /* Handle the non-boolean TESTs. */
4697 case rtx_test::CODE:
4698 case rtx_test::MODE:
4699 case rtx_test::VECLEN:
4700 case rtx_test::REGNO_FIELD:
4701 case rtx_test::INT_FIELD:
4702 case rtx_test::WIDE_INT_FIELD:
4703 case rtx_test::PATTERN:
4704 print_nonbool_test (os, test);
4705 printf (" %s ", invert_p ? "!=" : "==");
4706 print_label_value (test, is_param, value);
4707 break;
4709 case rtx_test::SUBREG_FIELD:
4710 printf ("%s (", invert_p ? "maybe_ne" : "known_eq");
4711 print_nonbool_test (os, test);
4712 printf (", ");
4713 print_label_value (test, is_param, value);
4714 printf (")");
4715 break;
4717 case rtx_test::SAVED_CONST_INT:
4718 gcc_assert (!is_param && value == 1);
4719 print_test_rtx (os, test);
4720 printf (" %s const_int_rtx[MAX_SAVED_CONST_INT + ",
4721 invert_p ? "!=" : "==");
4722 print_parameter_value (parameter (parameter::INT,
4723 test.u.integer.is_param,
4724 test.u.integer.value));
4725 printf ("]");
4726 break;
4728 case rtx_test::PEEP2_COUNT:
4729 gcc_assert (!is_param && value == 1);
4730 printf ("peep2_current_count %s %d", invert_p ? "<" : ">=",
4731 test.u.min_len);
4732 break;
4734 case rtx_test::VECLEN_GE:
4735 gcc_assert (!is_param && value == 1);
4736 printf ("XVECLEN (");
4737 print_test_rtx (os, test);
4738 printf (", 0) %s %d", invert_p ? "<" : ">=", test.u.min_len);
4739 break;
4741 case rtx_test::PREDICATE:
4742 gcc_assert (!is_param && value == 1);
4743 printf ("%s%s (", invert_p ? "!" : "", test.u.predicate.data->name);
4744 print_test_rtx (os, test);
4745 printf (", ");
4746 print_parameter_value (parameter (parameter::MODE,
4747 test.u.predicate.mode_is_param,
4748 test.u.predicate.mode));
4749 printf (")");
4750 break;
4752 case rtx_test::DUPLICATE:
4753 gcc_assert (!is_param && value == 1);
4754 printf ("%srtx_equal_p (", invert_p ? "!" : "");
4755 print_test_rtx (os, test);
4756 printf (", operands[%d])", test.u.opno);
4757 break;
4759 case rtx_test::HAVE_NUM_CLOBBERS:
4760 gcc_assert (!is_param && value == 1);
4761 printf ("pnum_clobbers %s NULL", invert_p ? "==" : "!=");
4762 break;
4764 case rtx_test::C_TEST:
4765 gcc_assert (!is_param && value == 1);
4766 if (invert_p)
4767 printf ("!");
4768 rtx_reader_ptr->print_c_condition (test.u.string);
4769 break;
4771 case rtx_test::ACCEPT:
4772 case rtx_test::SET_OP:
4773 gcc_unreachable ();
4777 static exit_state print_decision (output_state *, decision *,
4778 unsigned int, bool);
4780 /* Print code to perform S, indent each line by INDENT spaces.
4781 IS_FINAL is true if there are no fallback decisions to test on failure;
4782 if the state fails then the entire routine fails. */
4784 static exit_state
4785 print_state (output_state *os, state *s, unsigned int indent, bool is_final)
4787 exit_state es = ES_FALLTHROUGH;
4788 for (decision *d = s->first; d; d = d->next)
4789 es = print_decision (os, d, indent, is_final && !d->next);
4790 if (es != ES_RETURNED && is_final)
4792 printf_indent (indent, "return %s;\n", get_failure_return (os->type));
4793 es = ES_RETURNED;
4795 return es;
4798 /* Print the code for subroutine call ACCEPTANCE (for which partial_p
4799 is known to be true). Return the C condition that indicates a successful
4800 match. */
4802 static const char *
4803 print_subroutine_call (const acceptance_type &acceptance)
4805 switch (acceptance.type)
4807 case SUBPATTERN:
4808 gcc_unreachable ();
4810 case RECOG:
4811 printf ("recog_%d (x1, insn, pnum_clobbers)",
4812 acceptance.u.subroutine_id);
4813 return ">= 0";
4815 case SPLIT:
4816 printf ("split_%d (x1, insn)", acceptance.u.subroutine_id);
4817 return "!= NULL_RTX";
4819 case PEEPHOLE2:
4820 printf ("peephole2_%d (x1, insn, pmatch_len_)",
4821 acceptance.u.subroutine_id);
4822 return "!= NULL_RTX";
4824 gcc_unreachable ();
4827 /* Print code for the successful match described by ACCEPTANCE.
4828 INDENT and IS_FINAL are as for print_state. */
4830 static exit_state
4831 print_acceptance (const acceptance_type &acceptance, unsigned int indent,
4832 bool is_final)
4834 if (acceptance.partial_p)
4836 /* Defer the rest of the match to a subroutine. */
4837 if (is_final)
4839 printf_indent (indent, "return ");
4840 print_subroutine_call (acceptance);
4841 printf (";\n");
4842 return ES_RETURNED;
4844 else
4846 printf_indent (indent, "res = ");
4847 const char *res_test = print_subroutine_call (acceptance);
4848 printf (";\n");
4849 printf_indent (indent, "if (res %s)\n", res_test);
4850 printf_indent (indent + 2, "return res;\n");
4851 return ES_FALLTHROUGH;
4854 switch (acceptance.type)
4856 case SUBPATTERN:
4857 printf_indent (indent, "return %d;\n", acceptance.u.full.code);
4858 return ES_RETURNED;
4860 case RECOG:
4861 if (acceptance.u.full.u.num_clobbers != 0)
4862 printf_indent (indent, "*pnum_clobbers = %d;\n",
4863 acceptance.u.full.u.num_clobbers);
4864 printf_indent (indent, "return %d; /* %s */\n", acceptance.u.full.code,
4865 get_insn_name (acceptance.u.full.code));
4866 return ES_RETURNED;
4868 case SPLIT:
4869 printf_indent (indent, "return gen_split_%d (insn, operands);\n",
4870 acceptance.u.full.code);
4871 return ES_RETURNED;
4873 case PEEPHOLE2:
4874 printf_indent (indent, "*pmatch_len_ = %d;\n",
4875 acceptance.u.full.u.match_len);
4876 if (is_final)
4878 printf_indent (indent, "return gen_peephole2_%d (insn, operands);\n",
4879 acceptance.u.full.code);
4880 return ES_RETURNED;
4882 else
4884 printf_indent (indent, "res = gen_peephole2_%d (insn, operands);\n",
4885 acceptance.u.full.code);
4886 printf_indent (indent, "if (res != NULL_RTX)\n");
4887 printf_indent (indent + 2, "return res;\n");
4888 return ES_FALLTHROUGH;
4891 gcc_unreachable ();
4894 /* Print code to perform D. INDENT and IS_FINAL are as for print_state. */
4896 static exit_state
4897 print_decision (output_state *os, decision *d, unsigned int indent,
4898 bool is_final)
4900 uint64_t label;
4901 unsigned int base, count;
4903 /* Make sure the rtx under test is available either in operands[] or
4904 in an xN variable. */
4905 if (d->test.pos && d->test.pos_operand < 0)
4906 change_state (os, d->test.pos, indent);
4908 /* Look for cases where a pattern routine P1 calls another pattern routine
4909 P2 and where P1 returns X + BASE whenever P2 returns X. If IS_FINAL
4910 is true and BASE is zero we can simply use:
4912 return patternN (...);
4914 Otherwise we can use:
4916 res = patternN (...);
4917 if (res >= 0)
4918 return res + BASE;
4920 However, if BASE is nonzero and patternN only returns 0 or -1,
4921 the usual "return BASE;" is better than "return res + BASE;".
4922 If BASE is zero, "return res;" should be better than "return 0;",
4923 since no assignment to the return register is required. */
4924 if (os->type == SUBPATTERN
4925 && terminal_pattern_p (d, &base, &count)
4926 && (base == 0 || count > 1))
4928 if (is_final && base == 0)
4930 printf_indent (indent, "return ");
4931 print_nonbool_test (os, d->test);
4932 printf ("; /* [-1, %d] */\n", count - 1);
4933 return ES_RETURNED;
4935 else
4937 printf_indent (indent, "res = ");
4938 print_nonbool_test (os, d->test);
4939 printf (";\n");
4940 printf_indent (indent, "if (res >= 0)\n");
4941 printf_indent (indent + 2, "return res");
4942 if (base != 0)
4943 printf (" + %d", base);
4944 printf ("; /* [%d, %d] */\n", base, base + count - 1);
4945 return ES_FALLTHROUGH;
4948 else if (d->test.kind == rtx_test::ACCEPT)
4949 return print_acceptance (d->test.u.acceptance, indent, is_final);
4950 else if (d->test.kind == rtx_test::SET_OP)
4952 printf_indent (indent, "operands[%d] = ", d->test.u.opno);
4953 print_test_rtx (os, d->test);
4954 printf (";\n");
4955 return print_state (os, d->singleton ()->to, indent, is_final);
4957 /* Handle decisions with a single transition and a single transition
4958 label. */
4959 else if (d->if_statement_p (&label))
4961 transition *trans = d->singleton ();
4962 if (mark_optional_transitions_p && trans->optional)
4963 printf_indent (indent, "/* OPTIONAL IF */\n");
4965 /* Print the condition associated with TRANS. Invert it if IS_FINAL,
4966 so that we return immediately on failure and fall through on
4967 success. */
4968 printf_indent (indent, "if (");
4969 print_test (os, d->test, trans->is_param, label, is_final);
4971 /* Look for following states that would be handled by this code
4972 on recursion. If they don't need any preparatory statements,
4973 include them in the current "if" statement rather than creating
4974 a new one. */
4975 for (;;)
4977 d = trans->to->singleton ();
4978 if (!d
4979 || d->test.kind == rtx_test::ACCEPT
4980 || d->test.kind == rtx_test::SET_OP
4981 || !d->if_statement_p (&label)
4982 || !test_position_available_p (os, d->test))
4983 break;
4984 trans = d->first;
4985 printf ("\n");
4986 if (mark_optional_transitions_p && trans->optional)
4987 printf_indent (indent + 4, "/* OPTIONAL IF */\n");
4988 printf_indent (indent + 4, "%s ", is_final ? "||" : "&&");
4989 print_test (os, d->test, trans->is_param, label, is_final);
4991 printf (")\n");
4993 /* Print the conditional code with INDENT + 2 and the fallthrough
4994 code with indent INDENT. */
4995 state *to = trans->to;
4996 if (is_final)
4998 /* We inverted the condition above, so return failure in the
4999 "if" body and fall through to the target of the transition. */
5000 printf_indent (indent + 2, "return %s;\n",
5001 get_failure_return (os->type));
5002 return print_state (os, to, indent, is_final);
5004 else if (to->singleton ()
5005 && to->first->test.kind == rtx_test::ACCEPT
5006 && single_statement_p (to->first->test.u.acceptance))
5008 /* The target of the transition is a simple "return" statement.
5009 It doesn't need any braces and doesn't fall through. */
5010 if (print_acceptance (to->first->test.u.acceptance,
5011 indent + 2, true) != ES_RETURNED)
5012 gcc_unreachable ();
5013 return ES_FALLTHROUGH;
5015 else
5017 /* The general case. Output code for the target of the transition
5018 in braces. This will not invalidate any of the xN variables
5019 that are already valid, but we mustn't rely on any that are
5020 set by the "if" body. */
5021 auto_vec <bool, 32> old_seen;
5022 old_seen.safe_splice (os->seen_vars);
5024 printf_indent (indent + 2, "{\n");
5025 print_state (os, trans->to, indent + 4, is_final);
5026 printf_indent (indent + 2, "}\n");
5028 os->seen_vars.truncate (0);
5029 os->seen_vars.splice (old_seen);
5030 return ES_FALLTHROUGH;
5033 else
5035 /* Output the decision as a switch statement. */
5036 printf_indent (indent, "switch (");
5037 print_nonbool_test (os, d->test);
5038 printf (")\n");
5040 /* Each case statement starts with the same set of valid variables.
5041 These are also the only variables will be valid on fallthrough. */
5042 auto_vec <bool, 32> old_seen;
5043 old_seen.safe_splice (os->seen_vars);
5045 printf_indent (indent + 2, "{\n");
5046 for (transition *trans = d->first; trans; trans = trans->next)
5048 gcc_assert (!trans->is_param);
5049 if (mark_optional_transitions_p && trans->optional)
5050 printf_indent (indent + 2, "/* OPTIONAL CASE */\n");
5051 for (int_set::iterator j = trans->labels.begin ();
5052 j != trans->labels.end (); ++j)
5054 printf_indent (indent + 2, "case ");
5055 print_label_value (d->test, trans->is_param, *j);
5056 printf (":\n");
5058 if (print_state (os, trans->to, indent + 4, is_final))
5060 /* The state can fall through. Add an explicit break. */
5061 gcc_assert (!is_final);
5062 printf_indent (indent + 4, "break;\n");
5064 printf ("\n");
5066 /* Restore the original set of valid variables. */
5067 os->seen_vars.truncate (0);
5068 os->seen_vars.splice (old_seen);
5070 /* Add a default case. */
5071 printf_indent (indent + 2, "default:\n");
5072 if (is_final)
5073 printf_indent (indent + 4, "return %s;\n",
5074 get_failure_return (os->type));
5075 else
5076 printf_indent (indent + 4, "break;\n");
5077 printf_indent (indent + 2, "}\n");
5078 return is_final ? ES_RETURNED : ES_FALLTHROUGH;
5082 /* Make sure that OS has a position variable for POS. ROOT_P is true if
5083 POS is the root position for the routine. */
5085 static void
5086 assign_position_var (output_state *os, position *pos, bool root_p)
5088 unsigned int idx = os->id_to_var[pos->id];
5089 if (idx < os->var_to_id.length () && os->var_to_id[idx] == pos->id)
5090 return;
5091 if (!root_p && pos->type != POS_PEEP2_INSN)
5092 assign_position_var (os, pos->base, false);
5093 os->id_to_var[pos->id] = os->var_to_id.length ();
5094 os->var_to_id.safe_push (pos->id);
5097 /* Make sure that OS has the position variables required by S. */
5099 static void
5100 assign_position_vars (output_state *os, state *s)
5102 for (decision *d = s->first; d; d = d->next)
5104 /* Positions associated with operands can be read from the
5105 operands[] array. */
5106 if (d->test.pos && d->test.pos_operand < 0)
5107 assign_position_var (os, d->test.pos, false);
5108 for (transition *trans = d->first; trans; trans = trans->next)
5109 assign_position_vars (os, trans->to);
5113 /* Print the open brace and variable definitions for a routine that
5114 implements S. ROOT is the deepest rtx from which S can access all
5115 relevant parts of the first instruction it matches. Initialize OS
5116 so that every relevant position has an rtx variable xN and so that
5117 only ROOT's variable has a valid value. */
5119 static void
5120 print_subroutine_start (output_state *os, state *s, position *root)
5122 printf ("{\n rtx * const operands ATTRIBUTE_UNUSED"
5123 " = &recog_data.operand[0];\n");
5124 os->var_to_id.truncate (0);
5125 os->seen_vars.truncate (0);
5126 if (root)
5128 /* Create a fake entry for position 0 so that an id_to_var of 0
5129 is always invalid. This also makes the xN variables naturally
5130 1-based rather than 0-based. */
5131 os->var_to_id.safe_push (num_positions);
5133 /* Associate ROOT with x1. */
5134 assign_position_var (os, root, true);
5136 /* Assign xN variables to all other relevant positions. */
5137 assign_position_vars (os, s);
5139 /* Output the variable declarations (except for ROOT's, which is
5140 passed in as a parameter). */
5141 unsigned int num_vars = os->var_to_id.length ();
5142 if (num_vars > 2)
5144 for (unsigned int i = 2; i < num_vars; ++i)
5145 /* Print 8 rtx variables to a line. */
5146 printf ("%s x%d",
5147 i == 2 ? " rtx" : (i - 2) % 8 == 0 ? ";\n rtx" : ",", i);
5148 printf (";\n");
5151 /* Say that x1 is valid and the rest aren't. */
5152 os->seen_vars.safe_grow_cleared (num_vars);
5153 os->seen_vars[1] = true;
5155 if (os->type == SUBPATTERN || os->type == RECOG)
5156 printf (" int res ATTRIBUTE_UNUSED;\n");
5157 else
5158 printf (" rtx_insn *res ATTRIBUTE_UNUSED;\n");
5161 /* Output the definition of pattern routine ROUTINE. */
5163 static void
5164 print_pattern (output_state *os, pattern_routine *routine)
5166 printf ("\nstatic int\npattern%d (", routine->pattern_id);
5167 const char *sep = "";
5168 /* Add the top-level rtx parameter, if any. */
5169 if (routine->pos)
5171 printf ("%srtx x1", sep);
5172 sep = ", ";
5174 /* Add the optional parameters. */
5175 if (routine->insn_p)
5177 /* We can't easily tell whether a C condition actually reads INSN,
5178 so add an ATTRIBUTE_UNUSED just in case. */
5179 printf ("%srtx_insn *insn ATTRIBUTE_UNUSED", sep);
5180 sep = ", ";
5182 if (routine->pnum_clobbers_p)
5184 printf ("%sint *pnum_clobbers", sep);
5185 sep = ", ";
5187 /* Add the "i" parameters. */
5188 for (unsigned int i = 0; i < routine->param_types.length (); ++i)
5190 printf ("%s%s i%d", sep,
5191 parameter_type_string (routine->param_types[i]), i + 1);
5192 sep = ", ";
5194 printf (")\n");
5195 os->type = SUBPATTERN;
5196 print_subroutine_start (os, routine->s, routine->pos);
5197 print_state (os, routine->s, 2, true);
5198 printf ("}\n");
5201 /* Output a routine of type TYPE that implements S. PROC_ID is the
5202 number of the subroutine associated with S, or 0 if S is the main
5203 routine. */
5205 static void
5206 print_subroutine (output_state *os, state *s, int proc_id)
5208 printf ("\n");
5209 switch (os->type)
5211 case SUBPATTERN:
5212 gcc_unreachable ();
5214 case RECOG:
5215 if (proc_id)
5216 printf ("static int\nrecog_%d", proc_id);
5217 else
5218 printf ("int\nrecog");
5219 printf (" (rtx x1 ATTRIBUTE_UNUSED,\n"
5220 "\trtx_insn *insn ATTRIBUTE_UNUSED,\n"
5221 "\tint *pnum_clobbers ATTRIBUTE_UNUSED)\n");
5222 break;
5224 case SPLIT:
5225 if (proc_id)
5226 printf ("static rtx_insn *\nsplit_%d", proc_id);
5227 else
5228 printf ("rtx_insn *\nsplit_insns");
5229 printf (" (rtx x1 ATTRIBUTE_UNUSED, rtx_insn *insn ATTRIBUTE_UNUSED)\n");
5230 break;
5232 case PEEPHOLE2:
5233 if (proc_id)
5234 printf ("static rtx_insn *\npeephole2_%d", proc_id);
5235 else
5236 printf ("rtx_insn *\npeephole2_insns");
5237 printf (" (rtx x1 ATTRIBUTE_UNUSED,\n"
5238 "\trtx_insn *insn ATTRIBUTE_UNUSED,\n"
5239 "\tint *pmatch_len_ ATTRIBUTE_UNUSED)\n");
5240 break;
5242 print_subroutine_start (os, s, &root_pos);
5243 if (proc_id == 0)
5245 printf (" recog_data.insn = NULL;\n");
5247 print_state (os, s, 2, true);
5248 printf ("}\n");
5251 /* Print out a routine of type TYPE that performs ROOT. */
5253 static void
5254 print_subroutine_group (output_state *os, routine_type type, state *root)
5256 os->type = type;
5257 if (use_subroutines_p)
5259 /* Split ROOT up into smaller pieces, both for readability and to
5260 help the compiler. */
5261 auto_vec <state *> subroutines;
5262 find_subroutines (type, root, subroutines);
5264 /* Output the subroutines (but not ROOT itself). */
5265 unsigned int i;
5266 state *s;
5267 FOR_EACH_VEC_ELT (subroutines, i, s)
5268 print_subroutine (os, s, i + 1);
5270 /* Output the main routine. */
5271 print_subroutine (os, root, 0);
5274 /* Return the rtx pattern for the list of rtxes in a define_peephole2. */
5276 static rtx
5277 get_peephole2_pattern (md_rtx_info *info)
5279 int i, j;
5280 rtvec vec = XVEC (info->def, 0);
5281 rtx pattern = rtx_alloc (SEQUENCE);
5282 XVEC (pattern, 0) = rtvec_alloc (GET_NUM_ELEM (vec));
5283 for (i = j = 0; i < GET_NUM_ELEM (vec); i++)
5285 rtx x = RTVEC_ELT (vec, i);
5286 /* Ignore scratch register requirements. */
5287 if (GET_CODE (x) != MATCH_SCRATCH && GET_CODE (x) != MATCH_DUP)
5289 XVECEXP (pattern, 0, j) = x;
5290 j++;
5293 XVECLEN (pattern, 0) = j;
5294 if (j == 0)
5295 error_at (info->loc, "empty define_peephole2");
5296 return pattern;
5299 /* Return true if *PATTERN_PTR is a PARALLEL in which at least one trailing
5300 rtx can be added automatically by add_clobbers. If so, update
5301 *ACCEPTANCE_PTR so that its num_clobbers field contains the number
5302 of such trailing rtxes and update *PATTERN_PTR so that it contains
5303 the pattern without those rtxes. */
5305 static bool
5306 remove_clobbers (acceptance_type *acceptance_ptr, rtx *pattern_ptr)
5308 int i;
5309 rtx new_pattern;
5311 /* Find the last non-clobber in the parallel. */
5312 rtx pattern = *pattern_ptr;
5313 for (i = XVECLEN (pattern, 0); i > 0; i--)
5315 rtx x = XVECEXP (pattern, 0, i - 1);
5316 if ((GET_CODE (x) != CLOBBER && GET_CODE (x) != CLOBBER_HIGH)
5317 || (!REG_P (XEXP (x, 0))
5318 && GET_CODE (XEXP (x, 0)) != MATCH_SCRATCH))
5319 break;
5322 if (i == XVECLEN (pattern, 0))
5323 return false;
5325 /* Build a similar insn without the clobbers. */
5326 if (i == 1)
5327 new_pattern = XVECEXP (pattern, 0, 0);
5328 else
5330 new_pattern = rtx_alloc (PARALLEL);
5331 XVEC (new_pattern, 0) = rtvec_alloc (i);
5332 for (int j = 0; j < i; ++j)
5333 XVECEXP (new_pattern, 0, j) = XVECEXP (pattern, 0, j);
5336 /* Recognize it. */
5337 acceptance_ptr->u.full.u.num_clobbers = XVECLEN (pattern, 0) - i;
5338 *pattern_ptr = new_pattern;
5339 return true;
5343 main (int argc, const char **argv)
5345 state insn_root, split_root, peephole2_root;
5347 progname = "genrecog";
5349 if (!init_rtx_reader_args (argc, argv))
5350 return (FATAL_EXIT_CODE);
5352 write_header ();
5354 /* Read the machine description. */
5356 md_rtx_info info;
5357 while (read_md_rtx (&info))
5359 rtx def = info.def;
5361 acceptance_type acceptance;
5362 acceptance.partial_p = false;
5363 acceptance.u.full.code = info.index;
5365 rtx pattern;
5366 switch (GET_CODE (def))
5368 case DEFINE_INSN:
5370 /* Match the instruction in the original .md form. */
5371 acceptance.type = RECOG;
5372 acceptance.u.full.u.num_clobbers = 0;
5373 pattern = add_implicit_parallel (XVEC (def, 1));
5374 validate_pattern (pattern, &info, NULL_RTX, 0);
5375 match_pattern (&insn_root, &info, pattern, acceptance);
5377 /* If the pattern is a PARALLEL with trailing CLOBBERs,
5378 allow recog_for_combine to match without the clobbers. */
5379 if (GET_CODE (pattern) == PARALLEL
5380 && remove_clobbers (&acceptance, &pattern))
5381 match_pattern (&insn_root, &info, pattern, acceptance);
5382 break;
5385 case DEFINE_SPLIT:
5386 acceptance.type = SPLIT;
5387 pattern = add_implicit_parallel (XVEC (def, 0));
5388 validate_pattern (pattern, &info, NULL_RTX, 0);
5389 match_pattern (&split_root, &info, pattern, acceptance);
5391 /* Declare the gen_split routine that we'll call if the
5392 pattern matches. The definition comes from insn-emit.c. */
5393 printf ("extern rtx_insn *gen_split_%d (rtx_insn *, rtx *);\n",
5394 info.index);
5395 break;
5397 case DEFINE_PEEPHOLE2:
5398 acceptance.type = PEEPHOLE2;
5399 pattern = get_peephole2_pattern (&info);
5400 validate_pattern (pattern, &info, NULL_RTX, 0);
5401 match_pattern (&peephole2_root, &info, pattern, acceptance);
5403 /* Declare the gen_peephole2 routine that we'll call if the
5404 pattern matches. The definition comes from insn-emit.c. */
5405 printf ("extern rtx_insn *gen_peephole2_%d (rtx_insn *, rtx *);\n",
5406 info.index);
5407 break;
5409 default:
5410 /* do nothing */;
5414 if (have_error)
5415 return FATAL_EXIT_CODE;
5417 puts ("\n\n");
5419 /* Optimize each routine in turn. */
5420 optimize_subroutine_group ("recog", &insn_root);
5421 optimize_subroutine_group ("split_insns", &split_root);
5422 optimize_subroutine_group ("peephole2_insns", &peephole2_root);
5424 output_state os;
5425 os.id_to_var.safe_grow_cleared (num_positions);
5427 if (use_pattern_routines_p)
5429 /* Look for common patterns and split them out into subroutines. */
5430 auto_vec <merge_state_info> states;
5431 states.safe_push (&insn_root);
5432 states.safe_push (&split_root);
5433 states.safe_push (&peephole2_root);
5434 split_out_patterns (states);
5436 /* Print out the routines that we just created. */
5437 unsigned int i;
5438 pattern_routine *routine;
5439 FOR_EACH_VEC_ELT (patterns, i, routine)
5440 print_pattern (&os, routine);
5443 /* Print out the matching routines. */
5444 print_subroutine_group (&os, RECOG, &insn_root);
5445 print_subroutine_group (&os, SPLIT, &split_root);
5446 print_subroutine_group (&os, PEEPHOLE2, &peephole2_root);
5448 fflush (stdout);
5449 return (ferror (stdout) != 0 ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE);