https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61236

--- Comment #9 from Mukund Sivaraman <muks at banu dot com> ---
Hi Jakub, Markus

We discussed this during our daily standup call today, and there are two
points we'd like to make:

1. The qsort() defintion in C99 doesn't explicitly state that base must
not be NULL, though it seems you are deducing that from "the initial
element of which is pointed to by base."

The POSIX definition of qsort() adds this:

 "If the nel argument has the value zero, the comparison function
  pointed to by compar shall not be called and no rearrangement shall
  take place."

2. From our perpective as users of GCC, this kind of agressive
optimization seems counter-intuitive. We'd like code to compile to
correct object code first before performance.

When the compiler knows at that point that base (=x) is NULL as an
argument to qsort(), why isn't it warning when the attribute expects it
to be non-NULL, esp. as it is using this inferred decision to optimize
code down below?

The compiler knows x is NULL at this point in this codepath regardless
of what qsort()'s attributes say. Why is it using the attribute then?

qsort() also does not assert (at runtime) that base is non-NULL.  There
is no way to detect this for code which used to run correctly before,
but doesn't anymore (without it _hopefully_ crashing somewhere).

Other similar functions such as memcpy(), etc. also have this annotation
in glibc, whereas there is no definition of n=0 case in C99.

This example of qsort() is in libc, but imagine a case where a program
uses a 3rd party system installed utility shared library. If the
library, in a new version, adds a nonnull annotation for a function, but
the library function itself continues to work for NULL input, see what
happens to the program: The library is not affected, but the pointer in
the calling program is affected if the compiler infers that the pointer
is non-NULL due to the attribute. The calling program is now buggy due
to a change in the library. How do we discover it?

It makes sense to just avoid the qsort() in our case and we will update
our code to do so, but please consider the arguments above.

Reply via email to