Skip to content
What a CPU Does
step 1/5

Reading — step 1 of 5

Read

~1 min readArchitecture Basics

What a CPU Does

A CPU is a state machine that reads instructions from memory and acts on registers + memory. The fetch-decode-execute cycle:

loop:
    instruction = memory[pc]
    decode(instruction)
    execute(instruction)   # may write registers, memory, set pc

That's it. Everything else — pipelines, caches, branch prediction, out-of-order execution, SIMD — is performance optimization on top of this skeleton.

We'll simulate a RISC-V RV32I subset: 32-bit instructions, 32 general-purpose registers, simple addressing. No floating point, no atomics, no privileged mode. About 40 instructions cover most user code.

Why RISC-V?

  • Open standard, no licensing.
  • Clean instruction encoding (vs x86's chaos).
  • Modern; widely adopted in hardware (SiFive, etc.).
  • Simulators are easy to write (~1000 LOC).

Real CPUs:

  • x86-64 (Intel, AMD): variable-length, dozens of addressing modes, 1500+ instructions. Brutal to decode.
  • ARM (Apple Silicon, mobile): 32-bit fixed (ARMv7) or variable mix (ARMv8/A64).
  • RISC-V: 32-bit fixed (RV32) or 16-bit compressed (RVC). What we'll build.

Real simulators:

  • QEMU: full system, multi-arch.
  • Spike: official RISC-V reference simulator.
  • Renode: embedded simulator with peripherals.

Our goal: simulate enough RISC-V to run small C programs compiled with riscv-gcc. Test: load a binary, run, observe output. The fetch-decode-execute loop is the heart.

Memory model:

  • Flat 32-bit address space (4 GiB).
  • Word-addressed accesses 4-byte aligned (or use byte/halfword loads/stores).
  • Little-endian.

Registers:

  • x0: hardwired zero.
  • x1-x31: general purpose. Conventions: x1 = return address (ra), x2 = stack pointer (sp), x10-x17 = function args / return values (a0-a7).
  • pc: program counter.

Discussion

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

Sign in to post a comment or reply.

Loading…