0

i was reading some examples for Assembly x86_64 and hit this slide: https://i.stack.imgur.com/KWAI8.jpg or incase the link goes down:

void multstore
(long x, long y, long *dest) {
  long t = mult2(x, y);
  *dest = t;
}

long mult2(long a, long b)
{
  long s = a * b;
  return s;
}

0000000000400540 <multstore>:
400540: push   %rbx     # Save %rbx
400541: mov    %rdx,%rbx        # Save dest
400544: callq  400550 <mult2>   # mult2(x,y)
400549: mov    %rax,(%rbx)  # Save at dest
40054c: pop    %rbx     # Restore %rbx
40054d: retq            # Return

0000000000400550 <mult2>:
400550:  mov    %rdi,%rax   # a 
400553:  imul   %rsi,%rax   # a * b
400557:  retq           # Return

What i dont understand is at 400541 why the author saves the DEST, what about this - i can just use the %rdx to handle the work:

mulstore:
push %rbx
callq mult2
mov %rax, (%rdx)
retq

isnt this simpler? or im missing something important here? TY.

  • probably the calling convention on the target platform makes `rdx` call-clobbered. The current implementation of `mult2` seems to not modify `rdx` (gave it 0.5s check, so I'm not sure), but the `mulstore` must be still written in accordance with used calling convention. If you don't follow any calling convention, and you guarantee `mult2` will not modify `rdx`, then your adjustment seems correct. (but you have to do `pop %rbx` or delete also `push`, otherwise the posted snippet of code would use for `retq` the `rbx` value instead of return address). – Ped7g Oct 16 '18 at 09:59
  • Please paste the code from the slide into your question. External images often go down which makes your question not useful to future readers, so their use should be avoided if possible. – fuz Oct 16 '18 at 10:00
  • thank you l have learnt something from this. – Hiệp Nguyễn Oct 16 '18 at 10:04
  • ok ill do it right now – Hiệp Nguyễn Oct 16 '18 at 10:05
  • Looks like compiler output from `gcc -fno-inline-functions -O3`. The caller avoids making any assumptions about `mult2` leaving RDX unclobbered. [What registers are preserved through a linux x86-64 function call](https://stackoverflow.com/q/18024672). Normally the compiler would inline `mult2` and then this would go away. – Peter Cordes Oct 16 '18 at 16:09

0 Answers0