// SPDX-License-Identifier: MIT AND Zlib // booth_multiply and its helpers: zaydlang's multiplication-algorithm (Zlib), through the reference's Python transcription; notice below and in NOTICE. //! Multiplies: MUL, MLA, UMULL, UMLAL, SMULL, SMLAL and Thumb's MUL (DS 4.7, 4.8, 5.4). //! //! Transcribed from `arm7tdmi_python/_multiply.py`. //! //! Timing (TRM 6.20, timing.md tables 6-5 to 6-8): the prefetch, then `m` internal cycles at //! pc+12 for MUL, one more at pc+8 first for MLA, `m + 1` for UMULL and SMULL and `m + 2` for //! the accumulating long forms. `m` counts the multiplier's significant bytes: 1 to 4 as its //! bits 31:8, 31:16 or 31:24 are all zeros (or all ones, for the signed forms); UMULL and UMLAL //! stop early only on zeros (DS 4.8.3, U11). The next fetch is S (merged IS, C1). //! //! Flags with S set: N and Z from the result (bit 63 and all 64 bits for the long forms); V is //! unchanged (DS 4.7.2, 4.8.2). C, which the data sheet calls "meaningless", is the carry the //! multiplier array leaves: [`booth_multiply`] computes it with zaydlang's model of the //! ARM7TDMI's Booth multiplier, fuzzed against a GBA ("Multiplication Algorithm" research, //! the reference's reference/docs/bmchtech-multiply.html; rung 6 judges the core against the //! model's own C code). //! //! R15 as an operand of a multiply reads pc+12: the operands are read after the PC has advanced //! past the first internal cycle (U12; DS 4.7.3 forbids R15 as an operand; OBSERVED, the //! SingleStepTests corpus v1 shows +12 for every such case). //! //! ---- //! //! [`booth_multiply`] is a Rust transcription of arm7tdmi-python's Python transcription of //! `booths_multiplication` and its helpers in zaydlang's `multiplication-algorithm` //! (`impl.h`, `bitwise.h`, commit 29cef09), altered from its original form: C translated to //! Python, globals made locals, renamed, and the result split from the carry (by //! arm7tdmi-python); then Python translated to Rust (here). The original carries this notice: //! //! ```text //! Copyright (c) 2024 zaydlang //! //! This software is provided 'as-is', without any express or implied warranty. In no event //! will the authors be held liable for any damages arising from the use of this software. //! //! Permission is granted to anyone to use this software for any purpose, including //! commercial applications, and to alter it and redistribute it freely, subject to the //! following restrictions: //! //! 1. The origin of this software must not be misrepresented; you must not claim that you //! wrote the original software. If you use this software in a product, an acknowledgment //! in the product documentation would be appreciated but is not required. //! 2. Altered source versions must be plainly marked as such, and must not be //! misrepresented as being the original software. //! 3. This notice may not be removed or altered from any source distribution. //! ``` use crate::core::{Bus, ARM7TDMI}; use crate::modes::{FLAG_C, FLAG_N, FLAG_Z}; pub const S_BIT: u32 = 1 << 20; const MASK64: u64 = u64::MAX; pub const SHORT: u32 = 0; pub const LONG_SIGNED: u32 = 1; pub const LONG_UNSIGNED: u32 = 2; /// `value` (32 bits wide) with its sign. #[inline] fn sign_extend(value: u32) -> i64 { value as i32 as i64 } /// `m`, the multiplier's significant bytes (TRM 6.20, DS 4.8.3, U11). #[inline] pub fn multiply_cycles(multiplier: u32, signed: bool) -> u32 { for (m, shift) in [(1, 8), (2, 16), (3, 24)] { let top = multiplier >> shift; if top == 0 || (signed && top == u32::MAX >> shift) { return m; } } 4 } // --------------------------------------------------------------------------- zaydlang's model // (zlib; altered, see the module documentation) /// bitwise.h `sign_extend`: copy bit `from_size - 1` up to bit `to_size - 1`. #[inline] fn extend(value: u64, from_size: u32, to_size: u32) -> u64 { let mut value = value; if value >> (from_size - 1) & 1 != 0 { value |= ((1u64 << (to_size - from_size)) - 1) << from_size; } value } /// bitwise.h `asr`: arithmetic shift right within `size` bits. #[inline] fn asr(value: u64, shift: u32, size: u32) -> u64 { let extended = extend(value, size, 64) as i64; ((extended >> shift) as u64) & ((1u64 << size) - 1) } /// One radix-4 Booth digit: (the recoded addend, its carry), 34 bits. #[inline] fn booth_recode(value: u64, chunk: u64) -> (u64, u64) { let (out, carry) = match chunk { 1 | 2 => (value, 0), 3 => (2 * value, 0), 4 => (!(2 * value) & MASK64, 1), 5 | 6 => (!value & MASK64, 1), _ => (0, 0), // 0 and 7 }; (out & 0x3_FFFF_FFFF, carry) } /// Four carry-save adders; returns (sum, carry, the accumulator shift register). #[inline] fn csa_array(total: u64, carry: u64, addends: &[(u64, u64); 4], acc: u64) -> (u64, u64, u64) { let (mut total, mut carry, mut acc) = (total, carry, acc); let mut final_total = 0u64; let mut final_carry = 0u64; for (i, &(addend, booth_carry)) in addends.iter().enumerate() { total &= 0x1_FFFF_FFFF; carry &= 0x1_FFFF_FFFF; let b = addend & 0x1_FFFF_FFFF; let mut out = total ^ b ^ carry; let mut out_carry = (total & b) | (b & carry) | (carry & total); out_carry = ((out_carry << 1) | booth_carry) & MASK64; final_total |= (out & 3) << (2 * i); final_carry |= (out_carry & 3) << (2 * i); out >>= 2; out_carry >>= 2; let magic = (acc & 1) + if carry >> 32 & 1 != 0 { 0 } else { 1 } + if addend >> 33 & 1 != 0 { 0 } else { 1 }; out |= magic << 31; out_carry |= (if acc >> 1 & 1 != 0 { 0 } else { 1 }) << 32; acc >>= 2; total = out; carry = out_carry; } let final_total = (final_total | (total << 8)) & MASK64; let final_carry = (final_carry | (carry << 8)) & MASK64; (final_total, final_carry, acc) } /// The carry flag the ARM7TDMI's multiplier leaves (0 or 1), by zaydlang's model. /// /// `flavor` is `SHORT` (MUL, MLA: signed operands), `LONG_SIGNED` or `LONG_UNSIGNED`; /// `multiplicand` is Rm, `multiplier` Rs, `accumulator` Rn or RdHi:RdLo (0 without). /// /// Only the carry is kept. The model collects each iteration's low carry byte and the last /// iteration's remainder into a 128-bit register, rotates it, and returns bit 127 (bit 95 /// for a four-iteration MUL/MLA). Following those rotations back, that bit is always one /// bit of the last iteration's carry vector: bit `38 - 8 * iterations` for one to three /// iterations, bit 38 (bit 6 for MUL/MLA) for four. The function reads that bit directly /// instead of building the register (equal to the model on rung 4's 7,000,000 cases in the /// reference). pub fn booth_multiply(flavor: u32, multiplicand: u32, multiplier: u32, accumulator: u64) -> u32 { let signed = flavor != LONG_UNSIGNED; let (mut multiplier, multiplicand) = if signed { ( extend(multiplier as u64, 32, 34), extend(multiplicand as u64, 32, 34), ) } else { ( multiplier as u64 & 0x1_FFFF_FFFF, multiplicand as u64 & 0x1_FFFF_FFFF, ) }; let mut carry = if multiplier & 1 != 0 { !multiplicand & MASK64 } else { 0 }; let mut total = accumulator & MASK64; let mut acc = total >> 34; total >>= 1; carry >>= 1; let mut iterations = 0; loop { let addends = [ booth_recode(multiplicand, multiplier & 7), booth_recode(multiplicand, (multiplier >> 2) & 7), booth_recode(multiplicand, (multiplier >> 4) & 7), booth_recode(multiplicand, (multiplier >> 6) & 7), ]; (total, carry, acc) = csa_array(total, carry, &addends, acc); multiplier = asr(multiplier, 8, 33); iterations += 1; if multiplier == 0 || (signed && multiplier == 0x1_FFFF_FFFF) { break; } total >>= 8; carry >>= 8; } if iterations == 4 { let bit = if flavor == SHORT { 6 } else { 38 }; return ((carry >> bit) & 1) as u32; } ((carry >> (38 - 8 * iterations)) & 1) as u32 } // --------------------------------------------------------------------------- the instructions impl ARM7TDMI { #[inline] fn multiply_flags(&mut self, negative: bool, zero: bool, carry: u32) { self.cpsr = (self.cpsr & !(FLAG_N | FLAG_Z | FLAG_C)) | if negative { FLAG_N } else { 0 } | if zero { FLAG_Z } else { 0 } | if carry != 0 { FLAG_C } else { 0 }; } fn multiply_short(&mut self, op: u32, accumulate: bool) { // Register reads follow the cycle that makes them (U7): MLA reads Rn in its first // cycle and Rm, Rs after its extra internal cycle at pc+8; MUL reads Rm, Rs first. let mut rn = 0u32; if accumulate { rn = self.reg(((op >> 12) & 0xF) as usize); if (op >> 12) & 0xF == 15 { rn = rn.wrapping_add(4); // R15 as Rn reads pc+12 (U12) } self.idle(self.r[15]); } self.r[15] = self.r[15].wrapping_add(4); let rm = self.reg((op & 0xF) as usize); let rs = self.reg(((op >> 8) & 0xF) as usize); for _ in 0..multiply_cycles(rs, true) { self.idle(self.r[15]); } let result = rm.wrapping_mul(rs).wrapping_add(rn); if op & S_BIT != 0 { let carry = booth_multiply(SHORT, rm, rs, rn as u64); self.multiply_flags(result >> 31 != 0, result == 0, carry); } let rd = ((op >> 16) & 0xF) as usize; self.set_reg(rd, result); self.next_fetch_seq = true; // merged IS (C1) if rd == 15 { self.refill(); // DS 4.7.3 forbids it; the corpus refills (OBSERVED corpus v1) } } fn multiply_long(&mut self, op: u32, signed: bool, accumulate: bool) { self.r[15] = self.r[15].wrapping_add(4); let (rd_lo, rd_hi) = (((op >> 12) & 0xF) as usize, ((op >> 16) & 0xF) as usize); // The accumulating forms read RdHi:RdLo in their first cycle and Rm, Rs in the next; // the others read Rm, Rs first (U7). let mut accumulator = 0u64; if accumulate { accumulator = (self.reg(rd_hi) as u64) << 32 | self.reg(rd_lo) as u64; self.idle(self.r[15]); } let rm = self.reg((op & 0xF) as usize); let rs = self.reg(((op >> 8) & 0xF) as usize); for _ in 0..multiply_cycles(rs, signed) + 1 { self.idle(self.r[15]); } let product = if signed { (sign_extend(rm) * sign_extend(rs)) as u64 } else { rm as u64 * rs as u64 }; let result = product.wrapping_add(accumulator); if op & S_BIT != 0 { let flavor = if signed { LONG_SIGNED } else { LONG_UNSIGNED }; let carry = booth_multiply(flavor, rm, rs, accumulator); self.multiply_flags(result >> 63 != 0, result == 0, carry); } self.set_reg(rd_lo, result as u32); self.set_reg(rd_hi, (result >> 32) as u32); self.next_fetch_seq = true; // merged IS (C1) if rd_lo == 15 || rd_hi == 15 { self.refill(); // DS 4.8.3 forbids it; the corpus refills (OBSERVED corpus v1) } } /// MUL -- Rd = Rm x Rs (DS 4.7, TRM 6.20). pub(crate) fn arm_mul(&mut self, op: u32) { self.multiply_short(op, false); } /// MLA -- Rd = Rm x Rs + Rn (DS 4.7, TRM 6.20). pub(crate) fn arm_mla(&mut self, op: u32) { self.multiply_short(op, true); } /// UMULL -- RdHi:RdLo = Rm x Rs, unsigned (DS 4.8, U11). pub(crate) fn arm_umull(&mut self, op: u32) { self.multiply_long(op, false, false); } /// UMLAL -- RdHi:RdLo += Rm x Rs, unsigned (DS 4.8, U11). pub(crate) fn arm_umlal(&mut self, op: u32) { self.multiply_long(op, false, true); } /// SMULL -- RdHi:RdLo = Rm x Rs, signed (DS 4.8). pub(crate) fn arm_smull(&mut self, op: u32) { self.multiply_long(op, true, false); } /// SMLAL -- RdHi:RdLo += Rm x Rs, signed (DS 4.8). pub(crate) fn arm_smlal(&mut self, op: u32) { self.multiply_long(op, true, true); } /// MUL Rd,Rs -- format 4: Rd = Rs x Rd; N, Z and the multiplier's C (DS 5.4, TRM /// 6.20). pub(crate) fn thumb_mul(&mut self, op: u32) { let rd = (op & 7) as usize; let (multiplicand, multiplier) = (self.r[((op >> 3) & 7) as usize], self.r[rd]); self.r[15] = self.r[15].wrapping_add(2); for _ in 0..multiply_cycles(multiplier, true) { self.idle(self.r[15]); } let result = multiplicand.wrapping_mul(multiplier); let carry = booth_multiply(SHORT, multiplicand, multiplier, 0); self.multiply_flags(result >> 31 != 0, result == 0, carry); self.r[rd] = result; self.next_fetch_seq = true; // merged IS (C1) } }