Skip to content
x86-64 Assembly Basics
step 1/5

Reading — step 1 of 5

Read

~1 min readCode Generation

x86-64 Assembly Basics

x86-64 (AMD64): the 64-bit successor to x86. Most desktop/server CPUs.

Registers (general-purpose):

  • 64-bit: rax, rbx, rcx, rdx, rsi, rdi, rbp, rsp, r8-r15.
  • 32-bit aliases: eax, ebx, ... r8d-r15d.
  • 16-bit: ax, bx, ...
  • 8-bit: al, bl, ...

Special registers:

  • rip: instruction pointer (next inst).
  • rsp: stack pointer.
  • rbp: base pointer (frame pointer).
  • rflags: flags (CF, ZF, SF, OF).

Calling convention (System V AMD64 ABI, Linux/Mac):

  • Arg registers: rdi, rsi, rdx, rcx, r8, r9 (first 6 args).
  • Return: rax (and rdx for 128-bit).
  • Caller-saved: rax, rcx, rdx, rsi, rdi, r8-r11.
  • Callee-saved: rbx, rbp, r12-r15.
  • Stack 16-byte aligned at call.

Common instructions:

  • mov rax, rbx: copy.
  • add rax, 5: rax += 5.
  • sub rsp, 16: allocate 16 bytes on stack.
  • push rax: rsp -= 8; mem[rsp] = rax.
  • pop rax: rax = mem[rsp]; rsp += 8.
  • lea rax, [rsp+8]: load effective address.
  • cmp rax, 0: compare (sets flags).
  • je label: jump if equal.
  • jne label, jg, jl, jge, jle.
  • call func: push return addr; jump.
  • ret: pop return addr; jump.
add:
    mov rax, rdi
    add rax, rsi
    ret

main:
    mov rdi, 5
    mov rsi, 10
    call add
    ; rax now contains 15

Function prologue/epilogue:

foo:
    push rbp           ; save old base pointer
    mov rbp, rsp       ; new base pointer
    sub rsp, 32        ; allocate 32 bytes for locals

    ...               ; function body

    mov rsp, rbp       ; deallocate locals
    pop rbp            ; restore base pointer
    ret

Stack frame layout:

[caller's stack] ... old rbp (saved) | local vars | ... rsp
                  ^ rbp

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…