https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128752
Bug ID: 128752
Summary: [15/16/17 Regression] wrong code at -O1: SRA rewrites
part stores of a reverse-storage-order _Complex field
into a MEM_REF store; real and imaginary parts swapped
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Keywords: wrong-code
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: jeffchen006 at gmail dot com
Target Milestone: ---
Target: x86_64-pc-linux-gnu
int printf(const char *, ...);
#pragma scalar_storage_order big-endian
struct S { short a; _Complex int z; unsigned char b:5; };
#pragma scalar_storage_order default
int r, i;
void f(const struct S *q) {
r = __real__ q->z;
i = __imag__ q->z;
}
void (*fp)(const struct S *) = f;
int main(void) {
struct S l = { 18, 3 + 4i, 18 };
struct S t = l;
fp(&t);
printf("%d %d\n", r, i);
}
$ gcc -O0 t.c && ./a.out
3 4
$ gcc -O1 t.c && ./a.out
4 3
-O1, -O2, -O3 fail; -O1 -fno-tree-sra gives 3 4. The same happens with _Complex
float. The fields a and b, and the copy `t = l`, are needed.
Before late SRA the IL has `REALPART_EXPR <l.z> = 3; IMAGPART_EXPR <l.z> = 4;`.
The sra dump has the access `expr = l.z, type = complex int, reverse = 1` and
the new statement
MEM <complex int> [(struct S *)&l + 4B] = _15;
The result has the parts swapped (not byte-garbled), so the reverse store of
this MEM_REF flips the 8-byte complex as one integer (DImode) instead of each
4-byte part. A complex store through the COMPONENT_REF (`q->z = w` with w in a
register) is right on 7.5 to trunk, so the problem is in the reverse MEM_REF
store of a complex mode that SRA creates.
Suspected cause (not confirmed in the code): SRA (tree-sra.cc,
build_ref_for_offset with REF_REVERSE_STORAGE_ORDER) together with the
expansion of a reverse-order store of a complex value through a MEM_REF
(expr.cc expand_assignment / flip_storage_order called with an integer mode).
14.3 is correct, 15.2 fails (not bisected).
-O0 -fsanitize=undefined,address is clean.
gcc -Wall -Wextra gives no warnings. -fno-strict-aliasing -fwrapv does not
change the output.
Possible fix: We are not sure of the right fix. A minimal guard would be to not
create a MEM_REF replacement for a reverse-storage-order access of complex type
in SRA (keep the COMPONENT_REF, which expands correctly), or to make the
expansion of a reverse MEM_REF store of a complex mode flip each part in the
complex mode.
gcc version 17.0.0 20261114 (experimental), r17-6275-gfceddda853f,
x86_64-pc-linux-gnu
Configured with: --enable-languages=c,c++ --disable-multilib
--disable-bootstrap --enable-checking=release