d: Merge upstream dmd, druntime c8ae4adb2e, phobos 792c8b7c1.
[official-gcc.git] / gcc / tree-ssa-dse.cc
blob82976bdbeb0b9d2b2cbc14d67f47ed4caf114071
1 /* Dead and redundant store elimination
2 Copyright (C) 2004-2022 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #define INCLUDE_MEMORY
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "tree-pass.h"
29 #include "ssa.h"
30 #include "gimple-pretty-print.h"
31 #include "fold-const.h"
32 #include "gimple-iterator.h"
33 #include "tree-cfg.h"
34 #include "tree-dfa.h"
35 #include "tree-cfgcleanup.h"
36 #include "alias.h"
37 #include "tree-ssa-loop.h"
38 #include "tree-ssa-dse.h"
39 #include "builtins.h"
40 #include "gimple-fold.h"
41 #include "gimplify.h"
42 #include "tree-eh.h"
43 #include "cfganal.h"
44 #include "cgraph.h"
45 #include "ipa-modref-tree.h"
46 #include "ipa-modref.h"
47 #include "target.h"
48 #include "tree-ssa-loop-niter.h"
49 #include "cfgloop.h"
50 #include "tree-data-ref.h"
52 /* This file implements dead store elimination.
54 A dead store is a store into a memory location which will later be
55 overwritten by another store without any intervening loads. In this
56 case the earlier store can be deleted or trimmed if the store
57 was partially dead.
59 A redundant store is a store into a memory location which stores
60 the exact same value as a prior store to the same memory location.
61 While this can often be handled by dead store elimination, removing
62 the redundant store is often better than removing or trimming the
63 dead store.
65 In our SSA + virtual operand world we use immediate uses of virtual
66 operands to detect these cases. If a store's virtual definition
67 is used precisely once by a later store to the same location which
68 post dominates the first store, then the first store is dead. If
69 the data stored is the same, then the second store is redundant.
71 The single use of the store's virtual definition ensures that
72 there are no intervening aliased loads and the requirement that
73 the second load post dominate the first ensures that if the earlier
74 store executes, then the later stores will execute before the function
75 exits.
77 It may help to think of this as first moving the earlier store to
78 the point immediately before the later store. Again, the single
79 use of the virtual definition and the post-dominance relationship
80 ensure that such movement would be safe. Clearly if there are
81 back to back stores, then the second is makes the first dead. If
82 the second store stores the same value, then the second store is
83 redundant.
85 Reviewing section 10.7.2 in Morgan's "Building an Optimizing Compiler"
86 may also help in understanding this code since it discusses the
87 relationship between dead store and redundant load elimination. In
88 fact, they are the same transformation applied to different views of
89 the CFG. */
91 static void delete_dead_or_redundant_call (gimple_stmt_iterator *, const char *);
93 /* Bitmap of blocks that have had EH statements cleaned. We should
94 remove their dead edges eventually. */
95 static bitmap need_eh_cleanup;
96 static bitmap need_ab_cleanup;
98 /* STMT is a statement that may write into memory. Analyze it and
99 initialize WRITE to describe how STMT affects memory. When
100 MAY_DEF_OK is true then the function initializes WRITE to what
101 the stmt may define.
103 Return TRUE if the statement was analyzed, FALSE otherwise.
105 It is always safe to return FALSE. But typically better optimziation
106 can be achieved by analyzing more statements. */
108 static bool
109 initialize_ao_ref_for_dse (gimple *stmt, ao_ref *write, bool may_def_ok = false)
111 /* It's advantageous to handle certain mem* functions. */
112 if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
114 switch (DECL_FUNCTION_CODE (gimple_call_fndecl (stmt)))
116 case BUILT_IN_MEMCPY:
117 case BUILT_IN_MEMMOVE:
118 case BUILT_IN_MEMSET:
119 case BUILT_IN_MEMCPY_CHK:
120 case BUILT_IN_MEMMOVE_CHK:
121 case BUILT_IN_MEMSET_CHK:
122 case BUILT_IN_STRNCPY:
123 case BUILT_IN_STRNCPY_CHK:
125 tree size = gimple_call_arg (stmt, 2);
126 tree ptr = gimple_call_arg (stmt, 0);
127 ao_ref_init_from_ptr_and_size (write, ptr, size);
128 return true;
131 /* A calloc call can never be dead, but it can make
132 subsequent stores redundant if they store 0 into
133 the same memory locations. */
134 case BUILT_IN_CALLOC:
136 tree nelem = gimple_call_arg (stmt, 0);
137 tree selem = gimple_call_arg (stmt, 1);
138 tree lhs;
139 if (TREE_CODE (nelem) == INTEGER_CST
140 && TREE_CODE (selem) == INTEGER_CST
141 && (lhs = gimple_call_lhs (stmt)) != NULL_TREE)
143 tree size = fold_build2 (MULT_EXPR, TREE_TYPE (nelem),
144 nelem, selem);
145 ao_ref_init_from_ptr_and_size (write, lhs, size);
146 return true;
150 default:
151 break;
154 else if (is_gimple_call (stmt)
155 && gimple_call_internal_p (stmt))
157 switch (gimple_call_internal_fn (stmt))
159 case IFN_LEN_STORE:
160 ao_ref_init_from_ptr_and_size
161 (write, gimple_call_arg (stmt, 0),
162 int_const_binop (MINUS_EXPR,
163 gimple_call_arg (stmt, 2),
164 gimple_call_arg (stmt, 4)));
165 return true;
166 case IFN_MASK_STORE:
167 /* We cannot initialize a must-def ao_ref (in all cases) but we
168 can provide a may-def variant. */
169 if (may_def_ok)
171 ao_ref_init_from_ptr_and_size
172 (write, gimple_call_arg (stmt, 0),
173 TYPE_SIZE_UNIT (TREE_TYPE (gimple_call_arg (stmt, 3))));
174 return true;
176 break;
177 default:;
180 else if (tree lhs = gimple_get_lhs (stmt))
182 if (TREE_CODE (lhs) != SSA_NAME)
184 ao_ref_init (write, lhs);
185 return true;
188 return false;
191 /* Given REF from the alias oracle, return TRUE if it is a valid
192 kill memory reference for dead store elimination, false otherwise.
194 In particular, the reference must have a known base, known maximum
195 size, start at a byte offset and have a size that is one or more
196 bytes. */
198 static bool
199 valid_ao_ref_kill_for_dse (ao_ref *ref)
201 return (ao_ref_base (ref)
202 && known_size_p (ref->max_size)
203 && maybe_ne (ref->size, 0)
204 && known_eq (ref->max_size, ref->size)
205 && known_ge (ref->offset, 0));
208 /* Given REF from the alias oracle, return TRUE if it is a valid
209 load or store memory reference for dead store elimination, false otherwise.
211 Unlike for valid_ao_ref_kill_for_dse we can accept writes where max_size
212 is not same as size since we can handle conservatively the larger range. */
214 static bool
215 valid_ao_ref_for_dse (ao_ref *ref)
217 return (ao_ref_base (ref)
218 && known_size_p (ref->max_size)
219 && known_ge (ref->offset, 0));
222 /* Initialize OFFSET and SIZE to a range known to contain REF
223 where the boundaries are divisible by BITS_PER_UNIT (bit still in bits).
224 Return false if this is impossible. */
226 static bool
227 get_byte_aligned_range_containing_ref (ao_ref *ref, poly_int64 *offset,
228 HOST_WIDE_INT *size)
230 if (!known_size_p (ref->max_size))
231 return false;
232 *offset = aligned_lower_bound (ref->offset, BITS_PER_UNIT);
233 poly_int64 end = aligned_upper_bound (ref->offset + ref->max_size,
234 BITS_PER_UNIT);
235 return (end - *offset).is_constant (size);
238 /* Initialize OFFSET and SIZE to a range known to be contained REF
239 where the boundaries are divisible by BITS_PER_UNIT (but still in bits).
240 Return false if this is impossible. */
242 static bool
243 get_byte_aligned_range_contained_in_ref (ao_ref *ref, poly_int64 *offset,
244 HOST_WIDE_INT *size)
246 if (!known_size_p (ref->size)
247 || !known_eq (ref->size, ref->max_size))
248 return false;
249 *offset = aligned_upper_bound (ref->offset, BITS_PER_UNIT);
250 poly_int64 end = aligned_lower_bound (ref->offset + ref->max_size,
251 BITS_PER_UNIT);
252 /* For bit accesses we can get -1 here, but also 0 sized kill is not
253 useful. */
254 if (!known_gt (end, *offset))
255 return false;
256 return (end - *offset).is_constant (size);
259 /* Compute byte range (returned iN REF_OFFSET and RET_SIZE) for access COPY
260 inside REF. If KILL is true, then COPY represent a kill and the byte range
261 needs to be fully contained in bit range given by COPY. If KILL is false
262 then the byte range returned must contain the range of COPY. */
264 static bool
265 get_byte_range (ao_ref *copy, ao_ref *ref, bool kill,
266 HOST_WIDE_INT *ret_offset, HOST_WIDE_INT *ret_size)
268 HOST_WIDE_INT copy_size, ref_size;
269 poly_int64 copy_offset, ref_offset;
270 HOST_WIDE_INT diff;
272 /* First translate from bits to bytes, rounding to bigger or smaller ranges
273 as needed. Kills needs to be always rounded to smaller ranges while
274 uses and stores to larger ranges. */
275 if (kill)
277 if (!get_byte_aligned_range_contained_in_ref (copy, &copy_offset,
278 &copy_size))
279 return false;
281 else
283 if (!get_byte_aligned_range_containing_ref (copy, &copy_offset,
284 &copy_size))
285 return false;
288 if (!get_byte_aligned_range_containing_ref (ref, &ref_offset, &ref_size)
289 || !ordered_p (copy_offset, ref_offset))
290 return false;
292 /* Switch sizes from bits to bytes so we do not need to care about
293 overflows. Offset calculation needs to stay in bits until we compute
294 the difference and can switch to HOST_WIDE_INT. */
295 copy_size /= BITS_PER_UNIT;
296 ref_size /= BITS_PER_UNIT;
298 /* If COPY starts before REF, then reset the beginning of
299 COPY to match REF and decrease the size of COPY by the
300 number of bytes removed from COPY. */
301 if (maybe_lt (copy_offset, ref_offset))
303 if (!(ref_offset - copy_offset).is_constant (&diff)
304 || copy_size < diff / BITS_PER_UNIT)
305 return false;
306 copy_size -= diff / BITS_PER_UNIT;
307 copy_offset = ref_offset;
310 if (!(copy_offset - ref_offset).is_constant (&diff)
311 || ref_size <= diff / BITS_PER_UNIT)
312 return false;
314 /* If COPY extends beyond REF, chop off its size appropriately. */
315 HOST_WIDE_INT limit = ref_size - diff / BITS_PER_UNIT;
317 if (copy_size > limit)
318 copy_size = limit;
319 *ret_size = copy_size;
320 if (!(copy_offset - ref_offset).is_constant (ret_offset))
321 return false;
322 *ret_offset /= BITS_PER_UNIT;
323 return true;
326 /* Update LIVE_BYTES tracking REF for write to WRITE:
327 Verify we have the same base memory address, the write
328 has a known size and overlaps with REF. */
329 static void
330 clear_live_bytes_for_ref (sbitmap live_bytes, ao_ref *ref, ao_ref *write)
332 HOST_WIDE_INT start, size;
334 if (valid_ao_ref_kill_for_dse (write)
335 && operand_equal_p (write->base, ref->base, OEP_ADDRESS_OF)
336 && get_byte_range (write, ref, true, &start, &size))
337 bitmap_clear_range (live_bytes, start, size);
340 /* Clear any bytes written by STMT from the bitmap LIVE_BYTES. The base
341 address written by STMT must match the one found in REF, which must
342 have its base address previously initialized.
344 This routine must be conservative. If we don't know the offset or
345 actual size written, assume nothing was written. */
347 static void
348 clear_bytes_written_by (sbitmap live_bytes, gimple *stmt, ao_ref *ref)
350 ao_ref write;
352 if (gcall *call = dyn_cast <gcall *> (stmt))
354 bool interposed;
355 modref_summary *summary = get_modref_function_summary (call, &interposed);
357 if (summary && !interposed)
358 for (auto kill : summary->kills)
359 if (kill.get_ao_ref (as_a <gcall *> (stmt), &write))
360 clear_live_bytes_for_ref (live_bytes, ref, &write);
362 if (!initialize_ao_ref_for_dse (stmt, &write))
363 return;
365 clear_live_bytes_for_ref (live_bytes, ref, &write);
368 /* REF is a memory write. Extract relevant information from it and
369 initialize the LIVE_BYTES bitmap. If successful, return TRUE.
370 Otherwise return FALSE. */
372 static bool
373 setup_live_bytes_from_ref (ao_ref *ref, sbitmap live_bytes)
375 HOST_WIDE_INT const_size;
376 if (valid_ao_ref_for_dse (ref)
377 && ((aligned_upper_bound (ref->offset + ref->max_size, BITS_PER_UNIT)
378 - aligned_lower_bound (ref->offset,
379 BITS_PER_UNIT)).is_constant (&const_size))
380 && (const_size / BITS_PER_UNIT <= param_dse_max_object_size)
381 && const_size > 1)
383 bitmap_clear (live_bytes);
384 bitmap_set_range (live_bytes, 0, const_size / BITS_PER_UNIT);
385 return true;
387 return false;
390 /* Compute the number of elements that we can trim from the head and
391 tail of ORIG resulting in a bitmap that is a superset of LIVE.
393 Store the number of elements trimmed from the head and tail in
394 TRIM_HEAD and TRIM_TAIL.
396 STMT is the statement being trimmed and is used for debugging dump
397 output only. */
399 static void
400 compute_trims (ao_ref *ref, sbitmap live, int *trim_head, int *trim_tail,
401 gimple *stmt)
403 /* We use sbitmaps biased such that ref->offset is bit zero and the bitmap
404 extends through ref->size. So we know that in the original bitmap
405 bits 0..ref->size were true. We don't actually need the bitmap, just
406 the REF to compute the trims. */
408 /* Now identify how much, if any of the tail we can chop off. */
409 HOST_WIDE_INT const_size;
410 int last_live = bitmap_last_set_bit (live);
411 if (ref->size.is_constant (&const_size))
413 int last_orig = (const_size / BITS_PER_UNIT) - 1;
414 /* We can leave inconvenient amounts on the tail as
415 residual handling in mem* and str* functions is usually
416 reasonably efficient. */
417 *trim_tail = last_orig - last_live;
419 /* But don't trim away out of bounds accesses, as this defeats
420 proper warnings.
422 We could have a type with no TYPE_SIZE_UNIT or we could have a VLA
423 where TYPE_SIZE_UNIT is not a constant. */
424 if (*trim_tail
425 && TYPE_SIZE_UNIT (TREE_TYPE (ref->base))
426 && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (ref->base))) == INTEGER_CST
427 && compare_tree_int (TYPE_SIZE_UNIT (TREE_TYPE (ref->base)),
428 last_orig) <= 0)
429 *trim_tail = 0;
431 else
432 *trim_tail = 0;
434 /* Identify how much, if any of the head we can chop off. */
435 int first_orig = 0;
436 int first_live = bitmap_first_set_bit (live);
437 *trim_head = first_live - first_orig;
439 /* If REF is aligned, try to maintain this alignment if it reduces
440 the number of (power-of-two sized aligned) writes to memory. */
441 unsigned int align_bits;
442 unsigned HOST_WIDE_INT bitpos;
443 if ((*trim_head || *trim_tail)
444 && last_live - first_live >= 2
445 && ao_ref_alignment (ref, &align_bits, &bitpos)
446 && align_bits >= 32
447 && bitpos == 0
448 && align_bits % BITS_PER_UNIT == 0)
450 unsigned int align_units = align_bits / BITS_PER_UNIT;
451 if (align_units > 16)
452 align_units = 16;
453 while ((first_live | (align_units - 1)) > (unsigned int)last_live)
454 align_units >>= 1;
456 if (*trim_head)
458 unsigned int pos = first_live & (align_units - 1);
459 for (unsigned int i = 1; i <= align_units; i <<= 1)
461 unsigned int mask = ~(i - 1);
462 unsigned int bytes = align_units - (pos & mask);
463 if (wi::popcount (bytes) <= 1)
465 *trim_head &= mask;
466 break;
471 if (*trim_tail)
473 unsigned int pos = last_live & (align_units - 1);
474 for (unsigned int i = 1; i <= align_units; i <<= 1)
476 int mask = i - 1;
477 unsigned int bytes = (pos | mask) + 1;
478 if ((last_live | mask) > (last_live + *trim_tail))
479 break;
480 if (wi::popcount (bytes) <= 1)
482 unsigned int extra = (last_live | mask) - last_live;
483 *trim_tail -= extra;
484 break;
490 if ((*trim_head || *trim_tail)
491 && dump_file && (dump_flags & TDF_DETAILS))
493 fprintf (dump_file, " Trimming statement (head = %d, tail = %d): ",
494 *trim_head, *trim_tail);
495 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
496 fprintf (dump_file, "\n");
500 /* STMT initializes an object from COMPLEX_CST where one or more of the
501 bytes written may be dead stores. REF is a representation of the
502 memory written. LIVE is the bitmap of stores that are actually live.
504 Attempt to rewrite STMT so that only the real or imaginary part of
505 the object is actually stored. */
507 static void
508 maybe_trim_complex_store (ao_ref *ref, sbitmap live, gimple *stmt)
510 int trim_head, trim_tail;
511 compute_trims (ref, live, &trim_head, &trim_tail, stmt);
513 /* The amount of data trimmed from the head or tail must be at
514 least half the size of the object to ensure we're trimming
515 the entire real or imaginary half. By writing things this
516 way we avoid more O(n) bitmap operations. */
517 if (known_ge (trim_tail * 2 * BITS_PER_UNIT, ref->size))
519 /* TREE_REALPART is live */
520 tree x = TREE_REALPART (gimple_assign_rhs1 (stmt));
521 tree y = gimple_assign_lhs (stmt);
522 y = build1 (REALPART_EXPR, TREE_TYPE (x), y);
523 gimple_assign_set_lhs (stmt, y);
524 gimple_assign_set_rhs1 (stmt, x);
526 else if (known_ge (trim_head * 2 * BITS_PER_UNIT, ref->size))
528 /* TREE_IMAGPART is live */
529 tree x = TREE_IMAGPART (gimple_assign_rhs1 (stmt));
530 tree y = gimple_assign_lhs (stmt);
531 y = build1 (IMAGPART_EXPR, TREE_TYPE (x), y);
532 gimple_assign_set_lhs (stmt, y);
533 gimple_assign_set_rhs1 (stmt, x);
536 /* Other cases indicate parts of both the real and imag subobjects
537 are live. We do not try to optimize those cases. */
540 /* STMT initializes an object using a CONSTRUCTOR where one or more of the
541 bytes written are dead stores. ORIG is the bitmap of bytes stored by
542 STMT. LIVE is the bitmap of stores that are actually live.
544 Attempt to rewrite STMT so that only the real or imaginary part of
545 the object is actually stored.
547 The most common case for getting here is a CONSTRUCTOR with no elements
548 being used to zero initialize an object. We do not try to handle other
549 cases as those would force us to fully cover the object with the
550 CONSTRUCTOR node except for the components that are dead. */
552 static void
553 maybe_trim_constructor_store (ao_ref *ref, sbitmap live, gimple *stmt)
555 tree ctor = gimple_assign_rhs1 (stmt);
557 /* This is the only case we currently handle. It actually seems to
558 catch most cases of actual interest. */
559 gcc_assert (CONSTRUCTOR_NELTS (ctor) == 0);
561 int head_trim = 0;
562 int tail_trim = 0;
563 compute_trims (ref, live, &head_trim, &tail_trim, stmt);
565 /* Now we want to replace the constructor initializer
566 with memset (object + head_trim, 0, size - head_trim - tail_trim). */
567 if (head_trim || tail_trim)
569 /* We want &lhs for the MEM_REF expression. */
570 tree lhs_addr = build_fold_addr_expr (gimple_assign_lhs (stmt));
572 if (! is_gimple_min_invariant (lhs_addr))
573 return;
575 /* The number of bytes for the new constructor. */
576 poly_int64 ref_bytes = exact_div (ref->size, BITS_PER_UNIT);
577 poly_int64 count = ref_bytes - head_trim - tail_trim;
579 /* And the new type for the CONSTRUCTOR. Essentially it's just
580 a char array large enough to cover the non-trimmed parts of
581 the original CONSTRUCTOR. Note we want explicit bounds here
582 so that we know how many bytes to clear when expanding the
583 CONSTRUCTOR. */
584 tree type = build_array_type_nelts (char_type_node, count);
586 /* Build a suitable alias type rather than using alias set zero
587 to avoid pessimizing. */
588 tree alias_type = reference_alias_ptr_type (gimple_assign_lhs (stmt));
590 /* Build a MEM_REF representing the whole accessed area, starting
591 at the first byte not trimmed. */
592 tree exp = fold_build2 (MEM_REF, type, lhs_addr,
593 build_int_cst (alias_type, head_trim));
595 /* Now update STMT with a new RHS and LHS. */
596 gimple_assign_set_lhs (stmt, exp);
597 gimple_assign_set_rhs1 (stmt, build_constructor (type, NULL));
601 /* STMT is a memcpy, memmove or memset. Decrement the number of bytes
602 copied/set by DECREMENT. */
603 static void
604 decrement_count (gimple *stmt, int decrement)
606 tree *countp = gimple_call_arg_ptr (stmt, 2);
607 gcc_assert (TREE_CODE (*countp) == INTEGER_CST);
608 *countp = wide_int_to_tree (TREE_TYPE (*countp), (TREE_INT_CST_LOW (*countp)
609 - decrement));
612 static void
613 increment_start_addr (gimple *stmt, tree *where, int increment)
615 if (tree lhs = gimple_call_lhs (stmt))
616 if (where == gimple_call_arg_ptr (stmt, 0))
618 gassign *newop = gimple_build_assign (lhs, unshare_expr (*where));
619 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
620 gsi_insert_after (&gsi, newop, GSI_SAME_STMT);
621 gimple_call_set_lhs (stmt, NULL_TREE);
622 update_stmt (stmt);
625 if (TREE_CODE (*where) == SSA_NAME)
627 tree tem = make_ssa_name (TREE_TYPE (*where));
628 gassign *newop
629 = gimple_build_assign (tem, POINTER_PLUS_EXPR, *where,
630 build_int_cst (sizetype, increment));
631 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
632 gsi_insert_before (&gsi, newop, GSI_SAME_STMT);
633 *where = tem;
634 update_stmt (stmt);
635 return;
638 *where = build_fold_addr_expr (fold_build2 (MEM_REF, char_type_node,
639 *where,
640 build_int_cst (ptr_type_node,
641 increment)));
644 /* STMT is builtin call that writes bytes in bitmap ORIG, some bytes are dead
645 (ORIG & ~NEW) and need not be stored. Try to rewrite STMT to reduce
646 the amount of data it actually writes.
648 Right now we only support trimming from the head or the tail of the
649 memory region. In theory we could split the mem* call, but it's
650 likely of marginal value. */
652 static void
653 maybe_trim_memstar_call (ao_ref *ref, sbitmap live, gimple *stmt)
655 int head_trim, tail_trim;
656 switch (DECL_FUNCTION_CODE (gimple_call_fndecl (stmt)))
658 case BUILT_IN_STRNCPY:
659 case BUILT_IN_STRNCPY_CHK:
660 compute_trims (ref, live, &head_trim, &tail_trim, stmt);
661 if (head_trim)
663 /* Head trimming of strncpy is only possible if we can
664 prove all bytes we would trim are non-zero (or we could
665 turn the strncpy into memset if there must be zero
666 among the head trimmed bytes). If we don't know anything
667 about those bytes, the presence or absence of '\0' bytes
668 in there will affect whether it acts for the non-trimmed
669 bytes as memset or memcpy/strncpy. */
670 c_strlen_data lendata = { };
671 int orig_head_trim = head_trim;
672 tree srcstr = gimple_call_arg (stmt, 1);
673 if (!get_range_strlen (srcstr, &lendata, /*eltsize=*/1)
674 || !tree_fits_uhwi_p (lendata.minlen))
675 head_trim = 0;
676 else if (tree_to_uhwi (lendata.minlen) < (unsigned) head_trim)
678 head_trim = tree_to_uhwi (lendata.minlen);
679 if ((orig_head_trim & (UNITS_PER_WORD - 1)) == 0)
680 head_trim &= ~(UNITS_PER_WORD - 1);
682 if (orig_head_trim != head_trim
683 && dump_file
684 && (dump_flags & TDF_DETAILS))
685 fprintf (dump_file,
686 " Adjusting strncpy trimming to (head = %d,"
687 " tail = %d)\n", head_trim, tail_trim);
689 goto do_memcpy;
691 case BUILT_IN_MEMCPY:
692 case BUILT_IN_MEMMOVE:
693 case BUILT_IN_MEMCPY_CHK:
694 case BUILT_IN_MEMMOVE_CHK:
695 compute_trims (ref, live, &head_trim, &tail_trim, stmt);
697 do_memcpy:
698 /* Tail trimming is easy, we can just reduce the count. */
699 if (tail_trim)
700 decrement_count (stmt, tail_trim);
702 /* Head trimming requires adjusting all the arguments. */
703 if (head_trim)
705 /* For __*_chk need to adjust also the last argument. */
706 if (gimple_call_num_args (stmt) == 4)
708 tree size = gimple_call_arg (stmt, 3);
709 if (!tree_fits_uhwi_p (size))
710 break;
711 if (!integer_all_onesp (size))
713 unsigned HOST_WIDE_INT sz = tree_to_uhwi (size);
714 if (sz < (unsigned) head_trim)
715 break;
716 tree arg = wide_int_to_tree (TREE_TYPE (size),
717 sz - head_trim);
718 gimple_call_set_arg (stmt, 3, arg);
721 tree *dst = gimple_call_arg_ptr (stmt, 0);
722 increment_start_addr (stmt, dst, head_trim);
723 tree *src = gimple_call_arg_ptr (stmt, 1);
724 increment_start_addr (stmt, src, head_trim);
725 decrement_count (stmt, head_trim);
727 break;
729 case BUILT_IN_MEMSET:
730 case BUILT_IN_MEMSET_CHK:
731 compute_trims (ref, live, &head_trim, &tail_trim, stmt);
733 /* Tail trimming is easy, we can just reduce the count. */
734 if (tail_trim)
735 decrement_count (stmt, tail_trim);
737 /* Head trimming requires adjusting all the arguments. */
738 if (head_trim)
740 /* For __*_chk need to adjust also the last argument. */
741 if (gimple_call_num_args (stmt) == 4)
743 tree size = gimple_call_arg (stmt, 3);
744 if (!tree_fits_uhwi_p (size))
745 break;
746 if (!integer_all_onesp (size))
748 unsigned HOST_WIDE_INT sz = tree_to_uhwi (size);
749 if (sz < (unsigned) head_trim)
750 break;
751 tree arg = wide_int_to_tree (TREE_TYPE (size),
752 sz - head_trim);
753 gimple_call_set_arg (stmt, 3, arg);
756 tree *dst = gimple_call_arg_ptr (stmt, 0);
757 increment_start_addr (stmt, dst, head_trim);
758 decrement_count (stmt, head_trim);
760 break;
762 default:
763 break;
767 /* STMT is a memory write where one or more bytes written are dead
768 stores. ORIG is the bitmap of bytes stored by STMT. LIVE is the
769 bitmap of stores that are actually live.
771 Attempt to rewrite STMT so that it writes fewer memory locations. Right
772 now we only support trimming at the start or end of the memory region.
773 It's not clear how much there is to be gained by trimming from the middle
774 of the region. */
776 static void
777 maybe_trim_partially_dead_store (ao_ref *ref, sbitmap live, gimple *stmt)
779 if (is_gimple_assign (stmt)
780 && TREE_CODE (gimple_assign_lhs (stmt)) != TARGET_MEM_REF)
782 switch (gimple_assign_rhs_code (stmt))
784 case CONSTRUCTOR:
785 maybe_trim_constructor_store (ref, live, stmt);
786 break;
787 case COMPLEX_CST:
788 maybe_trim_complex_store (ref, live, stmt);
789 break;
790 default:
791 break;
796 /* Return TRUE if USE_REF reads bytes from LIVE where live is
797 derived from REF, a write reference.
799 While this routine may modify USE_REF, it's passed by value, not
800 location. So callers do not see those modifications. */
802 static bool
803 live_bytes_read (ao_ref *use_ref, ao_ref *ref, sbitmap live)
805 /* We have already verified that USE_REF and REF hit the same object.
806 Now verify that there's actually an overlap between USE_REF and REF. */
807 HOST_WIDE_INT start, size;
808 if (get_byte_range (use_ref, ref, false, &start, &size))
810 /* If USE_REF covers all of REF, then it will hit one or more
811 live bytes. This avoids useless iteration over the bitmap
812 below. */
813 if (start == 0 && known_eq (size * 8, ref->size))
814 return true;
816 /* Now check if any of the remaining bits in use_ref are set in LIVE. */
817 return bitmap_bit_in_range_p (live, start, (start + size - 1));
819 return true;
822 /* Callback for dse_classify_store calling for_each_index. Verify that
823 indices are invariant in the loop with backedge PHI in basic-block DATA. */
825 static bool
826 check_name (tree, tree *idx, void *data)
828 basic_block phi_bb = (basic_block) data;
829 if (TREE_CODE (*idx) == SSA_NAME
830 && !SSA_NAME_IS_DEFAULT_DEF (*idx)
831 && dominated_by_p (CDI_DOMINATORS, gimple_bb (SSA_NAME_DEF_STMT (*idx)),
832 phi_bb))
833 return false;
834 return true;
837 /* STMT stores the value 0 into one or more memory locations
838 (via memset, empty constructor, calloc call, etc).
840 See if there is a subsequent store of the value 0 to one
841 or more of the same memory location(s). If so, the subsequent
842 store is redundant and can be removed.
844 The subsequent stores could be via memset, empty constructors,
845 simple MEM stores, etc. */
847 static void
848 dse_optimize_redundant_stores (gimple *stmt)
850 int cnt = 0;
852 /* TBAA state of STMT, if it is a call it is effectively alias-set zero. */
853 alias_set_type earlier_set = 0;
854 alias_set_type earlier_base_set = 0;
855 if (is_gimple_assign (stmt))
857 ao_ref lhs_ref;
858 ao_ref_init (&lhs_ref, gimple_assign_lhs (stmt));
859 earlier_set = ao_ref_alias_set (&lhs_ref);
860 earlier_base_set = ao_ref_base_alias_set (&lhs_ref);
863 /* We could do something fairly complex and look through PHIs
864 like DSE_CLASSIFY_STORE, but it doesn't seem to be worth
865 the effort.
867 Look at all the immediate uses of the VDEF (which are obviously
868 dominated by STMT). See if one or more stores 0 into the same
869 memory locations a STMT, if so remove the immediate use statements. */
870 tree defvar = gimple_vdef (stmt);
871 imm_use_iterator ui;
872 gimple *use_stmt;
873 FOR_EACH_IMM_USE_STMT (use_stmt, ui, defvar)
875 /* Limit stmt walking. */
876 if (++cnt > param_dse_max_alias_queries_per_store)
877 break;
879 /* If USE_STMT stores 0 into one or more of the same locations
880 as STMT and STMT would kill USE_STMT, then we can just remove
881 USE_STMT. */
882 tree fndecl;
883 if ((is_gimple_assign (use_stmt)
884 && gimple_vdef (use_stmt)
885 && (gimple_assign_single_p (use_stmt)
886 && initializer_zerop (gimple_assign_rhs1 (use_stmt))))
887 || (gimple_call_builtin_p (use_stmt, BUILT_IN_NORMAL)
888 && (fndecl = gimple_call_fndecl (use_stmt)) != NULL
889 && (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMSET
890 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMSET_CHK)
891 && integer_zerop (gimple_call_arg (use_stmt, 1))))
893 ao_ref write;
895 if (!initialize_ao_ref_for_dse (use_stmt, &write))
896 break;
898 if (valid_ao_ref_for_dse (&write)
899 && stmt_kills_ref_p (stmt, &write))
901 gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt);
902 if (is_gimple_assign (use_stmt))
904 ao_ref lhs_ref;
905 ao_ref_init (&lhs_ref, gimple_assign_lhs (use_stmt));
906 if ((earlier_set == ao_ref_alias_set (&lhs_ref)
907 || alias_set_subset_of (ao_ref_alias_set (&lhs_ref),
908 earlier_set))
909 && (earlier_base_set == ao_ref_base_alias_set (&lhs_ref)
910 || alias_set_subset_of
911 (ao_ref_base_alias_set (&lhs_ref),
912 earlier_base_set)))
913 delete_dead_or_redundant_assignment (&gsi, "redundant",
914 need_eh_cleanup,
915 need_ab_cleanup);
917 else if (is_gimple_call (use_stmt))
919 if ((earlier_set == 0
920 || alias_set_subset_of (0, earlier_set))
921 && (earlier_base_set == 0
922 || alias_set_subset_of (0, earlier_base_set)))
923 delete_dead_or_redundant_call (&gsi, "redundant");
925 else
926 gcc_unreachable ();
932 /* Return whether PHI contains ARG as an argument. */
934 static bool
935 contains_phi_arg (gphi *phi, tree arg)
937 for (unsigned i = 0; i < gimple_phi_num_args (phi); ++i)
938 if (gimple_phi_arg_def (phi, i) == arg)
939 return true;
940 return false;
943 /* Hash map of the memory use in a GIMPLE assignment to its
944 data reference. If NULL data-ref analysis isn't used. */
945 static hash_map<gimple *, data_reference_p> *dse_stmt_to_dr_map;
947 /* A helper of dse_optimize_stmt.
948 Given a GIMPLE_ASSIGN in STMT that writes to REF, classify it
949 according to downstream uses and defs. Sets *BY_CLOBBER_P to true
950 if only clobber statements influenced the classification result.
951 Returns the classification. */
953 dse_store_status
954 dse_classify_store (ao_ref *ref, gimple *stmt,
955 bool byte_tracking_enabled, sbitmap live_bytes,
956 bool *by_clobber_p, tree stop_at_vuse)
958 gimple *temp;
959 int cnt = 0;
960 auto_bitmap visited;
961 std::unique_ptr<data_reference, void(*)(data_reference_p)>
962 dra (nullptr, free_data_ref);
964 if (by_clobber_p)
965 *by_clobber_p = true;
967 /* Find the first dominated statement that clobbers (part of) the
968 memory stmt stores to with no intermediate statement that may use
969 part of the memory stmt stores. That is, find a store that may
970 prove stmt to be a dead store. */
971 temp = stmt;
974 gimple *use_stmt;
975 imm_use_iterator ui;
976 bool fail = false;
977 tree defvar;
979 if (gimple_code (temp) == GIMPLE_PHI)
981 defvar = PHI_RESULT (temp);
982 bitmap_set_bit (visited, SSA_NAME_VERSION (defvar));
984 else
985 defvar = gimple_vdef (temp);
987 /* If we're instructed to stop walking at region boundary, do so. */
988 if (defvar == stop_at_vuse)
989 return DSE_STORE_LIVE;
991 auto_vec<gimple *, 10> defs;
992 gphi *first_phi_def = NULL;
993 gphi *last_phi_def = NULL;
994 FOR_EACH_IMM_USE_STMT (use_stmt, ui, defvar)
996 /* Limit stmt walking. */
997 if (++cnt > param_dse_max_alias_queries_per_store)
999 fail = true;
1000 break;
1003 /* In simple cases we can look through PHI nodes, but we
1004 have to be careful with loops and with memory references
1005 containing operands that are also operands of PHI nodes.
1006 See gcc.c-torture/execute/20051110-*.c. */
1007 if (gimple_code (use_stmt) == GIMPLE_PHI)
1009 /* If we already visited this PHI ignore it for further
1010 processing. */
1011 if (!bitmap_bit_p (visited,
1012 SSA_NAME_VERSION (PHI_RESULT (use_stmt))))
1014 /* If we visit this PHI by following a backedge then we have
1015 to make sure ref->ref only refers to SSA names that are
1016 invariant with respect to the loop represented by this
1017 PHI node. */
1018 if (dominated_by_p (CDI_DOMINATORS, gimple_bb (stmt),
1019 gimple_bb (use_stmt))
1020 && !for_each_index (ref->ref ? &ref->ref : &ref->base,
1021 check_name, gimple_bb (use_stmt)))
1022 return DSE_STORE_LIVE;
1023 defs.safe_push (use_stmt);
1024 if (!first_phi_def)
1025 first_phi_def = as_a <gphi *> (use_stmt);
1026 last_phi_def = as_a <gphi *> (use_stmt);
1029 /* If the statement is a use the store is not dead. */
1030 else if (ref_maybe_used_by_stmt_p (use_stmt, ref))
1032 if (dse_stmt_to_dr_map
1033 && ref->ref
1034 && is_gimple_assign (use_stmt))
1036 if (!dra)
1037 dra.reset (create_data_ref (NULL, NULL, ref->ref, stmt,
1038 false, false));
1039 bool existed_p;
1040 data_reference_p &drb
1041 = dse_stmt_to_dr_map->get_or_insert (use_stmt, &existed_p);
1042 if (!existed_p)
1043 drb = create_data_ref (NULL, NULL,
1044 gimple_assign_rhs1 (use_stmt),
1045 use_stmt, false, false);
1046 if (!dr_may_alias_p (dra.get (), drb, NULL))
1048 if (gimple_vdef (use_stmt))
1049 defs.safe_push (use_stmt);
1050 continue;
1054 /* Handle common cases where we can easily build an ao_ref
1055 structure for USE_STMT and in doing so we find that the
1056 references hit non-live bytes and thus can be ignored.
1058 TODO: We can also use modref summary to handle calls. */
1059 if (byte_tracking_enabled
1060 && is_gimple_assign (use_stmt))
1062 ao_ref use_ref;
1063 ao_ref_init (&use_ref, gimple_assign_rhs1 (use_stmt));
1064 if (valid_ao_ref_for_dse (&use_ref)
1065 && operand_equal_p (use_ref.base, ref->base,
1066 OEP_ADDRESS_OF)
1067 && !live_bytes_read (&use_ref, ref, live_bytes))
1069 /* If this is a store, remember it as we possibly
1070 need to walk the defs uses. */
1071 if (gimple_vdef (use_stmt))
1072 defs.safe_push (use_stmt);
1073 continue;
1077 fail = true;
1078 break;
1080 /* We have visited ourselves already so ignore STMT for the
1081 purpose of chaining. */
1082 else if (use_stmt == stmt)
1084 /* If this is a store, remember it as we possibly need to walk the
1085 defs uses. */
1086 else if (gimple_vdef (use_stmt))
1087 defs.safe_push (use_stmt);
1090 if (fail)
1092 /* STMT might be partially dead and we may be able to reduce
1093 how many memory locations it stores into. */
1094 if (byte_tracking_enabled && !gimple_clobber_p (stmt))
1095 return DSE_STORE_MAYBE_PARTIAL_DEAD;
1096 return DSE_STORE_LIVE;
1099 /* If we didn't find any definition this means the store is dead
1100 if it isn't a store to global reachable memory. In this case
1101 just pretend the stmt makes itself dead. Otherwise fail. */
1102 if (defs.is_empty ())
1104 if (ref_may_alias_global_p (ref, false))
1105 return DSE_STORE_LIVE;
1107 if (by_clobber_p)
1108 *by_clobber_p = false;
1109 return DSE_STORE_DEAD;
1112 /* Process defs and remove those we need not process further. */
1113 for (unsigned i = 0; i < defs.length ();)
1115 gimple *def = defs[i];
1116 gimple *use_stmt;
1117 use_operand_p use_p;
1118 tree vdef = (gimple_code (def) == GIMPLE_PHI
1119 ? gimple_phi_result (def) : gimple_vdef (def));
1120 gphi *phi_def;
1121 /* If the path to check starts with a kill we do not need to
1122 process it further.
1123 ??? With byte tracking we need only kill the bytes currently
1124 live. */
1125 if (stmt_kills_ref_p (def, ref))
1127 if (by_clobber_p && !gimple_clobber_p (def))
1128 *by_clobber_p = false;
1129 defs.unordered_remove (i);
1131 /* If the path ends here we do not need to process it further.
1132 This for example happens with calls to noreturn functions. */
1133 else if (has_zero_uses (vdef))
1135 /* But if the store is to global memory it is definitely
1136 not dead. */
1137 if (ref_may_alias_global_p (ref, false))
1138 return DSE_STORE_LIVE;
1139 defs.unordered_remove (i);
1141 /* In addition to kills we can remove defs whose only use
1142 is another def in defs. That can only ever be PHIs of which
1143 we track two for simplicity reasons, the first and last in
1144 {first,last}_phi_def (we fail for multiple PHIs anyways).
1145 We can also ignore defs that feed only into
1146 already visited PHIs. */
1147 else if (single_imm_use (vdef, &use_p, &use_stmt)
1148 && (use_stmt == first_phi_def
1149 || use_stmt == last_phi_def
1150 || (gimple_code (use_stmt) == GIMPLE_PHI
1151 && bitmap_bit_p (visited,
1152 SSA_NAME_VERSION
1153 (PHI_RESULT (use_stmt))))))
1155 defs.unordered_remove (i);
1156 if (def == first_phi_def)
1157 first_phi_def = NULL;
1158 else if (def == last_phi_def)
1159 last_phi_def = NULL;
1161 /* If def is a PHI and one of its arguments is another PHI node still
1162 in consideration we can defer processing it. */
1163 else if ((phi_def = dyn_cast <gphi *> (def))
1164 && ((last_phi_def
1165 && phi_def != last_phi_def
1166 && contains_phi_arg (phi_def,
1167 gimple_phi_result (last_phi_def)))
1168 || (first_phi_def
1169 && phi_def != first_phi_def
1170 && contains_phi_arg
1171 (phi_def, gimple_phi_result (first_phi_def)))))
1173 defs.unordered_remove (i);
1174 if (phi_def == first_phi_def)
1175 first_phi_def = NULL;
1176 else if (phi_def == last_phi_def)
1177 last_phi_def = NULL;
1179 else
1180 ++i;
1183 /* If all defs kill the ref we are done. */
1184 if (defs.is_empty ())
1185 return DSE_STORE_DEAD;
1186 /* If more than one def survives fail. */
1187 if (defs.length () > 1)
1189 /* STMT might be partially dead and we may be able to reduce
1190 how many memory locations it stores into. */
1191 if (byte_tracking_enabled && !gimple_clobber_p (stmt))
1192 return DSE_STORE_MAYBE_PARTIAL_DEAD;
1193 return DSE_STORE_LIVE;
1195 temp = defs[0];
1197 /* Track partial kills. */
1198 if (byte_tracking_enabled)
1200 clear_bytes_written_by (live_bytes, temp, ref);
1201 if (bitmap_empty_p (live_bytes))
1203 if (by_clobber_p && !gimple_clobber_p (temp))
1204 *by_clobber_p = false;
1205 return DSE_STORE_DEAD;
1209 /* Continue walking until there are no more live bytes. */
1210 while (1);
1214 /* Delete a dead call at GSI, which is mem* call of some kind. */
1215 static void
1216 delete_dead_or_redundant_call (gimple_stmt_iterator *gsi, const char *type)
1218 gimple *stmt = gsi_stmt (*gsi);
1219 if (dump_file && (dump_flags & TDF_DETAILS))
1221 fprintf (dump_file, " Deleted %s call: ", type);
1222 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
1223 fprintf (dump_file, "\n");
1226 basic_block bb = gimple_bb (stmt);
1227 tree lhs = gimple_call_lhs (stmt);
1228 if (lhs)
1230 tree ptr = gimple_call_arg (stmt, 0);
1231 gimple *new_stmt = gimple_build_assign (lhs, ptr);
1232 unlink_stmt_vdef (stmt);
1233 if (gsi_replace (gsi, new_stmt, true))
1234 bitmap_set_bit (need_eh_cleanup, bb->index);
1236 else
1238 /* Then we need to fix the operand of the consuming stmt. */
1239 unlink_stmt_vdef (stmt);
1241 /* Remove the dead store. */
1242 if (gsi_remove (gsi, true))
1243 bitmap_set_bit (need_eh_cleanup, bb->index);
1244 release_defs (stmt);
1248 /* Delete a dead store at GSI, which is a gimple assignment. */
1250 void
1251 delete_dead_or_redundant_assignment (gimple_stmt_iterator *gsi,
1252 const char *type,
1253 bitmap need_eh_cleanup,
1254 bitmap need_ab_cleanup)
1256 gimple *stmt = gsi_stmt (*gsi);
1257 if (dump_file && (dump_flags & TDF_DETAILS))
1259 fprintf (dump_file, " Deleted %s store: ", type);
1260 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
1261 fprintf (dump_file, "\n");
1264 /* Then we need to fix the operand of the consuming stmt. */
1265 unlink_stmt_vdef (stmt);
1267 /* Remove the dead store. */
1268 basic_block bb = gimple_bb (stmt);
1269 if (need_ab_cleanup && stmt_can_make_abnormal_goto (stmt))
1270 bitmap_set_bit (need_ab_cleanup, bb->index);
1271 if (gsi_remove (gsi, true) && need_eh_cleanup)
1272 bitmap_set_bit (need_eh_cleanup, bb->index);
1274 /* And release any SSA_NAMEs set in this statement back to the
1275 SSA_NAME manager. */
1276 release_defs (stmt);
1279 /* Try to prove, using modref summary, that all memory written to by a call is
1280 dead and remove it. Assume that if return value is written to memory
1281 it is already proved to be dead. */
1283 static bool
1284 dse_optimize_call (gimple_stmt_iterator *gsi, sbitmap live_bytes)
1286 gcall *stmt = dyn_cast <gcall *> (gsi_stmt (*gsi));
1288 if (!stmt)
1289 return false;
1291 tree callee = gimple_call_fndecl (stmt);
1293 if (!callee)
1294 return false;
1296 /* Pure/const functions are optimized by normal DCE
1297 or handled as store above. */
1298 int flags = gimple_call_flags (stmt);
1299 if ((flags & (ECF_PURE|ECF_CONST|ECF_NOVOPS))
1300 && !(flags & (ECF_LOOPING_CONST_OR_PURE)))
1301 return false;
1303 cgraph_node *node = cgraph_node::get (callee);
1304 if (!node)
1305 return false;
1307 if (stmt_could_throw_p (cfun, stmt)
1308 && !cfun->can_delete_dead_exceptions)
1309 return false;
1311 /* If return value is used the call is not dead. */
1312 tree lhs = gimple_call_lhs (stmt);
1313 if (lhs && TREE_CODE (lhs) == SSA_NAME)
1315 imm_use_iterator ui;
1316 gimple *use_stmt;
1317 FOR_EACH_IMM_USE_STMT (use_stmt, ui, lhs)
1318 if (!is_gimple_debug (use_stmt))
1319 return false;
1322 /* Verify that there are no side-effects except for return value
1323 and memory writes tracked by modref. */
1324 modref_summary *summary = get_modref_function_summary (node);
1325 if (!summary || !summary->try_dse)
1326 return false;
1328 bool by_clobber_p = false;
1330 /* Walk all memory writes and verify that they are dead. */
1331 for (auto base_node : summary->stores->bases)
1332 for (auto ref_node : base_node->refs)
1333 for (auto access_node : ref_node->accesses)
1335 tree arg = access_node.get_call_arg (stmt);
1337 if (!arg || !POINTER_TYPE_P (TREE_TYPE (arg)))
1338 return false;
1340 if (integer_zerop (arg)
1341 && !targetm.addr_space.zero_address_valid
1342 (TYPE_ADDR_SPACE (TREE_TYPE (arg))))
1343 continue;
1345 ao_ref ref;
1347 if (!access_node.get_ao_ref (stmt, &ref))
1348 return false;
1349 ref.ref_alias_set = ref_node->ref;
1350 ref.base_alias_set = base_node->base;
1352 bool byte_tracking_enabled
1353 = setup_live_bytes_from_ref (&ref, live_bytes);
1354 enum dse_store_status store_status;
1356 store_status = dse_classify_store (&ref, stmt,
1357 byte_tracking_enabled,
1358 live_bytes, &by_clobber_p);
1359 if (store_status != DSE_STORE_DEAD)
1360 return false;
1362 delete_dead_or_redundant_assignment (gsi, "dead", need_eh_cleanup,
1363 need_ab_cleanup);
1364 return true;
1367 /* Attempt to eliminate dead stores in the statement referenced by BSI.
1369 A dead store is a store into a memory location which will later be
1370 overwritten by another store without any intervening loads. In this
1371 case the earlier store can be deleted.
1373 In our SSA + virtual operand world we use immediate uses of virtual
1374 operands to detect dead stores. If a store's virtual definition
1375 is used precisely once by a later store to the same location which
1376 post dominates the first store, then the first store is dead. */
1378 static void
1379 dse_optimize_stmt (function *fun, gimple_stmt_iterator *gsi, sbitmap live_bytes)
1381 gimple *stmt = gsi_stmt (*gsi);
1383 /* Don't return early on *this_2(D) ={v} {CLOBBER}. */
1384 if (gimple_has_volatile_ops (stmt)
1385 && (!gimple_clobber_p (stmt)
1386 || TREE_CODE (gimple_assign_lhs (stmt)) != MEM_REF))
1387 return;
1389 ao_ref ref;
1390 /* If this is not a store we can still remove dead call using
1391 modref summary. Note we specifically allow ref to be initialized
1392 to a conservative may-def since we are looking for followup stores
1393 to kill all of it. */
1394 if (!initialize_ao_ref_for_dse (stmt, &ref, true))
1396 dse_optimize_call (gsi, live_bytes);
1397 return;
1400 /* We know we have virtual definitions. We can handle assignments and
1401 some builtin calls. */
1402 if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
1404 tree fndecl = gimple_call_fndecl (stmt);
1405 switch (DECL_FUNCTION_CODE (fndecl))
1407 case BUILT_IN_MEMCPY:
1408 case BUILT_IN_MEMMOVE:
1409 case BUILT_IN_STRNCPY:
1410 case BUILT_IN_MEMSET:
1411 case BUILT_IN_MEMCPY_CHK:
1412 case BUILT_IN_MEMMOVE_CHK:
1413 case BUILT_IN_STRNCPY_CHK:
1414 case BUILT_IN_MEMSET_CHK:
1416 /* Occasionally calls with an explicit length of zero
1417 show up in the IL. It's pointless to do analysis
1418 on them, they're trivially dead. */
1419 tree size = gimple_call_arg (stmt, 2);
1420 if (integer_zerop (size))
1422 delete_dead_or_redundant_call (gsi, "dead");
1423 return;
1426 /* If this is a memset call that initializes an object
1427 to zero, it may be redundant with an earlier memset
1428 or empty CONSTRUCTOR of a larger object. */
1429 if ((DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMSET
1430 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMSET_CHK)
1431 && integer_zerop (gimple_call_arg (stmt, 1)))
1432 dse_optimize_redundant_stores (stmt);
1434 enum dse_store_status store_status;
1435 bool byte_tracking_enabled
1436 = setup_live_bytes_from_ref (&ref, live_bytes);
1437 store_status = dse_classify_store (&ref, stmt,
1438 byte_tracking_enabled,
1439 live_bytes);
1440 if (store_status == DSE_STORE_LIVE)
1441 return;
1443 if (store_status == DSE_STORE_MAYBE_PARTIAL_DEAD)
1445 maybe_trim_memstar_call (&ref, live_bytes, stmt);
1446 return;
1449 if (store_status == DSE_STORE_DEAD)
1450 delete_dead_or_redundant_call (gsi, "dead");
1451 return;
1454 case BUILT_IN_CALLOC:
1455 /* We already know the arguments are integer constants. */
1456 dse_optimize_redundant_stores (stmt);
1457 return;
1459 default:
1460 return;
1463 else if (is_gimple_call (stmt)
1464 && gimple_call_internal_p (stmt))
1466 switch (gimple_call_internal_fn (stmt))
1468 case IFN_LEN_STORE:
1469 case IFN_MASK_STORE:
1471 enum dse_store_status store_status;
1472 store_status = dse_classify_store (&ref, stmt, false, live_bytes);
1473 if (store_status == DSE_STORE_DEAD)
1474 delete_dead_or_redundant_call (gsi, "dead");
1475 return;
1477 default:;
1481 bool by_clobber_p = false;
1483 /* Check if this statement stores zero to a memory location,
1484 and if there is a subsequent store of zero to the same
1485 memory location. If so, remove the subsequent store. */
1486 if (gimple_assign_single_p (stmt)
1487 && initializer_zerop (gimple_assign_rhs1 (stmt)))
1488 dse_optimize_redundant_stores (stmt);
1490 /* Self-assignments are zombies. */
1491 if (is_gimple_assign (stmt)
1492 && operand_equal_p (gimple_assign_rhs1 (stmt),
1493 gimple_assign_lhs (stmt), 0))
1495 else
1497 bool byte_tracking_enabled
1498 = setup_live_bytes_from_ref (&ref, live_bytes);
1499 enum dse_store_status store_status;
1500 store_status = dse_classify_store (&ref, stmt,
1501 byte_tracking_enabled,
1502 live_bytes, &by_clobber_p);
1503 if (store_status == DSE_STORE_LIVE)
1504 return;
1506 if (store_status == DSE_STORE_MAYBE_PARTIAL_DEAD)
1508 maybe_trim_partially_dead_store (&ref, live_bytes, stmt);
1509 return;
1513 /* Now we know that use_stmt kills the LHS of stmt. */
1515 /* But only remove *this_2(D) ={v} {CLOBBER} if killed by
1516 another clobber stmt. */
1517 if (gimple_clobber_p (stmt)
1518 && !by_clobber_p)
1519 return;
1521 if (is_gimple_call (stmt)
1522 && (gimple_has_side_effects (stmt)
1523 || (stmt_could_throw_p (fun, stmt)
1524 && !fun->can_delete_dead_exceptions)))
1526 /* See if we can remove complete call. */
1527 if (dse_optimize_call (gsi, live_bytes))
1528 return;
1529 /* Make sure we do not remove a return slot we cannot reconstruct
1530 later. */
1531 if (gimple_call_return_slot_opt_p (as_a <gcall *>(stmt))
1532 && (TREE_ADDRESSABLE (TREE_TYPE (gimple_call_fntype (stmt)))
1533 || !poly_int_tree_p
1534 (TYPE_SIZE (TREE_TYPE (gimple_call_fntype (stmt))))))
1535 return;
1536 if (dump_file && (dump_flags & TDF_DETAILS))
1538 fprintf (dump_file, " Deleted dead store in call LHS: ");
1539 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
1540 fprintf (dump_file, "\n");
1542 gimple_call_set_lhs (stmt, NULL_TREE);
1543 update_stmt (stmt);
1545 else if (!stmt_could_throw_p (fun, stmt)
1546 || fun->can_delete_dead_exceptions)
1547 delete_dead_or_redundant_assignment (gsi, "dead", need_eh_cleanup,
1548 need_ab_cleanup);
1551 namespace {
1553 const pass_data pass_data_dse =
1555 GIMPLE_PASS, /* type */
1556 "dse", /* name */
1557 OPTGROUP_NONE, /* optinfo_flags */
1558 TV_TREE_DSE, /* tv_id */
1559 ( PROP_cfg | PROP_ssa ), /* properties_required */
1560 0, /* properties_provided */
1561 0, /* properties_destroyed */
1562 0, /* todo_flags_start */
1563 0, /* todo_flags_finish */
1566 class pass_dse : public gimple_opt_pass
1568 public:
1569 pass_dse (gcc::context *ctxt)
1570 : gimple_opt_pass (pass_data_dse, ctxt), use_dr_analysis_p (false)
1573 /* opt_pass methods: */
1574 opt_pass * clone () final override { return new pass_dse (m_ctxt); }
1575 void set_pass_param (unsigned n, bool param) final override
1577 gcc_assert (n == 0);
1578 use_dr_analysis_p = param;
1580 bool gate (function *) final override { return flag_tree_dse != 0; }
1581 unsigned int execute (function *) final override;
1583 private:
1584 bool use_dr_analysis_p;
1585 }; // class pass_dse
1587 unsigned int
1588 pass_dse::execute (function *fun)
1590 unsigned todo = 0;
1591 bool released_def = false;
1593 need_eh_cleanup = BITMAP_ALLOC (NULL);
1594 need_ab_cleanup = BITMAP_ALLOC (NULL);
1595 auto_sbitmap live_bytes (param_dse_max_object_size);
1596 if (flag_expensive_optimizations && use_dr_analysis_p)
1597 dse_stmt_to_dr_map = new hash_map<gimple *, data_reference_p>;
1599 renumber_gimple_stmt_uids (fun);
1601 calculate_dominance_info (CDI_DOMINATORS);
1603 /* Dead store elimination is fundamentally a reverse program order walk. */
1604 int *rpo = XNEWVEC (int, n_basic_blocks_for_fn (fun) - NUM_FIXED_BLOCKS);
1605 int n = pre_and_rev_post_order_compute_fn (fun, NULL, rpo, false);
1606 for (int i = n; i != 0; --i)
1608 basic_block bb = BASIC_BLOCK_FOR_FN (fun, rpo[i-1]);
1609 gimple_stmt_iterator gsi;
1611 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi);)
1613 gimple *stmt = gsi_stmt (gsi);
1615 if (gimple_vdef (stmt))
1616 dse_optimize_stmt (fun, &gsi, live_bytes);
1617 else if (def_operand_p
1618 def_p = single_ssa_def_operand (stmt, SSA_OP_DEF))
1620 /* When we remove dead stores make sure to also delete trivially
1621 dead SSA defs. */
1622 if (has_zero_uses (DEF_FROM_PTR (def_p))
1623 && !gimple_has_side_effects (stmt)
1624 && !is_ctrl_altering_stmt (stmt)
1625 && (!stmt_could_throw_p (fun, stmt)
1626 || fun->can_delete_dead_exceptions))
1628 if (dump_file && (dump_flags & TDF_DETAILS))
1630 fprintf (dump_file, " Deleted trivially dead stmt: ");
1631 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
1632 fprintf (dump_file, "\n");
1634 if (gsi_remove (&gsi, true) && need_eh_cleanup)
1635 bitmap_set_bit (need_eh_cleanup, bb->index);
1636 release_defs (stmt);
1637 released_def = true;
1640 if (gsi_end_p (gsi))
1641 gsi = gsi_last_bb (bb);
1642 else
1643 gsi_prev (&gsi);
1645 bool removed_phi = false;
1646 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);)
1648 gphi *phi = si.phi ();
1649 if (has_zero_uses (gimple_phi_result (phi)))
1651 if (dump_file && (dump_flags & TDF_DETAILS))
1653 fprintf (dump_file, " Deleted trivially dead PHI: ");
1654 print_gimple_stmt (dump_file, phi, 0, dump_flags);
1655 fprintf (dump_file, "\n");
1657 remove_phi_node (&si, true);
1658 removed_phi = true;
1659 released_def = true;
1661 else
1662 gsi_next (&si);
1664 if (removed_phi && gimple_seq_empty_p (phi_nodes (bb)))
1665 todo |= TODO_cleanup_cfg;
1667 free (rpo);
1669 /* Removal of stores may make some EH edges dead. Purge such edges from
1670 the CFG as needed. */
1671 if (!bitmap_empty_p (need_eh_cleanup))
1673 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
1674 todo |= TODO_cleanup_cfg;
1676 if (!bitmap_empty_p (need_ab_cleanup))
1678 gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
1679 todo |= TODO_cleanup_cfg;
1682 BITMAP_FREE (need_eh_cleanup);
1683 BITMAP_FREE (need_ab_cleanup);
1685 if (released_def)
1686 free_numbers_of_iterations_estimates (fun);
1688 if (flag_expensive_optimizations && use_dr_analysis_p)
1690 for (auto i = dse_stmt_to_dr_map->begin ();
1691 i != dse_stmt_to_dr_map->end (); ++i)
1692 free_data_ref ((*i).second);
1693 delete dse_stmt_to_dr_map;
1694 dse_stmt_to_dr_map = NULL;
1697 return todo;
1700 } // anon namespace
1702 gimple_opt_pass *
1703 make_pass_dse (gcc::context *ctxt)
1705 return new pass_dse (ctxt);