]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/genrecog.c
PR c++/87554 - ICE with extern template and reference member.
[thirdparty/gcc.git] / gcc / genrecog.c
CommitLineData
263287f7 1/* Generate code from machine description to recognize rtl as insns.
fbd26352 2 Copyright (C) 1987-2019 Free Software Foundation, Inc.
263287f7 3
f12b58b3 4 This file is part of GCC.
6d69ff19 5
f12b58b3 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
8c4c00c1 8 the Free Software Foundation; either version 3, or (at your option)
6d69ff19 9 any later version.
10
f12b58b3 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.
6d69ff19 15
16 You should have received a copy of the GNU General Public License
8c4c00c1 17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
6d69ff19 19
20
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.
25
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).
32
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
263287f7 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
6d69ff19 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.
263287f7 41
6d69ff19 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
31d3e01c 44 rtl as an INSN list.
6d69ff19 45
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,
31d3e01c 48 the new rtl is returned in an INSN list, and LAST_INSN will point
59250a8d 49 to the last recognized insn in the old sequence.
50
51
52 At a high level, the algorithm used in this file is as follows:
53
54 1. Build up a decision tree for each routine, using the following
55 approach to matching an rtx:
56
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.
62
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.
67
68 - Next check match_dups.
69
70 - Finally check the C condition and (where appropriate) pnum_clobbers.
71
72 2. Try to optimize the tree by removing redundant tests, CSEing tests,
73 folding tests together, etc.
74
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:
81
82 (plus:SI (match_operand:SI 1 "register_operand")
83 (match_operand:SI 2 "register_operand"))
84
85 we can split the associated matching code out into a subroutine.
86 If a pattern contains:
87
88 (minus:DI (match_operand:DI 1 "register_operand")
89 (match_operand:DI 2 "register_operand"))
90
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.
94
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.
98
99 4. Split the matching trees into functions, trying to limit the
100 size of each function to a sensible amount.
101
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.)
104
105 5. Write out C++ code for each function. */
263287f7 106
805e22b2 107#include "bconfig.h"
802ba5cb 108#define INCLUDE_ALGORITHM
5ce88198 109#include "system.h"
805e22b2 110#include "coretypes.h"
111#include "tm.h"
263287f7 112#include "rtl.h"
04b58880 113#include "errors.h"
960ebfe7 114#include "read-md.h"
c5ddd6b5 115#include "gensupport.h"
59250a8d 116
117#undef GENERATOR_FILE
118enum 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
123};
124#define NUM_TRUE_RTX_CODE ((int) FIRST_GENERATOR_RTX_CODE)
125#define GENERATOR_FILE 1
126
127/* Debugging variables to control which optimizations are performed.
128 Note that disabling merge_states_p leads to very large output. */
129static const bool merge_states_p = true;
130static const bool collapse_optional_decisions_p = true;
131static const bool cse_tests_p = true;
132static const bool simplify_tests_p = true;
133static const bool use_operand_variables_p = true;
134static const bool use_subroutines_p = true;
135static const bool use_pattern_routines_p = true;
136
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. */
140static const bool mark_optional_transitions_p = false;
141
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.
146
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. */
151static const bool relative_patterns_p = false;
152
153/* Whether pattern routines should be allowed to test whether pnum_clobbers
154 is null. This requires passing pnum_clobbers around as a parameter. */
155static const bool pattern_have_num_clobbers_p = true;
156
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. */
161static const bool pattern_c_test_p = false;
162
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. */
168static const bool force_unique_params_p = true;
169
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. */
00788409 173static const unsigned int MAX_DEPTH = 6;
59250a8d 174
175/* The minimum number of pseudo-statements that a state must have before
176 we split it out into a subroutine. */
00788409 177static const unsigned int MIN_NUM_STATEMENTS = 5;
59250a8d 178
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.). */
00788409 183static const unsigned int MAX_NUM_STATEMENTS = 200;
59250a8d 184
185/* The minimum number of pseudo-statements that can be used in a pattern
186 routine. */
187static const unsigned int MIN_COMBINE_COST = 4;
188
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. */
193static const unsigned int MAX_PATTERN_PARAMS = 5;
194
195/* The maximum operand number plus one. */
196int num_operands;
41e80e4b 197
2494d261 198/* Ways of obtaining an rtx to be tested. */
199enum position_type {
200 /* PATTERN (peep2_next_insn (ARG)). */
201 POS_PEEP2_INSN,
202
203 /* XEXP (BASE, ARG). */
204 POS_XEXP,
205
206 /* XVECEXP (BASE, 0, ARG). */
207 POS_XVECEXP0
208};
209
210/* The position of an rtx relative to X0. Each useful position is
211 represented by exactly one instance of this structure. */
212struct position
213{
214 /* The parent rtx. This is the root position for POS_PEEP2_INSNs. */
215 struct position *base;
216
217 /* A position with the same BASE and TYPE, but with the next value
218 of ARG. */
219 struct position *next;
220
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;
225
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;
230
231 /* The type of position. */
232 enum position_type type;
233
234 /* The argument to TYPE (shown as ARG in the position_type comments). */
235 int arg;
236
59250a8d 237 /* The instruction to which the position belongs. */
238 unsigned int insn_id;
a698628e 239
59250a8d 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;
263287f7 244
59250a8d 245 /* A unique identifier for this position. */
246 unsigned int id;
263287f7 247};
248
6d69ff19 249enum routine_type {
59250a8d 250 SUBPATTERN, RECOG, SPLIT, PEEPHOLE2
6d69ff19 251};
82575fa7 252
2494d261 253/* The root position (x0). */
254static struct position root_pos;
255
59250a8d 256/* The number of positions created. Also one higher than the maximum
257 position id. */
258static unsigned int num_positions = 1;
259
2494d261 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. */
262static struct position *peep2_insn_pos_list = &root_pos;
cbf464bd 263\f
2494d261 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. */
268
269static struct position *
270next_position (struct position **next_ptr, struct position *base,
271 enum position_type type, int arg)
272{
273 struct position *pos;
274
275 pos = *next_ptr;
276 if (!pos)
277 {
278 pos = XCNEW (struct position);
2494d261 279 pos->type = type;
280 pos->arg = arg;
59250a8d 281 if (type == POS_PEEP2_INSN)
282 {
283 pos->base = 0;
284 pos->insn_id = arg;
285 pos->depth = base->depth;
286 }
287 else
288 {
289 pos->base = base;
290 pos->insn_id = base->insn_id;
291 pos->depth = base->depth + 1;
292 }
293 pos->id = num_positions++;
2494d261 294 *next_ptr = pos;
295 }
296 return pos;
297}
298
299/* Compare positions POS1 and POS2 lexicographically. */
300
301static int
302compare_positions (struct position *pos1, struct position *pos2)
303{
304 int diff;
305
306 diff = pos1->depth - pos2->depth;
307 if (diff < 0)
308 do
309 pos2 = pos2->base;
310 while (pos1->depth != pos2->depth);
311 else if (diff > 0)
312 do
313 pos1 = pos1->base;
314 while (pos1->depth != pos2->depth);
315 while (pos1 != pos2)
316 {
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;
322 }
323 return diff;
324}
325
59250a8d 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. */
263287f7 329
59250a8d 330static struct position *
331common_position (struct position *pos1, struct position *pos2)
6d69ff19 332{
59250a8d 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)
340 {
341 pos1 = pos1->base;
342 pos2 = pos2->base;
343 }
344 return pos1;
a698628e 345}
59250a8d 346\f
f82dbd66 347/* Search for and return operand N, stop when reaching node STOP. */
3a074b0f 348
349static rtx
f82dbd66 350find_operand (rtx pattern, int n, rtx stop)
3a074b0f 351{
352 const char *fmt;
353 RTX_CODE code;
354 int i, j, len;
355 rtx r;
356
f82dbd66 357 if (pattern == stop)
358 return stop;
359
3a074b0f 360 code = GET_CODE (pattern);
361 if ((code == MATCH_SCRATCH
3a074b0f 362 || code == MATCH_OPERAND
363 || code == MATCH_OPERATOR
364 || code == MATCH_PARALLEL)
365 && XINT (pattern, 0) == n)
366 return pattern;
367
368 fmt = GET_RTX_FORMAT (code);
369 len = GET_RTX_LENGTH (code);
370 for (i = 0; i < len; i++)
371 {
372 switch (fmt[i])
373 {
374 case 'e': case 'u':
f82dbd66 375 if ((r = find_operand (XEXP (pattern, i), n, stop)) != NULL_RTX)
3a074b0f 376 return r;
377 break;
378
386d0079 379 case 'V':
380 if (! XVEC (pattern, i))
381 break;
d632b59a 382 /* Fall through. */
386d0079 383
3a074b0f 384 case 'E':
385 for (j = 0; j < XVECLEN (pattern, i); j++)
f82dbd66 386 if ((r = find_operand (XVECEXP (pattern, i, j), n, stop))
387 != NULL_RTX)
3a074b0f 388 return r;
389 break;
390
9edf7ea8 391 case 'r': case 'p': case 'i': case 'w': case '0': case 's':
3a074b0f 392 break;
393
394 default:
e0a4c0c2 395 gcc_unreachable ();
3a074b0f 396 }
397 }
398
399 return NULL;
400}
401
386d0079 402/* Search for and return operand M, such that it has a matching
403 constraint for operand N. */
404
405static rtx
1a97be37 406find_matching_operand (rtx pattern, int n)
386d0079 407{
408 const char *fmt;
409 RTX_CODE code;
410 int i, j, len;
411 rtx r;
412
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;
419
420 fmt = GET_RTX_FORMAT (code);
421 len = GET_RTX_LENGTH (code);
422 for (i = 0; i < len; i++)
423 {
424 switch (fmt[i])
425 {
426 case 'e': case 'u':
427 if ((r = find_matching_operand (XEXP (pattern, i), n)))
428 return r;
429 break;
430
431 case 'V':
432 if (! XVEC (pattern, i))
433 break;
d632b59a 434 /* Fall through. */
386d0079 435
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;
441
9edf7ea8 442 case 'r': case 'p': case 'i': case 'w': case '0': case 's':
386d0079 443 break;
444
445 default:
e0a4c0c2 446 gcc_unreachable ();
386d0079 447 }
448 }
449
450 return NULL;
451}
452
ffcd6b16 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. */
457
458static bool
459constraints_supported_in_insn_p (rtx insn)
460{
461 return !(GET_CODE (insn) == DEFINE_EXPAND
462 || GET_CODE (insn) == DEFINE_SPLIT
463 || GET_CODE (insn) == DEFINE_PEEPHOLE2);
464}
386d0079 465
7a23db96 466/* Return the name of the predicate matched by MATCH_RTX. */
467
468static const char *
469predicate_name (rtx match_rtx)
470{
471 if (GET_CODE (match_rtx) == MATCH_SCRATCH)
472 return "scratch_operand";
473 else
474 return XSTR (match_rtx, 1);
475}
476
477/* Return true if OPERAND is a MATCH_OPERAND using a special predicate
478 function. */
479
480static bool
481special_predicate_operand_p (rtx operand)
482{
483 if (GET_CODE (operand) == MATCH_OPERAND)
484 {
485 const char *pred_name = predicate_name (operand);
486 if (pred_name[0] != 0)
487 {
488 const struct pred_data *pred;
489
490 pred = lookup_predicate (pred_name);
491 return pred != NULL && pred->special;
492 }
493 }
494
495 return false;
496}
497
c04601c1 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. */
0922b1b8 502
503static void
c04601c1 504validate_pattern (rtx pattern, md_rtx_info *info, rtx set, int set_code)
0922b1b8 505{
506 const char *fmt;
507 RTX_CODE code;
3a074b0f 508 size_t i, len;
509 int j;
0922b1b8 510
511 code = GET_CODE (pattern);
512 switch (code)
513 {
514 case MATCH_SCRATCH:
ffcd6b16 515 {
516 const char constraints0 = XSTR (pattern, 1)[0];
517
c04601c1 518 if (!constraints_supported_in_insn_p (info->def))
ffcd6b16 519 {
520 if (constraints0)
521 {
c04601c1 522 error_at (info->loc, "constraints not supported in %s",
523 GET_RTX_NAME (GET_CODE (info->def)));
ffcd6b16 524 }
525 return;
526 }
527
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 == '='
0993e186 531 && constraints0
ffcd6b16 532 && constraints0 != '='
533 && constraints0 != '+')
534 {
c04601c1 535 error_at (info->loc, "operand %d missing output reload",
536 XINT (pattern, 0));
ffcd6b16 537 }
538 return;
539 }
f82dbd66 540 case MATCH_DUP:
541 case MATCH_OP_DUP:
542 case MATCH_PAR_DUP:
c04601c1 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));
f82dbd66 546 break;
0922b1b8 547 case MATCH_OPERAND:
3a074b0f 548 case MATCH_OPERATOR:
0922b1b8 549 {
550 const char *pred_name = XSTR (pattern, 1);
cbf464bd 551 const struct pred_data *pred;
3a074b0f 552 const char *c_test;
553
7c1b1064 554 c_test = get_c_test (info->def);
0922b1b8 555
556 if (pred_name[0] != 0)
557 {
cbf464bd 558 pred = lookup_predicate (pred_name);
559 if (!pred)
c04601c1 560 error_at (info->loc, "unknown predicate '%s'", pred_name);
3a074b0f 561 }
cbf464bd 562 else
563 pred = 0;
3a074b0f 564
ad9465d6 565 if (code == MATCH_OPERAND)
4747a74c 566 {
f1a7e25b 567 const char *constraints = XSTR (pattern, 2);
568 const char constraints0 = constraints[0];
ad9465d6 569
c04601c1 570 if (!constraints_supported_in_insn_p (info->def))
d55ea929 571 {
ad9465d6 572 if (constraints0)
ffcd6b16 573 {
c04601c1 574 error_at (info->loc, "constraints not supported in %s",
575 GET_RTX_NAME (GET_CODE (info->def)));
ffcd6b16 576 }
ad9465d6 577 }
1a97be37 578
ad9465d6 579 /* A MATCH_OPERAND that is a SET should have an output reload. */
580 else if (set && constraints0)
581 {
582 if (set_code == '+')
583 {
584 if (constraints0 == '+')
585 ;
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 == '='
c04601c1 589 && find_matching_operand (info->def,
590 XINT (pattern, 0)))
ad9465d6 591 ;
592 else
c04601c1 593 error_at (info->loc, "operand %d missing in-out reload",
594 XINT (pattern, 0));
386d0079 595 }
b638f5c8 596 else if (constraints0 != '=' && constraints0 != '+')
c04601c1 597 error_at (info->loc, "operand %d missing output reload",
598 XINT (pattern, 0));
d55ea929 599 }
f1a7e25b 600
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)
605 {
606 while (constraints[0]
607 && (constraints[0] == ' ' || constraints[0] == ','))
608 constraints++;
609 if (!constraints[0])
610 break;
611
612 if (constraints[0] >= '0' && constraints[0] <= '9')
613 {
614 int val;
615
616 sscanf (constraints, "%d", &val);
617 if (val >= XINT (pattern, 0))
c04601c1 618 error_at (info->loc, "constraint digit %d is not"
619 " smaller than operand %d",
620 val, XINT (pattern, 0));
f1a7e25b 621 }
622
623 while (constraints[0] && constraints[0] != ',')
624 constraints++;
625 }
4747a74c 626 }
627
3a074b0f 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. */
cbf464bd 631 if (set && pred && pred->allows_non_lvalue)
c04601c1 632 error_at (info->loc, "destination operand %d allows non-lvalue",
633 XINT (pattern, 0));
3a074b0f 634
cbf464bd 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. */
3a074b0f 642
643 if (GET_MODE (pattern) == VOIDmode
644 && code == MATCH_OPERAND
c04601c1 645 && GET_CODE (info->def) == DEFINE_INSN
cbf464bd 646 && pred
647 && !pred->special
648 && pred->allows_non_const
4747a74c 649 && strstr (c_test, "operands") == NULL
650 && ! (set
651 && GET_CODE (set) == SET
652 && GET_CODE (SET_SRC (set)) == CALL))
c04601c1 653 message_at (info->loc, "warning: operand %d missing mode?",
654 XINT (pattern, 0));
0922b1b8 655 return;
656 }
657
658 case SET:
3a074b0f 659 {
3754d046 660 machine_mode dmode, smode;
3a074b0f 661 rtx dest, src;
662
663 dest = SET_DEST (pattern);
664 src = SET_SRC (pattern);
665
ad9465d6 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);
670
40e55fbb 671 /* Find the referent for a DUP. */
3a074b0f 672
673 if (GET_CODE (dest) == MATCH_DUP
674 || GET_CODE (dest) == MATCH_OP_DUP
675 || GET_CODE (dest) == MATCH_PAR_DUP)
c04601c1 676 dest = find_operand (info->def, XINT (dest, 0), NULL);
3a074b0f 677
678 if (GET_CODE (src) == MATCH_DUP
679 || GET_CODE (src) == MATCH_OP_DUP
680 || GET_CODE (src) == MATCH_PAR_DUP)
c04601c1 681 src = find_operand (info->def, XINT (src, 0), NULL);
3a074b0f 682
3a074b0f 683 dmode = GET_MODE (dest);
684 smode = GET_MODE (src);
0922b1b8 685
7a23db96 686 /* Mode checking is not performed for special predicates. */
687 if (special_predicate_operand_p (src)
688 || special_predicate_operand_p (dest))
3a074b0f 689 ;
690
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)
c04601c1 694 error_at (info->loc, "mode mismatch in set: %smode vs %smode",
695 GET_MODE_NAME (dmode), GET_MODE_NAME (smode));
3a074b0f 696
fcb53c1e 697 /* If only one of the operands is VOIDmode, and PC or CC0 is
3a074b0f 698 not involved, it's probably a mistake. */
699 else if (dmode != smode
700 && GET_CODE (dest) != PC
701 && GET_CODE (dest) != CC0
4747a74c 702 && GET_CODE (src) != PC
703 && GET_CODE (src) != CC0
971ba038 704 && !CONST_INT_P (src)
219f3246 705 && !CONST_WIDE_INT_P (src)
84e907aa 706 && GET_CODE (src) != CALL)
3a074b0f 707 {
708 const char *which;
709 which = (dmode == VOIDmode ? "destination" : "source");
c04601c1 710 message_at (info->loc, "warning: %s missing a mode?", which);
3a074b0f 711 }
712
713 if (dest != SET_DEST (pattern))
c04601c1 714 validate_pattern (dest, info, pattern, '=');
715 validate_pattern (SET_DEST (pattern), info, pattern, '=');
716 validate_pattern (SET_SRC (pattern), info, NULL_RTX, 0);
3a074b0f 717 return;
718 }
719
720 case CLOBBER:
ccd6679f 721 case CLOBBER_HIGH:
c04601c1 722 validate_pattern (SET_DEST (pattern), info, pattern, '=');
d55ea929 723 return;
724
725 case ZERO_EXTRACT:
c04601c1 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);
d55ea929 729 return;
730
731 case STRICT_LOW_PART:
c04601c1 732 validate_pattern (XEXP (pattern, 0), info, set, set ? '+' : 0);
0922b1b8 733 return;
3a074b0f 734
0922b1b8 735 case LABEL_REF:
c7799456 736 if (GET_MODE (XEXP (pattern, 0)) != VOIDmode)
c04601c1 737 error_at (info->loc, "operand to label_ref %smode not VOIDmode",
c7799456 738 GET_MODE_NAME (GET_MODE (XEXP (pattern, 0))));
0922b1b8 739 break;
740
9b067f04 741 case VEC_SELECT:
742 if (GET_MODE (pattern) != VOIDmode)
743 {
582adad1 744 machine_mode mode = GET_MODE (pattern);
745 machine_mode imode = GET_MODE (XEXP (pattern, 0));
746 machine_mode emode
9b067f04 747 = VECTOR_MODE_P (mode) ? GET_MODE_INNER (mode) : mode;
748 if (GET_CODE (XEXP (pattern, 1)) == PARALLEL)
749 {
ba7efd65 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)
9b067f04 758 error_at (info->loc,
759 "vec_select parallel with %d elements, expected %d",
760 XVECLEN (XEXP (pattern, 1), 0), expected);
ba7efd65 761 else if (VECTOR_MODE_P (imode)
762 && GET_MODE_NUNITS (imode).is_constant (&nelems))
ddd399ff 763 {
ddd399ff 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);
775 }
9b067f04 776 }
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)));
785 }
786 break;
787
0922b1b8 788 default:
789 break;
790 }
791
792 fmt = GET_RTX_FORMAT (code);
793 len = GET_RTX_LENGTH (code);
794 for (i = 0; i < len; i++)
795 {
796 switch (fmt[i])
797 {
798 case 'e': case 'u':
c04601c1 799 validate_pattern (XEXP (pattern, i), info, NULL_RTX, 0);
0922b1b8 800 break;
801
802 case 'E':
803 for (j = 0; j < XVECLEN (pattern, i); j++)
c04601c1 804 validate_pattern (XVECEXP (pattern, i, j), info, NULL_RTX, 0);
0922b1b8 805 break;
806
9edf7ea8 807 case 'r': case 'p': case 'i': case 'w': case '0': case 's':
0922b1b8 808 break;
809
810 default:
e0a4c0c2 811 gcc_unreachable ();
0922b1b8 812 }
813 }
0922b1b8 814}
59250a8d 815\f
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. */
820template <typename T>
821struct list_head
263287f7 822{
59250a8d 823 /* A range of linked items. */
824 struct range
825 {
826 range (T *);
827 range (T *, T *);
263287f7 828
59250a8d 829 T *start, *end;
830 void set_parent (list_head *);
831 };
263287f7 832
59250a8d 833 list_head ();
834 range release ();
835 void push_back (range);
836 range remove (range);
837 void replace (range, range);
838 T *singleton () const;
263287f7 839
59250a8d 840 T *first, *last;
841};
263287f7 842
59250a8d 843/* Create a range [START_IN, START_IN]. */
393d701f 844
59250a8d 845template <typename T>
846list_head <T>::range::range (T *start_in) : start (start_in), end (start_in) {}
82575fa7 847
59250a8d 848/* Create a range [START_IN, END_IN], linked by next and prev fields. */
6d69ff19 849
59250a8d 850template <typename T>
851list_head <T>::range::range (T *start_in, T *end_in)
852 : start (start_in), end (end_in) {}
6d69ff19 853
59250a8d 854template <typename T>
855void
856list_head <T>::range::set_parent (list_head <T> *owner)
857{
858 for (T *item = start; item != end; item = item->next)
859 item->set_parent (owner);
860 end->set_parent (owner);
861}
35b0bfe2 862
59250a8d 863template <typename T>
864list_head <T>::list_head () : first (0), last (0) {}
6d69ff19 865
59250a8d 866/* Add R to the end of the list. */
6d69ff19 867
59250a8d 868template <typename T>
869void
870list_head <T>::push_back (range r)
871{
872 if (last)
873 last->next = r.start;
874 else
875 first = r.start;
876 r.start->prev = last;
877 last = r.end;
878 r.set_parent (this);
879}
cbf464bd 880
59250a8d 881/* Remove R from the list. R remains valid and can be inserted into
882 other lists. */
6d69ff19 883
59250a8d 884template <typename T>
885typename list_head <T>::range
886list_head <T>::remove (range r)
887{
888 if (r.start->prev)
889 r.start->prev->next = r.end->next;
890 else
891 first = r.end->next;
892 if (r.end->next)
893 r.end->next->prev = r.start->prev;
894 else
895 last = r.start->prev;
896 r.start->prev = 0;
897 r.end->next = 0;
898 r.set_parent (0);
899 return r;
900}
a698628e 901
59250a8d 902/* Replace OLDR with NEWR. OLDR remains valid and can be inserted into
903 other lists. */
940b9cea 904
59250a8d 905template <typename T>
906void
907list_head <T>::replace (range oldr, range newr)
908{
909 newr.start->prev = oldr.start->prev;
910 newr.end->next = oldr.end->next;
a698628e 911
59250a8d 912 oldr.start->prev = 0;
913 oldr.end->next = 0;
914 oldr.set_parent (0);
a698628e 915
59250a8d 916 if (newr.start->prev)
917 newr.start->prev->next = newr.start;
918 else
919 first = newr.start;
920 if (newr.end->next)
921 newr.end->next->prev = newr.end;
922 else
923 last = newr.end;
924 newr.set_parent (this);
925}
263287f7 926
59250a8d 927/* Empty the list and return the previous contents as a range that can
928 be inserted into other lists. */
6d69ff19 929
59250a8d 930template <typename T>
931typename list_head <T>::range
932list_head <T>::release ()
933{
934 range r (first, last);
935 first = 0;
936 last = 0;
937 r.set_parent (0);
938 return r;
939}
6d69ff19 940
59250a8d 941/* If the list contains a single item, return that item, otherwise return
942 null. */
6d69ff19 943
59250a8d 944template <typename T>
945T *
946list_head <T>::singleton () const
947{
948 return first == last ? first : 0;
949}
950\f
951struct state;
263287f7 952
59250a8d 953/* Describes a possible successful return from a routine. */
954struct acceptance_type
955{
956 /* The type of routine we're returning from. */
957 routine_type type : 16;
6d69ff19 958
59250a8d 959 /* True if this structure only really represents a partial match,
960 and if we must call a subroutine of type TYPE to complete the match.
961 In this case we'll call the subroutine and, if it succeeds, return
962 whatever the subroutine returned.
263287f7 963
59250a8d 964 False if this structure presents a full match. */
965 unsigned int partial_p : 1;
263287f7 966
59250a8d 967 union
968 {
969 /* If PARTIAL_P, this is the number of the subroutine to call. */
970 int subroutine_id;
6d69ff19 971
59250a8d 972 /* Valid if !PARTIAL_P. */
973 struct
263287f7 974 {
59250a8d 975 /* The identifier of the matching pattern. For SUBPATTERNs this
976 value belongs to an ad-hoc routine-specific enum. For the
977 others it's the number of an .md file pattern. */
978 int code;
979 union
980 {
981 /* For RECOG, the number of clobbers that must be added to the
982 pattern in order for it to match CODE. */
983 int num_clobbers;
984
985 /* For PEEPHOLE2, the number of additional instructions that were
986 included in the optimization. */
987 int match_len;
988 } u;
989 } full;
990 } u;
991};
fb16c776 992
59250a8d 993bool
994operator == (const acceptance_type &a, const acceptance_type &b)
995{
996 if (a.partial_p != b.partial_p)
997 return false;
998 if (a.partial_p)
999 return a.u.subroutine_id == b.u.subroutine_id;
1000 else
1001 return a.u.full.code == b.u.full.code;
1002}
3164740a 1003
59250a8d 1004bool
1005operator != (const acceptance_type &a, const acceptance_type &b)
1006{
1007 return !operator == (a, b);
1008}
6d69ff19 1009
59250a8d 1010/* Represents a parameter to a pattern routine. */
1011struct parameter
1012{
1013 /* The C type of parameter. */
1014 enum type_enum {
1015 /* Represents an invalid parameter. */
1016 UNSET,
6d69ff19 1017
59250a8d 1018 /* A machine_mode parameter. */
1019 MODE,
6d69ff19 1020
59250a8d 1021 /* An rtx_code parameter. */
1022 CODE,
6d69ff19 1023
59250a8d 1024 /* An int parameter. */
1025 INT,
2494d261 1026
15183fd2 1027 /* An unsigned int parameter. */
1028 UINT,
1029
59250a8d 1030 /* A HOST_WIDE_INT parameter. */
1031 WIDE_INT
1032 };
6d69ff19 1033
59250a8d 1034 parameter ();
1035 parameter (type_enum, bool, uint64_t);
6d69ff19 1036
59250a8d 1037 /* The type of the parameter. */
1038 type_enum type;
6d69ff19 1039
59250a8d 1040 /* True if the value passed is variable, false if it is constant. */
1041 bool is_param;
6d69ff19 1042
59250a8d 1043 /* If IS_PARAM, this is the number of the variable passed, for an "i%d"
1044 format string. If !IS_PARAM, this is the constant value passed. */
1045 uint64_t value;
1046};
6d69ff19 1047
59250a8d 1048parameter::parameter ()
1049 : type (UNSET), is_param (false), value (0) {}
6d69ff19 1050
59250a8d 1051parameter::parameter (type_enum type_in, bool is_param_in, uint64_t value_in)
1052 : type (type_in), is_param (is_param_in), value (value_in) {}
6d69ff19 1053
59250a8d 1054bool
1055operator == (const parameter &param1, const parameter &param2)
6d69ff19 1056{
59250a8d 1057 return (param1.type == param2.type
1058 && param1.is_param == param2.is_param
1059 && param1.value == param2.value);
1060}
6d69ff19 1061
59250a8d 1062bool
1063operator != (const parameter &param1, const parameter &param2)
1064{
1065 return !operator == (param1, param2);
1066}
6d69ff19 1067
59250a8d 1068/* Represents a routine that matches a partial rtx pattern, returning
1069 an ad-hoc enum value on success and -1 on failure. The routine can
1070 be used by any subroutine type. The match can be parameterized by
1071 things like mode, code and UNSPEC number. */
1072struct pattern_routine
1073{
1074 /* The state that implements the pattern. */
1075 state *s;
6d69ff19 1076
59250a8d 1077 /* The deepest root position from which S can access all the rtxes it needs.
1078 This is NULL if the pattern doesn't need an rtx input, usually because
1079 all matching is done on operands[] instead. */
1080 position *pos;
6d69ff19 1081
59250a8d 1082 /* A unique identifier for the routine. */
1083 unsigned int pattern_id;
6d69ff19 1084
59250a8d 1085 /* True if the routine takes pnum_clobbers as argument. */
1086 bool pnum_clobbers_p;
6d69ff19 1087
59250a8d 1088 /* True if the routine takes the enclosing instruction as argument. */
1089 bool insn_p;
6d69ff19 1090
59250a8d 1091 /* The types of the other parameters to the routine, if any. */
1092 auto_vec <parameter::type_enum, MAX_PATTERN_PARAMS> param_types;
1093};
6d69ff19 1094
59250a8d 1095/* All defined patterns. */
1096static vec <pattern_routine *> patterns;
35b0bfe2 1097
59250a8d 1098/* Represents one use of a pattern routine. */
1099struct pattern_use
1100{
1101 /* The pattern routine to use. */
1102 pattern_routine *routine;
6d69ff19 1103
59250a8d 1104 /* The values to pass as parameters. This vector has the same length
1105 as ROUTINE->PARAM_TYPES. */
1106 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
1107};
6d69ff19 1108
59250a8d 1109/* Represents a test performed by a decision. */
abef0e58 1110struct rtx_test
6d69ff19 1111{
abef0e58 1112 rtx_test ();
6d69ff19 1113
59250a8d 1114 /* The types of test that can be performed. Most of them take as input
1115 an rtx X. Some also take as input a transition label LABEL; the others
1116 are booleans for which the transition label is always "true".
6d69ff19 1117
59250a8d 1118 The order of the enum isn't important. */
1119 enum kind_enum {
1120 /* Check GET_CODE (X) == LABEL. */
1121 CODE,
6d69ff19 1122
59250a8d 1123 /* Check GET_MODE (X) == LABEL. */
1124 MODE,
6d69ff19 1125
15183fd2 1126 /* Check REGNO (X) == LABEL. */
1127 REGNO_FIELD,
1128
9edf7ea8 1129 /* Check known_eq (SUBREG_BYTE (X), LABEL). */
1130 SUBREG_FIELD,
1131
59250a8d 1132 /* Check XINT (X, u.opno) == LABEL. */
1133 INT_FIELD,
263287f7 1134
59250a8d 1135 /* Check XWINT (X, u.opno) == LABEL. */
1136 WIDE_INT_FIELD,
263287f7 1137
59250a8d 1138 /* Check XVECLEN (X, 0) == LABEL. */
1139 VECLEN,
15d18ea0 1140
59250a8d 1141 /* Check peep2_current_count >= u.min_len. */
1142 PEEP2_COUNT,
15d18ea0 1143
59250a8d 1144 /* Check XVECLEN (X, 0) >= u.min_len. */
1145 VECLEN_GE,
15d18ea0 1146
59250a8d 1147 /* Check whether X is a cached const_int with value u.integer. */
1148 SAVED_CONST_INT,
15d18ea0 1149
59250a8d 1150 /* Check u.predicate.data (X, u.predicate.mode). */
1151 PREDICATE,
15d18ea0 1152
59250a8d 1153 /* Check rtx_equal_p (X, operands[u.opno]). */
1154 DUPLICATE,
15d18ea0 1155
59250a8d 1156 /* Check whether X matches pattern u.pattern. */
1157 PATTERN,
15d18ea0 1158
59250a8d 1159 /* Check whether pnum_clobbers is nonnull (RECOG only). */
1160 HAVE_NUM_CLOBBERS,
15d18ea0 1161
59250a8d 1162 /* Check whether general C test u.string holds. In general the condition
1163 needs access to "insn" and the full operand list. */
1164 C_TEST,
a698628e 1165
59250a8d 1166 /* Execute operands[u.opno] = X. (Always succeeds.) */
1167 SET_OP,
6d69ff19 1168
59250a8d 1169 /* Accept u.acceptance. Always succeeds for SUBPATTERN, RECOG and SPLIT.
1170 May fail for PEEPHOLE2 if the define_peephole2 C code executes FAIL. */
1171 ACCEPT
1172 };
6d69ff19 1173
59250a8d 1174 /* The position of rtx X in the above description, relative to the
1175 incoming instruction "insn". The position is null if the test
1176 doesn't take an X as input. */
1177 position *pos;
a698628e 1178
59250a8d 1179 /* Which element of operands[] already contains POS, or -1 if no element
1180 is known to hold POS. */
1181 int pos_operand;
a698628e 1182
59250a8d 1183 /* The type of test and its parameters, as described above. */
1184 kind_enum kind;
1185 union
1186 {
1187 int opno;
1188 int min_len;
1189 struct
263287f7 1190 {
59250a8d 1191 bool is_param;
1192 int value;
1193 } integer;
1194 struct
1195 {
1196 const struct pred_data *data;
1197 /* True if the mode is taken from a machine_mode parameter
1198 to the routine rather than a constant machine_mode. If true,
1199 MODE is the number of the parameter (for an "i%d" format string),
1200 otherwise it is the mode itself. */
1201 bool mode_is_param;
1202 unsigned int mode;
1203 } predicate;
1204 pattern_use *pattern;
1205 const char *string;
1206 acceptance_type acceptance;
1207 } u;
a698628e 1208
abef0e58 1209 static rtx_test code (position *);
1210 static rtx_test mode (position *);
15183fd2 1211 static rtx_test regno_field (position *);
9edf7ea8 1212 static rtx_test subreg_field (position *);
abef0e58 1213 static rtx_test int_field (position *, int);
1214 static rtx_test wide_int_field (position *, int);
1215 static rtx_test veclen (position *);
1216 static rtx_test peep2_count (int);
1217 static rtx_test veclen_ge (position *, int);
1218 static rtx_test predicate (position *, const pred_data *, machine_mode);
1219 static rtx_test duplicate (position *, int);
1220 static rtx_test pattern (position *, pattern_use *);
1221 static rtx_test have_num_clobbers ();
1222 static rtx_test c_test (const char *);
1223 static rtx_test set_op (position *, int);
1224 static rtx_test accept (const acceptance_type &);
59250a8d 1225
1226 bool terminal_p () const;
1227 bool single_outcome_p () const;
1228
1229private:
abef0e58 1230 rtx_test (position *, kind_enum);
59250a8d 1231};
a698628e 1232
abef0e58 1233rtx_test::rtx_test () {}
a698628e 1234
abef0e58 1235rtx_test::rtx_test (position *pos_in, kind_enum kind_in)
59250a8d 1236 : pos (pos_in), pos_operand (-1), kind (kind_in) {}
a698628e 1237
abef0e58 1238rtx_test
1239rtx_test::code (position *pos)
59250a8d 1240{
abef0e58 1241 return rtx_test (pos, rtx_test::CODE);
59250a8d 1242}
a698628e 1243
abef0e58 1244rtx_test
1245rtx_test::mode (position *pos)
59250a8d 1246{
abef0e58 1247 return rtx_test (pos, rtx_test::MODE);
59250a8d 1248}
6d69ff19 1249
15183fd2 1250rtx_test
1251rtx_test::regno_field (position *pos)
1252{
1253 rtx_test res (pos, rtx_test::REGNO_FIELD);
1254 return res;
1255}
1256
9edf7ea8 1257rtx_test
1258rtx_test::subreg_field (position *pos)
1259{
1260 rtx_test res (pos, rtx_test::SUBREG_FIELD);
1261 return res;
1262}
1263
abef0e58 1264rtx_test
1265rtx_test::int_field (position *pos, int opno)
59250a8d 1266{
abef0e58 1267 rtx_test res (pos, rtx_test::INT_FIELD);
59250a8d 1268 res.u.opno = opno;
1269 return res;
1270}
6d69ff19 1271
abef0e58 1272rtx_test
1273rtx_test::wide_int_field (position *pos, int opno)
59250a8d 1274{
abef0e58 1275 rtx_test res (pos, rtx_test::WIDE_INT_FIELD);
59250a8d 1276 res.u.opno = opno;
1277 return res;
6d69ff19 1278}
263287f7 1279
abef0e58 1280rtx_test
1281rtx_test::veclen (position *pos)
59250a8d 1282{
abef0e58 1283 return rtx_test (pos, rtx_test::VECLEN);
59250a8d 1284}
263287f7 1285
abef0e58 1286rtx_test
1287rtx_test::peep2_count (int min_len)
6d69ff19 1288{
abef0e58 1289 rtx_test res (0, rtx_test::PEEP2_COUNT);
59250a8d 1290 res.u.min_len = min_len;
1291 return res;
1292}
a698628e 1293
abef0e58 1294rtx_test
1295rtx_test::veclen_ge (position *pos, int min_len)
59250a8d 1296{
abef0e58 1297 rtx_test res (pos, rtx_test::VECLEN_GE);
59250a8d 1298 res.u.min_len = min_len;
1299 return res;
1300}
a698628e 1301
abef0e58 1302rtx_test
1303rtx_test::predicate (position *pos, const struct pred_data *data,
1304 machine_mode mode)
59250a8d 1305{
abef0e58 1306 rtx_test res (pos, rtx_test::PREDICATE);
59250a8d 1307 res.u.predicate.data = data;
1308 res.u.predicate.mode_is_param = false;
1309 res.u.predicate.mode = mode;
1310 return res;
1311}
4747a74c 1312
abef0e58 1313rtx_test
1314rtx_test::duplicate (position *pos, int opno)
59250a8d 1315{
abef0e58 1316 rtx_test res (pos, rtx_test::DUPLICATE);
59250a8d 1317 res.u.opno = opno;
1318 return res;
1319}
4747a74c 1320
abef0e58 1321rtx_test
1322rtx_test::pattern (position *pos, pattern_use *pattern)
59250a8d 1323{
abef0e58 1324 rtx_test res (pos, rtx_test::PATTERN);
59250a8d 1325 res.u.pattern = pattern;
1326 return res;
a698628e 1327}
a698628e 1328
abef0e58 1329rtx_test
1330rtx_test::have_num_clobbers ()
59250a8d 1331{
abef0e58 1332 return rtx_test (0, rtx_test::HAVE_NUM_CLOBBERS);
59250a8d 1333}
6d69ff19 1334
abef0e58 1335rtx_test
1336rtx_test::c_test (const char *string)
263287f7 1337{
abef0e58 1338 rtx_test res (0, rtx_test::C_TEST);
59250a8d 1339 res.u.string = string;
1340 return res;
1341}
6d69ff19 1342
abef0e58 1343rtx_test
1344rtx_test::set_op (position *pos, int opno)
59250a8d 1345{
abef0e58 1346 rtx_test res (pos, rtx_test::SET_OP);
59250a8d 1347 res.u.opno = opno;
1348 return res;
1349}
a698628e 1350
abef0e58 1351rtx_test
1352rtx_test::accept (const acceptance_type &acceptance)
59250a8d 1353{
abef0e58 1354 rtx_test res (0, rtx_test::ACCEPT);
59250a8d 1355 res.u.acceptance = acceptance;
1356 return res;
1357}
a698628e 1358
59250a8d 1359/* Return true if the test represents an unconditionally successful match. */
a698628e 1360
59250a8d 1361bool
abef0e58 1362rtx_test::terminal_p () const
59250a8d 1363{
abef0e58 1364 return kind == rtx_test::ACCEPT && u.acceptance.type != PEEPHOLE2;
a698628e 1365}
a698628e 1366
59250a8d 1367/* Return true if the test is a boolean that is always true. */
6d69ff19 1368
59250a8d 1369bool
abef0e58 1370rtx_test::single_outcome_p () const
a698628e 1371{
abef0e58 1372 return terminal_p () || kind == rtx_test::SET_OP;
59250a8d 1373}
a698628e 1374
59250a8d 1375bool
abef0e58 1376operator == (const rtx_test &a, const rtx_test &b)
59250a8d 1377{
1378 if (a.pos != b.pos || a.kind != b.kind)
1379 return false;
1380 switch (a.kind)
6d69ff19 1381 {
abef0e58 1382 case rtx_test::CODE:
1383 case rtx_test::MODE:
15183fd2 1384 case rtx_test::REGNO_FIELD:
9edf7ea8 1385 case rtx_test::SUBREG_FIELD:
abef0e58 1386 case rtx_test::VECLEN:
1387 case rtx_test::HAVE_NUM_CLOBBERS:
59250a8d 1388 return true;
1389
abef0e58 1390 case rtx_test::PEEP2_COUNT:
1391 case rtx_test::VECLEN_GE:
59250a8d 1392 return a.u.min_len == b.u.min_len;
1393
abef0e58 1394 case rtx_test::INT_FIELD:
1395 case rtx_test::WIDE_INT_FIELD:
1396 case rtx_test::DUPLICATE:
1397 case rtx_test::SET_OP:
59250a8d 1398 return a.u.opno == b.u.opno;
1399
abef0e58 1400 case rtx_test::SAVED_CONST_INT:
59250a8d 1401 return (a.u.integer.is_param == b.u.integer.is_param
1402 && a.u.integer.value == b.u.integer.value);
1403
abef0e58 1404 case rtx_test::PREDICATE:
59250a8d 1405 return (a.u.predicate.data == b.u.predicate.data
1406 && a.u.predicate.mode_is_param == b.u.predicate.mode_is_param
1407 && a.u.predicate.mode == b.u.predicate.mode);
1408
abef0e58 1409 case rtx_test::PATTERN:
59250a8d 1410 return (a.u.pattern->routine == b.u.pattern->routine
1411 && a.u.pattern->params == b.u.pattern->params);
1412
abef0e58 1413 case rtx_test::C_TEST:
59250a8d 1414 return strcmp (a.u.string, b.u.string) == 0;
1415
abef0e58 1416 case rtx_test::ACCEPT:
59250a8d 1417 return a.u.acceptance == b.u.acceptance;
6d69ff19 1418 }
59250a8d 1419 gcc_unreachable ();
1420}
263287f7 1421
59250a8d 1422bool
abef0e58 1423operator != (const rtx_test &a, const rtx_test &b)
59250a8d 1424{
1425 return !operator == (a, b);
1426}
a698628e 1427
59250a8d 1428/* A simple set of transition labels. Most transitions have a singleton
1429 label, so try to make that case as efficient as possible. */
1430struct int_set : public auto_vec <uint64_t, 1>
1431{
1432 typedef uint64_t *iterator;
a698628e 1433
59250a8d 1434 int_set ();
1435 int_set (uint64_t);
1436 int_set (const int_set &);
a698628e 1437
59250a8d 1438 int_set &operator = (const int_set &);
a698628e 1439
59250a8d 1440 iterator begin ();
1441 iterator end ();
1442};
a698628e 1443
6d443cda 1444int_set::int_set () : auto_vec<uint64_t, 1> () {}
fcb53c1e 1445
6d443cda 1446int_set::int_set (uint64_t label) :
1447 auto_vec<uint64_t, 1> ()
59250a8d 1448{
1449 safe_push (label);
1450}
a698628e 1451
6d443cda 1452int_set::int_set (const int_set &other) :
1453 auto_vec<uint64_t, 1> ()
59250a8d 1454{
1455 safe_splice (other);
1456}
a698628e 1457
59250a8d 1458int_set &
1459int_set::operator = (const int_set &other)
1460{
1461 truncate (0);
1462 safe_splice (other);
1463 return *this;
1464}
ec4c9f0c 1465
59250a8d 1466int_set::iterator
1467int_set::begin ()
1468{
1469 return address ();
1470}
6d69ff19 1471
59250a8d 1472int_set::iterator
1473int_set::end ()
1474{
1475 return address () + length ();
6d69ff19 1476}
6d69ff19 1477
59250a8d 1478bool
1479operator == (const int_set &a, const int_set &b)
6d69ff19 1480{
59250a8d 1481 if (a.length () != b.length ())
1482 return false;
1483 for (unsigned int i = 0; i < a.length (); ++i)
1484 if (a[i] != b[i])
1485 return false;
1486 return true;
1487}
a698628e 1488
59250a8d 1489bool
1490operator != (const int_set &a, const int_set &b)
1491{
1492 return !operator == (a, b);
1493}
a698628e 1494
59250a8d 1495struct decision;
a698628e 1496
59250a8d 1497/* Represents a transition between states, dependent on the result of
1498 a test T. */
1499struct transition
1500{
1501 transition (const int_set &, state *, bool);
263287f7 1502
59250a8d 1503 void set_parent (list_head <transition> *);
263287f7 1504
59250a8d 1505 /* Links to other transitions for T. Always null for boolean tests. */
1506 transition *prev, *next;
fcb53c1e 1507
59250a8d 1508 /* The transition should be taken when T has one of these values.
abef0e58 1509 E.g. for rtx_test::CODE this is a set of codes, while for booleans like
1510 rtx_test::PREDICATE it is always a singleton "true". The labels are
59250a8d 1511 sorted in ascending order. */
1512 int_set labels;
6d69ff19 1513
59250a8d 1514 /* The source decision. */
1515 decision *from;
6d69ff19 1516
59250a8d 1517 /* The target state. */
1518 state *to;
263287f7 1519
59250a8d 1520 /* True if TO would function correctly even if TEST wasn't performed.
1521 E.g. it isn't necessary to check whether GET_MODE (x1) is SImode
1522 before calling register_operand (x1, SImode), since register_operand
1523 performs its own mode check. However, checking GET_MODE can be a cheap
1524 way of disambiguating SImode and DImode register operands. */
1525 bool optional;
263287f7 1526
59250a8d 1527 /* True if LABELS contains parameter numbers rather than constants.
abef0e58 1528 E.g. if this is true for a rtx_test::CODE, the label is the number
59250a8d 1529 of an rtx_code parameter rather than an rtx_code itself.
1530 LABELS is always a singleton when this variable is true. */
1531 bool is_param;
1532};
263287f7 1533
59250a8d 1534/* Represents a test and the action that should be taken on the result.
1535 If a transition exists for the test outcome, the machine switches
1536 to the transition's target state. If no suitable transition exists,
1537 the machine either falls through to the next decision or, if there are no
1538 more decisions to try, fails the match. */
1539struct decision : list_head <transition>
1540{
abef0e58 1541 decision (const rtx_test &);
6d69ff19 1542
59250a8d 1543 void set_parent (list_head <decision> *s);
1544 bool if_statement_p (uint64_t * = 0) const;
6d69ff19 1545
59250a8d 1546 /* The state to which this decision belongs. */
1547 state *s;
6d69ff19 1548
59250a8d 1549 /* Links to other decisions in the same state. */
1550 decision *prev, *next;
6d69ff19 1551
59250a8d 1552 /* The test to perform. */
abef0e58 1553 rtx_test test;
59250a8d 1554};
6d69ff19 1555
59250a8d 1556/* Represents one machine state. For each state the machine tries a list
1557 of decisions, in order, and acts on the first match. It fails without
1558 further backtracking if no decisions match. */
1559struct state : list_head <decision>
1560{
1561 void set_parent (list_head <state> *) {}
1562};
6d69ff19 1563
59250a8d 1564transition::transition (const int_set &labels_in, state *to_in,
1565 bool optional_in)
1566 : prev (0), next (0), labels (labels_in), from (0), to (to_in),
1567 optional (optional_in), is_param (false) {}
1568
1569/* Set the source decision of the transition. */
263287f7 1570
59250a8d 1571void
1572transition::set_parent (list_head <transition> *from_in)
1573{
1574 from = static_cast <decision *> (from_in);
263287f7 1575}
6d69ff19 1576
abef0e58 1577decision::decision (const rtx_test &test_in)
59250a8d 1578 : prev (0), next (0), test (test_in) {}
263287f7 1579
59250a8d 1580/* Set the state to which this decision belongs. */
1581
1582void
1583decision::set_parent (list_head <decision> *s_in)
263287f7 1584{
59250a8d 1585 s = static_cast <state *> (s_in);
1586}
a698628e 1587
59250a8d 1588/* Return true if the decision has a single transition with a single label.
1589 If so, return the label in *LABEL if nonnull. */
a698628e 1590
59250a8d 1591inline bool
1592decision::if_statement_p (uint64_t *label) const
1593{
1594 if (singleton () && first->labels.length () == 1)
263287f7 1595 {
59250a8d 1596 if (label)
1597 *label = first->labels[0];
1598 return true;
263287f7 1599 }
59250a8d 1600 return false;
263287f7 1601}
6d69ff19 1602
59250a8d 1603/* Add to FROM a decision that performs TEST and has a single transition
1604 TRANS. */
263287f7 1605
1606static void
abef0e58 1607add_decision (state *from, const rtx_test &test, transition *trans)
263287f7 1608{
59250a8d 1609 decision *d = new decision (test);
1610 from->push_back (d);
1611 d->push_back (trans);
6d69ff19 1612}
a698628e 1613
59250a8d 1614/* Add a transition from FROM to a new, empty state that is taken
1615 when TEST == LABELS. OPTIONAL says whether the new transition
1616 should be optional. Return the new state. */
a698628e 1617
59250a8d 1618static state *
abef0e58 1619add_decision (state *from, const rtx_test &test, int_set labels, bool optional)
6d69ff19 1620{
59250a8d 1621 state *to = new state;
1622 add_decision (from, test, new transition (labels, to, optional));
1623 return to;
1624}
2494d261 1625
59250a8d 1626/* Insert a decision before decisions R to make them dependent on
1627 TEST == LABELS. OPTIONAL says whether the new transition should be
1628 optional. */
2494d261 1629
59250a8d 1630static decision *
abef0e58 1631insert_decision_before (state::range r, const rtx_test &test,
59250a8d 1632 const int_set &labels, bool optional)
1633{
1634 decision *newd = new decision (test);
1635 state *news = new state;
1636 newd->push_back (new transition (labels, news, optional));
1637 r.start->s->replace (r, newd);
1638 news->push_back (r);
1639 return newd;
6d69ff19 1640}
59250a8d 1641
1642/* Remove any optional transitions from S that turned out not to be useful. */
6d69ff19 1643
1644static void
59250a8d 1645collapse_optional_decisions (state *s)
6d69ff19 1646{
59250a8d 1647 decision *d = s->first;
1648 while (d)
1649 {
1650 decision *next = d->next;
1651 for (transition *trans = d->first; trans; trans = trans->next)
1652 collapse_optional_decisions (trans->to);
1653 /* A decision with a single optional transition doesn't help
1654 partition the potential matches and so is unlikely to be
1655 worthwhile. In particular, if the decision that performs the
1656 test is the last in the state, the best it could do is reject
1657 an invalid pattern slightly earlier. If instead the decision
1658 is not the last in the state, the condition it tests could hold
1659 even for the later decisions in the state. The best it can do
1660 is save work in some cases where only the later decisions can
1661 succeed.
1662
1663 In both cases the optional transition would add extra work to
1664 successful matches when the tested condition holds. */
1665 if (transition *trans = d->singleton ())
1666 if (trans->optional)
1667 s->replace (d, trans->to->release ());
1668 d = next;
1669 }
6d69ff19 1670}
263287f7 1671
59250a8d 1672/* Try to squash several separate tests into simpler ones. */
263287f7 1673
6d69ff19 1674static void
59250a8d 1675simplify_tests (state *s)
6d69ff19 1676{
59250a8d 1677 for (decision *d = s->first; d; d = d->next)
6d69ff19 1678 {
59250a8d 1679 uint64_t label;
1680 /* Convert checks for GET_CODE (x) == CONST_INT and XWINT (x, 0) == N
1681 into checks for const_int_rtx[N'], if N is suitably small. */
abef0e58 1682 if (d->test.kind == rtx_test::CODE
59250a8d 1683 && d->if_statement_p (&label)
1684 && label == CONST_INT)
1685 if (decision *second = d->first->to->singleton ())
fe512d6d 1686 if (d->test.pos == second->test.pos
abef0e58 1687 && second->test.kind == rtx_test::WIDE_INT_FIELD
59250a8d 1688 && second->test.u.opno == 0
1689 && second->if_statement_p (&label)
1690 && IN_RANGE (int64_t (label),
1691 -MAX_SAVED_CONST_INT, MAX_SAVED_CONST_INT))
1692 {
abef0e58 1693 d->test.kind = rtx_test::SAVED_CONST_INT;
59250a8d 1694 d->test.u.integer.is_param = false;
1695 d->test.u.integer.value = label;
1696 d->replace (d->first, second->release ());
1697 d->first->labels[0] = true;
1698 }
1699 /* If we have a CODE test followed by a PREDICATE test, rely on
1700 the predicate to test the code.
1701
1702 This case exists for match_operators. We initially treat the
1703 CODE test for a match_operator as non-optional so that we can
1704 safely move down to its operands. It may turn out that all
1705 paths that reach that code test require the same predicate
1706 to be true. cse_tests will then put the predicate test in
1707 series with the code test. */
abef0e58 1708 if (d->test.kind == rtx_test::CODE)
59250a8d 1709 if (transition *trans = d->singleton ())
1710 {
1711 state *s = trans->to;
1712 while (decision *d2 = s->singleton ())
1713 {
1714 if (d->test.pos != d2->test.pos)
1715 break;
1716 transition *trans2 = d2->singleton ();
1717 if (!trans2)
1718 break;
abef0e58 1719 if (d2->test.kind == rtx_test::PREDICATE)
59250a8d 1720 {
1721 d->test = d2->test;
1722 trans->labels = int_set (true);
1723 s->replace (d2, trans2->to->release ());
1724 break;
1725 }
1726 s = trans2->to;
1727 }
1728 }
1729 for (transition *trans = d->first; trans; trans = trans->next)
1730 simplify_tests (trans->to);
6d69ff19 1731 }
1732}
a698628e 1733
59250a8d 1734/* Return true if all successful returns passing through D require the
1735 condition tested by COMMON to be true.
ad85fb32 1736
59250a8d 1737 When returning true, add all transitions like COMMON in D to WHERE.
1738 WHERE may contain a partial result on failure. */
1739
1740static bool
1741common_test_p (decision *d, transition *common, vec <transition *> *where)
ad85fb32 1742{
abef0e58 1743 if (d->test.kind == rtx_test::ACCEPT)
59250a8d 1744 /* We found a successful return that didn't require COMMON. */
1745 return false;
1746 if (d->test == common->from->test)
1747 {
1748 transition *trans = d->singleton ();
1749 if (!trans
1750 || trans->optional != common->optional
1751 || trans->labels != common->labels)
1752 return false;
1753 where->safe_push (trans);
1754 return true;
1755 }
1756 for (transition *trans = d->first; trans; trans = trans->next)
1757 for (decision *subd = trans->to->first; subd; subd = subd->next)
1758 if (!common_test_p (subd, common, where))
1759 return false;
1760 return true;
ad85fb32 1761}
1762
59250a8d 1763/* Indicates that we have tested GET_CODE (X) for a particular rtx X. */
1764const unsigned char TESTED_CODE = 1;
a698628e 1765
59250a8d 1766/* Indicates that we have tested XVECLEN (X, 0) for a particular rtx X. */
1767const unsigned char TESTED_VECLEN = 2;
263287f7 1768
59250a8d 1769/* Represents a set of conditions that are known to hold. */
1770struct known_conditions
1771{
1772 /* A mask of TESTED_ values for each position, indexed by the position's
1773 id field. */
1774 auto_vec <unsigned char> position_tests;
a698628e 1775
59250a8d 1776 /* Index N says whether operands[N] has been set. */
1777 auto_vec <bool> set_operands;
a698628e 1778
59250a8d 1779 /* A guranteed lower bound on the value of peep2_current_count. */
1780 int peep2_count;
1781};
263287f7 1782
59250a8d 1783/* Return true if TEST can safely be performed at D, where
1784 the conditions in KC hold. TEST is known to occur along the
1785 first path from D (i.e. always following the first transition
1786 of the first decision). Any intervening tests can be used as
1787 negative proof that hoisting isn't safe, but only KC can be used
1788 as positive proof. */
263287f7 1789
59250a8d 1790static bool
abef0e58 1791safe_to_hoist_p (decision *d, const rtx_test &test, known_conditions *kc)
59250a8d 1792{
1793 switch (test.kind)
1794 {
abef0e58 1795 case rtx_test::C_TEST:
59250a8d 1796 /* In general, C tests require everything else to have been
1797 verified and all operands to have been set up. */
1798 return false;
1799
abef0e58 1800 case rtx_test::ACCEPT:
59250a8d 1801 /* Don't accept something before all conditions have been tested. */
1802 return false;
1803
abef0e58 1804 case rtx_test::PREDICATE:
59250a8d 1805 /* Don't move a predicate over a test for VECLEN_GE, since the
1806 predicate used in a match_parallel can legitimately expect the
1807 length to be checked first. */
1808 for (decision *subd = d;
1809 subd->test != test;
1810 subd = subd->first->to->first)
1811 if (subd->test.pos == test.pos
abef0e58 1812 && subd->test.kind == rtx_test::VECLEN_GE)
59250a8d 1813 return false;
1814 goto any_rtx;
1815
abef0e58 1816 case rtx_test::DUPLICATE:
59250a8d 1817 /* Don't test for a match_dup until the associated operand has
1818 been set. */
1819 if (!kc->set_operands[test.u.opno])
1820 return false;
1821 goto any_rtx;
1822
abef0e58 1823 case rtx_test::CODE:
1824 case rtx_test::MODE:
1825 case rtx_test::SAVED_CONST_INT:
1826 case rtx_test::SET_OP:
59250a8d 1827 any_rtx:
1828 /* Check whether it is safe to access the rtx under test. */
1829 switch (test.pos->type)
263287f7 1830 {
59250a8d 1831 case POS_PEEP2_INSN:
1832 return test.pos->arg < kc->peep2_count;
0ced2f66 1833
59250a8d 1834 case POS_XEXP:
1835 return kc->position_tests[test.pos->base->id] & TESTED_CODE;
6d69ff19 1836
59250a8d 1837 case POS_XVECEXP0:
1838 return kc->position_tests[test.pos->base->id] & TESTED_VECLEN;
6d69ff19 1839 }
59250a8d 1840 gcc_unreachable ();
a698628e 1841
15183fd2 1842 case rtx_test::REGNO_FIELD:
9edf7ea8 1843 case rtx_test::SUBREG_FIELD:
abef0e58 1844 case rtx_test::INT_FIELD:
1845 case rtx_test::WIDE_INT_FIELD:
1846 case rtx_test::VECLEN:
1847 case rtx_test::VECLEN_GE:
59250a8d 1848 /* These tests access a specific part of an rtx, so are only safe
1849 once we know what the rtx is. */
1850 return kc->position_tests[test.pos->id] & TESTED_CODE;
a698628e 1851
abef0e58 1852 case rtx_test::PEEP2_COUNT:
1853 case rtx_test::HAVE_NUM_CLOBBERS:
59250a8d 1854 /* These tests can be performed anywhere. */
1855 return true;
263287f7 1856
abef0e58 1857 case rtx_test::PATTERN:
59250a8d 1858 gcc_unreachable ();
1859 }
1860 gcc_unreachable ();
1861}
a698628e 1862
59250a8d 1863/* Look for a transition that is taken by all successful returns from a range
1864 of decisions starting at OUTER and that would be better performed by
1865 OUTER's state instead. On success, store all instances of that transition
1866 in WHERE and return the last decision in the range. The range could
1867 just be OUTER, or it could include later decisions as well.
1868
1869 WITH_POSITION_P is true if only tests with position POS should be tried,
1870 false if any test should be tried. WORTHWHILE_SINGLE_P is true if the
1871 result is useful even when the range contains just a single decision
1872 with a single transition. KC are the conditions that are known to
1873 hold at OUTER. */
1874
1875static decision *
1876find_common_test (decision *outer, bool with_position_p,
1877 position *pos, bool worthwhile_single_p,
1878 known_conditions *kc, vec <transition *> *where)
1879{
1880 /* After this, WORTHWHILE_SINGLE_P indicates whether a range that contains
1881 just a single decision is useful, regardless of the number of
1882 transitions it has. */
1883 if (!outer->singleton ())
1884 worthwhile_single_p = true;
1885 /* Quick exit if we don't have enough decisions to form a worthwhile
1886 range. */
1887 if (!worthwhile_single_p && !outer->next)
1888 return 0;
1889 /* Follow the first chain down, as one example of a path that needs
1890 to contain the common test. */
1891 for (decision *d = outer; d; d = d->first->to->first)
1892 {
1893 transition *trans = d->singleton ();
1894 if (trans
1895 && (!with_position_p || d->test.pos == pos)
1896 && safe_to_hoist_p (outer, d->test, kc))
263287f7 1897 {
59250a8d 1898 if (common_test_p (outer, trans, where))
63e9de92 1899 {
59250a8d 1900 if (!outer->next)
1901 /* We checked above whether the move is worthwhile. */
1902 return outer;
1903 /* See how many decisions in OUTER's chain could reuse
1904 the same test. */
1905 decision *outer_end = outer;
1906 do
1907 {
1908 unsigned int length = where->length ();
1909 if (!common_test_p (outer_end->next, trans, where))
1910 {
1911 where->truncate (length);
1912 break;
1913 }
1914 outer_end = outer_end->next;
1915 }
1916 while (outer_end->next);
1917 /* It is worth moving TRANS if it can be shared by more than
1918 one decision. */
1919 if (outer_end != outer || worthwhile_single_p)
1920 return outer_end;
63e9de92 1921 }
59250a8d 1922 where->truncate (0);
263287f7 1923 }
6d69ff19 1924 }
59250a8d 1925 return 0;
1926}
1927
1928/* Try to promote common subtests in S to a single, shared decision.
1929 Also try to bunch tests for the same position together. POS is the
1930 position of the rtx tested before reaching S. KC are the conditions
1931 that are known to hold on entry to S. */
ff5decbb 1932
59250a8d 1933static void
1934cse_tests (position *pos, state *s, known_conditions *kc)
1935{
1936 for (decision *d = s->first; d; d = d->next)
1937 {
1938 auto_vec <transition *, 16> where;
1939 if (d->test.pos)
7abd96cd 1940 {
59250a8d 1941 /* Try to find conditions that don't depend on a particular rtx,
1942 such as pnum_clobbers != NULL or peep2_current_count >= X.
1943 It's usually better to check these conditions as soon as
1944 possible, so the change is worthwhile even if there is
1945 only one copy of the test. */
1946 decision *endd = find_common_test (d, true, 0, true, kc, &where);
1947 if (!endd && d->test.pos != pos)
1948 /* Try to find other conditions related to position POS
1949 before moving to the new position. Again, this is
1950 worthwhile even if there is only one copy of the test,
1951 since it means that fewer position variables are live
1952 at a given time. */
1953 endd = find_common_test (d, true, pos, true, kc, &where);
1954 if (!endd)
1955 /* Try to find any condition that is used more than once. */
1956 endd = find_common_test (d, false, 0, false, kc, &where);
1957 if (endd)
1958 {
1959 transition *common = where[0];
1960 /* Replace [D, ENDD] with a test like COMMON. We'll recurse
1961 on the common test and see the original D again next time. */
1962 d = insert_decision_before (state::range (d, endd),
1963 common->from->test,
1964 common->labels,
1965 common->optional);
1966 /* Remove the old tests. */
1967 while (!where.is_empty ())
1968 {
1969 transition *trans = where.pop ();
1970 trans->from->s->replace (trans->from, trans->to->release ());
1971 }
1972 }
7abd96cd 1973 }
59250a8d 1974
1975 /* Make sure that safe_to_hoist_p isn't being overly conservative.
1976 It should realize that D's test is safe in the current
1977 environment. */
abef0e58 1978 gcc_assert (d->test.kind == rtx_test::C_TEST
1979 || d->test.kind == rtx_test::ACCEPT
59250a8d 1980 || safe_to_hoist_p (d, d->test, kc));
1981
1982 /* D won't be changed any further by the current optimization.
1983 Recurse with the state temporarily updated to include D. */
1984 int prev = 0;
1985 switch (d->test.kind)
6d69ff19 1986 {
abef0e58 1987 case rtx_test::CODE:
59250a8d 1988 prev = kc->position_tests[d->test.pos->id];
1989 kc->position_tests[d->test.pos->id] |= TESTED_CODE;
6d69ff19 1990 break;
59250a8d 1991
abef0e58 1992 case rtx_test::VECLEN:
1993 case rtx_test::VECLEN_GE:
59250a8d 1994 prev = kc->position_tests[d->test.pos->id];
1995 kc->position_tests[d->test.pos->id] |= TESTED_VECLEN;
6d69ff19 1996 break;
59250a8d 1997
abef0e58 1998 case rtx_test::SET_OP:
59250a8d 1999 prev = kc->set_operands[d->test.u.opno];
2000 gcc_assert (!prev);
2001 kc->set_operands[d->test.u.opno] = true;
6d69ff19 2002 break;
59250a8d 2003
abef0e58 2004 case rtx_test::PEEP2_COUNT:
59250a8d 2005 prev = kc->peep2_count;
2006 kc->peep2_count = MAX (prev, d->test.u.min_len);
6d69ff19 2007 break;
59250a8d 2008
6d69ff19 2009 default:
59250a8d 2010 break;
6d69ff19 2011 }
59250a8d 2012 for (transition *trans = d->first; trans; trans = trans->next)
2013 cse_tests (d->test.pos ? d->test.pos : pos, trans->to, kc);
2014 switch (d->test.kind)
a698628e 2015 {
abef0e58 2016 case rtx_test::CODE:
2017 case rtx_test::VECLEN:
2018 case rtx_test::VECLEN_GE:
59250a8d 2019 kc->position_tests[d->test.pos->id] = prev;
2020 break;
a4245b4f 2021
abef0e58 2022 case rtx_test::SET_OP:
59250a8d 2023 kc->set_operands[d->test.u.opno] = prev;
2024 break;
7903ba8d 2025
abef0e58 2026 case rtx_test::PEEP2_COUNT:
59250a8d 2027 kc->peep2_count = prev;
2028 break;
263287f7 2029
59250a8d 2030 default:
2031 break;
2032 }
6d69ff19 2033 }
59250a8d 2034}
2035
2036/* Return the type of value that can be used to parameterize test KIND,
2037 or parameter::UNSET if none. */
2038
2039parameter::type_enum
abef0e58 2040transition_parameter_type (rtx_test::kind_enum kind)
59250a8d 2041{
2042 switch (kind)
6d69ff19 2043 {
abef0e58 2044 case rtx_test::CODE:
59250a8d 2045 return parameter::CODE;
2046
abef0e58 2047 case rtx_test::MODE:
59250a8d 2048 return parameter::MODE;
2049
15183fd2 2050 case rtx_test::REGNO_FIELD:
9edf7ea8 2051 case rtx_test::SUBREG_FIELD:
15183fd2 2052 return parameter::UINT;
2053
abef0e58 2054 case rtx_test::INT_FIELD:
2055 case rtx_test::VECLEN:
2056 case rtx_test::PATTERN:
59250a8d 2057 return parameter::INT;
2058
abef0e58 2059 case rtx_test::WIDE_INT_FIELD:
59250a8d 2060 return parameter::WIDE_INT;
2061
abef0e58 2062 case rtx_test::PEEP2_COUNT:
2063 case rtx_test::VECLEN_GE:
2064 case rtx_test::SAVED_CONST_INT:
2065 case rtx_test::PREDICATE:
2066 case rtx_test::DUPLICATE:
2067 case rtx_test::HAVE_NUM_CLOBBERS:
2068 case rtx_test::C_TEST:
2069 case rtx_test::SET_OP:
2070 case rtx_test::ACCEPT:
59250a8d 2071 return parameter::UNSET;
6d69ff19 2072 }
59250a8d 2073 gcc_unreachable ();
6d69ff19 2074}
263287f7 2075
59250a8d 2076/* Initialize the pos_operand fields of each state reachable from S.
2077 If OPERAND_POS[ID] >= 0, the position with id ID is stored in
2078 operands[OPERAND_POS[ID]] on entry to S. */
a698628e 2079
6d69ff19 2080static void
59250a8d 2081find_operand_positions (state *s, vec <int> &operand_pos)
6d69ff19 2082{
59250a8d 2083 for (decision *d = s->first; d; d = d->next)
6d69ff19 2084 {
59250a8d 2085 int this_operand = (d->test.pos ? operand_pos[d->test.pos->id] : -1);
2086 if (this_operand >= 0)
2087 d->test.pos_operand = this_operand;
abef0e58 2088 if (d->test.kind == rtx_test::SET_OP)
59250a8d 2089 operand_pos[d->test.pos->id] = d->test.u.opno;
2090 for (transition *trans = d->first; trans; trans = trans->next)
2091 find_operand_positions (trans->to, operand_pos);
abef0e58 2092 if (d->test.kind == rtx_test::SET_OP)
59250a8d 2093 operand_pos[d->test.pos->id] = this_operand;
2094 }
2095}
6d69ff19 2096
59250a8d 2097/* Statistics about a matching routine. */
2098struct stats
2099{
2100 stats ();
2101
2102 /* The total number of decisions in the routine, excluding trivial
2103 ones that never fail. */
2104 unsigned int num_decisions;
2105
2106 /* The number of non-trivial decisions on the longest path through
2107 the routine, and the return value that contributes most to that
2108 long path. */
2109 unsigned int longest_path;
2110 int longest_path_code;
2111
2112 /* The maximum number of times that a single call to the routine
2113 can backtrack, and the value returned at the end of that path.
2114 "Backtracking" here means failing one decision in state and
2115 going onto to the next. */
2116 unsigned int longest_backtrack;
2117 int longest_backtrack_code;
2118};
6d69ff19 2119
59250a8d 2120stats::stats ()
2121 : num_decisions (0), longest_path (0), longest_path_code (-1),
2122 longest_backtrack (0), longest_backtrack_code (-1) {}
6d69ff19 2123
59250a8d 2124/* Return statistics about S. */
6d69ff19 2125
59250a8d 2126static stats
2127get_stats (state *s)
2128{
2129 stats for_s;
2130 unsigned int longest_path = 0;
2131 for (decision *d = s->first; d; d = d->next)
2132 {
2133 /* Work out the statistics for D. */
2134 stats for_d;
2135 for (transition *trans = d->first; trans; trans = trans->next)
2136 {
2137 stats for_trans = get_stats (trans->to);
2138 for_d.num_decisions += for_trans.num_decisions;
2139 /* Each transition is mutually-exclusive, so just pick the
2140 longest of the individual paths. */
2141 if (for_d.longest_path <= for_trans.longest_path)
2142 {
2143 for_d.longest_path = for_trans.longest_path;
2144 for_d.longest_path_code = for_trans.longest_path_code;
2145 }
2146 /* Likewise for backtracking. */
2147 if (for_d.longest_backtrack <= for_trans.longest_backtrack)
2148 {
2149 for_d.longest_backtrack = for_trans.longest_backtrack;
2150 for_d.longest_backtrack_code = for_trans.longest_backtrack_code;
2151 }
2152 }
6d69ff19 2153
59250a8d 2154 /* Account for D's test in its statistics. */
2155 if (!d->test.single_outcome_p ())
2156 {
2157 for_d.num_decisions += 1;
2158 for_d.longest_path += 1;
2159 }
abef0e58 2160 if (d->test.kind == rtx_test::ACCEPT)
59250a8d 2161 {
2162 for_d.longest_path_code = d->test.u.acceptance.u.full.code;
2163 for_d.longest_backtrack_code = d->test.u.acceptance.u.full.code;
2164 }
7e5202bc 2165
59250a8d 2166 /* Keep a running count of the number of backtracks. */
2167 if (d->prev)
2168 for_s.longest_backtrack += 1;
35b0bfe2 2169
59250a8d 2170 /* Accumulate D's statistics into S's. */
2171 for_s.num_decisions += for_d.num_decisions;
2172 for_s.longest_path += for_d.longest_path;
2173 for_s.longest_backtrack += for_d.longest_backtrack;
6d69ff19 2174
59250a8d 2175 /* Use the code from the decision with the longest individual path,
2176 since that's more likely to be useful if trying to make the
2177 path shorter. In the event of a tie, pick the later decision,
2178 since that's closer to the end of the path. */
2179 if (longest_path <= for_d.longest_path)
2180 {
2181 longest_path = for_d.longest_path;
2182 for_s.longest_path_code = for_d.longest_path_code;
2183 }
6d69ff19 2184
59250a8d 2185 /* Later decisions in a state are necessarily in a longer backtrack
2186 than earlier decisions. */
2187 for_s.longest_backtrack_code = for_d.longest_backtrack_code;
2188 }
2189 return for_s;
2190}
6d69ff19 2191
59250a8d 2192/* Optimize ROOT. Use TYPE to describe ROOT in status messages. */
263287f7 2193
59250a8d 2194static void
2195optimize_subroutine_group (const char *type, state *root)
2196{
2197 /* Remove optional transitions that turned out not to be worthwhile. */
2198 if (collapse_optional_decisions_p)
2199 collapse_optional_decisions (root);
2200
2201 /* Try to remove duplicated tests and to rearrange tests into a more
2202 logical order. */
2203 if (cse_tests_p)
2204 {
2205 known_conditions kc;
2206 kc.position_tests.safe_grow_cleared (num_positions);
2207 kc.set_operands.safe_grow_cleared (num_operands);
2208 kc.peep2_count = 1;
2209 cse_tests (&root_pos, root, &kc);
2210 }
2211
2212 /* Try to simplify two or more tests into one. */
2213 if (simplify_tests_p)
2214 simplify_tests (root);
2215
2216 /* Try to use operands[] instead of xN variables. */
2217 if (use_operand_variables_p)
2218 {
2219 auto_vec <int> operand_pos (num_positions);
2220 for (unsigned int i = 0; i < num_positions; ++i)
2221 operand_pos.quick_push (-1);
2222 find_operand_positions (root, operand_pos);
2223 }
2224
2225 /* Print a summary of the new state. */
2226 stats st = get_stats (root);
2227 fprintf (stderr, "Statistics for %s:\n", type);
2228 fprintf (stderr, " Number of decisions: %6d\n", st.num_decisions);
2229 fprintf (stderr, " longest path: %6d (code: %6d)\n",
2230 st.longest_path, st.longest_path_code);
2231 fprintf (stderr, " longest backtrack: %6d (code: %6d)\n",
2232 st.longest_backtrack, st.longest_backtrack_code);
2233}
2234
2235struct merge_pattern_info;
2236
2237/* Represents a transition from one pattern to another. */
2238struct merge_pattern_transition
2239{
2240 merge_pattern_transition (merge_pattern_info *);
2241
2242 /* The target pattern. */
2243 merge_pattern_info *to;
2244
2245 /* The parameters that the source pattern passes to the target pattern.
2246 "parameter (TYPE, true, I)" represents parameter I of the source
2247 pattern. */
2248 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
2249};
2250
2251merge_pattern_transition::merge_pattern_transition (merge_pattern_info *to_in)
2252 : to (to_in)
2253{
2254}
2255
2256/* Represents a pattern that can might match several states. The pattern
2257 may replace parts of the test with a parameter value. It may also
2258 replace transition labels with parameters. */
2259struct merge_pattern_info
2260{
2261 merge_pattern_info (unsigned int);
2262
2263 /* If PARAM_TEST_P, the state's singleton test should be generalized
2264 to use the runtime value of PARAMS[PARAM_TEST]. */
2265 unsigned int param_test : 8;
2266
2267 /* If PARAM_TRANSITION_P, the state's single transition label should
2268 be replaced by the runtime value of PARAMS[PARAM_TRANSITION]. */
2269 unsigned int param_transition : 8;
2270
2271 /* True if we have decided to generalize the root decision's test,
2272 as per PARAM_TEST. */
2273 unsigned int param_test_p : 1;
2274
2275 /* Likewise for the root decision's transition, as per PARAM_TRANSITION. */
2276 unsigned int param_transition_p : 1;
2277
2278 /* True if the contents of the structure are completely filled in. */
2279 unsigned int complete_p : 1;
2280
2281 /* The number of pseudo-statements in the pattern. Used to decide
2282 whether it's big enough to break out into a subroutine. */
2283 unsigned int num_statements;
2284
2285 /* The number of states that use this pattern. */
2286 unsigned int num_users;
2287
2288 /* The number of distinct success values that the pattern returns. */
2289 unsigned int num_results;
2290
2291 /* This array has one element for each runtime parameter to the pattern.
2292 PARAMS[I] gives the default value of parameter I, which is always
2293 constant.
2294
2295 These default parameters are used in cases where we match the
2296 pattern against some state S1, then add more parameters while
2297 matching against some state S2. S1 is then left passing fewer
2298 parameters than S2. The array gives us enough informatino to
2299 construct a full parameter list for S1 (see update_parameters).
2300
2301 If we decide to create a subroutine for this pattern,
2302 PARAMS[I].type determines the C type of parameter I. */
2303 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
2304
2305 /* All states that match this pattern must have the same number of
2306 transitions. TRANSITIONS[I] describes the subpattern for transition
2307 number I; it is null if transition I represents a successful return
2308 from the pattern. */
2309 auto_vec <merge_pattern_transition *, 1> transitions;
2310
2311 /* The routine associated with the pattern, or null if we haven't generated
2312 one yet. */
2313 pattern_routine *routine;
2314};
2315
2316merge_pattern_info::merge_pattern_info (unsigned int num_transitions)
2317 : param_test (0),
2318 param_transition (0),
2319 param_test_p (false),
2320 param_transition_p (false),
2321 complete_p (false),
2322 num_statements (0),
2323 num_users (0),
2324 num_results (0),
2325 routine (0)
2326{
2327 transitions.safe_grow_cleared (num_transitions);
2328}
2329
2330/* Describes one way of matching a particular state to a particular
2331 pattern. */
2332struct merge_state_result
2333{
2334 merge_state_result (merge_pattern_info *, position *, merge_state_result *);
2335
2336 /* A pattern that matches the state. */
2337 merge_pattern_info *pattern;
2338
2339 /* If we decide to use this match and create a subroutine for PATTERN,
2340 the state should pass the rtx at position ROOT to the pattern's
2341 rtx parameter. A null root means that the pattern doesn't need
2342 an rtx parameter; all the rtxes it matches come from elsewhere. */
2343 position *root;
2344
2345 /* The parameters that should be passed to PATTERN for this state.
2346 If the array is shorter than PATTERN->params, the missing entries
2347 should be taken from the corresponding element of PATTERN->params. */
2348 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
2349
2350 /* An earlier match for the same state, or null if none. Patterns
2351 matched by earlier entries are smaller than PATTERN. */
2352 merge_state_result *prev;
2353};
2354
2355merge_state_result::merge_state_result (merge_pattern_info *pattern_in,
2356 position *root_in,
2357 merge_state_result *prev_in)
2358 : pattern (pattern_in), root (root_in), prev (prev_in)
2359{}
2360
2361/* Information about a state, used while trying to match it against
2362 a pattern. */
2363struct merge_state_info
2364{
2365 merge_state_info (state *);
2366
2367 /* The state itself. */
2368 state *s;
2369
2370 /* Index I gives information about the target of transition I. */
2371 merge_state_info *to_states;
2372
2373 /* The number of transitions in S. */
2374 unsigned int num_transitions;
2375
2376 /* True if the state has been deleted in favor of a call to a
2377 pattern routine. */
2378 bool merged_p;
2379
2380 /* The previous state that might be a merge candidate for S, or null
2381 if no previous states could be merged with S. */
2382 merge_state_info *prev_same_test;
2383
2384 /* A list of pattern matches for this state. */
2385 merge_state_result *res;
2386};
2387
2388merge_state_info::merge_state_info (state *s_in)
2389 : s (s_in),
2390 to_states (0),
2391 num_transitions (0),
2392 merged_p (false),
2393 prev_same_test (0),
2394 res (0) {}
2395
2396/* True if PAT would be useful as a subroutine. */
2397
2398static bool
2399useful_pattern_p (merge_pattern_info *pat)
2400{
2401 return pat->num_statements >= MIN_COMBINE_COST;
2402}
2403
2404/* PAT2 is a subpattern of PAT1. Return true if PAT2 should be inlined
2405 into PAT1's C routine. */
2406
2407static bool
2408same_pattern_p (merge_pattern_info *pat1, merge_pattern_info *pat2)
2409{
2410 return pat1->num_users == pat2->num_users || !useful_pattern_p (pat2);
2411}
2412
2413/* PAT was previously matched against SINFO based on tentative matches
2414 for the target states of SINFO's state. Return true if the match
2415 still holds; that is, if the target states of SINFO's state still
2416 match the corresponding transitions of PAT. */
2417
2418static bool
2419valid_result_p (merge_pattern_info *pat, merge_state_info *sinfo)
2420{
2421 for (unsigned int j = 0; j < sinfo->num_transitions; ++j)
2422 if (merge_pattern_transition *ptrans = pat->transitions[j])
2423 {
2424 merge_state_result *to_res = sinfo->to_states[j].res;
2425 if (!to_res || to_res->pattern != ptrans->to)
2426 return false;
2427 }
2428 return true;
2429}
2430
2431/* Remove any matches that are no longer valid from the head of SINFO's
2432 list of matches. */
2433
2434static void
2435prune_invalid_results (merge_state_info *sinfo)
2436{
2437 while (sinfo->res && !valid_result_p (sinfo->res->pattern, sinfo))
2438 {
2439 sinfo->res = sinfo->res->prev;
2440 gcc_assert (sinfo->res);
a698628e 2441 }
6d69ff19 2442}
263287f7 2443
59250a8d 2444/* Return true if PAT represents the biggest posssible match for SINFO;
2445 that is, if the next action of SINFO's state on return from PAT will
2446 be something that cannot be merged with any other state. */
2447
2448static bool
2449complete_result_p (merge_pattern_info *pat, merge_state_info *sinfo)
2450{
2451 for (unsigned int j = 0; j < sinfo->num_transitions; ++j)
2452 if (sinfo->to_states[j].res && !pat->transitions[j])
2453 return false;
2454 return true;
2455}
2456
2457/* Update TO for any parameters that have been added to FROM since TO
2458 was last set. The extra parameters in FROM will be constants or
2459 instructions to duplicate earlier parameters. */
263287f7 2460
6d69ff19 2461static void
59250a8d 2462update_parameters (vec <parameter> &to, const vec <parameter> &from)
6d69ff19 2463{
59250a8d 2464 for (unsigned int i = to.length (); i < from.length (); ++i)
2465 to.quick_push (from[i]);
2466}
6d69ff19 2467
59250a8d 2468/* Return true if A and B can be tested by a single test. If the test
2469 can be parameterised, store the parameter value for A in *PARAMA and
2470 the parameter value for B in *PARAMB, otherwise leave PARAMA and
2471 PARAMB alone. */
2472
2473static bool
abef0e58 2474compatible_tests_p (const rtx_test &a, const rtx_test &b,
59250a8d 2475 parameter *parama, parameter *paramb)
2476{
2477 if (a.kind != b.kind)
2478 return false;
2479 switch (a.kind)
a698628e 2480 {
abef0e58 2481 case rtx_test::PREDICATE:
59250a8d 2482 if (a.u.predicate.data != b.u.predicate.data)
2483 return false;
2484 *parama = parameter (parameter::MODE, false, a.u.predicate.mode);
2485 *paramb = parameter (parameter::MODE, false, b.u.predicate.mode);
2486 return true;
2487
abef0e58 2488 case rtx_test::SAVED_CONST_INT:
59250a8d 2489 *parama = parameter (parameter::INT, false, a.u.integer.value);
2490 *paramb = parameter (parameter::INT, false, b.u.integer.value);
2491 return true;
2492
2493 default:
2494 return a == b;
a698628e 2495 }
59250a8d 2496}
2497
2498/* PARAMS is an array of the parameters that a state is going to pass
2499 to a pattern routine. It is still incomplete; index I has a kind of
2500 parameter::UNSET if we don't yet know what the state will pass
2501 as parameter I. Try to make parameter ID equal VALUE, returning
2502 true on success. */
263287f7 2503
59250a8d 2504static bool
2505set_parameter (vec <parameter> &params, unsigned int id,
2506 const parameter &value)
2507{
2508 if (params[id].type == parameter::UNSET)
a698628e 2509 {
59250a8d 2510 if (force_unique_params_p)
2511 for (unsigned int i = 0; i < params.length (); ++i)
2512 if (params[i] == value)
2513 return false;
2514 params[id] = value;
2515 return true;
2516 }
2517 return params[id] == value;
2518}
2519
2520/* PARAMS2 is the "params" array for a pattern and PARAMS1 is the
2521 set of parameters that a particular state is going to pass to
2522 that pattern.
2523
2524 Try to extend PARAMS1 and PARAMS2 so that there is a parameter
2525 that is equal to PARAM1 for the state and has a default value of
2526 PARAM2. Parameters beginning at START were added as part of the
2527 same match and so may be reused. */
2528
2529static bool
2530add_parameter (vec <parameter> &params1, vec <parameter> &params2,
2531 const parameter &param1, const parameter &param2,
2532 unsigned int start, unsigned int *res)
2533{
2534 gcc_assert (params1.length () == params2.length ());
2535 gcc_assert (!param1.is_param && !param2.is_param);
2536
2537 for (unsigned int i = start; i < params2.length (); ++i)
2538 if (params1[i] == param1 && params2[i] == param2)
2539 {
2540 *res = i;
2541 return true;
2542 }
2543
2544 if (force_unique_params_p)
2545 for (unsigned int i = 0; i < params2.length (); ++i)
2546 if (params1[i] == param1 || params2[i] == param2)
2547 return false;
2548
2549 if (params2.length () >= MAX_PATTERN_PARAMS)
2550 return false;
6d69ff19 2551
59250a8d 2552 *res = params2.length ();
2553 params1.quick_push (param1);
2554 params2.quick_push (param2);
2555 return true;
2556}
2557
2558/* If *ROOTA is nonnull, return true if the same sequence of steps are
2559 required to reach A from *ROOTA as to reach B from ROOTB. If *ROOTA
2560 is null, update it if necessary in order to make the condition hold. */
2561
2562static bool
2563merge_relative_positions (position **roota, position *a,
2564 position *rootb, position *b)
2565{
2566 if (!relative_patterns_p)
2567 {
2568 if (a != b)
2569 return false;
2570 if (!*roota)
6d69ff19 2571 {
59250a8d 2572 *roota = rootb;
2573 return true;
6d69ff19 2574 }
59250a8d 2575 return *roota == rootb;
2576 }
2577 /* If B does not belong to the same instruction as ROOTB, we don't
2578 start with ROOTB but instead start with a call to peep2_next_insn.
2579 In that case the sequences for B and A are identical iff B and A
2580 are themselves identical. */
2581 if (rootb->insn_id != b->insn_id)
2582 return a == b;
2583 while (rootb != b)
2584 {
2585 if (!a || b->type != a->type || b->arg != a->arg)
2586 return false;
2587 b = b->base;
2588 a = a->base;
263287f7 2589 }
59250a8d 2590 if (!*roota)
2591 *roota = a;
2592 return *roota == a;
2593}
263287f7 2594
59250a8d 2595/* A hasher of states that treats two states as "equal" if they might be
2596 merged (but trying to be more discriminating than "return true"). */
770ff93b 2597struct test_pattern_hasher : nofree_ptr_hash <merge_state_info>
59250a8d 2598{
59250a8d 2599 static inline hashval_t hash (const value_type &);
2600 static inline bool equal (const value_type &, const compare_type &);
2601};
263287f7 2602
59250a8d 2603hashval_t
2604test_pattern_hasher::hash (merge_state_info *const &sinfo)
2605{
2606 inchash::hash h;
2607 decision *d = sinfo->s->singleton ();
2608 h.add_int (d->test.pos_operand + 1);
2609 if (!relative_patterns_p)
2610 h.add_int (d->test.pos ? d->test.pos->id + 1 : 0);
2611 h.add_int (d->test.kind);
2612 h.add_int (sinfo->num_transitions);
2613 return h.end ();
2614}
6d69ff19 2615
59250a8d 2616bool
2617test_pattern_hasher::equal (merge_state_info *const &sinfo1,
2618 merge_state_info *const &sinfo2)
2619{
2620 decision *d1 = sinfo1->s->singleton ();
2621 decision *d2 = sinfo2->s->singleton ();
2622 gcc_assert (d1 && d2);
2623
2624 parameter new_param1, new_param2;
2625 return (d1->test.pos_operand == d2->test.pos_operand
2626 && (relative_patterns_p || d1->test.pos == d2->test.pos)
2627 && compatible_tests_p (d1->test, d2->test, &new_param1, &new_param2)
2628 && sinfo1->num_transitions == sinfo2->num_transitions);
2629}
6d69ff19 2630
59250a8d 2631/* Try to make the state described by SINFO1 use the same pattern as the
2632 state described by SINFO2. Return true on success.
3e9f1237 2633
59250a8d 2634 SINFO1 and SINFO2 are known to have the same hash value. */
2635
2636static bool
2637merge_patterns (merge_state_info *sinfo1, merge_state_info *sinfo2)
2638{
2639 merge_state_result *res2 = sinfo2->res;
2640 merge_pattern_info *pat = res2->pattern;
2641
2642 /* Write to temporary arrays while matching, in case we have to abort
2643 half way through. */
2644 auto_vec <parameter, MAX_PATTERN_PARAMS> params1;
2645 auto_vec <parameter, MAX_PATTERN_PARAMS> params2;
2646 params1.quick_grow_cleared (pat->params.length ());
2647 params2.splice (pat->params);
2648 unsigned int start_param = params2.length ();
2649
2650 /* An array for recording changes to PAT->transitions[?].params.
2651 All changes involve replacing a constant parameter with some
2652 PAT->params[N], where N is the second element of the pending_param. */
2653 typedef std::pair <parameter *, unsigned int> pending_param;
2654 auto_vec <pending_param, 32> pending_params;
2655
2656 decision *d1 = sinfo1->s->singleton ();
2657 decision *d2 = sinfo2->s->singleton ();
2658 gcc_assert (d1 && d2);
2659
2660 /* If D2 tests a position, SINFO1's root relative to D1 is the same
2661 as SINFO2's root relative to D2. */
2662 position *root1 = 0;
2663 position *root2 = res2->root;
2664 if (d2->test.pos_operand < 0
2665 && d1->test.pos
2666 && !merge_relative_positions (&root1, d1->test.pos,
2667 root2, d2->test.pos))
2668 return false;
2669
2670 /* Check whether the patterns have the same shape. */
2671 unsigned int num_transitions = sinfo1->num_transitions;
2672 gcc_assert (num_transitions == sinfo2->num_transitions);
2673 for (unsigned int i = 0; i < num_transitions; ++i)
2674 if (merge_pattern_transition *ptrans = pat->transitions[i])
2675 {
2676 merge_state_result *to1_res = sinfo1->to_states[i].res;
2677 merge_state_result *to2_res = sinfo2->to_states[i].res;
2678 merge_pattern_info *to_pat = ptrans->to;
2679 gcc_assert (to2_res && to2_res->pattern == to_pat);
2680 if (!to1_res || to1_res->pattern != to_pat)
2681 return false;
2682 if (to2_res->root
2683 && !merge_relative_positions (&root1, to1_res->root,
2684 root2, to2_res->root))
2685 return false;
2686 /* Match the parameters that TO1_RES passes to TO_PAT with the
2687 parameters that PAT passes to TO_PAT. */
2688 update_parameters (to1_res->params, to_pat->params);
2689 for (unsigned int j = 0; j < to1_res->params.length (); ++j)
2690 {
2691 const parameter &param1 = to1_res->params[j];
2692 const parameter &param2 = ptrans->params[j];
2693 gcc_assert (!param1.is_param);
2694 if (param2.is_param)
2695 {
2696 if (!set_parameter (params1, param2.value, param1))
2697 return false;
2698 }
2699 else if (param1 != param2)
2700 {
2701 unsigned int id;
2702 if (!add_parameter (params1, params2,
2703 param1, param2, start_param, &id))
2704 return false;
2705 /* Record that PAT should now pass parameter ID to TO_PAT,
2706 instead of the current contents of *PARAM2. We only
2707 make the change if the rest of the match succeeds. */
2708 pending_params.safe_push
2709 (pending_param (&ptrans->params[j], id));
2710 }
3e9f1237 2711 }
59250a8d 2712 }
6d69ff19 2713
59250a8d 2714 unsigned int param_test = pat->param_test;
2715 unsigned int param_transition = pat->param_transition;
2716 bool param_test_p = pat->param_test_p;
2717 bool param_transition_p = pat->param_transition_p;
2718
2719 /* If the tests don't match exactly, try to parameterize them. */
2720 parameter new_param1, new_param2;
2721 if (!compatible_tests_p (d1->test, d2->test, &new_param1, &new_param2))
2722 gcc_unreachable ();
2723 if (new_param1.type != parameter::UNSET)
2724 {
2725 /* If the test has not already been parameterized, all existing
2726 matches use constant NEW_PARAM2. */
2727 if (param_test_p)
2728 {
2729 if (!set_parameter (params1, param_test, new_param1))
2730 return false;
2731 }
2732 else if (new_param1 != new_param2)
2733 {
2734 if (!add_parameter (params1, params2, new_param1, new_param2,
2735 start_param, &param_test))
2736 return false;
2737 param_test_p = true;
6d69ff19 2738 }
263287f7 2739 }
59250a8d 2740
2741 /* Match the transitions. */
2742 transition *trans1 = d1->first;
2743 transition *trans2 = d2->first;
2744 for (unsigned int i = 0; i < num_transitions; ++i)
6d69ff19 2745 {
59250a8d 2746 if (param_transition_p || trans1->labels != trans2->labels)
2747 {
2748 /* We can only generalize a single transition with a single
2749 label. */
2750 if (num_transitions != 1
2751 || trans1->labels.length () != 1
2752 || trans2->labels.length () != 1)
2753 return false;
2754
2755 /* Although we can match wide-int fields, in practice it leads
2756 to some odd results for const_vectors. We end up
2757 parameterizing the first N const_ints of the vector
2758 and then (once we reach the maximum number of parameters)
2759 we go on to match the other elements exactly. */
abef0e58 2760 if (d1->test.kind == rtx_test::WIDE_INT_FIELD)
59250a8d 2761 return false;
2762
2763 /* See whether the label has a generalizable type. */
2764 parameter::type_enum param_type
2765 = transition_parameter_type (d1->test.kind);
2766 if (param_type == parameter::UNSET)
2767 return false;
2768
2769 /* Match the labels using parameters. */
2770 new_param1 = parameter (param_type, false, trans1->labels[0]);
2771 if (param_transition_p)
2772 {
2773 if (!set_parameter (params1, param_transition, new_param1))
2774 return false;
2775 }
2776 else
2777 {
2778 new_param2 = parameter (param_type, false, trans2->labels[0]);
2779 if (!add_parameter (params1, params2, new_param1, new_param2,
2780 start_param, &param_transition))
2781 return false;
2782 param_transition_p = true;
2783 }
2784 }
2785 trans1 = trans1->next;
2786 trans2 = trans2->next;
6d69ff19 2787 }
263287f7 2788
59250a8d 2789 /* Set any unset parameters to their default values. This occurs if some
2790 other state needed something to be parameterized in order to match SINFO2,
2791 but SINFO1 on its own does not. */
2792 for (unsigned int i = 0; i < params1.length (); ++i)
2793 if (params1[i].type == parameter::UNSET)
2794 params1[i] = params2[i];
2795
2796 /* The match was successful. Commit all pending changes to PAT. */
2797 update_parameters (pat->params, params2);
2798 {
2799 pending_param *pp;
2800 unsigned int i;
2801 FOR_EACH_VEC_ELT (pending_params, i, pp)
2802 *pp->first = parameter (pp->first->type, true, pp->second);
2803 }
2804 pat->param_test = param_test;
2805 pat->param_transition = param_transition;
2806 pat->param_test_p = param_test_p;
2807 pat->param_transition_p = param_transition_p;
2808
2809 /* Record the match of SINFO1. */
2810 merge_state_result *new_res1 = new merge_state_result (pat, root1,
2811 sinfo1->res);
2812 new_res1->params.splice (params1);
2813 sinfo1->res = new_res1;
2814 return true;
263287f7 2815}
2816
59250a8d 2817/* The number of states that were removed by calling pattern routines. */
2818static unsigned int pattern_use_states;
6d69ff19 2819
59250a8d 2820/* The number of states used while defining pattern routines. */
2821static unsigned int pattern_def_states;
2822
2823/* Information used while constructing a use or definition of a pattern
2824 routine. */
2825struct create_pattern_info
2826{
2827 /* The routine itself. */
2828 pattern_routine *routine;
2829
2830 /* The first unclaimed return value for this particular use or definition.
2831 We walk the substates of uses and definitions in the same order
2832 so each return value always refers to the same position within
2833 the pattern. */
2834 unsigned int next_result;
2835};
2836
2837static void populate_pattern_routine (create_pattern_info *,
2838 merge_state_info *, state *,
2839 const vec <parameter> &);
2840
2841/* SINFO matches a pattern for which we've decided to create a C routine.
2842 Return a decision that performs a call to the pattern routine,
2843 but leave the caller to add the transitions to it. Initialize CPI
2844 for this purpose. Also create a definition for the pattern routine,
2845 if it doesn't already have one.
2846
2847 PARAMS are the parameters that SINFO passes to its pattern. */
2848
2849static decision *
2850init_pattern_use (create_pattern_info *cpi, merge_state_info *sinfo,
2851 const vec <parameter> &params)
263287f7 2852{
59250a8d 2853 state *s = sinfo->s;
2854 merge_state_result *res = sinfo->res;
2855 merge_pattern_info *pat = res->pattern;
2856 cpi->routine = pat->routine;
2857 if (!cpi->routine)
2858 {
2859 /* We haven't defined the pattern routine yet, so create
2860 a definition now. */
2861 pattern_routine *routine = new pattern_routine;
2862 pat->routine = routine;
2863 cpi->routine = routine;
2864 routine->s = new state;
2865 routine->insn_p = false;
2866 routine->pnum_clobbers_p = false;
2867
2868 /* Create an "idempotent" mapping of parameter I to parameter I.
2869 Also record the C type of each parameter to the routine. */
2870 auto_vec <parameter, MAX_PATTERN_PARAMS> def_params;
2871 for (unsigned int i = 0; i < pat->params.length (); ++i)
2872 {
2873 def_params.quick_push (parameter (pat->params[i].type, true, i));
2874 routine->param_types.quick_push (pat->params[i].type);
2875 }
2876
2877 /* Any of the states that match the pattern could be used to
2878 create the routine definition. We might as well use SINFO
2879 since it's already to hand. This means that all positions
2880 in the definition will be relative to RES->root. */
2881 routine->pos = res->root;
2882 cpi->next_result = 0;
2883 populate_pattern_routine (cpi, sinfo, routine->s, def_params);
2884 gcc_assert (cpi->next_result == pat->num_results);
2885
2886 /* Add the routine to the global list, after the subroutines
2887 that it calls. */
2888 routine->pattern_id = patterns.length ();
2889 patterns.safe_push (routine);
2890 }
2891
2892 /* Create a decision to call the routine, passing PARAMS to it. */
2893 pattern_use *use = new pattern_use;
2894 use->routine = pat->routine;
2895 use->params.splice (params);
abef0e58 2896 decision *d = new decision (rtx_test::pattern (res->root, use));
59250a8d 2897
2898 /* If the original decision could use an element of operands[] instead
2899 of an rtx variable, try to transfer it to the new decision. */
2900 if (s->first->test.pos && res->root == s->first->test.pos)
2901 d->test.pos_operand = s->first->test.pos_operand;
2902
2903 cpi->next_result = 0;
2904 return d;
2905}
2906
2907/* Make S return the next unclaimed pattern routine result for CPI. */
2908
2909static void
2910add_pattern_acceptance (create_pattern_info *cpi, state *s)
2911{
2912 acceptance_type acceptance;
2913 acceptance.type = SUBPATTERN;
2914 acceptance.partial_p = false;
2915 acceptance.u.full.code = cpi->next_result;
abef0e58 2916 add_decision (s, rtx_test::accept (acceptance), true, false);
59250a8d 2917 cpi->next_result += 1;
2918}
2919
2920/* Initialize new empty state NEWS so that it implements SINFO's pattern
2921 (here referred to as "P"). P may be the top level of a pattern routine
2922 or a subpattern that should be inlined into its parent pattern's routine
2923 (as per same_pattern_p). The choice of SINFO for a top-level pattern is
2924 arbitrary; it could be any of the states that use P. The choice for
2925 subpatterns follows the choice for the parent pattern.
2926
2927 PARAMS gives the value of each parameter to P in terms of the parameters
2928 to the top-level pattern. If P itself is the top level pattern, PARAMS[I]
2929 is always "parameter (TYPE, true, I)". */
263287f7 2930
59250a8d 2931static void
2932populate_pattern_routine (create_pattern_info *cpi, merge_state_info *sinfo,
2933 state *news, const vec <parameter> &params)
2934{
2935 pattern_def_states += 1;
2936
2937 decision *d = sinfo->s->singleton ();
2938 merge_pattern_info *pat = sinfo->res->pattern;
2939 pattern_routine *routine = cpi->routine;
2940
2941 /* Create a copy of D's test for the pattern routine and generalize it
2942 as appropriate. */
2943 decision *newd = new decision (d->test);
2944 gcc_assert (newd->test.pos_operand >= 0
2945 || !newd->test.pos
2946 || common_position (newd->test.pos,
2947 routine->pos) == routine->pos);
2948 if (pat->param_test_p)
6d69ff19 2949 {
59250a8d 2950 const parameter &param = params[pat->param_test];
2951 switch (newd->test.kind)
6d69ff19 2952 {
abef0e58 2953 case rtx_test::PREDICATE:
59250a8d 2954 newd->test.u.predicate.mode_is_param = param.is_param;
2955 newd->test.u.predicate.mode = param.value;
2956 break;
2957
abef0e58 2958 case rtx_test::SAVED_CONST_INT:
59250a8d 2959 newd->test.u.integer.is_param = param.is_param;
2960 newd->test.u.integer.value = param.value;
2961 break;
2962
6d69ff19 2963 default:
e0a4c0c2 2964 gcc_unreachable ();
59250a8d 2965 break;
6d69ff19 2966 }
2967 }
abef0e58 2968 if (d->test.kind == rtx_test::C_TEST)
59250a8d 2969 routine->insn_p = true;
abef0e58 2970 else if (d->test.kind == rtx_test::HAVE_NUM_CLOBBERS)
59250a8d 2971 routine->pnum_clobbers_p = true;
2972 news->push_back (newd);
2973
2974 /* Fill in the transitions of NEWD. */
2975 unsigned int i = 0;
2976 for (transition *trans = d->first; trans; trans = trans->next)
2977 {
2978 /* Create a new state to act as the target of the new transition. */
2979 state *to_news = new state;
2980 if (merge_pattern_transition *ptrans = pat->transitions[i])
2981 {
2982 /* The pattern hasn't finished matching yet. Get the target
2983 pattern and the corresponding target state of SINFO. */
2984 merge_pattern_info *to_pat = ptrans->to;
2985 merge_state_info *to = sinfo->to_states + i;
2986 gcc_assert (to->res->pattern == to_pat);
2987 gcc_assert (ptrans->params.length () == to_pat->params.length ());
2988
2989 /* Express the parameters to TO_PAT in terms of the parameters
2990 to the top-level pattern. */
2991 auto_vec <parameter, MAX_PATTERN_PARAMS> to_params;
2992 for (unsigned int j = 0; j < ptrans->params.length (); ++j)
2993 {
2994 const parameter &param = ptrans->params[j];
2995 to_params.quick_push (param.is_param
2996 ? params[param.value]
2997 : param);
2998 }
263287f7 2999
59250a8d 3000 if (same_pattern_p (pat, to_pat))
3001 /* TO_PAT is part of the current routine, so just recurse. */
3002 populate_pattern_routine (cpi, to, to_news, to_params);
3003 else
3004 {
3005 /* TO_PAT should be matched by calling a separate routine. */
3006 create_pattern_info sub_cpi;
3007 decision *subd = init_pattern_use (&sub_cpi, to, to_params);
3008 routine->insn_p |= sub_cpi.routine->insn_p;
3009 routine->pnum_clobbers_p |= sub_cpi.routine->pnum_clobbers_p;
263287f7 3010
59250a8d 3011 /* Add the pattern routine call to the new target state. */
3012 to_news->push_back (subd);
6d69ff19 3013
59250a8d 3014 /* Add a transition for each successful call result. */
3015 for (unsigned int j = 0; j < to_pat->num_results; ++j)
3016 {
3017 state *res = new state;
3018 add_pattern_acceptance (cpi, res);
3019 subd->push_back (new transition (j, res, false));
3020 }
3021 }
3022 }
3023 else
3024 /* This transition corresponds to a successful match. */
3025 add_pattern_acceptance (cpi, to_news);
3026
3027 /* Create the transition itself, generalizing as necessary. */
3028 transition *new_trans = new transition (trans->labels, to_news,
3029 trans->optional);
3030 if (pat->param_transition_p)
7e5202bc 3031 {
59250a8d 3032 const parameter &param = params[pat->param_transition];
3033 new_trans->is_param = param.is_param;
3034 new_trans->labels[0] = param.value;
7e5202bc 3035 }
59250a8d 3036 newd->push_back (new_trans);
3037 i += 1;
7e5202bc 3038 }
59250a8d 3039}
3040
3041/* USE is a decision that calls a pattern routine and SINFO is part of the
3042 original state tree that the call is supposed to replace. Add the
3043 transitions for SINFO and its substates to USE. */
7e5202bc 3044
59250a8d 3045static void
3046populate_pattern_use (create_pattern_info *cpi, decision *use,
3047 merge_state_info *sinfo)
3048{
3049 pattern_use_states += 1;
3050 gcc_assert (!sinfo->merged_p);
3051 sinfo->merged_p = true;
3052 merge_state_result *res = sinfo->res;
3053 merge_pattern_info *pat = res->pattern;
3054 decision *d = sinfo->s->singleton ();
3055 unsigned int i = 0;
3056 for (transition *trans = d->first; trans; trans = trans->next)
6d69ff19 3057 {
59250a8d 3058 if (pat->transitions[i])
3059 /* The target state is also part of the pattern. */
3060 populate_pattern_use (cpi, use, sinfo->to_states + i);
3061 else
3062 {
3063 /* The transition corresponds to a successful return from the
3064 pattern routine. */
3065 use->push_back (new transition (cpi->next_result, trans->to, false));
3066 cpi->next_result += 1;
3067 }
3068 i += 1;
3069 }
3070}
3071
3072/* We have decided to replace SINFO's state with a call to a pattern
3073 routine. Make the change, creating a definition of the pattern routine
3074 if it doesn't have one already. */
6d69ff19 3075
59250a8d 3076static void
3077use_pattern (merge_state_info *sinfo)
3078{
3079 merge_state_result *res = sinfo->res;
3080 merge_pattern_info *pat = res->pattern;
3081 state *s = sinfo->s;
3082
3083 /* The pattern may have acquired new parameters after it was matched
3084 against SINFO. Update the parameters that SINFO passes accordingly. */
3085 update_parameters (res->params, pat->params);
3086
3087 create_pattern_info cpi;
3088 decision *d = init_pattern_use (&cpi, sinfo, res->params);
3089 populate_pattern_use (&cpi, d, sinfo);
3090 s->release ();
3091 s->push_back (d);
3092}
3093
3094/* Look through the state trees in STATES for common patterns and
3095 split them into subroutines. */
3096
3097static void
3098split_out_patterns (vec <merge_state_info> &states)
3099{
3100 unsigned int first_transition = states.length ();
3101 hash_table <test_pattern_hasher> hashtab (128);
3102 /* Stage 1: Create an order in which parent states come before their child
3103 states and in which sibling states are at consecutive locations.
3104 Having consecutive sibling states allows merge_state_info to have
3105 a single to_states pointer. */
3106 for (unsigned int i = 0; i < states.length (); ++i)
3107 for (decision *d = states[i].s->first; d; d = d->next)
3108 for (transition *trans = d->first; trans; trans = trans->next)
6d69ff19 3109 {
59250a8d 3110 states.safe_push (trans->to);
3111 states[i].num_transitions += 1;
3112 }
3113 /* Stage 2: Now that the addresses are stable, set up the to_states
3114 pointers. Look for states that might be merged and enter them
3115 into the hash table. */
3116 for (unsigned int i = 0; i < states.length (); ++i)
3117 {
3118 merge_state_info *sinfo = &states[i];
3119 if (sinfo->num_transitions)
3120 {
3121 sinfo->to_states = &states[first_transition];
3122 first_transition += sinfo->num_transitions;
3123 }
3124 /* For simplicity, we only try to merge states that have a single
3125 decision. This is in any case the best we can do for peephole2,
3126 since whether a peephole2 ACCEPT succeeds or not depends on the
3127 specific peephole2 pattern (which is unique to each ACCEPT
3128 and so couldn't be shared between states). */
3129 if (decision *d = sinfo->s->singleton ())
3130 /* ACCEPT states are unique, so don't even try to merge them. */
abef0e58 3131 if (d->test.kind != rtx_test::ACCEPT
59250a8d 3132 && (pattern_have_num_clobbers_p
abef0e58 3133 || d->test.kind != rtx_test::HAVE_NUM_CLOBBERS)
59250a8d 3134 && (pattern_c_test_p
abef0e58 3135 || d->test.kind != rtx_test::C_TEST))
59250a8d 3136 {
3137 merge_state_info **slot = hashtab.find_slot (sinfo, INSERT);
3138 sinfo->prev_same_test = *slot;
3139 *slot = sinfo;
3140 }
3141 }
3142 /* Stage 3: Walk backwards through the list of states and try to merge
3143 them. This is a greedy, bottom-up match; parent nodes can only start
3144 a new leaf pattern if they fail to match when combined with all child
3145 nodes that have matching patterns.
3146
3147 For each state we keep a list of potential matches, with each
3148 potential match being larger (and deeper) than the next match in
3149 the list. The final element in the list is a leaf pattern that
3150 matches just a single state.
3151
3152 Each candidate pattern created in this loop is unique -- it won't
3153 have been seen by an earlier iteration. We try to match each pattern
3154 with every state that appears earlier in STATES.
3155
3156 Because the patterns created in the loop are unique, any state
3157 that already has a match must have a final potential match that
3158 is different from any new leaf pattern. Therefore, when matching
3159 leaf patterns, we need only consider states whose list of matches
3160 is empty.
3161
3162 The non-leaf patterns that we try are as deep as possible
3163 and are an extension of the state's previous best candidate match (PB).
3164 We need only consider states whose current potential match is also PB;
3165 any states that don't match as much as PB cannnot match the new pattern,
3166 while any states that already match more than PB must be different from
3167 the new pattern. */
3168 for (unsigned int i2 = states.length (); i2-- > 0; )
3169 {
3170 merge_state_info *sinfo2 = &states[i2];
3171
3172 /* Enforce the bottom-upness of the match: remove matches with later
3173 states if SINFO2's child states ended up finding a better match. */
3174 prune_invalid_results (sinfo2);
3175
3176 /* Do nothing if the state doesn't match a later one and if there are
3177 no earlier states it could match. */
3178 if (!sinfo2->res && !sinfo2->prev_same_test)
3179 continue;
3180
3181 merge_state_result *res2 = sinfo2->res;
3182 decision *d2 = sinfo2->s->singleton ();
3183 position *root2 = (d2->test.pos_operand < 0 ? d2->test.pos : 0);
3184 unsigned int num_transitions = sinfo2->num_transitions;
3185
3186 /* If RES2 is null then SINFO2's test in isolation has not been seen
3187 before. First try matching that on its own. */
3188 if (!res2)
3189 {
3190 merge_pattern_info *new_pat
3191 = new merge_pattern_info (num_transitions);
3192 merge_state_result *new_res2
3193 = new merge_state_result (new_pat, root2, res2);
3194 sinfo2->res = new_res2;
3195
3196 new_pat->num_statements = !d2->test.single_outcome_p ();
3197 new_pat->num_results = num_transitions;
3198 bool matched_p = false;
3199 /* Look for states that don't currently match anything but
3200 can be made to match SINFO2 on its own. */
3201 for (merge_state_info *sinfo1 = sinfo2->prev_same_test; sinfo1;
3202 sinfo1 = sinfo1->prev_same_test)
3203 if (!sinfo1->res && merge_patterns (sinfo1, sinfo2))
3204 matched_p = true;
3205 if (!matched_p)
3206 {
3207 /* No other states match. */
3208 sinfo2->res = res2;
3209 delete new_pat;
3210 delete new_res2;
3211 continue;
3212 }
3213 else
3214 res2 = new_res2;
3215 }
3216
3217 /* Keep the existing pattern if it's as good as anything we'd
3218 create for SINFO2. */
3219 if (complete_result_p (res2->pattern, sinfo2))
3220 {
3221 res2->pattern->num_users += 1;
3222 continue;
3223 }
3224
3225 /* Create a new pattern for SINFO2. */
3226 merge_pattern_info *new_pat = new merge_pattern_info (num_transitions);
3227 merge_state_result *new_res2
3228 = new merge_state_result (new_pat, root2, res2);
3229 sinfo2->res = new_res2;
3230
3231 /* Fill in details about the pattern. */
3232 new_pat->num_statements = !d2->test.single_outcome_p ();
3233 new_pat->num_results = 0;
3234 for (unsigned int j = 0; j < num_transitions; ++j)
3235 if (merge_state_result *to_res = sinfo2->to_states[j].res)
3236 {
3237 /* Count the target state as part of this pattern.
3238 First update the root position so that it can reach
3239 the target state's root. */
3240 if (to_res->root)
3241 {
3242 if (new_res2->root)
3243 new_res2->root = common_position (new_res2->root,
3244 to_res->root);
3245 else
3246 new_res2->root = to_res->root;
3247 }
3248 merge_pattern_info *to_pat = to_res->pattern;
3249 merge_pattern_transition *ptrans
3250 = new merge_pattern_transition (to_pat);
3251
3252 /* TO_PAT may have acquired more parameters when matching
3253 states earlier in STATES than TO_RES's, but the list is
3254 now final. Make sure that TO_RES is up to date. */
3255 update_parameters (to_res->params, to_pat->params);
3256
3257 /* Start out by assuming that every user of NEW_PAT will
3258 want to pass the same (constant) parameters as TO_RES. */
3259 update_parameters (ptrans->params, to_res->params);
3260
3261 new_pat->transitions[j] = ptrans;
3262 new_pat->num_statements += to_pat->num_statements;
3263 new_pat->num_results += to_pat->num_results;
3264 }
3265 else
3266 /* The target state doesn't match anything and so is not part
3267 of the pattern. */
3268 new_pat->num_results += 1;
3269
3270 /* See if any earlier states that match RES2's pattern also match
3271 NEW_PAT. */
3272 bool matched_p = false;
3273 for (merge_state_info *sinfo1 = sinfo2->prev_same_test; sinfo1;
3274 sinfo1 = sinfo1->prev_same_test)
3275 {
3276 prune_invalid_results (sinfo1);
3277 if (sinfo1->res
3278 && sinfo1->res->pattern == res2->pattern
3279 && merge_patterns (sinfo1, sinfo2))
3280 matched_p = true;
3281 }
3282 if (!matched_p)
3283 {
3284 /* Nothing else matches NEW_PAT, so go back to the previous
3285 pattern (possibly just a single-state one). */
3286 sinfo2->res = res2;
3287 delete new_pat;
3288 delete new_res2;
3289 }
3290 /* Assume that SINFO2 will use RES. At this point we don't know
3291 whether earlier states that match the same pattern will use
3292 that match or a different one. */
3293 sinfo2->res->pattern->num_users += 1;
3294 }
3295 /* Step 4: Finalize the choice of pattern for each state, ignoring
3296 patterns that were only used once. Update each pattern's size
3297 so that it doesn't include subpatterns that are going to be split
3298 out into subroutines. */
3299 for (unsigned int i = 0; i < states.length (); ++i)
3300 {
3301 merge_state_info *sinfo = &states[i];
3302 merge_state_result *res = sinfo->res;
3303 /* Wind past patterns that are only used by SINFO. */
3304 while (res && res->pattern->num_users == 1)
3305 {
3306 res = res->prev;
3307 sinfo->res = res;
3308 if (res)
3309 res->pattern->num_users += 1;
3310 }
3311 if (!res)
3312 continue;
3313
3314 /* We have a shared pattern and are now committed to the match. */
3315 merge_pattern_info *pat = res->pattern;
3316 gcc_assert (valid_result_p (pat, sinfo));
3317
3318 if (!pat->complete_p)
3319 {
3320 /* Look for subpatterns that are going to be split out and remove
3321 them from the number of statements. */
3322 for (unsigned int j = 0; j < sinfo->num_transitions; ++j)
3323 if (merge_pattern_transition *ptrans = pat->transitions[j])
3324 {
3325 merge_pattern_info *to_pat = ptrans->to;
3326 if (!same_pattern_p (pat, to_pat))
3327 pat->num_statements -= to_pat->num_statements;
3328 }
3329 pat->complete_p = true;
3330 }
3331 }
3332 /* Step 5: Split out the patterns. */
3333 for (unsigned int i = 0; i < states.length (); ++i)
3334 {
3335 merge_state_info *sinfo = &states[i];
3336 merge_state_result *res = sinfo->res;
3337 if (!sinfo->merged_p && res && useful_pattern_p (res->pattern))
3338 use_pattern (sinfo);
3339 }
3340 fprintf (stderr, "Shared %d out of %d states by creating %d new states,"
3341 " saving %d\n",
3342 pattern_use_states, states.length (), pattern_def_states,
3343 pattern_use_states - pattern_def_states);
3344}
3345
3346/* Information about a state tree that we're considering splitting into a
3347 subroutine. */
3348struct state_size
3349{
3350 /* The number of pseudo-statements in the state tree. */
3351 unsigned int num_statements;
3352
3353 /* The approximate number of nested "if" and "switch" statements that
3354 would be required if control could fall through to a later state. */
3355 unsigned int depth;
3356};
3357
3358/* Pairs a transition with information about its target state. */
3359typedef std::pair <transition *, state_size> subroutine_candidate;
3360
3361/* Sort two subroutine_candidates so that the one with the largest
3362 number of statements comes last. */
3363
3364static int
3365subroutine_candidate_cmp (const void *a, const void *b)
3366{
3367 return int (((const subroutine_candidate *) a)->second.num_statements
3368 - ((const subroutine_candidate *) b)->second.num_statements);
3369}
3370
3371/* Turn S into a subroutine of type TYPE and add it to PROCS. Return a new
3372 state that performs a subroutine call to S. */
3373
3374static state *
3375create_subroutine (routine_type type, state *s, vec <state *> &procs)
3376{
3377 procs.safe_push (s);
3378 acceptance_type acceptance;
3379 acceptance.type = type;
3380 acceptance.partial_p = true;
3381 acceptance.u.subroutine_id = procs.length ();
3382 state *news = new state;
abef0e58 3383 add_decision (news, rtx_test::accept (acceptance), true, false);
59250a8d 3384 return news;
3385}
3386
3387/* Walk state tree S, of type TYPE, and look for subtrees that would be
3388 better split into subroutines. Accumulate all such subroutines in PROCS.
3389 Return the size of the new state tree (excluding subroutines). */
3390
3391static state_size
3392find_subroutines (routine_type type, state *s, vec <state *> &procs)
3393{
3394 auto_vec <subroutine_candidate, 16> candidates;
3395 state_size size;
3396 size.num_statements = 0;
3397 size.depth = 0;
3398 for (decision *d = s->first; d; d = d->next)
3399 {
3400 if (!d->test.single_outcome_p ())
3401 size.num_statements += 1;
3402 for (transition *trans = d->first; trans; trans = trans->next)
3403 {
3404 /* Keep chains of simple decisions together if we know that no
3405 change of position is required. We'll output this chain as a
3406 single "if" statement, so it counts as a single nesting level. */
3407 if (d->test.pos && d->if_statement_p ())
3408 for (;;)
3409 {
3410 decision *newd = trans->to->singleton ();
3411 if (!newd
3412 || (newd->test.pos
3413 && newd->test.pos_operand < 0
3414 && newd->test.pos != d->test.pos)
3415 || !newd->if_statement_p ())
3416 break;
3417 if (!newd->test.single_outcome_p ())
3418 size.num_statements += 1;
3419 trans = newd->singleton ();
abef0e58 3420 if (newd->test.kind == rtx_test::SET_OP
3421 || newd->test.kind == rtx_test::ACCEPT)
59250a8d 3422 break;
3423 }
3424 /* The target of TRANS is a subroutine candidate. First recurse
3425 on it to see how big it is after subroutines have been
3426 split out. */
3427 state_size to_size = find_subroutines (type, trans->to, procs);
3428 if (d->next && to_size.depth > MAX_DEPTH)
3429 /* Keeping the target state in the same routine would lead
3430 to an excessive nesting of "if" and "switch" statements.
3431 Split it out into a subroutine so that it can use
3432 inverted tests that return early on failure. */
3433 trans->to = create_subroutine (type, trans->to, procs);
3434 else
3435 {
3436 size.num_statements += to_size.num_statements;
3437 if (to_size.num_statements < MIN_NUM_STATEMENTS)
3438 /* The target state is too small to be worth splitting.
3439 Keep it in the same routine as S. */
3440 size.depth = MAX (size.depth, to_size.depth);
3441 else
3442 /* Assume for now that we'll keep the target state in the
3443 same routine as S, but record it as a subroutine candidate
3444 if S grows too big. */
3445 candidates.safe_push (subroutine_candidate (trans, to_size));
3446 }
3447 }
3448 }
3449 if (size.num_statements > MAX_NUM_STATEMENTS)
3450 {
3451 /* S is too big. Sort the subroutine candidates so that bigger ones
3452 are nearer the end. */
3453 candidates.qsort (subroutine_candidate_cmp);
3454 while (!candidates.is_empty ()
3455 && size.num_statements > MAX_NUM_STATEMENTS)
3456 {
3457 /* Peel off a candidate and force it into a subroutine. */
3458 subroutine_candidate cand = candidates.pop ();
3459 size.num_statements -= cand.second.num_statements;
3460 cand.first->to = create_subroutine (type, cand.first->to, procs);
3461 }
3462 }
3463 /* Update the depth for subroutine candidates that we decided not to
3464 split out. */
3465 for (unsigned int i = 0; i < candidates.length (); ++i)
3466 size.depth = MAX (size.depth, candidates[i].second.depth);
3467 size.depth += 1;
3468 return size;
3469}
3470
3471/* Return true if, for all X, PRED (X, MODE) implies that X has mode MODE. */
3472
3473static bool
3474safe_predicate_mode (const struct pred_data *pred, machine_mode mode)
3475{
3476 /* Scalar integer constants have VOIDmode. */
3477 if (GET_MODE_CLASS (mode) == MODE_INT
3478 && (pred->codes[CONST_INT]
3479 || pred->codes[CONST_DOUBLE]
8770d0ad 3480 || pred->codes[CONST_WIDE_INT]
3481 || pred->codes[LABEL_REF]))
59250a8d 3482 return false;
3483
3484 return !pred->special && mode != VOIDmode;
3485}
3486
3487/* Fill CODES with the set of codes that could be matched by PRED. */
3488
3489static void
3490get_predicate_codes (const struct pred_data *pred, int_set *codes)
3491{
3492 for (int i = 0; i < NUM_TRUE_RTX_CODE; ++i)
3493 if (!pred || pred->codes[i])
3494 codes->safe_push (i);
3495}
3496
3497/* Return true if the first path through D1 tests the same thing as D2. */
3498
3499static bool
3500has_same_test_p (decision *d1, decision *d2)
3501{
3502 do
3503 {
3504 if (d1->test == d2->test)
3505 return true;
3506 d1 = d1->first->to->first;
3507 }
3508 while (d1);
3509 return false;
3510}
3511
3512/* Return true if D1 and D2 cannot match the same rtx. All states reachable
3513 from D2 have single decisions and all those decisions have single
3514 transitions. */
3515
3516static bool
3517mutually_exclusive_p (decision *d1, decision *d2)
3518{
3519 /* If one path through D1 fails to test the same thing as D2, assume
3520 that D2's test could be true for D1 and look for a later, more useful,
3521 test. This isn't as expensive as it looks in practice. */
3522 while (!has_same_test_p (d1, d2))
3523 {
3524 d2 = d2->singleton ()->to->singleton ();
3525 if (!d2)
3526 return false;
3527 }
3528 if (d1->test == d2->test)
3529 {
3530 /* Look for any transitions from D1 that have the same labels as
3531 the transition from D2. */
3532 transition *trans2 = d2->singleton ();
3533 for (transition *trans1 = d1->first; trans1; trans1 = trans1->next)
3534 {
3535 int_set::iterator i1 = trans1->labels.begin ();
3536 int_set::iterator end1 = trans1->labels.end ();
3537 int_set::iterator i2 = trans2->labels.begin ();
3538 int_set::iterator end2 = trans2->labels.end ();
3539 while (i1 != end1 && i2 != end2)
3540 if (*i1 < *i2)
3541 ++i1;
3542 else if (*i2 < *i1)
3543 ++i2;
3544 else
3545 {
3546 /* TRANS1 has some labels in common with TRANS2. Assume
3547 that D1 and D2 could match the same rtx if the target
3548 of TRANS1 could match the same rtx as D2. */
3549 for (decision *subd1 = trans1->to->first;
3550 subd1; subd1 = subd1->next)
3551 if (!mutually_exclusive_p (subd1, d2))
3552 return false;
3553 break;
3554 }
3555 }
3556 return true;
3557 }
3558 for (transition *trans1 = d1->first; trans1; trans1 = trans1->next)
3559 for (decision *subd1 = trans1->to->first; subd1; subd1 = subd1->next)
3560 if (!mutually_exclusive_p (subd1, d2))
3561 return false;
3562 return true;
3563}
3564
3565/* Try to merge S2's decision into D1, given that they have the same test.
3566 Fail only if EXCLUDE is nonnull and the new transition would have the
3567 same labels as *EXCLUDE. When returning true, set *NEXT_S1, *NEXT_S2
3568 and *NEXT_EXCLUDE as for merge_into_state_1, or set *NEXT_S2 to null
3569 if the merge is complete. */
3570
3571static bool
3572merge_into_decision (decision *d1, state *s2, const int_set *exclude,
3573 state **next_s1, state **next_s2,
3574 const int_set **next_exclude)
3575{
3576 decision *d2 = s2->singleton ();
3577 transition *trans2 = d2->singleton ();
3578
3579 /* Get a list of the transitions that intersect TRANS2. */
3580 auto_vec <transition *, 32> intersecting;
3581 for (transition *trans1 = d1->first; trans1; trans1 = trans1->next)
3582 {
3583 int_set::iterator i1 = trans1->labels.begin ();
3584 int_set::iterator end1 = trans1->labels.end ();
3585 int_set::iterator i2 = trans2->labels.begin ();
3586 int_set::iterator end2 = trans2->labels.end ();
3587 bool trans1_is_subset = true;
3588 bool trans2_is_subset = true;
3589 bool intersect_p = false;
3590 while (i1 != end1 && i2 != end2)
3591 if (*i1 < *i2)
3592 {
3593 trans1_is_subset = false;
3594 ++i1;
3595 }
3596 else if (*i2 < *i1)
3597 {
3598 trans2_is_subset = false;
3599 ++i2;
3600 }
3601 else
3602 {
3603 intersect_p = true;
3604 ++i1;
3605 ++i2;
3606 }
3607 if (i1 != end1)
3608 trans1_is_subset = false;
3609 if (i2 != end2)
3610 trans2_is_subset = false;
3611 if (trans1_is_subset && trans2_is_subset)
3612 {
3613 /* There's already a transition that matches exactly.
3614 Merge the target states. */
3615 trans1->optional &= trans2->optional;
3616 *next_s1 = trans1->to;
3617 *next_s2 = trans2->to;
3618 *next_exclude = 0;
3619 return true;
3620 }
3621 if (trans2_is_subset)
3622 {
3623 /* TRANS1 has all the labels that TRANS2 needs. Merge S2 into
3624 the target of TRANS1, but (to avoid infinite recursion)
3625 make sure that we don't end up creating another transition
3626 like TRANS1. */
3627 *next_s1 = trans1->to;
3628 *next_s2 = s2;
3629 *next_exclude = &trans1->labels;
3630 return true;
3631 }
3632 if (intersect_p)
3633 intersecting.safe_push (trans1);
3634 }
3635
3636 if (intersecting.is_empty ())
3637 {
3638 /* No existing labels intersect the new ones. We can just add
3639 TRANS2 itself. */
3640 d1->push_back (d2->release ());
3641 *next_s1 = 0;
3642 *next_s2 = 0;
3643 *next_exclude = 0;
3644 return true;
3645 }
3646
3647 /* Take the union of the labels in INTERSECTING and TRANS2. Store the
3648 result in COMBINED and use NEXT as a temporary. */
3649 int_set tmp1 = trans2->labels, tmp2;
3650 int_set *combined = &tmp1, *next = &tmp2;
3651 for (unsigned int i = 0; i < intersecting.length (); ++i)
3652 {
3653 transition *trans1 = intersecting[i];
3654 next->truncate (0);
3655 next->safe_grow (trans1->labels.length () + combined->length ());
3656 int_set::iterator end
3657 = std::set_union (trans1->labels.begin (), trans1->labels.end (),
3658 combined->begin (), combined->end (),
3659 next->begin ());
3660 next->truncate (end - next->begin ());
3661 std::swap (next, combined);
3662 }
3663
3664 /* Stop now if we've been told not to create a transition with these
3665 labels. */
3666 if (exclude && *combined == *exclude)
3667 return false;
3668
3669 /* Get the transition that should carry the new labels. */
3670 transition *new_trans = intersecting[0];
3671 if (intersecting.length () == 1)
3672 {
3673 /* We're merging with one existing transition whose labels are a
3674 subset of those required. If both transitions are optional,
3675 we can just expand the set of labels so that it's suitable
3676 for both transitions. It isn't worth preserving the original
3677 transitions since we know that they can't be merged; we would
3678 need to backtrack to S2 if TRANS1->to fails. In contrast,
3679 we might be able to merge the targets of the transitions
3680 without any backtracking.
3681
3682 If instead the existing transition is not optional, ensure that
3683 all target decisions are suitably protected. Some decisions
3684 might already have a more specific requirement than NEW_TRANS,
3685 in which case there's no point testing NEW_TRANS as well. E.g. this
3686 would have happened if a test for an (eq ...) rtx had been
3687 added to a decision that tested whether the code is suitable
3688 for comparison_operator. The original comparison_operator
3689 transition would have been non-optional and the (eq ...) test
3690 would be performed by a second decision in the target of that
3691 transition.
3692
3693 The remaining case -- keeping the original optional transition
3694 when adding a non-optional TRANS2 -- is a wash. Preserving
3695 the optional transition only helps if we later merge another
3696 state S3 that is mutually exclusive with S2 and whose labels
3697 belong to *COMBINED - TRANS1->labels. We can then test the
3698 original NEW_TRANS and S3 in the same decision. We keep the
3699 optional transition around for that case, but it occurs very
3700 rarely. */
3701 gcc_assert (new_trans->labels != *combined);
3702 if (!new_trans->optional || !trans2->optional)
3703 {
3704 decision *start = 0;
3705 for (decision *end = new_trans->to->first; end; end = end->next)
3706 {
3707 if (!start && end->test != d1->test)
3708 /* END belongs to a range of decisions that need to be
3709 protected by NEW_TRANS. */
3710 start = end;
3711 if (start && (!end->next || end->next->test == d1->test))
3712 {
3713 /* Protect [START, END] with NEW_TRANS. The decisions
3714 move to NEW_S and NEW_D becomes part of NEW_TRANS->to. */
3715 state *new_s = new state;
3716 decision *new_d = new decision (d1->test);
3717 new_d->push_back (new transition (new_trans->labels, new_s,
3718 new_trans->optional));
3719 state::range r (start, end);
3720 new_trans->to->replace (r, new_d);
3721 new_s->push_back (r);
3722
3723 /* Continue with an empty range. */
3724 start = 0;
3725
3726 /* Continue from the decision after NEW_D. */
3727 end = new_d;
3728 }
3729 }
3730 }
3731 new_trans->optional = true;
3732 new_trans->labels = *combined;
3733 }
3734 else
3735 {
3736 /* We're merging more than one existing transition together.
3737 Those transitions are successfully dividing the matching space
3738 and so we want to preserve them, even if they're optional.
3739
3740 Create a new transition with the union set of labels and make
3741 it go to a state that has the original transitions. */
3742 decision *new_d = new decision (d1->test);
3743 for (unsigned int i = 0; i < intersecting.length (); ++i)
3744 new_d->push_back (d1->remove (intersecting[i]));
3745
3746 state *new_s = new state;
3747 new_s->push_back (new_d);
3748
3749 new_trans = new transition (*combined, new_s, true);
3750 d1->push_back (new_trans);
3751 }
3752
3753 /* We now have an optional transition with labels *COMBINED. Decide
3754 whether we can use it as TRANS2 or whether we need to merge S2
3755 into the target of NEW_TRANS. */
3756 gcc_assert (new_trans->optional);
3757 if (new_trans->labels == trans2->labels)
3758 {
3759 /* NEW_TRANS matches TRANS2. Just merge the target states. */
3760 new_trans->optional = trans2->optional;
3761 *next_s1 = new_trans->to;
3762 *next_s2 = trans2->to;
3763 *next_exclude = 0;
3764 }
3765 else
3766 {
3767 /* Try to merge TRANS2 into the target of the overlapping transition,
3768 but (to prevent infinite recursion or excessive redundancy) without
3769 creating another transition of the same type. */
3770 *next_s1 = new_trans->to;
3771 *next_s2 = s2;
3772 *next_exclude = &new_trans->labels;
3773 }
3774 return true;
3775}
3776
3777/* Make progress in merging S2 into S1, given that each state in S2
3778 has a single decision. If EXCLUDE is nonnull, avoid creating a new
3779 transition with the same test as S2's decision and with the labels
3780 in *EXCLUDE.
3781
3782 Return true if there is still work to do. When returning true,
3783 set *NEXT_S1, *NEXT_S2 and *NEXT_EXCLUDE to the values that
3784 S1, S2 and EXCLUDE should have next time round.
3785
3786 If S1 and S2 both match a particular rtx, give priority to S1. */
3787
3788static bool
3789merge_into_state_1 (state *s1, state *s2, const int_set *exclude,
3790 state **next_s1, state **next_s2,
3791 const int_set **next_exclude)
3792{
3793 decision *d2 = s2->singleton ();
3794 if (decision *d1 = s1->last)
3795 {
3796 if (d1->test.terminal_p ())
3797 /* D1 is an unconditional return, so S2 can never match. This can
3798 sometimes be a bug in the .md description, but might also happen
3799 if genconditions forces some conditions to true for certain
3800 configurations. */
3801 return false;
3802
3803 /* Go backwards through the decisions in S1, stopping once we find one
3804 that could match the same thing as S2. */
3805 while (d1->prev && mutually_exclusive_p (d1, d2))
3806 d1 = d1->prev;
3807
3808 /* Search forwards from that point, merging D2 into the first
3809 decision we can. */
3810 for (; d1; d1 = d1->next)
3811 {
3812 /* If S2 performs some optional tests before testing the same thing
3813 as D1, those tests do not help to distinguish D1 and S2, so it's
3814 better to drop them. Search through such optional decisions
3815 until we find something that tests the same thing as D1. */
3816 state *sub_s2 = s2;
3817 for (;;)
3818 {
3819 decision *sub_d2 = sub_s2->singleton ();
3820 if (d1->test == sub_d2->test)
3821 {
3822 /* Only apply EXCLUDE if we're testing the same thing
3823 as D2. */
3824 const int_set *sub_exclude = (d2 == sub_d2 ? exclude : 0);
3825
3826 /* Try to merge SUB_S2 into D1. This can only fail if
3827 it would involve creating a new transition with
3828 labels SUB_EXCLUDE. */
3829 if (merge_into_decision (d1, sub_s2, sub_exclude,
3830 next_s1, next_s2, next_exclude))
3831 return *next_s2 != 0;
3832
3833 /* Can't merge with D1; try a later decision. */
3834 break;
3835 }
3836 transition *sub_trans2 = sub_d2->singleton ();
3837 if (!sub_trans2->optional)
3838 /* Can't merge with D1; try a later decision. */
3839 break;
3840 sub_s2 = sub_trans2->to;
3841 }
3842 }
3843 }
3844
3845 /* We can't merge D2 with any existing decision. Just add it to the end. */
3846 s1->push_back (s2->release ());
3847 return false;
3848}
3849
3850/* Merge S2 into S1. If they both match a particular rtx, give
3851 priority to S1. Each state in S2 has a single decision. */
3852
3853static void
3854merge_into_state (state *s1, state *s2)
3855{
3856 const int_set *exclude = 0;
3857 while (s2 && merge_into_state_1 (s1, s2, exclude, &s1, &s2, &exclude))
3858 continue;
3859}
3860
3861/* Pairs a pattern that needs to be matched with the rtx position at
3862 which the pattern should occur. */
3863struct pattern_pos {
3864 pattern_pos () {}
3865 pattern_pos (rtx, position *);
3866
3867 rtx pattern;
3868 position *pos;
3869};
3870
3871pattern_pos::pattern_pos (rtx pattern_in, position *pos_in)
3872 : pattern (pattern_in), pos (pos_in)
3873{}
3874
3875/* Compare entries according to their depth-first order. There shouldn't
3876 be two entries at the same position. */
3877
3878bool
3879operator < (const pattern_pos &e1, const pattern_pos &e2)
3880{
3881 int diff = compare_positions (e1.pos, e2.pos);
3882 gcc_assert (diff != 0 || e1.pattern == e2.pattern);
3883 return diff < 0;
3884}
3885
59250a8d 3886/* Add new decisions to S that check whether the rtx at position POS
3887 matches PATTERN. Return the state that is reached in that case.
3888 TOP_PATTERN is the overall pattern, as passed to match_pattern_1. */
3889
3890static state *
c04601c1 3891match_pattern_2 (state *s, md_rtx_info *info, position *pos, rtx pattern)
59250a8d 3892{
3893 auto_vec <pattern_pos, 32> worklist;
3894 auto_vec <pattern_pos, 32> pred_and_mode_tests;
3895 auto_vec <pattern_pos, 32> dup_tests;
3896
3897 worklist.safe_push (pattern_pos (pattern, pos));
3898 while (!worklist.is_empty ())
3899 {
3900 pattern_pos next = worklist.pop ();
3901 pattern = next.pattern;
3902 pos = next.pos;
3903 unsigned int reverse_s = worklist.length ();
3904
3905 enum rtx_code code = GET_CODE (pattern);
3906 switch (code)
3907 {
3908 case MATCH_OP_DUP:
3909 case MATCH_DUP:
3910 case MATCH_PAR_DUP:
3911 /* Add a test that the rtx matches the earlier one, but only
3912 after the structure and predicates have been checked. */
3913 dup_tests.safe_push (pattern_pos (pattern, pos));
3914
3915 /* Use the same code check as the original operand. */
c04601c1 3916 pattern = find_operand (info->def, XINT (pattern, 0), NULL_RTX);
59250a8d 3917 /* Fall through. */
3918
3919 case MATCH_PARALLEL:
3920 case MATCH_OPERAND:
3921 case MATCH_SCRATCH:
3922 case MATCH_OPERATOR:
3923 {
3924 const char *pred_name = predicate_name (pattern);
3925 const struct pred_data *pred = 0;
3926 if (pred_name[0] != 0)
3927 {
3928 pred = lookup_predicate (pred_name);
3929 /* Only report errors once per rtx. */
3930 if (code == GET_CODE (pattern))
3931 {
3932 if (!pred)
c04601c1 3933 error_at (info->loc, "unknown predicate '%s' used in %s",
3934 pred_name, GET_RTX_NAME (code));
59250a8d 3935 else if (code == MATCH_PARALLEL
3936 && pred->singleton != PARALLEL)
c04601c1 3937 error_at (info->loc, "predicate '%s' used in"
3938 " match_parallel does not allow only PARALLEL",
3939 pred->name);
59250a8d 3940 }
3941 }
3942
3943 if (code == MATCH_PARALLEL || code == MATCH_PAR_DUP)
3944 {
3945 /* Check that we have a parallel with enough elements. */
abef0e58 3946 s = add_decision (s, rtx_test::code (pos), PARALLEL, false);
59250a8d 3947 int min_len = XVECLEN (pattern, 2);
abef0e58 3948 s = add_decision (s, rtx_test::veclen_ge (pos, min_len),
59250a8d 3949 true, false);
3950 }
3951 else
3952 {
3953 /* Check that the rtx has one of codes accepted by the
3954 predicate. This is necessary when matching suboperands
3955 of a MATCH_OPERATOR or MATCH_OP_DUP, since we can't
3956 call XEXP (X, N) without checking that X has at least
3957 N+1 operands. */
3958 int_set codes;
3959 get_predicate_codes (pred, &codes);
3960 bool need_codes = (pred
3961 && (code == MATCH_OPERATOR
3962 || code == MATCH_OP_DUP));
abef0e58 3963 s = add_decision (s, rtx_test::code (pos), codes, !need_codes);
59250a8d 3964 }
3965
3966 /* Postpone the predicate check until we've checked the rest
3967 of the rtx structure. */
3968 if (code == GET_CODE (pattern))
3969 pred_and_mode_tests.safe_push (pattern_pos (pattern, pos));
3970
3971 /* If we need to match suboperands, add them to the worklist. */
3972 if (code == MATCH_OPERATOR || code == MATCH_PARALLEL)
3973 {
3974 position **subpos_ptr;
3975 enum position_type pos_type;
3976 int i;
3977 if (code == MATCH_OPERATOR || code == MATCH_OP_DUP)
3978 {
3979 pos_type = POS_XEXP;
3980 subpos_ptr = &pos->xexps;
3981 i = (code == MATCH_OPERATOR ? 2 : 1);
3982 }
3983 else
3984 {
3985 pos_type = POS_XVECEXP0;
3986 subpos_ptr = &pos->xvecexp0s;
3987 i = 2;
3988 }
3989 for (int j = 0; j < XVECLEN (pattern, i); ++j)
3990 {
3991 position *subpos = next_position (subpos_ptr, pos,
3992 pos_type, j);
3993 worklist.safe_push (pattern_pos (XVECEXP (pattern, i, j),
3994 subpos));
3995 subpos_ptr = &subpos->next;
3996 }
3997 }
3998 break;
3999 }
4000
4001 default:
4002 {
4003 /* Check that the rtx has the right code. */
abef0e58 4004 s = add_decision (s, rtx_test::code (pos), code, false);
59250a8d 4005
4006 /* Queue a test for the mode if one is specified. */
4007 if (GET_MODE (pattern) != VOIDmode)
4008 pred_and_mode_tests.safe_push (pattern_pos (pattern, pos));
4009
4010 /* Push subrtxes onto the worklist. Match nonrtx operands now. */
4011 const char *fmt = GET_RTX_FORMAT (code);
4012 position **subpos_ptr = &pos->xexps;
4013 for (size_t i = 0; fmt[i]; ++i)
4014 {
4015 position *subpos = next_position (subpos_ptr, pos,
4016 POS_XEXP, i);
4017 switch (fmt[i])
4018 {
4019 case 'e': case 'u':
4020 worklist.safe_push (pattern_pos (XEXP (pattern, i),
4021 subpos));
4022 break;
4023
4024 case 'E':
4025 {
4026 /* Make sure the vector has the right number of
4027 elements. */
4028 int length = XVECLEN (pattern, i);
abef0e58 4029 s = add_decision (s, rtx_test::veclen (pos),
4030 length, false);
59250a8d 4031
4032 position **subpos2_ptr = &pos->xvecexp0s;
4033 for (int j = 0; j < length; j++)
4034 {
4035 position *subpos2 = next_position (subpos2_ptr, pos,
4036 POS_XVECEXP0, j);
4037 rtx x = XVECEXP (pattern, i, j);
4038 worklist.safe_push (pattern_pos (x, subpos2));
4039 subpos2_ptr = &subpos2->next;
4040 }
4041 break;
4042 }
4043
4044 case 'i':
4045 /* Make sure that XINT (X, I) has the right value. */
abef0e58 4046 s = add_decision (s, rtx_test::int_field (pos, i),
59250a8d 4047 XINT (pattern, i), false);
4048 break;
4049
15183fd2 4050 case 'r':
4051 /* Make sure that REGNO (X) has the right value. */
4052 gcc_assert (i == 0);
4053 s = add_decision (s, rtx_test::regno_field (pos),
4054 REGNO (pattern), false);
4055 break;
4056
59250a8d 4057 case 'w':
4058 /* Make sure that XWINT (X, I) has the right value. */
abef0e58 4059 s = add_decision (s, rtx_test::wide_int_field (pos, i),
59250a8d 4060 XWINT (pattern, 0), false);
4061 break;
4062
9edf7ea8 4063 case 'p':
4064 /* We don't have a way of parsing polynomial offsets yet,
4065 and hopefully never will. */
4066 s = add_decision (s, rtx_test::subreg_field (pos),
4067 SUBREG_BYTE (pattern).to_constant (),
4068 false);
4069 break;
4070
59250a8d 4071 case '0':
4072 break;
4073
4074 default:
4075 gcc_unreachable ();
4076 }
4077 subpos_ptr = &subpos->next;
4078 }
4079 }
4080 break;
4081 }
4082 /* Operands are pushed onto the worklist so that later indices are
4083 nearer the top. That's what we want for SETs, since a SET_SRC
4084 is a better discriminator than a SET_DEST. In other cases it's
4085 usually better to match earlier indices first. This is especially
4086 true of PARALLELs, where the first element tends to be the most
4087 individual. It's also true for commutative operators, where the
4088 canonicalization rules say that the more complex operand should
4089 come first. */
4090 if (code != SET && worklist.length () > reverse_s)
4091 std::reverse (&worklist[0] + reverse_s,
4092 &worklist[0] + worklist.length ());
4093 }
4094
4095 /* Sort the predicate and mode tests so that they're in depth-first order.
4096 The main goal of this is to put SET_SRC match_operands after SET_DEST
4097 match_operands and after mode checks for the enclosing SET_SRC operators
4098 (such as the mode of a PLUS in an addition instruction). The latter
4099 two types of test can determine the mode exactly, whereas a SET_SRC
4100 match_operand often has to cope with the possibility of the operand
4101 being a modeless constant integer. E.g. something that matches
4102 register_operand (x, SImode) never matches register_operand (x, DImode),
4103 but a const_int that matches immediate_operand (x, SImode) also matches
4104 immediate_operand (x, DImode). The register_operand cases can therefore
4105 be distinguished by a switch on the mode, but the immediate_operand
4106 cases can't. */
4107 if (pred_and_mode_tests.length () > 1)
4108 std::sort (&pred_and_mode_tests[0],
4109 &pred_and_mode_tests[0] + pred_and_mode_tests.length ());
4110
4111 /* Add the mode and predicate tests. */
4112 pattern_pos *e;
4113 unsigned int i;
4114 FOR_EACH_VEC_ELT (pred_and_mode_tests, i, e)
4115 {
4116 switch (GET_CODE (e->pattern))
4117 {
4118 case MATCH_PARALLEL:
4119 case MATCH_OPERAND:
4120 case MATCH_SCRATCH:
4121 case MATCH_OPERATOR:
4122 {
4123 int opno = XINT (e->pattern, 0);
4124 num_operands = MAX (num_operands, opno + 1);
4125 const char *pred_name = predicate_name (e->pattern);
4126 if (pred_name[0])
4127 {
4128 const struct pred_data *pred = lookup_predicate (pred_name);
4129 /* Check the mode first, to distinguish things like SImode
4130 and DImode register_operands, as described above. */
4131 machine_mode mode = GET_MODE (e->pattern);
85099d88 4132 if (pred && safe_predicate_mode (pred, mode))
abef0e58 4133 s = add_decision (s, rtx_test::mode (e->pos), mode, true);
59250a8d 4134
4135 /* Assign to operands[] first, so that the rtx usually doesn't
4136 need to be live across the call to the predicate.
4137
4138 This shouldn't cause a problem with dirtying the page,
4139 since we fully expect to assign to operands[] at some point,
4140 and since the caller usually writes to other parts of
4141 recog_data anyway. */
abef0e58 4142 s = add_decision (s, rtx_test::set_op (e->pos, opno),
4143 true, false);
4144 s = add_decision (s, rtx_test::predicate (e->pos, pred, mode),
59250a8d 4145 true, false);
4146 }
4147 else
4148 /* Historically we've ignored the mode when there's no
4149 predicate. Just set up operands[] unconditionally. */
abef0e58 4150 s = add_decision (s, rtx_test::set_op (e->pos, opno),
4151 true, false);
59250a8d 4152 break;
4153 }
4154
4155 default:
abef0e58 4156 s = add_decision (s, rtx_test::mode (e->pos),
59250a8d 4157 GET_MODE (e->pattern), false);
4158 break;
4159 }
4160 }
4161
4162 /* Finally add rtx_equal_p checks for duplicated operands. */
4163 FOR_EACH_VEC_ELT (dup_tests, i, e)
abef0e58 4164 s = add_decision (s, rtx_test::duplicate (e->pos, XINT (e->pattern, 0)),
59250a8d 4165 true, false);
4166 return s;
4167}
4168
4169/* Add new decisions to S that make it return ACCEPTANCE if:
4170
4171 (1) the rtx doesn't match anything already matched by S
4172 (2) the rtx matches TOP_PATTERN and
7c1b1064 4173 (3) the C test required by INFO->def is true
59250a8d 4174
a545c6cd 4175 For peephole2, TOP_PATTERN is a SEQUENCE of the instruction patterns
4176 to match, otherwise it is a single instruction pattern. */
59250a8d 4177
4178static void
7c1b1064 4179match_pattern_1 (state *s, md_rtx_info *info, rtx pattern,
59250a8d 4180 acceptance_type acceptance)
4181{
a545c6cd 4182 if (acceptance.type == PEEPHOLE2)
59250a8d 4183 {
4184 /* Match each individual instruction. */
4185 position **subpos_ptr = &peep2_insn_pos_list;
4186 int count = 0;
c04601c1 4187 for (int i = 0; i < XVECLEN (pattern, 0); ++i)
59250a8d 4188 {
c04601c1 4189 rtx x = XVECEXP (pattern, 0, i);
a545c6cd 4190 position *subpos = next_position (subpos_ptr, &root_pos,
4191 POS_PEEP2_INSN, count);
4192 if (count > 0)
4193 s = add_decision (s, rtx_test::peep2_count (count + 1),
4194 true, false);
c04601c1 4195 s = match_pattern_2 (s, info, subpos, x);
a545c6cd 4196 subpos_ptr = &subpos->next;
4197 count += 1;
59250a8d 4198 }
4199 acceptance.u.full.u.match_len = count - 1;
4200 }
4201 else
4202 {
4203 /* Make the rtx itself. */
c04601c1 4204 s = match_pattern_2 (s, info, &root_pos, pattern);
59250a8d 4205
4206 /* If the match is only valid when extra clobbers are added,
4207 make sure we're able to pass that information to the caller. */
4208 if (acceptance.type == RECOG && acceptance.u.full.u.num_clobbers)
abef0e58 4209 s = add_decision (s, rtx_test::have_num_clobbers (), true, false);
59250a8d 4210 }
4211
4212 /* Make sure that the C test is true. */
7c1b1064 4213 const char *c_test = get_c_test (info->def);
59250a8d 4214 if (maybe_eval_c_test (c_test) != 1)
abef0e58 4215 s = add_decision (s, rtx_test::c_test (c_test), true, false);
59250a8d 4216
4217 /* Accept the pattern. */
abef0e58 4218 add_decision (s, rtx_test::accept (acceptance), true, false);
59250a8d 4219}
4220
4221/* Like match_pattern_1, but (if merge_states_p) try to merge the
4222 decisions with what's already in S, to reduce the amount of
4223 backtracking. */
4224
4225static void
7c1b1064 4226match_pattern (state *s, md_rtx_info *info, rtx pattern,
59250a8d 4227 acceptance_type acceptance)
4228{
4229 if (merge_states_p)
4230 {
4231 state root;
4232 /* Add the decisions to a fresh state and then merge the full tree
4233 into the existing one. */
7c1b1064 4234 match_pattern_1 (&root, info, pattern, acceptance);
59250a8d 4235 merge_into_state (s, &root);
4236 }
4237 else
7c1b1064 4238 match_pattern_1 (s, info, pattern, acceptance);
59250a8d 4239}
4240
4241/* Begin the output file. */
4242
4243static void
4244write_header (void)
4245{
4246 puts ("\
4247/* Generated automatically by the program `genrecog' from the target\n\
4248 machine description file. */\n\
4249\n\
785790dc 4250#define IN_TARGET_CODE 1\n\
4251\n\
59250a8d 4252#include \"config.h\"\n\
4253#include \"system.h\"\n\
4254#include \"coretypes.h\"\n\
9ef16211 4255#include \"backend.h\"\n\
d040a5b0 4256#include \"predict.h\"\n\
59250a8d 4257#include \"rtl.h\"\n\
ad7b10a2 4258#include \"memmodel.h\"\n\
59250a8d 4259#include \"tm_p.h\"\n\
73bde8df 4260#include \"emit-rtl.h\"\n\
59250a8d 4261#include \"insn-config.h\"\n\
4262#include \"recog.h\"\n\
4263#include \"output.h\"\n\
4264#include \"flags.h\"\n\
9ef16211 4265#include \"df.h\"\n\
59250a8d 4266#include \"resource.h\"\n\
4267#include \"diagnostic-core.h\"\n\
4268#include \"reload.h\"\n\
4269#include \"regs.h\"\n\
4270#include \"tm-constrs.h\"\n\
59250a8d 4271\n");
4272
4273 puts ("\n\
4274/* `recog' contains a decision tree that recognizes whether the rtx\n\
4275 X0 is a valid instruction.\n\
4276\n\
4277 recog returns -1 if the rtx is not valid. If the rtx is valid, recog\n\
4278 returns a nonnegative number which is the insn code number for the\n\
4279 pattern that matched. This is the same as the order in the machine\n\
4280 description of the entry that matched. This number can be used as an\n\
4281 index into `insn_data' and other tables.\n");
4282 puts ("\
4283 The third parameter to recog is an optional pointer to an int. If\n\
4284 present, recog will accept a pattern if it matches except for missing\n\
4285 CLOBBER expressions at the end. In that case, the value pointed to by\n\
4286 the optional pointer will be set to the number of CLOBBERs that need\n\
4287 to be added (it should be initialized to zero by the caller). If it");
4288 puts ("\
4289 is set nonzero, the caller should allocate a PARALLEL of the\n\
4290 appropriate size, copy the initial entries, and call add_clobbers\n\
4291 (found in insn-emit.c) to fill in the CLOBBERs.\n\
4292");
4293
4294 puts ("\n\
4295 The function split_insns returns 0 if the rtl could not\n\
4296 be split or the split rtl as an INSN list if it can be.\n\
4297\n\
4298 The function peephole2_insns returns 0 if the rtl could not\n\
4299 be matched. If there was a match, the new rtl is returned in an INSN list,\n\
4300 and LAST_INSN will point to the last recognized insn in the old sequence.\n\
4301*/\n\n");
4302}
4303
4304/* Return the C type of a parameter with type TYPE. */
4305
4306static const char *
4307parameter_type_string (parameter::type_enum type)
4308{
4309 switch (type)
4310 {
4311 case parameter::UNSET:
4312 break;
4313
4314 case parameter::CODE:
4315 return "rtx_code";
4316
4317 case parameter::MODE:
4318 return "machine_mode";
4319
4320 case parameter::INT:
4321 return "int";
4322
15183fd2 4323 case parameter::UINT:
4324 return "unsigned int";
4325
59250a8d 4326 case parameter::WIDE_INT:
4327 return "HOST_WIDE_INT";
4328 }
4329 gcc_unreachable ();
4330}
4331
4332/* Return true if ACCEPTANCE requires only a single C statement even in
4333 a backtracking context. */
4334
4335static bool
4336single_statement_p (const acceptance_type &acceptance)
4337{
4338 if (acceptance.partial_p)
4339 /* We need to handle failures of the subroutine. */
4340 return false;
4341 switch (acceptance.type)
4342 {
4343 case SUBPATTERN:
4344 case SPLIT:
4345 return true;
4346
4347 case RECOG:
4348 /* False if we need to assign to pnum_clobbers. */
4349 return acceptance.u.full.u.num_clobbers == 0;
4350
4351 case PEEPHOLE2:
4352 /* We need to assign to pmatch_len_ and handle null returns from the
4353 peephole2 routine. */
4354 return false;
4355 }
4356 gcc_unreachable ();
4357}
4358
4359/* Return the C failure value for a routine of type TYPE. */
4360
4361static const char *
4362get_failure_return (routine_type type)
4363{
4364 switch (type)
4365 {
4366 case SUBPATTERN:
4367 case RECOG:
4368 return "-1";
4369
4370 case SPLIT:
4371 case PEEPHOLE2:
58a87a29 4372 return "NULL";
59250a8d 4373 }
4374 gcc_unreachable ();
4375}
4376
4377/* Indicates whether a block of code always returns or whether it can fall
4378 through. */
4379
4380enum exit_state {
4381 ES_RETURNED,
4382 ES_FALLTHROUGH
4383};
4384
4385/* Information used while writing out code. */
4386
4387struct output_state
4388{
4389 /* The type of routine that we're generating. */
4390 routine_type type;
4391
4392 /* Maps position ids to xN variable numbers. The entry is only valid if
4393 it is less than the length of VAR_TO_ID, but this holds for every position
4394 tested by a state when writing out that state. */
4395 auto_vec <unsigned int> id_to_var;
4396
4397 /* Maps xN variable numbers to position ids. */
4398 auto_vec <unsigned int> var_to_id;
4399
4400 /* Index N is true if variable xN has already been set. */
4401 auto_vec <bool> seen_vars;
4402};
4403
4404/* Return true if D is a call to a pattern routine and if there is some X
4405 such that the transition for pattern result N goes to a successful return
4406 with code X+N. When returning true, set *BASE_OUT to this X and *COUNT_OUT
4407 to the number of return values. (We know that every PATTERN decision has
4408 a transition for every successful return.) */
4409
4410static bool
4411terminal_pattern_p (decision *d, unsigned int *base_out,
4412 unsigned int *count_out)
4413{
abef0e58 4414 if (d->test.kind != rtx_test::PATTERN)
59250a8d 4415 return false;
4416 unsigned int base = 0;
4417 unsigned int count = 0;
4418 for (transition *trans = d->first; trans; trans = trans->next)
4419 {
4420 if (trans->is_param || trans->labels.length () != 1)
4421 return false;
4422 decision *subd = trans->to->singleton ();
abef0e58 4423 if (!subd || subd->test.kind != rtx_test::ACCEPT)
59250a8d 4424 return false;
4425 unsigned int this_base = (subd->test.u.acceptance.u.full.code
4426 - trans->labels[0]);
4427 if (trans == d->first)
4428 base = this_base;
4429 else if (base != this_base)
4430 return false;
4431 count += 1;
4432 }
4433 *base_out = base;
4434 *count_out = count;
4435 return true;
4436}
4437
4438/* Return true if TEST doesn't test an rtx or if the rtx it tests is
4439 already available in state OS. */
4440
4441static bool
abef0e58 4442test_position_available_p (output_state *os, const rtx_test &test)
59250a8d 4443{
4444 return (!test.pos
4445 || test.pos_operand >= 0
4446 || os->seen_vars[os->id_to_var[test.pos->id]]);
4447}
4448
4449/* Like printf, but print INDENT spaces at the beginning. */
4450
4451static void ATTRIBUTE_PRINTF_2
4452printf_indent (unsigned int indent, const char *format, ...)
4453{
4454 va_list ap;
4455 va_start (ap, format);
4456 printf ("%*s", indent, "");
4457 vprintf (format, ap);
4458 va_end (ap);
4459}
4460
4461/* Emit code to initialize the variable associated with POS, if it isn't
4462 already valid in state OS. Indent each line by INDENT spaces. Update
4463 OS with the new state. */
4464
4465static void
4466change_state (output_state *os, position *pos, unsigned int indent)
4467{
4468 unsigned int var = os->id_to_var[pos->id];
4469 gcc_assert (var < os->var_to_id.length () && os->var_to_id[var] == pos->id);
4470 if (os->seen_vars[var])
4471 return;
4472 switch (pos->type)
4473 {
4474 case POS_PEEP2_INSN:
4475 printf_indent (indent, "x%d = PATTERN (peep2_next_insn (%d));\n",
4476 var, pos->arg);
4477 break;
4478
4479 case POS_XEXP:
4480 change_state (os, pos->base, indent);
4481 printf_indent (indent, "x%d = XEXP (x%d, %d);\n",
4482 var, os->id_to_var[pos->base->id], pos->arg);
4483 break;
4484
4485 case POS_XVECEXP0:
4486 change_state (os, pos->base, indent);
4487 printf_indent (indent, "x%d = XVECEXP (x%d, 0, %d);\n",
4488 var, os->id_to_var[pos->base->id], pos->arg);
4489 break;
4490 }
4491 os->seen_vars[var] = true;
4492}
4493
4494/* Print the enumerator constant for CODE -- the upcase version of
4495 the name. */
4496
4497static void
4498print_code (enum rtx_code code)
4499{
4500 const char *p;
4501 for (p = GET_RTX_NAME (code); *p; p++)
4502 putchar (TOUPPER (*p));
4503}
4504
4505/* Emit a uint64_t as an integer constant expression. We need to take
4506 special care to avoid "decimal constant is so large that it is unsigned"
4507 warnings in the resulting code. */
4508
4509static void
4510print_host_wide_int (uint64_t val)
4511{
4512 uint64_t min = uint64_t (1) << (HOST_BITS_PER_WIDE_INT - 1);
4513 if (val == min)
4514 printf ("(" HOST_WIDE_INT_PRINT_DEC_C " - 1)", val + 1);
4515 else
4516 printf (HOST_WIDE_INT_PRINT_DEC_C, val);
4517}
4518
4519/* Print the C expression for actual parameter PARAM. */
4520
4521static void
4522print_parameter_value (const parameter &param)
4523{
4524 if (param.is_param)
4525 printf ("i%d", (int) param.value + 1);
4526 else
4527 switch (param.type)
4528 {
4529 case parameter::UNSET:
4530 gcc_unreachable ();
4531 break;
4532
4533 case parameter::CODE:
4534 print_code ((enum rtx_code) param.value);
4535 break;
4536
4537 case parameter::MODE:
1e0295b9 4538 printf ("E_%smode", GET_MODE_NAME ((machine_mode) param.value));
59250a8d 4539 break;
4540
4541 case parameter::INT:
4542 printf ("%d", (int) param.value);
4543 break;
4544
15183fd2 4545 case parameter::UINT:
4546 printf ("%u", (unsigned int) param.value);
4547 break;
4548
59250a8d 4549 case parameter::WIDE_INT:
4550 print_host_wide_int (param.value);
4551 break;
4552 }
4553}
4554
4555/* Print the C expression for the rtx tested by TEST. */
4556
4557static void
abef0e58 4558print_test_rtx (output_state *os, const rtx_test &test)
59250a8d 4559{
4560 if (test.pos_operand >= 0)
4561 printf ("operands[%d]", test.pos_operand);
4562 else
4563 printf ("x%d", os->id_to_var[test.pos->id]);
4564}
4565
4566/* Print the C expression for non-boolean test TEST. */
4567
4568static void
abef0e58 4569print_nonbool_test (output_state *os, const rtx_test &test)
59250a8d 4570{
4571 switch (test.kind)
4572 {
abef0e58 4573 case rtx_test::CODE:
59250a8d 4574 printf ("GET_CODE (");
4575 print_test_rtx (os, test);
4576 printf (")");
4577 break;
4578
abef0e58 4579 case rtx_test::MODE:
59250a8d 4580 printf ("GET_MODE (");
4581 print_test_rtx (os, test);
4582 printf (")");
4583 break;
4584
abef0e58 4585 case rtx_test::VECLEN:
59250a8d 4586 printf ("XVECLEN (");
4587 print_test_rtx (os, test);
4588 printf (", 0)");
4589 break;
4590
abef0e58 4591 case rtx_test::INT_FIELD:
59250a8d 4592 printf ("XINT (");
4593 print_test_rtx (os, test);
4594 printf (", %d)", test.u.opno);
4595 break;
4596
15183fd2 4597 case rtx_test::REGNO_FIELD:
4598 printf ("REGNO (");
4599 print_test_rtx (os, test);
4600 printf (")");
4601 break;
4602
9edf7ea8 4603 case rtx_test::SUBREG_FIELD:
4604 printf ("SUBREG_BYTE (");
4605 print_test_rtx (os, test);
4606 printf (")");
4607 break;
4608
abef0e58 4609 case rtx_test::WIDE_INT_FIELD:
59250a8d 4610 printf ("XWINT (");
4611 print_test_rtx (os, test);
4612 printf (", %d)", test.u.opno);
4613 break;
4614
abef0e58 4615 case rtx_test::PATTERN:
59250a8d 4616 {
4617 pattern_routine *routine = test.u.pattern->routine;
4618 printf ("pattern%d (", routine->pattern_id);
4619 const char *sep = "";
4620 if (test.pos)
4621 {
4622 print_test_rtx (os, test);
4623 sep = ", ";
4624 }
4625 if (routine->insn_p)
4626 {
4627 printf ("%sinsn", sep);
4628 sep = ", ";
4629 }
4630 if (routine->pnum_clobbers_p)
4631 {
4632 printf ("%spnum_clobbers", sep);
4633 sep = ", ";
4634 }
4635 for (unsigned int i = 0; i < test.u.pattern->params.length (); ++i)
4636 {
4637 fputs (sep, stdout);
4638 print_parameter_value (test.u.pattern->params[i]);
4639 sep = ", ";
4640 }
4641 printf (")");
4642 break;
4643 }
4644
abef0e58 4645 case rtx_test::PEEP2_COUNT:
4646 case rtx_test::VECLEN_GE:
4647 case rtx_test::SAVED_CONST_INT:
4648 case rtx_test::DUPLICATE:
4649 case rtx_test::PREDICATE:
4650 case rtx_test::SET_OP:
4651 case rtx_test::HAVE_NUM_CLOBBERS:
4652 case rtx_test::C_TEST:
4653 case rtx_test::ACCEPT:
59250a8d 4654 gcc_unreachable ();
4655 }
4656}
4657
4658/* IS_PARAM and LABEL are taken from a transition whose source
4659 decision performs TEST. Print the C code for the label. */
4660
4661static void
abef0e58 4662print_label_value (const rtx_test &test, bool is_param, uint64_t value)
59250a8d 4663{
4664 print_parameter_value (parameter (transition_parameter_type (test.kind),
4665 is_param, value));
4666}
4667
4668/* If IS_PARAM, print code to compare TEST with the C variable i<VALUE+1>.
4669 If !IS_PARAM, print code to compare TEST with the C constant VALUE.
4670 Test for inequality if INVERT_P, otherwise test for equality. */
4671
4672static void
abef0e58 4673print_test (output_state *os, const rtx_test &test, bool is_param,
4674 uint64_t value, bool invert_p)
59250a8d 4675{
4676 switch (test.kind)
4677 {
4678 /* Handle the non-boolean TESTs. */
abef0e58 4679 case rtx_test::CODE:
4680 case rtx_test::MODE:
4681 case rtx_test::VECLEN:
15183fd2 4682 case rtx_test::REGNO_FIELD:
abef0e58 4683 case rtx_test::INT_FIELD:
4684 case rtx_test::WIDE_INT_FIELD:
4685 case rtx_test::PATTERN:
59250a8d 4686 print_nonbool_test (os, test);
4687 printf (" %s ", invert_p ? "!=" : "==");
4688 print_label_value (test, is_param, value);
4689 break;
4690
9edf7ea8 4691 case rtx_test::SUBREG_FIELD:
4692 printf ("%s (", invert_p ? "maybe_ne" : "known_eq");
4693 print_nonbool_test (os, test);
4694 printf (", ");
4695 print_label_value (test, is_param, value);
4696 printf (")");
4697 break;
4698
abef0e58 4699 case rtx_test::SAVED_CONST_INT:
59250a8d 4700 gcc_assert (!is_param && value == 1);
4701 print_test_rtx (os, test);
4702 printf (" %s const_int_rtx[MAX_SAVED_CONST_INT + ",
4703 invert_p ? "!=" : "==");
4704 print_parameter_value (parameter (parameter::INT,
4705 test.u.integer.is_param,
4706 test.u.integer.value));
4707 printf ("]");
4708 break;
4709
abef0e58 4710 case rtx_test::PEEP2_COUNT:
59250a8d 4711 gcc_assert (!is_param && value == 1);
4712 printf ("peep2_current_count %s %d", invert_p ? "<" : ">=",
4713 test.u.min_len);
4714 break;
4715
abef0e58 4716 case rtx_test::VECLEN_GE:
59250a8d 4717 gcc_assert (!is_param && value == 1);
4718 printf ("XVECLEN (");
4719 print_test_rtx (os, test);
4720 printf (", 0) %s %d", invert_p ? "<" : ">=", test.u.min_len);
4721 break;
4722
abef0e58 4723 case rtx_test::PREDICATE:
59250a8d 4724 gcc_assert (!is_param && value == 1);
4725 printf ("%s%s (", invert_p ? "!" : "", test.u.predicate.data->name);
4726 print_test_rtx (os, test);
4727 printf (", ");
4728 print_parameter_value (parameter (parameter::MODE,
4729 test.u.predicate.mode_is_param,
4730 test.u.predicate.mode));
4731 printf (")");
4732 break;
4733
abef0e58 4734 case rtx_test::DUPLICATE:
59250a8d 4735 gcc_assert (!is_param && value == 1);
4736 printf ("%srtx_equal_p (", invert_p ? "!" : "");
4737 print_test_rtx (os, test);
4738 printf (", operands[%d])", test.u.opno);
4739 break;
4740
abef0e58 4741 case rtx_test::HAVE_NUM_CLOBBERS:
59250a8d 4742 gcc_assert (!is_param && value == 1);
4743 printf ("pnum_clobbers %s NULL", invert_p ? "==" : "!=");
4744 break;
4745
abef0e58 4746 case rtx_test::C_TEST:
59250a8d 4747 gcc_assert (!is_param && value == 1);
4748 if (invert_p)
4749 printf ("!");
e1e9159b 4750 rtx_reader_ptr->print_c_condition (test.u.string);
59250a8d 4751 break;
4752
abef0e58 4753 case rtx_test::ACCEPT:
4754 case rtx_test::SET_OP:
59250a8d 4755 gcc_unreachable ();
4756 }
4757}
4758
4759static exit_state print_decision (output_state *, decision *,
4760 unsigned int, bool);
4761
4762/* Print code to perform S, indent each line by INDENT spaces.
4763 IS_FINAL is true if there are no fallback decisions to test on failure;
4764 if the state fails then the entire routine fails. */
4765
4766static exit_state
4767print_state (output_state *os, state *s, unsigned int indent, bool is_final)
4768{
4769 exit_state es = ES_FALLTHROUGH;
4770 for (decision *d = s->first; d; d = d->next)
4771 es = print_decision (os, d, indent, is_final && !d->next);
4772 if (es != ES_RETURNED && is_final)
4773 {
4774 printf_indent (indent, "return %s;\n", get_failure_return (os->type));
4775 es = ES_RETURNED;
4776 }
4777 return es;
4778}
4779
4780/* Print the code for subroutine call ACCEPTANCE (for which partial_p
4781 is known to be true). Return the C condition that indicates a successful
4782 match. */
4783
4784static const char *
4785print_subroutine_call (const acceptance_type &acceptance)
4786{
4787 switch (acceptance.type)
4788 {
4789 case SUBPATTERN:
4790 gcc_unreachable ();
4791
4792 case RECOG:
4793 printf ("recog_%d (x1, insn, pnum_clobbers)",
4794 acceptance.u.subroutine_id);
4795 return ">= 0";
4796
4797 case SPLIT:
4798 printf ("split_%d (x1, insn)", acceptance.u.subroutine_id);
4799 return "!= NULL_RTX";
4800
4801 case PEEPHOLE2:
4802 printf ("peephole2_%d (x1, insn, pmatch_len_)",
4803 acceptance.u.subroutine_id);
4804 return "!= NULL_RTX";
4805 }
4806 gcc_unreachable ();
4807}
4808
4809/* Print code for the successful match described by ACCEPTANCE.
4810 INDENT and IS_FINAL are as for print_state. */
4811
4812static exit_state
4813print_acceptance (const acceptance_type &acceptance, unsigned int indent,
4814 bool is_final)
4815{
4816 if (acceptance.partial_p)
4817 {
4818 /* Defer the rest of the match to a subroutine. */
4819 if (is_final)
4820 {
4821 printf_indent (indent, "return ");
4822 print_subroutine_call (acceptance);
4823 printf (";\n");
4824 return ES_RETURNED;
4825 }
4826 else
4827 {
4828 printf_indent (indent, "res = ");
4829 const char *res_test = print_subroutine_call (acceptance);
4830 printf (";\n");
4831 printf_indent (indent, "if (res %s)\n", res_test);
4832 printf_indent (indent + 2, "return res;\n");
4833 return ES_FALLTHROUGH;
4834 }
4835 }
4836 switch (acceptance.type)
4837 {
4838 case SUBPATTERN:
4839 printf_indent (indent, "return %d;\n", acceptance.u.full.code);
4840 return ES_RETURNED;
4841
4842 case RECOG:
4843 if (acceptance.u.full.u.num_clobbers != 0)
4844 printf_indent (indent, "*pnum_clobbers = %d;\n",
4845 acceptance.u.full.u.num_clobbers);
4846 printf_indent (indent, "return %d; /* %s */\n", acceptance.u.full.code,
4847 get_insn_name (acceptance.u.full.code));
4848 return ES_RETURNED;
4849
4850 case SPLIT:
4851 printf_indent (indent, "return gen_split_%d (insn, operands);\n",
4852 acceptance.u.full.code);
4853 return ES_RETURNED;
4854
4855 case PEEPHOLE2:
4856 printf_indent (indent, "*pmatch_len_ = %d;\n",
4857 acceptance.u.full.u.match_len);
4858 if (is_final)
4859 {
4860 printf_indent (indent, "return gen_peephole2_%d (insn, operands);\n",
4861 acceptance.u.full.code);
4862 return ES_RETURNED;
4863 }
4864 else
4865 {
4866 printf_indent (indent, "res = gen_peephole2_%d (insn, operands);\n",
4867 acceptance.u.full.code);
4868 printf_indent (indent, "if (res != NULL_RTX)\n");
4869 printf_indent (indent + 2, "return res;\n");
4870 return ES_FALLTHROUGH;
4871 }
4872 }
4873 gcc_unreachable ();
4874}
4875
4876/* Print code to perform D. INDENT and IS_FINAL are as for print_state. */
4877
4878static exit_state
4879print_decision (output_state *os, decision *d, unsigned int indent,
4880 bool is_final)
4881{
4882 uint64_t label;
4883 unsigned int base, count;
4884
4885 /* Make sure the rtx under test is available either in operands[] or
4886 in an xN variable. */
4887 if (d->test.pos && d->test.pos_operand < 0)
4888 change_state (os, d->test.pos, indent);
4889
4890 /* Look for cases where a pattern routine P1 calls another pattern routine
4891 P2 and where P1 returns X + BASE whenever P2 returns X. If IS_FINAL
4892 is true and BASE is zero we can simply use:
4893
4894 return patternN (...);
4895
4896 Otherwise we can use:
4897
4898 res = patternN (...);
4899 if (res >= 0)
4900 return res + BASE;
4901
4902 However, if BASE is nonzero and patternN only returns 0 or -1,
4903 the usual "return BASE;" is better than "return res + BASE;".
4904 If BASE is zero, "return res;" should be better than "return 0;",
4905 since no assignment to the return register is required. */
4906 if (os->type == SUBPATTERN
4907 && terminal_pattern_p (d, &base, &count)
4908 && (base == 0 || count > 1))
4909 {
4910 if (is_final && base == 0)
4911 {
4912 printf_indent (indent, "return ");
4913 print_nonbool_test (os, d->test);
4914 printf ("; /* [-1, %d] */\n", count - 1);
4915 return ES_RETURNED;
4916 }
4917 else
4918 {
4919 printf_indent (indent, "res = ");
4920 print_nonbool_test (os, d->test);
4921 printf (";\n");
4922 printf_indent (indent, "if (res >= 0)\n");
4923 printf_indent (indent + 2, "return res");
4924 if (base != 0)
4925 printf (" + %d", base);
4926 printf ("; /* [%d, %d] */\n", base, base + count - 1);
4927 return ES_FALLTHROUGH;
4928 }
4929 }
abef0e58 4930 else if (d->test.kind == rtx_test::ACCEPT)
59250a8d 4931 return print_acceptance (d->test.u.acceptance, indent, is_final);
abef0e58 4932 else if (d->test.kind == rtx_test::SET_OP)
59250a8d 4933 {
4934 printf_indent (indent, "operands[%d] = ", d->test.u.opno);
4935 print_test_rtx (os, d->test);
4936 printf (";\n");
4937 return print_state (os, d->singleton ()->to, indent, is_final);
4938 }
4939 /* Handle decisions with a single transition and a single transition
4940 label. */
4941 else if (d->if_statement_p (&label))
4942 {
4943 transition *trans = d->singleton ();
4944 if (mark_optional_transitions_p && trans->optional)
4945 printf_indent (indent, "/* OPTIONAL IF */\n");
4946
4947 /* Print the condition associated with TRANS. Invert it if IS_FINAL,
4948 so that we return immediately on failure and fall through on
4949 success. */
4950 printf_indent (indent, "if (");
4951 print_test (os, d->test, trans->is_param, label, is_final);
4952
4953 /* Look for following states that would be handled by this code
4954 on recursion. If they don't need any preparatory statements,
4955 include them in the current "if" statement rather than creating
4956 a new one. */
4957 for (;;)
4958 {
4959 d = trans->to->singleton ();
4960 if (!d
abef0e58 4961 || d->test.kind == rtx_test::ACCEPT
4962 || d->test.kind == rtx_test::SET_OP
59250a8d 4963 || !d->if_statement_p (&label)
4964 || !test_position_available_p (os, d->test))
4965 break;
4966 trans = d->first;
4967 printf ("\n");
4968 if (mark_optional_transitions_p && trans->optional)
4969 printf_indent (indent + 4, "/* OPTIONAL IF */\n");
4970 printf_indent (indent + 4, "%s ", is_final ? "||" : "&&");
4971 print_test (os, d->test, trans->is_param, label, is_final);
4972 }
4973 printf (")\n");
4974
4975 /* Print the conditional code with INDENT + 2 and the fallthrough
4976 code with indent INDENT. */
4977 state *to = trans->to;
4978 if (is_final)
4979 {
4980 /* We inverted the condition above, so return failure in the
4981 "if" body and fall through to the target of the transition. */
4982 printf_indent (indent + 2, "return %s;\n",
4983 get_failure_return (os->type));
4984 return print_state (os, to, indent, is_final);
4985 }
4986 else if (to->singleton ()
abef0e58 4987 && to->first->test.kind == rtx_test::ACCEPT
59250a8d 4988 && single_statement_p (to->first->test.u.acceptance))
4989 {
4990 /* The target of the transition is a simple "return" statement.
4991 It doesn't need any braces and doesn't fall through. */
4992 if (print_acceptance (to->first->test.u.acceptance,
4993 indent + 2, true) != ES_RETURNED)
4994 gcc_unreachable ();
4995 return ES_FALLTHROUGH;
4996 }
4997 else
4998 {
4999 /* The general case. Output code for the target of the transition
5000 in braces. This will not invalidate any of the xN variables
5001 that are already valid, but we mustn't rely on any that are
5002 set by the "if" body. */
5003 auto_vec <bool, 32> old_seen;
5004 old_seen.safe_splice (os->seen_vars);
5005
5006 printf_indent (indent + 2, "{\n");
5007 print_state (os, trans->to, indent + 4, is_final);
5008 printf_indent (indent + 2, "}\n");
5009
5010 os->seen_vars.truncate (0);
5011 os->seen_vars.splice (old_seen);
5012 return ES_FALLTHROUGH;
5013 }
5014 }
5015 else
5016 {
5017 /* Output the decision as a switch statement. */
5018 printf_indent (indent, "switch (");
5019 print_nonbool_test (os, d->test);
5020 printf (")\n");
5021
5022 /* Each case statement starts with the same set of valid variables.
5023 These are also the only variables will be valid on fallthrough. */
5024 auto_vec <bool, 32> old_seen;
5025 old_seen.safe_splice (os->seen_vars);
5026
5027 printf_indent (indent + 2, "{\n");
5028 for (transition *trans = d->first; trans; trans = trans->next)
5029 {
5030 gcc_assert (!trans->is_param);
5031 if (mark_optional_transitions_p && trans->optional)
5032 printf_indent (indent + 2, "/* OPTIONAL CASE */\n");
5033 for (int_set::iterator j = trans->labels.begin ();
5034 j != trans->labels.end (); ++j)
5035 {
5036 printf_indent (indent + 2, "case ");
5037 print_label_value (d->test, trans->is_param, *j);
5038 printf (":\n");
5039 }
5040 if (print_state (os, trans->to, indent + 4, is_final))
5041 {
5042 /* The state can fall through. Add an explicit break. */
5043 gcc_assert (!is_final);
5044 printf_indent (indent + 4, "break;\n");
5045 }
5046 printf ("\n");
6d69ff19 5047
59250a8d 5048 /* Restore the original set of valid variables. */
5049 os->seen_vars.truncate (0);
5050 os->seen_vars.splice (old_seen);
6d69ff19 5051 }
59250a8d 5052 /* Add a default case. */
5053 printf_indent (indent + 2, "default:\n");
5054 if (is_final)
5055 printf_indent (indent + 4, "return %s;\n",
5056 get_failure_return (os->type));
5057 else
5058 printf_indent (indent + 4, "break;\n");
5059 printf_indent (indent + 2, "}\n");
5060 return is_final ? ES_RETURNED : ES_FALLTHROUGH;
6d69ff19 5061 }
59250a8d 5062}
6d69ff19 5063
59250a8d 5064/* Make sure that OS has a position variable for POS. ROOT_P is true if
5065 POS is the root position for the routine. */
6d69ff19 5066
59250a8d 5067static void
5068assign_position_var (output_state *os, position *pos, bool root_p)
5069{
5070 unsigned int idx = os->id_to_var[pos->id];
5071 if (idx < os->var_to_id.length () && os->var_to_id[idx] == pos->id)
5072 return;
5073 if (!root_p && pos->type != POS_PEEP2_INSN)
5074 assign_position_var (os, pos->base, false);
5075 os->id_to_var[pos->id] = os->var_to_id.length ();
5076 os->var_to_id.safe_push (pos->id);
263287f7 5077}
5078
59250a8d 5079/* Make sure that OS has the position variables required by S. */
6d69ff19 5080
263287f7 5081static void
59250a8d 5082assign_position_vars (output_state *os, state *s)
263287f7 5083{
59250a8d 5084 for (decision *d = s->first; d; d = d->next)
6d69ff19 5085 {
59250a8d 5086 /* Positions associated with operands can be read from the
5087 operands[] array. */
5088 if (d->test.pos && d->test.pos_operand < 0)
5089 assign_position_var (os, d->test.pos, false);
5090 for (transition *trans = d->first; trans; trans = trans->next)
5091 assign_position_vars (os, trans->to);
6d69ff19 5092 }
6d69ff19 5093}
a698628e 5094
59250a8d 5095/* Print the open brace and variable definitions for a routine that
5096 implements S. ROOT is the deepest rtx from which S can access all
5097 relevant parts of the first instruction it matches. Initialize OS
5098 so that every relevant position has an rtx variable xN and so that
5099 only ROOT's variable has a valid value. */
a698628e 5100
5101static void
59250a8d 5102print_subroutine_start (output_state *os, state *s, position *root)
a698628e 5103{
59250a8d 5104 printf ("{\n rtx * const operands ATTRIBUTE_UNUSED"
5105 " = &recog_data.operand[0];\n");
5106 os->var_to_id.truncate (0);
5107 os->seen_vars.truncate (0);
5108 if (root)
a698628e 5109 {
59250a8d 5110 /* Create a fake entry for position 0 so that an id_to_var of 0
5111 is always invalid. This also makes the xN variables naturally
5112 1-based rather than 0-based. */
5113 os->var_to_id.safe_push (num_positions);
6d69ff19 5114
59250a8d 5115 /* Associate ROOT with x1. */
5116 assign_position_var (os, root, true);
a698628e 5117
59250a8d 5118 /* Assign xN variables to all other relevant positions. */
5119 assign_position_vars (os, s);
6d69ff19 5120
59250a8d 5121 /* Output the variable declarations (except for ROOT's, which is
5122 passed in as a parameter). */
5123 unsigned int num_vars = os->var_to_id.length ();
5124 if (num_vars > 2)
a698628e 5125 {
59250a8d 5126 for (unsigned int i = 2; i < num_vars; ++i)
5127 /* Print 8 rtx variables to a line. */
5128 printf ("%s x%d",
5129 i == 2 ? " rtx" : (i - 2) % 8 == 0 ? ";\n rtx" : ",", i);
5130 printf (";\n");
6d69ff19 5131 }
a698628e 5132
59250a8d 5133 /* Say that x1 is valid and the rest aren't. */
5134 os->seen_vars.safe_grow_cleared (num_vars);
5135 os->seen_vars[1] = true;
6d69ff19 5136 }
59250a8d 5137 if (os->type == SUBPATTERN || os->type == RECOG)
5138 printf (" int res ATTRIBUTE_UNUSED;\n");
5139 else
58a87a29 5140 printf (" rtx_insn *res ATTRIBUTE_UNUSED;\n");
a698628e 5141}
5142
59250a8d 5143/* Output the definition of pattern routine ROUTINE. */
82575fa7 5144
6d69ff19 5145static void
59250a8d 5146print_pattern (output_state *os, pattern_routine *routine)
6d69ff19 5147{
59250a8d 5148 printf ("\nstatic int\npattern%d (", routine->pattern_id);
5149 const char *sep = "";
5150 /* Add the top-level rtx parameter, if any. */
5151 if (routine->pos)
5152 {
5153 printf ("%srtx x1", sep);
5154 sep = ", ";
5155 }
5156 /* Add the optional parameters. */
5157 if (routine->insn_p)
5158 {
5159 /* We can't easily tell whether a C condition actually reads INSN,
5160 so add an ATTRIBUTE_UNUSED just in case. */
5161 printf ("%srtx_insn *insn ATTRIBUTE_UNUSED", sep);
5162 sep = ", ";
5163 }
5164 if (routine->pnum_clobbers_p)
5165 {
5166 printf ("%sint *pnum_clobbers", sep);
5167 sep = ", ";
5168 }
5169 /* Add the "i" parameters. */
5170 for (unsigned int i = 0; i < routine->param_types.length (); ++i)
5171 {
5172 printf ("%s%s i%d", sep,
5173 parameter_type_string (routine->param_types[i]), i + 1);
5174 sep = ", ";
5175 }
5176 printf (")\n");
5177 os->type = SUBPATTERN;
5178 print_subroutine_start (os, routine->s, routine->pos);
5179 print_state (os, routine->s, 2, true);
5180 printf ("}\n");
5181}
a698628e 5182
59250a8d 5183/* Output a routine of type TYPE that implements S. PROC_ID is the
5184 number of the subroutine associated with S, or 0 if S is the main
5185 routine. */
6d69ff19 5186
59250a8d 5187static void
5188print_subroutine (output_state *os, state *s, int proc_id)
5189{
59250a8d 5190 printf ("\n");
5191 switch (os->type)
e4ba8ded 5192 {
59250a8d 5193 case SUBPATTERN:
5194 gcc_unreachable ();
5195
e4ba8ded 5196 case RECOG:
59250a8d 5197 if (proc_id)
5198 printf ("static int\nrecog_%d", proc_id);
5199 else
5200 printf ("int\nrecog");
5201 printf (" (rtx x1 ATTRIBUTE_UNUSED,\n"
30302b7c 5202 "\trtx_insn *insn ATTRIBUTE_UNUSED,\n"
5203 "\tint *pnum_clobbers ATTRIBUTE_UNUSED)\n");
e4ba8ded 5204 break;
59250a8d 5205
e4ba8ded 5206 case SPLIT:
59250a8d 5207 if (proc_id)
58a87a29 5208 printf ("static rtx_insn *\nsplit_%d", proc_id);
59250a8d 5209 else
58a87a29 5210 printf ("rtx_insn *\nsplit_insns");
5211 printf (" (rtx x1 ATTRIBUTE_UNUSED, rtx_insn *insn ATTRIBUTE_UNUSED)\n");
e4ba8ded 5212 break;
59250a8d 5213
e4ba8ded 5214 case PEEPHOLE2:
59250a8d 5215 if (proc_id)
58a87a29 5216 printf ("static rtx_insn *\npeephole2_%d", proc_id);
59250a8d 5217 else
58a87a29 5218 printf ("rtx_insn *\npeephole2_insns");
59250a8d 5219 printf (" (rtx x1 ATTRIBUTE_UNUSED,\n"
58a87a29 5220 "\trtx_insn *insn ATTRIBUTE_UNUSED,\n"
5221 "\tint *pmatch_len_ ATTRIBUTE_UNUSED)\n");
e4ba8ded 5222 break;
5223 }
59250a8d 5224 print_subroutine_start (os, s, &root_pos);
5225 if (proc_id == 0)
bf59a32d 5226 {
60ff05a9 5227 printf (" recog_data.insn = NULL;\n");
bf59a32d 5228 }
59250a8d 5229 print_state (os, s, 2, true);
5230 printf ("}\n");
6d69ff19 5231}
5232
59250a8d 5233/* Print out a routine of type TYPE that performs ROOT. */
a698628e 5234
263287f7 5235static void
59250a8d 5236print_subroutine_group (output_state *os, routine_type type, state *root)
263287f7 5237{
59250a8d 5238 os->type = type;
5239 if (use_subroutines_p)
5240 {
5241 /* Split ROOT up into smaller pieces, both for readability and to
5242 help the compiler. */
5243 auto_vec <state *> subroutines;
5244 find_subroutines (type, root, subroutines);
5245
5246 /* Output the subroutines (but not ROOT itself). */
5247 unsigned int i;
5248 state *s;
5249 FOR_EACH_VEC_ELT (subroutines, i, s)
5250 print_subroutine (os, s, i + 1);
5251 }
5252 /* Output the main routine. */
5253 print_subroutine (os, root, 0);
6d69ff19 5254}
82575fa7 5255
a545c6cd 5256/* Return the rtx pattern for the list of rtxes in a define_peephole2. */
5257
5258static rtx
c04601c1 5259get_peephole2_pattern (md_rtx_info *info)
a545c6cd 5260{
5261 int i, j;
c04601c1 5262 rtvec vec = XVEC (info->def, 0);
a545c6cd 5263 rtx pattern = rtx_alloc (SEQUENCE);
5264 XVEC (pattern, 0) = rtvec_alloc (GET_NUM_ELEM (vec));
5265 for (i = j = 0; i < GET_NUM_ELEM (vec); i++)
5266 {
5267 rtx x = RTVEC_ELT (vec, i);
5268 /* Ignore scratch register requirements. */
5269 if (GET_CODE (x) != MATCH_SCRATCH && GET_CODE (x) != MATCH_DUP)
5270 {
5271 XVECEXP (pattern, 0, j) = x;
5272 j++;
5273 }
5274 }
5275 XVECLEN (pattern, 0) = j;
5276 if (j == 0)
c04601c1 5277 error_at (info->loc, "empty define_peephole2");
a545c6cd 5278 return pattern;
5279}
5280
59250a8d 5281/* Return true if *PATTERN_PTR is a PARALLEL in which at least one trailing
5282 rtx can be added automatically by add_clobbers. If so, update
5283 *ACCEPTANCE_PTR so that its num_clobbers field contains the number
5284 of such trailing rtxes and update *PATTERN_PTR so that it contains
5285 the pattern without those rtxes. */
6d69ff19 5286
59250a8d 5287static bool
5288remove_clobbers (acceptance_type *acceptance_ptr, rtx *pattern_ptr)
5289{
5290 int i;
5291 rtx new_pattern;
6d69ff19 5292
59250a8d 5293 /* Find the last non-clobber in the parallel. */
5294 rtx pattern = *pattern_ptr;
5295 for (i = XVECLEN (pattern, 0); i > 0; i--)
6d69ff19 5296 {
59250a8d 5297 rtx x = XVECEXP (pattern, 0, i - 1);
ccd6679f 5298 if ((GET_CODE (x) != CLOBBER && GET_CODE (x) != CLOBBER_HIGH)
59250a8d 5299 || (!REG_P (XEXP (x, 0))
5300 && GET_CODE (XEXP (x, 0)) != MATCH_SCRATCH))
5301 break;
263287f7 5302 }
a698628e 5303
59250a8d 5304 if (i == XVECLEN (pattern, 0))
5305 return false;
263287f7 5306
59250a8d 5307 /* Build a similar insn without the clobbers. */
5308 if (i == 1)
5309 new_pattern = XVECEXP (pattern, 0, 0);
f4adfe76 5310 else
a5deb6f6 5311 {
59250a8d 5312 new_pattern = rtx_alloc (PARALLEL);
5313 XVEC (new_pattern, 0) = rtvec_alloc (i);
5314 for (int j = 0; j < i; ++j)
5315 XVECEXP (new_pattern, 0, j) = XVECEXP (pattern, 0, j);
a5deb6f6 5316 }
f4adfe76 5317
59250a8d 5318 /* Recognize it. */
5319 acceptance_ptr->u.full.u.num_clobbers = XVECLEN (pattern, 0) - i;
5320 *pattern_ptr = new_pattern;
5321 return true;
6d69ff19 5322}
867b95d0 5323
263287f7 5324int
16570c04 5325main (int argc, const char **argv)
263287f7 5326{
59250a8d 5327 state insn_root, split_root, peephole2_root;
263287f7 5328
04b58880 5329 progname = "genrecog";
6d69ff19 5330
77ba95d0 5331 if (!init_rtx_reader_args (argc, argv))
c5ddd6b5 5332 return (FATAL_EXIT_CODE);
263287f7 5333
6d69ff19 5334 write_header ();
263287f7 5335
5336 /* Read the machine description. */
5337
c04601c1 5338 md_rtx_info info;
5339 while (read_md_rtx (&info))
263287f7 5340 {
c04601c1 5341 rtx def = info.def;
263287f7 5342
59250a8d 5343 acceptance_type acceptance;
5344 acceptance.partial_p = false;
c04601c1 5345 acceptance.u.full.code = info.index;
59250a8d 5346
a545c6cd 5347 rtx pattern;
c04601c1 5348 switch (GET_CODE (def))
6d69ff19 5349 {
cbf464bd 5350 case DEFINE_INSN:
59250a8d 5351 {
5352 /* Match the instruction in the original .md form. */
59250a8d 5353 acceptance.type = RECOG;
5354 acceptance.u.full.u.num_clobbers = 0;
c04601c1 5355 pattern = add_implicit_parallel (XVEC (def, 1));
5356 validate_pattern (pattern, &info, NULL_RTX, 0);
7c1b1064 5357 match_pattern (&insn_root, &info, pattern, acceptance);
59250a8d 5358
5359 /* If the pattern is a PARALLEL with trailing CLOBBERs,
5360 allow recog_for_combine to match without the clobbers. */
5361 if (GET_CODE (pattern) == PARALLEL
5362 && remove_clobbers (&acceptance, &pattern))
7c1b1064 5363 match_pattern (&insn_root, &info, pattern, acceptance);
59250a8d 5364 break;
5365 }
cbf464bd 5366
5367 case DEFINE_SPLIT:
59250a8d 5368 acceptance.type = SPLIT;
c04601c1 5369 pattern = add_implicit_parallel (XVEC (def, 0));
5370 validate_pattern (pattern, &info, NULL_RTX, 0);
7c1b1064 5371 match_pattern (&split_root, &info, pattern, acceptance);
59250a8d 5372
5373 /* Declare the gen_split routine that we'll call if the
5374 pattern matches. The definition comes from insn-emit.c. */
58a87a29 5375 printf ("extern rtx_insn *gen_split_%d (rtx_insn *, rtx *);\n",
c04601c1 5376 info.index);
cbf464bd 5377 break;
5378
5379 case DEFINE_PEEPHOLE2:
59250a8d 5380 acceptance.type = PEEPHOLE2;
c04601c1 5381 pattern = get_peephole2_pattern (&info);
5382 validate_pattern (pattern, &info, NULL_RTX, 0);
7c1b1064 5383 match_pattern (&peephole2_root, &info, pattern, acceptance);
59250a8d 5384
5385 /* Declare the gen_peephole2 routine that we'll call if the
5386 pattern matches. The definition comes from insn-emit.c. */
58a87a29 5387 printf ("extern rtx_insn *gen_peephole2_%d (rtx_insn *, rtx *);\n",
c04601c1 5388 info.index);
59250a8d 5389 break;
fcb53c1e 5390
cbf464bd 5391 default:
5392 /* do nothing */;
5393 }
263287f7 5394 }
5395
b638f5c8 5396 if (have_error)
0922b1b8 5397 return FATAL_EXIT_CODE;
5398
6d69ff19 5399 puts ("\n\n");
263287f7 5400
59250a8d 5401 /* Optimize each routine in turn. */
5402 optimize_subroutine_group ("recog", &insn_root);
5403 optimize_subroutine_group ("split_insns", &split_root);
5404 optimize_subroutine_group ("peephole2_insns", &peephole2_root);
6d69ff19 5405
59250a8d 5406 output_state os;
5407 os.id_to_var.safe_grow_cleared (num_positions);
6d69ff19 5408
59250a8d 5409 if (use_pattern_routines_p)
6d69ff19 5410 {
59250a8d 5411 /* Look for common patterns and split them out into subroutines. */
5412 auto_vec <merge_state_info> states;
5413 states.safe_push (&insn_root);
5414 states.safe_push (&split_root);
5415 states.safe_push (&peephole2_root);
5416 split_out_patterns (states);
5417
5418 /* Print out the routines that we just created. */
5419 unsigned int i;
5420 pattern_routine *routine;
5421 FOR_EACH_VEC_ELT (patterns, i, routine)
5422 print_pattern (&os, routine);
6d69ff19 5423 }
5424
59250a8d 5425 /* Print out the matching routines. */
5426 print_subroutine_group (&os, RECOG, &insn_root);
5427 print_subroutine_group (&os, SPLIT, &split_root);
5428 print_subroutine_group (&os, PEEPHOLE2, &peephole2_root);
940b9cea 5429
59250a8d 5430 fflush (stdout);
5431 return (ferror (stdout) != 0 ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE);
940b9cea 5432}