https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128672
Bug ID: 128672
Summary: wrong code for (int)-x / 2 when (int)x / 2 is also
computed
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/qs6xzj5vq
(int)-x / 2 gets the wrong sign from -O1 up when (int)x / 2 is also computed.
$ cat t1.c
#include <stdio.h>
static volatile unsigned X = 0x80000000;
int g;
int main(void) {
unsigned x = X;
g = (int)x / 2;
printf("%d\n", (int)-x / 2);
}
x is 0x80000000, so -x is 0x80000000 too, (int)x and (int)-x are both INT_MIN,
and (int)-x / 2 must be INT_MIN / 2. The program should print -1073741824.
$ gcc -O0 t1.c -o t1 && ./t1
-1073741824 (correct)
$ gcc -O1 t1.c -o t1 && ./t1
1073741824 (wrong)
x86_64 trunk (842e09f03b64) wrong
x86_64 16.2.0 wrong
x86_64 15.3.0 wrong
x86_64 14.4.0 wrong
x86_64 13.5.0 wrong
x86_64 12.5.0 wrong
x86_64 11.5.0 wrong
x86_64 10.5.0 correct
x86_64 9.5.0 correct
-O0 is correct; -O1, -O2, -O3 and -Os are wrong. -fno-tree-fre makes -O1 print
-1073741824. Without the line g = (int)x / 2; the program prints -1073741824 at
every level. aarch64 and loongarch64 trunk are wrong too; clang prints
-1073741824.