I am trying to pick up a little x86. I am compiling on a 64bit mac with gcc -S -O0.
Code in C:
printf("%d", 1);
Output:
movl $1, %esi
leaq LC0(%rip), %rdi
movl $0, %eax ; WHY?
call _printf
I do not understand why %eax is cleared to 0 before ‘printf’ is called. Since printf returns the number of characters printed to %eax my best guess it is zeroed out to prepare it for printf but I would have assumed that printf would have to be responsible for getting it ready. Also, in contrast, if I call my own function int testproc(int p1), gcc sees no need to prepare %eax. So I wonder why gcc treats printf and testproc differently.
From the x86_64 System V ABI register usage table:
printfis a function with variable arguments, and the number of vector registers used is zero.Note that
printfmust check only%al, because the caller is allowed to leave garbage in the higher bytes of%rax. (Still,xor %eax,%eaxis the most efficient way to zero%al)See the this Q&A and the x86 tag wiki for more details, or for up-to-date ABI links if the above link is stale.