diff --git a/README.md b/README.md index 8430939..52c7943 100644 --- a/README.md +++ b/README.md @@ -7,11 +7,13 @@ SPDX-License-Identifier: MIT # zig65 A cycle accurate 6502 and 65C02 written in Zig, and a terminal debugger to -drive it. +drive them. All 256 opcodes of each are implemented: on the NMOS part the 151 documented -ones and the 105 that are not, and on the CMOS part everything it added and -everything it does differently, decimal mode included. Correctness is not taken on trust. Every +ones and the 105 that are not, and on the CMOS parts everything they added and +everything they do differently, decimal mode included. There are four in all, +since the CMOS parts differ from one another too: the plain 65C02, Rockwell's +with its bit instructions, and Western Design's with those and two more. Correctness is not taken on trust. Every opcode is run against the [SingleStepTests][sst] corpus, 10,000 cases apiece recorded from hardware, and each case is checked three ways: the registers and memory it ended with, the number of cycles it took, and the address, @@ -30,23 +32,31 @@ $ zig build corpus bus traces: every cycle matches cycle counts: all 2560000 cases match -$ zig build corpus -Dprocessor=65C02 -2560000 tests: 2560000 succeeded, 0 failed, 0 skipped, 1280821 decimal -bus traces: 9979 mismatches across 2 opcodes -cycle counts: all 2560000 cases match -``` - -Both processors pass every case: every register, every flag, every cycle -count. The two remaining trace differences are one cycle each of `ADC #` and -`SBC #` in decimal mode, and they are worth explaining rather than hiding. The -CMOS part spends an extra cycle there putting the answer right, and drives an -address while it does. Where there is an address to drive — a zero page or -absolute operand — it re-reads that, and this does the same. Against a -constant there is no such address, and the recorded traces show the same one -in every single case, $0056 for `ADC` and $0000 for `SBC`, which is not -something an instruction can be doing: it is whatever the harness that -recorded them left on the bus. Reproducing it would be recording their bench -rather than the chip. +$ zig build corpus -Dprocessor=W65C02 +2540000 tests: 2540000 succeeded, 0 failed, 0 skipped, 1270184 decimal +bus traces: every cycle matches but 9975, which are the decimal correction + of ADC and SBC against a constant and are the recording + rather than the chip: see known_difference +cycle counts: all 2540000 cases match +``` + +All four processors pass every case: every register, every flag, every cycle +count. The exception in the CMOS runs is one cycle of `ADC #` and `SBC #` in +decimal, and it is worth explaining rather than hiding. Those instructions +cost the CMOS parts an extra cycle there, which they spend putting the answer +right, and something is on the address bus while they do. Every other +addressing mode has an operand address to re-read, and does, and so does this. +Against a constant there is none — and what the recordings show instead is the +same address in every single case of an opcode: $0056 for `ADC` on one set, +$0059 on another, $0000 for `SBC` on both. An address that does not vary with +the operands, the registers or the counter, and that differs between +recordings of the same instruction, is the bench that made the recording +rather than the chip. The runner names those cycles and counts them +separately, in `known_difference`, rather than either failing on them or +quietly passing. + +The two Western Design instructions are not in that total: 2,540,000 rather +than 2,560,000, because the corpus files for `WAI` and `STP` are empty. ## Building @@ -68,7 +78,7 @@ zig build | `zig build -Dmachine=ii+` | pick the machine: `flat`, `ii+` or `iie` | | `zig build test` | unit tests | | `zig build corpus` | the whole SingleStepTests corpus, run in `corpus/` | -| `zig build -Dprocessor=65C02` | build with the CMOS part in the socket | +| `zig build -Dprocessor=65C02` | build with a CMOS part in the socket: also `R65C02`, `W65C02` | | `zig build bench` | instruction throughput, built ReleaseFast | | `zig build coverage` | kcov report over the unit tests | | `zig build example -- ROM` | run the worked embedding example | @@ -615,7 +625,8 @@ with the hardware fails the build. ``` zig build corpus # from here, which runs it over there -zig build corpus -Dprocessor=65C02 # against the CMOS part instead +zig build corpus -Dprocessor=65C02 # against a CMOS part instead +zig build corpus -Dprocessor=R65C02 # or Rockwell's, or W65C02 for WDC's cd corpus && zig build run # or from the project itself cd corpus && zig build run -Dssf=69 # just opcode $69 ./single_step_tests path/to/65x02/6502/v1 @@ -755,9 +766,26 @@ machine around them is not. perfectly well underneath. `src/graphics/` is an unfinished attempt at drawing that properly. The Apple manuals in the bibliography are the references for the rest. -- **Both processors.** `-Dprocessor=65C02` builds the CMOS part instead of the - NMOS one, and a IIe with that in the socket is what was sold as an enhanced - IIe. It is exact against its own corpus too, all 2,560,000 cases. What +- **Four processors.** `-Dprocessor` chooses: `6502`, `65C02`, `R65C02` or + `W65C02`. Each is exact against its own corpus, and the corpus has all four + because the chips themselves differ. A IIe with a CMOS part in the socket is + what was sold as an enhanced IIe. + + The CMOS parts differ from each other as well as from the NMOS one. The + plain 65C02 is what Synertek, NCR and GTE made. Rockwell's added sixteen + instructions for setting or clearing one bit of a zero page byte and sixteen + for branching on one, which are worth having because they touch no register + and no flag: a byte two things are both looking at can be changed without + disturbing what is being tested around it. Western Design's has those and + two more that stop the processor, one until an interrupt and one until + reset. On the parts without them, all thirty-four encodings do nothing. + + `WAI` and `STP` are the only instructions here with no corpus behind them, + and for a good reason: an instruction that stops cannot be recorded a case + at a time, and the corpus holds an empty file for each. They are tested by + hand instead. + + What changed is not only the instructions it has and the NMOS part has not — the branch that always branches, the index registers on the stack, storing nothing, testing and setting bits, a pointer with no index, `INC A` — but diff --git a/build.zig b/build.zig index 7a0ddde..b15ba9f 100644 --- a/build.zig +++ b/build.zig @@ -141,7 +141,7 @@ pub fn build(b: *std.Build) void { // And which processor goes in it. An enhanced IIe is a IIe with a 65C02 // in the socket, which is the whole of the difference as far as this is // concerned. - const Processor = enum { @"6502", @"65C02" }; + const Processor = enum { @"6502", @"65C02", @"R65C02", @"W65C02" }; // The completions are embedded as well as installed, so that a test can // hold them up against the usage text and fail if the two drift apart. exe.root_module.addAnonymousImport("zig65.fish", .{ @@ -283,6 +283,8 @@ pub fn build(b: *std.Build) void { corpus_run.addArg(switch (processor) { .@"6502" => "-Dprocessor=6502", .@"65C02" => "-Dprocessor=65C02", + .@"R65C02" => "-Dprocessor=R65C02", + .@"W65C02" => "-Dprocessor=W65C02", }); if (b.args) |args| { corpus_run.addArg("--"); diff --git a/corpus/build.zig b/corpus/build.zig index 3943352..e521939 100644 --- a/corpus/build.zig +++ b/corpus/build.zig @@ -15,7 +15,7 @@ const std = @import("std"); -const Processor = enum { @"6502", @"65C02" }; +const Processor = enum { @"6502", @"65C02", @"R65C02", @"W65C02" }; pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); @@ -62,11 +62,12 @@ pub fn build(b: *std.Build) void { // Which corpus to run against, handed over as an argument rather than // compiled in, so the same binary can be pointed at a checkout by hand. run.addDirectoryArg(corpus.path(switch (processor) { - // The plain CMOS part, without the bit instructions Rockwell and - // Western Design added to theirs: what is here is what all three - // of them agree on. - .@"65C02" => "synertek65c02/v1", .@"6502" => "6502/v1", + // The plain CMOS part, without the bit instructions the other two + // have: what is here is what all three of them agree on. + .@"65C02" => "synertek65c02/v1", + .@"R65C02" => "rockwell65c02/v1", + .@"W65C02" => "wdc65c02/v1", })); if (b.args) |args| run.addArgs(args); run_step.dependOn(&run.step); diff --git a/corpus/src/main.zig b/corpus/src/main.zig index 3eea493..413af3c 100644 --- a/corpus/src/main.zig +++ b/corpus/src/main.zig @@ -56,6 +56,27 @@ const cases_per_opcode = 10_000; var debug_allocator: std.heap.DebugAllocator(.{}) = .init; +/// Whether a cycle the corpus records is one no emulator can reproduce. +/// +/// There is exactly one such cycle, and it is worth being precise about rather +/// than waving away. Adding or subtracting against a constant in decimal mode +/// costs the CMOS parts an extra cycle, which they spend putting the answer +/// right, and something is on the address bus while they do. Every other mode +/// has an operand address to re-read and does; a constant has none, and what +/// the recordings show instead is the same address in every single case of an +/// opcode — $0056 for ADC and $0000 for SBC on one set, $0059 and $0000 on +/// another. An address that does not vary with the operands, the registers or +/// the program counter, and differs between recordings of the same +/// instruction, is the bench that made the recording rather than the chip. +/// Reproducing it would be reproducing their bench. +fn known_difference(opcode: u8, cycle: usize, case: Test) bool { + if (options.processor == .@"6502") return false; + if (opcode != 0x69 and opcode != 0xe9) return false; + // Only in decimal, and only the last cycle, which is the correction. + if (case.initial.p & 0x08 == 0) return false; + return cycle == case.cycles.len - 1; +} + /// Runs every opcode against the SingleStepTests corpus in the directory named /// on the command line. /// @@ -70,10 +91,16 @@ var debug_allocator: std.heap.DebugAllocator(.{}) = .init; /// whole address space as ordinary memory, including the page a real machine /// fills with I/O. And it is the one caller that wants the bus log, since /// checking the trace against the hardware's is the point. -const CPU = switch (options.processor) { - .@"6502" => zig65.CPU(zig65.clock.FakeClock, zig65.memory.Flat(.{ .bus_log = true })), - .@"65C02" => zig65.CMOS(zig65.clock.FakeClock, zig65.memory.Flat(.{ .bus_log = true })), -}; +const CPU = zig65.Chip( + .{ .processor = switch (options.processor) { + .@"6502" => .@"6502", + .@"65C02" => .@"65C02", + .@"R65C02" => .@"R65C02", + .@"W65C02" => .@"W65C02", + } }, + zig65.clock.FakeClock, + zig65.memory.Flat(.{ .bus_log = true }), +); /// What running one opcode's ten thousand cases came to. /// @@ -90,6 +117,9 @@ const Outcome = struct { /// The first disagreement, as wanted and got. cycle_example: [2]u64 = .{ 0, 0 }, bus_mismatches: usize = 0, + /// Cycles that differ from the recording for a reason that is understood + /// and written down: see `known_difference`. + known: usize = 0, /// The first bus disagreement, described. Owned by the caller. bus_report: ?[]u8 = null, /// The first architectural failure, described at length. Owned by the @@ -127,6 +157,16 @@ fn runOpcode( return outcome; }; + // An empty file is not a broken one. Western Design's part has two + // instructions that stop the processor — one until an interrupt, one until + // reset — and neither can be recorded a case at a time, so the corpus + // holds a file with nothing in it for each. There is nothing here to check + // them against, and saying so is better than either failing or pretending. + if (test_data.len == 0) { + outcome.total = 0; + return outcome; + } + const parsed = std.json.parseFromSlice([]Test, alloc, test_data, .{}) catch { outcome.fatal = "cannot parse the corpus file"; return outcome; @@ -307,6 +347,10 @@ fn runCase( (access.direction == .write) == (want.direction == .write)) continue; } + if (known_difference(opcode, j, case)) { + outcome.known += 1; + continue; + } if (outcome.bus_report == null) describe: { var buffer: std.Io.Writer.Allocating = .init(gpa); const out = &buffer.writer; @@ -433,6 +477,7 @@ pub fn main(init: std.process.Init) !void { var decimal_cases: usize = 0; var cycle_mismatches: usize = 0; var bus_mismatches: usize = 0; + var known_cycles: usize = 0; for (&outcomes, 0..) |*outcome, i| { defer outcome.deinit(gpa); @@ -447,14 +492,22 @@ pub fn main(init: std.process.Init) !void { decimal_cases += outcome.decimal; cycle_mismatches += outcome.cycle_mismatches; bus_mismatches += outcome.bus_mismatches; + known_cycles += outcome.known; if (outcome.report) |report| std.debug.print("{s}", .{report}); if (outcome.bus_report) |report| std.debug.print("{s}", .{report}); } std.debug.print("\n{d} tests: {d} succeeded, {d} failed, {d} skipped, {d} decimal\n", .{ total_cases, successful_cases, failed_cases, skipped_cases, decimal_cases }); - if (bus_mismatches == 0) { + if (bus_mismatches == 0 and known_cycles == 0) { std.debug.print("bus traces: every cycle matches\n", .{}); + } else if (bus_mismatches == 0) { + std.debug.print( + "bus traces: every cycle matches but {d}, which are the decimal correction\n" ++ + " of ADC and SBC against a constant and are the recording\n" ++ + " rather than the chip: see known_difference\n", + .{known_cycles}, + ); } else { var opcodes: usize = 0; for (&outcomes) |outcome| { diff --git a/src/cpu.zig b/src/cpu.zig index 2e87abc..9bdc0ad 100644 --- a/src/cpu.zig +++ b/src/cpu.zig @@ -190,6 +190,11 @@ pub fn Chip( /// Three bytes, three cycles: two operands fetched and never /// looked at. @"Two Operands", + + /// A byte in the zero page and a distance to branch, which is + /// what the instructions Rockwell added take: three bytes, and + /// neither half of it means anything without the other. + @"Zero Page, Relative", }; /// Where the processor looks for the address to carry on from when @@ -212,6 +217,15 @@ pub fn Chip( /// until whatever pulled it lets go, so a device that is still asking /// will be answered again as soon as the handler enables interrupts. irq: bool = false, + + /// Whether the processor has been told to wait, which only Western + /// Design's part can be. It stops fetching and lets the clock run until + /// something pulls an interrupt line, and what happens then depends on + /// whether interrupts are enabled: either the handler, or simply the next + /// instruction. + waiting: bool = false, + /// And whether it has been stopped, which nothing but a reset undoes. + stopped: bool = false, /// The non-maskable interrupt line. Edge triggered: answering it is /// what clears it, and the interrupt disable flag does not apply. nmi: bool = false, @@ -260,6 +274,10 @@ pub fn Chip( // is one of the things the line decides, so the switches have to // be back where they start before the vector is read through them. self.memory.reset(); + // A processor that was told to stop starts again here, which is + // the only thing that undoes it. + self.stopped = false; + self.waiting = false; self.program_counter.reset(); self.registers.reset(); self.flags.reset(); @@ -286,7 +304,7 @@ pub fn Chip( // wanted to add had to clear it itself and put it back, and one // that forgot did its arithmetic in the wrong base. The CMOS part // clears it on the way in. - if (comptime processor != .@"6502") self.flags.clear(.D); + if (comptime processor.cmos()) self.flags.clear(.D); self.program_counter.jump(self.memory.read(u16, switch (line) { .irq => vector.irq, .nmi => vector.nmi, @@ -300,6 +318,24 @@ pub fn Chip( /// is answered whatever the interrupt disable flag says, which is what /// makes it non-maskable, and answering it is what clears it. pub fn executeInstruction(self: *Self) error{ IllegalOpcode, Break, Jam }!void { + // A stopped processor does nothing at all until it is reset: the + // clock still runs, since a machine around it still has a clock, + // but nothing is fetched. + if (self.stopped) { + self.clock.sleep(1); + return; + } + // A waiting one is the same until something interrupts it. If + // interrupts are enabled it goes to the handler below; if they are + // not it simply carries on, which is the useful half of this + // instruction. + if (self.waiting) { + if (!self.irq and !self.nmi) { + self.clock.sleep(1); + return; + } + self.waiting = false; + } if (self.nmi) { self.nmi = false; self.serviceInterrupt(.nmi); @@ -401,3 +437,96 @@ test "an IRQ is answered again while the line is held" { try cpu.executeInstruction(); try std.testing.expectEqual(@as(u16, 0x3000), cpu.program_counter.value); } + +test "the processor can be told to wait, and what wakes it" { + // Neither this nor stopping can be checked against the corpus: an + // instruction that waits cannot be recorded a case at a time, and the + // files for both are empty there. So they are checked here instead. + var cpu: Chip(.{ .processor = .W65C02 }, @import("clock.zig").FakeClock, memory.Flat(.{})) = undefined; + try cpu.init(null, null); + defer cpu.deinit(); + + try cpu.memory.loadProgram(0x0200, &[_]u8{ 0xcb, 0xa9, 0x42 }); // WAI : LDA #$42 + try cpu.memory.loadProgram(0xfffe, &[_]u8{ 0x00, 0x03 }); // the IRQ vector + cpu.program_counter.value = 0x0200; + cpu.flags.set(.I); // interrupts off, so it carries on rather than jumping + + try cpu.executeInstruction(); + try std.testing.expect(cpu.waiting); + + // Waiting costs cycles and nothing else: the counter does not move. + const before = cpu.clock.cycles; + for (0..100) |_| try cpu.executeInstruction(); + try std.testing.expect(cpu.clock.cycles > before); + try std.testing.expectEqual(@as(u16, 0x0201), cpu.program_counter.value); + try std.testing.expect(cpu.waiting); + + // Something asks for attention. Interrupts are off, so what happens is + // the instruction after the wait rather than the handler. + cpu.irq = true; + try cpu.executeInstruction(); + try std.testing.expect(!cpu.waiting); + try std.testing.expectEqual(@as(u8, 0x42), cpu.registers.get(.A)); + + // And with interrupts on it goes to the handler instead. + var handled: Chip(.{ .processor = .W65C02 }, @import("clock.zig").FakeClock, memory.Flat(.{})) = undefined; + try handled.init(null, null); + defer handled.deinit(); + try handled.memory.loadProgram(0x0200, &[_]u8{0xcb}); + try handled.memory.loadProgram(0xfffe, &[_]u8{ 0x00, 0x03 }); + handled.program_counter.value = 0x0200; + handled.flags.clear(.I); + try handled.executeInstruction(); + handled.irq = true; + try handled.executeInstruction(); + try std.testing.expectEqual(@as(u16, 0x0300), handled.program_counter.value); +} + +test "the processor can be stopped, and only reset starts it again" { + var cpu: Chip(.{ .processor = .W65C02 }, @import("clock.zig").FakeClock, memory.Flat(.{})) = undefined; + try cpu.init(null, null); + defer cpu.deinit(); + + try cpu.memory.loadProgram(0x0200, &[_]u8{ 0xdb, 0xa9, 0x42 }); // STP : LDA #$42 + try cpu.memory.loadProgram(0xfffc, &[_]u8{ 0x00, 0x04 }); // the reset vector + cpu.program_counter.value = 0x0200; + + try cpu.executeInstruction(); + try std.testing.expect(cpu.stopped); + + // Nothing wakes it: not an interrupt, not anything. + cpu.irq = true; + cpu.nmi = true; + cpu.flags.clear(.I); + for (0..100) |_| try cpu.executeInstruction(); + try std.testing.expect(cpu.stopped); + try std.testing.expectEqual(@as(u8, 0x00), cpu.registers.get(.A)); + try std.testing.expectEqual(@as(u16, 0x0201), cpu.program_counter.value); + + cpu.reset(); + try std.testing.expect(!cpu.stopped); + try std.testing.expectEqual(@as(u16, 0x0400), cpu.program_counter.value); +} + +test "the bit instructions are only on the parts that have them" { + // The plain CMOS part does nothing at these encodings, and Rockwell's and + // Western Design's move a bit of a byte in the zero page. + inline for (.{ .@"65C02", .R65C02, .W65C02 }) |which| { + var cpu: Chip(.{ .processor = which }, @import("clock.zig").FakeClock, memory.Flat(.{})) = undefined; + try cpu.init(null, null); + defer cpu.deinit(); + + // SMB3 $10, then RMB1 $10. + try cpu.memory.loadProgram(0x0200, &[_]u8{ 0xb7, 0x10, 0x17, 0x10 }); + try cpu.memory.loadProgram(0x0010, &[_]u8{0b0000_0010}); + cpu.program_counter.value = 0x0200; + try cpu.executeInstruction(); + try cpu.executeInstruction(); + + const expected: u8 = switch (which) { + .@"65C02" => 0b0000_0010, // nothing happened at all + else => 0b0000_1000, // bit three set, bit one cleared + }; + try std.testing.expectEqual(expected, cpu.memory.peek(0x0010)); + } +} diff --git a/src/cpu/add.zig b/src/cpu/add.zig index cd264ca..4e3c9c5 100644 --- a/src/cpu/add.zig +++ b/src/cpu/add.zig @@ -149,7 +149,7 @@ pub fn add(augend: u8, addend: u8, carry_flag: bool, decimal_flag: bool, comptim // rather than about the binary sum underneath it. That is a different // enough sum to be worth doing separately, and it is the cycle it costs // over binary that pays for it. - if (processor != .@"6502" and decimal_flag) { + if (processor.cmos() and decimal_flag) { return switch (operation) { .adc => decimalAdd(augend, addend, carry_flag), .sbc => decimalSubtract(augend, ~addend, carry_flag), diff --git a/src/cpu/addressing_modes.zig b/src/cpu/addressing_modes.zig index f093948..5136f34 100644 --- a/src/cpu/addressing_modes.zig +++ b/src/cpu/addressing_modes.zig @@ -48,7 +48,7 @@ pub fn AddressingModes(comptime CPU: type) type { return switch (self) { .read => false, .write => true, - .modify => CPU.processor == .@"6502", + .modify => !CPU.processor.cmos(), }; } }; @@ -169,6 +169,10 @@ pub fn AddressingModes(comptime CPU: type) type { // whatever fetching they do, they do for themselves. .@"No Operand", .@"Two Operands" => @compileError("no address to work out"), + // Two addresses rather than one, so the instruction fetches + // them itself: there is nothing useful to hand back here. + .@"Zero Page, Relative" => @compileError("two addresses, not one"), + .@"(Indirect)" => addr: { const pointer = cpu.program_counter.read(u8); const low = cpu.memory.read(u8, pointer); @@ -193,7 +197,7 @@ pub fn AddressingModes(comptime CPU: type) type { .Indirect => addr: { const indirect = cpu.program_counter.read(u16); - if (comptime CPU.processor != .@"6502") { + if (comptime CPU.processor.cmos()) { // The CMOS part gets this right, and the way it does is // worth seeing: it makes the NMOS part's mistake first // and then corrects it. The low byte, then a read of diff --git a/src/cpu/opcodes.zig b/src/cpu/opcodes.zig index f3be321..3fe81da 100644 --- a/src/cpu/opcodes.zig +++ b/src/cpu/opcodes.zig @@ -113,9 +113,35 @@ pub fn Opcodes(comptime CPU: type) type { @import("opcodes/tsb.zig"), }; + /// Rockwell's sixteen instructions for moving a bit of a zero page + /// byte, and sixteen for branching on one. Each is generated from + /// which bit it works on and which way round it goes, since that is + /// the only thing telling one from another, and writing thirty-two of + /// them out by hand would be thirty-two chances to get a bit wrong. + const move = @import("opcodes/rmb.zig"); + const test_ = @import("opcodes/bbr.zig"); + const rockwell_only = .{ + move.at(0, false), move.at(0, true), test_.at(0, false), test_.at(0, true), + move.at(1, false), move.at(1, true), test_.at(1, false), test_.at(1, true), + move.at(2, false), move.at(2, true), test_.at(2, false), test_.at(2, true), + move.at(3, false), move.at(3, true), test_.at(3, false), test_.at(3, true), + move.at(4, false), move.at(4, true), test_.at(4, false), test_.at(4, true), + move.at(5, false), move.at(5, true), test_.at(5, false), test_.at(5, true), + move.at(6, false), move.at(6, true), test_.at(6, false), test_.at(6, true), + move.at(7, false), move.at(7, true), test_.at(7, false), test_.at(7, true), + }; + + /// And Western Design's two for stopping. + const wdc_only = .{ + @import("opcodes/wai.zig"), + @import("opcodes/stp.zig"), + }; + const instructions = switch (CPU.processor) { .@"6502" => common ++ nmos_only, .@"65C02", .@"65C816" => common ++ cmos_only, + .R65C02 => common ++ cmos_only ++ rockwell_only, + .W65C02 => common ++ cmos_only ++ rockwell_only ++ wdc_only, }; pub const Error = error{ diff --git a/src/cpu/opcodes/adc.zig b/src/cpu/opcodes/adc.zig index 3a2786b..0d503e5 100644 --- a/src/cpu/opcodes/adc.zig +++ b/src/cpu/opcodes/adc.zig @@ -55,7 +55,7 @@ pub fn data(comptime CPU: type) type { }, }, // The CMOS part gave this one more to answer to. - .@"65C02", .@"65C816" => &.{ + else => &.{ .{ .opcode = 0x61, .addressing_mode = .@"(Indirect, X)", @@ -134,7 +134,7 @@ pub fn data(comptime CPU: type) type { // than binary, which is what it spends correcting the // answer and the flags. The chip drives the address it // last used while it does. - if (CPU.processor != .@"6502" and cpu.flags.isSet(.D)) { + if (CPU.processor.cmos() and cpu.flags.isSet(.D)) { _ = cpu.memory.read(u8, address); } diff --git a/src/cpu/opcodes/and.zig b/src/cpu/opcodes/and.zig index 77b85ed..51889b4 100644 --- a/src/cpu/opcodes/and.zig +++ b/src/cpu/opcodes/and.zig @@ -52,7 +52,7 @@ pub fn data(comptime CPU: type) type { }, }, // The CMOS part gave this one more to answer to. - .@"65C02", .@"65C816" => &.{ + else => &.{ .{ .opcode = 0x21, .addressing_mode = .@"(Indirect, X)", diff --git a/src/cpu/opcodes/bbr.zig b/src/cpu/opcodes/bbr.zig new file mode 100644 index 0000000..38d5ca4 --- /dev/null +++ b/src/cpu/opcodes/bbr.zig @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie +// +// SPDX-License-Identifier: MIT + +//! Branching on one bit of a byte in the zero page: sixteen instructions, one +//! for each bit either way round. +//! +//! Three bytes: which byte, and how far to go. Testing a bit and branching on +//! it otherwise takes a load, a test and a branch, and disturbs a register to +//! do it. Rockwell's part added these and Western Design's kept them. + +/// One of them: which bit, and whether it branches when the bit is set. +pub fn at(comptime which: u3, comptime when_set: bool) type { + return struct { + pub fn data(comptime CPU: type) type { + return struct { + pub const mnemonic = (if (when_set) "BBS" else "BBR") ++ .{'0' + @as(u8, which)}; + pub const opcodes = [_]CPU.Opcodes.Init{ + .{ + .opcode = (if (when_set) 0x8f else 0x0f) | @as(u8, which) << 4, + .addressing_mode = .@"Zero Page, Relative", + .cycles = 5, + }, + }; + + pub fn func(comptime addressing_mode: CPU.AddressingModes) *const fn (*CPU) error{}!void { + if (addressing_mode != .@"Zero Page, Relative") @compileError("illegal addressing mode"); + const f = struct { + pub fn branch(cpu: *CPU) error{}!void { + // The byte comes first and is read twice, the way + // this chip reads anything it might have written, + // and only then is the distance fetched. + const address: u16 = cpu.program_counter.read(u8); + const value = cpu.memory.read(u8, address); + _ = cpu.memory.read(u8, address); + + const offset: i8 = @bitCast(cpu.program_counter.read(u8)); + const target = cpu.program_counter.calculateBranchLocation(offset); + const bit = value & (@as(u8, 1) << which) != 0; + if (bit != when_set) return; + + // Taken costs a cycle, and landing in another page + // costs a second. Both of them are spent with the + // counter on the bus, which is not what an + // ordinary branch does: that one drives the + // address it built before fixing up the high byte. + cpu.program_counter.phantomRead(); + if (cpu.program_counter.value & 0xff00 != target & 0xff00) { + cpu.program_counter.phantomRead(); + } + cpu.program_counter.value = target; + } + }; + return f.branch; + } + }; + } + }; +} diff --git a/src/cpu/opcodes/bit.zig b/src/cpu/opcodes/bit.zig index c741903..5be289d 100644 --- a/src/cpu/opcodes/bit.zig +++ b/src/cpu/opcodes/bit.zig @@ -22,7 +22,7 @@ pub fn data(comptime CPU: type) type { }, }, // The CMOS part gave this one more to answer to. - .@"65C02", .@"65C816" => &.{ + else => &.{ .{ .opcode = 0x24, .addressing_mode = .@"Zero Page", @@ -72,7 +72,7 @@ pub fn data(comptime CPU: type) type { // itself: it already knows what they are. Every other form // puts them in N and V, which is what makes this // instruction the way to read a flag byte from hardware. - if (comptime !(CPU.processor != .@"6502" and addressing_mode == .Immediate)) { + if (comptime !(CPU.processor.cmos() and addressing_mode == .Immediate)) { cpu.flags.update(.N, value & 0x80 == 0x80); cpu.flags.update(.V, value & 0x40 == 0x40); } diff --git a/src/cpu/opcodes/brk.zig b/src/cpu/opcodes/brk.zig index a2b5f1f..eff26b7 100644 --- a/src/cpu/opcodes/brk.zig +++ b/src/cpu/opcodes/brk.zig @@ -38,7 +38,7 @@ pub fn data(comptime CPU: type) type { // The CMOS part clears the decimal flag on its way into a // handler; the NMOS part left it, so a handler that added // anything had to know what base it was in. - if (comptime CPU.processor != .@"6502") cpu.flags.clear(.D); + if (comptime CPU.processor.cmos()) cpu.flags.clear(.D); // Through the interrupt vector, which is not the one reset // uses. Both used to go through ProgramCounter.reset, which // was right for BRK and wrong for reset. diff --git a/src/cpu/opcodes/cmp.zig b/src/cpu/opcodes/cmp.zig index 95cca99..86af702 100644 --- a/src/cpu/opcodes/cmp.zig +++ b/src/cpu/opcodes/cmp.zig @@ -53,7 +53,7 @@ pub fn data(comptime CPU: type) type { }, }, // The CMOS part gave this one more to answer to. - .@"65C02", .@"65C816" => &.{ + else => &.{ .{ .opcode = 0xc1, .addressing_mode = .@"(Indirect, X)", diff --git a/src/cpu/opcodes/dec.zig b/src/cpu/opcodes/dec.zig index 1a71093..319629a 100644 --- a/src/cpu/opcodes/dec.zig +++ b/src/cpu/opcodes/dec.zig @@ -32,7 +32,7 @@ pub fn data(comptime CPU: type) type { }, }, // The CMOS part gave this one more to answer to. - .@"65C02", .@"65C816" => &.{ + else => &.{ .{ .opcode = 0xc6, .addressing_mode = .@"Zero Page", diff --git a/src/cpu/opcodes/eor.zig b/src/cpu/opcodes/eor.zig index 9fd68dd..b50cbd1 100644 --- a/src/cpu/opcodes/eor.zig +++ b/src/cpu/opcodes/eor.zig @@ -52,7 +52,7 @@ pub fn data(comptime CPU: type) type { }, }, // The CMOS part gave this one more to answer to. - .@"65C02", .@"65C816" => &.{ + else => &.{ .{ .opcode = 0x41, .addressing_mode = .@"(Indirect, X)", diff --git a/src/cpu/opcodes/inc.zig b/src/cpu/opcodes/inc.zig index 8349309..7bba6cb 100644 --- a/src/cpu/opcodes/inc.zig +++ b/src/cpu/opcodes/inc.zig @@ -32,7 +32,7 @@ pub fn data(comptime CPU: type) type { }, }, // The CMOS part gave this one more to answer to. - .@"65C02", .@"65C816" => &.{ + else => &.{ .{ .opcode = 0xe6, .addressing_mode = .@"Zero Page", diff --git a/src/cpu/opcodes/jmp.zig b/src/cpu/opcodes/jmp.zig index 583b4dc..4bf47ab 100644 --- a/src/cpu/opcodes/jmp.zig +++ b/src/cpu/opcodes/jmp.zig @@ -23,7 +23,7 @@ pub fn data(comptime CPU: type) type { }, }, // The CMOS part gave this one more to answer to. - .@"65C02", .@"65C816" => &.{ + else => &.{ .{ .opcode = 0x4c, .addressing_mode = .Absolute, diff --git a/src/cpu/opcodes/lda.zig b/src/cpu/opcodes/lda.zig index de697d1..3781cfb 100644 --- a/src/cpu/opcodes/lda.zig +++ b/src/cpu/opcodes/lda.zig @@ -52,7 +52,7 @@ pub fn data(comptime CPU: type) type { }, }, // The CMOS part gave this one more to answer to. - .@"65C02", .@"65C816" => &.{ + else => &.{ .{ .opcode = 0xa1, .addressing_mode = .@"(Indirect, X)", diff --git a/src/cpu/opcodes/nop.zig b/src/cpu/opcodes/nop.zig index e2970c2..67f8edf 100644 --- a/src/cpu/opcodes/nop.zig +++ b/src/cpu/opcodes/nop.zig @@ -2,6 +2,8 @@ // // SPDX-License-Identifier: MIT +const std = @import("std"); + /// Describes one instruction: its mnemonic, and every opcode that selects /// it together with that opcode's addressing mode and cycle count. Opcodes /// collects these at comptime to build the dispatch table. @@ -160,402 +162,449 @@ pub fn data(comptime CPU: type) type { .cycles = 4, }, }, - .@"65C02", .@"65C816" => &.{ - .{ - .opcode = 0x03, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x0b, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x13, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x1b, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x23, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x2b, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x33, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x3b, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x43, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x4b, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x53, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x5b, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x63, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x6b, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x73, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x7b, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x83, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x8b, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x93, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0x9b, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0xa3, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0xab, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0xb3, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0xbb, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0xc3, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0xd3, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0xe3, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0xeb, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0xf3, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0xfb, - .addressing_mode = .@"No Operand", - .cycles = 1, - }, - .{ - .opcode = 0xcb, - .addressing_mode = .Implied, - .cycles = 2, - }, - .{ - .opcode = 0xea, - .addressing_mode = .Implied, - .cycles = 2, - }, - .{ - .opcode = 0x02, - .addressing_mode = .Immediate, - .cycles = 2, - }, - .{ - .opcode = 0x22, - .addressing_mode = .Immediate, - .cycles = 2, - }, - .{ - .opcode = 0x42, - .addressing_mode = .Immediate, - .cycles = 2, - }, - .{ - .opcode = 0x62, - .addressing_mode = .Immediate, - .cycles = 2, - }, - .{ - .opcode = 0x82, - .addressing_mode = .Immediate, - .cycles = 2, - }, - .{ - .opcode = 0xc2, - .addressing_mode = .Immediate, - .cycles = 2, - }, - .{ - .opcode = 0xe2, - .addressing_mode = .Immediate, - .cycles = 2, - }, - .{ - .opcode = 0x07, - .addressing_mode = .@"Zero Page", - .cycles = 3, - }, - .{ - .opcode = 0x27, - .addressing_mode = .@"Zero Page", - .cycles = 3, - }, - .{ - .opcode = 0x44, - .addressing_mode = .@"Zero Page", - .cycles = 3, - }, - .{ - .opcode = 0x47, - .addressing_mode = .@"Zero Page", - .cycles = 3, - }, - .{ - .opcode = 0x67, - .addressing_mode = .@"Zero Page", - .cycles = 3, - }, - .{ - .opcode = 0x87, - .addressing_mode = .@"Zero Page", - .cycles = 3, - }, - .{ - .opcode = 0xa7, - .addressing_mode = .@"Zero Page", - .cycles = 3, - }, - .{ - .opcode = 0xc7, - .addressing_mode = .@"Zero Page", - .cycles = 3, - }, - .{ - .opcode = 0xe7, - .addressing_mode = .@"Zero Page", - .cycles = 3, - }, - .{ - .opcode = 0x17, - .addressing_mode = .@"Zero Page, X", - .cycles = 4, - }, - .{ - .opcode = 0x37, - .addressing_mode = .@"Zero Page, X", - .cycles = 4, - }, - .{ - .opcode = 0x54, - .addressing_mode = .@"Zero Page, X", - .cycles = 4, - }, - .{ - .opcode = 0x57, - .addressing_mode = .@"Zero Page, X", - .cycles = 4, - }, - .{ - .opcode = 0x77, - .addressing_mode = .@"Zero Page, X", - .cycles = 4, - }, - .{ - .opcode = 0x97, - .addressing_mode = .@"Zero Page, X", - .cycles = 4, - }, - .{ - .opcode = 0xb7, - .addressing_mode = .@"Zero Page, X", - .cycles = 4, - }, - .{ - .opcode = 0xd4, - .addressing_mode = .@"Zero Page, X", - .cycles = 4, - }, - .{ - .opcode = 0xd7, - .addressing_mode = .@"Zero Page, X", - .cycles = 4, - }, - .{ - .opcode = 0xdb, - .addressing_mode = .@"Zero Page, X", - .cycles = 4, - }, - .{ - .opcode = 0xf4, - .addressing_mode = .@"Zero Page, X", - .cycles = 4, - }, - .{ - .opcode = 0xf7, - .addressing_mode = .@"Zero Page, X", - .cycles = 4, - }, - .{ - .opcode = 0x0f, - .addressing_mode = .@"Two Operands", - .cycles = 3, - }, - .{ - .opcode = 0x2f, - .addressing_mode = .@"Two Operands", - .cycles = 3, - }, - .{ - .opcode = 0x4f, - .addressing_mode = .@"Two Operands", - .cycles = 3, - }, - .{ - .opcode = 0x6f, - .addressing_mode = .@"Two Operands", - .cycles = 3, - }, - .{ - .opcode = 0x8f, - .addressing_mode = .@"Two Operands", - .cycles = 3, - }, - .{ - .opcode = 0xaf, - .addressing_mode = .@"Two Operands", - .cycles = 3, - }, - .{ - .opcode = 0xcf, - .addressing_mode = .@"Two Operands", - .cycles = 3, - }, - .{ - .opcode = 0xef, - .addressing_mode = .@"Two Operands", - .cycles = 3, - }, - .{ - .opcode = 0x1f, - .addressing_mode = .Absolute, - .cycles = 4, - }, - .{ - .opcode = 0x3f, - .addressing_mode = .Absolute, - .cycles = 4, - }, - .{ - .opcode = 0x5c, - .addressing_mode = .Absolute, - .cycles = 4, - }, - .{ - .opcode = 0x5f, - .addressing_mode = .Absolute, - .cycles = 4, - }, - .{ - .opcode = 0x7f, - .addressing_mode = .Absolute, - .cycles = 4, - }, - .{ - .opcode = 0x9f, - .addressing_mode = .Absolute, - .cycles = 4, - }, - .{ - .opcode = 0xbf, - .addressing_mode = .Absolute, - .cycles = 4, - }, - .{ - .opcode = 0xdc, - .addressing_mode = .Absolute, - .cycles = 4, - }, - .{ - .opcode = 0xdf, - .addressing_mode = .Absolute, - .cycles = 4, - }, - .{ - .opcode = 0xfc, - .addressing_mode = .Absolute, - .cycles = 4, - }, - .{ - .opcode = 0xff, - .addressing_mode = .Absolute, - .cycles = 4, - }, + .@"65C02", .@"65C816" => &cmos, + // Rockwell's part has instructions on two whole columns of the + // table, so those encodings are no longer nothing. + .R65C02 => &without(&cmos, &bit_instructions), + // And Western Design's has two more on top of that. + .W65C02 => &without(&cmos, &(bit_instructions ++ [_]u8{ 0xcb, 0xdb })), + }; + + /// The encodings Rockwell gave instructions to: the $x7 column moves a + /// bit of a zero page byte, the $xF column branches on one. + const bit_instructions = blk: { + var taken: [32]u8 = undefined; + for (0..8) |which| { + taken[which * 4 + 0] = 0x07 | @as(u8, which) << 4; + taken[which * 4 + 1] = 0x87 | @as(u8, which) << 4; + taken[which * 4 + 2] = 0x0f | @as(u8, which) << 4; + taken[which * 4 + 3] = 0x8f | @as(u8, which) << 4; + } + break :blk taken; + }; + + /// How many of a list survive dropping the encodings named. + fn remaining(comptime list: []const CPU.Opcodes.Init, comptime drop: []const u8) usize { + @setEvalBranchQuota(10000); + var kept: usize = 0; + for (list) |entry| { + if (std.mem.indexOfScalar(u8, drop, entry.opcode) == null) kept += 1; + } + return kept; + } + + /// The list without them, which is how a part with more instructions + /// comes to have fewer of these. + fn without( + comptime list: []const CPU.Opcodes.Init, + comptime drop: []const u8, + ) [remaining(list, drop)]CPU.Opcodes.Init { + @setEvalBranchQuota(10000); + var kept: [remaining(list, drop)]CPU.Opcodes.Init = undefined; + var at: usize = 0; + for (list) |entry| { + if (std.mem.indexOfScalar(u8, drop, entry.opcode) != null) continue; + kept[at] = entry; + at += 1; + } + return kept; + } + + const cmos = [_]CPU.Opcodes.Init{ + .{ + .opcode = 0x03, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x0b, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x13, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x1b, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x23, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x2b, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x33, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x3b, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x43, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x4b, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x53, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x5b, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x63, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x6b, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x73, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x7b, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x83, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x8b, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x93, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0x9b, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0xa3, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0xab, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0xb3, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0xbb, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0xc3, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0xd3, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0xe3, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0xeb, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0xf3, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0xfb, + .addressing_mode = .@"No Operand", + .cycles = 1, + }, + .{ + .opcode = 0xcb, + .addressing_mode = .Implied, + .cycles = 2, + }, + .{ + .opcode = 0xea, + .addressing_mode = .Implied, + .cycles = 2, + }, + .{ + .opcode = 0x02, + .addressing_mode = .Immediate, + .cycles = 2, + }, + .{ + .opcode = 0x22, + .addressing_mode = .Immediate, + .cycles = 2, + }, + .{ + .opcode = 0x42, + .addressing_mode = .Immediate, + .cycles = 2, + }, + .{ + .opcode = 0x62, + .addressing_mode = .Immediate, + .cycles = 2, + }, + .{ + .opcode = 0x82, + .addressing_mode = .Immediate, + .cycles = 2, + }, + .{ + .opcode = 0xc2, + .addressing_mode = .Immediate, + .cycles = 2, + }, + .{ + .opcode = 0xe2, + .addressing_mode = .Immediate, + .cycles = 2, + }, + .{ + .opcode = 0x07, + .addressing_mode = .@"Zero Page", + .cycles = 3, + }, + .{ + .opcode = 0x27, + .addressing_mode = .@"Zero Page", + .cycles = 3, + }, + .{ + .opcode = 0x44, + .addressing_mode = .@"Zero Page", + .cycles = 3, + }, + .{ + .opcode = 0x47, + .addressing_mode = .@"Zero Page", + .cycles = 3, + }, + .{ + .opcode = 0x67, + .addressing_mode = .@"Zero Page", + .cycles = 3, + }, + .{ + .opcode = 0x87, + .addressing_mode = .@"Zero Page", + .cycles = 3, + }, + .{ + .opcode = 0xa7, + .addressing_mode = .@"Zero Page", + .cycles = 3, + }, + .{ + .opcode = 0xc7, + .addressing_mode = .@"Zero Page", + .cycles = 3, + }, + .{ + .opcode = 0xe7, + .addressing_mode = .@"Zero Page", + .cycles = 3, + }, + .{ + .opcode = 0x17, + .addressing_mode = .@"Zero Page, X", + .cycles = 4, + }, + .{ + .opcode = 0x37, + .addressing_mode = .@"Zero Page, X", + .cycles = 4, + }, + .{ + .opcode = 0x54, + .addressing_mode = .@"Zero Page, X", + .cycles = 4, + }, + .{ + .opcode = 0x57, + .addressing_mode = .@"Zero Page, X", + .cycles = 4, + }, + .{ + .opcode = 0x77, + .addressing_mode = .@"Zero Page, X", + .cycles = 4, + }, + .{ + .opcode = 0x97, + .addressing_mode = .@"Zero Page, X", + .cycles = 4, + }, + .{ + .opcode = 0xb7, + .addressing_mode = .@"Zero Page, X", + .cycles = 4, + }, + .{ + .opcode = 0xd4, + .addressing_mode = .@"Zero Page, X", + .cycles = 4, + }, + .{ + .opcode = 0xd7, + .addressing_mode = .@"Zero Page, X", + .cycles = 4, + }, + .{ + .opcode = 0xdb, + .addressing_mode = .@"Zero Page, X", + .cycles = 4, + }, + .{ + .opcode = 0xf4, + .addressing_mode = .@"Zero Page, X", + .cycles = 4, + }, + .{ + .opcode = 0xf7, + .addressing_mode = .@"Zero Page, X", + .cycles = 4, + }, + .{ + .opcode = 0x0f, + .addressing_mode = .@"Two Operands", + .cycles = 3, + }, + .{ + .opcode = 0x2f, + .addressing_mode = .@"Two Operands", + .cycles = 3, + }, + .{ + .opcode = 0x4f, + .addressing_mode = .@"Two Operands", + .cycles = 3, + }, + .{ + .opcode = 0x6f, + .addressing_mode = .@"Two Operands", + .cycles = 3, + }, + .{ + .opcode = 0x8f, + .addressing_mode = .@"Two Operands", + .cycles = 3, + }, + .{ + .opcode = 0xaf, + .addressing_mode = .@"Two Operands", + .cycles = 3, + }, + .{ + .opcode = 0xcf, + .addressing_mode = .@"Two Operands", + .cycles = 3, + }, + .{ + .opcode = 0xef, + .addressing_mode = .@"Two Operands", + .cycles = 3, + }, + .{ + .opcode = 0x1f, + .addressing_mode = .Absolute, + .cycles = 4, + }, + .{ + .opcode = 0x3f, + .addressing_mode = .Absolute, + .cycles = 4, + }, + .{ + .opcode = 0x5c, + .addressing_mode = .Absolute, + .cycles = 4, + }, + .{ + .opcode = 0x5f, + .addressing_mode = .Absolute, + .cycles = 4, + }, + .{ + .opcode = 0x7f, + .addressing_mode = .Absolute, + .cycles = 4, + }, + .{ + .opcode = 0x9f, + .addressing_mode = .Absolute, + .cycles = 4, + }, + .{ + .opcode = 0xbf, + .addressing_mode = .Absolute, + .cycles = 4, + }, + .{ + .opcode = 0xdc, + .addressing_mode = .Absolute, + .cycles = 4, + }, + .{ + .opcode = 0xdf, + .addressing_mode = .Absolute, + .cycles = 4, + }, + .{ + .opcode = 0xfc, + .addressing_mode = .Absolute, + .cycles = 4, + }, + .{ + .opcode = 0xff, + .addressing_mode = .Absolute, + .cycles = 4, }, }; diff --git a/src/cpu/opcodes/ora.zig b/src/cpu/opcodes/ora.zig index 3da4d91..847a9ab 100644 --- a/src/cpu/opcodes/ora.zig +++ b/src/cpu/opcodes/ora.zig @@ -52,7 +52,7 @@ pub fn data(comptime CPU: type) type { }, }, // The CMOS part gave this one more to answer to. - .@"65C02", .@"65C816" => &.{ + else => &.{ .{ .opcode = 0x01, .addressing_mode = .@"(Indirect, X)", diff --git a/src/cpu/opcodes/rmb.zig b/src/cpu/opcodes/rmb.zig new file mode 100644 index 0000000..7deada9 --- /dev/null +++ b/src/cpu/opcodes/rmb.zig @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie +// +// SPDX-License-Identifier: MIT + +//! Clearing one bit of a byte in the zero page, and setting it: sixteen +//! instructions between them, one for each bit either way. +//! +//! Rockwell added these to their CMOS part and Western Design kept them; the +//! plain 65C02 has neither, and the encodings do nothing there. They are +//! generated rather than written out because there is nothing to tell one from +//! another but which bit it moves, and thirty-two files saying that would be +//! thirty-two chances to say it wrong. + +/// One of them: which bit, and which way. +pub fn at(comptime which: u3, comptime set: bool) type { + return struct { + pub fn data(comptime CPU: type) type { + return struct { + pub const mnemonic = (if (set) "SMB" else "RMB") ++ .{'0' + @as(u8, which)}; + pub const opcodes = [_]CPU.Opcodes.Init{ + .{ + // The bit is the top three bits of the opcode, and + // whether it is set or cleared is the one above them. + .opcode = (if (set) 0x87 else 0x07) | @as(u8, which) << 4, + .addressing_mode = .@"Zero Page", + .cycles = 5, + }, + }; + + pub fn func(comptime addressing_mode: CPU.AddressingModes) *const fn (*CPU) error{}!void { + if (addressing_mode != .@"Zero Page") @compileError("illegal addressing mode"); + const f = struct { + /// Moves one bit and leaves every flag alone, which is + /// what makes these worth having: a flag byte can be + /// changed without disturbing what is being tested + /// around it. + pub fn move(cpu: *CPU) error{}!void { + const address = cpu.addressing_modes.decode(addressing_mode, .write); + const value = cpu.memory.read(u8, address); + // The CMOS read-modify-write: a second read rather + // than the old value written back. + _ = cpu.memory.read(u8, address); + const bit = @as(u8, 1) << which; + cpu.memory.write(u8, address, if (set) value | bit else value & ~bit); + } + }; + return f.move; + } + }; + } + }; +} diff --git a/src/cpu/opcodes/sbc.zig b/src/cpu/opcodes/sbc.zig index b7d0270..388c795 100644 --- a/src/cpu/opcodes/sbc.zig +++ b/src/cpu/opcodes/sbc.zig @@ -61,7 +61,7 @@ pub fn data(comptime CPU: type) type { }, // The CMOS part took the undocumented duplicate back and gave this // one a pointer with no index instead. - .@"65C02", .@"65C816" => &.{ + else => &.{ .{ .opcode = 0xe1, .addressing_mode = .@"(Indirect, X)", @@ -149,7 +149,7 @@ pub fn data(comptime CPU: type) type { // than binary, which is what it spends putting the answer // and the flags right. The chip drives the address it last // used while it does. - if (CPU.processor != .@"6502" and cpu.flags.isSet(.D)) { + if (CPU.processor.cmos() and cpu.flags.isSet(.D)) { _ = cpu.memory.read(u8, address); } } diff --git a/src/cpu/opcodes/sta.zig b/src/cpu/opcodes/sta.zig index 6cbb297..acf0c10 100644 --- a/src/cpu/opcodes/sta.zig +++ b/src/cpu/opcodes/sta.zig @@ -47,7 +47,7 @@ pub fn data(comptime CPU: type) type { }, }, // The CMOS part gave this one more to answer to. - .@"65C02", .@"65C816" => &.{ + else => &.{ .{ .opcode = 0x81, .addressing_mode = .@"(Indirect, X)", diff --git a/src/cpu/opcodes/stp.zig b/src/cpu/opcodes/stp.zig new file mode 100644 index 0000000..3684dc4 --- /dev/null +++ b/src/cpu/opcodes/stp.zig @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie +// +// SPDX-License-Identifier: MIT + +/// Describes one instruction: its mnemonic, and every opcode that selects +/// it together with that opcode's addressing mode and cycle count. Opcodes +/// collects these at comptime to build the dispatch table. +pub fn data(comptime CPU: type) type { + return struct { + pub const mnemonic = "STP"; + pub const opcodes = [_]CPU.Opcodes.Init{ + .{ + .opcode = 0xdb, + .addressing_mode = .Implied, + .cycles = 3, + }, + }; + + /// The implementation for a single addressing mode. Resolved at + /// comptime so the dispatch table holds a plain function pointer with + /// no mode left to branch on at runtime. + pub fn func(comptime addressing_mode: CPU.AddressingModes) *const fn (*CPU) error{}!void { + if (addressing_mode != .Implied) @compileError("illegal addressing mode"); + const f = struct { + /// Stops until reset. + /// + /// Not a halt in the sense the NMOS part's undocumented jams + /// were, which were a processor left fetching the same byte + /// for ever: this one stops the clock, and a machine built + /// around it draws almost nothing until the reset line moves. + /// + /// The corpus has nothing to say about this one either, for + /// the same reason as WAI. + pub fn STP(cpu: *CPU) error{}!void { + // Two discarded fetches, and then it is not fetching any + // more. + cpu.program_counter.phantomRead(); + cpu.program_counter.phantomRead(); + cpu.stopped = true; + } + }; + return f.STP; + } + }; +} diff --git a/src/cpu/opcodes/wai.zig b/src/cpu/opcodes/wai.zig new file mode 100644 index 0000000..91f3914 --- /dev/null +++ b/src/cpu/opcodes/wai.zig @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie +// +// SPDX-License-Identifier: MIT + +/// Describes one instruction: its mnemonic, and every opcode that selects +/// it together with that opcode's addressing mode and cycle count. Opcodes +/// collects these at comptime to build the dispatch table. +pub fn data(comptime CPU: type) type { + return struct { + pub const mnemonic = "WAI"; + pub const opcodes = [_]CPU.Opcodes.Init{ + .{ + .opcode = 0xcb, + .addressing_mode = .Implied, + .cycles = 3, + }, + }; + + /// The implementation for a single addressing mode. Resolved at + /// comptime so the dispatch table holds a plain function pointer with + /// no mode left to branch on at runtime. + pub fn func(comptime addressing_mode: CPU.AddressingModes) *const fn (*CPU) error{}!void { + if (addressing_mode != .Implied) @compileError("illegal addressing mode"); + const f = struct { + /// Waits until something interrupts. + /// + /// The processor stops fetching and lets the clock run. What + /// wakes it is the interrupt line: if interrupts are enabled + /// it goes to the handler, and if they are not it carries on + /// with the instruction after this one, which is how a program + /// waits for something without a polling loop and without + /// giving up control of what happens next. + /// + /// The corpus has nothing to say about this one: an + /// instruction that waits cannot be recorded a case at a time, + /// and the file for it in the corpus is empty. + pub fn WAI(cpu: *CPU) error{}!void { + // Two discarded fetches, and then it is not fetching any + // more. + cpu.program_counter.phantomRead(); + cpu.program_counter.phantomRead(); + cpu.waiting = true; + } + }; + return f.WAI; + } + }; +} diff --git a/src/instantiation.zig b/src/instantiation.zig index 655fc94..710d8dd 100644 --- a/src/instantiation.zig +++ b/src/instantiation.zig @@ -91,7 +91,8 @@ test "every generic declaration is instantiated" { // a compile error rather than a runtime one. The same goes for the // shapes of the CMOS part's undecoded encodings, which do their own // fetching because there is no address in them to work out. - if (mode == .Implied or mode == .@"No Operand" or mode == .@"Two Operands") continue; + if (mode == .Implied or mode == .@"No Operand" or mode == .@"Two Operands" or + mode == .@"Zero Page, Relative") continue; inline for (.{ .read, .write }) |access| { _ = cpu.addressing_modes.decode(mode, access); } diff --git a/src/main.zig b/src/main.zig index 6764f98..c8084a2 100644 --- a/src/main.zig +++ b/src/main.zig @@ -21,10 +21,16 @@ pub const std_options: std.Options = .{ /// Which processor is in the socket, chosen at build time with -Dprocessor. /// A IIe with a 65C02 in it is an enhanced IIe, which is what the machine was /// sold as from 1985 and what most later software wants. -const Chip = switch (@import("machine").processor) { - .@"6502" => zig65.CPU, - .@"65C02" => zig65.CMOS, -}; +const Chip = struct { + fn of(comptime Clock: type, comptime MemoryModel: fn (type) type) type { + return zig65.Chip(.{ .processor = switch (@import("machine").processor) { + .@"6502" => .@"6502", + .@"65C02" => .@"65C02", + .@"R65C02" => .@"R65C02", + .@"W65C02" => .@"W65C02", + } }, Clock, MemoryModel); + } +}.of; /// Which machine is wrapped around the processor, chosen at build time with /// -Dmachine. The memory model is a comptime parameter, so this cannot be a diff --git a/src/root.zig b/src/root.zig index 7f61856..c489518 100644 --- a/src/root.zig +++ b/src/root.zig @@ -15,6 +15,10 @@ pub const CPU = @import("cpu.zig").CPU; /// undocumented encodings programs written for the older one rely on. pub const CMOS = @import("cpu.zig").CMOS; +/// A processor of whichever kind the options name, for a caller that wants to +/// choose between them rather than name one. +pub const Chip = @import("cpu.zig").Chip; + /// A 6502 with nothing built around it, for tests and for the corpus. pub const Bare = @import("cpu.zig").Bare; @@ -72,10 +76,33 @@ pub const memory = @import("memory.zig"); pub const Processor = enum { /// 6502 @"6502", - /// 65C02 + /// 65C02, the plain CMOS part: what Synertek, NCR and GTE made, and the + /// instructions all the CMOS parts agree on. @"65C02", + /// Rockwell's, which added sixteen instructions for setting and clearing + /// a bit of a zero page byte and sixteen more for branching on one. + @"R65C02", + /// Western Design's, which has Rockwell's and two of its own for stopping + /// the processor: one until an interrupt, one until reset. + @"W65C02", /// 65C816 in 8-bit emulation mode @"65C816", + + /// Whether this is one of the CMOS parts, which is what most of the + /// differences hang off. + pub fn cmos(self: Processor) bool { + return self != .@"6502"; + } + + /// Whether it has Rockwell's bit instructions. + pub fn bits(self: Processor) bool { + return self == .@"R65C02" or self == .@"W65C02"; + } + + /// Whether it can be told to stop. + pub fn stops(self: Processor) bool { + return self == .@"W65C02"; + } }; test {