Support for memcpy with equal source and destination
Ralf Jung
post@ralfj.de
Sat Nov 25 08:20:09 GMT 2023
Hi,
On 25.11.23 08:48, Paul Eggert wrote:
> I see several areas of possible confusion, so if we make this change to the
> glibc documentation, the new documentation should make the following clear:
>
> * This is a GNU extension, and other C libraries might not guarantee this (not
> surprising). Also, other C compilers might not guarantee this even when used
> with glibc (somewhat more surprising).
>
> * GCC and other compilers might warn about memcpy (X, X, SIZE) even if it is
> supported.
>
> * This an exception to the usual rule about "restrict", since the prototype says
> "restrict" but it's OK if the two pointers are the same (so "restrict" now means
> that they cannot overlap other than being equal, just for this particular
> function).
Note that "restrict" does not mean "must not be equal". It means "the accesses
performed through this pointer (and pointers derived from it) must be disjoint
from the accesses performed through other pointers (excluding memory that is
only being read)".
So when one sees restrict in a signature, it is impossible to tell what the
actual constraint is without further documentation: the function needs to say
which memory is being accesses through which pointer, and *that* is then where
the disjointness comes from.
That said, if the glibc memcpy has "restrict" in its signature, then GCC itself
will optimize it assuming that the two buffers are truly disjoint. For a memcpy
that is implemented in C (rather than assembly), I don't think it is possible to
make this promise (of supporting src==dest) when there is "restrict" in the
signature. So if glibc wants to make that promise I think it needs to remove
"restrict" from its memcpy signatures.
Kind regards,
Ralf
More information about the Libc-alpha
mailing list