I have the following C program:
int main()
{
int c[10] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2};
return c[0];
}
and when compiled using the -S
Also why does gcc not use push instead of movl, to push the array elements onto the stack?
It is quite rare to have a large initialized array in exactly the right place in the stack frame that you could use a sequence of pushes, so gcc has not been taught to do that. (In more detail: array initialization is handled as a block memory copy, which is emitted as either a sequence of move instructions or a call to memcpy
, depending on how big it would be. The code that decides what to emit doesn't know where in memory the block is going, so it doesn't know if it could use push
instead.)
Also, movl
is faster. Specifically, push
does an implicit read-modify-write of %esp
, and therefore a sequence of push
es must execute in order. movl
to independent addresses, by contrast, can execute in parallel. So by using a sequence of movl
s rather than push
es, gcc offers the CPU more instruction-level parallelism to take advantage of.
Note that if I compile your code with any level of optimization activated, the array vanishes altogether! Here's -O1
(this is the result of running objdump -dr
on an object file, rather than -S
output, so you can see the actual machine code)
0000000000000000 <main>:
0: b8 00 00 00 00 mov $0x0,%eax
5: c3 retq
and -Os
:
0000000000000000 <main>:
0: 31 c0 xor %eax,%eax
2: c3 retq
Doing nothing is always faster than doing something. Clearing a register with xor
is two bytes instead of five, but has a formal data dependence on the old contents of the register and modifies the condition codes, so might be slower and is thus only chosen when optimizing for size.
Keep in mind that on x86 the stack grows downward. Pushing onto the stack will subtract from the stack pointer.
%rbp <-- Highest memory address
-12
-16
-20
-24
-28
-32
-36
-40
-44
-48 <-- Address of array
First of all, the x86 stack grows downwards. By convention, rbp
stores the original value of rsp
. Therefore, the function's arguments reside at positive offsets relative to rbp
, and its automatic variables reside at negative offsets. The first element of an automatic array has a lower address than all other elements, and thus is the furthest away from rbp
.
Here is a handy diagram that appears on this page:
I see no reason why the compiler couldn't use a series of push
instructions to initialize your array. Whether this would be a good idea, I am not sure.