Skip to content
Assembly

Function Call Convention (System V AMD64)

Pass args in registers, preserve callee-saved regs, keep rsp 16-byte aligned.

By EZ4Code Team
calling-conventionabifunctions

Code

; sum3(a, b, c) -> a + b + c
; Args: rdi=a, rsi=b, rdx=c ; result in rax
section .text
global sum3
sum3:
    mov     rax, rdi
    add     rax, rsi
    add     rax, rdx
    ret

; A non-leaf function that calls printf — must save rbx (callee-saved)
extern printf
fmt: db "n=%d", 10, 0

global show_n
show_n:
    push    rbx             ; save callee-saved reg we will use
    mov     rbx, rdi        ; keep arg across the printf call

    sub     rsp, 8          ; align rsp to 16 before 'call'
    mov     rdi, fmt
    mov     esi, ebx
    xor     eax, eax        ; 0 vector args (variadic ABI)
    call    printf
    add     rsp, 8          ; restore rsp

    mov     rax, rbx        ; return n
    pop     rbx             ; restore rbx
    ret

Explanation

The System V AMD64 ABI passes the first 6 integer args in rdi, rsi, rdx, rcx, r8, r9 and returns in rax. Caller-saved registers (rax, rcx, rdx, rsi, rdi, r8-r11) may be clobbered by any call; callee-saved ones (rbx, rbp, r12-r15) must be preserved. rsp must be 16-byte aligned at the moment of 'call' (the call then pushes 8 bytes of return address, leaving the callee with rsp 8 off).

More Assembly Snippets