So I ask for your opinion on this matter.
Here's the URL: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=98168
Copied the text below.
Here GCC thinks that if both signed integers are positive, then the sum of these integers is also positive. And removes the next bounds check for the negative values (it could be written different, but this is the common way).
int test(int a, int b, int *buf) {
if (a >= 0 && b >= 0) {
a += b;
// let's check that we are not reading outside the buffer
if (a >= 0 && a < 8) return buf[a];
}
return -1;
}
So this code supposed to read the element A+B from a buffer of 8 values. And if the sum is out of the buffer, then return -1. But when compiling with GCC -O2/O3 on x86/x86_64 (and possibly others), you can pass A=0x7fffffff, B=0x7fffffff and access buf[-2] (as with any negative value except -1).Thus, optimizations that falsely assume that the target machine is performing signed integer saturation when it is not - should be considered dangerous.
In my opinion, UB in C has a different purpose, it exists because C is a low-level language and in most cases can use a single machine instruction for a general operation. So for compilers it should be "target machine behavior", not "we can do anything". And compilers must maintain this behavior while removing some operations when optimizing the code.