Debian Codegraph @

gcc/ext-dce.cc

raw
1 /* RTL dead zero/sign extension (code) elimination.
2 Copyright (C) 2000-2025 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "backend.h"
24 #include "rtl.h"
25 #include "tree.h"
26 #include "memmodel.h"
27 #include "insn-config.h"
28 #include "emit-rtl.h"
29 #include "recog.h"
30 #include "cfganal.h"
31 #include "tree-pass.h"
32 #include "cfgrtl.h"
33 #include "rtl-iter.h"
34 #include "df.h"
35 #include "print-rtl.h"
36 #include "dbgcnt.h"
37 #include "diagnostic-core.h"
38 #include "target.h"
39
40 /* These should probably move into a C++ class. */
41 static vec<bitmap_head> livein;
42 static bitmap all_blocks;
43 static bitmap livenow;
44 static bitmap changed_pseudos;
45 static bool modify;
46
47 /* We consider four bit groups for liveness:
48 bit 0..7 (least significant byte)
49 bit 8..15 (second least significant byte)
50 bit 16..31
51 bit 32..BITS_PER_WORD-1 */
52
53 /* For the given REG, return the number of bit groups implied by the
54 size of the REG's mode, up to a maximum of 4 (number of bit groups
55 tracked by this pass).
56
57 For partial integer and variable sized modes also return 4. This
58 could possibly be refined for something like PSI mode, but it
59 does not seem worth the effort. */
60
61 static int
62 group_limit (const_rtx reg)
63 {
64 machine_mode mode = GET_MODE (reg);
65
66 if (!GET_MODE_BITSIZE (mode).is_constant ())
67 return 4;
68
69 int size = GET_MODE_SIZE (mode).to_constant ();
70
71 size = exact_log2 (size);
72
73 if (size < 0)
74 return 4;
75
76 size++;
77 return (size > 4 ? 4 : size);
78 }
79
80 /* Make all bit groups live for REGNO in bitmap BMAP. For hard regs,
81 we assume all groups are live. For a pseudo we consider the size
82 of the pseudo to avoid creating unnecessarily live chunks of data. */
83
84 static void
85 make_reg_live (bitmap bmap, int regno)
86 {
87 int limit;
88
89 /* For pseudos we can use the mode to limit how many bit groups
90 are marked as live since a pseudo only has one mode. Hard
91 registers have to be handled more conservatively. */
92 if (regno > FIRST_PSEUDO_REGISTER)
93 {
94 rtx reg = regno_reg_rtx[regno];
95 limit = group_limit (reg);
96 }
97 else
98 limit = 4;
99
100 for (int i = 0; i < limit; i++)
101 bitmap_set_bit (bmap, regno * 4 + i);
102 }
103
104 /* Note this pass could be used to narrow memory loads too. It's
105 not clear if that's profitable or not in general. */
106
107 #define UNSPEC_P(X) (GET_CODE (X) == UNSPEC || GET_CODE (X) == UNSPEC_VOLATILE)
108
109 /* If we know the destination of CODE only uses some low bits
110 (say just the QI bits of an SI operation), then return true
111 if we can propagate the need for just the subset of bits
112 from the destination to the sources.
113
114 FIXME: This is safe for operands 1 and 2 of an IF_THEN_ELSE, but not
115 operand 0. Thus is likely would need some special casing to handle. */
116
117 static bool
118 safe_for_live_propagation (rtx_code code)
119 {
120 /* First handle rtx classes which as a whole are known to
121 be either safe or unsafe. */
122 switch (GET_RTX_CLASS (code))
123 {
124 case RTX_OBJ:
125 case RTX_CONST_OBJ:
126 return true;
127
128 case RTX_COMPARE:
129 case RTX_COMM_COMPARE:
130 case RTX_TERNARY:
131 return false;
132
133 default:
134 break;
135 }
136
137 /* What's left are specific codes. We only need to identify those
138 which are safe. */
139 switch (code)
140 {
141 /* These are trivially safe. */
142 case SUBREG:
143 case NOT:
144 case ZERO_EXTEND:
145 case SIGN_EXTEND:
146 case TRUNCATE:
147 case PLUS:
148 case MINUS:
149 case MULT:
150 case SMUL_HIGHPART:
151 case UMUL_HIGHPART:
152 case AND:
153 case IOR:
154 case XOR:
155 return true;
156
157 /* We can propagate for the shifted operand, but not the shift
158 count. The count is handled specially. */
159 case ASHIFT:
160 case LSHIFTRT:
161 case ASHIFTRT:
162 case SS_ASHIFT:
163 case US_ASHIFT:
164 return true;
165
166 /* There may be other safe codes. If so they can be added
167 individually when discovered. */
168 default:
169 return false;
170 }
171 }
172
173 /* Clear bits in LIVENOW and set bits in LIVE_TMP for objects
174 set/clobbered by OBJ contained in INSN.
175
176 Conceptually it is always safe to ignore a particular destination
177 here as that will result in more chunks of data being considered
178 live. That's what happens when we "continue" the main loop when
179 we see something we don't know how to handle such as a vector
180 mode destination.
181
182 The more accurate we are in identifying what objects (and chunks
183 within an object) are set by INSN, the more aggressive the
184 optimization phase during use handling will be. */
185
186 static bool
187 ext_dce_process_sets (rtx_insn *insn, rtx obj, bitmap live_tmp)
188 {
189 bool skipped_dest = false;
190
191 subrtx_iterator::array_type array;
192 FOR_EACH_SUBRTX (iter, array, obj, NONCONST)
193 {
194 const_rtx x = *iter;
195
196 /* An EXPR_LIST (from call fusage) ends in NULL_RTX. */
197 if (x == NULL_RTX)
198 continue;
199
200 if (UNSPEC_P (x))
201 continue;
202
203 if (GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
204 {
205 unsigned bit = 0;
206 x = SET_DEST (x);
207
208 /* We don't support vector destinations or destinations
209 wider than DImode. */
210 scalar_mode outer_mode;
211 if (!is_a <scalar_mode> (GET_MODE (x), &outer_mode)
212 || GET_MODE_BITSIZE (outer_mode) > HOST_BITS_PER_WIDE_INT)
213 {
214 /* Skip the subrtxs of this destination. There is
215 little value in iterating into the subobjects, so
216 just skip them for a bit of efficiency. */
217 skipped_dest = true;
218 iter.skip_subrtxes ();
219 continue;
220 }
221
222 /* We could have (strict_low_part (subreg ...)). We can not just
223 strip the STRICT_LOW_PART as that would result in clearing
224 some bits in LIVENOW that are still live. So process the
225 STRICT_LOW_PART specially. */
226 if (GET_CODE (x) == STRICT_LOW_PART)
227 {
228 x = XEXP (x, 0);
229
230 /* The only valid operand of a STRICT_LOW_PART is a non
231 paradoxical SUBREG. */
232 gcc_assert (SUBREG_P (x)
233 && !paradoxical_subreg_p (x)
234 && SUBREG_BYTE (x).is_constant ());
235
236 /* I think we should always see a REG here. But let's
237 be sure. */
238 gcc_assert (REG_P (SUBREG_REG (x)));
239
240 /* The inner mode might be larger, just punt for
241 that case. Remember, we can not just continue to process
242 the inner RTXs due to the STRICT_LOW_PART. */
243 if (!is_a <scalar_mode> (GET_MODE (SUBREG_REG (x)), &outer_mode)
244 || GET_MODE_BITSIZE (outer_mode) > HOST_BITS_PER_WIDE_INT)
245 {
246 /* Skip the subrtxs of the STRICT_LOW_PART. We can't
247 process them because it'll set objects as no longer
248 live when they are in fact still live. */
249 skipped_dest = true;
250 iter.skip_subrtxes ();
251 continue;
252 }
253
254 /* LIVE_TMP contains the set groups that are live-out and set in
255 this insn. It is used to narrow the groups live-in for the
256 inputs of this insn.
257
258 The simple thing to do is mark all the groups as live, but
259 that will significantly inhibit optimization.
260
261 We also need to be careful in the case where we have an in-out
262 operand. If we're not careful we'd clear LIVE_TMP
263 incorrectly. */
264 HOST_WIDE_INT rn = REGNO (SUBREG_REG (x));
265 int limit = group_limit (SUBREG_REG (x));
266 for (HOST_WIDE_INT i = 4 * rn; i < 4 * rn + limit; i++)
267 if (bitmap_bit_p (livenow, i))
268 bitmap_set_bit (live_tmp, i);
269
270 if (bitmap_empty_p (live_tmp))
271 make_reg_live (live_tmp, rn);
272
273 /* The mode of the SUBREG tells us how many bits we can
274 clear. */
275 machine_mode mode = GET_MODE (x);
276 HOST_WIDE_INT size
277 = exact_log2 (GET_MODE_SIZE (mode).to_constant ()) + 1;
278 bitmap_clear_range (livenow, 4 * rn, size);
279
280 /* We have fully processed this destination. */
281 iter.skip_subrtxes ();
282 continue;
283 }
284
285 /* Phase one of destination handling. First remove any wrapper
286 such as SUBREG or ZERO_EXTRACT. */
287 unsigned HOST_WIDE_INT mask
288 = GET_MODE_MASK (GET_MODE_INNER (GET_MODE (x)));
289 if (SUBREG_P (x))
290 {
291 /* If we have a SUBREG destination that is too wide, just
292 skip the destination rather than continuing this iterator.
293 While continuing would be better, we'd need to strip the
294 subreg and restart within the SET processing rather than
295 the top of the loop which just complicates the flow even
296 more. */
297 if (!is_a <scalar_mode> (GET_MODE (SUBREG_REG (x)), &outer_mode)
298 || GET_MODE_BITSIZE (outer_mode) > HOST_BITS_PER_WIDE_INT)
299 {
300 skipped_dest = true;
301 iter.skip_subrtxes ();
302 continue;
303 }
304
305 /* We can safely strip a paradoxical subreg. The inner mode will
306 be narrower than the outer mode. We'll clear fewer bits in
307 LIVENOW than we'd like, but that's always safe. */
308 if (paradoxical_subreg_p (x))
309 x = XEXP (x, 0);
310 else if (SUBREG_BYTE (x).is_constant ())
311 {
312 bit = subreg_lsb (x).to_constant ();
313 mask = GET_MODE_MASK (GET_MODE (SUBREG_REG (x))) << bit;
314 gcc_assert (mask);
315 x = SUBREG_REG (x);
316 }
317 else
318 gcc_unreachable ();
319 }
320
321 if (GET_CODE (x) == ZERO_EXTRACT)
322 {
323 /* Unlike a SUBREG destination, a set of a ZERO_EXTRACT only
324 modifies the bits referenced in the ZERO_EXTRACT, the rest
325 remain the same. Thus we can not continue here, we must
326 either figure out what part of the destination is modified
327 or skip the sub-rtxs. */
328 skipped_dest = true;
329 iter.skip_subrtxes ();
330 continue;
331 }
332
333 /* BIT >= 64 indicates something went horribly wrong. */
334 gcc_assert (bit <= HOST_BITS_PER_WIDE_INT - 1);
335
336 /* Now handle the actual object that was changed. */
337 if (REG_P (x))
338 {
339 /* LIVE_TMP contains the set groups that are live-out and set in
340 this insn. It is used to narrow the groups live-in for the
341 inputs of this insn.
342
343 The simple thing to do is mark all the groups as live, but
344 that will significantly inhibit optimization.
345
346 We also need to be careful in the case where we have an in-out
347 operand. If we're not careful we'd clear LIVE_TMP
348 incorrectly. */
349 HOST_WIDE_INT rn = REGNO (x);
350 int limit = group_limit (x);
351 for (HOST_WIDE_INT i = 4 * rn; i < 4 * rn + limit; i++)
352 if (bitmap_bit_p (livenow, i))
353 bitmap_set_bit (live_tmp, i);
354
355 if (bitmap_empty_p (live_tmp))
356 make_reg_live (live_tmp, rn);
357
358 /* Now clear the bits known written by this instruction.
359 Note that BIT need not be a power of two, consider a
360 ZERO_EXTRACT destination. */
361 int start = (bit < 8 ? 0 : bit < 16 ? 1 : bit < 32 ? 2 : 3);
362 int end = ((mask & ~HOST_WIDE_INT_UC (0xffffffff)) ? 4
363 : (mask & HOST_WIDE_INT_UC (0xffff0000)) ? 3
364 : (mask & 0xff00) ? 2 : 1);
365 bitmap_clear_range (livenow, 4 * rn + start, end - start);
366 }
367 /* Some ports generate (clobber (const_int)). */
368 else if (CONST_INT_P (x))
369 continue;
370 else
371 gcc_assert (CALL_P (insn)
372 || MEM_P (x)
373 || x == pc_rtx
374 || GET_CODE (x) == SCRATCH);
375
376 iter.skip_subrtxes ();
377 }
378 else if (GET_CODE (x) == COND_EXEC)
379 {
380 /* This isn't ideal, but may not be so bad in practice. */
381 skipped_dest = true;
382 iter.skip_subrtxes ();
383 }
384 }
385 return skipped_dest;
386 }
387
388 /* INSN has a sign/zero extended source inside SET that we will
389 try to turn into a SUBREG. */
390 static void
391 ext_dce_try_optimize_insn (rtx_insn *insn, rtx set)
392 {
393 rtx src = SET_SRC (set);
394 rtx inner = XEXP (src, 0);
395
396 /* Avoid (subreg (mem)) and other constructs which may be valid RTL, but
397 not useful for this optimization. */
398 if (!(REG_P (inner) || (SUBREG_P (inner) && REG_P (SUBREG_REG (inner)))))
399 return;
400
401 rtx new_pattern;
402 if (dump_file)
403 {
404 fprintf (dump_file, "Processing insn:\n");
405 dump_insn_slim (dump_file, insn);
406 fprintf (dump_file, "Trying to simplify pattern:\n");
407 print_rtl_single (dump_file, SET_SRC (set));
408 }
409
410 /* We decided to turn do the optimization but allow it to be rejected for
411 bisection purposes. */
412 if (!dbg_cnt (::ext_dce))
413 {
414 if (dump_file)
415 fprintf (dump_file, "Rejected due to debug counter.\n");
416 return;
417 }
418
419 new_pattern = simplify_gen_subreg (GET_MODE (src), inner,
420 GET_MODE (inner), 0);
421 /* simplify_gen_subreg may fail in which case NEW_PATTERN will be NULL.
422 We must not pass that as a replacement pattern to validate_change. */
423 if (new_pattern)
424 {
425 int ok = validate_change (insn, &SET_SRC (set), new_pattern, false);
426
427 rtx x = SET_DEST (set);
428 while (SUBREG_P (x) || GET_CODE (x) == ZERO_EXTRACT)
429 x = XEXP (x, 0);
430
431 gcc_assert (REG_P (x));
432 if (ok)
433 bitmap_set_bit (changed_pseudos, REGNO (x));
434
435 if (dump_file)
436 {
437 if (ok)
438 fprintf (dump_file, "Successfully transformed to:\n");
439 else
440 fprintf (dump_file, "Failed transformation to:\n");
441
442 print_rtl_single (dump_file, new_pattern);
443 fprintf (dump_file, "\n");
444 }
445
446 /* INSN may have a REG_EQUAL note indicating that the value was
447 sign or zero extended. That note is no longer valid since we've
448 just removed the extension. Just wipe the notes. */
449 remove_reg_equal_equiv_notes (insn, false);
450 }
451 else
452 {
453 if (dump_file)
454 fprintf (dump_file, "Unable to generate valid SUBREG expression.\n");
455 }
456 }
457
458 /* Some operators imply that their second operand is fully live,
459 regardless of how many bits in the output are live. An example
460 would be the shift count on a target without SHIFT_COUNT_TRUNCATED
461 defined.
462
463 Return TRUE if CODE is such an operator. FALSE otherwise. */
464
465 static bool
466 binop_implies_op2_fully_live (rtx_code code)
467 {
468 switch (code)
469 {
470 case ASHIFT:
471 case LSHIFTRT:
472 case ASHIFTRT:
473 case ROTATE:
474 case ROTATERT:
475 case SS_ASHIFT:
476 case US_ASHIFT:
477 return !SHIFT_COUNT_TRUNCATED;
478
479 default:
480 return false;
481 }
482 }
483
484 /* X, with code CODE, is an operation for which safe_for_live_propagation
485 holds true, and bits set in MASK are live in the result. Compute a
486 mask of (potentially) live bits in the non-constant inputs. In case of
487 binop_implies_op2_fully_live (e.g. shifts), the computed mask may
488 exclusively pertain to the first operand.
489
490 This looks wrong as we may have some important operations embedded as
491 operands of another operation. For example, we might have an extension
492 wrapping a shift. It really feels like this needs to be recursing down
493 into operands much more often. */
494
495 unsigned HOST_WIDE_INT
496 carry_backpropagate (unsigned HOST_WIDE_INT mask, enum rtx_code code, rtx x)
497 {
498 if (mask == 0)
499 return 0;
500
501 enum machine_mode mode = GET_MODE_INNER (GET_MODE (x));
502 unsigned HOST_WIDE_INT mmask = GET_MODE_MASK (mode);
503
504 /* While we don't try to optimize operations on types larger
505 than 64 bits, we do want to make sure not to invoke undefined
506 behavior when presented with such operations during use
507 processing. The safe thing to do is to just return mmask
508 for that scenario indicating every possible chunk is life. */
509 scalar_int_mode smode;
510 if (!is_a <scalar_int_mode> (mode, &smode)
511 || GET_MODE_BITSIZE (smode) > HOST_BITS_PER_WIDE_INT)
512 return mmask;
513
514 switch (code)
515 {
516 case PLUS:
517 case MINUS:
518 case MULT:
519 return (HOST_WIDE_INT_UC (2) << floor_log2 (mask)) - 1;
520
521 /* We propagate for the shifted operand, but not the shift
522 count. The count is handled specially. */
523 case ASHIFT:
524 if (CONST_INT_P (XEXP (x, 1))
525 && UINTVAL (XEXP (x, 1)) < GET_MODE_BITSIZE (smode))
526 return (HOST_WIDE_INT) mask >> INTVAL (XEXP (x, 1));
527 return (HOST_WIDE_INT_UC (2) << floor_log2 (mask)) - 1;
528
529 /* We propagate for the shifted operand, but not the shift
530 count. The count is handled specially. */
531 case LSHIFTRT:
532 if (CONST_INT_P (XEXP (x, 1))
533 && UINTVAL (XEXP (x, 1)) < GET_MODE_BITSIZE (smode))
534 return mmask & (mask << INTVAL (XEXP (x, 1)));
535 return mmask;
536
537 /* We propagate for the shifted operand, but not the shift
538 count. The count is handled specially. */
539 case ASHIFTRT:
540 if (CONST_INT_P (XEXP (x, 1))
541 && UINTVAL (XEXP (x, 1)) < GET_MODE_BITSIZE (smode))
542 {
543 HOST_WIDE_INT sign = 0;
544 if (HOST_BITS_PER_WIDE_INT - clz_hwi (mask) + INTVAL (XEXP (x, 1))
545 > GET_MODE_BITSIZE (smode))
546 sign = HOST_WIDE_INT_1U << (GET_MODE_BITSIZE (smode) - 1);
547 return sign | (mmask & (mask << INTVAL (XEXP (x, 1))));
548 }
549 return mmask;
550
551 case SMUL_HIGHPART:
552 case UMUL_HIGHPART:
553 if (XEXP (x, 1) == const0_rtx)
554 return 0;
555 if (XEXP (x, 1) == const1_rtx)
556 return mmask;
557 if (CONST_INT_P (XEXP (x, 1)))
558 {
559 if (pow2p_hwi (INTVAL (XEXP (x, 1))))
560 return mmask & (mask << (GET_MODE_BITSIZE (smode)
561 - exact_log2 (INTVAL (XEXP (x, 1)))));
562
563 int bits = (HOST_BITS_PER_WIDE_INT + GET_MODE_BITSIZE (smode)
564 - clz_hwi (mask) - ctz_hwi (INTVAL (XEXP (x, 1))));
565 if (bits < GET_MODE_BITSIZE (smode))
566 return (HOST_WIDE_INT_1U << bits) - 1;
567 }
568 return mmask;
569
570 case SIGN_EXTEND:
571 if (!GET_MODE_BITSIZE (GET_MODE (x)).is_constant ()
572 || !GET_MODE_BITSIZE (GET_MODE (XEXP (x, 0))).is_constant ())
573 return -1;
574
575 /* We want the mode of the inner object. We need to ensure its
576 sign bit is on in MASK. */
577 mode = GET_MODE_INNER (GET_MODE (XEXP (x, 0)));
578 if (mask & ~GET_MODE_MASK (mode))
579 mask |= HOST_WIDE_INT_1U << (GET_MODE_BITSIZE (mode).to_constant ()
580 - 1);
581
582 /* Recurse into the operand. */
583 return carry_backpropagate (mask, GET_CODE (XEXP (x, 0)), XEXP (x, 0));
584
585 case ZERO_EXTEND:
586 if (!GET_MODE_BITSIZE (GET_MODE (x)).is_constant ()
587 || !GET_MODE_BITSIZE (GET_MODE (XEXP (x, 0))).is_constant ())
588 return -1;
589
590 /* Recurse into the operand. */
591 return carry_backpropagate (mask, GET_CODE (XEXP (x, 0)), XEXP (x, 0));
592
593 /* We propagate for the shifted operand, but not the shift
594 count. The count is handled specially. */
595 case SS_ASHIFT:
596 case US_ASHIFT:
597 if (CONST_INT_P (XEXP (x, 1))
598 && UINTVAL (XEXP (x, 1)) < GET_MODE_BITSIZE (smode))
599 {
600 return ((mmask & ~((unsigned HOST_WIDE_INT) mmask
601 >> (INTVAL (XEXP (x, 1))
602 + (XEXP (x, 1) != const0_rtx
603 && code == SS_ASHIFT))))
604 | ((HOST_WIDE_INT) mask >> INTVAL (XEXP (x, 1))));
605 }
606 return mmask;
607
608 default:
609 return mask;
610 }
611 }
612
613 /* Process uses in INSN contained in OBJ. Set appropriate bits in LIVENOW
614 for any chunks of pseudos that become live, potentially filtering using
615 bits from LIVE_TMP.
616
617 If MODIFY is true, then optimize sign/zero extensions to SUBREGs when
618 the extended bits are never read and mark pseudos which had extensions
619 eliminated in CHANGED_PSEUDOS. */
620
621 static void
622 ext_dce_process_uses (rtx_insn *insn, rtx obj,
623 bitmap live_tmp, bool skipped_dest)
624 {
625 subrtx_var_iterator::array_type array_var;
626 FOR_EACH_SUBRTX_VAR (iter, array_var, obj, NONCONST)
627 {
628 /* An EXPR_LIST (from call fusage) ends in NULL_RTX. */
629 rtx x = *iter;
630 if (x == NULL_RTX)
631 continue;
632
633 /* So the basic idea in this FOR_EACH_SUBRTX_VAR loop is to
634 handle SETs explicitly, possibly propagating live information
635 into the uses.
636
637 We may continue the loop at various points which will cause
638 iteration into the next level of RTL. Breaking from the loop
639 is never safe as it can lead us to fail to process some of the
640 RTL and thus not make objects live when necessary. */
641 enum rtx_code xcode = GET_CODE (x);
642 if (xcode == SET)
643 {
644 const_rtx dst = SET_DEST (x);
645 rtx src = SET_SRC (x);
646 const_rtx y;
647 unsigned HOST_WIDE_INT bit = 0;
648
649 /* The code of the RHS of a SET. */
650 enum rtx_code code = GET_CODE (src);
651
652 /* ?!? How much of this should mirror SET handling, potentially
653 being shared? */
654 if (SUBREG_P (dst) && subreg_lsb (dst).is_constant (&bit))
655 {
656 if (bit >= HOST_BITS_PER_WIDE_INT)
657 bit = HOST_BITS_PER_WIDE_INT - 1;
658 dst = SUBREG_REG (dst);
659 }
660 else if (GET_CODE (dst) == STRICT_LOW_PART)
661 dst = XEXP (dst, 0);
662
663 /* Main processing of the uses. Two major goals here.
664
665 First, we want to try and propagate liveness (or the lack
666 thereof) from the destination register to the source
667 register(s).
668
669 Second, if the source is an extension, try to optimize
670 it into a SUBREG. The SUBREG form indicates we don't
671 care about the upper bits and will usually be copy
672 propagated away.
673
674 If we fail to handle something in here, the expectation
675 is the iterator will dive into the sub-components and
676 mark all the chunks in any found REGs as live. */
677 if (REG_P (dst) && safe_for_live_propagation (code))
678 {
679 /* Create a mask representing the bits of this output
680 operand that are live after this insn. We can use
681 this information to refine the live in state of
682 inputs to this insn in many cases.
683
684 We have to do this on a per SET basis, we might have
685 an INSN with multiple SETS, some of which can narrow
686 the source operand liveness, some of which may not. */
687 unsigned HOST_WIDE_INT dst_mask = 0;
688 HOST_WIDE_INT rn = REGNO (dst);
689 unsigned HOST_WIDE_INT mask_array[]
690 = { 0xff, 0xff00, HOST_WIDE_INT_UC (0xffff0000),
691 -HOST_WIDE_INT_UC (0x100000000) };
692 for (int i = 0; i < 4; i++)
693 if (bitmap_bit_p (live_tmp, 4 * rn + i))
694 dst_mask |= mask_array[i];
695 dst_mask >>= bit;
696
697 /* If we ignored a destination during set processing, then
698 consider all the bits live. */
699 if (skipped_dest)
700 dst_mask = -1;
701
702 dst_mask = carry_backpropagate (dst_mask, code, src);
703
704 /* ??? Could also handle ZERO_EXTRACT / SIGN_EXTRACT
705 of the source specially to improve optimization. */
706 if (code == SIGN_EXTEND || code == ZERO_EXTEND)
707 {
708 rtx inner = XEXP (src, 0);
709 unsigned HOST_WIDE_INT src_mask
710 = GET_MODE_MASK (GET_MODE_INNER (GET_MODE (inner)));
711
712 /* DST_MASK could be zero if we had something in the SET
713 that we couldn't handle. */
714 if (modify && !skipped_dest && (dst_mask & ~src_mask) == 0)
715 ext_dce_try_optimize_insn (insn, x);
716
717 /* Stripping the extension here just seems wrong on multiple
718 levels. It's source side handling, so it seems like it
719 belongs in the loop below. Stripping here also makes it
720 harder than necessary to properly handle live bit groups
721 for (ANY_EXTEND (SUBREG)) where the SUBREG has
722 SUBREG_PROMOTED state. */
723 dst_mask &= src_mask;
724 src = XEXP (src, 0);
725 code = GET_CODE (src);
726 }
727
728 /* Optimization is done at this point. We just want to make
729 sure everything that should get marked as live is marked
730 from here onward. */
731
732 /* We will handle the other operand of a binary operator
733 at the bottom of the loop by resetting Y. */
734 if (BINARY_P (src))
735 y = XEXP (src, 0);
736 else
737 y = src;
738
739 /* We're inside a SET and want to process the source operands
740 making things live. Breaking from this loop will cause
741 the iterator to work on sub-rtxs, so it is safe to break
742 if we see something we don't know how to handle.
743
744 This code is just hokey as it really just handles trivial
745 unary and binary cases. Otherwise the loop exits and we
746 continue iterating on sub-rtxs, but outside the set context. */
747 unsigned HOST_WIDE_INT save_mask = dst_mask;
748 for (;;)
749 {
750 /* In general we want to restore DST_MASK before each loop
751 iteration. The exception is when the opcode implies that
752 the other operand is fully live. That's handled by
753 changing SAVE_MASK below. */
754 dst_mask = save_mask;
755 /* Strip an outer paradoxical subreg. The bits outside
756 the inner mode are don't cares. So we can just strip
757 and process the inner object. */
758 if (paradoxical_subreg_p (y))
759 y = XEXP (y, 0);
760 else if (SUBREG_P (y) && subreg_lsb (y).is_constant (&bit))
761 {
762 /* If !TRULY_NOOP_TRUNCATION_MODES_P, the mode
763 change performed by Y would normally need to be a
764 TRUNCATE rather than a SUBREG. It is probably the
765 guarantee provided by SUBREG_PROMOTED_VAR_P that
766 allows the SUBREG in Y as an exception. We must
767 therefore preserve that guarantee and treat the
768 upper bits of the inner register as live
769 regardless of the outer code. See PR 120050. */
770 if (!REG_P (SUBREG_REG (y))
771 || (SUBREG_PROMOTED_VAR_P (y)
772 && (!TRULY_NOOP_TRUNCATION_MODES_P (
773 GET_MODE (y),
774 GET_MODE (SUBREG_REG (y))))))
775 break;
776
777 /* If this is a wide object (more bits than we can fit
778 in a HOST_WIDE_INT), then just break from the SET
779 context. That will cause the iterator to walk down
780 into the subrtx and if we land on a REG we'll mark
781 the whole think live. */
782 if (bit >= HOST_BITS_PER_WIDE_INT)
783 break;
784
785 /* The SUBREG's mode determines the live width. */
786 if (dst_mask)
787 {
788 dst_mask <<= bit;
789 if (!dst_mask)
790 dst_mask = -HOST_WIDE_INT_UC (0x100000000);
791 }
792 y = SUBREG_REG (y);
793 }
794
795 if (REG_P (y))
796 {
797 /* We have found the use of a register. We need to mark
798 the appropriate chunks of the register live. The mode
799 of the REG is a starting point. We may refine that
800 based on what chunks in the output were live. */
801 rn = 4 * REGNO (y);
802 unsigned HOST_WIDE_INT tmp_mask = dst_mask;
803
804 /* If the RTX code for the SET_SRC is not one we can
805 propagate destination liveness through, then just
806 set the mask to the mode's mask. */
807 if (!safe_for_live_propagation (code))
808 tmp_mask
809 = GET_MODE_MASK (GET_MODE_INNER (GET_MODE (y)));
810
811 if (tmp_mask & 0xff)
812 bitmap_set_bit (livenow, rn);
813 if (tmp_mask & 0xff00)
814 bitmap_set_bit (livenow, rn + 1);
815 if (tmp_mask & HOST_WIDE_INT_UC (0xffff0000))
816 bitmap_set_bit (livenow, rn + 2);
817 if (tmp_mask & -HOST_WIDE_INT_UC (0x100000000))
818 bitmap_set_bit (livenow, rn + 3);
819 }
820 else if (!CONSTANT_P (y))
821 break;
822
823 /* We might have (ashift (const_int 1) (reg...))
824 By setting dst_mask we can continue iterating on the
825 the next operand and it will be considered fully live.
826
827 Note that since we restore DST_MASK from SAVE_MASK at the
828 top of the loop, we have to change SAVE_MASK to get the
829 semantics we want. */
830 if (binop_implies_op2_fully_live (GET_CODE (src)))
831 save_mask = -1;
832
833 /* If this was anything but a binary operand, break the inner
834 loop. This is conservatively correct as it will cause the
835 iterator to look at the sub-rtxs outside the SET context. */
836 if (!BINARY_P (src))
837 break;
838
839 /* We processed the first operand of a binary operator. Now
840 handle the second. */
841 y = XEXP (src, 1), src = pc_rtx;
842 }
843
844 /* These are leaf nodes, no need to iterate down into them. */
845 if (REG_P (y) || CONSTANT_P (y))
846 iter.skip_subrtxes ();
847 }
848 }
849 /* If we are reading the low part of a SUBREG, then we can
850 refine liveness of the input register, otherwise let the
851 iterator continue into SUBREG_REG. */
852 else if (SUBREG_P (x)
853 && REG_P (SUBREG_REG (x))
854 && !paradoxical_subreg_p (x)
855 && subreg_lowpart_p (x)
856 && GET_MODE_BITSIZE (GET_MODE (x)).is_constant ()
857 && GET_MODE_BITSIZE (GET_MODE (x)).to_constant () <= 32)
858 {
859 HOST_WIDE_INT size = GET_MODE_BITSIZE (GET_MODE (x)).to_constant ();
860 HOST_WIDE_INT rn = 4 * REGNO (SUBREG_REG (x));
861
862 /* If this is a promoted subreg, then more of it may be live than
863 is otherwise obvious. */
864 if (SUBREG_PROMOTED_VAR_P (x))
865 size = GET_MODE_BITSIZE (GET_MODE (SUBREG_REG (x))).to_constant ();
866
867 bitmap_set_bit (livenow, rn);
868 if (size > 8)
869 bitmap_set_bit (livenow, rn + 1);
870 if (size > 16)
871 bitmap_set_bit (livenow, rn + 2);
872 if (size >= 32)
873 bitmap_set_bit (livenow, rn + 3);
874 iter.skip_subrtxes ();
875 }
876 /* If we have a register reference that is not otherwise handled,
877 just assume all the chunks are live. */
878 else if (REG_P (x))
879 bitmap_set_range (livenow, REGNO (x) * 4, group_limit (x));
880 }
881 }
882
883 /* Process a single basic block BB with current liveness information
884 in LIVENOW, returning updated liveness information.
885
886 If MODIFY is true, then this is the last pass and unnecessary
887 extensions should be eliminated when possible. If an extension
888 is removed, the source pseudo is marked in CHANGED_PSEUDOS. */
889
890 static void
891 ext_dce_process_bb (basic_block bb)
892 {
893 rtx_insn *insn;
894
895 FOR_BB_INSNS_REVERSE (bb, insn)
896 {
897 if (!NONDEBUG_INSN_P (insn))
898 continue;
899
900 /* Live-out state of the destination of this insn. We can
901 use this to refine the live-in state of the sources of
902 this insn in many cases. */
903 bitmap live_tmp = BITMAP_ALLOC (NULL);
904
905 /* First process any sets/clobbers in INSN. */
906 bool skipped_dest = ext_dce_process_sets (insn, PATTERN (insn), live_tmp);
907
908 /* CALL_INSNs need processing their fusage data. */
909 if (CALL_P (insn))
910 skipped_dest |= ext_dce_process_sets (insn,
911 CALL_INSN_FUNCTION_USAGE (insn),
912 live_tmp);
913
914 /* And now uses, optimizing away SIGN/ZERO extensions as we go. */
915 ext_dce_process_uses (insn, PATTERN (insn), live_tmp, skipped_dest);
916
917 /* A nonlocal goto implicitly uses the frame pointer. */
918 if (JUMP_P (insn) && find_reg_note (insn, REG_NON_LOCAL_GOTO, NULL_RTX))
919 {
920 bitmap_set_range (livenow, FRAME_POINTER_REGNUM * 4, 4);
921 if (!HARD_FRAME_POINTER_IS_FRAME_POINTER)
922 bitmap_set_range (livenow, HARD_FRAME_POINTER_REGNUM * 4, 4);
923 }
924
925 /* And process fusage data for the use as well. */
926 if (CALL_P (insn))
927 {
928 if (!FAKE_CALL_P (insn))
929 bitmap_set_range (livenow, STACK_POINTER_REGNUM * 4, 4);
930
931 /* If this is not a call to a const fucntion, then assume it
932 can read any global register. */
933 if (!RTL_CONST_CALL_P (insn))
934 for (unsigned i = 0; i < FIRST_PSEUDO_REGISTER; i++)
935 if (global_regs[i])
936 bitmap_set_range (livenow, i * 4, 4);
937
938 ext_dce_process_uses (insn, CALL_INSN_FUNCTION_USAGE (insn), live_tmp, false);
939 }
940
941 BITMAP_FREE (live_tmp);
942 }
943 }
944
945 /* SUBREG_PROMOTED_VAR_P is set by the gimple->rtl optimizers and
946 is usually helpful. However, in some cases setting the value when
947 it not strictly needed can cause this pass to miss optimizations.
948
949 Specifically consider (set (mem) (subreg (reg))). If set in that
950 case it will cause more bit groups to be live for REG than would
951 be strictly necessary which in turn can inhibit extension removal.
952
953 So do a pass over the IL wiping the SUBREG_PROMOTED_VAR_P when it
954 is obviously not needed. */
955
956 static void
957 maybe_clear_subreg_promoted_p (void)
958 {
959 for (rtx_insn *insn = get_insns(); insn; insn = NEXT_INSN (insn))
960 {
961 if (!NONDEBUG_INSN_P (insn))
962 continue;
963
964 rtx set = single_set (insn);
965 if (!set)
966 continue;
967
968 /* There may be other cases where we should clear, but for
969 now, this is the only known case where it causes problems. */
970 if (MEM_P (SET_DEST (set)) && SUBREG_P (SET_SRC (set))
971 && GET_MODE (SET_DEST (set)) <= GET_MODE (SUBREG_REG (SET_SRC (set))))
972 SUBREG_PROMOTED_VAR_P (SET_SRC (set)) = 0;
973 }
974 }
975
976 /* Walk the IL and build the transitive closure of all the REGs tied
977 together by copies where either the source or destination is
978 marked in CHANGED_PSEUDOS. */
979
980 static void
981 expand_changed_pseudos (void)
982 {
983 /* Build a vector of registers related by a copy. This is meant to
984 speed up the next step by avoiding full IL walks. */
985 struct copy_pair { rtx first; rtx second; };
986 auto_vec<copy_pair> pairs;
987 for (rtx_insn *insn = get_insns(); insn; insn = NEXT_INSN (insn))
988 {
989 if (!NONDEBUG_INSN_P (insn))
990 continue;
991
992 rtx pat = PATTERN (insn);
993
994 /* Simple copies to a REG from another REG or SUBREG of a REG. */
995 if (GET_CODE (pat) == SET
996 && REG_P (SET_DEST (pat))
997 && (REG_P (SET_SRC (pat))
998 || (SUBREG_P (SET_SRC (pat))
999 && REG_P (SUBREG_REG (SET_SRC (pat))))))
1000 {
1001 rtx src = (REG_P (SET_SRC (pat))
1002 ? SET_SRC (pat)
1003 : SUBREG_REG (SET_SRC (pat)));
1004 pairs.safe_push ({ SET_DEST (pat), src });
1005 }
1006
1007 /* Simple copies to a REG from another REG or SUBREG of a REG
1008 held inside a PARALLEL. */
1009 if (GET_CODE (pat) == PARALLEL)
1010 {
1011 for (int i = XVECLEN (pat, 0) - 1; i >= 0; i--)
1012 {
1013 rtx elem = XVECEXP (pat, 0, i);
1014
1015 if (GET_CODE (elem) == SET
1016 && REG_P (SET_DEST (elem))
1017 && (REG_P (SET_SRC (elem))
1018 || (SUBREG_P (SET_SRC (elem))
1019 && REG_P (SUBREG_REG (SET_SRC (elem))))))
1020 {
1021 rtx src = (REG_P (SET_SRC (elem))
1022 ? SET_SRC (elem)
1023 : SUBREG_REG (SET_SRC (elem)));
1024 pairs.safe_push ({ SET_DEST (elem), src });
1025 }
1026 }
1027 continue;
1028 }
1029 }
1030
1031 /* Now we have a vector with copy pairs. Iterate over that list
1032 updating CHANGED_PSEUDOS as we go. Eliminate copies from the
1033 list as we go as they don't need further processing. */
1034 bool changed = true;
1035 while (changed)
1036 {
1037 changed = false;
1038 unsigned int i;
1039 copy_pair *p;
1040 FOR_EACH_VEC_ELT (pairs, i, p)
1041 {
1042 if (bitmap_bit_p (changed_pseudos, REGNO (p->second))
1043 && bitmap_set_bit (changed_pseudos, REGNO (p->first)))
1044 {
1045 pairs.unordered_remove (i);
1046 changed = true;
1047 }
1048 }
1049 }
1050 }
1051
1052 /* We optimize away sign/zero extensions in this pass and replace
1053 them with SUBREGs indicating certain bits are don't cares.
1054
1055 This changes the SUBREG_PROMOTED_VAR_P state of the object.
1056 It is fairly painful to fix this on the fly, so we have
1057 recorded which pseudos are affected and we look for SUBREGs
1058 of those pseudos and fix them up. */
1059
1060 static void
1061 reset_subreg_promoted_p (void)
1062 {
1063 /* This pass eliminates zero/sign extensions on pseudo regs found
1064 in CHANGED_PSEUDOS. Elimination of those extensions changes if
1065 the pseudos are known to hold values extended to wider modes
1066 via SUBREG_PROMOTED_VAR. So we wipe the SUBREG_PROMOTED_VAR
1067 state on all affected pseudos.
1068
1069 But that is insufficient. We might have a copy from one REG
1070 to another (possibly with the source register wrapped with a
1071 SUBREG). We need to wipe SUBREG_PROMOTED_VAR on the transitive
1072 closure of the original CHANGED_PSEUDOS and registers they're
1073 connected to via copies. So expand the set. */
1074 expand_changed_pseudos ();
1075
1076 /* If we removed an extension, that changed the promoted state
1077 of the destination of that extension. Thus we need to go
1078 find any SUBREGs that reference that pseudo and adjust their
1079 SUBREG_PROMOTED_P state. */
1080 for (rtx_insn *insn = get_insns(); insn; insn = NEXT_INSN (insn))
1081 {
1082 if (!NONDEBUG_INSN_P (insn))
1083 continue;
1084
1085 rtx pat = PATTERN (insn);
1086 subrtx_var_iterator::array_type array;
1087 FOR_EACH_SUBRTX_VAR (iter, array, pat, NONCONST)
1088 {
1089 rtx sub = *iter;
1090
1091 /* We only care about SUBREGs. */
1092 if (GET_CODE (sub) != SUBREG)
1093 continue;
1094
1095 const_rtx x = SUBREG_REG (sub);
1096
1097 /* We only care if the inner object is a REG. */
1098 if (!REG_P (x))
1099 continue;
1100
1101 /* And only if the SUBREG is a promoted var. */
1102 if (!SUBREG_PROMOTED_VAR_P (sub))
1103 continue;
1104
1105 if (bitmap_bit_p (changed_pseudos, REGNO (x)))
1106 SUBREG_PROMOTED_VAR_P (sub) = 0;
1107 }
1108 }
1109 }
1110
1111 /* Initialization of the ext-dce pass. Primarily this means
1112 setting up the various bitmaps we utilize. */
1113
1114 static void
1115 ext_dce_init (void)
1116 {
1117 livein.create (last_basic_block_for_fn (cfun));
1118 livein.quick_grow_cleared (last_basic_block_for_fn (cfun));
1119 for (int i = 0; i < last_basic_block_for_fn (cfun); i++)
1120 bitmap_initialize (&livein[i], &bitmap_default_obstack);
1121
1122 auto_bitmap refs (&bitmap_default_obstack);
1123 df_get_exit_block_use_set (refs);
1124
1125 unsigned i;
1126 bitmap_iterator bi;
1127 EXECUTE_IF_SET_IN_BITMAP (refs, 0, i, bi)
1128 make_reg_live (&livein[EXIT_BLOCK], i);
1129
1130 livenow = BITMAP_ALLOC (NULL);
1131 all_blocks = BITMAP_ALLOC (NULL);
1132 changed_pseudos = BITMAP_ALLOC (NULL);
1133
1134 for (int i = 0; i < last_basic_block_for_fn (cfun); i++)
1135 if (i != ENTRY_BLOCK && i != EXIT_BLOCK)
1136 bitmap_set_bit (all_blocks, i);
1137
1138 modify = false;
1139 }
1140
1141 /* Finalization of the ext-dce pass. Primarily this means
1142 releasing up the various bitmaps we utilize. */
1143
1144 static void
1145 ext_dce_finish (void)
1146 {
1147 for (unsigned i = 0; i < livein.length (); i++)
1148 bitmap_clear (&livein[i]);
1149 livein.release ();
1150
1151 BITMAP_FREE (livenow);
1152 BITMAP_FREE (changed_pseudos);
1153 BITMAP_FREE (all_blocks);
1154 }
1155
1156 /* Process block number BB_INDEX as part of the backward
1157 simple dataflow analysis. Return TRUE if something in
1158 this block changed or FALSE otherwise. */
1159
1160 static bool
1161 ext_dce_rd_transfer_n (int bb_index)
1162 {
1163 /* The ENTRY/EXIT blocks never change. */
1164 if (bb_index == ENTRY_BLOCK || bb_index == EXIT_BLOCK)
1165 return false;
1166
1167 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, bb_index);
1168
1169 /* Make everything live that's live in the successors. */
1170 bitmap_clear (livenow);
1171 edge_iterator ei;
1172 edge e;
1173
1174 FOR_EACH_EDGE (e, ei, bb->succs)
1175 bitmap_ior_into (livenow, &livein[e->dest->index]);
1176
1177 ext_dce_process_bb (bb);
1178
1179 /* We only allow widening the set of objects live at the start
1180 of a block. Otherwise we run the risk of not converging. */
1181 return bitmap_ior_into (&livein[bb_index], livenow);
1182 }
1183
1184 /* Dummy function for the df_simple_dataflow API. */
1185 static bool ext_dce_rd_confluence_n (edge) { return true; }
1186
1187 /* Use lifetime analyis to identify extensions that set bits that
1188 are never read. Turn such extensions into SUBREGs instead which
1189 can often be propagated away. */
1190
1191 void
1192 ext_dce_execute (void)
1193 {
1194 /* Limit the amount of memory we use for livein, with 4 bits per
1195 reg per basic-block including overhead that maps to one byte
1196 per reg per basic-block. */
1197 uint64_t memory_request
1198 = (uint64_t)n_basic_blocks_for_fn (cfun) * max_reg_num ();
1199 if (memory_request / 1024 > (uint64_t)param_max_gcse_memory)
1200 {
1201 warning (OPT_Wdisabled_optimization,
1202 "ext-dce disabled: %d basic blocks and %d registers; "
1203 "increase %<--param max-gcse-memory%> above %wu",
1204 n_basic_blocks_for_fn (cfun), max_reg_num (),
1205 memory_request / 1024);
1206 return;
1207 }
1208
1209 /* Some settings of SUBREG_PROMOTED_VAR_P are actively harmful
1210 to this pass. Clear it for those cases. */
1211 maybe_clear_subreg_promoted_p ();
1212 df_analyze ();
1213 ext_dce_init ();
1214
1215 do
1216 {
1217 df_simple_dataflow (DF_BACKWARD, NULL, NULL,
1218 ext_dce_rd_confluence_n, ext_dce_rd_transfer_n,
1219 all_blocks, df_get_postorder (DF_BACKWARD),
1220 df_get_n_blocks (DF_BACKWARD));
1221 modify = !modify;
1222 }
1223 while (modify);
1224
1225 reset_subreg_promoted_p ();
1226
1227 ext_dce_finish ();
1228 }
1229
1230
1231 namespace {
1232
1233 const pass_data pass_data_ext_dce =
1234 {
1235 RTL_PASS, /* type */
1236 "ext_dce", /* name */
1237 OPTGROUP_NONE, /* optinfo_flags */
1238 TV_EXT_DCE, /* tv_id */
1239 PROP_cfglayout, /* properties_required */
1240 0, /* properties_provided */
1241 0, /* properties_destroyed */
1242 0, /* todo_flags_start */
1243 TODO_df_finish, /* todo_flags_finish */
1244 };
1245
1246 class pass_ext_dce : public rtl_opt_pass
1247 {
1248 public:
1249 pass_ext_dce (gcc::context *ctxt)
1250 : rtl_opt_pass (pass_data_ext_dce, ctxt)
1251 {}
1252
1253 /* opt_pass methods: */
1254 virtual bool gate (function *) { return flag_ext_dce && optimize > 0; }
1255 virtual unsigned int execute (function *)
1256 {
1257 ext_dce_execute ();
1258 return 0;
1259 }
1260
1261 }; // class pass_combine
1262
1263 } // anon namespace
1264
1265 rtl_opt_pass *
1266 make_pass_ext_dce (gcc::context *ctxt)
1267 {
1268 return new pass_ext_dce (ctxt);
1269 }