// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! 6502 addition & subtraction //! based on https://github.com/aniou/morfeo/blob/master/doc/6502-ADC-SBC-implementation.rst const std = @import("std"); const shl = std.math.shl; const shr = std.math.shr; const assert = std.debug.assert; const Processor = @import("../root.zig").Processor; pub const Result = struct { A: u8, C: bool, N: bool, Z: bool, V: bool, }; const Operation = enum { adc, sbc, }; const Nibble = enum { low, high, }; /// Overflow: set when two operands of the same sign produce a result of the /// other sign. inline fn test_V(augend: u8, addend: u8, binary_sum: u8) bool { const arg_sign_eq = (augend ^ addend) & 0x80 == 0; const prod_sign_neq = (addend ^ binary_sum) & 0x80 != 0; return arg_sign_eq and prod_sign_neq; } /// Negative: bit 7 of the result. inline fn test_N(a: u8) bool { return a & 0x80 == 0x80; } /// Zero: whether the result is zero. inline fn test_Z(a: u8) bool { return a == 0; } const CarryResult = struct { carry_flag: bool, decimal_carry_flag: bool, }; /// Carry out of a nibble. Decimal mode carries at 9 rather than 15, and /// subtraction always uses the binary answer because its correction happens /// afterwards. inline fn compute_carry(tmp: u8, decimal_flag: bool, comptime operation: Operation) CarryResult { const binary_carry_flag = tmp > 0x0f; const decimal_carry_flag = tmp > 0x09; return switch (operation) { .adc => .{ .carry_flag = (decimal_flag and decimal_carry_flag) or binary_carry_flag, .decimal_carry_flag = decimal_carry_flag, }, .sbc => .{ .carry_flag = binary_carry_flag, .decimal_carry_flag = decimal_carry_flag, }, }; } /// Pulls a nibble back into range after a decimal add or subtract, by 6 in the /// direction of the operation. The 65C02 takes an extra step off the high /// nibble that the 6502 does not. inline fn decimal_correction( a: u4, carry_result: CarryResult, decimal_flag: bool, comptime operation: Operation, comptime processor: Processor, comptime nibble: Nibble, ) u4 { switch (operation) { .adc => { if (decimal_flag and carry_result.carry_flag) return a +% 0x6; return a; }, .sbc => { if (!decimal_flag) return a; var tmp = a; if (!carry_result.carry_flag) tmp -%= 0x6; if (nibble == .low) return tmp; if (processor != .@"65C02") return tmp; if (carry_result.decimal_carry_flag) tmp -%= 0x1; return tmp; }, } unreachable; } const PartialResult = struct { binary_sum: u4, decimal_corrected_sum: u4, carry_result: CarryResult, }; /// Adds one nibble, giving both the raw binary answer and the decimal corrected /// one, since the flags come from one and the result from the other. inline fn compute_partial( augend: u4, addend: u4, carry_result: CarryResult, decimal_flag: bool, comptime operation: Operation, comptime processor: Processor, comptime nibble: Nibble, ) PartialResult { const tmp: u8 = @as(u8, @intCast(augend)) + @as(u8, @intCast(addend)) + @intFromBool(carry_result.carry_flag); const binary_sum: u4 = @truncate(tmp); const new_carry_result = compute_carry(tmp, decimal_flag, operation); const decimal_corrected_sum = decimal_correction( binary_sum, new_carry_result, decimal_flag, operation, processor, nibble, ); return .{ .binary_sum = binary_sum, .decimal_corrected_sum = decimal_corrected_sum, .carry_result = new_carry_result, }; } /// The whole of the 6502's addition and subtraction, a nibble at a time. /// /// Subtraction is addition of the complement, so the caller passes ~addend and /// the operation only changes how carry and the decimal correction behave. The /// flags come from the binary sum even in decimal mode, which is why both are /// carried through: it is what makes N and V meaningless but predictable on a /// decimal ADC. pub fn add(augend: u8, addend: u8, carry_flag: bool, decimal_flag: bool, comptime operation: Operation, comptime processor: Processor) Result { // On Ricoh's part the flag is there but the correction is not on the die, // so the sum is the binary one however the caller found the flag. Gating // it here rather than at the call sites keeps the one place that knows // what the D flag means the only place that has to know this. const decimal = decimal_flag and comptime processor.decimal(); // The CMOS part does decimal arithmetic properly, which means the flags // as well as the digits: N and Z are about the answer it arrived at // 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.cmos() and decimal) { return switch (operation) { .adc => decimalAdd(augend, addend, carry_flag), .sbc => decimalSubtract(augend, ~addend, carry_flag), }; } const augend_l: u4 = @truncate(augend); const augend_h: u4 = @truncate(augend >> 4); const addend_l: u4 = @truncate(addend); const addend_h: u4 = @truncate(addend >> 4); const partial_result_l = compute_partial( augend_l, addend_l, .{ .carry_flag = carry_flag, .decimal_carry_flag = carry_flag, }, decimal, operation, processor, .low, ); const partial_result_h = compute_partial( augend_h, addend_h, partial_result_l.carry_result, decimal, operation, processor, .high, ); const binary_sum = shl(u8, partial_result_h.binary_sum, 4) | partial_result_l.binary_sum; const decimal_corrected_sum = shl(u8, partial_result_h.decimal_corrected_sum, 4) | partial_result_l.decimal_corrected_sum; return .{ .A = decimal_corrected_sum, .C = partial_result_h.carry_result.carry_flag, .N = test_N(binary_sum), .Z = test_Z(binary_sum), .V = test_V(augend, addend, binary_sum), }; } /// Decimal addition on the CMOS part: a digit at a time, each corrected as it /// is made, and the flags taken from what came out. /// /// Correcting the whole byte at once gives the same answer for digits that are /// really digits and the wrong one for the six values a nibble can hold that /// are not, which programs do use: the numbers below reproduce every decimal /// case in the SingleStepTests corpus, including those. fn decimalAdd(augend: u8, addend: u8, carry_flag: bool) Result { var low: u16 = @as(u16, augend & 0x0f) + (addend & 0x0f) + @intFromBool(carry_flag); if (low > 9) low += 6; var high: u16 = @as(u16, augend >> 4) + (addend >> 4) + @intFromBool(low > 0x0f); // Overflow is worked out from the high digit as it stands before it is // corrected, which is why it means so little after a decimal add and is // still worth reproducing exactly. const uncorrected: u8 = @truncate(high << 4); const overflow = ~(augend ^ addend) & (augend ^ uncorrected) & 0x80 != 0; if (high > 9) high += 6; const value: u8 = @truncate((high << 4) | (low & 0x0f)); return .{ .A = value, .C = high > 0x0f, .N = value & 0x80 != 0, .Z = value == 0, .V = overflow, }; } /// Decimal subtraction on the CMOS part. The correction goes the other way and /// is applied to the whole byte rather than digit by digit, which is what the /// corpus says the chip does. fn decimalSubtract(minuend: u8, subtrahend: u8, carry_flag: bool) Result { const borrow: i16 = @intFromBool(!carry_flag); const binary: i16 = @as(i16, minuend) - subtrahend - borrow; var corrected: i16 = binary & 0xff; if (@as(i16, minuend & 0x0f) - borrow < subtrahend & 0x0f) corrected -= 6; if (binary < 0) corrected -= 0x60; const value: u8 = @truncate(@as(u16, @bitCast(corrected))); const wrapped: u8 = @truncate(@as(u16, @bitCast(binary))); return .{ .A = value, .C = binary >= 0, .N = value & 0x80 != 0, .Z = value == 0, .V = (minuend ^ subtrahend) & (minuend ^ wrapped) & 0x80 != 0, }; } test "add 1" { const r = add(0x1, 0x1, false, false, .adc, .@"6502"); try std.testing.expectEqual(2, r.A); } test "sub 1" { const a: u8 = 0x02; const b: u8 = 0x01; const r = add(a, ~b, true, false, .sbc, .@"6502"); try std.testing.expectEqual(1, r.A); } test "sub 2" { const a: u8 = 0xa1; const b: u8 = 0x33; const r = add(a, b, false, true, .sbc, .@"6502"); try std.testing.expectEqual(0x7e, r.A); } test "the decimal flag does nothing on Ricoh's part" { // 0x19 + 0x01 is 0x20 in decimal and 0x1a in binary. The NMOS part with // the flag set gives the first, Ricoh's gives the second, and the two // agree the moment the flag is clear. try std.testing.expectEqual(0x20, add(0x19, 0x01, false, true, .adc, .@"6502").A); try std.testing.expectEqual(0x1a, add(0x19, 0x01, false, true, .adc, .RP2A03).A); try std.testing.expectEqual(0x1a, add(0x19, 0x01, false, false, .adc, .@"6502").A); try std.testing.expectEqual(0x1a, add(0x19, 0x01, false, false, .adc, .RP2A03).A); // And subtraction the same way: 0x32 - 0x01 is 0x31 either way, so take a // pair that a borrow out of the low nibble tells apart. 0x30 - 0x01 is // 0x29 in decimal and 0x2f in binary. try std.testing.expectEqual(0x29, add(0x30, ~@as(u8, 0x01), true, true, .sbc, .@"6502").A); try std.testing.expectEqual(0x2f, add(0x30, ~@as(u8, 0x01), true, true, .sbc, .RP2A03).A); }