https://gcc.gnu.org/bugzilla/show_bug.cgi?id=129123
Bug ID: 129123
Summary: [16/17 Regression] wrong code at -O2: state machine
loop with a switch fall-through miscompiled
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: haoxintu at gmail dot com
Target Milestone: ---
Hi,
$cat repro.c
__attribute__((noinline)) unsigned f(int r)
{
signed char c = r;
int st = 2, flag = 0;
unsigned acc = 0;
for (int i = 0; i < 16; i++) {
switch (st) {
case 0:
acc = 0;
if (c > 0)
flag = 0;
/* fall through */
case 1:
acc += (unsigned short)(c + 1);
st = c <= i ? 1 : 3;
if (flag)
st = 0;
flag = i;
break;
default:
st = 0;
}
}
return acc;
}
int main(void)
{
if (f(127) != 128)
__builtin_abort();
return 0;
}
$ gcc -O0 repro.c && ./a.out # ok, also -O1, -O3, -Os
$ gcc -O2 repro.c && ./a.out
Aborted
For c = 127 the loop alternates between the default case (st = 0) and case 0
falling through into case 1: case 0 resets acc to 0, case 1 adds (unsigned
short)(127 + 1) = 128 and sets st = 3 (c > i for every i < 16), so f returns
128. clang -O0/-O2 and gcc -O0/-O1/-O3/-Os agree.
Each of `-fdisable-tree-threadfull1`, `-fdisable-tree-vrp1`,
`-fdisable-tree-evrp`, `-fdisable-tree-pre`, `-fno-tree-vrp`,
`-fno-thread-jumps`, `-fno-code-hoisting` and `-fno-expensive-optimizations`
restores the right result at -O2. threadfull1 registers three jump threads in
f, two of them from the same incoming edge with different continuations (`(5,
6) incoming edge; (6, 8) normal (8, 10) nocopy` and `(5, 6) incoming edge; (6,
7) normal (7, 8) normal (8, 10) nocopy`), so the thread through the switch
looks like the culprit. I have not bisected it.
Reproduced in Godbolt (gcc trunk, -O2 vs -O0): https://godbolt.org/z/fWs5crfrG
## Checked versions
- gcc trunk c3129ba5e3e (2026-11-27, --enable-checking=yes): -O2 aborts; -O0,
-O1, -O3, -Os ok
- gcc 16.0.1 and gcc 16.2: -O2 aborts
- gcc 15.2, 12.2, 13.4, 14.4, 15.1, 15.3 (Godbolt): ok
- clang 21 -O0/-O2: ok; gcc -O0 -fsanitize=address,undefined clean
Thanks.