4 ms·
I always thought the memcopy is optimized out, but can you explain how in int i; float f; memcopy (&i, &f,4) the memcopy can be optimized out? Probably I am mis
by andi999 6y ago
I always thought the memcopy is optimized out, but can you explain how in
int i;
float f;
memcopy (&i, &f,4)
the memcopy can be optimized out? Probably I am misunderstanding the statement.
- hurrrrrrrr 6y agoThe compiler is not beholden to the standard library but the standard. So all modern compilers come with a bit of knowledge of how standard library functions like memcpy are supposed to behave and as long as the visible effect is the same it's allowed to do anything it wants. So instead of calling the function memcpy for a size of 4, it can e.g. just use a mov instruction to move the value from a float to an integer register. [1] It does additional analysis on how the values are used and maybe it doesn't even need to move the value at all, but that's the gist of it. [1] https://gcc.godbolt.org/z/x4P7jE https://gcc.godbolt.org/z/x4P7jE
- colejohnson66 6y agoA good example of this is the string functions in the C stdlib. I’ve reverse engineered some programs where the compiler used x86’s built-in “string” instructions instead of calling out to, say, `strlen`.
- andrewaylett 6y agoThe C abstract machine presents i and f as having separate locations in memory, but a compiler that knows that memcopy does can avoid actually saving the target machine registers to the stack, then avoid even copying values between registers.