https://gcc.gnu.org/bugzilla/show_bug.cgi?id=129204
Bug ID: 129204
Summary: wrong code at -O1 and -Os: ivopts replaces the early
exit i * 3 == b with a test on a step-12 IV
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: jeffchen006 at gmail dot com
Target Milestone: ---
Target: x86_64-pc-linux-gnu
int printf(const char *, ...);
unsigned long f(unsigned long b) {
unsigned long s = 0;
for (unsigned long i = 0; i < 300; i += 3) {
s += i * 4;
if (i * 3 == b)
break;
}
return s;
}
int main(void) {
printf("%lu\n", f(0xc000000000000000UL));
return 0;
}
$ gcc -O0 t.c && ./a.out
59400
$ gcc -O1 t.c && ./a.out
0
Wrong at -O1, -Os. -Os fails on 7.5 to 10.5 as well; -O1 fails since 14.
-fno-ivopts gives 59400.
Bisected to r14-2675-gef28aadad6e ("loop-ch improvements, part 3") for -O1; its
parent is fine at -O1. That commit only changes loop header copying; -Os was
already wrong on 7.5.
The exit test i * 3 == b is rewritten as ivtmp == b * 0xaaaaaaaaaaaaaaac with
ivtmp stepping by 12. may_eliminate_iv accepts this because the niter bound of
this exit (2^64/9) is below the period of the candidate, but that bound only
holds if the exit is taken. Since 12 = 4 * 3, the new test is true at i = 0 for
b = 0xc000000000000000, where i * 3 == b is never true.
Clean with -fsanitize=address,undefined (gcc and clang).
gcc version 17.0.0 20261201 (experimental), r17-6987-gdeb313acd22,
x86_64-pc-linux-gnu
Configured with: --enable-languages=c,c++ --disable-multilib
--disable-bootstrap --enable-checking=release