https://gcc.gnu.org/bugzilla/show_bug.cgi?id=129013

            Bug ID: 129013
           Summary: wrong code at -O3 for a sign-extended _BitInt
                    bit-field read through a union: code hoisting inserts
                    an out-of-bounds VIEW_CONVERT_EXPR<unsigned long[5]>
                    limb load, which FRE then disambiguates
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: 0599jiangyc at gmail dot com
  Target Milestone: ---

The following code:

```c
/* GCC trunk: wrong code at -O3 (and -O2 -fpeel-loops) for a sign-extended
 * signed _BitInt(300) bit-field read through a union after a conditional
 * XOR of the whole 1024-bit member.
 * Godbolt: x86-64 gcc (trunk), flags: -O3   (correct: -O0, -O1, -O2)
 * (f2 makes s cover all 1024 bits, so no union byte is padding after the
u.s.f0 store.)
 * EXPECTED: exit 0.  BUGGY: limbs 7, 9, 11, 13 print as ffffffffffffffff, exit
1.
 */
#include <stdio.h>
#include <string.h>

union U {
  unsigned _BitInt(1024) big;
  struct __attribute__((packed)) { signed _BitInt(300) f0 : 300; unsigned
_BitInt(3) f1 : 3; unsigned _BitInt(721) f2 : 721; } s;
};

__attribute__((noinline)) unsigned _BitInt(1024) g(int c) {
  union U u;
  memset(&u, 0, sizeof u);
  u.s.f0 = 1;
  if (c)
    u.big ^= ~(unsigned _BitInt(1024))0 >> 115;   /* bits 0..908 */
  /* u.s.f0 is now -2 (low 300 bits all ones except bit 0) */
  return u.big ^ ((unsigned _BitInt(1024))u.s.f0 << 7);
}

_Static_assert (sizeof (((union U *)0)->s) == sizeof (unsigned _BitInt(1024)),
"no union padding");

int main(void) {
  unsigned _BitInt(1024) r = g(1);
  /* u.big = bits 1..908 set; f0 sign-extended = ~1, << 7 = ~0 << 8 */
  unsigned _BitInt(1024) e = ((~(unsigned _BitInt(1024))0 >> 115) ^ 1) ^
(~(unsigned _BitInt(1024))0 << 8);
  int bad = 0;
  for (int j = 0; j < 16; j++) {
    unsigned long long x = (unsigned long long)(r >> (64 * j)), y = (unsigned
long long)(e >> (64 * j));
    printf("limb %2d = %016llx  expected %016llx%s\n", j, x, y, x == y ? "" : "
  <-- WRONG");
    bad |= x != y;
  }
  return bad;
}
```

Resulted in this output:
```
$ gcc -O3 repro.c && ./a.out        (also -O2 -fpeel-loops)
limb  7 = ffffffffffffffff  expected 0000000000000000   <-- WRONG
limb  9 = ffffffffffffffff  expected 0000000000000000   <-- WRONG
limb 11 = ffffffffffffffff  expected 0000000000000000   <-- WRONG
limb 13 = ffffffffffffffff  expected 0000000000000000   <-- WRONG
(exit 1; -O0, -O1, -O2, -O3 -fno-code-hoisting and clang print the expected
values)
```

Trunk: https://godbolt.org/z/PjPYrMfcb (x86-64 gcc trunk, -O3, executed;
reproduces as of 2026-11-12)
  • [Bug c/129013] New: wrong code a... 0599jiangyc at gmail dot com via Gcc-bugs

Reply via email to