← Runtimes
Runtimes

Instructions, registers, and the CPU

Fetch, decode, execute, and the registers each step reads and writes.

Trace the state an instruction reads and changes.

Outcome

Trace a short instruction list through fetch, decode and execute, say what a conditional jump reads, and predict a fixed-width register after an add.

Terminology (7)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Program counter (pc)
The register that holds the address of the next instruction to fetch.
Fetch, decode, execute
The repeated cycle of reading the instruction at pc, identifying its operation and operands, and carrying it out.
Register
A small, fixed-width storage location inside the processor that instructions read and write directly.
Accumulator
In simple machines, the register that arithmetic instructions read and write by default.
Flag
A one-bit status register, such as zero or carry, written by some instructions and read by conditional jumps.
Instruction set architecture (ISA)
The instructions, registers and encodings a processor family promises to programs, such as x86-64 or AArch64.
Wraparound
Keeping only the low n bits of a result in an n-bit register, so 255 + 1 becomes 0 in 8 bits.

Instructions act on processor state

A processor runs instructions that read and change a small set of state: registers, memory and the address of the next instruction. A register holds a value inside the processor. The program counter is a register used to locate the next instruction; a flag records a condition that another instruction can consult.

Fetching obtains an instruction, decoding identifies its operation, and executing applies that operation. Following those state changes explains a run more reliably than reading source lines in order. The small interpreter here makes its rules visible; its registers and integer widths are teaching choices, which we will distinguish from the host language’s values.

01Fetch, decode, execute

What does the processor do with each instruction?

A firmware team keeps short display-test routines in its repository. An offline runner lets CI check the values those routines emit before anyone connects a device. One routine contains two OUT instructions, but the runner emits only one value. Is an output missing, or did execution skip it?

To explain the missing output, track which instruction the runner fetches. The program counter (pc) holds that address. Our model fetches the instruction at pc, advances pc, then decodes and executes the fetched operation. The accumulator holds the value that LOAD replaces, ADD changes and OUT emits. JMP writes pc; HALT stops the loop.

The seven-entry routine below is the report reduced to a trace. Addresses are list positions starting at 0. Both OUT entries are present, so changing output code before checking the fetched addresses could hide a control-flow mistake.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// The display-test runner: an authored CPU model with five instructions.
// Trace a seven-entry routine that contains two OUT instructions.

type Instruction = {
  op: "LOAD" | "ADD" | "JMP" | "OUT" | "HALT";
  arg: number;
};

const program: Instruction[] = [
  { op: "LOAD", arg: 2 },
  { op: "JMP", arg: 4 },
  { op: "ADD", arg: 10 },
  { op: "OUT", arg: 0 },
  { op: "ADD", arg: 5 },
  { op: "OUT", arg: 0 },
  { op: "HALT", arg: 0 }
];

let acc = 0;
let pc = 0;
let running = true;

while (running) {
  const instruction = program[pc]; // fetch the instruction at pc
  const address = pc;
  pc += 1; // pc now names the next instruction

  switch (
    instruction.op // decode, then execute
  ) {
    case "LOAD":
      acc = instruction.arg;
      break;
    case "ADD":
      acc += instruction.arg;
      break;
    case "JMP":
      pc = instruction.arg;
      break;
    case "OUT":
      console.log(`out ${acc}`);
      break;
    case "HALT":
      running = false;
      break;
  }

  console.log(`ran ${address} ${instruction.op}, next pc ${pc}`);
}
Which addresses does this program run, in order?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --strict && node main.ts

Put each example in the shown file and run the command. No extra packages are needed. The C++ command uses C++23 mode; these examples need only C++17.

02Flags

What does a conditional jump look at?

The runner next needs a countdown routine that repeats until arithmetic reaches zero. Its new instruction, JNZ, jumps when the zero flag is false. ADD records whether its result is zero; LOAD leaves that flag alone. The flag starts false. These are the instruction format’s rules, so a conditional jump must preserve them even when the accumulator changes afterward.

Before adding the jump, probe the state it will read. This three-step routine finishes a count at zero, then loads a different display value. Does loading that value erase the arithmetic result recorded in the flag?

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Probe the display-test runner before implementing conditional repetition.
// Its machine model has an accumulator, a program counter and a zero flag.

type Machine = {
  acc: number;
  pc: number;
  zero: boolean;
};

type Step = [op: "LOAD" | "ADD", arg: number];

const steps: Step[] = [
  ["LOAD", 8],
  ["ADD", -8],
  ["LOAD", 6]
];

const machine: Machine = { acc: 0, pc: 0, zero: false };

for (const [op, arg] of steps) {
  machine.pc += 1;

  if (op === "LOAD") {
    machine.acc = arg;
  } else {
    machine.acc += arg;
    machine.zero = machine.acc === 0;
  }

  console.log(`${op} ${arg}: acc ${machine.acc}, zero ${machine.zero}`);
}
After the third step, LOAD 6, the accumulator holds 6. What does the zero flag hold?

03Register width

What happens when a register runs out of bits?

The trace and countdown work for small values, but the display tests also exercise byte boundaries. The runner’s full contract uses an unsigned 8-bit accumulator: ADD keeps the low 8 bits, then records whether that stored result is zero. Thus 255 + 1 leaves 0, while 0 − 1 leaves 255. A wide accumulator would give both the wrong output and, at the first boundary, the wrong branch decision.

The examples so far deliberately used wider numbers to isolate control flow. Before refining the runner, check what storage the implementation language offers. Each probe adds 1 to 255 using an 8-bit type and an ordinary integer type. Does choosing a byte-sized type also choose the required arithmetic behavior?

TypeScript’s number is a 64-bit floating-point value with no 8-bit form. A Uint8Array element stores one byte.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Probe byte storage for the display-test runner next to an
// ordinary number.

const register = new Uint8Array(1); // one 8-bit unsigned element
register[0] = 255;
register[0] += 1;

let count = 255;
count += 1;

console.log(`Uint8Array element: ${register[0]}`);
console.log(`number: ${count}`);
What do the two lines print?

04Practice

Complete the display-test runner

Continue the routine runner from the reading. It reads instruction lines from stdin, prints the values emitted by OUT and reports whether execution stopped or exhausted its instruction budget. Accept the team’s aligned text listings, support conditional repetition, then bring arithmetic into agreement with the byte-width contract. Each task supplies the helpers outside its edit.

The display-test runner

Read the routine, preserve its branch decisions, then check its byte boundaries.

  1. easy · R-CPU-V4-1 Decode instruction lines
  2. medium · R-CPU-V4-2 Add the conditional jump
  3. hard · R-CPU-V4-3 Match the 8-bit register
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.