# SPDX-License-Identifier: MIT """Branches: B, BL, BX and Thumb's B, B, the two BL halves and BX. 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). """ from __future__ import annotations from arm7tdmi_python._core import MASK32, CoreMixin from arm7tdmi_python._modes import THUMB, condition_passes def signed(value: int, bits: int) -> int: return value - (1 << bits) if value >> (bits - 1) & 1 else value class BranchMixin(CoreMixin): def _branch_exchange(self, target: int) -> None: if target & 1: self.cpsr |= THUMB self._set_pc(target & ~1) else: self.cpsr &= ~THUMB self._set_pc(target) def _arm_b(self, op: int) -> None: """B -- PC = PC + offset24 x 4 (DS 4.4).""" self._set_pc(self.r[15] + signed(op & 0xFFFFFF, 24) * 4) def _arm_bl(self, op: int) -> None: """BL -- R14 = address of the next instruction; PC = PC + offset24 x 4 (DS 4.4).""" self._set_reg(14, (self.r[15] - 4) & MASK32) self._set_pc(self.r[15] + signed(op & 0xFFFFFF, 24) * 4) def _arm_bx(self, op: int) -> None: """BX -- PC = Rm, T = Rm[0] (DS 4.3, C3).""" self._branch_exchange(self._reg(op & 0xF)) def _thumb_bcc(self, op: int) -> None: """B label -- format 16: taken is 2S+N, not taken one S (DS 5.16, table 6-22).""" if condition_passes((op >> 8) & 0xF, self.cpsr): self._set_pc(self.r[15] + signed(op & 0xFF, 8) * 2) else: self.next_fetch_seq = True self.r[15] = (self.r[15] + 2) & MASK32 def _thumb_b(self, op: int) -> None: """B label -- format 18: PC = PC + offset11 x 2 (DS 5.18).""" self._set_pc(self.r[15] + signed(op & 0x7FF, 11) * 2) def _thumb_bl_prefix(self, op: int) -> None: """BL label (first half) -- format 19: LR = PC + offset_hi << 12; one cycle (DS 5.19, U18).""" self.r[14] = (self.r[15] + (signed(op & 0x7FF, 11) << 12)) & MASK32 self.next_fetch_seq = True self.r[15] = (self.r[15] + 2) & MASK32 def _thumb_bl_suffix(self, op: int) -> None: """BL label (second half) -- format 19: PC = LR + offset_lo x 2; LR = next | 1 (DS 5.19, U18).""" link = ((self.r[15] - 2) & MASK32) | 1 target = (self.r[14] + (op & 0x7FF) * 2) & ~1 self.r[14] = link self._set_pc(target) def _thumb_bx(self, op: int) -> None: """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).""" self._branch_exchange(self.r[(op >> 3) & 0xF])