13.4 โ Functions in assembly
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] retJust two lines!
- The arguments arrive in registers:
ainedi,binesi. lea eax, [rdi+rsi]works outa + band puts it ineax.- The answer is returned in
eax.retgoes 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 retpush 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 ofaandbon the stack.- Then it loads them back, adds, and returns in
eax. pop rbpputs 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 retFollow it step by step:
- Save
b(esi) inebp, becausecallmay wipeesi. ais already inedi, socall square(int)โ answer ineax.- Save that answer in
ebx. - Move
bintoediand callsquareagain. add eax, ebxadds both answers. Return.
The push / pop pairs save and restore registers the function borrowed.
Tip: press โ / โ to move between lessons, / to search.