https://gcc.gnu.org/bugzilla/show_bug.cgi?id=121371
Bug ID: 121371
Summary: Misoptimize when signed integer is used as index and
increase repeatedly
Product: gcc
Version: unknown
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: z00823823 at outlook dot com
Target Milestone: ---
I watched a video of CppCon 2016
https://youtu.be/yG1OZ69H_-o?t=2357&si=PHngSgE8CboKWpeq
There is an example in the video (below is a heavily simplified version):
```c
#define False ((Bool)0)
typedef unsigned int UInt32;
typedef unsigned char UChar;
typedef unsigned char Bool;
Bool mainGtU ( UInt32 i1,
UInt32 i2,
UChar* block )
{
UChar c1, c2;
/* 1 */
c1 = block[i1]; c2 = block[i2];
if (c1 != c2) return (c1 > c2);
i1++; i2++;
/* 2 */
c1 = block[i1]; c2 = block[i2];
if (c1 != c2) return (c1 > c2);
i1++; i2++;
/* 3 */
c1 = block[i1]; c2 = block[i2];
if (c1 != c2) return (c1 > c2);
i1++; i2++;
return False;
}
```
This code is not good because the i1 and i2 is unsigned int and the cimpiler
can not "cache" the block+i1 result because the i1 i2 must warp aroud if it
overlfows.
The speaker provides a better code, by simply using signed int i1/i2 because
signed int overflow is UB and compiler can assume they never happens and
generate better code.
I tried the speaker's method in clang and it does generate better code:
https://godbolt.org/z/cez7W7x36
But when I tried it in gcc it generates worth code:
https://godbolt.org/z/fG5ce7rqK