13.3 — Registers and instructions

📘 Chapter 13⏱ about 3 min read✍️ Beginner friendly
Read one box at a time. No rush.

Registers: the CPU's own tiny variables#

The CPU can't do math directly on your variables in memory very fast. It first loads values into registers: a handful of super-fast boxes inside the CPU itself.

On x86-64 (the CPU type in most PCs), the main ones are:

64-bit32-bit partCommon job
raxeaxthe return value of a function
rdiedi1st argument (Linux/Mac)
rsiesi2nd argument (Linux/Mac)
rdxedx3rd argument (Linux/Mac)
rcxecx4th argument (Linux/Mac), 1st on Windows
rspespthe stack pointer — top of the stack
rbpebpoften the base pointer of the current function
r8–r15r8d–r15dextra general registers
Tip

An int is 32 bits, so code working with ints uses the 32-bit names like eax and edi. Pointers are 64 bits, so they use rax, rdi and so on.

Reading one instruction#

Most instructions look like this (Intel style):

text
instruction  destination, source
Assembly (x86-64, GCC -O1)
mov     eax, edi        ; eax = ediadd     eax, 5          ; eax = eax + 5

Everything after ; is a comment.

Key idea

In Intel syntax, the left side is where the result goes. mov eax, edi copies into eax. Read it like eax = edi.

The instructions you'll see most#

InstructionMeaningLike in C++
mov a, bcopya = b
add a, badda += b
sub a, bsubtracta -= b
imul a, bmultiplya *= b
lea a, [x+y]work out an address/suma = x + y
cmp a, bcompare (sets flags)a == b, a < b...
test a, acheck zero / signa == 0, a < 0
jmp Ljump to label Lgoto
je / jne / jl / jg...jump if equal / not equal / less / greater...if
call fcall a functionf()
retreturn from functionreturn
push / popput on / take off the stack—

Memory access#

Square brackets [ ] mean "the memory at this address" — just like * for a pointer.

Assembly (x86-64, GCC -O1)
mov     eax, DWORD PTR [rdi+8]   ; eax = the 4 bytes at address (rdi + 8)
  • DWORD PTR = read 4 bytes (an int).
  • QWORD PTR = read 8 bytes (a pointer or long long).
  • BYTE PTR = read 1 byte (a char).
Two assembly styles

There are two ways to write x86 assembly. Intel syntax (used here, by Ghidra, IDA and x64dbg) puts the destination first. AT&T syntax (the default of objdump and gdb on Linux) puts it last and adds % and $: movl %edi, %eax. Same instructions, different spelling. Use objdump -M intel to switch.

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

Tip: press ← / → to move between lessons, / to search.