13.4 โ€” Functions in assembly

๐Ÿ“˜ Chapter 13โฑ about 3 min readโœ๏ธ Beginner friendly
Read one box at a time. No rush.

The simplest function#

Let's compile a tiny function and look at the result. Press ๐Ÿ” See assembly to try it live.

int add(int a, int b){    return a + b;}
Assembly (x86-64, GCC -O1)
add(int, int):        lea     eax, [rdi+rsi]        ret

Just two lines!

  • The arguments arrive in registers: a in edi, b in esi.
  • lea eax, [rdi+rsi] works out a + b and puts it in eax.
  • The answer is returned in eax. ret goes back to the caller.
Calling convention

The agreed rules for where arguments go and where the return value comes back. On Linux and Mac (the "System V" rules), integer arguments go in rdi, rsi, rdx, rcx, r8, r9. On Windows, they go in rcx, rdx, r8, r9. Both return values in rax / eax.

The same function, unoptimized#

With -O0 (no optimization), the compiler is much more literal:

int add(int a, int b){    return a + b;}
Assembly (x86-64, GCC -O0)
add(int, int):        push    rbp        mov     rbp, rsp        mov     DWORD PTR [rbp-4], edi        mov     DWORD PTR [rbp-8], esi        mov     edx, DWORD PTR [rbp-4]        mov     eax, DWORD PTR [rbp-8]        add     eax, edx        pop     rbp        ret
  • push rbp / mov rbp, rsp = set up this function's stack frame (its own area of memory).
  • [rbp-4] and [rbp-8] are the local copies of a and b on the stack.
  • Then it loads them back, adds, and returns in eax.
  • pop rbp puts the old frame back before returning.
Key idea

-O0 code is long but easy to follow: every variable gets its own spot on the stack. Optimized code is short but clever. Real-world programs are usually optimized.

Calling another function#

int square(int x); int sumOfSquares(int a, int b){    return square(a) + square(b);}
Assembly (x86-64, GCC -O1)
sumOfSquares(int, int):        push    rbp        push    rbx        sub     rsp, 8        mov     ebp, esi        call    square(int)        mov     ebx, eax        mov     edi, ebp        call    square(int)        add     eax, ebx        add     rsp, 8        pop     rbx        pop     rbp        ret

Follow it step by step:

  1. Save b (esi) in ebp, because call may wipe esi.
  2. a is already in edi, so call square(int) โ†’ answer in eax.
  3. Save that answer in ebx.
  4. Move b into edi and call square again.
  5. add eax, ebx adds both answers. Return.

The push / pop pairs save and restore registers the function borrowed.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press โ† / โ†’ to move between lessons, / to search.