This is the part where a calculator turns into a computer. It is also the part with the strangest idea so far, a byte that means a negative number. If it does not click on first reading, run the broken version below, look at where the program lands, and read the section once more. It clicks on the second pass for most people, me included.
Last time our processor got a memory and learned to store into it. But a program still runs once, top to bottom. The last exercise asked for a program that fills five slots: that takes 18 bytes, and two hundred slots would take 603. Today the processor learns to go back and do something again.
By the end of this part
- Your processor remembers whether the last result was zero.
- It can jump backwards in its program depending on that, which makes a loop.
- It prints a line for every instruction it runs, so you can watch it think.
A program that counts to three
Here is the program we want to run today. On the left is where each instruction sits in memory.
8000 A2 00 LDX #$00 put 0 into X
8002 E8 INX add one to X
8003 E0 03 CPX #$03 is X equal to 3?
8005 D0 FB BNE $8002 if not, go back to $8002
8007 00 BRK stopLDX is easy: it is LDA for the X register. The other two new opcodes raise three questions, and the rest of this part answers them in order:
CPXasks a question andBNE, a separate instruction, acts on the answer. Where is the answer kept in between?- How does a program "go back"?
- The instruction says go back to
$8002, but its second byte isFB. Where is the address?
A. Where the answer is kept
Besides its registers, the processor has a handful of single bits that it updates as a side effect of other work. Each one is called a flag. What is a flag? A flag is one bit inside the processor that records a yes-or-no fact about the last result.
The one we need is the zero flag, written Z. Whenever an instruction puts a value into a register, Z is set to 1 if that value was zero, and to 0 otherwise. CPX uses the same flag: it subtracts its number from X, throws the answer away, and keeps only the fact "was that zero?". If X minus 3 is zero, X is 3.
In Rust a yes-or-no value has the type bool, and its two values are true and false. So Z becomes a new field:
struct Cpu {
a: u8,
x: u8,
pc: u16,
zero: bool,
memory: [u8; 0x10000],
}
impl Cpu {
fn new() -> Cpu {
Cpu { a: 0, x: 0, pc: 0x8000, zero: false, memory: [0; 0x10000] }
}And every instruction that changes a register gets one more line. The comparison self.x == 0 produces a bool, which is exactly what the field wants:
0xE8 => {
// INX: add one to X
self.x = self.x.wrapping_add(1);
self.zero = self.x == 0;
}
0xE0 => {
// CPX: compare X with the next byte
let value = self.fetch();
self.zero = self.x == value;
}INX has grown from one line to a block in braces, because it now does two things.
B. How a program goes back
You already know everything needed. The processor always reads its next instruction from wherever pc points. So to go back, an instruction only has to put a smaller address into pc.
An instruction that does this depending on a flag is called a branch. What is a branch? A branch is an instruction that changes pc, but only if a flag has a certain value. BNE stands for "branch if not equal": it changes pc if Z is 0, and does nothing if Z is 1.
C. Where the address went
A branch does not carry an address. To save a byte, it carries a distance: how far to move pc from where it is now. So let us try the obvious thing and add that byte to pc:
0xD0 => {
// BNE: branch if the last result was not zero
let offset = self.fetch();
if !self.zero {
self.pc = self.pc + offset as u16;
}
}To see what happens we will also make the processor print one line per instruction, just before it runs it: the address, the opcode, and the registers and flag at that moment. This goes at the top of the loop:
loop {
println!(
"{:04X} {:02X} A={:02X} X={:02X} Z={}",
self.pc, self.read(self.pc), self.a, self.x, self.zero as u8
);
let opcode = self.fetch();({:04X} prints four hex digits. self.zero as u8 turns false and true into 0 and 1.) A printout like this is called a trace, and it is the emulator builder's best friend. Run the first attempt:
$ cargo run -q
8000 A2 A=00 X=00 Z=0
8002 E8 A=00 X=00 Z=1
8003 E0 A=00 X=01 Z=0
8005 D0 A=00 X=01 Z=0
8102 00 A=00 X=01 Z=0
A = $00 X = $01
Read it line by line. It starts well. Then, after the D0 at $8005, the next instruction comes from $8102. The branch did not go back five bytes. It went forward 251, landed in empty memory, found a 00 and stopped.
$FB is 251. How can 251 mean "back five"?
Remember Part 2: a byte wraps. Start at 5 and add 251, and you get 256, which wraps to 0. So within one byte, adding 251 has the same effect as subtracting 5. The 6502's designers used this. In a branch, the bytes $00 to $7F mean forward 0 to 127, and the bytes $80 to $FF mean backward: $FF is −1, $FE is −2, and $FB is −5.
This way of reading a byte is called two's complement. What is two's complement? Two's complement is a way of reading a byte in which the top half of its values, $80 to $FF, stand for the negative numbers −128 to −1.
Rust has a type for each reading. u8 is a byte read as 0 to 255. i8 is the same eight bits read as −128 to 127 (the "i" is for integer, meaning it may be negative). Converting with as i8 does not change any bits; it changes which column of the table you are in.
pc is after the whole branch instruction has been read: $8007 − 5 = $8002.So the fix is to read the byte as an i8 and add that to pc:
0xD0 => {
// BNE: branch if the last result was not zero
let offset = self.fetch() as i8;
if !self.zero {
self.pc = self.pc.wrapping_add_signed(offset as i16);
}
}self.fetch() as i8reads the distance as a signed number.if !self.zero { … }: the!means "not". In Rust the condition has no brackets round it, and the braces are required.wrapping_add_signedadds a possibly negative number to an unsigned one. Its argument must be 16 bits wide likepc, so we widen the distance withas i16, which keeps −5 as −5.
Watch it loop
0xE8 => { // INX
self.x = self.x.wrapping_add(1);
self.zero = self.x == 0;
}
0xE0 => { // CPX
let value = self.fetch();
self.zero = self.x == value;
}
0xD0 => { // BNE
let offset = self.fetch() as i8;
if !self.zero { /* move pc by offset */ }
}- The start.
pcis$8000, X is 0, and Z is 0. A2 00, LDX: X is loaded with 0. The value loaded was zero, so Z becomes 1. Nobody is looking at Z yet.E8, INX: X becomes 1. That is not zero, so Z goes back to 0.E0 03, CPX: is X equal to 3? 1 is not 3, so Z stays 0.D0 FB, BNE. After reading both bytespcis$8007. Z is 0, so we branch:pcmoves back 5 to$8002.- Lap 2 runs the same three instructions: X becomes 2, 2 is not 3, and the branch sends
pcback to$8002again. - Lap 3. INX makes X = 3. Now CPX finds that X is equal to 3, and Z becomes 1.
- BNE again, but this time Z is 1, so it does nothing.
pcsimply carries on to$8007. 00, BRK. The loop ran three times and X holds 3.
The whole run method
Here is run with everything in place. Besides the three new opcodes, LDA and TAX have each grown a line to keep Z up to date.
fn run(&mut self) {
loop {
println!(
"{:04X} {:02X} A={:02X} X={:02X} Z={}",
self.pc, self.read(self.pc), self.a, self.x, self.zero as u8
);
let opcode = self.fetch();
match opcode {
0xA9 => {
// LDA: load the next byte into A
self.a = self.fetch();
self.zero = self.a == 0;
}
0xA2 => {
// LDX: load the next byte into X
self.x = self.fetch();
self.zero = self.x == 0;
}
0x8D => {
// STA: store A at the address that follows
let addr = self.fetch_addr();
self.write(addr, self.a);
}
0xAA => {
// TAX: copy A into X
self.x = self.a;
self.zero = self.x == 0;
}
0xE8 => {
// INX: add one to X
self.x = self.x.wrapping_add(1);
self.zero = self.x == 0;
}
0xE0 => {
// CPX: compare X with the next byte
let value = self.fetch();
self.zero = self.x == value;
}
0xD0 => {
// BNE: branch if the last result was not zero
let offset = self.fetch() as i8;
if !self.zero {
self.pc = self.pc.wrapping_add_signed(offset as i16);
}
}
0x00 => break, // BRK: stop
_ => panic!("unknown opcode ${:02X}", opcode),
}
}
}Put today's program in main (the snapshot has it with comments) and run:
$ cargo run -q
8000 A2 A=00 X=00 Z=0
8002 E8 A=00 X=00 Z=1
8003 E0 A=00 X=01 Z=0
8005 D0 A=00 X=01 Z=0
8002 E8 A=00 X=01 Z=0
8003 E0 A=00 X=02 Z=0
8005 D0 A=00 X=02 Z=0
8002 E8 A=00 X=02 Z=0
8003 E0 A=00 X=03 Z=0
8005 D0 A=00 X=03 Z=1
8007 00 A=00 X=03 Z=1
A = $00 X = $03
Look down the first column: 8002, 8003, 8005, three times over. Your processor is running a loop. Eight bytes of program, and it would be the same eight bytes for a count of two hundred.
Shortcuts we took on purpose
- A real 6502 has seven flags, packed together into one register called P. We have one, as a separate
bool. Left open; our cartridge only needs Z. - A real
CPXalso updates two other flags. Left open, for the same reason. - The trace is always on. Fixed in Part 7, where we give it a switch.
What changed today
- The Cpu has a
zeroflag, updated by every instruction that changes a register. - New opcodes:
LDX($A2),CPX($E0) and the branchBNE($D0). - A branch distance is read as an
i8, so it can point backwards. runprints a trace line before each instruction.
Now you
- On paper: what byte follows
D0to branch back 3 bytes? Forward 4 bytes? Back 128?Hint
Going backwards, count down from$00with wrapping: −1 is$FF, −2 is$FE, and so on. - Add
DEX($CA, subtract one from X, updating Z) if you have not yet. Then work out by hand whatA2 05 CA D0 FD 00does, and check it with the trace. Why does this loop need noCPX? - Add
BEQ($F0), "branch if equal": the opposite ofBNE. It is one character different. - Our loop goes round three times and does the same thing each time. Suppose lap one should write to
$0200, lap two to$0201and lap three to$0202. Which register already holds a different number on each lap? How might aSTAmake use of it? Think about it before Part 5. - From blank: this time, start by writing the trace line, and add opcodes one at a time, running after each.
Check your understanding
- What is a flag?
Answer
One bit inside the processor that records a yes-or-no fact about the last result. - What is a branch?
Answer
An instruction that changespc, but only if a flag has a certain value. - What is two's complement?
Answer
A way of reading a byte in which the values$80to$FFstand for the negative numbers −128 to −1. - What is the difference between
u8andi8?Answer
Both are eight bits.u8reads them as 0 to 255;i8reads them as −128 to 127. - A branch distance is counted from where?
Answer
Frompcafter the whole branch instruction, both bytes, has been read.
Next time
Right now the loop can count, but every lap touches the same places. In Part 5 the count itself becomes part of an address, so that each lap works on the next byte of a list.