30

Let's consider the following program, which computes an unsigned square of the argument:

.global foo
.text
foo:
    mov %rdi, %rax
    mul %rdi
    ret

This is properly compiled by as, but disassembles to

0000000000000000 <foo>:
   0:   48 89 f8                mov    %rdi,%rax
   3:   48 f7 e7                mul    %rdi
   6:   c3                      retq   

Is there any difference between ret and retq?

marmistrz
  • 5,974
  • 10
  • 42
  • 94

1 Answers1

35

In long (64-bit) mode, you return (ret) by popping a quadword address from the stack to %rip.

In 32-bit mode, you return (ret) by popping a dword address from the stack to %eip.

Some tools like objdump -d call the first one retq. It's just a name, the instruction encoding is the same either way (C3).

ephemient
  • 198,619
  • 38
  • 280
  • 391
  • Does the stack pointer `rsp` gets updated when `retq`/`ret` is executed? Or that has to be done manually? – stillanoob Jun 20 '18 at 12:28
  • Obviously. It does pop, after all. – jv110 Jul 19 '18 at 18:09
  • 1
    @stillanoob the `ret` instruction does two things: (1) pops the stack (which modifies `rsp` by subtracting 4 or 8 from it) (2) alters the `rip` (because the popped value goes into the `rip`). – Fixee Sep 27 '19 at 20:20