C++: Difference between calling memcpy and __builtin_memcpy
Florian Weimer
fweimer@redhat.com
Thu Mar 10 11:54:00 GMT 2016
On 02/15/2016 06:49 PM, Martin Sebor wrote:
> On 02/15/2016 07:13 AM, Florian Weimer wrote:
>> On 02/15/2016 03:21 AM, Martin Sebor wrote:
>>> On 02/12/2016 04:55 AM, Florian Weimer wrote:
>>>> For the C++ compilers version which recognize memcpy, is there a
>>>> difference between calling memcpy via your own extern "C" declaration,
>>>> and calling __builtin_memcpy?
>>>
>>> Except in freestanding mode (with builtins disabled) I don't believe
>>> there is a difference. They both get expanded the same way (either
>>> inline or to a call to memcpy depending on arguments).
>>
>> Hmm. I tried to verify this using:
>
> I would expect the other string builtins to be treated the same
> as memcpy although I don't think gcc provides the required C++
> overloads of functions like strchr.
Sorry about the subject. I'm interested more in those built-ins which
have C++ overloads.
>> #include <stddef.h>
>>
>> extern "C" size_t strlen(const char*);
>> extern "C" char *strchr(const char *, char);
>
> Though it shouldn't matter here, strchr takes an int as the second
> argument.
It does matter, thanks for spotting this. :)
>> Only the last call in call_builtin is optimized with the knowledge of
>> the meaning of the strchr function.
>
> I don't see a difference between it and call_strchr_0. How is it
> optimized differently and for what target (and with what options)?
With the int fix above, I get:
call_strchr_0 optimize to âreturn 0;â
call_strchr_1 not optimized
call_strchr_2 not optimized
call_search not optimized
call_builtin optimize to âreturn 0;â
This separate test:
#include <stddef.h>
extern "C" size_t strlen(const char*);
const char *search(const char *, int) __asm__ ("strchr");
extern "C" {
char *call_strchr(const char *s, int ch)
{
extern char *strchr(const char *, int);
return strchr(s, ch);
}
}
size_t
call_strchr_3 (const char *s)
{
return strlen(call_strchr(s, 0));
}
is also optimized (just like call_builtin).
>> I'm trying to determine what to use as the best possible fix for this
>> glibc bug:
>>
>> https://sourceware.org/bugzilla/show_bug.cgi?id=19618
>>
>> I'm wondering if I should switch to a __builtin-based approach for GCC,
>> and the extern hack for non-GCC compilers.
>
> Not having tried it or even thought about it too carefully, Richard's
> suggestion makes sense to me (the __call_memchr function outlined in
> the bug is etxern "C"). Does it not work?
Yes, as the test above shows. I was a bit confused, but this cleared up
things for me.
The only reason not to do this is that the address of the strchr
function will not be consistent across the entire process. Do you think
this could be a problem, even just a conformance problem?
Florian
More information about the Gcc-help
mailing list