Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memcpy vs assignment when copying into an array; why does this generate different code?

When compiling the following code,

#include <cstring>
struct X { char a, b, c, d; };

void copy_assignment(char* p, X x) {
    *p++ = x.a;
    *p++ = x.b;
    *p++ = x.c;
    *p++ = x.d;
}

void copy_memcpy(char* p, X x) {
    memcpy(p, &x, sizeof(X));
}

both GCC and clang emit a a series of movb instructions for copy_assignment, while emitting a single movl instruction for copy_memcpy. Assuming X has no padding, which it doesn't here, shouldn't the two be equivalent, and isn't a single movl more efficient?

To be precise, I am compiling with:

g++ -O3 -S -o prog.S prog.cpp

and idem for clang. GCC version is 7.1.1, Clang version is 4.0.1. Using -O2, -Os, and -Ofast gives the same result.

like image 605
Anton Golov Avatar asked Aug 31 '17 12:08

Anton Golov


1 Answers

The answer is not necessarily. As you've said the difference between the compilers and version might stay the same. But looking at the trunk version of gcc the answer is the output is the same as seen in compiler explorer.

like image 150
Bo R Avatar answered Nov 15 '22 06:11

Bo R