huc6280/
alu.rs

1//! Arithmetic, logic, compare and bit test: ADC SBC AND ORA EOR CMP CPX CPY
2//! BIT (`_alu.py`).
3//!
4//! `ORA`, `AND`, `EOR` and `ADC` honour the T flag (U4): with T set the
5//! accumulator is replaced by the zero-page byte at X (logical `$2000 + X`),
6//! the result goes back there, A is untouched and the instruction takes three
7//! more cycles (read, internal, write). `SBC` does not (C5: SW's entry has no
8//! T clause; MAME's yes is a guess), unless `sbc_honours_t` is set.
9//!
10//! Decimal mode (U14, HW HB-4, SW `ADC`): one more cycle, N, Z and C taken
11//! from the decimal result, **V left alone**. How invalid digits adjust is
12//! C13: neither manual says. `decimal_formula` picks the digit adjust. The
13//! default, `Mednafen`, gives the results Mednafen's HuC6280 gives
14//! ("corrected ... per tests on a HuC6280", its ChangeLog, 2015-04-29: the
15//! one author statement of hardware testing); `Mesen` gives Mesen's, the
16//! results the 640,000-case SingleStepTests corpus was made with. They
17//! differ only with an invalid BCD digit (the reference's docs/issues/0004).
18//! Both are transcribed from the reference's own routines, which were
19//! written from the rules stated in words there and checked against recorded
20//! result tables; neither emulator's code is copied.
21//!
22//! Differences forced by Rust: the digit arithmetic is done in `i32`, with
23//! `rem_euclid` where the reference's `%` meets a negative number (Python's
24//! `%` takes the sign of the divisor); an unknown formula cannot be named,
25//! so the reference's `ValueError` has no counterpart.
26
27use crate::core::{Bus, HuC6280, C, D, N, V, Z, ZERO_PAGE};
28use crate::dispatch::Mode;
29
30/// C13: the decimal digit adjust of ADC and SBC (`decimal_formula`).
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub enum DecimalFormula {
33    /// The default: the results Mednafen gives.
34    Mednafen,
35    /// The results Mesen gives, which the SingleStepTests corpus records.
36    Mesen,
37}
38
39/// N and Z for a result that has not been masked to 8 bits yet.
40fn nz(value: i32) -> u8 {
41    (value as u8 & N) | if value & 0xFF != 0 { 0 } else { Z }
42}
43
44/// The decimal sum before masking: 256 and up is the carry out.
45///
46/// Written from the rule each emulator's result table follows (the
47/// reference's docs/issues/0004 states both in words), digit by digit; no
48/// emulator's source is reproduced here.
49fn decimal_add(a: i32, operand: i32, carry: i32, formula: DecimalFormula) -> i32 {
50    let mut ones = a % 16 + operand % 16 + carry;
51    let sixteens = a / 16 + operand / 16;
52    if ones >= 10 {
53        ones += 6; // a digit past 9 skips the six unused codes
54    }
55    let mut total = match formula {
56        // Everything the ones digit overflowed by is carried, however much that is.
57        DecimalFormula::Mednafen => 16 * sixteens + ones,
58        // One carry at most, and only the low four bits of the ones digit are kept.
59        DecimalFormula::Mesen => 16 * (sixteens + if ones >= 16 { 1 } else { 0 }) + ones % 16,
60    };
61    if total >= 0xA0 {
62        total += 0x60;
63    }
64    total
65}
66
67/// The decimal difference: 256 and up means no borrow (carry out). Written as above.
68fn decimal_subtract(a: i32, operand: i32, carry: i32, formula: DecimalFormula) -> i32 {
69    match formula {
70        DecimalFormula::Mednafen => {
71            // Digit differences with a borrow between them; each digit that
72            // borrowed is corrected (by 6, by $60) on the assembled byte,
73            // modulo 256.
74            let ones = a % 16 - operand % 16 - (1 - carry);
75            let sixteens = a / 16 - operand / 16 - if ones < 0 { 1 } else { 0 };
76            let mut byte = 16 * sixteens.rem_euclid(16) + ones.rem_euclid(16);
77            if ones < 0 {
78                byte -= 0x06;
79            }
80            if sixteens < 0 {
81                byte -= 0x60;
82            }
83            byte.rem_euclid(256) + if sixteens < 0 { 0 } else { 256 }
84        }
85        DecimalFormula::Mesen => {
86            // The sum with the operand's complement; a digit that produced no
87            // carry is corrected before the next is formed, and the
88            // correction is not reduced modulo 256 here.
89            let complement = 255 - operand;
90            let mut ones = a % 16 + complement % 16 + carry;
91            if ones < 16 {
92                ones -= 6;
93            }
94            let mut total = 16 * (a / 16 + complement / 16 + if ones >= 16 { 1 } else { 0 })
95                + ones.rem_euclid(16);
96            if total < 256 {
97                total -= 0x60;
98            }
99            total
100        }
101    }
102}
103
104/// A + operand + C, binary or decimal; return (result, P).
105pub fn add(a: u8, operand: u8, p: u8, formula: DecimalFormula) -> (u8, u8) {
106    let (a, operand) = (a as i32, operand as i32);
107    let carry = (p & C) as i32;
108    let mut p = p;
109    let result;
110    if p & D != 0 {
111        result = decimal_add(a, operand, carry, formula);
112        p &= !(N | Z | C); // V is unchanged in decimal mode (U14)
113    } else {
114        result = a + operand + carry;
115        p &= !(N | V | Z | C);
116        if !(a ^ operand) & (a ^ result) & 0x80 != 0 {
117            p |= V;
118        }
119    }
120    if result > 0xFF {
121        p |= C;
122    }
123    (result as u8, p | nz(result))
124}
125
126/// A - operand - (1 - C), binary or decimal; return (result, P).
127pub fn subtract(a: u8, operand: u8, p: u8, formula: DecimalFormula) -> (u8, u8) {
128    let (a, operand) = (a as i32, operand as i32);
129    let carry = (p & C) as i32;
130    let mut p = p;
131    let result;
132    if p & D != 0 {
133        result = decimal_subtract(a, operand, carry, formula);
134        p &= !(N | Z | C);
135    } else {
136        let inverted = !operand & 0xFF;
137        result = a + inverted + carry;
138        p &= !(N | V | Z | C);
139        if !(a ^ inverted) & (a ^ result) & 0x80 != 0 {
140            p |= V;
141        }
142    }
143    if result > 0xFF {
144        p |= C;
145    }
146    (result as u8, p | nz(result))
147}
148
149/// ADC's or SBC's arithmetic: [`add`] or [`subtract`].
150type Arithmetic = fn(u8, u8, u8, DecimalFormula) -> (u8, u8);
151
152impl<B: Bus> HuC6280<B> {
153    /// U4: T set, so the operation's other operand is M($2000 + X) and the
154    /// result goes back.
155    ///
156    /// The three extra cycles are a read, an internal cycle (two in decimal
157    /// mode, where the adjust takes one more) and a write.
158    fn memory_mode(
159        &mut self,
160        operand: u8,
161        operation: impl FnOnce(&mut Self, u8, u8) -> u8,
162        extra_cycle: bool,
163    ) {
164        let address = ZERO_PAGE | self.x as u16;
165        let memory = self.cycle_read(address);
166        self.io();
167        if extra_cycle {
168            self.io();
169        }
170        let result = operation(self, memory, operand);
171        self.set_nz(result);
172        self.cycle_write(address, result);
173    }
174
175    /// ORA -- A OR M -> A, or M(X) OR M -> M(X) with T set (SW SB-58).
176    #[inline(always)]
177    pub(crate) fn op_ora(&mut self, mode: Mode) {
178        let address = self.ea(mode);
179        let operand = self.load(address);
180        if self.t != 0 {
181            self.memory_mode(operand, |_, memory, value| memory | value, false);
182        } else {
183            self.a = self.set_nz(self.a | operand);
184        }
185    }
186
187    /// AND -- A AND M -> A, or M(X) AND M -> M(X) with T set (SW SB-18).
188    #[inline(always)]
189    pub(crate) fn op_and(&mut self, mode: Mode) {
190        let address = self.ea(mode);
191        let operand = self.load(address);
192        if self.t != 0 {
193            self.memory_mode(operand, |_, memory, value| memory & value, false);
194        } else {
195            self.a = self.set_nz(self.a & operand);
196        }
197    }
198
199    /// EOR -- A EOR M -> A, or M(X) EOR M -> M(X) with T set (SW SB-47).
200    #[inline(always)]
201    pub(crate) fn op_eor(&mut self, mode: Mode) {
202        let address = self.ea(mode);
203        let operand = self.load(address);
204        if self.t != 0 {
205            self.memory_mode(operand, |_, memory, value| memory ^ value, false);
206        } else {
207            self.a = self.set_nz(self.a ^ operand);
208        }
209    }
210
211    #[inline(always)]
212    fn arithmetic(&mut self, mode: Mode, operation: Arithmetic, uses_t: bool) {
213        let address = self.ea(mode);
214        let operand = self.load(address);
215        let decimal = self.p & D != 0;
216        if uses_t && self.t != 0 {
217            // The adjust's extra cycle (U14) sits among the memory-mode cycles.
218            self.memory_mode(
219                operand,
220                |cpu, memory, value| {
221                    let (result, p) = operation(memory, value, cpu.p, cpu.decimal_formula);
222                    cpu.p = p;
223                    result
224                },
225                decimal,
226            );
227            return;
228        }
229        if decimal {
230            // U14: the extra cycle. A dummy read at the next opcode, or an
231            // internal cycle for SBC while T is set (it does not use the
232            // memory mode but keeps its cycle; Mesen).
233            if self.t != 0 {
234                self.io();
235            } else {
236                self.dummy(self.pc);
237            }
238        }
239        (self.a, self.p) = operation(self.a, operand, self.p, self.decimal_formula);
240    }
241
242    /// ADC -- A + M + C -> A, or M(X) + M + C -> M(X) with T set (SW SB-17).
243    #[inline(always)]
244    pub(crate) fn op_adc(&mut self, mode: Mode) {
245        self.arithmetic(mode, add, true);
246    }
247
248    /// SBC -- A - M - (1 - C) -> A; T is ignored (C5) (SW SB-74).
249    #[inline(always)]
250    pub(crate) fn op_sbc(&mut self, mode: Mode) {
251        self.arithmetic(mode, subtract, self.sbc_honours_t);
252    }
253
254    fn compare(&mut self, register: u8, operand: u8) {
255        let difference = register.wrapping_sub(operand);
256        let mut p = self.p & !(N | Z | C);
257        if register >= operand {
258            p |= C;
259        }
260        self.p = p | crate::core::nz(difference);
261    }
262
263    /// CMP -- A - M, flags only (SW SB-41).
264    #[inline(always)]
265    pub(crate) fn op_cmp(&mut self, mode: Mode) {
266        let address = self.ea(mode);
267        let operand = self.load(address);
268        self.compare(self.a, operand);
269    }
270
271    /// CPX -- X - M, flags only (SW SB-42).
272    #[inline(always)]
273    pub(crate) fn op_cpx(&mut self, mode: Mode) {
274        let address = self.ea(mode);
275        let operand = self.load(address);
276        self.compare(self.x, operand);
277    }
278
279    /// CPY -- Y - M, flags only (SW SB-43).
280    #[inline(always)]
281    pub(crate) fn op_cpy(&mut self, mode: Mode) {
282        let address = self.ea(mode);
283        let operand = self.load(address);
284        self.compare(self.y, operand);
285    }
286
287    fn bit_flags(&mut self, operand: u8, mask_with: u8) {
288        // U19: N and V come from the operand, Z from the AND; HW HB-5, SW BIT.
289        let mut p = (self.p & !(N | V | Z)) | (operand & (N | V));
290        if mask_with & operand == 0 {
291            p |= Z;
292        }
293        self.p = p;
294    }
295
296    /// BIT -- A AND M sets Z; M bits 7 and 6 -> N and V, immediate form too
297    /// (U19) (SW SB-25).
298    #[inline(always)]
299    pub(crate) fn op_bit(&mut self, mode: Mode) {
300        let address = self.ea(mode);
301        let operand = self.load(address);
302        self.bit_flags(operand, self.a);
303    }
304}