program counter

tutorial preview
This tutorial page is still under construction — full version coming soon!

Our goal is to build a CPU — a Central Processing Unit. This is the “brains” of a computer, the part responsible for following programs.

We already know that a program is just a list of instructions for the computer to follow. Let’s unpack exactly how this works.

To follow a list of instructions, we need to keep track of which instruction we’re currently at. Computers track this using a program counter (PC), which stores a number indicating what instruction we’re at.

definition

A program counter is a device that keeps track of our position in the program.

So to execute a program, a computer must:

  • Read the Program Counter to find out what instruction we’re at
  • Read the instruction that corresponds to the PC
  • Perform that instruction
  • Increment the PC
tip

Imagine you’re cooking a complicated meal — you might use a bookmark (program counter) to keep track of where you are in the recipe book (program).

This will make our computer step through its instructions one by one. We’ll also need to let certain instructions change the PC directly, making it jump to different parts of the program. This is what will give us branching behaviour.

implementation

Our PC is just storing a number, so to begin with we can reuse our register:

00/0000/00
loading…

dynamic register

Here’s how we might design the program loop:

  1. Read the current value of the PC. Call this A.
  2. Create a clone of A, called B.
  3. Dispatch B to the instruction processor, which will handle finding and executing the corresponding instruction.
  4. Meanwhile, increment A and write it back into the PC.

This might seem a bit risky — we’re incrementing the PC and performing the instruction in parallel, instead of one at a time. What if they interfere with each other?

We should generally be careful with this kind of thing, but in this instance it’s safe. Incrementing A happens much quicker than the instruction execution, so it’ll be done long before B needs to touch the PC. If the instruction happens to affect the PC, it’ll just overwrite the incremented value.

coming soon
We’re still working on this part of the tutorial — come back later!

next

We have the basic idea of how we’ll read each instruction. Next we’ll look at the instruction processor, the device that receives and executes those instructions.

continue