2017-11-09 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / gcc / gimple-ssa-store-merging.c
blob4bae70dc7ac6fd3bdd6344b9fa9ffa377be4a376
1 /* GIMPLE store merging pass.
2 Copyright (C) 2016-2017 Free Software Foundation, Inc.
3 Contributed by ARM Ltd.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 /* The purpose of this pass is to combine multiple memory stores of
22 constant values, values loaded from memory or bitwise operations
23 on those to consecutive memory locations into fewer wider stores.
24 For example, if we have a sequence peforming four byte stores to
25 consecutive memory locations:
26 [p ] := imm1;
27 [p + 1B] := imm2;
28 [p + 2B] := imm3;
29 [p + 3B] := imm4;
30 we can transform this into a single 4-byte store if the target supports it:
31 [p] := imm1:imm2:imm3:imm4 //concatenated immediates according to endianness.
33 Or:
34 [p ] := [q ];
35 [p + 1B] := [q + 1B];
36 [p + 2B] := [q + 2B];
37 [p + 3B] := [q + 3B];
38 if there is no overlap can be transformed into a single 4-byte
39 load followed by single 4-byte store.
41 Or:
42 [p ] := [q ] ^ imm1;
43 [p + 1B] := [q + 1B] ^ imm2;
44 [p + 2B] := [q + 2B] ^ imm3;
45 [p + 3B] := [q + 3B] ^ imm4;
46 if there is no overlap can be transformed into a single 4-byte
47 load, xored with imm1:imm2:imm3:imm4 and stored using a single 4-byte store.
49 The algorithm is applied to each basic block in three phases:
51 1) Scan through the basic block recording assignments to
52 destinations that can be expressed as a store to memory of a certain size
53 at a certain bit offset from expressions we can handle. For bit-fields
54 we also note the surrounding bit region, bits that could be stored in
55 a read-modify-write operation when storing the bit-field. Record store
56 chains to different bases in a hash_map (m_stores) and make sure to
57 terminate such chains when appropriate (for example when when the stored
58 values get used subsequently).
59 These stores can be a result of structure element initializers, array stores
60 etc. A store_immediate_info object is recorded for every such store.
61 Record as many such assignments to a single base as possible until a
62 statement that interferes with the store sequence is encountered.
63 Each store has up to 2 operands, which can be an immediate constant
64 or a memory load, from which the value to be stored can be computed.
65 At most one of the operands can be a constant. The operands are recorded
66 in store_operand_info struct.
68 2) Analyze the chain of stores recorded in phase 1) (i.e. the vector of
69 store_immediate_info objects) and coalesce contiguous stores into
70 merged_store_group objects. For bit-fields stores, we don't need to
71 require the stores to be contiguous, just their surrounding bit regions
72 have to be contiguous. If the expression being stored is different
73 between adjacent stores, such as one store storing a constant and
74 following storing a value loaded from memory, or if the loaded memory
75 objects are not adjacent, a new merged_store_group is created as well.
77 For example, given the stores:
78 [p ] := 0;
79 [p + 1B] := 1;
80 [p + 3B] := 0;
81 [p + 4B] := 1;
82 [p + 5B] := 0;
83 [p + 6B] := 0;
84 This phase would produce two merged_store_group objects, one recording the
85 two bytes stored in the memory region [p : p + 1] and another
86 recording the four bytes stored in the memory region [p + 3 : p + 6].
88 3) The merged_store_group objects produced in phase 2) are processed
89 to generate the sequence of wider stores that set the contiguous memory
90 regions to the sequence of bytes that correspond to it. This may emit
91 multiple stores per store group to handle contiguous stores that are not
92 of a size that is a power of 2. For example it can try to emit a 40-bit
93 store as a 32-bit store followed by an 8-bit store.
94 We try to emit as wide stores as we can while respecting STRICT_ALIGNMENT or
95 TARGET_SLOW_UNALIGNED_ACCESS rules.
97 Note on endianness and example:
98 Consider 2 contiguous 16-bit stores followed by 2 contiguous 8-bit stores:
99 [p ] := 0x1234;
100 [p + 2B] := 0x5678;
101 [p + 4B] := 0xab;
102 [p + 5B] := 0xcd;
104 The memory layout for little-endian (LE) and big-endian (BE) must be:
105 p |LE|BE|
106 ---------
107 0 |34|12|
108 1 |12|34|
109 2 |78|56|
110 3 |56|78|
111 4 |ab|ab|
112 5 |cd|cd|
114 To merge these into a single 48-bit merged value 'val' in phase 2)
115 on little-endian we insert stores to higher (consecutive) bitpositions
116 into the most significant bits of the merged value.
117 The final merged value would be: 0xcdab56781234
119 For big-endian we insert stores to higher bitpositions into the least
120 significant bits of the merged value.
121 The final merged value would be: 0x12345678abcd
123 Then, in phase 3), we want to emit this 48-bit value as a 32-bit store
124 followed by a 16-bit store. Again, we must consider endianness when
125 breaking down the 48-bit value 'val' computed above.
126 For little endian we emit:
127 [p] (32-bit) := 0x56781234; // val & 0x0000ffffffff;
128 [p + 4B] (16-bit) := 0xcdab; // (val & 0xffff00000000) >> 32;
130 Whereas for big-endian we emit:
131 [p] (32-bit) := 0x12345678; // (val & 0xffffffff0000) >> 16;
132 [p + 4B] (16-bit) := 0xabcd; // val & 0x00000000ffff; */
134 #include "config.h"
135 #include "system.h"
136 #include "coretypes.h"
137 #include "backend.h"
138 #include "tree.h"
139 #include "gimple.h"
140 #include "builtins.h"
141 #include "fold-const.h"
142 #include "tree-pass.h"
143 #include "ssa.h"
144 #include "gimple-pretty-print.h"
145 #include "alias.h"
146 #include "fold-const.h"
147 #include "params.h"
148 #include "print-tree.h"
149 #include "tree-hash-traits.h"
150 #include "gimple-iterator.h"
151 #include "gimplify.h"
152 #include "stor-layout.h"
153 #include "timevar.h"
154 #include "tree-cfg.h"
155 #include "tree-eh.h"
156 #include "target.h"
157 #include "gimplify-me.h"
158 #include "rtl.h"
159 #include "expr.h" /* For get_bit_range. */
160 #include "selftest.h"
162 /* The maximum size (in bits) of the stores this pass should generate. */
163 #define MAX_STORE_BITSIZE (BITS_PER_WORD)
164 #define MAX_STORE_BYTES (MAX_STORE_BITSIZE / BITS_PER_UNIT)
166 /* Limit to bound the number of aliasing checks for loads with the same
167 vuse as the corresponding store. */
168 #define MAX_STORE_ALIAS_CHECKS 64
170 namespace {
172 /* Struct recording one operand for the store, which is either a constant,
173 then VAL represents the constant and all the other fields are zero,
174 or a memory load, then VAL represents the reference, BASE_ADDR is non-NULL
175 and the other fields also reflect the memory load. */
177 struct store_operand_info
179 tree val;
180 tree base_addr;
181 unsigned HOST_WIDE_INT bitsize;
182 unsigned HOST_WIDE_INT bitpos;
183 unsigned HOST_WIDE_INT bitregion_start;
184 unsigned HOST_WIDE_INT bitregion_end;
185 gimple *stmt;
186 bool bit_not_p;
187 store_operand_info ();
190 store_operand_info::store_operand_info ()
191 : val (NULL_TREE), base_addr (NULL_TREE), bitsize (0), bitpos (0),
192 bitregion_start (0), bitregion_end (0), stmt (NULL), bit_not_p (false)
196 /* Struct recording the information about a single store of an immediate
197 to memory. These are created in the first phase and coalesced into
198 merged_store_group objects in the second phase. */
200 struct store_immediate_info
202 unsigned HOST_WIDE_INT bitsize;
203 unsigned HOST_WIDE_INT bitpos;
204 unsigned HOST_WIDE_INT bitregion_start;
205 /* This is one past the last bit of the bit region. */
206 unsigned HOST_WIDE_INT bitregion_end;
207 gimple *stmt;
208 unsigned int order;
209 /* INTEGER_CST for constant stores, MEM_REF for memory copy or
210 BIT_*_EXPR for logical bitwise operation. */
211 enum tree_code rhs_code;
212 /* Operands. For BIT_*_EXPR rhs_code both operands are used, otherwise
213 just the first one. */
214 store_operand_info ops[2];
215 store_immediate_info (unsigned HOST_WIDE_INT, unsigned HOST_WIDE_INT,
216 unsigned HOST_WIDE_INT, unsigned HOST_WIDE_INT,
217 gimple *, unsigned int, enum tree_code,
218 const store_operand_info &,
219 const store_operand_info &);
222 store_immediate_info::store_immediate_info (unsigned HOST_WIDE_INT bs,
223 unsigned HOST_WIDE_INT bp,
224 unsigned HOST_WIDE_INT brs,
225 unsigned HOST_WIDE_INT bre,
226 gimple *st,
227 unsigned int ord,
228 enum tree_code rhscode,
229 const store_operand_info &op0r,
230 const store_operand_info &op1r)
231 : bitsize (bs), bitpos (bp), bitregion_start (brs), bitregion_end (bre),
232 stmt (st), order (ord), rhs_code (rhscode)
233 #if __cplusplus >= 201103L
234 , ops { op0r, op1r }
237 #else
239 ops[0] = op0r;
240 ops[1] = op1r;
242 #endif
244 /* Struct representing a group of stores to contiguous memory locations.
245 These are produced by the second phase (coalescing) and consumed in the
246 third phase that outputs the widened stores. */
248 struct merged_store_group
250 unsigned HOST_WIDE_INT start;
251 unsigned HOST_WIDE_INT width;
252 unsigned HOST_WIDE_INT bitregion_start;
253 unsigned HOST_WIDE_INT bitregion_end;
254 /* The size of the allocated memory for val and mask. */
255 unsigned HOST_WIDE_INT buf_size;
256 unsigned HOST_WIDE_INT align_base;
257 unsigned HOST_WIDE_INT load_align_base[2];
259 unsigned int align;
260 unsigned int load_align[2];
261 unsigned int first_order;
262 unsigned int last_order;
264 auto_vec<store_immediate_info *> stores;
265 /* We record the first and last original statements in the sequence because
266 we'll need their vuse/vdef and replacement position. It's easier to keep
267 track of them separately as 'stores' is reordered by apply_stores. */
268 gimple *last_stmt;
269 gimple *first_stmt;
270 unsigned char *val;
271 unsigned char *mask;
273 merged_store_group (store_immediate_info *);
274 ~merged_store_group ();
275 void merge_into (store_immediate_info *);
276 void merge_overlapping (store_immediate_info *);
277 bool apply_stores ();
278 private:
279 void do_merge (store_immediate_info *);
282 /* Debug helper. Dump LEN elements of byte array PTR to FD in hex. */
284 static void
285 dump_char_array (FILE *fd, unsigned char *ptr, unsigned int len)
287 if (!fd)
288 return;
290 for (unsigned int i = 0; i < len; i++)
291 fprintf (fd, "%x ", ptr[i]);
292 fprintf (fd, "\n");
295 /* Shift left the bytes in PTR of SZ elements by AMNT bits, carrying over the
296 bits between adjacent elements. AMNT should be within
297 [0, BITS_PER_UNIT).
298 Example, AMNT = 2:
299 00011111|11100000 << 2 = 01111111|10000000
300 PTR[1] | PTR[0] PTR[1] | PTR[0]. */
302 static void
303 shift_bytes_in_array (unsigned char *ptr, unsigned int sz, unsigned int amnt)
305 if (amnt == 0)
306 return;
308 unsigned char carry_over = 0U;
309 unsigned char carry_mask = (~0U) << (unsigned char) (BITS_PER_UNIT - amnt);
310 unsigned char clear_mask = (~0U) << amnt;
312 for (unsigned int i = 0; i < sz; i++)
314 unsigned prev_carry_over = carry_over;
315 carry_over = (ptr[i] & carry_mask) >> (BITS_PER_UNIT - amnt);
317 ptr[i] <<= amnt;
318 if (i != 0)
320 ptr[i] &= clear_mask;
321 ptr[i] |= prev_carry_over;
326 /* Like shift_bytes_in_array but for big-endian.
327 Shift right the bytes in PTR of SZ elements by AMNT bits, carrying over the
328 bits between adjacent elements. AMNT should be within
329 [0, BITS_PER_UNIT).
330 Example, AMNT = 2:
331 00011111|11100000 >> 2 = 00000111|11111000
332 PTR[0] | PTR[1] PTR[0] | PTR[1]. */
334 static void
335 shift_bytes_in_array_right (unsigned char *ptr, unsigned int sz,
336 unsigned int amnt)
338 if (amnt == 0)
339 return;
341 unsigned char carry_over = 0U;
342 unsigned char carry_mask = ~(~0U << amnt);
344 for (unsigned int i = 0; i < sz; i++)
346 unsigned prev_carry_over = carry_over;
347 carry_over = ptr[i] & carry_mask;
349 carry_over <<= (unsigned char) BITS_PER_UNIT - amnt;
350 ptr[i] >>= amnt;
351 ptr[i] |= prev_carry_over;
355 /* Clear out LEN bits starting from bit START in the byte array
356 PTR. This clears the bits to the *right* from START.
357 START must be within [0, BITS_PER_UNIT) and counts starting from
358 the least significant bit. */
360 static void
361 clear_bit_region_be (unsigned char *ptr, unsigned int start,
362 unsigned int len)
364 if (len == 0)
365 return;
366 /* Clear len bits to the right of start. */
367 else if (len <= start + 1)
369 unsigned char mask = (~(~0U << len));
370 mask = mask << (start + 1U - len);
371 ptr[0] &= ~mask;
373 else if (start != BITS_PER_UNIT - 1)
375 clear_bit_region_be (ptr, start, (start % BITS_PER_UNIT) + 1);
376 clear_bit_region_be (ptr + 1, BITS_PER_UNIT - 1,
377 len - (start % BITS_PER_UNIT) - 1);
379 else if (start == BITS_PER_UNIT - 1
380 && len > BITS_PER_UNIT)
382 unsigned int nbytes = len / BITS_PER_UNIT;
383 memset (ptr, 0, nbytes);
384 if (len % BITS_PER_UNIT != 0)
385 clear_bit_region_be (ptr + nbytes, BITS_PER_UNIT - 1,
386 len % BITS_PER_UNIT);
388 else
389 gcc_unreachable ();
392 /* In the byte array PTR clear the bit region starting at bit
393 START and is LEN bits wide.
394 For regions spanning multiple bytes do this recursively until we reach
395 zero LEN or a region contained within a single byte. */
397 static void
398 clear_bit_region (unsigned char *ptr, unsigned int start,
399 unsigned int len)
401 /* Degenerate base case. */
402 if (len == 0)
403 return;
404 else if (start >= BITS_PER_UNIT)
405 clear_bit_region (ptr + 1, start - BITS_PER_UNIT, len);
406 /* Second base case. */
407 else if ((start + len) <= BITS_PER_UNIT)
409 unsigned char mask = (~0U) << (unsigned char) (BITS_PER_UNIT - len);
410 mask >>= BITS_PER_UNIT - (start + len);
412 ptr[0] &= ~mask;
414 return;
416 /* Clear most significant bits in a byte and proceed with the next byte. */
417 else if (start != 0)
419 clear_bit_region (ptr, start, BITS_PER_UNIT - start);
420 clear_bit_region (ptr + 1, 0, len - (BITS_PER_UNIT - start));
422 /* Whole bytes need to be cleared. */
423 else if (start == 0 && len > BITS_PER_UNIT)
425 unsigned int nbytes = len / BITS_PER_UNIT;
426 /* We could recurse on each byte but we clear whole bytes, so a simple
427 memset will do. */
428 memset (ptr, '\0', nbytes);
429 /* Clear the remaining sub-byte region if there is one. */
430 if (len % BITS_PER_UNIT != 0)
431 clear_bit_region (ptr + nbytes, 0, len % BITS_PER_UNIT);
433 else
434 gcc_unreachable ();
437 /* Write BITLEN bits of EXPR to the byte array PTR at
438 bit position BITPOS. PTR should contain TOTAL_BYTES elements.
439 Return true if the operation succeeded. */
441 static bool
442 encode_tree_to_bitpos (tree expr, unsigned char *ptr, int bitlen, int bitpos,
443 unsigned int total_bytes)
445 unsigned int first_byte = bitpos / BITS_PER_UNIT;
446 tree tmp_int = expr;
447 bool sub_byte_op_p = ((bitlen % BITS_PER_UNIT)
448 || (bitpos % BITS_PER_UNIT)
449 || !int_mode_for_size (bitlen, 0).exists ());
451 if (!sub_byte_op_p)
452 return native_encode_expr (tmp_int, ptr + first_byte, total_bytes) != 0;
454 /* LITTLE-ENDIAN
455 We are writing a non byte-sized quantity or at a position that is not
456 at a byte boundary.
457 |--------|--------|--------| ptr + first_byte
459 xxx xxxxxxxx xxx< bp>
460 |______EXPR____|
462 First native_encode_expr EXPR into a temporary buffer and shift each
463 byte in the buffer by 'bp' (carrying the bits over as necessary).
464 |00000000|00xxxxxx|xxxxxxxx| << bp = |000xxxxx|xxxxxxxx|xxx00000|
465 <------bitlen---->< bp>
466 Then we clear the destination bits:
467 |---00000|00000000|000-----| ptr + first_byte
468 <-------bitlen--->< bp>
470 Finally we ORR the bytes of the shifted EXPR into the cleared region:
471 |---xxxxx||xxxxxxxx||xxx-----| ptr + first_byte.
473 BIG-ENDIAN
474 We are writing a non byte-sized quantity or at a position that is not
475 at a byte boundary.
476 ptr + first_byte |--------|--------|--------|
478 <bp >xxx xxxxxxxx xxx
479 |_____EXPR_____|
481 First native_encode_expr EXPR into a temporary buffer and shift each
482 byte in the buffer to the right by (carrying the bits over as necessary).
483 We shift by as much as needed to align the most significant bit of EXPR
484 with bitpos:
485 |00xxxxxx|xxxxxxxx| >> 3 = |00000xxx|xxxxxxxx|xxxxx000|
486 <---bitlen----> <bp ><-----bitlen----->
487 Then we clear the destination bits:
488 ptr + first_byte |-----000||00000000||00000---|
489 <bp ><-------bitlen----->
491 Finally we ORR the bytes of the shifted EXPR into the cleared region:
492 ptr + first_byte |---xxxxx||xxxxxxxx||xxx-----|.
493 The awkwardness comes from the fact that bitpos is counted from the
494 most significant bit of a byte. */
496 /* We must be dealing with fixed-size data at this point, since the
497 total size is also fixed. */
498 fixed_size_mode mode = as_a <fixed_size_mode> (TYPE_MODE (TREE_TYPE (expr)));
499 /* Allocate an extra byte so that we have space to shift into. */
500 unsigned int byte_size = GET_MODE_SIZE (mode) + 1;
501 unsigned char *tmpbuf = XALLOCAVEC (unsigned char, byte_size);
502 memset (tmpbuf, '\0', byte_size);
503 /* The store detection code should only have allowed constants that are
504 accepted by native_encode_expr. */
505 if (native_encode_expr (expr, tmpbuf, byte_size - 1) == 0)
506 gcc_unreachable ();
508 /* The native_encode_expr machinery uses TYPE_MODE to determine how many
509 bytes to write. This means it can write more than
510 ROUND_UP (bitlen, BITS_PER_UNIT) / BITS_PER_UNIT bytes (for example
511 write 8 bytes for a bitlen of 40). Skip the bytes that are not within
512 bitlen and zero out the bits that are not relevant as well (that may
513 contain a sign bit due to sign-extension). */
514 unsigned int padding
515 = byte_size - ROUND_UP (bitlen, BITS_PER_UNIT) / BITS_PER_UNIT - 1;
516 /* On big-endian the padding is at the 'front' so just skip the initial
517 bytes. */
518 if (BYTES_BIG_ENDIAN)
519 tmpbuf += padding;
521 byte_size -= padding;
523 if (bitlen % BITS_PER_UNIT != 0)
525 if (BYTES_BIG_ENDIAN)
526 clear_bit_region_be (tmpbuf, BITS_PER_UNIT - 1,
527 BITS_PER_UNIT - (bitlen % BITS_PER_UNIT));
528 else
529 clear_bit_region (tmpbuf, bitlen,
530 byte_size * BITS_PER_UNIT - bitlen);
532 /* Left shifting relies on the last byte being clear if bitlen is
533 a multiple of BITS_PER_UNIT, which might not be clear if
534 there are padding bytes. */
535 else if (!BYTES_BIG_ENDIAN)
536 tmpbuf[byte_size - 1] = '\0';
538 /* Clear the bit region in PTR where the bits from TMPBUF will be
539 inserted into. */
540 if (BYTES_BIG_ENDIAN)
541 clear_bit_region_be (ptr + first_byte,
542 BITS_PER_UNIT - 1 - (bitpos % BITS_PER_UNIT), bitlen);
543 else
544 clear_bit_region (ptr + first_byte, bitpos % BITS_PER_UNIT, bitlen);
546 int shift_amnt;
547 int bitlen_mod = bitlen % BITS_PER_UNIT;
548 int bitpos_mod = bitpos % BITS_PER_UNIT;
550 bool skip_byte = false;
551 if (BYTES_BIG_ENDIAN)
553 /* BITPOS and BITLEN are exactly aligned and no shifting
554 is necessary. */
555 if (bitpos_mod + bitlen_mod == BITS_PER_UNIT
556 || (bitpos_mod == 0 && bitlen_mod == 0))
557 shift_amnt = 0;
558 /* |. . . . . . . .|
559 <bp > <blen >.
560 We always shift right for BYTES_BIG_ENDIAN so shift the beginning
561 of the value until it aligns with 'bp' in the next byte over. */
562 else if (bitpos_mod + bitlen_mod < BITS_PER_UNIT)
564 shift_amnt = bitlen_mod + bitpos_mod;
565 skip_byte = bitlen_mod != 0;
567 /* |. . . . . . . .|
568 <----bp--->
569 <---blen---->.
570 Shift the value right within the same byte so it aligns with 'bp'. */
571 else
572 shift_amnt = bitlen_mod + bitpos_mod - BITS_PER_UNIT;
574 else
575 shift_amnt = bitpos % BITS_PER_UNIT;
577 /* Create the shifted version of EXPR. */
578 if (!BYTES_BIG_ENDIAN)
580 shift_bytes_in_array (tmpbuf, byte_size, shift_amnt);
581 if (shift_amnt == 0)
582 byte_size--;
584 else
586 gcc_assert (BYTES_BIG_ENDIAN);
587 shift_bytes_in_array_right (tmpbuf, byte_size, shift_amnt);
588 /* If shifting right forced us to move into the next byte skip the now
589 empty byte. */
590 if (skip_byte)
592 tmpbuf++;
593 byte_size--;
597 /* Insert the bits from TMPBUF. */
598 for (unsigned int i = 0; i < byte_size; i++)
599 ptr[first_byte + i] |= tmpbuf[i];
601 return true;
604 /* Sorting function for store_immediate_info objects.
605 Sorts them by bitposition. */
607 static int
608 sort_by_bitpos (const void *x, const void *y)
610 store_immediate_info *const *tmp = (store_immediate_info * const *) x;
611 store_immediate_info *const *tmp2 = (store_immediate_info * const *) y;
613 if ((*tmp)->bitpos < (*tmp2)->bitpos)
614 return -1;
615 else if ((*tmp)->bitpos > (*tmp2)->bitpos)
616 return 1;
617 else
618 /* If they are the same let's use the order which is guaranteed to
619 be different. */
620 return (*tmp)->order - (*tmp2)->order;
623 /* Sorting function for store_immediate_info objects.
624 Sorts them by the order field. */
626 static int
627 sort_by_order (const void *x, const void *y)
629 store_immediate_info *const *tmp = (store_immediate_info * const *) x;
630 store_immediate_info *const *tmp2 = (store_immediate_info * const *) y;
632 if ((*tmp)->order < (*tmp2)->order)
633 return -1;
634 else if ((*tmp)->order > (*tmp2)->order)
635 return 1;
637 gcc_unreachable ();
640 /* Initialize a merged_store_group object from a store_immediate_info
641 object. */
643 merged_store_group::merged_store_group (store_immediate_info *info)
645 start = info->bitpos;
646 width = info->bitsize;
647 bitregion_start = info->bitregion_start;
648 bitregion_end = info->bitregion_end;
649 /* VAL has memory allocated for it in apply_stores once the group
650 width has been finalized. */
651 val = NULL;
652 mask = NULL;
653 unsigned HOST_WIDE_INT align_bitpos = 0;
654 get_object_alignment_1 (gimple_assign_lhs (info->stmt),
655 &align, &align_bitpos);
656 align_base = start - align_bitpos;
657 for (int i = 0; i < 2; ++i)
659 store_operand_info &op = info->ops[i];
660 if (op.base_addr == NULL_TREE)
662 load_align[i] = 0;
663 load_align_base[i] = 0;
665 else
667 get_object_alignment_1 (op.val, &load_align[i], &align_bitpos);
668 load_align_base[i] = op.bitpos - align_bitpos;
671 stores.create (1);
672 stores.safe_push (info);
673 last_stmt = info->stmt;
674 last_order = info->order;
675 first_stmt = last_stmt;
676 first_order = last_order;
677 buf_size = 0;
680 merged_store_group::~merged_store_group ()
682 if (val)
683 XDELETEVEC (val);
686 /* Helper method for merge_into and merge_overlapping to do
687 the common part. */
688 void
689 merged_store_group::do_merge (store_immediate_info *info)
691 bitregion_start = MIN (bitregion_start, info->bitregion_start);
692 bitregion_end = MAX (bitregion_end, info->bitregion_end);
694 unsigned int this_align;
695 unsigned HOST_WIDE_INT align_bitpos = 0;
696 get_object_alignment_1 (gimple_assign_lhs (info->stmt),
697 &this_align, &align_bitpos);
698 if (this_align > align)
700 align = this_align;
701 align_base = info->bitpos - align_bitpos;
703 for (int i = 0; i < 2; ++i)
705 store_operand_info &op = info->ops[i];
706 if (!op.base_addr)
707 continue;
709 get_object_alignment_1 (op.val, &this_align, &align_bitpos);
710 if (this_align > load_align[i])
712 load_align[i] = this_align;
713 load_align_base[i] = op.bitpos - align_bitpos;
717 gimple *stmt = info->stmt;
718 stores.safe_push (info);
719 if (info->order > last_order)
721 last_order = info->order;
722 last_stmt = stmt;
724 else if (info->order < first_order)
726 first_order = info->order;
727 first_stmt = stmt;
731 /* Merge a store recorded by INFO into this merged store.
732 The store is not overlapping with the existing recorded
733 stores. */
735 void
736 merged_store_group::merge_into (store_immediate_info *info)
738 unsigned HOST_WIDE_INT wid = info->bitsize;
739 /* Make sure we're inserting in the position we think we're inserting. */
740 gcc_assert (info->bitpos >= start + width
741 && info->bitregion_start <= bitregion_end);
743 width += wid;
744 do_merge (info);
747 /* Merge a store described by INFO into this merged store.
748 INFO overlaps in some way with the current store (i.e. it's not contiguous
749 which is handled by merged_store_group::merge_into). */
751 void
752 merged_store_group::merge_overlapping (store_immediate_info *info)
754 /* If the store extends the size of the group, extend the width. */
755 if (info->bitpos + info->bitsize > start + width)
756 width += info->bitpos + info->bitsize - (start + width);
758 do_merge (info);
761 /* Go through all the recorded stores in this group in program order and
762 apply their values to the VAL byte array to create the final merged
763 value. Return true if the operation succeeded. */
765 bool
766 merged_store_group::apply_stores ()
768 /* Make sure we have more than one store in the group, otherwise we cannot
769 merge anything. */
770 if (bitregion_start % BITS_PER_UNIT != 0
771 || bitregion_end % BITS_PER_UNIT != 0
772 || stores.length () == 1)
773 return false;
775 stores.qsort (sort_by_order);
776 store_immediate_info *info;
777 unsigned int i;
778 /* Create a buffer of a size that is 2 times the number of bytes we're
779 storing. That way native_encode_expr can write power-of-2-sized
780 chunks without overrunning. */
781 buf_size = 2 * ((bitregion_end - bitregion_start) / BITS_PER_UNIT);
782 val = XNEWVEC (unsigned char, 2 * buf_size);
783 mask = val + buf_size;
784 memset (val, 0, buf_size);
785 memset (mask, ~0U, buf_size);
787 FOR_EACH_VEC_ELT (stores, i, info)
789 unsigned int pos_in_buffer = info->bitpos - bitregion_start;
790 tree cst = NULL_TREE;
791 if (info->ops[0].val && info->ops[0].base_addr == NULL_TREE)
792 cst = info->ops[0].val;
793 else if (info->ops[1].val && info->ops[1].base_addr == NULL_TREE)
794 cst = info->ops[1].val;
795 bool ret = true;
796 if (cst)
797 ret = encode_tree_to_bitpos (cst, val, info->bitsize,
798 pos_in_buffer, buf_size);
799 if (cst && dump_file && (dump_flags & TDF_DETAILS))
801 if (ret)
803 fprintf (dump_file, "After writing ");
804 print_generic_expr (dump_file, cst, 0);
805 fprintf (dump_file, " of size " HOST_WIDE_INT_PRINT_DEC
806 " at position %d the merged region contains:\n",
807 info->bitsize, pos_in_buffer);
808 dump_char_array (dump_file, val, buf_size);
810 else
811 fprintf (dump_file, "Failed to merge stores\n");
813 if (!ret)
814 return false;
815 unsigned char *m = mask + (pos_in_buffer / BITS_PER_UNIT);
816 if (BYTES_BIG_ENDIAN)
817 clear_bit_region_be (m, (BITS_PER_UNIT - 1
818 - (pos_in_buffer % BITS_PER_UNIT)),
819 info->bitsize);
820 else
821 clear_bit_region (m, pos_in_buffer % BITS_PER_UNIT, info->bitsize);
823 return true;
826 /* Structure describing the store chain. */
828 struct imm_store_chain_info
830 /* Doubly-linked list that imposes an order on chain processing.
831 PNXP (prev's next pointer) points to the head of a list, or to
832 the next field in the previous chain in the list.
833 See pass_store_merging::m_stores_head for more rationale. */
834 imm_store_chain_info *next, **pnxp;
835 tree base_addr;
836 auto_vec<store_immediate_info *> m_store_info;
837 auto_vec<merged_store_group *> m_merged_store_groups;
839 imm_store_chain_info (imm_store_chain_info *&inspt, tree b_a)
840 : next (inspt), pnxp (&inspt), base_addr (b_a)
842 inspt = this;
843 if (next)
845 gcc_checking_assert (pnxp == next->pnxp);
846 next->pnxp = &next;
849 ~imm_store_chain_info ()
851 *pnxp = next;
852 if (next)
854 gcc_checking_assert (&next == next->pnxp);
855 next->pnxp = pnxp;
858 bool terminate_and_process_chain ();
859 bool coalesce_immediate_stores ();
860 bool output_merged_store (merged_store_group *);
861 bool output_merged_stores ();
864 const pass_data pass_data_tree_store_merging = {
865 GIMPLE_PASS, /* type */
866 "store-merging", /* name */
867 OPTGROUP_NONE, /* optinfo_flags */
868 TV_GIMPLE_STORE_MERGING, /* tv_id */
869 PROP_ssa, /* properties_required */
870 0, /* properties_provided */
871 0, /* properties_destroyed */
872 0, /* todo_flags_start */
873 TODO_update_ssa, /* todo_flags_finish */
876 class pass_store_merging : public gimple_opt_pass
878 public:
879 pass_store_merging (gcc::context *ctxt)
880 : gimple_opt_pass (pass_data_tree_store_merging, ctxt), m_stores_head ()
884 /* Pass not supported for PDP-endianness, nor for insane hosts
885 or target character sizes where native_{encode,interpret}_expr
886 doesn't work properly. */
887 virtual bool
888 gate (function *)
890 return flag_store_merging
891 && WORDS_BIG_ENDIAN == BYTES_BIG_ENDIAN
892 && CHAR_BIT == 8
893 && BITS_PER_UNIT == 8;
896 virtual unsigned int execute (function *);
898 private:
899 hash_map<tree_operand_hash, struct imm_store_chain_info *> m_stores;
901 /* Form a doubly-linked stack of the elements of m_stores, so that
902 we can iterate over them in a predictable way. Using this order
903 avoids extraneous differences in the compiler output just because
904 of tree pointer variations (e.g. different chains end up in
905 different positions of m_stores, so they are handled in different
906 orders, so they allocate or release SSA names in different
907 orders, and when they get reused, subsequent passes end up
908 getting different SSA names, which may ultimately change
909 decisions when going out of SSA). */
910 imm_store_chain_info *m_stores_head;
912 void process_store (gimple *);
913 bool terminate_and_process_all_chains ();
914 bool terminate_all_aliasing_chains (imm_store_chain_info **, gimple *);
915 bool terminate_and_release_chain (imm_store_chain_info *);
916 }; // class pass_store_merging
918 /* Terminate and process all recorded chains. Return true if any changes
919 were made. */
921 bool
922 pass_store_merging::terminate_and_process_all_chains ()
924 bool ret = false;
925 while (m_stores_head)
926 ret |= terminate_and_release_chain (m_stores_head);
927 gcc_assert (m_stores.elements () == 0);
928 gcc_assert (m_stores_head == NULL);
930 return ret;
933 /* Terminate all chains that are affected by the statement STMT.
934 CHAIN_INFO is the chain we should ignore from the checks if
935 non-NULL. */
937 bool
938 pass_store_merging::terminate_all_aliasing_chains (imm_store_chain_info
939 **chain_info,
940 gimple *stmt)
942 bool ret = false;
944 /* If the statement doesn't touch memory it can't alias. */
945 if (!gimple_vuse (stmt))
946 return false;
948 for (imm_store_chain_info *next = m_stores_head, *cur = next; cur; cur = next)
950 next = cur->next;
952 /* We already checked all the stores in chain_info and terminated the
953 chain if necessary. Skip it here. */
954 if (chain_info && *chain_info == cur)
955 continue;
957 store_immediate_info *info;
958 unsigned int i;
959 FOR_EACH_VEC_ELT (cur->m_store_info, i, info)
961 if (ref_maybe_used_by_stmt_p (stmt, gimple_assign_lhs (info->stmt))
962 || stmt_may_clobber_ref_p (stmt, gimple_assign_lhs (info->stmt)))
964 if (dump_file && (dump_flags & TDF_DETAILS))
966 fprintf (dump_file, "stmt causes chain termination:\n");
967 print_gimple_stmt (dump_file, stmt, 0);
969 terminate_and_release_chain (cur);
970 ret = true;
971 break;
976 return ret;
979 /* Helper function. Terminate the recorded chain storing to base object
980 BASE. Return true if the merging and output was successful. The m_stores
981 entry is removed after the processing in any case. */
983 bool
984 pass_store_merging::terminate_and_release_chain (imm_store_chain_info *chain_info)
986 bool ret = chain_info->terminate_and_process_chain ();
987 m_stores.remove (chain_info->base_addr);
988 delete chain_info;
989 return ret;
992 /* Return true if stmts in between FIRST (inclusive) and LAST (exclusive)
993 may clobber REF. FIRST and LAST must be in the same basic block and
994 have non-NULL vdef. */
996 bool
997 stmts_may_clobber_ref_p (gimple *first, gimple *last, tree ref)
999 ao_ref r;
1000 ao_ref_init (&r, ref);
1001 unsigned int count = 0;
1002 tree vop = gimple_vdef (last);
1003 gimple *stmt;
1005 gcc_checking_assert (gimple_bb (first) == gimple_bb (last));
1008 stmt = SSA_NAME_DEF_STMT (vop);
1009 if (stmt_may_clobber_ref_p_1 (stmt, &r))
1010 return true;
1011 /* Avoid quadratic compile time by bounding the number of checks
1012 we perform. */
1013 if (++count > MAX_STORE_ALIAS_CHECKS)
1014 return true;
1015 vop = gimple_vuse (stmt);
1017 while (stmt != first);
1018 return false;
1021 /* Return true if INFO->ops[IDX] is mergeable with the
1022 corresponding loads already in MERGED_STORE group.
1023 BASE_ADDR is the base address of the whole store group. */
1025 bool
1026 compatible_load_p (merged_store_group *merged_store,
1027 store_immediate_info *info,
1028 tree base_addr, int idx)
1030 store_immediate_info *infof = merged_store->stores[0];
1031 if (!info->ops[idx].base_addr
1032 || info->ops[idx].bit_not_p != infof->ops[idx].bit_not_p
1033 || (info->ops[idx].bitpos - infof->ops[idx].bitpos
1034 != info->bitpos - infof->bitpos)
1035 || !operand_equal_p (info->ops[idx].base_addr,
1036 infof->ops[idx].base_addr, 0))
1037 return false;
1039 store_immediate_info *infol = merged_store->stores.last ();
1040 tree load_vuse = gimple_vuse (info->ops[idx].stmt);
1041 /* In this case all vuses should be the same, e.g.
1042 _1 = s.a; _2 = s.b; _3 = _1 | 1; t.a = _3; _4 = _2 | 2; t.b = _4;
1044 _1 = s.a; _2 = s.b; t.a = _1; t.b = _2;
1045 and we can emit the coalesced load next to any of those loads. */
1046 if (gimple_vuse (infof->ops[idx].stmt) == load_vuse
1047 && gimple_vuse (infol->ops[idx].stmt) == load_vuse)
1048 return true;
1050 /* Otherwise, at least for now require that the load has the same
1051 vuse as the store. See following examples. */
1052 if (gimple_vuse (info->stmt) != load_vuse)
1053 return false;
1055 if (gimple_vuse (infof->stmt) != gimple_vuse (infof->ops[idx].stmt)
1056 || (infof != infol
1057 && gimple_vuse (infol->stmt) != gimple_vuse (infol->ops[idx].stmt)))
1058 return false;
1060 /* If the load is from the same location as the store, already
1061 the construction of the immediate chain info guarantees no intervening
1062 stores, so no further checks are needed. Example:
1063 _1 = s.a; _2 = _1 & -7; s.a = _2; _3 = s.b; _4 = _3 & -7; s.b = _4; */
1064 if (info->ops[idx].bitpos == info->bitpos
1065 && operand_equal_p (info->ops[idx].base_addr, base_addr, 0))
1066 return true;
1068 /* Otherwise, we need to punt if any of the loads can be clobbered by any
1069 of the stores in the group, or any other stores in between those.
1070 Previous calls to compatible_load_p ensured that for all the
1071 merged_store->stores IDX loads, no stmts starting with
1072 merged_store->first_stmt and ending right before merged_store->last_stmt
1073 clobbers those loads. */
1074 gimple *first = merged_store->first_stmt;
1075 gimple *last = merged_store->last_stmt;
1076 unsigned int i;
1077 store_immediate_info *infoc;
1078 /* The stores are sorted by increasing store bitpos, so if info->stmt store
1079 comes before the so far first load, we'll be changing
1080 merged_store->first_stmt. In that case we need to give up if
1081 any of the earlier processed loads clobber with the stmts in the new
1082 range. */
1083 if (info->order < merged_store->first_order)
1085 FOR_EACH_VEC_ELT (merged_store->stores, i, infoc)
1086 if (stmts_may_clobber_ref_p (info->stmt, first, infoc->ops[idx].val))
1087 return false;
1088 first = info->stmt;
1090 /* Similarly, we could change merged_store->last_stmt, so ensure
1091 in that case no stmts in the new range clobber any of the earlier
1092 processed loads. */
1093 else if (info->order > merged_store->last_order)
1095 FOR_EACH_VEC_ELT (merged_store->stores, i, infoc)
1096 if (stmts_may_clobber_ref_p (last, info->stmt, infoc->ops[idx].val))
1097 return false;
1098 last = info->stmt;
1100 /* And finally, we'd be adding a new load to the set, ensure it isn't
1101 clobbered in the new range. */
1102 if (stmts_may_clobber_ref_p (first, last, info->ops[idx].val))
1103 return false;
1105 /* Otherwise, we are looking for:
1106 _1 = s.a; _2 = _1 ^ 15; t.a = _2; _3 = s.b; _4 = _3 ^ 15; t.b = _4;
1108 _1 = s.a; t.a = _1; _2 = s.b; t.b = _2; */
1109 return true;
1112 /* Go through the candidate stores recorded in m_store_info and merge them
1113 into merged_store_group objects recorded into m_merged_store_groups
1114 representing the widened stores. Return true if coalescing was successful
1115 and the number of widened stores is fewer than the original number
1116 of stores. */
1118 bool
1119 imm_store_chain_info::coalesce_immediate_stores ()
1121 /* Anything less can't be processed. */
1122 if (m_store_info.length () < 2)
1123 return false;
1125 if (dump_file && (dump_flags & TDF_DETAILS))
1126 fprintf (dump_file, "Attempting to coalesce %u stores in chain.\n",
1127 m_store_info.length ());
1129 store_immediate_info *info;
1130 unsigned int i;
1132 /* Order the stores by the bitposition they write to. */
1133 m_store_info.qsort (sort_by_bitpos);
1135 info = m_store_info[0];
1136 merged_store_group *merged_store = new merged_store_group (info);
1138 FOR_EACH_VEC_ELT (m_store_info, i, info)
1140 if (dump_file && (dump_flags & TDF_DETAILS))
1142 fprintf (dump_file, "Store %u:\nbitsize:" HOST_WIDE_INT_PRINT_DEC
1143 " bitpos:" HOST_WIDE_INT_PRINT_DEC " val:\n",
1144 i, info->bitsize, info->bitpos);
1145 print_generic_expr (dump_file, gimple_assign_rhs1 (info->stmt));
1146 fprintf (dump_file, "\n------------\n");
1149 if (i == 0)
1150 continue;
1152 /* |---store 1---|
1153 |---store 2---|
1154 Overlapping stores. */
1155 unsigned HOST_WIDE_INT start = info->bitpos;
1156 if (IN_RANGE (start, merged_store->start,
1157 merged_store->start + merged_store->width - 1))
1159 /* Only allow overlapping stores of constants. */
1160 if (info->rhs_code == INTEGER_CST
1161 && merged_store->stores[0]->rhs_code == INTEGER_CST)
1163 merged_store->merge_overlapping (info);
1164 continue;
1167 /* |---store 1---||---store 2---|
1168 This store is consecutive to the previous one.
1169 Merge it into the current store group. There can be gaps in between
1170 the stores, but there can't be gaps in between bitregions. */
1171 else if (info->bitregion_start <= merged_store->bitregion_end
1172 && info->rhs_code == merged_store->stores[0]->rhs_code)
1174 store_immediate_info *infof = merged_store->stores[0];
1176 /* All the rhs_code ops that take 2 operands are commutative,
1177 swap the operands if it could make the operands compatible. */
1178 if (infof->ops[0].base_addr
1179 && infof->ops[1].base_addr
1180 && info->ops[0].base_addr
1181 && info->ops[1].base_addr
1182 && (info->ops[1].bitpos - infof->ops[0].bitpos
1183 == info->bitpos - infof->bitpos)
1184 && operand_equal_p (info->ops[1].base_addr,
1185 infof->ops[0].base_addr, 0))
1186 std::swap (info->ops[0], info->ops[1]);
1187 if ((!infof->ops[0].base_addr
1188 || compatible_load_p (merged_store, info, base_addr, 0))
1189 && (!infof->ops[1].base_addr
1190 || compatible_load_p (merged_store, info, base_addr, 1)))
1192 merged_store->merge_into (info);
1193 continue;
1197 /* |---store 1---| <gap> |---store 2---|.
1198 Gap between stores or the rhs not compatible. Start a new group. */
1200 /* Try to apply all the stores recorded for the group to determine
1201 the bitpattern they write and discard it if that fails.
1202 This will also reject single-store groups. */
1203 if (!merged_store->apply_stores ())
1204 delete merged_store;
1205 else
1206 m_merged_store_groups.safe_push (merged_store);
1208 merged_store = new merged_store_group (info);
1211 /* Record or discard the last store group. */
1212 if (!merged_store->apply_stores ())
1213 delete merged_store;
1214 else
1215 m_merged_store_groups.safe_push (merged_store);
1217 gcc_assert (m_merged_store_groups.length () <= m_store_info.length ());
1218 bool success
1219 = !m_merged_store_groups.is_empty ()
1220 && m_merged_store_groups.length () < m_store_info.length ();
1222 if (success && dump_file)
1223 fprintf (dump_file, "Coalescing successful!\n"
1224 "Merged into %u stores\n",
1225 m_merged_store_groups.length ());
1227 return success;
1230 /* Return the type to use for the merged stores or loads described by STMTS.
1231 This is needed to get the alias sets right. If IS_LOAD, look for rhs,
1232 otherwise lhs. Additionally set *CLIQUEP and *BASEP to MR_DEPENDENCE_*
1233 of the MEM_REFs if any. */
1235 static tree
1236 get_alias_type_for_stmts (vec<gimple *> &stmts, bool is_load,
1237 unsigned short *cliquep, unsigned short *basep)
1239 gimple *stmt;
1240 unsigned int i;
1241 tree type = NULL_TREE;
1242 tree ret = NULL_TREE;
1243 *cliquep = 0;
1244 *basep = 0;
1246 FOR_EACH_VEC_ELT (stmts, i, stmt)
1248 tree ref = is_load ? gimple_assign_rhs1 (stmt)
1249 : gimple_assign_lhs (stmt);
1250 tree type1 = reference_alias_ptr_type (ref);
1251 tree base = get_base_address (ref);
1253 if (i == 0)
1255 if (TREE_CODE (base) == MEM_REF)
1257 *cliquep = MR_DEPENDENCE_CLIQUE (base);
1258 *basep = MR_DEPENDENCE_BASE (base);
1260 ret = type = type1;
1261 continue;
1263 if (!alias_ptr_types_compatible_p (type, type1))
1264 ret = ptr_type_node;
1265 if (TREE_CODE (base) != MEM_REF
1266 || *cliquep != MR_DEPENDENCE_CLIQUE (base)
1267 || *basep != MR_DEPENDENCE_BASE (base))
1269 *cliquep = 0;
1270 *basep = 0;
1273 return ret;
1276 /* Return the location_t information we can find among the statements
1277 in STMTS. */
1279 static location_t
1280 get_location_for_stmts (vec<gimple *> &stmts)
1282 gimple *stmt;
1283 unsigned int i;
1285 FOR_EACH_VEC_ELT (stmts, i, stmt)
1286 if (gimple_has_location (stmt))
1287 return gimple_location (stmt);
1289 return UNKNOWN_LOCATION;
1292 /* Used to decribe a store resulting from splitting a wide store in smaller
1293 regularly-sized stores in split_group. */
1295 struct split_store
1297 unsigned HOST_WIDE_INT bytepos;
1298 unsigned HOST_WIDE_INT size;
1299 unsigned HOST_WIDE_INT align;
1300 auto_vec<store_immediate_info *> orig_stores;
1301 /* True if there is a single orig stmt covering the whole split store. */
1302 bool orig;
1303 split_store (unsigned HOST_WIDE_INT, unsigned HOST_WIDE_INT,
1304 unsigned HOST_WIDE_INT);
1307 /* Simple constructor. */
1309 split_store::split_store (unsigned HOST_WIDE_INT bp,
1310 unsigned HOST_WIDE_INT sz,
1311 unsigned HOST_WIDE_INT al)
1312 : bytepos (bp), size (sz), align (al), orig (false)
1314 orig_stores.create (0);
1317 /* Record all stores in GROUP that write to the region starting at BITPOS and
1318 is of size BITSIZE. Record infos for such statements in STORES if
1319 non-NULL. The stores in GROUP must be sorted by bitposition. Return INFO
1320 if there is exactly one original store in the range. */
1322 static store_immediate_info *
1323 find_constituent_stores (struct merged_store_group *group,
1324 vec<store_immediate_info *> *stores,
1325 unsigned int *first,
1326 unsigned HOST_WIDE_INT bitpos,
1327 unsigned HOST_WIDE_INT bitsize)
1329 store_immediate_info *info, *ret = NULL;
1330 unsigned int i;
1331 bool second = false;
1332 bool update_first = true;
1333 unsigned HOST_WIDE_INT end = bitpos + bitsize;
1334 for (i = *first; group->stores.iterate (i, &info); ++i)
1336 unsigned HOST_WIDE_INT stmt_start = info->bitpos;
1337 unsigned HOST_WIDE_INT stmt_end = stmt_start + info->bitsize;
1338 if (stmt_end <= bitpos)
1340 /* BITPOS passed to this function never decreases from within the
1341 same split_group call, so optimize and don't scan info records
1342 which are known to end before or at BITPOS next time.
1343 Only do it if all stores before this one also pass this. */
1344 if (update_first)
1345 *first = i + 1;
1346 continue;
1348 else
1349 update_first = false;
1351 /* The stores in GROUP are ordered by bitposition so if we're past
1352 the region for this group return early. */
1353 if (stmt_start >= end)
1354 return ret;
1356 if (stores)
1358 stores->safe_push (info);
1359 if (ret)
1361 ret = NULL;
1362 second = true;
1365 else if (ret)
1366 return NULL;
1367 if (!second)
1368 ret = info;
1370 return ret;
1373 /* Return how many SSA_NAMEs used to compute value to store in the INFO
1374 store have multiple uses. If any SSA_NAME has multiple uses, also
1375 count statements needed to compute it. */
1377 static unsigned
1378 count_multiple_uses (store_immediate_info *info)
1380 gimple *stmt = info->stmt;
1381 unsigned ret = 0;
1382 switch (info->rhs_code)
1384 case INTEGER_CST:
1385 return 0;
1386 case BIT_AND_EXPR:
1387 case BIT_IOR_EXPR:
1388 case BIT_XOR_EXPR:
1389 if (!has_single_use (gimple_assign_rhs1 (stmt)))
1391 ret += 1 + info->ops[0].bit_not_p;
1392 if (info->ops[1].base_addr)
1393 ret += 1 + info->ops[1].bit_not_p;
1394 return ret + 1;
1396 stmt = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
1397 /* stmt is now the BIT_*_EXPR. */
1398 if (!has_single_use (gimple_assign_rhs1 (stmt)))
1399 ret += 1 + info->ops[0].bit_not_p;
1400 else if (info->ops[0].bit_not_p)
1402 gimple *stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
1403 if (!has_single_use (gimple_assign_rhs1 (stmt2)))
1404 ++ret;
1406 if (info->ops[1].base_addr == NULL_TREE)
1407 return ret;
1408 if (!has_single_use (gimple_assign_rhs2 (stmt)))
1409 ret += 1 + info->ops[1].bit_not_p;
1410 else if (info->ops[1].bit_not_p)
1412 gimple *stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs2 (stmt));
1413 if (!has_single_use (gimple_assign_rhs1 (stmt2)))
1414 ++ret;
1416 return ret;
1417 case MEM_REF:
1418 if (!has_single_use (gimple_assign_rhs1 (stmt)))
1419 return 1 + info->ops[0].bit_not_p;
1420 else if (info->ops[0].bit_not_p)
1422 stmt = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
1423 if (!has_single_use (gimple_assign_rhs1 (stmt)))
1424 return 1;
1426 return 0;
1427 default:
1428 gcc_unreachable ();
1432 /* Split a merged store described by GROUP by populating the SPLIT_STORES
1433 vector (if non-NULL) with split_store structs describing the byte offset
1434 (from the base), the bit size and alignment of each store as well as the
1435 original statements involved in each such split group.
1436 This is to separate the splitting strategy from the statement
1437 building/emission/linking done in output_merged_store.
1438 Return number of new stores.
1439 If ALLOW_UNALIGNED_STORE is false, then all stores must be aligned.
1440 If ALLOW_UNALIGNED_LOAD is false, then all loads must be aligned.
1441 If SPLIT_STORES is NULL, it is just a dry run to count number of
1442 new stores. */
1444 static unsigned int
1445 split_group (merged_store_group *group, bool allow_unaligned_store,
1446 bool allow_unaligned_load,
1447 vec<struct split_store *> *split_stores,
1448 unsigned *total_orig,
1449 unsigned *total_new)
1451 unsigned HOST_WIDE_INT pos = group->bitregion_start;
1452 unsigned HOST_WIDE_INT size = group->bitregion_end - pos;
1453 unsigned HOST_WIDE_INT bytepos = pos / BITS_PER_UNIT;
1454 unsigned HOST_WIDE_INT group_align = group->align;
1455 unsigned HOST_WIDE_INT align_base = group->align_base;
1456 unsigned HOST_WIDE_INT group_load_align = group_align;
1457 bool any_orig = false;
1459 gcc_assert ((size % BITS_PER_UNIT == 0) && (pos % BITS_PER_UNIT == 0));
1461 unsigned int ret = 0, first = 0;
1462 unsigned HOST_WIDE_INT try_pos = bytepos;
1463 group->stores.qsort (sort_by_bitpos);
1465 if (total_orig)
1467 unsigned int i;
1468 store_immediate_info *info = group->stores[0];
1470 total_new[0] = 0;
1471 total_orig[0] = 1; /* The orig store. */
1472 info = group->stores[0];
1473 if (info->ops[0].base_addr)
1474 total_orig[0] += 1 + info->ops[0].bit_not_p;
1475 if (info->ops[1].base_addr)
1476 total_orig[0] += 1 + info->ops[1].bit_not_p;
1477 switch (info->rhs_code)
1479 case BIT_AND_EXPR:
1480 case BIT_IOR_EXPR:
1481 case BIT_XOR_EXPR:
1482 total_orig[0]++; /* The orig BIT_*_EXPR stmt. */
1483 break;
1484 default:
1485 break;
1487 total_orig[0] *= group->stores.length ();
1489 FOR_EACH_VEC_ELT (group->stores, i, info)
1490 total_new[0] += count_multiple_uses (info);
1493 if (!allow_unaligned_load)
1494 for (int i = 0; i < 2; ++i)
1495 if (group->load_align[i])
1496 group_load_align = MIN (group_load_align, group->load_align[i]);
1498 while (size > 0)
1500 if ((allow_unaligned_store || group_align <= BITS_PER_UNIT)
1501 && group->mask[try_pos - bytepos] == (unsigned char) ~0U)
1503 /* Skip padding bytes. */
1504 ++try_pos;
1505 size -= BITS_PER_UNIT;
1506 continue;
1509 unsigned HOST_WIDE_INT try_bitpos = try_pos * BITS_PER_UNIT;
1510 unsigned int try_size = MAX_STORE_BITSIZE, nonmasked;
1511 unsigned HOST_WIDE_INT align_bitpos
1512 = (try_bitpos - align_base) & (group_align - 1);
1513 unsigned HOST_WIDE_INT align = group_align;
1514 if (align_bitpos)
1515 align = least_bit_hwi (align_bitpos);
1516 if (!allow_unaligned_store)
1517 try_size = MIN (try_size, align);
1518 if (!allow_unaligned_load)
1520 /* If we can't do or don't want to do unaligned stores
1521 as well as loads, we need to take the loads into account
1522 as well. */
1523 unsigned HOST_WIDE_INT load_align = group_load_align;
1524 align_bitpos = (try_bitpos - align_base) & (load_align - 1);
1525 if (align_bitpos)
1526 load_align = least_bit_hwi (align_bitpos);
1527 for (int i = 0; i < 2; ++i)
1528 if (group->load_align[i])
1530 align_bitpos = try_bitpos - group->stores[0]->bitpos;
1531 align_bitpos += group->stores[0]->ops[i].bitpos;
1532 align_bitpos -= group->load_align_base[i];
1533 align_bitpos &= (group_load_align - 1);
1534 if (align_bitpos)
1536 unsigned HOST_WIDE_INT a = least_bit_hwi (align_bitpos);
1537 load_align = MIN (load_align, a);
1540 try_size = MIN (try_size, load_align);
1542 store_immediate_info *info
1543 = find_constituent_stores (group, NULL, &first, try_bitpos, try_size);
1544 if (info)
1546 /* If there is just one original statement for the range, see if
1547 we can just reuse the original store which could be even larger
1548 than try_size. */
1549 unsigned HOST_WIDE_INT stmt_end
1550 = ROUND_UP (info->bitpos + info->bitsize, BITS_PER_UNIT);
1551 info = find_constituent_stores (group, NULL, &first, try_bitpos,
1552 stmt_end - try_bitpos);
1553 if (info && info->bitpos >= try_bitpos)
1555 try_size = stmt_end - try_bitpos;
1556 goto found;
1560 /* Approximate store bitsize for the case when there are no padding
1561 bits. */
1562 while (try_size > size)
1563 try_size /= 2;
1564 /* Now look for whole padding bytes at the end of that bitsize. */
1565 for (nonmasked = try_size / BITS_PER_UNIT; nonmasked > 0; --nonmasked)
1566 if (group->mask[try_pos - bytepos + nonmasked - 1]
1567 != (unsigned char) ~0U)
1568 break;
1569 if (nonmasked == 0)
1571 /* If entire try_size range is padding, skip it. */
1572 try_pos += try_size / BITS_PER_UNIT;
1573 size -= try_size;
1574 continue;
1576 /* Otherwise try to decrease try_size if second half, last 3 quarters
1577 etc. are padding. */
1578 nonmasked *= BITS_PER_UNIT;
1579 while (nonmasked <= try_size / 2)
1580 try_size /= 2;
1581 if (!allow_unaligned_store && group_align > BITS_PER_UNIT)
1583 /* Now look for whole padding bytes at the start of that bitsize. */
1584 unsigned int try_bytesize = try_size / BITS_PER_UNIT, masked;
1585 for (masked = 0; masked < try_bytesize; ++masked)
1586 if (group->mask[try_pos - bytepos + masked] != (unsigned char) ~0U)
1587 break;
1588 masked *= BITS_PER_UNIT;
1589 gcc_assert (masked < try_size);
1590 if (masked >= try_size / 2)
1592 while (masked >= try_size / 2)
1594 try_size /= 2;
1595 try_pos += try_size / BITS_PER_UNIT;
1596 size -= try_size;
1597 masked -= try_size;
1599 /* Need to recompute the alignment, so just retry at the new
1600 position. */
1601 continue;
1605 found:
1606 ++ret;
1608 if (split_stores)
1610 struct split_store *store
1611 = new split_store (try_pos, try_size, align);
1612 info = find_constituent_stores (group, &store->orig_stores,
1613 &first, try_bitpos, try_size);
1614 if (info
1615 && info->bitpos >= try_bitpos
1616 && info->bitpos + info->bitsize <= try_bitpos + try_size)
1618 store->orig = true;
1619 any_orig = true;
1621 split_stores->safe_push (store);
1624 try_pos += try_size / BITS_PER_UNIT;
1625 size -= try_size;
1628 if (total_orig)
1630 /* If we are reusing some original stores and any of the
1631 original SSA_NAMEs had multiple uses, we need to subtract
1632 those now before we add the new ones. */
1633 if (total_new[0] && any_orig)
1635 unsigned int i;
1636 struct split_store *store;
1637 FOR_EACH_VEC_ELT (*split_stores, i, store)
1638 if (store->orig)
1639 total_new[0] -= count_multiple_uses (store->orig_stores[0]);
1641 total_new[0] += ret; /* The new store. */
1642 store_immediate_info *info = group->stores[0];
1643 if (info->ops[0].base_addr)
1644 total_new[0] += ret * (1 + info->ops[0].bit_not_p);
1645 if (info->ops[1].base_addr)
1646 total_new[0] += ret * (1 + info->ops[1].bit_not_p);
1647 switch (info->rhs_code)
1649 case BIT_AND_EXPR:
1650 case BIT_IOR_EXPR:
1651 case BIT_XOR_EXPR:
1652 total_new[0] += ret; /* The new BIT_*_EXPR stmt. */
1653 break;
1654 default:
1655 break;
1659 return ret;
1662 /* Given a merged store group GROUP output the widened version of it.
1663 The store chain is against the base object BASE.
1664 Try store sizes of at most MAX_STORE_BITSIZE bits wide and don't output
1665 unaligned stores for STRICT_ALIGNMENT targets or if it's too expensive.
1666 Make sure that the number of statements output is less than the number of
1667 original statements. If a better sequence is possible emit it and
1668 return true. */
1670 bool
1671 imm_store_chain_info::output_merged_store (merged_store_group *group)
1673 unsigned HOST_WIDE_INT start_byte_pos
1674 = group->bitregion_start / BITS_PER_UNIT;
1676 unsigned int orig_num_stmts = group->stores.length ();
1677 if (orig_num_stmts < 2)
1678 return false;
1680 auto_vec<struct split_store *, 32> split_stores;
1681 split_stores.create (0);
1682 bool allow_unaligned_store
1683 = !STRICT_ALIGNMENT && PARAM_VALUE (PARAM_STORE_MERGING_ALLOW_UNALIGNED);
1684 bool allow_unaligned_load = allow_unaligned_store;
1685 if (allow_unaligned_store)
1687 /* If unaligned stores are allowed, see how many stores we'd emit
1688 for unaligned and how many stores we'd emit for aligned stores.
1689 Only use unaligned stores if it allows fewer stores than aligned. */
1690 unsigned aligned_cnt
1691 = split_group (group, false, allow_unaligned_load, NULL, NULL, NULL);
1692 unsigned unaligned_cnt
1693 = split_group (group, true, allow_unaligned_load, NULL, NULL, NULL);
1694 if (aligned_cnt <= unaligned_cnt)
1695 allow_unaligned_store = false;
1697 unsigned total_orig, total_new;
1698 split_group (group, allow_unaligned_store, allow_unaligned_load,
1699 &split_stores, &total_orig, &total_new);
1701 if (split_stores.length () >= orig_num_stmts)
1703 /* We didn't manage to reduce the number of statements. Bail out. */
1704 if (dump_file && (dump_flags & TDF_DETAILS))
1705 fprintf (dump_file, "Exceeded original number of stmts (%u)."
1706 " Not profitable to emit new sequence.\n",
1707 orig_num_stmts);
1708 return false;
1710 if (total_orig <= total_new)
1712 /* If number of estimated new statements is above estimated original
1713 statements, bail out too. */
1714 if (dump_file && (dump_flags & TDF_DETAILS))
1715 fprintf (dump_file, "Estimated number of original stmts (%u)"
1716 " not larger than estimated number of new"
1717 " stmts (%u).\n",
1718 total_orig, total_new);
1721 gimple_stmt_iterator last_gsi = gsi_for_stmt (group->last_stmt);
1722 gimple_seq seq = NULL;
1723 tree last_vdef, new_vuse;
1724 last_vdef = gimple_vdef (group->last_stmt);
1725 new_vuse = gimple_vuse (group->last_stmt);
1727 gimple *stmt = NULL;
1728 split_store *split_store;
1729 unsigned int i;
1730 auto_vec<gimple *, 32> orig_stmts;
1731 tree addr = force_gimple_operand_1 (unshare_expr (base_addr), &seq,
1732 is_gimple_mem_ref_addr, NULL_TREE);
1734 tree load_addr[2] = { NULL_TREE, NULL_TREE };
1735 gimple_seq load_seq[2] = { NULL, NULL };
1736 gimple_stmt_iterator load_gsi[2] = { gsi_none (), gsi_none () };
1737 for (int j = 0; j < 2; ++j)
1739 store_operand_info &op = group->stores[0]->ops[j];
1740 if (op.base_addr == NULL_TREE)
1741 continue;
1743 store_immediate_info *infol = group->stores.last ();
1744 if (gimple_vuse (op.stmt) == gimple_vuse (infol->ops[j].stmt))
1746 load_gsi[j] = gsi_for_stmt (op.stmt);
1747 load_addr[j]
1748 = force_gimple_operand_1 (unshare_expr (op.base_addr),
1749 &load_seq[j], is_gimple_mem_ref_addr,
1750 NULL_TREE);
1752 else if (operand_equal_p (base_addr, op.base_addr, 0))
1753 load_addr[j] = addr;
1754 else
1756 gimple_seq this_seq;
1757 load_addr[j]
1758 = force_gimple_operand_1 (unshare_expr (op.base_addr),
1759 &this_seq, is_gimple_mem_ref_addr,
1760 NULL_TREE);
1761 gimple_seq_add_seq_without_update (&seq, this_seq);
1765 FOR_EACH_VEC_ELT (split_stores, i, split_store)
1767 unsigned HOST_WIDE_INT try_size = split_store->size;
1768 unsigned HOST_WIDE_INT try_pos = split_store->bytepos;
1769 unsigned HOST_WIDE_INT align = split_store->align;
1770 tree dest, src;
1771 location_t loc;
1772 if (split_store->orig)
1774 /* If there is just a single constituent store which covers
1775 the whole area, just reuse the lhs and rhs. */
1776 gimple *orig_stmt = split_store->orig_stores[0]->stmt;
1777 dest = gimple_assign_lhs (orig_stmt);
1778 src = gimple_assign_rhs1 (orig_stmt);
1779 loc = gimple_location (orig_stmt);
1781 else
1783 store_immediate_info *info;
1784 unsigned short clique, base;
1785 unsigned int k;
1786 FOR_EACH_VEC_ELT (split_store->orig_stores, k, info)
1787 orig_stmts.safe_push (info->stmt);
1788 tree offset_type
1789 = get_alias_type_for_stmts (orig_stmts, false, &clique, &base);
1790 loc = get_location_for_stmts (orig_stmts);
1791 orig_stmts.truncate (0);
1793 tree int_type = build_nonstandard_integer_type (try_size, UNSIGNED);
1794 int_type = build_aligned_type (int_type, align);
1795 dest = fold_build2 (MEM_REF, int_type, addr,
1796 build_int_cst (offset_type, try_pos));
1797 if (TREE_CODE (dest) == MEM_REF)
1799 MR_DEPENDENCE_CLIQUE (dest) = clique;
1800 MR_DEPENDENCE_BASE (dest) = base;
1803 tree mask
1804 = native_interpret_expr (int_type,
1805 group->mask + try_pos - start_byte_pos,
1806 group->buf_size);
1808 tree ops[2];
1809 for (int j = 0;
1810 j < 1 + (split_store->orig_stores[0]->ops[1].val != NULL_TREE);
1811 ++j)
1813 store_operand_info &op = split_store->orig_stores[0]->ops[j];
1814 if (op.base_addr)
1816 FOR_EACH_VEC_ELT (split_store->orig_stores, k, info)
1817 orig_stmts.safe_push (info->ops[j].stmt);
1819 offset_type = get_alias_type_for_stmts (orig_stmts, true,
1820 &clique, &base);
1821 location_t load_loc = get_location_for_stmts (orig_stmts);
1822 orig_stmts.truncate (0);
1824 unsigned HOST_WIDE_INT load_align = group->load_align[j];
1825 unsigned HOST_WIDE_INT align_bitpos
1826 = (try_pos * BITS_PER_UNIT
1827 - split_store->orig_stores[0]->bitpos
1828 + op.bitpos) & (load_align - 1);
1829 if (align_bitpos)
1830 load_align = least_bit_hwi (align_bitpos);
1832 tree load_int_type
1833 = build_nonstandard_integer_type (try_size, UNSIGNED);
1834 load_int_type
1835 = build_aligned_type (load_int_type, load_align);
1837 unsigned HOST_WIDE_INT load_pos
1838 = (try_pos * BITS_PER_UNIT
1839 - split_store->orig_stores[0]->bitpos
1840 + op.bitpos) / BITS_PER_UNIT;
1841 ops[j] = fold_build2 (MEM_REF, load_int_type, load_addr[j],
1842 build_int_cst (offset_type, load_pos));
1843 if (TREE_CODE (ops[j]) == MEM_REF)
1845 MR_DEPENDENCE_CLIQUE (ops[j]) = clique;
1846 MR_DEPENDENCE_BASE (ops[j]) = base;
1848 if (!integer_zerop (mask))
1849 /* The load might load some bits (that will be masked off
1850 later on) uninitialized, avoid -W*uninitialized
1851 warnings in that case. */
1852 TREE_NO_WARNING (ops[j]) = 1;
1854 stmt = gimple_build_assign (make_ssa_name (int_type),
1855 ops[j]);
1856 gimple_set_location (stmt, load_loc);
1857 if (gsi_bb (load_gsi[j]))
1859 gimple_set_vuse (stmt, gimple_vuse (op.stmt));
1860 gimple_seq_add_stmt_without_update (&load_seq[j], stmt);
1862 else
1864 gimple_set_vuse (stmt, new_vuse);
1865 gimple_seq_add_stmt_without_update (&seq, stmt);
1867 ops[j] = gimple_assign_lhs (stmt);
1868 if (op.bit_not_p)
1870 stmt = gimple_build_assign (make_ssa_name (int_type),
1871 BIT_NOT_EXPR, ops[j]);
1872 gimple_set_location (stmt, load_loc);
1873 ops[j] = gimple_assign_lhs (stmt);
1875 if (gsi_bb (load_gsi[j]))
1876 gimple_seq_add_stmt_without_update (&load_seq[j],
1877 stmt);
1878 else
1879 gimple_seq_add_stmt_without_update (&seq, stmt);
1882 else
1883 ops[j] = native_interpret_expr (int_type,
1884 group->val + try_pos
1885 - start_byte_pos,
1886 group->buf_size);
1889 switch (split_store->orig_stores[0]->rhs_code)
1891 case BIT_AND_EXPR:
1892 case BIT_IOR_EXPR:
1893 case BIT_XOR_EXPR:
1894 FOR_EACH_VEC_ELT (split_store->orig_stores, k, info)
1896 tree rhs1 = gimple_assign_rhs1 (info->stmt);
1897 orig_stmts.safe_push (SSA_NAME_DEF_STMT (rhs1));
1899 location_t bit_loc;
1900 bit_loc = get_location_for_stmts (orig_stmts);
1901 orig_stmts.truncate (0);
1903 stmt
1904 = gimple_build_assign (make_ssa_name (int_type),
1905 split_store->orig_stores[0]->rhs_code,
1906 ops[0], ops[1]);
1907 gimple_set_location (stmt, bit_loc);
1908 /* If there is just one load and there is a separate
1909 load_seq[0], emit the bitwise op right after it. */
1910 if (load_addr[1] == NULL_TREE && gsi_bb (load_gsi[0]))
1911 gimple_seq_add_stmt_without_update (&load_seq[0], stmt);
1912 /* Otherwise, if at least one load is in seq, we need to
1913 emit the bitwise op right before the store. If there
1914 are two loads and are emitted somewhere else, it would
1915 be better to emit the bitwise op as early as possible;
1916 we don't track where that would be possible right now
1917 though. */
1918 else
1919 gimple_seq_add_stmt_without_update (&seq, stmt);
1920 src = gimple_assign_lhs (stmt);
1921 break;
1922 default:
1923 src = ops[0];
1924 break;
1927 if (!integer_zerop (mask))
1929 tree tem = make_ssa_name (int_type);
1930 tree load_src = unshare_expr (dest);
1931 /* The load might load some or all bits uninitialized,
1932 avoid -W*uninitialized warnings in that case.
1933 As optimization, it would be nice if all the bits are
1934 provably uninitialized (no stores at all yet or previous
1935 store a CLOBBER) we'd optimize away the load and replace
1936 it e.g. with 0. */
1937 TREE_NO_WARNING (load_src) = 1;
1938 stmt = gimple_build_assign (tem, load_src);
1939 gimple_set_location (stmt, loc);
1940 gimple_set_vuse (stmt, new_vuse);
1941 gimple_seq_add_stmt_without_update (&seq, stmt);
1943 /* FIXME: If there is a single chunk of zero bits in mask,
1944 perhaps use BIT_INSERT_EXPR instead? */
1945 stmt = gimple_build_assign (make_ssa_name (int_type),
1946 BIT_AND_EXPR, tem, mask);
1947 gimple_set_location (stmt, loc);
1948 gimple_seq_add_stmt_without_update (&seq, stmt);
1949 tem = gimple_assign_lhs (stmt);
1951 if (TREE_CODE (src) == INTEGER_CST)
1952 src = wide_int_to_tree (int_type,
1953 wi::bit_and_not (wi::to_wide (src),
1954 wi::to_wide (mask)));
1955 else
1957 tree nmask
1958 = wide_int_to_tree (int_type,
1959 wi::bit_not (wi::to_wide (mask)));
1960 stmt = gimple_build_assign (make_ssa_name (int_type),
1961 BIT_AND_EXPR, src, nmask);
1962 gimple_set_location (stmt, loc);
1963 gimple_seq_add_stmt_without_update (&seq, stmt);
1964 src = gimple_assign_lhs (stmt);
1966 stmt = gimple_build_assign (make_ssa_name (int_type),
1967 BIT_IOR_EXPR, tem, src);
1968 gimple_set_location (stmt, loc);
1969 gimple_seq_add_stmt_without_update (&seq, stmt);
1970 src = gimple_assign_lhs (stmt);
1974 stmt = gimple_build_assign (dest, src);
1975 gimple_set_location (stmt, loc);
1976 gimple_set_vuse (stmt, new_vuse);
1977 gimple_seq_add_stmt_without_update (&seq, stmt);
1979 tree new_vdef;
1980 if (i < split_stores.length () - 1)
1981 new_vdef = make_ssa_name (gimple_vop (cfun), stmt);
1982 else
1983 new_vdef = last_vdef;
1985 gimple_set_vdef (stmt, new_vdef);
1986 SSA_NAME_DEF_STMT (new_vdef) = stmt;
1987 new_vuse = new_vdef;
1990 FOR_EACH_VEC_ELT (split_stores, i, split_store)
1991 delete split_store;
1993 gcc_assert (seq);
1994 if (dump_file)
1996 fprintf (dump_file,
1997 "New sequence of %u stmts to replace old one of %u stmts\n",
1998 split_stores.length (), orig_num_stmts);
1999 if (dump_flags & TDF_DETAILS)
2000 print_gimple_seq (dump_file, seq, 0, TDF_VOPS | TDF_MEMSYMS);
2002 gsi_insert_seq_after (&last_gsi, seq, GSI_SAME_STMT);
2003 for (int j = 0; j < 2; ++j)
2004 if (load_seq[j])
2005 gsi_insert_seq_after (&load_gsi[j], load_seq[j], GSI_SAME_STMT);
2007 return true;
2010 /* Process the merged_store_group objects created in the coalescing phase.
2011 The stores are all against the base object BASE.
2012 Try to output the widened stores and delete the original statements if
2013 successful. Return true iff any changes were made. */
2015 bool
2016 imm_store_chain_info::output_merged_stores ()
2018 unsigned int i;
2019 merged_store_group *merged_store;
2020 bool ret = false;
2021 FOR_EACH_VEC_ELT (m_merged_store_groups, i, merged_store)
2023 if (output_merged_store (merged_store))
2025 unsigned int j;
2026 store_immediate_info *store;
2027 FOR_EACH_VEC_ELT (merged_store->stores, j, store)
2029 gimple *stmt = store->stmt;
2030 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
2031 gsi_remove (&gsi, true);
2032 if (stmt != merged_store->last_stmt)
2034 unlink_stmt_vdef (stmt);
2035 release_defs (stmt);
2038 ret = true;
2041 if (ret && dump_file)
2042 fprintf (dump_file, "Merging successful!\n");
2044 return ret;
2047 /* Coalesce the store_immediate_info objects recorded against the base object
2048 BASE in the first phase and output them.
2049 Delete the allocated structures.
2050 Return true if any changes were made. */
2052 bool
2053 imm_store_chain_info::terminate_and_process_chain ()
2055 /* Process store chain. */
2056 bool ret = false;
2057 if (m_store_info.length () > 1)
2059 ret = coalesce_immediate_stores ();
2060 if (ret)
2061 ret = output_merged_stores ();
2064 /* Delete all the entries we allocated ourselves. */
2065 store_immediate_info *info;
2066 unsigned int i;
2067 FOR_EACH_VEC_ELT (m_store_info, i, info)
2068 delete info;
2070 merged_store_group *merged_info;
2071 FOR_EACH_VEC_ELT (m_merged_store_groups, i, merged_info)
2072 delete merged_info;
2074 return ret;
2077 /* Return true iff LHS is a destination potentially interesting for
2078 store merging. In practice these are the codes that get_inner_reference
2079 can process. */
2081 static bool
2082 lhs_valid_for_store_merging_p (tree lhs)
2084 tree_code code = TREE_CODE (lhs);
2086 if (code == ARRAY_REF || code == ARRAY_RANGE_REF || code == MEM_REF
2087 || code == COMPONENT_REF || code == BIT_FIELD_REF)
2088 return true;
2090 return false;
2093 /* Return true if the tree RHS is a constant we want to consider
2094 during store merging. In practice accept all codes that
2095 native_encode_expr accepts. */
2097 static bool
2098 rhs_valid_for_store_merging_p (tree rhs)
2100 return native_encode_expr (rhs, NULL,
2101 GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (rhs)))) != 0;
2104 /* If MEM is a memory reference usable for store merging (either as
2105 store destination or for loads), return the non-NULL base_addr
2106 and set *PBITSIZE, *PBITPOS, *PBITREGION_START and *PBITREGION_END.
2107 Otherwise return NULL, *PBITPOS should be still valid even for that
2108 case. */
2110 static tree
2111 mem_valid_for_store_merging (tree mem, unsigned HOST_WIDE_INT *pbitsize,
2112 unsigned HOST_WIDE_INT *pbitpos,
2113 unsigned HOST_WIDE_INT *pbitregion_start,
2114 unsigned HOST_WIDE_INT *pbitregion_end)
2116 HOST_WIDE_INT bitsize;
2117 HOST_WIDE_INT bitpos;
2118 unsigned HOST_WIDE_INT bitregion_start = 0;
2119 unsigned HOST_WIDE_INT bitregion_end = 0;
2120 machine_mode mode;
2121 int unsignedp = 0, reversep = 0, volatilep = 0;
2122 tree offset;
2123 tree base_addr = get_inner_reference (mem, &bitsize, &bitpos, &offset, &mode,
2124 &unsignedp, &reversep, &volatilep);
2125 *pbitsize = bitsize;
2126 if (bitsize == 0)
2127 return NULL_TREE;
2129 if (TREE_CODE (mem) == COMPONENT_REF
2130 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (mem, 1)))
2132 get_bit_range (&bitregion_start, &bitregion_end, mem, &bitpos, &offset);
2133 if (bitregion_end)
2134 ++bitregion_end;
2137 if (reversep)
2138 return NULL_TREE;
2140 /* We do not want to rewrite TARGET_MEM_REFs. */
2141 if (TREE_CODE (base_addr) == TARGET_MEM_REF)
2142 return NULL_TREE;
2143 /* In some cases get_inner_reference may return a
2144 MEM_REF [ptr + byteoffset]. For the purposes of this pass
2145 canonicalize the base_addr to MEM_REF [ptr] and take
2146 byteoffset into account in the bitpos. This occurs in
2147 PR 23684 and this way we can catch more chains. */
2148 else if (TREE_CODE (base_addr) == MEM_REF)
2150 offset_int bit_off, byte_off = mem_ref_offset (base_addr);
2151 bit_off = byte_off << LOG2_BITS_PER_UNIT;
2152 bit_off += bitpos;
2153 if (!wi::neg_p (bit_off) && wi::fits_shwi_p (bit_off))
2155 bitpos = bit_off.to_shwi ();
2156 if (bitregion_end)
2158 bit_off = byte_off << LOG2_BITS_PER_UNIT;
2159 bit_off += bitregion_start;
2160 if (wi::fits_uhwi_p (bit_off))
2162 bitregion_start = bit_off.to_uhwi ();
2163 bit_off = byte_off << LOG2_BITS_PER_UNIT;
2164 bit_off += bitregion_end;
2165 if (wi::fits_uhwi_p (bit_off))
2166 bitregion_end = bit_off.to_uhwi ();
2167 else
2168 bitregion_end = 0;
2170 else
2171 bitregion_end = 0;
2174 else
2175 return NULL_TREE;
2176 base_addr = TREE_OPERAND (base_addr, 0);
2178 /* get_inner_reference returns the base object, get at its
2179 address now. */
2180 else
2182 if (bitpos < 0)
2183 return NULL_TREE;
2184 base_addr = build_fold_addr_expr (base_addr);
2187 if (!bitregion_end)
2189 bitregion_start = ROUND_DOWN (bitpos, BITS_PER_UNIT);
2190 bitregion_end = ROUND_UP (bitpos + bitsize, BITS_PER_UNIT);
2193 if (offset != NULL_TREE)
2195 /* If the access is variable offset then a base decl has to be
2196 address-taken to be able to emit pointer-based stores to it.
2197 ??? We might be able to get away with re-using the original
2198 base up to the first variable part and then wrapping that inside
2199 a BIT_FIELD_REF. */
2200 tree base = get_base_address (base_addr);
2201 if (! base
2202 || (DECL_P (base) && ! TREE_ADDRESSABLE (base)))
2203 return NULL_TREE;
2205 base_addr = build2 (POINTER_PLUS_EXPR, TREE_TYPE (base_addr),
2206 base_addr, offset);
2209 *pbitsize = bitsize;
2210 *pbitpos = bitpos;
2211 *pbitregion_start = bitregion_start;
2212 *pbitregion_end = bitregion_end;
2213 return base_addr;
2216 /* Return true if STMT is a load that can be used for store merging.
2217 In that case fill in *OP. BITSIZE, BITPOS, BITREGION_START and
2218 BITREGION_END are properties of the corresponding store. */
2220 static bool
2221 handled_load (gimple *stmt, store_operand_info *op,
2222 unsigned HOST_WIDE_INT bitsize, unsigned HOST_WIDE_INT bitpos,
2223 unsigned HOST_WIDE_INT bitregion_start,
2224 unsigned HOST_WIDE_INT bitregion_end)
2226 if (!is_gimple_assign (stmt))
2227 return false;
2228 if (gimple_assign_rhs_code (stmt) == BIT_NOT_EXPR)
2230 tree rhs1 = gimple_assign_rhs1 (stmt);
2231 if (TREE_CODE (rhs1) == SSA_NAME
2232 && handled_load (SSA_NAME_DEF_STMT (rhs1), op, bitsize, bitpos,
2233 bitregion_start, bitregion_end))
2235 op->bit_not_p = !op->bit_not_p;
2236 return true;
2238 return false;
2240 if (gimple_vuse (stmt)
2241 && gimple_assign_load_p (stmt)
2242 && !stmt_can_throw_internal (stmt)
2243 && !gimple_has_volatile_ops (stmt))
2245 tree mem = gimple_assign_rhs1 (stmt);
2246 op->base_addr
2247 = mem_valid_for_store_merging (mem, &op->bitsize, &op->bitpos,
2248 &op->bitregion_start,
2249 &op->bitregion_end);
2250 if (op->base_addr != NULL_TREE
2251 && op->bitsize == bitsize
2252 && ((op->bitpos - bitpos) % BITS_PER_UNIT) == 0
2253 && op->bitpos - op->bitregion_start >= bitpos - bitregion_start
2254 && op->bitregion_end - op->bitpos >= bitregion_end - bitpos)
2256 op->stmt = stmt;
2257 op->val = mem;
2258 op->bit_not_p = false;
2259 return true;
2262 return false;
2265 /* Record the store STMT for store merging optimization if it can be
2266 optimized. */
2268 void
2269 pass_store_merging::process_store (gimple *stmt)
2271 tree lhs = gimple_assign_lhs (stmt);
2272 tree rhs = gimple_assign_rhs1 (stmt);
2273 unsigned HOST_WIDE_INT bitsize, bitpos;
2274 unsigned HOST_WIDE_INT bitregion_start;
2275 unsigned HOST_WIDE_INT bitregion_end;
2276 tree base_addr
2277 = mem_valid_for_store_merging (lhs, &bitsize, &bitpos,
2278 &bitregion_start, &bitregion_end);
2279 if (bitsize == 0)
2280 return;
2282 bool invalid = (base_addr == NULL_TREE
2283 || ((bitsize > MAX_BITSIZE_MODE_ANY_INT)
2284 && (TREE_CODE (rhs) != INTEGER_CST)));
2285 enum tree_code rhs_code = ERROR_MARK;
2286 store_operand_info ops[2];
2287 if (invalid)
2289 else if (rhs_valid_for_store_merging_p (rhs))
2291 rhs_code = INTEGER_CST;
2292 ops[0].val = rhs;
2294 else if (TREE_CODE (rhs) != SSA_NAME)
2295 invalid = true;
2296 else
2298 gimple *def_stmt = SSA_NAME_DEF_STMT (rhs), *def_stmt1, *def_stmt2;
2299 if (!is_gimple_assign (def_stmt))
2300 invalid = true;
2301 else if (handled_load (def_stmt, &ops[0], bitsize, bitpos,
2302 bitregion_start, bitregion_end))
2303 rhs_code = MEM_REF;
2304 else
2305 switch ((rhs_code = gimple_assign_rhs_code (def_stmt)))
2307 case BIT_AND_EXPR:
2308 case BIT_IOR_EXPR:
2309 case BIT_XOR_EXPR:
2310 tree rhs1, rhs2;
2311 rhs1 = gimple_assign_rhs1 (def_stmt);
2312 rhs2 = gimple_assign_rhs2 (def_stmt);
2313 invalid = true;
2314 if (TREE_CODE (rhs1) != SSA_NAME)
2315 break;
2316 def_stmt1 = SSA_NAME_DEF_STMT (rhs1);
2317 if (!is_gimple_assign (def_stmt1)
2318 || !handled_load (def_stmt1, &ops[0], bitsize, bitpos,
2319 bitregion_start, bitregion_end))
2320 break;
2321 if (rhs_valid_for_store_merging_p (rhs2))
2322 ops[1].val = rhs2;
2323 else if (TREE_CODE (rhs2) != SSA_NAME)
2324 break;
2325 else
2327 def_stmt2 = SSA_NAME_DEF_STMT (rhs2);
2328 if (!is_gimple_assign (def_stmt2))
2329 break;
2330 else if (!handled_load (def_stmt2, &ops[1], bitsize, bitpos,
2331 bitregion_start, bitregion_end))
2332 break;
2334 invalid = false;
2335 break;
2336 default:
2337 invalid = true;
2338 break;
2342 if (invalid)
2344 terminate_all_aliasing_chains (NULL, stmt);
2345 return;
2348 struct imm_store_chain_info **chain_info = NULL;
2349 if (base_addr)
2350 chain_info = m_stores.get (base_addr);
2352 store_immediate_info *info;
2353 if (chain_info)
2355 unsigned int ord = (*chain_info)->m_store_info.length ();
2356 info = new store_immediate_info (bitsize, bitpos, bitregion_start,
2357 bitregion_end, stmt, ord, rhs_code,
2358 ops[0], ops[1]);
2359 if (dump_file && (dump_flags & TDF_DETAILS))
2361 fprintf (dump_file, "Recording immediate store from stmt:\n");
2362 print_gimple_stmt (dump_file, stmt, 0);
2364 (*chain_info)->m_store_info.safe_push (info);
2365 terminate_all_aliasing_chains (chain_info, stmt);
2366 /* If we reach the limit of stores to merge in a chain terminate and
2367 process the chain now. */
2368 if ((*chain_info)->m_store_info.length ()
2369 == (unsigned int) PARAM_VALUE (PARAM_MAX_STORES_TO_MERGE))
2371 if (dump_file && (dump_flags & TDF_DETAILS))
2372 fprintf (dump_file,
2373 "Reached maximum number of statements to merge:\n");
2374 terminate_and_release_chain (*chain_info);
2376 return;
2379 /* Store aliases any existing chain? */
2380 terminate_all_aliasing_chains (NULL, stmt);
2381 /* Start a new chain. */
2382 struct imm_store_chain_info *new_chain
2383 = new imm_store_chain_info (m_stores_head, base_addr);
2384 info = new store_immediate_info (bitsize, bitpos, bitregion_start,
2385 bitregion_end, stmt, 0, rhs_code,
2386 ops[0], ops[1]);
2387 new_chain->m_store_info.safe_push (info);
2388 m_stores.put (base_addr, new_chain);
2389 if (dump_file && (dump_flags & TDF_DETAILS))
2391 fprintf (dump_file, "Starting new chain with statement:\n");
2392 print_gimple_stmt (dump_file, stmt, 0);
2393 fprintf (dump_file, "The base object is:\n");
2394 print_generic_expr (dump_file, base_addr);
2395 fprintf (dump_file, "\n");
2399 /* Entry point for the pass. Go over each basic block recording chains of
2400 immediate stores. Upon encountering a terminating statement (as defined
2401 by stmt_terminates_chain_p) process the recorded stores and emit the widened
2402 variants. */
2404 unsigned int
2405 pass_store_merging::execute (function *fun)
2407 basic_block bb;
2408 hash_set<gimple *> orig_stmts;
2410 FOR_EACH_BB_FN (bb, fun)
2412 gimple_stmt_iterator gsi;
2413 unsigned HOST_WIDE_INT num_statements = 0;
2414 /* Record the original statements so that we can keep track of
2415 statements emitted in this pass and not re-process new
2416 statements. */
2417 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2419 if (is_gimple_debug (gsi_stmt (gsi)))
2420 continue;
2422 if (++num_statements >= 2)
2423 break;
2426 if (num_statements < 2)
2427 continue;
2429 if (dump_file && (dump_flags & TDF_DETAILS))
2430 fprintf (dump_file, "Processing basic block <%d>:\n", bb->index);
2432 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2434 gimple *stmt = gsi_stmt (gsi);
2436 if (is_gimple_debug (stmt))
2437 continue;
2439 if (gimple_has_volatile_ops (stmt))
2441 /* Terminate all chains. */
2442 if (dump_file && (dump_flags & TDF_DETAILS))
2443 fprintf (dump_file, "Volatile access terminates "
2444 "all chains\n");
2445 terminate_and_process_all_chains ();
2446 continue;
2449 if (gimple_assign_single_p (stmt) && gimple_vdef (stmt)
2450 && !stmt_can_throw_internal (stmt)
2451 && lhs_valid_for_store_merging_p (gimple_assign_lhs (stmt)))
2452 process_store (stmt);
2453 else
2454 terminate_all_aliasing_chains (NULL, stmt);
2456 terminate_and_process_all_chains ();
2458 return 0;
2461 } // anon namespace
2463 /* Construct and return a store merging pass object. */
2465 gimple_opt_pass *
2466 make_pass_store_merging (gcc::context *ctxt)
2468 return new pass_store_merging (ctxt);
2471 #if CHECKING_P
2473 namespace selftest {
2475 /* Selftests for store merging helpers. */
2477 /* Assert that all elements of the byte arrays X and Y, both of length N
2478 are equal. */
2480 static void
2481 verify_array_eq (unsigned char *x, unsigned char *y, unsigned int n)
2483 for (unsigned int i = 0; i < n; i++)
2485 if (x[i] != y[i])
2487 fprintf (stderr, "Arrays do not match. X:\n");
2488 dump_char_array (stderr, x, n);
2489 fprintf (stderr, "Y:\n");
2490 dump_char_array (stderr, y, n);
2492 ASSERT_EQ (x[i], y[i]);
2496 /* Test shift_bytes_in_array and that it carries bits across between
2497 bytes correctly. */
2499 static void
2500 verify_shift_bytes_in_array (void)
2502 /* byte 1 | byte 0
2503 00011111 | 11100000. */
2504 unsigned char orig[2] = { 0xe0, 0x1f };
2505 unsigned char in[2];
2506 memcpy (in, orig, sizeof orig);
2508 unsigned char expected[2] = { 0x80, 0x7f };
2509 shift_bytes_in_array (in, sizeof (in), 2);
2510 verify_array_eq (in, expected, sizeof (in));
2512 memcpy (in, orig, sizeof orig);
2513 memcpy (expected, orig, sizeof orig);
2514 /* Check that shifting by zero doesn't change anything. */
2515 shift_bytes_in_array (in, sizeof (in), 0);
2516 verify_array_eq (in, expected, sizeof (in));
2520 /* Test shift_bytes_in_array_right and that it carries bits across between
2521 bytes correctly. */
2523 static void
2524 verify_shift_bytes_in_array_right (void)
2526 /* byte 1 | byte 0
2527 00011111 | 11100000. */
2528 unsigned char orig[2] = { 0x1f, 0xe0};
2529 unsigned char in[2];
2530 memcpy (in, orig, sizeof orig);
2531 unsigned char expected[2] = { 0x07, 0xf8};
2532 shift_bytes_in_array_right (in, sizeof (in), 2);
2533 verify_array_eq (in, expected, sizeof (in));
2535 memcpy (in, orig, sizeof orig);
2536 memcpy (expected, orig, sizeof orig);
2537 /* Check that shifting by zero doesn't change anything. */
2538 shift_bytes_in_array_right (in, sizeof (in), 0);
2539 verify_array_eq (in, expected, sizeof (in));
2542 /* Test clear_bit_region that it clears exactly the bits asked and
2543 nothing more. */
2545 static void
2546 verify_clear_bit_region (void)
2548 /* Start with all bits set and test clearing various patterns in them. */
2549 unsigned char orig[3] = { 0xff, 0xff, 0xff};
2550 unsigned char in[3];
2551 unsigned char expected[3];
2552 memcpy (in, orig, sizeof in);
2554 /* Check zeroing out all the bits. */
2555 clear_bit_region (in, 0, 3 * BITS_PER_UNIT);
2556 expected[0] = expected[1] = expected[2] = 0;
2557 verify_array_eq (in, expected, sizeof in);
2559 memcpy (in, orig, sizeof in);
2560 /* Leave the first and last bits intact. */
2561 clear_bit_region (in, 1, 3 * BITS_PER_UNIT - 2);
2562 expected[0] = 0x1;
2563 expected[1] = 0;
2564 expected[2] = 0x80;
2565 verify_array_eq (in, expected, sizeof in);
2568 /* Test verify_clear_bit_region_be that it clears exactly the bits asked and
2569 nothing more. */
2571 static void
2572 verify_clear_bit_region_be (void)
2574 /* Start with all bits set and test clearing various patterns in them. */
2575 unsigned char orig[3] = { 0xff, 0xff, 0xff};
2576 unsigned char in[3];
2577 unsigned char expected[3];
2578 memcpy (in, orig, sizeof in);
2580 /* Check zeroing out all the bits. */
2581 clear_bit_region_be (in, BITS_PER_UNIT - 1, 3 * BITS_PER_UNIT);
2582 expected[0] = expected[1] = expected[2] = 0;
2583 verify_array_eq (in, expected, sizeof in);
2585 memcpy (in, orig, sizeof in);
2586 /* Leave the first and last bits intact. */
2587 clear_bit_region_be (in, BITS_PER_UNIT - 2, 3 * BITS_PER_UNIT - 2);
2588 expected[0] = 0x80;
2589 expected[1] = 0;
2590 expected[2] = 0x1;
2591 verify_array_eq (in, expected, sizeof in);
2595 /* Run all of the selftests within this file. */
2597 void
2598 store_merging_c_tests (void)
2600 verify_shift_bytes_in_array ();
2601 verify_shift_bytes_in_array_right ();
2602 verify_clear_bit_region ();
2603 verify_clear_bit_region_be ();
2606 } // namespace selftest
2607 #endif /* CHECKING_P. */