"""Swap: SWP and SWPB, an atomic read then write of the same address (DS 4.12). S+2N+I: the read (N), the write of Rm (N) to the address in Rn, then an internal cycle at pc+12 while the read data reaches Rd; the next fetch is S (merged IS, C1). The TRM drives LOCK in both the read and the write; NBA and the corpus mark only the write (timing.md table 6-14, C10). A misaligned SWP rotates the word it read, like LDR, and writes Rm unrotated (U1). """ from __future__ import annotations from arm7tdmi_python._alu import ror32 from arm7tdmi_python._core import MASK32, CoreMixin class SwapMixin(CoreMixin): def _arm_swp(self, op: int) -> None: """SWP/SWPB -- Rd = [Rn]; [Rn] = Rm, locked; B swaps a byte (DS 4.12, U1, C10).""" rd = (op >> 12) & 0xF self.r[15] = (self.r[15] + 4) & MASK32 # the PC has advanced: R15 reads pc+12 address = self._reg((op >> 16) & 0xF) if op & (1 << 22): value = self._read(address, 8, lock=True) self._write(address, 8, self._reg(op & 0xF), lock=True) else: value = ror32(self._read(address, 32, lock=True), (address & 3) * 8) self._write(address, 32, self._reg(op & 0xF), lock=True) self._idle(self.r[15]) self._set_reg(rd, value) self.next_fetch_seq = True # merged IS (C1) if rd == 15: self._refill()