// SPDX-License-Identifier: MIT //! Branches: B, BL, BX and Thumb's B, B, the two BL halves and BX. //! //! Transcribed from `arm7tdmi_python/_branch.py`. //! //! Every taken branch is 2S+N: the prefetch, then the refill at the target (N) and target+L (S) //! (timing.md tables 6-1 to 6-3). The offset is relative to the PC as the pipeline sees it, the //! instruction's address plus 2L. BX's target bit 0 selects Thumb; an ARM target with bit 1 set //! is fetched with it cleared (C3). use crate::core::{Bus, ARM7TDMI}; use crate::modes::{condition_passes, THUMB}; /// `value` (`bits` wide) as a signed number. #[inline] pub fn signed(value: u32, bits: u32) -> i32 { if value >> (bits - 1) & 1 != 0 { (value as i64 - (1i64 << bits)) as i32 } else { value as i32 } } impl ARM7TDMI { #[inline] fn branch_exchange(&mut self, target: u32) { if target & 1 != 0 { self.cpsr |= THUMB; self.set_pc(target & !1); } else { self.cpsr &= !THUMB; self.set_pc(target); } } /// B -- PC = PC + offset24 x 4 (DS 4.4). pub(crate) fn arm_b(&mut self, op: u32) { self.set_pc(self.r[15].wrapping_add((signed(op & 0xFF_FFFF, 24) as u32).wrapping_mul(4))); } /// BL -- R14 = address of the next instruction; PC = PC + offset24 x 4 (DS 4.4). pub(crate) fn arm_bl(&mut self, op: u32) { self.set_reg(14, self.r[15].wrapping_sub(4)); self.set_pc(self.r[15].wrapping_add((signed(op & 0xFF_FFFF, 24) as u32).wrapping_mul(4))); } /// BX -- PC = Rm, T = Rm[0] (DS 4.3, C3). pub(crate) fn arm_bx(&mut self, op: u32) { self.branch_exchange(self.reg((op & 0xF) as usize)); } /// B label -- format 16: taken is 2S+N, not taken one S (DS 5.16, table 6-22). pub(crate) fn thumb_bcc(&mut self, op: u32) { if condition_passes((op >> 8) & 0xF, self.cpsr) { self.set_pc(self.r[15].wrapping_add((signed(op & 0xFF, 8) as u32).wrapping_mul(2))); } else { self.next_fetch_seq = true; self.r[15] = self.r[15].wrapping_add(2); } } /// B label -- format 18: PC = PC + offset11 x 2 (DS 5.18). pub(crate) fn thumb_b(&mut self, op: u32) { self.set_pc(self.r[15].wrapping_add((signed(op & 0x7FF, 11) as u32).wrapping_mul(2))); } /// BL label (first half) -- format 19: LR = PC + offset_hi << 12; one cycle (DS 5.19, /// U18). pub(crate) fn thumb_bl_prefix(&mut self, op: u32) { self.r[14] = self.r[15].wrapping_add((signed(op & 0x7FF, 11) << 12) as u32); self.next_fetch_seq = true; self.r[15] = self.r[15].wrapping_add(2); } /// BL label (second half) -- format 19: PC = LR + offset_lo x 2; LR = next | 1 (DS 5.19, /// U18). pub(crate) fn thumb_bl_suffix(&mut self, op: u32) { let link = self.r[15].wrapping_sub(2) | 1; let target = self.r[14].wrapping_add((op & 0x7FF) * 2) & !1; self.r[14] = link; self.set_pc(target); } /// BX Rs/BX Hs -- format 5: PC = Rs, T = Rs[0]; H1 is ignored, so 0x4780-0x47FF are /// BX too, without a link (DS 5.5, U19: alyosha-tas `thumb/blx`, run on a Game Boy /// Player). pub(crate) fn thumb_bx(&mut self, op: u32) { self.branch_exchange(self.r[((op >> 3) & 0xF) as usize]); } }