0

I was playing with this useless C code:

int func(int a, int b);

int main(void)
{

int k=6,z=4,result;

result=func(k,z);

return result;
}

int func(int a, int b)
{
int x, y, t;
x = a + b;
y = a - b;
t = x*x - y*y; 
return t;
}

And I saw that the main function compiles (x86-64 gcc 12.2) in

pushq   %rbp
movq    %rsp, %rbp
subq    $16, %rsp
movl    $6, -4(%rbp)
movl    $4, -8(%rbp)
movl    -8(%rbp), %edx
movl    -4(%rbp), %eax
movl    %edx, %esi
movl    %eax, %edi
call    func(int, int)
movl    %eax, -12(%rbp)
movl    -12(%rbp), %eax
leave
ret

Now, I wonder: why are the two local variables k and z first copied into edx and eax? Wouldn't it be better for the compiler to copy them directly into the two parameter registers esi and edi? What is the need for an indirect transfer?

diciotto
  • 69
  • 3
  • 3
    If you don't compile with optimizations enabled (`-O1`, `-O2` or `-O3`), then the compiler will not make (almost) _any_ optimizations, not even obvious ones. Every write to a variable will be compiled to a write to memory and every read to a read from memory. See linked duplicate for details. – user17732522 Mar 16 '23 at 22:40

0 Answers0