// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT const std = @import("std"); /// What the instruction means to do with the address, which several of the /// modes need to know: an index that carries out of its low byte costs a cycle /// to put right, and a read can sometimes get away without paying it while a /// write never can, because a write must know where it is going before it /// goes there. pub const Access = enum { read, write }; /// Where an instruction's operand is. /// /// The 6502 had thirteen ways of saying it and the 65816 has these, which is /// most of the difference between the two instruction sets: the same /// instructions, reaching further. Three things are new. A bank can be named /// outright, which is what the long modes do and how anything outside the data /// bank is reached at all. The direct page can be anywhere, so what was the /// zero page is now wherever D points — and if D is not on a page boundary /// every use of it costs a cycle, which is why programs keep it aligned. And /// the stack is addressable, so a compiler has somewhere to put locals, which /// is what the 65816 was for. /// /// `decode` works each of them out, spending the cycles on the bus rather than /// counting them, as the 8-bit core does. pub fn AddressingModes(comptime CPU: type) type { return struct { const Self = @This(); /// The CPU this belongs to, recovered from the field it is embedded in. inline fn getCPU(self: *Self) *CPU { return @alignCast(@fieldParentPtr("addressing_modes", self)); } pub fn init(self: *Self) void { _ = self; } /// The direct page address one byte of operand names. /// /// Two cycles' worth of behaviour in one line of arithmetic. The sum /// is sixteen bits and lands in bank zero however far it wraps, which /// is what makes the direct page a page of bank zero rather than a /// window that can slide out of it. And it costs a cycle whenever the /// low half of D is not zero, because the chip can only add the two /// halves separately then; a program that keeps its direct page on a /// page boundary never pays it, which is most of why they do. fn direct(self: *Self) u16 { const cpu = self.getCPU(); // Where the offset was. The cycle spent adding it keeps that // address on the bus rather than moving on, which is the same // thing REP and SEP do with theirs: an internal cycle holds what // the chip last had a reason to drive. const at = cpu.program_counter.address(); const offset = cpu.program_counter.read(u8); if (cpu.registers.direct & 0x00ff != 0) cpu.memory.internal(at); return cpu.registers.direct +% offset; } /// The direct page address one byte of operand and an index name. /// /// Two cycles rather than one: the penalty for a direct page that is /// not aligned, if it applies, and then one for the indexing itself, /// which is always paid because the chip has to do the addition /// somewhere. /// /// The wrap is the interesting part. In native mode the sum is /// sixteen bits and can move anywhere inside bank zero. In emulation /// mode with the direct page on a page boundary it wraps inside that /// page instead — which is the 6502's zero page indexing, bug and all, /// kept because a program written for the older machine is entitled to /// it. fn directIndexed(self: *Self, comptime index: CPU.Registers.Name) u16 { const cpu = self.getCPU(); const at = cpu.program_counter.address(); const offset = cpu.program_counter.read(u8); const page = cpu.registers.direct; if (page & 0x00ff != 0) cpu.memory.internal(at); cpu.memory.internal(at); const idx = cpu.registers.get(index); if (cpu.flags.emulation and page & 0x00ff == 0) return (page & 0xff00) | (offset +% @as(u8, @truncate(idx))); return page +% offset +% idx; } /// An absolute address with an index added, which may carry out of the /// bank the data bank register named: an array is allowed to run off /// the end of a bank and go on into the next. /// /// Whether the addition costs a cycle depends on three things, and /// the recordings had to settle the third. /// /// A read can start before the high half of the address is known and /// put it right afterwards, so it only pays when the low half carried. /// A write cannot: it must know where it is going before it goes /// there, so it pays every time. And a sixteen-bit index pays whatever /// happens, because then there is no low half to add on its own — the /// whole of the index has to go in before any of the address is /// settled. That last one accounted for one case in eight: exactly the /// ones with a wide index where the low byte happened not to carry. fn absoluteIndexed( self: *Self, comptime index: CPU.Registers.Name, comptime access: Access, ) u24 { const cpu = self.getCPU(); const base = @as(u24, cpu.registers.data_bank) << 16 | cpu.program_counter.read(u16); const idx = cpu.registers.get(index); const effective = base +% idx; const carried = (base & 0x0000ff) + (idx & 0x00ff) > 0xff; if (access == .write or carried or cpu.flags.isClear(.X)) { // The address the chip has built so far, before the high half // is put right. cpu.memory.internal((base & 0xffff00) | (effective & 0x0000ff)); } return effective; } /// Reads a pointer out of the direct page. /// /// Pointers live in bank zero and stay there — the halves of one at /// the very top of the bank come from the top and then the bottom, /// never from bank one — and that is the whole of the rule. There is /// no tighter wrap inside the direct page itself. /// /// This took three goes to believe. The 6502 wrapped a zero page /// pointer inside the zero page, so a pointer at $ff took its high /// byte from $00, and the natural guess is that the 65816 keeps that /// while it is emulating. It does not, and the recordings said so /// three separate times, each on a case so rare it turned up alone: /// once for a long pointer, once for a stack-relative one, once for /// `(dp,X)`. The quirk the emulation mode does keep is in the index /// arithmetic — see `directIndexed` — not in the pointer fetch. fn pointer(self: *Self, comptime T: type, at: u16) T { const cpu = self.getCPU(); var value: T = 0; inline for (0..@typeInfo(T).int.bits / 8) |i| { const step: u16 = @intCast(i); const address: u16 = at +% step; value |= @as(T, cpu.memory.read(address, .data)) << (8 * i); } return value; } /// The stack-relative address one byte of operand names: the stack /// pointer plus it, in bank zero, and a cycle to add them. fn stackRelative(self: *Self) u16 { const cpu = self.getCPU(); const at = cpu.program_counter.address(); const offset = cpu.program_counter.read(u8); cpu.memory.internal(at); return cpu.stack.get() +% offset; } /// A pointer at a stack-relative address, with Y added. /// /// Seven cycles and always seven: a cycle to work out where on the /// stack, two to read the pointer, one more of the chip's own, and /// then the operand. Unlike every other indexed mode there is no /// conditional penalty here — the cycle is spent whether the addition /// carries or not, and whether the index is eight bits or sixteen. fn stackRelativeIndirect(self: *Self) u24 { const cpu = self.getCPU(); const at = self.stackRelative(); const base = @as(u24, cpu.registers.data_bank) << 16 | self.pointer(u16, at); cpu.memory.internal(at +% 1); return base +% cpu.registers.get(.Y); } /// An index added to a pointer that has already been read, which is /// what the four indirect indexed modes end with. /// /// The penalty is the same as the absolute indexed one for the modes /// that only know two bytes of address, and none at all for the long /// ones: when the pointer already said which bank, there is no high /// half left to put right. fn indexPointer( self: *Self, base: u24, comptime access: Access, comptime long: bool, ) u24 { const cpu = self.getCPU(); const idx = cpu.registers.get(.Y); const effective = base +% idx; if (comptime !long) { const carried = (base & 0x0000ff) + (idx & 0x00ff) > 0xff; if (access == .write or carried or cpu.flags.isClear(.X)) cpu.memory.internal((base & 0xffff00) | (effective & 0x0000ff)); } return effective; } /// Works out where the operand is, spending the cycles it takes. /// /// Only the modes the instructions written so far use are worked out. /// The rest are named in the enum because the enum is the list of what /// this processor can do, and one that is not implemented is a compile /// error at the instruction that asks for it rather than something /// that quietly returns a wrong address. pub fn decode(self: *Self, comptime mode: Modes, comptime access: Access) u24 { const cpu = self.getCPU(); return switch (mode) { // The value follows the opcode. Nothing to work out: this // hands back where it is, and the instruction reads it itself, // because how much of it to read is not this function's // business. .Immediate => cpu.program_counter.address(), // One byte, added to the direct page register, in bank zero. .@"Direct Page" => self.direct(), .@"Direct Page, X" => self.directIndexed(.X), .@"Direct Page, Y" => self.directIndexed(.Y), // Two bytes, in whichever bank the data bank register names. .Absolute => @as(u24, cpu.registers.data_bank) << 16 | cpu.program_counter.read(u16), .@"Absolute, X" => self.absoluteIndexed(.X, access), .@"Absolute, Y" => self.absoluteIndexed(.Y, access), // A pointer in the direct page, pointing into the data bank. .@"(Direct Page)" => @as(u24, cpu.registers.data_bank) << 16 | self.pointer(u16, self.direct()), // The pointer is chosen by indexing, and then points where it // points; the index is spent before the pointer is read rather // than after. .@"(Direct Page, X)" => @as(u24, cpu.registers.data_bank) << 16 | self.pointer(u16, self.directIndexed(.X)), // And here the other way round: the pointer says where the // array starts and Y says how far into it, which is the pair // every loop over a table is written with. .@"(Direct Page), Y" => self.indexPointer( @as(u24, cpu.registers.data_bank) << 16 | self.pointer(u16, self.direct()), access, false, ), // Three bytes of pointer, so the bank comes out of memory // rather than out of a register: this reaches anywhere. .@"[Direct Page]" => self.pointer(u24, self.direct()), // And indexed, which is how an array longer than a bank is // walked. No cycle for the addition: the bank is already known. .@"[Direct Page], Y" => self.indexPointer(self.pointer(u24, self.direct()), access, true), // One byte, added to the stack pointer, in bank zero. .@"Stack Relative" => self.stackRelative(), // A pointer at a stack-relative address, then indexed: a // compiler's way of reaching through a pointer it put in a // local. .@"(Stack Relative), Y" => self.stackRelativeIndirect(), // Three bytes: the whole address, bank and all, and the only // mode that reaches anywhere without arranging anything first. .@"Absolute Long" => cpu.program_counter.read(u24), // Indexed, and no cycle for it either way: the bank is already // in hand, so there is no high half to put right afterwards. .@"Absolute Long, X" => cpu.program_counter.read(u24) +% cpu.registers.get(.X), else => @compileError("addressing mode " ++ @tagName(mode) ++ " is not implemented yet"), }; } /// Whether a two-byte access at this mode's address keeps both halves /// inside bank zero. /// /// The direct page is a page of bank zero and stays there: a word at /// the very top of it takes its high half from the bottom of the same /// bank rather than from the next one. Everywhere else the address /// simply counts on, carrying into the bank as it goes, which is how a /// structure is allowed to straddle a bank boundary. pub fn wrapsInBankZero(comptime mode: Modes) bool { return switch (mode) { .@"Direct Page", .@"Direct Page, X", .@"Direct Page, Y", .@"Stack Relative", => true, else => false, }; } /// Reads the operand at whatever width the instruction is using, /// spending a cycle per byte. Low half first, as everything on this /// family is. pub fn readData(self: *Self, comptime mode: Modes, comptime T: type, address: u24) T { const cpu = self.getCPU(); switch (@typeInfo(T).int.bits) { 8 => return cpu.memory.read(address, .data), 16 => { const low: u16 = cpu.memory.read(address, .data); const high: u16 = cpu.memory.read(next(mode, address), .data); return high << 8 | low; }, else => @compileError("must be a u8 or a u16"), } } /// Writes the operand at whatever width the instruction is using. Low /// half first, which is the order the recordings show and not /// something to guess at: a write is two separate cycles and anything /// watching the bus sees which came first. pub fn writeData(self: *Self, comptime mode: Modes, comptime T: type, address: u24, value: T) void { const cpu = self.getCPU(); switch (@typeInfo(T).int.bits) { 8 => cpu.memory.write(address, value, .data), 16 => { cpu.memory.write(address, @truncate(value), .data); cpu.memory.write(next(mode, address), @truncate(value >> 8), .data); }, else => @compileError("must be a u8 or a u16"), } } /// Writes the operand back the other way round: high half first. /// /// A read-modify-write reverses the order an ordinary store uses, and /// it is not a detail an emulator can decide for itself — the two /// writes are two cycles, and anything watching the bus sees which /// came first. It follows the shape of the instruction: the last byte /// read is the first written, so the chip never has to hold an address /// it is not already driving. pub fn writeDataReversed(self: *Self, comptime mode: Modes, comptime T: type, address: u24, value: T) void { const cpu = self.getCPU(); switch (@typeInfo(T).int.bits) { 8 => cpu.memory.write(address, value, .data), 16 => { cpu.memory.write(next(mode, address), @truncate(value >> 8), .data); cpu.memory.write(address, @truncate(value), .data); }, else => @compileError("must be a u8 or a u16"), } } /// The address of the high half, which is the low one plus a byte /// under whichever wrapping rule the mode follows. Public because a /// read-modify-write wants to know which address the chip last drove /// before it spends its cycle thinking. pub fn next(comptime mode: Modes, address: u24) u24 { if (comptime wrapsInBankZero(mode)) { const low: u16 = @truncate(address); return low +% 1; } return address +% 1; } }; } /// Every way a 65816 instruction can name its operand. /// /// Kept as a free declaration rather than inside the generic above so that the /// CPU can name it before it has finished being a type. pub const Modes = enum { /// Nothing to name: the instruction is the whole of it. Implied, /// The accumulator, which is not addressed so much as meant. Accumulator, /// The value itself follows the opcode. One byte or two, depending on /// which of M and X the instruction answers to, which is the first place /// the width flags stop being bookkeeping and start deciding how long an /// instruction is. Immediate, /// A pushed or pulled value, at the stack pointer. Stack, /// Two bytes of address, in the data bank. Absolute, /// The same, plus X. @"Absolute, X", /// And plus Y. @"Absolute, Y", /// A pointer at an absolute address in bank zero. Only the jumps use it. @"(Absolute)", /// A pointer at an absolute address plus X, in the program bank: a jump /// table, indexed, without the self-modifying code the 6502 needed. @"(Absolute, X)", /// A pointer at an absolute address in bank zero, three bytes of it, so /// the jump can leave the bank. @"[Absolute]", /// Three bytes of address: the whole of it, bank included. The one mode /// that can reach anywhere without arranging anything first. @"Absolute Long", /// The same, plus X. @"Absolute Long, X", /// One byte, added to the direct page register. What the zero page became /// when it was allowed to move. @"Direct Page", /// The same, plus X. @"Direct Page, X", /// And plus Y. @"Direct Page, Y", /// A pointer in the direct page, pointing into the data bank. @"(Direct Page)", /// A pointer in the direct page, chosen by adding X. @"(Direct Page, X)", /// A pointer in the direct page, then Y added to what it points at. @"(Direct Page), Y", /// A three-byte pointer in the direct page: the pointer says the bank /// too, so this reaches anywhere. @"[Direct Page]", /// The same, then Y added to what it points at. This is how a 65816 /// program walks an array that is bigger than a bank. @"[Direct Page], Y", /// One byte, added to the stack pointer. Where a compiler puts a local. @"Stack Relative", /// A pointer at a stack-relative address, then Y added to it. Where a /// compiler puts a pointer to something bigger. @"(Stack Relative), Y", /// A signed byte, counted from the instruction after the branch: 127 /// forward and 128 back, as before. Relative, /// A signed word, which reaches anywhere in the bank. The 6502's answer to /// a distant branch was to jump over a jump; BRL made that unnecessary. @"Relative Long", /// Two bank bytes, for the block moves. Neither is an address: they say /// which bank to move from and which to move to, and the registers say the /// rest. @"Block Move", }; test "the enum lists every mode the datasheet does, and splits one it folds" { // Twenty-five, where the data sheet counts twenty-four against the // W65C02S's thirteen. The one extra is the long indirect jump: section // 3.5.5 gives `(a)` and `[a]` one entry between them, since the second and // third bytes are read the same way and only the third byte of the pointer // tells them apart, and they are separate here because the operand syntax // differs and only one of them loads the program bank register. // // Worth pinning either way: a mode that quietly goes missing is an // instruction that cannot be described. // // (Western Design Center, 2018, Section 3.5) try std.testing.expectEqual(25, @typeInfo(Modes).@"enum".fields.len); }