https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128943
Bug ID: 128943
Summary: wrong code at -O2: (long)((unsigned long)x + 107) / 16
rounds the wrong way when x + 107 is computed under
conditional
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: shimizu2486 at gmail dot com
Target Milestone: ---
Live reproducer: https://godbolt.org/z/PEP5Yq5eP
$ cat t1.c
#include <stdio.h>
long X = 9223372036854775800, g;
int c, n;
long f(long x) {
if (n)
g = x ? 0 : 5;
x &= 9223372036854775807;
long r = 0;
if (c)
r = x + 10;
r += (long)((unsigned long)x + 10) / 6;
if (c && g == -1)
return 0;
return r;
}
int main(void) { printf("%ld\n", f(X)); }
n and c are 0, so g and r stay 0 and the signed x + 10 is never evaluated.
(unsigned long)x + 10 is 0x8000000000000002, which is -9223372036854775806 as
long, and dividing it by 6 gives -1537228672809129301. The program should
print -1537228672809129301.
$ gcc -O1 t1.c -o t1 && ./t1
-1537228672809129301 (correct)
$ gcc -O2 t1.c -o t1 && ./t1
1537228672809129301 (wrong)
x86_64 trunk (cdb8a10e1a82) wrong
x86_64 16.2.0, 15.3.0, 14.4.0 wrong
x86_64 13.5.0, 12.5.0, 11.5.0 wrong
x86_64 10.5.0, 9.5.0 wrong
-O2 and -O3 are wrong. -O0, -O1, -Os and -Og are correct.
-fno-code-hoisting or -fno-thread-jumps makes -O2 print -1537228672809129301;
-fno-tree-pre does not.