A program counter (PC), also called an instruction pointer, holds the address of the next instruction to execute. In a CHIP-8 interpreter, it is part of the emulated machine state, alongside registers and memory. section 6.3.2
Listing 6.5 Everything we can remember
pub const Memory = struct {
const Self = @This();
pub const total_memory_bytes = 0x1000; #1
pc: u12, #2
i: u12, #2
vars: [16]u8,
data: [total_memory_bytes]u8,
}
The Zig memory structure stores pc as a 12-bit value, alongside the I register, 16 variables, and 4096 bytes of memory. section 6.3.2
Before stepping, load the program into memory and point the PC at its first instruction. The interpreter uses address 0x200: on the COSMAC-VIP, addresses below it were reserved for the interpreter. section 6.3.3
Listing 6.9 Bing bang boom!
pub const program_load_addr = 0x200; #1
pub fn loadProgram(
self: *Self,
program: []const u8, #2
) error{WriteOutOfBounds}!void {
try self.writeBytes(program_load_addr, program);
self.pc = program_load_addr; #3
}
loadProgram copies the program to 0x200 and sets pc to that address. section 6.3.3
Listing 6.7 Our first real step
pub const Error = error {ReadOutOfBounds, UnknownInstruction}; #1
pub fn step(
random: std.Io.Random,
memory: *Memory,
display: *Display,
keypad: *Keypad,
) Error!void {
_ = random; #2
_ = display; #2
_ = keypad; #2
const bytecode = try memory.readBytes(memory.pc, 2); #3
memory.pc += 2; #4
#5
_ = bytecode;
return error.UnknownInstruction;
}
Each step reads two bytes at pc, then advances pc by two. The scaffold returns UnknownInstruction after the read; an out-of-bounds read returns an error before the advance. section 6.3.3
Advancing by two handles the ordinary path, but instructions can change where execution goes next: section 6.3.3 section 6.5.3
- 1MMM jumps to the constant address MMM. BMMM sets the PC to MMM plus register 0, with wrapping addition. section 6.5.3 section 6.5.4
- FX0A waits for a key. If none is pressed, subtract two from the already-advanced PC so the same instruction runs again on the next step. section 6.5.7
- A call saves the PC on a stack and jumps to a function; a return restores it. Store the 12-bit PC in two bytes, advancing the stack pointer by two on push and reversing that operation on pop. section 6.5.6
The call saves only the PC, not the other registers. A function that needs registers already in use can save and reload them separately. Reset the stack pointer to its base when loading a program. section 6.5.9 section 6.5.6
