// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT const std = @import("std"); /// The 65816's processor status register, and the emulation line beside it. /// /// Where the 6502 had a break flag and an unused bit, this has M and X: the /// two that say how wide the accumulator and the index registers are at this /// moment. They are ordinary bits of P, in the same positions — M is bit 5 and /// X is bit 4 — which is what makes REP and SEP able to change the width of /// the machine with one instruction. /// /// The emulation line is not a bit of P at all. It is kept here because it /// behaves like one and because everything that reads the width lines wants it /// alongside them, but it is reached only through XCE, which swaps it with the /// carry. While it is set the processor is a 6502: M and X are forced set, the /// index registers are eight bits, and the stack lives in page one. /// /// Each flag is kept separately rather than packed, with the byte assembled /// only when something pushes or reads it, and each carries the cycle it last /// changed on so the debugger can highlight it. Embedded in CPU, and finds its /// way back to it with @fieldParentPtr rather than holding a pointer, so the /// whole processor can be built in place. pub fn Flags(comptime CPU: type) type { return struct { const Self = @This(); pub const Name = enum { /// negative N, /// overflow V, /// eight-bit accumulator, bit 5 M, /// eight-bit index registers, bit 4 X, /// decimal mode D, /// interrupt disable I, /// zero Z, /// carry C, }; /// Which bit of the status byte each flag is. Public because REP and /// SEP take a mask written in exactly these terms. pub fn bitOf(comptime name: Name) u8 { return switch (name) { .N => 0x80, .V => 0x40, .M => 0x20, .X => 0x10, .D => 0x08, .I => 0x04, .Z => 0x02, .C => 0x01, }; } _values: std.EnumArray(Name, bool), _changed: std.EnumArray(Name, u64), /// The emulation line. Set is a 6502; clear is the processor this /// actually is. A reset sets it, so every 65816 starts up pretending. emulation: bool, /// The CPU this belongs to, recovered from the field it is embedded in. inline fn getCPU(self: *Self) *CPU { return @alignCast(@fieldParentPtr("flags", self)); } /// Clears every flag, for a CPU that is not running yet. Emulation is /// set, which is where the processor comes up. pub fn init(self: *Self) void { self.* = .{ ._values = .initFill(false), ._changed = .initFill(0), .emulation = true, }; self.setEmulation(true); } /// As init, but timestamps against the running clock. A reset puts the /// processor back into emulation mode and sets the interrupt disable, /// as the hardware does. pub fn reset(self: *Self) void { const cpu = self.getCPU(); self._values = .initFill(false); self._changed = .initFill(cpu.clock.read()); self._values.set(.I, true); self._values.set(.D, false); self.setEmulation(true); } /// Reads a flag. pub fn isSet(self: *const Self, comptime name: Name) bool { return self._values.get(name); } /// Reads a flag the other way round, which reads better at some call /// sites than negating the above. pub fn isClear(self: *const Self, comptime name: Name) bool { return !self._values.get(name); } /// Writes a flag and records when it changed. pub fn update(self: *Self, comptime name: Name, value: bool) void { const cpu = self.getCPU(); self._changed.set(name, cpu.clock.read()); self._values.set(name, value); // Narrowing the index registers throws away what was in their // high halves. The chip does this the moment the flag is set, not // the next time they are used, so a program that sets X and clears // it again has lost the high bytes in between. if (name == .X and value) cpu.registers.narrowIndexes(); // Under the table dispatch the widths choose which table is in // force, so a change to one of them is the moment to re-point it. if (name == .M or name == .X) cpu.selectTable(); } pub fn set(self: *Self, comptime name: Name) void { self.update(name, true); } pub fn clear(self: *Self, comptime name: Name) void { self.update(name, false); } /// How many cycles ago the flag last changed. pub fn changed(self: *Self, comptime name: Name) u64 { const cpu = self.getCPU(); return cpu.clock.read() - self._changed.get(name); } /// Moves the processor between emulation and native mode. /// /// Going into emulation forces both width flags set, because a 6502 /// has no other width, and puts the stack pointer back into page one. /// Coming out of it leaves them where they were, which is set, so a /// program that wants sixteen bits asks for them with REP afterwards. pub fn setEmulation(self: *Self, value: bool) void { const cpu = self.getCPU(); self.emulation = value; if (value) { self.update(.M, true); self.update(.X, true); } cpu.stack.normalize(); } /// Sets N and Z from a result, at whatever width the operation was. pub fn updateNZ(self: *Self, comptime T: type, value: T) void { const bits = @typeInfo(T).int.bits; self.update(.Z, value == 0); self.update(.N, value & (@as(T, 1) << (bits - 1)) != 0); } /// The status register as one byte, which is what the stack and the /// debugger see. /// /// In emulation mode M and X are forced set, so bits 5 and 4 read as /// ones, which is exactly what the 6502's unused bit and break flag /// read as when that machine pushes its own status. pub fn dump(self: *const Self) u8 { var value: u8 = 0; inline for (comptime std.enums.values(Name)) |name| { if (self._values.get(name)) value |= comptime bitOf(name); } return value; } /// Sets every flag from one byte. In emulation mode the width flags /// are not the caller's to choose. pub fn load(self: *Self, value: u8) void { inline for (comptime std.enums.values(Name)) |name| { self.update(name, (value & comptime bitOf(name)) != 0); } if (self.emulation) { self.update(.M, true); self.update(.X, true); } } /// Whether the status register matches a byte, for the corpus. pub fn compare(self: *const Self, value: u8) bool { return self.dump() == value; } /// Writes a status byte the way the debugger and the corpus reports /// show it: a letter per flag, capital for set. pub fn format(_: *const Self, writer: *std.Io.Writer, value: u8) !void { inline for (comptime std.enums.values(Name)) |name| { const letter = @tagName(name)[0]; const set_ = (value & comptime bitOf(name)) != 0; try writer.writeByte(if (set_) letter else std.ascii.toLower(letter)); } } }; } test "M and X are bits five and four, and emulation forces them" { const CPU = @import("../cpu16.zig").Bare; var cpu: CPU = undefined; try cpu.init(std.testing.allocator, null); defer cpu.deinit(); // A native-mode status byte from the corpus: ea.n case 1 has p = 170. cpu.flags.setEmulation(false); cpu.flags.load(170); try std.testing.expect(cpu.flags.isSet(.N)); try std.testing.expect(cpu.flags.isClear(.V)); try std.testing.expect(cpu.flags.isSet(.M)); try std.testing.expect(cpu.flags.isClear(.X)); try std.testing.expectEqual(@as(u8, 170), cpu.flags.dump()); // And an emulation-mode one: ea.e case 1 has p = 122, where bits five and // four are set because the width flags cannot be anything else. cpu.flags.setEmulation(true); cpu.flags.load(122 & ~@as(u8, 0x30)); try std.testing.expectEqual(@as(u8, 122), cpu.flags.dump()); }