FOUNDATIONS · LESSON 02

CPU Fundamentals

20 min

Learning Objectives

  • Understand the register model (GPRs, RIP, RFLAGS)
  • Explain the fetch-decode-execute cycle
  • Distinguish CISC vs RISC, understand x86-64 as CISC
  • Identify instruction encoding basics (prefixes, opcode, ModR/M, SIB, displacement, immediate)

The CPU is a state machine. Registers hold state. Instructions transition state.

x86-64 Register Model

General Purpose Registers (64-bit)

64-bit32-bit16-bit8-bit (low)8-bit (high)Conventional Role
RAXEAXAXALAHReturn value, accumulator
RBXEBXBXBLBHGeneral-purpose (callee-saved)
RCXECXCXCLCHLoop counter, 1st arg (Win64)
RDXEDXDXDLDH2nd arg (Win64), I/O
RSIESISISIL—Source index, 2nd arg (SysV)
RDIEDIDIDIL—Dest index, 1st arg (SysV)
RBPEBPBPBPL—Frame pointer (callee-saved)
RSPESPSPSPL—Stack pointer
R8–R11R8D–R11DR8W–R11WR8B–R11B—Additional GPRs (volatile)
R12–R15R12D–R15DR12W–R15WR12B–R15B—Additional GPRs (callee-saved)

Special Registers

RegisterPurpose
RIPInstruction Pointer — address of next instruction
RFLAGSStatus flags (ZF, CF, SF, OF, PF, AF, DF, IF, TF, etc.)

RFLAGS Bits You’ll Actually Read

FlagBitNameSet When
ZF6Zero FlagResult == 0
CF0Carry FlagUnsigned overflow / borrow
SF7Sign FlagResult MSB = 1 (negative)
OF11Overflow FlagSigned overflow
PF2Parity FlagLow byte has even parity
AF4Adjust FlagBCD carry (rare)

Fetch-Decode-Execute Cycle

while (true) {
  instruction = memory[RIP];     // FETCH
  decoded = decode(instruction); // DECODE
  execute(decoded);              // EXECUTE
  RIP += instruction.length;     // ADVANCE (unless branch)
}

Key insight: RIP always points to the next instruction. CALL/JMP modify RIP directly.

Instruction Encoding (x86-64)

[Prefixes] [REX] [Opcode] [ModR/M] [SIB] [Displacement] [Immediate]
   0-4B       1B     1-3B      1B      1B       0-4B          0-4B
  • Prefixes: REP, LOCK, operand-size, address-size, segment override
  • REX: Extends registers to R8-R15, 64-bit operand size
  • Opcode: The actual operation (1-3 bytes)
  • ModR/M: Encodes operands (register/memory, register)
  • SIB: Scale-Index-Base for complex addressing [base + index*scale + disp]
  • Displacement: Memory offset (8/32-bit)
  • Immediate: Literal value in instruction

Interactive: Register State Machine

Try it: Step through mov rax, 5 → add rax, 3 → sub rax, 1. Watch RAX change, RIP advance, flags update.

Calling Conventions (Preview)

Convention1st Arg2nd Arg3rd Arg4th ArgReturnVolatilePreserved
Win64RCXRDXR8R9RAXRCX,RDX,R8-R11RBX,RBP,RDI,RSI,R12-R15
SysV AMD64RDIRSIRDXRCXRAXRAX,RCX,RDX,R8-R11RBX,RBP,R12-R15

Stack shadow space: Win64 reserves 32 bytes (4*8) above return address for callees to spill register args.

Takeaway

Registers are the CPU’s scratchpad. Instructions are state transitions. Flags are the receipts.

Next: Memory Layout — where the stack lives, how the heap grows, and why ASLR exists.

Interactive