4

This is my C function:

int reg(struct my_callback_struct *p, int data)
{
   return p->data = data;
}

This is the same in assembly:

0x000000000040057d <+0>:  push   %rbp
0x000000000040057e <+1>:  mov    %rsp,%rbp
0x0000000000400581 <+4>:  mov    %rdi,-0x8(%rbp)
0x0000000000400585 <+8>:  mov    %esi,-0xc(%rbp)
0x0000000000400588 <+11>: mov    -0x8(%rbp),%rax
0x000000000040058c <+15>: mov    -0xc(%rbp),%edx
0x000000000040058f <+18>: mov    %edx,(%rax)
0x0000000000400591 <+20>: mov    -0x8(%rbp),%rax
0x0000000000400595 <+24>: mov    (%rax),%eax
0x0000000000400597 <+26>: pop    %rbp
0x0000000000400598 <+27>: retq

I think I understand what's going on. $rdi holds the pointer (address) and $esi the number 12.

This is how I called the function:

p->callback_func(p,12);

What I don't understand is:

0x0000000000400591 <+20>: mov -0x8(%rbp),%rax

Because on <+11> we have already filled $rax with the pointer address. Why load it twice?

4
  • The usual cause is that people forget to turn optimization on, so the compiler generates inefficient code. Commented Oct 5, 2014 at 17:25
  • You should identify which sub-species of assembler this is. It looks like it is probably for the Intel x86_64 family of chips, but it would be sensible to state as much. Different assemblers use different notations, too — identifying which assembler/compiler you're using and the platform you're using it on may also be relevant. Commented Oct 5, 2014 at 17:26
  • gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2; x86_64 Commented Oct 5, 2014 at 17:30
  • 1
    Compile with gcc -O -fverbose-asm -S Commented Oct 5, 2014 at 17:41

1 Answer 1

2

Indeed, the code is correct in that the instructions perform the functions called for by the C code. But not even the most trivial of optimizations have been performed.

This is easily corrected by turning on some level of compiler optimization. Probably the first level will clean up redundant loads no matter which compiler is used.

Note that extreme levels of optimization can result in correct code which is very difficult to follow.

Sign up to request clarification or add additional context in comments.

1 Comment

well, if this is the reason, now then i understand ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.