https://gcc.gnu.org/bugzilla/show_bug.cgi?id=129147
Bug ID: 129147
Summary: [14/15/16/17 Regression] wrong code at -O0: `(long
long) (a ? -a : a)` with unsigned `a` folded to
`-(long long) a`, introducing signed overflow
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Keywords: wrong-code
Severity: normal
Priority: P3
Component: middle-end
Assignee: unassigned at gcc dot gnu.org
Reporter: haoxintu at gmail dot com
Target Milestone: ---
Hi,
$cat repro.c
__attribute__((noinline)) int f (unsigned long long a)
{
/* a ? -a : a is -a (unsigned, wraps); for a == 1ULL << 63, -a == 1ULL << 63,
converted to long long it is LLONG_MIN (GCC's documented modulo
conversion), so the result is 0. */
return (long long) (a ? -a : a) > 0;
}
int main (void)
{
if (f (1ULL << 63))
__builtin_abort ();
return 0;
}
$ gcc -O0 repro.c && ./a.out # Aborted (also -O1, -O2, -O3, -Os)
$ gcc -O0 -fwrapv repro.c && ./a.out # ok
$ clang -O0 repro.c && ./a.out # ok
The program should have no undefined behaviour: `-a` is unsigned arithmetic,
and the conversion of `1ULL << 63` to `long long` is implementation-defined,
documented by GCC as reduction modulo 2^64, which gives `LLONG_MIN`. So `f`
must return `LLONG_MIN > 0`, which is 0. The C++ front end is correct (g++
trunk returns 0); clang with
`-fsanitize=address,undefined` reports nothing.
Godbolt (gcc trunk aborts, gcc 7.5 is correct): https://godbolt.org/z/Po71qP4rE
## Checked Versions:
- gcc 7.5 is correct.
- All versions between gcc 8.x to trunk (17.0.0 20261129) abort.
I’m surprised that GCC appears to have miscompiled such a simple case for so
long. If I’ve overlooked something, I’d be grateful if you could point it out.
I’d be happy to learn more.
Thanks!