Home / Learn Chip Programming / The Fetch, Decode, Execute Cycle (Build a CPU Simulator)

The Fetch, Decode, Execute Cycle (Build a CPU Simulator)

This one loop is what every CPU does, billions of times per second. Step through it with a real working simulator.

In shortFetch the instruction at PC, decode what it means, execute it, update PC, repeat. Everything a computer does is this loop.

Theory in plain words

The CPU loopFetch from [PC]Decode opcodeExecuteUpdate PCCPU
The CPU loop

What it is

The fetch-decode-execute cycle is the endless loop of a CPU. It reads an instruction from memory, works out what it means and does it, then moves to the next one.

Why we use it

It is the answer to "how does a chip run my program?". Once you see this loop, assembly, debuggers, interrupts and pipelines all make sense.

How it works

Fetch: IR = memory[PC]; PC = PC + 1. Decode: the control unit reads the opcode and operands. Execute: the ALU or memory does the work, registers and flags change. Jumps simply load a new value into PC.

Where it is used

  • The core of every CPU
  • What a debugger "single step" does
  • Writing emulators and virtual machines

Our teaching CPU

The simulator below has four 8 bit registers (R0 to R3), a zero flag (Z) and a program counter. The instructions are:

InstructionMeaning
LDI R0, 5load the number 5 into R0
MOV R1, R0copy R0 into R1
ADD R0, R1R0 = R0 + R1 (sets Z)
SUB / INC / DECsubtract, add 1, subtract 1 (set Z)
CMP R0, 5set Z if R0 equals 5
JMP label / JNZ label / JZ labeljump always / if Z is 0 / if Z is 1
OUT R0send a value to the output
HLTstop
Step through a program: add 5 + 3Try it Yourself

Press Step and watch PC, the registers and the arrow in the listing. This is what a debugger does when you single step firmware.

Machine code: instructions are numbers too

Real CPUs do not store text. Each instruction is encoded as bits: some bits say what to do (the opcode), the others say which registers or what number. For example, a 16 bit AVR instruction 0xE005 means LDI R16, 5.

FieldBitsExample (AVR LDI R16, 5)
Opcode1110load immediate
High nibble of value00000
Register (R16 + d)0000R16
Low nibble of value01015
Whole instruction1110 0000 0000 01010xE005
Careful:If the PC points into data instead of code, the CPU will happily "execute" the data as instructions. That is the root of many crashes and of buffer overflow attacks.

Quick quiz

1. What is the order of the cycle?

2. What does a jump instruction change?

Common questions

What is the order of the cycle?

Fetch, decode, execute. Fetch the instruction, decode it, execute it.

What does a jump instruction change?

The program counter. A jump loads a new value into PC.