
===== tools/recomp/ia32_native_backend.py:21798-21808 | _eflags_from_state =====

def _eflags_from_state(state: CpuState) -> int:
    flags = 0x2
    flags |= int(state.flags.cf) << 0
    flags |= int(state.flags.pf) << 2
    flags |= int(state.flags.af) << 4
    flags |= int(state.flags.zf) << 6
    flags |= int(state.flags.sf) << 7
    flags |= int(state.flags.interrupt_enabled) << 9
    flags |= int(state.flags.df) << 10
    flags |= int(state.flags.of) << 11
    return flags


===== tools/recomp/ia32_native_backend.py:21811-21821 | _flags_from_eflags =====

def _flags_from_eflags(value: int) -> CpuFlags:
    return CpuFlags(
        cf=bool(value & (1 << 0)),
        pf=bool(value & (1 << 2)),
        af=bool(value & (1 << 4)),
        zf=bool(value & (1 << 6)),
        sf=bool(value & (1 << 7)),
        interrupt_enabled=bool(value & (1 << 9)),
        df=bool(value & (1 << 10)),
        of=bool(value & (1 << 11)),
    )


===== tools/recomp/ia32_native_backend.py:21872-21891 | _float_to_extended80 =====

def _float_to_extended80(value: float) -> bytes:
    sign = 0x8000 if math.copysign(1.0, value) < 0.0 else 0
    magnitude = abs(value)
    if math.isnan(magnitude):
        return struct.pack("<QH", 0xC000000000000000, sign | 0x7FFF)
    if math.isinf(magnitude):
        return struct.pack("<QH", 0x8000000000000000, sign | 0x7FFF)
    if magnitude == 0.0:
        return struct.pack("<QH", 0, sign)
    fraction, exponent = math.frexp(magnitude)
    significand = int(math.ldexp(fraction, 64))
    extended_exponent = exponent - 1 + 16383
    if extended_exponent <= 0:
        significand >>= 1 - extended_exponent
        extended_exponent = 0
    return struct.pack(
        "<QH",
        significand & 0xFFFFFFFFFFFFFFFF,
        sign | (extended_exponent & 0x7FFF),
    )


===== tools/recomp/ia32_native_backend.py:21894-21907 | _extended80_to_float =====

def _extended80_to_float(payload: bytes) -> float:
    if len(payload) != 10:
        raise Ia32BackendError("malformed 80-bit x87 register")
    significand, sign_exponent = struct.unpack("<QH", payload)
    sign = -1.0 if sign_exponent & 0x8000 else 1.0
    exponent = sign_exponent & 0x7FFF
    if exponent == 0x7FFF:
        if significand == 0x8000000000000000:
            return math.copysign(math.inf, sign)
        return math.nan
    if significand == 0:
        return math.copysign(0.0, sign)
    unbiased = (1 - 16383 if exponent == 0 else exponent - 16383) - 63
    return sign * math.ldexp(float(significand), unbiased)


===== tools/recomp/ia32_native_backend.py:21910-21942 | _encode_phase3_fxsave =====

def _encode_phase3_fxsave(state: CpuState) -> bytes:
    payload = bytearray(_encode_fxsave(state))
    top = (state.fpu_status_word >> 11) & 0x7
    tag = 0
    if state.fpu_stack:
        if len(state.fpu_stack) > 8:
            raise Ia32BackendError("Phase-3 x87 input exceeds the eight-register stack")
        for logical_index, value in enumerate(state.fpu_stack):
            physical_index = (top + logical_index) & 0x7
            tag |= 1 << physical_index
            # FXSAVE stores the register payloads in logical ST(i) order while
            # its abridged tag byte remains indexed by physical register.
            start = 32 + logical_index * 16
            payload[start : start + 10] = _float_to_extended80(value)
    elif any(state.mmx_registers.values()):
        top = 0
        struct.pack_into(
            "<H",
            payload,
            2,
            (state.fpu_status_word & ~(0x7 << 11)),
        )
        tag = 0xFF
        for index in range(8):
            struct.pack_into(
                "<QH",
                payload,
                32 + index * 16,
                state.get_mmx_register(f"mm{index}"),
                0xFFFF,
            )
    payload[4] = tag
    return bytes(payload)


===== tools/recomp/ia32_native_backend.py:21945-21968 | _decode_phase3_fxsave =====

def _decode_phase3_fxsave(state: CpuState, payload: bytes) -> None:
    _decode_fxsave(state, payload)
    tag = payload[4]
    top = (state.fpu_status_word >> 11) & 0x7
    populated = [index for index in range(8) if tag & (1 << index)]
    mmx_mode = bool(populated) and all(
        struct.unpack_from("<H", payload, 32 + index * 16 + 8)[0] == 0xFFFF for index in populated
    )
    state.fpu_stack = []
    for index in range(8):
        state.set_mmx_register(f"mm{index}", 0)
    if mmx_mode:
        for index in populated:
            state.set_mmx_register(
                f"mm{index}",
                struct.unpack_from("<Q", payload, 32 + index * 16)[0],
            )
        return
    for logical_index in range(8):
        physical_index = (top + logical_index) & 0x7
        if not tag & (1 << physical_index):
            break
        start = 32 + logical_index * 16
        state.fpu_stack.append(_extended80_to_float(payload[start : start + 10]))


===== tools/recomp/x86_lifter.py:59-60 | RecompilationError =====

class RecompilationError(RuntimeError):
    """Base error for recompilation prototype failures."""


===== tools/recomp/x86_lifter.py:63-64 | X86DecodeError =====

class X86DecodeError(RecompilationError):
    """Raised when the prototype decoder reaches an unsupported instruction."""


===== tools/recomp/x86_lifter.py:83-97 | X86ExecutionError =====

class X86ExecutionError(RecompilationError):
    """Raised when lifted code cannot be executed by the trace executor."""

    def __init__(
        self,
        message: str,
        *,
        state: "CpuState | None" = None,
        trace: "ExecutionTrace | None" = None,
        steps: int = 0,
    ) -> None:
        super().__init__(message)
        self.state = state
        self.trace = trace
        self.steps = steps


===== tools/recomp/x86_lifter.py:100-101 | _u32 =====

def _u32(value: int) -> int:
    return value & 0xFFFFFFFF


===== tools/recomp/x86_lifter.py:104-105 | _i8 =====

def _i8(value: int) -> int:
    return value - 0x100 if value & 0x80 else value


===== tools/recomp/x86_lifter.py:108-109 | _i16 =====

def _i16(value: int) -> int:
    return value - 0x10000 if value & 0x8000 else value


===== tools/recomp/x86_lifter.py:112-113 | _i32 =====

def _i32(value: int) -> int:
    return value - 0x1_0000_0000 if value & 0x80000000 else value


===== tools/recomp/x86_lifter.py:116-119 | _read_u16 =====

def _read_u16(data: bytes, offset: int) -> int:
    if offset + 2 > len(data):
        raise X86DecodeError("truncated u16 immediate")
    return struct.unpack_from("<H", data, offset)[0]


===== tools/recomp/x86_lifter.py:122-125 | _read_u32 =====

def _read_u32(data: bytes, offset: int) -> int:
    if offset + 4 > len(data):
        raise X86DecodeError("truncated u32 immediate")
    return struct.unpack_from("<I", data, offset)[0]


===== tools/recomp/x86_lifter.py:128-131 | _x87_stack_register_index =====

def _x87_stack_register_index(operand: Operand) -> int:
    if operand.kind != "reg" or operand.reg not in REGISTER_NAMES:
        raise X86DecodeError("invalid x87 stack register encoding")
    return REGISTER_NAMES.index(operand.reg)


===== tools/recomp/x86_lifter.py:134-135 | _hex32 =====

def _hex32(value: int) -> str:
    return f"0x{value & 0xFFFFFFFF:08X}"


===== tools/recomp/x86_lifter.py:138-139 | _hex64 =====

def _hex64(value: int) -> str:
    return f"0x{value & 0xFFFFFFFFFFFFFFFF:016X}"


===== tools/recomp/x86_lifter.py:142-143 | _parity8 =====

def _parity8(value: int) -> bool:
    return bin(value & 0xFF).count("1") % 2 == 0


===== tools/recomp/x86_lifter.py:146-167 | CpuFlags =====

@dataclass
class CpuFlags:
    cf: bool = False
    pf: bool = False
    af: bool = False
    zf: bool = False
    sf: bool = False
    of: bool = False
    df: bool = False
    interrupt_enabled: bool = True

    def to_dict(self) -> dict[str, bool]:
        return {
            "cf": self.cf,
            "pf": self.pf,
            "af": self.af,
            "zf": self.zf,
            "sf": self.sf,
            "of": self.of,
            "df": self.df,
            "interrupt_enabled": self.interrupt_enabled,
        }


===== tools/recomp/x86_lifter.py:170-286 | CpuState =====

@dataclass
class CpuState:
    registers: dict[str, int] = field(
        default_factory=lambda: {name: 0 for name in REGISTER_NAMES}
    )
    flags: CpuFlags = field(default_factory=CpuFlags)
    eip: int = 0
    fs_base: int = 0
    cs_selector: int = 0x0008
    gdtr_base: int = 0
    gdtr_limit: int = 0xFFFF
    timestamp_counter: int = 0
    mxcsr: int = DEFAULT_MXCSR
    fpu_control_word: int = DEFAULT_X87_CONTROL_WORD
    fpu_status_word: int = 0
    fpu_stack: list[float] = field(default_factory=list)
    xmm_registers: dict[str, tuple[float, float, float, float]] = field(
        default_factory=lambda: {
            name: (0.0, 0.0, 0.0, 0.0) for name in XMM_REGISTER_NAMES
        }
    )
    mmx_registers: dict[str, int] = field(
        default_factory=lambda: {name: 0 for name in MMX_REGISTER_NAMES}
    )

    @classmethod
    def with_registers(cls, **registers: int) -> "CpuState":
        state = cls()
        for name, value in registers.items():
            normalized = name.casefold()
            if normalized == "fs_base":
                state.fs_base = _u32(value)
            elif normalized == "cs_selector":
                state.cs_selector = value & 0xFFFF
            elif normalized == "gdtr_base":
                state.gdtr_base = _u32(value)
            elif normalized == "gdtr_limit":
                state.gdtr_limit = value & 0xFFFF
            elif normalized == "timestamp_counter":
                state.timestamp_counter = value & 0xFFFFFFFFFFFFFFFF
            elif normalized == "mxcsr":
                state.mxcsr = _u32(value)
            elif normalized == "fpu_control_word":
                state.fpu_control_word = value & 0xFFFF
            elif normalized == "fpu_status_word":
                state.fpu_status_word = value & 0xFFFF
            else:
                state.set_register(name, value)
        return state

    def get_register(self, name: str) -> int:
        normalized = name.casefold()
        if normalized not in REGISTER_NAMES:
            raise X86ExecutionError(f"unknown register: {name}")
        return self.registers[normalized]

    def set_register(self, name: str, value: int) -> None:
        normalized = name.casefold()
        if normalized not in REGISTER_NAMES:
            raise X86ExecutionError(f"unknown register: {name}")
        self.registers[normalized] = _u32(value)

    def get_xmm_register(self, name: str) -> tuple[float, float, float, float]:
        normalized = name.casefold()
        if normalized not in XMM_REGISTER_NAMES:
            raise X86ExecutionError(f"unknown XMM register: {name}")
        return self.xmm_registers[normalized]

    def set_xmm_register(self, name: str, value: Iterable[float]) -> None:
        normalized = name.casefold()
        if normalized not in XMM_REGISTER_NAMES:
            raise X86ExecutionError(f"unknown XMM register: {name}")
        lanes = tuple(float(lane) for lane in value)
        if len(lanes) != 4:
            raise X86ExecutionError("XMM register writes require four lanes")
        self.xmm_registers[normalized] = (lanes[0], lanes[1], lanes[2], lanes[3])

    def get_mmx_register(self, name: str) -> int:
        normalized = name.casefold()
        if normalized not in MMX_REGISTER_NAMES:
            raise X86ExecutionError(f"unknown MMX register: {name}")
        return self.mmx_registers[normalized]

    def set_mmx_register(self, name: str, value: int) -> None:
        normalized = name.casefold()
        if normalized not in MMX_REGISTER_NAMES:
            raise X86ExecutionError(f"unknown MMX register: {name}")
        self.mmx_registers[normalized] = value & 0xFFFFFFFFFFFFFFFF

    def to_dict(self) -> dict[str, Any]:
        return {
            "registers": {name: _hex32(self.registers[name]) for name in REGISTER_NAMES},
            "segments": {
                "fs_base": _hex32(self.fs_base),
                "cs_selector": f"0x{self.cs_selector & 0xFFFF:04X}",
                "gdtr_base": _hex32(self.gdtr_base),
                "gdtr_limit": f"0x{self.gdtr_limit & 0xFFFF:04X}",
            },
            "flags": self.flags.to_dict(),
            "eip": self.eip,
            "eip_hex": _hex32(self.eip),
            "timestamp_counter": self.timestamp_counter,
            "timestamp_counter_hex": f"0x{self.timestamp_counter & 0xFFFFFFFFFFFFFFFF:016X}",
            "mxcsr": self.mxcsr,
            "mxcsr_hex": _hex32(self.mxcsr),
            "fpu_control_word": self.fpu_control_word,
            "fpu_control_word_hex": f"0x{self.fpu_control_word & 0xFFFF:04X}",
            "fpu_status_word": self.fpu_status_word,
            "fpu_status_word_hex": f"0x{self.fpu_status_word & 0xFFFF:04X}",
            "fpu_stack_depth": len(self.fpu_stack),
            "xmm_registers": {
                name: list(self.xmm_registers[name]) for name in XMM_REGISTER_NAMES
            },
            "mmx_registers": {
                name: _hex64(self.mmx_registers[name]) for name in MMX_REGISTER_NAMES
            },
        }


===== tools/recomp/x86_lifter.py:289-378 | Operand =====

@dataclass(frozen=True)
class Operand:
    kind: str
    size: int = 32
    reg: str | None = None
    immediate: int | None = None
    base: str | None = None
    index: str | None = None
    scale: int = 1
    displacement: int = 0
    absolute: int | None = None
    segment: str | None = None

    @classmethod
    def register(cls, reg: str, *, size: int = 32) -> "Operand":
        return cls("reg", size=size, reg=reg)

    @classmethod
    def immediate_u32(cls, value: int) -> "Operand":
        return cls("imm", immediate=_u32(value))

    @classmethod
    def memory(
        cls,
        *,
        base: str | None = None,
        index: str | None = None,
        scale: int = 1,
        displacement: int = 0,
        absolute: int | None = None,
        size: int = 32,
        segment: str | None = None,
    ) -> "Operand":
        return cls(
            "mem",
            size=size,
            base=base,
            index=index,
            scale=scale,
            displacement=displacement,
            absolute=absolute,
            segment=segment,
        )

    def to_dict(self) -> dict[str, Any]:
        data: dict[str, Any] = {"kind": self.kind, "size": self.size}
        if self.reg is not None:
            data["reg"] = self.reg
        if self.immediate is not None:
            data["immediate"] = self.immediate
            data["immediate_hex"] = _hex32(self.immediate)
        if self.kind == "mem":
            data.update(
                {
                    "base": self.base,
                    "index": self.index,
                    "scale": self.scale,
                    "displacement": self.displacement,
                    "absolute": self.absolute,
                    "absolute_hex": _hex32(self.absolute)
                    if self.absolute is not None
                    else None,
                    "segment": self.segment,
                }
            )
        return data

    def asm(self) -> str:
        if self.kind == "reg":
            return self.reg or "?"
        if self.kind == "imm":
            return _hex32(self.immediate or 0)
        if self.kind != "mem":
            return "?"
        prefix = f"{self.segment}:" if self.segment else ""
        if self.absolute is not None:
            return f"{prefix}[{_hex32(self.absolute)}]"
        parts: list[str] = []
        if self.base:
            parts.append(self.base)
        if self.index:
            parts.append(f"{self.index}*{self.scale}" if self.scale != 1 else self.index)
        if self.displacement:
            sign = "+" if self.displacement >= 0 else "-"
            magnitude = abs(self.displacement)
            parts.append(f"{sign} 0x{magnitude:X}")
        if not parts:
            parts.append("0")
        text = " ".join(parts)
        return f"{prefix}[{text}]"


===== tools/recomp/x86_lifter.py:381-419 | X86Instruction =====

@dataclass(frozen=True)
class X86Instruction:
    address: int
    size: int
    mnemonic: str
    operands: tuple[Operand, ...] = ()
    bytes_hex: str = ""
    target: int | None = None
    condition: str | None = None
    ret_stack_adjust: int = 0

    @property
    def next_address(self) -> int:
        return self.address + self.size

    def text(self) -> str:
        if not self.operands:
            return self.mnemonic
        return f"{self.mnemonic} " + ", ".join(operand.asm() for operand in self.operands)

    def to_dict(self, *, include_bytes: bool = False) -> dict[str, Any]:
        data: dict[str, Any] = {
            "address": self.address,
            "address_hex": _hex32(self.address),
            "size": self.size,
            "mnemonic": self.mnemonic,
            "operands": [operand.to_dict() for operand in self.operands],
            "text": self.text(),
        }
        if include_bytes:
            data["bytes_hex"] = self.bytes_hex
        if self.target is not None:
            data["target"] = self.target
            data["target_hex"] = _hex32(self.target)
        if self.condition is not None:
            data["condition"] = self.condition
        if self.ret_stack_adjust:
            data["ret_stack_adjust"] = self.ret_stack_adjust
        return data


===== tools/recomp/x86_lifter.py:772-2478 | X86Decoder =====

class X86Decoder:
    """Decoder for the Milestone 5 IA-32 subset."""

    def decode_function(
        self,
        code: bytes,
        *,
        base_address: int,
        symbol: str = "lifted_function",
        max_instructions: int = 256,
        stop_at_ret: bool = True,
    ) -> LiftedFunction:
        offset = 0
        instructions: list[X86Instruction] = []
        while offset < len(code) and len(instructions) < max_instructions:
            instruction, offset = self._decode_one(code, offset, base_address)
            instructions.append(instruction)
            if stop_at_ret and instruction.mnemonic in {"ret", "int3", "int"}:
                break
        if len(instructions) >= max_instructions and offset < len(code):
            raise X86DecodeError("instruction limit reached before function end")
        return LiftedFunction(
            symbol=symbol,
            base_address=base_address,
            code_size=offset,
            instructions=tuple(instructions),
        )

    def decode_block(
        self,
        code: bytes,
        *,
        base_address: int,
        symbol: str = "lifted_block",
        max_instructions: int = 128,
    ) -> LiftedFunction:
        offset = 0
        instructions: list[X86Instruction] = []
        terminated = False
        while offset < len(code) and len(instructions) < max_instructions:
            instruction, offset = self._decode_one(code, offset, base_address)
            instructions.append(instruction)
            if instruction.mnemonic in BLOCK_TERMINATORS:
                terminated = True
                break
        if not terminated:
            raise X86DecodeError("instruction limit reached before block end")
        return LiftedFunction(
            symbol=symbol,
            base_address=base_address,
            code_size=offset,
            instructions=tuple(instructions),
        )

    def _decode_one(
        self, code: bytes, offset: int, base_address: int
    ) -> tuple[X86Instruction, int]:
        start = offset
        address = base_address + offset
        repeat_prefix = False
        repeat_not_equal_prefix = False
        operand_size = 32
        segment_override: str | None = None
        while True:
            opcode = self._read_u8(code, offset)
            offset += 1
            if opcode == 0x64:
                segment_override = "fs"
                continue
            if opcode == 0x66:
                operand_size = 16
                continue
            if opcode == 0xF2:
                repeat_not_equal_prefix = True
                continue
            if opcode == 0xF3:
                repeat_prefix = True
                continue
            if opcode == 0xF0:
                continue
            break
        self._segment_override = segment_override

        def inst(
            mnemonic: str,
            operands: tuple[Operand, ...] = (),
            *,
            target: int | None = None,
            condition: str | None = None,
            ret_stack_adjust: int = 0,
        ) -> tuple[X86Instruction, int]:
            raw = code[start:offset]
            return (
                X86Instruction(
                    address,
                    offset - start,
                    mnemonic,
                    operands,
                    raw.hex().upper(),
                    target,
                    condition,
                    ret_stack_adjust,
                ),
                offset,
            )

        def scalar_float_operand(operand: Operand) -> Operand:
            if operand.kind != "mem":
                return operand
            return Operand.memory(
                base=operand.base,
                index=operand.index,
                scale=operand.scale,
                displacement=operand.displacement,
                absolute=operand.absolute,
                size=32,
                segment=operand.segment,
            )

        def mmx_operand(operand: Operand) -> Operand:
            if operand.kind == "reg":
                if operand.reg not in REGISTER_NAMES:
                    raise X86DecodeError("invalid MMX register encoding")
                return Operand.register(
                    MMX_REGISTER_BY_INDEX[REGISTER_NAMES.index(operand.reg)],
                    size=64,
                )
            if operand.kind == "mem":
                return Operand.memory(
                    base=operand.base,
                    index=operand.index,
                    scale=operand.scale,
                    displacement=operand.displacement,
                    absolute=operand.absolute,
                    size=64,
                    segment=operand.segment,
                )
            return operand

        def xmm_operand(operand: Operand, *, memory_size: int = 128) -> Operand:
            if operand.kind == "reg":
                if operand.reg not in REGISTER_NAMES:
                    raise X86DecodeError("invalid XMM register encoding")
                return Operand.register(
                    XMM_REGISTER_BY_INDEX[REGISTER_NAMES.index(operand.reg)],
                    size=128,
                )
            if operand.kind == "mem":
                return Operand.memory(
                    base=operand.base,
                    index=operand.index,
                    scale=operand.scale,
                    displacement=operand.displacement,
                    absolute=operand.absolute,
                    size=memory_size,
                    segment=operand.segment,
                )
            return operand

        if opcode == 0x90:
            return inst("nop")
        if 0x91 <= opcode <= 0x97:
            return inst(
                "xchg",
                (
                    Operand.register("eax", size=operand_size),
                    Operand.register(
                        REGISTER_BY_INDEX[opcode - 0x90],
                        size=operand_size,
                    ),
                ),
            )
        if opcode == 0x9B:
            return inst("fwait")
        if opcode == 0x9C:
            if operand_size != 32:
                raise X86DecodeError(
                    f"unsupported pushf operand size at {_hex32(address)}"
                )
            return inst("pushfd")
        if opcode == 0x9D:
            if operand_size != 32:
                raise X86DecodeError(
                    f"unsupported popf operand size at {_hex32(address)}"
                )
            return inst("popfd")
        if opcode == 0x9E:
            return inst("sahf")
        if opcode == 0xFA:
            return inst("cli")
        if opcode == 0xFB:
            return inst("sti")
        if opcode == 0xFC:
            return inst("cld")
        if opcode == 0xFD:
            return inst("std")
        if repeat_prefix and opcode == 0xAA:
            return inst("rep_stosb")
        if repeat_prefix and opcode == 0xAB:
            return inst("rep_stosd")
        if repeat_prefix and opcode == 0xA4:
            return inst("rep_movsb")
        if repeat_prefix and opcode == 0xA5:
            return inst("rep_movsd")
        if repeat_prefix and opcode == 0xA6:
            return inst("rep_cmpsb")
        if repeat_prefix and opcode == 0xA7:
            return inst("rep_cmpsd")
        if repeat_not_equal_prefix and opcode == 0xAE:
            return inst("repne_scasb")
        if opcode == 0xAA:
            return inst("stosb")
        if opcode == 0xAB:
            return inst("stosd")
        if opcode == 0xA4:
            return inst("movsb")
        if opcode == 0xA5:
            return inst("movsd")
        if opcode == 0xA6:
            return inst("cmpsb")
        if opcode == 0xA7:
            return inst("cmpsd")
        if opcode == 0xAE:
            return inst("scasb")
        if opcode == 0xCC:
            return inst("int3")
        if opcode == 0xCD:
            vector = self._read_u8(code, offset)
            offset += 1
            return inst("int", (Operand.immediate_u32(vector),))
        if opcode == 0xEE:
            return inst(
                "out",
                (
                    Operand.register("dx", size=16),
                    Operand.register("al", size=8),
                ),
            )
        if opcode == 0xEC:
            return inst(
                "in",
                (
                    Operand.register("al", size=8),
                    Operand.register("dx", size=16),
                ),
            )
        if opcode == 0xEA:
            if operand_size == 16:
                target = _read_u16(code, offset)
                offset += 2
            else:
                target = _read_u32(code, offset)
                offset += 4
            selector = _read_u16(code, offset)
            offset += 2
            return inst(
                "jmp_far",
                (Operand.immediate_u32(selector),),
                target=target,
            )
        if opcode == 0xDB:
            extension = self._read_u8(code, offset)
            if extension == 0xE2:
                offset += 1
                return inst("fnclex")
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=32,
            )
            if rm_operand.kind != "reg" and reg_index == 0:
                return inst("fild", (rm_operand,))
            if rm_operand.kind != "reg" and reg_index == 3:
                return inst("fistp", (rm_operand,))
            if rm_operand.kind != "reg" and reg_index == 5:
                return inst(
                    "fld",
                    (
                        Operand.memory(
                            base=rm_operand.base,
                            index=rm_operand.index,
                            scale=rm_operand.scale,
                            displacement=rm_operand.displacement,
                            absolute=rm_operand.absolute,
                            size=80,
                            segment=rm_operand.segment,
                        ),
                    ),
                )
            raise X86DecodeError(
                f"unsupported x87 DB {extension:02X} at {_hex32(address)}"
            )
        if opcode == 0xDF:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=64,
            )
            if (
                rm_operand.kind == "reg"
                and rm_operand.reg == "eax"
                and reg_index == 4
            ):
                return inst("fnstsw", (Operand.register("eax", size=16),))
            if reg_index == 5:
                return inst("fild", (rm_operand,))
            if reg_index == 7:
                return inst("fistp", (rm_operand,))
            raise X86DecodeError(
                f"unsupported x87 DF /{reg_index} at {_hex32(address)}"
            )
        if opcode == 0xD8:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=32,
            )
            if rm_operand.kind == "reg":
                st_index = _x87_stack_register_index(rm_operand)
                st_operand = Operand.immediate_u32(st_index)
                if reg_index == 0:
                    return inst("fadd", (st_operand,))
                if reg_index == 1:
                    return inst("fmul", (st_operand,))
                if reg_index == 2:
                    return inst("fcom", (st_operand,))
                if reg_index == 3:
                    return inst("fcomp", (st_operand,))
                if reg_index == 4:
                    return inst("fsub", (st_operand,))
                if reg_index == 5:
                    return inst("fsubr", (st_operand,))
                if reg_index == 6:
                    return inst("fdiv", (st_operand,))
                if reg_index == 7:
                    return inst("fdivr", (st_operand,))
            if reg_index == 0:
                return inst("fadd", (rm_operand,))
            if reg_index == 1:
                return inst("fmul", (rm_operand,))
            if reg_index == 2:
                return inst("fcom", (rm_operand,))
            if reg_index == 3:
                return inst("fcomp", (rm_operand,))
            if reg_index == 4:
                return inst("fsub", (rm_operand,))
            if reg_index == 5:
                return inst("fsubr", (rm_operand,))
            if reg_index == 6:
                return inst("fdiv", (rm_operand,))
            if reg_index == 7:
                return inst("fdivr", (rm_operand,))
            raise X86DecodeError(
                f"unsupported x87 D8 /{reg_index} at {_hex32(address)}"
            )
        if opcode == 0xDA:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=32,
            )
            if rm_operand.kind != "reg":
                if reg_index == 0:
                    return inst("fiadd", (rm_operand,))
                if reg_index == 1:
                    return inst("fimul", (rm_operand,))
                if reg_index == 4:
                    return inst("fisub", (rm_operand,))
                if reg_index == 6:
                    return inst("fidiv", (rm_operand,))
            raise X86DecodeError(
                f"unsupported x87 DA /{reg_index} at {_hex32(address)}"
            )
        if opcode == 0xD9:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=32,
            )
            if rm_operand.kind == "reg":
                st_index = _x87_stack_register_index(rm_operand)
                if reg_index == 0:
                    return inst("fld", (Operand.immediate_u32(st_index),))
                if reg_index == 1:
                    return inst("fxch", (Operand.immediate_u32(st_index),))
                if reg_index == 4 and st_index == 0:
                    return inst("fchs")
                if reg_index == 4 and st_index == 1:
                    return inst("fabs")
                if reg_index == 4 and st_index == 4:
                    return inst("ftst")
                if reg_index == 5:
                    constant_loads = {
                        0: "fld1",
                        1: "fldl2t",
                        2: "fldl2e",
                        3: "fldpi",
                        4: "fldlg2",
                        5: "fldln2",
                        6: "fldz",
                    }
                    constant_load = constant_loads.get(st_index)
                    if constant_load is not None:
                        return inst(constant_load)
                if reg_index == 6 and st_index == 0:
                    return inst("f2xm1")
                if reg_index == 6 and st_index == 1:
                    return inst("fyl2x")
                if reg_index == 6 and st_index == 2:
                    return inst("fptan")
                if reg_index == 6 and st_index == 3:
                    return inst("fpatan")
                if reg_index == 7 and st_index == 4:
                    return inst("frndint")
                if reg_index == 7 and st_index == 5:
                    return inst("fscale")
                if reg_index == 7 and st_index == 2:
                    return inst("fsqrt")
                if reg_index == 7 and st_index == 6:
                    return inst("fsin")
                if reg_index == 7 and st_index == 7:
                    return inst("fcos")
                raise X86DecodeError(
                    f"unsupported x87 D9 register form at {_hex32(address)}"
                )
            if reg_index == 0:
                return inst("fld", (rm_operand,))
            if reg_index == 2:
                return inst("fst", (rm_operand,))
            if reg_index == 3:
                return inst("fstp", (rm_operand,))
            if reg_index == 5:
                rm_operand = Operand.memory(
                    base=rm_operand.base,
                    index=rm_operand.index,
                    scale=rm_operand.scale,
                    displacement=rm_operand.displacement,
                    absolute=rm_operand.absolute,
                    size=16,
                    segment=rm_operand.segment,
                )
                return inst("fldcw", (rm_operand,))
            if reg_index == 7:
                rm_operand = Operand.memory(
                    base=rm_operand.base,
                    index=rm_operand.index,
                    scale=rm_operand.scale,
                    displacement=rm_operand.displacement,
                    absolute=rm_operand.absolute,
                    size=16,
                    segment=rm_operand.segment,
                )
                return inst("fnstcw", (rm_operand,))
            raise X86DecodeError(
                f"unsupported x87 D9 /{reg_index} at {_hex32(address)}"
            )
        if opcode == 0xDC:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=64,
            )
            if rm_operand.kind == "reg":
                st_index = _x87_stack_register_index(rm_operand)
                stack_operations = {
                    0: "fadd_st",
                    1: "fmul_st",
                    4: "fsubr_st",
                    5: "fsub_st",
                    6: "fdivr_st",
                    7: "fdiv_st",
                }
                stack_operation = stack_operations.get(reg_index)
                if stack_operation is not None:
                    return inst(
                        stack_operation,
                        (Operand.immediate_u32(st_index),),
                    )
            else:
                memory_operations = {
                    0: "fadd",
                    1: "fmul",
                    2: "fcom",
                    3: "fcomp",
                    4: "fsub",
                    5: "fsubr",
                    6: "fdiv",
                    7: "fdivr",
                }
                return inst(memory_operations[reg_index], (rm_operand,))
            raise X86DecodeError(
                f"unsupported x87 DC /{reg_index} at {_hex32(address)}"
            )
        if opcode == 0xDD:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=64,
            )
            if rm_operand.kind == "reg":
                st_index = _x87_stack_register_index(rm_operand)
                if reg_index == 0:
                    return inst("ffree", (Operand.immediate_u32(st_index),))
                if reg_index == 2:
                    return inst("fst", (Operand.immediate_u32(st_index),))
                if reg_index == 3:
                    return inst("fstp", (Operand.immediate_u32(st_index),))
            else:
                if reg_index == 0:
                    return inst("fld", (rm_operand,))
                if reg_index == 2:
                    return inst("fst", (rm_operand,))
                if reg_index == 3:
                    return inst("fstp", (rm_operand,))
                if reg_index in {4, 6}:
                    state_operand = Operand.memory(
                        base=rm_operand.base,
                        index=rm_operand.index,
                        scale=rm_operand.scale,
                        displacement=rm_operand.displacement,
                        absolute=rm_operand.absolute,
                        size=X87_SAVE_IMAGE_SIZE * 8,
                        segment=rm_operand.segment,
                    )
                    return inst(
                        "frstor" if reg_index == 4 else "fnsave",
                        (state_operand,),
                    )
                if reg_index == 7:
                    rm_operand = Operand.memory(
                        base=rm_operand.base,
                        index=rm_operand.index,
                        scale=rm_operand.scale,
                        displacement=rm_operand.displacement,
                        absolute=rm_operand.absolute,
                        size=16,
                        segment=rm_operand.segment,
                    )
                    return inst("fnstsw", (rm_operand,))
            raise X86DecodeError(
                f"unsupported x87 DD /{reg_index} at {_hex32(address)}"
            )
        if opcode == 0xDE:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=32,
            )
            if rm_operand.kind == "reg":
                st_index = _x87_stack_register_index(rm_operand)
                if reg_index == 0:
                    return inst("faddp", (Operand.immediate_u32(st_index),))
                if reg_index == 1:
                    return inst("fmulp", (Operand.immediate_u32(st_index),))
                if reg_index == 3 and st_index == 1:
                    return inst("fcompp")
                if reg_index == 4:
                    return inst("fsubrp", (Operand.immediate_u32(st_index),))
                if reg_index == 5:
                    return inst("fsubp", (Operand.immediate_u32(st_index),))
                if reg_index == 6:
                    return inst("fdivrp", (Operand.immediate_u32(st_index),))
                if reg_index == 7:
                    return inst("fdivp", (Operand.immediate_u32(st_index),))
            raise X86DecodeError(
                f"unsupported x87 DE /{reg_index} at {_hex32(address)}"
            )
        if 0x50 <= opcode <= 0x57:
            return inst("push", (Operand.register(REGISTER_BY_INDEX[opcode - 0x50]),))
        if 0x58 <= opcode <= 0x5F:
            return inst("pop", (Operand.register(REGISTER_BY_INDEX[opcode - 0x58]),))
        if 0x40 <= opcode <= 0x47:
            return inst("inc", (Operand.register(REGISTER_BY_INDEX[opcode - 0x40]),))
        if 0x48 <= opcode <= 0x4F:
            return inst("dec", (Operand.register(REGISTER_BY_INDEX[opcode - 0x48]),))
        if 0xB0 <= opcode <= 0xB7:
            value = self._read_u8(code, offset)
            offset += 1
            return inst(
                "mov",
                (
                    Operand.register(BYTE_REGISTER_BY_INDEX[opcode - 0xB0], size=8),
                    Operand.immediate_u32(value),
                ),
            )
        if 0xB8 <= opcode <= 0xBF:
            if operand_size == 16:
                value = _read_u16(code, offset)
                offset += 2
            else:
                value = _read_u32(code, offset)
                offset += 4
            return inst(
                "mov",
                (
                    Operand.register(
                        REGISTER_BY_INDEX[opcode - 0xB8],
                        size=operand_size,
                    ),
                    Operand.immediate_u32(value),
                ),
            )
        if opcode == 0x68:
            value = _read_u32(code, offset)
            offset += 4
            return inst("push", (Operand.immediate_u32(value),))
        if opcode == 0x6A:
            value = _u32(_i8(self._read_u8(code, offset)))
            offset += 1
            return inst("push", (Operand.immediate_u32(value),))
        if opcode in {0x69, 0x6B}:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=operand_size,
            )
            if opcode == 0x69:
                value = _read_u32(code, offset)
                offset += 4
            else:
                value = _u32(_i8(self._read_u8(code, offset)))
                offset += 1
            return inst(
                "imul",
                (
                    Operand.register(
                        REGISTER_BY_INDEX[reg_index],
                        size=operand_size,
                    ),
                    rm_operand,
                    Operand.immediate_u32(value),
                ),
            )
        if opcode in {0x86, 0x87}:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=8 if opcode == 0x86 else operand_size,
            )
            return inst(
                "xchg",
                (
                    rm_operand,
                    Operand.register(
                        BYTE_REGISTER_BY_INDEX[reg_index]
                        if opcode == 0x86
                        else REGISTER_BY_INDEX[reg_index],
                        size=8 if opcode == 0x86 else operand_size,
                    ),
                ),
            )
        if opcode in {0xA0, 0xA1}:
            absolute = _read_u32(code, offset)
            offset += 4
            value_size = 8 if opcode == 0xA0 else operand_size
            return inst(
                "mov",
                (
                    Operand.register(
                        "al" if opcode == 0xA0 else "eax",
                        size=value_size,
                    ),
                    Operand.memory(
                        absolute=absolute,
                        size=value_size,
                        segment=segment_override,
                    ),
                ),
            )
        if opcode in {0xA2, 0xA3}:
            absolute = _read_u32(code, offset)
            offset += 4
            value_size = 8 if opcode == 0xA2 else operand_size
            return inst(
                "mov",
                (
                    Operand.memory(
                        absolute=absolute,
                        size=value_size,
                        segment=segment_override,
                    ),
                    Operand.register(
                        "al" if opcode == 0xA2 else "eax",
                        size=value_size,
                    ),
                ),
            )
        if opcode in {0x88, 0x8A}:
            reg_index, rm_operand, offset = self._decode_modrm(
                code, offset, operand_size=8
            )
            reg_operand = Operand.register(
                BYTE_REGISTER_BY_INDEX[reg_index],
                size=8,
            )
            operands = (
                (rm_operand, reg_operand)
                if opcode == 0x88
                else (reg_operand, rm_operand)
            )
            return inst("mov", operands)
        if opcode == 0x84:
            reg_index, rm_operand, offset = self._decode_modrm(
                code, offset, operand_size=8
            )
            return inst(
                "test",
                (
                    rm_operand,
                    Operand.register(BYTE_REGISTER_BY_INDEX[reg_index], size=8),
                ),
            )
        if opcode in {0x38, 0x3A}:
            reg_index, rm_operand, offset = self._decode_modrm(
                code, offset, operand_size=8
            )
            reg_operand = Operand.register(
                BYTE_REGISTER_BY_INDEX[reg_index],
                size=8,
            )
            operands = (
                (rm_operand, reg_operand)
                if opcode == 0x38
                else (reg_operand, rm_operand)
            )
            return inst("cmp", operands)
        if opcode == 0x24:
            value = self._read_u8(code, offset)
            offset += 1
            return inst(
                "and",
                (Operand.register("al", size=8), Operand.immediate_u32(value)),
            )
        if opcode == 0x04:
            value = self._read_u8(code, offset)
            offset += 1
            return inst(
                "add",
                (Operand.register("al", size=8), Operand.immediate_u32(value)),
            )
        if opcode == 0x0C:
            value = self._read_u8(code, offset)
            offset += 1
            return inst(
                "or",
                (Operand.register("al", size=8), Operand.immediate_u32(value)),
            )
        if opcode == 0x1C:
            value = self._read_u8(code, offset)
            offset += 1
            return inst(
                "sbb",
                (Operand.register("al", size=8), Operand.immediate_u32(value)),
            )
        if opcode == 0x2C:
            value = self._read_u8(code, offset)
            offset += 1
            return inst(
                "sub",
                (Operand.register("al", size=8), Operand.immediate_u32(value)),
            )
        if opcode == 0x34:
            value = self._read_u8(code, offset)
            offset += 1
            return inst(
                "xor",
                (Operand.register("al", size=8), Operand.immediate_u32(value)),
            )
        if opcode == 0x3C:
            value = self._read_u8(code, offset)
            offset += 1
            return inst(
                "cmp",
                (Operand.register("al", size=8), Operand.immediate_u32(value)),
            )
        if opcode == 0xA8:
            value = self._read_u8(code, offset)
            offset += 1
            return inst(
                "test",
                (Operand.register("al", size=8), Operand.immediate_u32(value)),
            )
        if opcode == 0xC3:
            return inst("ret")
        if opcode == 0xC2:
            adjust = _read_u16(code, offset)
            offset += 2
            return inst("ret", ret_stack_adjust=adjust)
        if opcode == 0xC9:
            return inst("leave")
        if opcode == 0x99:
            return inst("cdq")
        if opcode == 0xE8:
            rel = _i32(_read_u32(code, offset))
            offset += 4
            return inst("call", target=_u32(base_address + offset + rel))
        if opcode == 0xE9:
            rel = _i32(_read_u32(code, offset))
            offset += 4
            return inst("jmp", target=_u32(base_address + offset + rel))
        if opcode == 0xEB:
            rel = _i8(self._read_u8(code, offset))
            offset += 1
            return inst("jmp", target=_u32(base_address + offset + rel))
        if opcode == 0xE3:
            rel = _i8(self._read_u8(code, offset))
            offset += 1
            return inst(
                "jcc",
                target=_u32(base_address + offset + rel),
                condition="ecx_zero",
            )
        if 0x70 <= opcode <= 0x7F:
            rel = _i8(self._read_u8(code, offset))
            offset += 1
            condition = _condition_for_short_opcode(opcode)
            return inst(
                "jcc",
                target=_u32(base_address + offset + rel),
                condition=condition,
            )
        if opcode == 0x0F:
            second = self._read_u8(code, offset)
            offset += 1
            if second == 0x01:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=32,
                )
                if reg_index == 0 and rm_operand.kind == "mem":
                    return inst(
                        "sgdt",
                        (
                            Operand.memory(
                                base=rm_operand.base,
                                index=rm_operand.index,
                                scale=rm_operand.scale,
                                displacement=rm_operand.displacement,
                                absolute=rm_operand.absolute,
                                size=48,
                                segment=rm_operand.segment,
                            ),
                        ),
                    )
                raise X86DecodeError(
                    f"unsupported 0F 01 /{reg_index} at {_hex32(address)}"
                )
            if second == 0x09:
                return inst("wbinvd")
            if second == 0x31:
                return inst("rdtsc")
            if second == 0x77:
                return inst("emms")
            if second == 0x18:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=8,
                )
                mnemonic = {
                    0: "prefetchnta",
                    1: "prefetcht0",
                    2: "prefetcht1",
                    3: "prefetcht2",
                }.get(reg_index, "prefetch")
                return inst(mnemonic, (rm_operand,))
            if operand_size == 32 and second == 0x2B:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=128,
                )
                if rm_operand.kind != "mem":
                    raise X86DecodeError(
                        f"movntps destination must be memory at {_hex32(address)}"
                    )
                return inst(
                    "movntps",
                    (
                        rm_operand,
                        Operand.register(
                            XMM_REGISTER_BY_INDEX[reg_index],
                            size=128,
                        ),
                    ),
                )
            if (
                operand_size == 32
                and not repeat_prefix
                and not repeat_not_equal_prefix
                and second == 0x2D
            ):
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=64,
                )
                return inst(
                    "cvtps2pi",
                    (
                        Operand.register(
                            MMX_REGISTER_BY_INDEX[reg_index],
                            size=64,
                        ),
                        xmm_operand(rm_operand, memory_size=64),
                    ),
                )
            if operand_size == 32 and second in {0x6E, 0x7E}:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=32,
                )
                mmx_register = Operand.register(
                    MMX_REGISTER_BY_INDEX[reg_index],
                    size=64,
                )
                if second == 0x6E:
                    return inst("movd", (mmx_register, rm_operand))
                return inst("movd", (rm_operand, mmx_register))
            if operand_size == 32 and second in {
                0x60,
                0x61,
                0x62,
                0x68,
                0x69,
                0x6A,
                0x6B,
                0xFE,
            }:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=32,
                )
                mnemonic = {
                    0x60: "punpcklbw",
                    0x61: "punpcklwd",
                    0x62: "punpckldq",
                    0x68: "punpckhbw",
                    0x69: "punpckhwd",
                    0x6A: "punpckhdq",
                    0x6B: "packssdw",
                    0xFE: "paddd",
                }[second]
                return inst(
                    mnemonic,
                    (
                        Operand.register(
                            MMX_REGISTER_BY_INDEX[reg_index],
                            size=64,
                        ),
                        mmx_operand(rm_operand),
                    ),
                )
            if operand_size == 32 and second == 0x70:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=32,
                )
                immediate = self._read_u8(code, offset)
                offset += 1
                return inst(
                    "pshufw",
                    (
                        Operand.register(
                            MMX_REGISTER_BY_INDEX[reg_index],
                            size=64,
                        ),
                        mmx_operand(rm_operand),
                        Operand.immediate_u32(immediate),
                    ),
                )
            if operand_size == 32 and second in {0x71, 0x72}:
                extension, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=32,
                )
                mnemonic = {
                    (0x71, 4): "psraw",
                    (0x72, 2): "psrld",
                    (0x72, 6): "pslld",
                }.get((second, extension))
                if mnemonic is None or rm_operand.kind != "reg":
                    raise X86DecodeError(
                        f"unsupported packed shift 0F {second:02X} /{extension} "
                        f"at {_hex32(address)}"
                    )
                immediate = self._read_u8(code, offset)
                offset += 1
                return inst(
                    mnemonic,
                    (
                        mmx_operand(rm_operand),
                        Operand.immediate_u32(immediate),
                    ),
                )
            if second in {0x6F, 0x7F, 0xE7}:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=32,
                )
                reg_operand = Operand.register(
                    MMX_REGISTER_BY_INDEX[reg_index],
                    size=64,
                )
                rm_operand = mmx_operand(rm_operand)
                if second == 0x6F:
                    return inst("movq", (reg_operand, rm_operand))
                if second == 0x7F:
                    return inst("movq", (rm_operand, reg_operand))
                return inst("movntq", (rm_operand, reg_operand))
            if repeat_prefix and second in {0x2C, 0x2D}:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=128,
                )
                rm_operand = scalar_float_operand(rm_operand)
                return inst(
                    "cvttss2si" if second == 0x2C else "cvtss2si",
                    (
                        Operand.register(REGISTER_BY_INDEX[reg_index]),
                        rm_operand,
                    ),
                )
            if repeat_prefix and second in {0x10, 0x11, 0x52}:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=128,
                )
                reg_operand = Operand.register(
                    XMM_REGISTER_BY_INDEX[reg_index],
                    size=128,
                )
                rm_operand = scalar_float_operand(rm_operand)
                if second == 0x10:
                    return inst("movss", (reg_operand, rm_operand))
                if second == 0x11:
                    return inst("movss", (rm_operand, reg_operand))
                return inst("rsqrtss", (reg_operand, rm_operand))
            if second in {0x10, 0x11}:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=128,
                )
                reg_operand = Operand.register(
                    XMM_REGISTER_BY_INDEX[reg_index],
                    size=128,
                )
                if second == 0x10:
                    return inst("movups", (reg_operand, rm_operand))
                return inst("movups", (rm_operand, reg_operand))
            if second in {0x13, 0x17}:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=64,
                )
                if rm_operand.kind != "mem":
                    raise X86DecodeError(
                        f"unsupported packed-half register destination at {_hex32(address)}"
                    )
                return inst(
                    "movlps_store" if second == 0x13 else "movhps_store",
                    (
                        rm_operand,
                        Operand.register(XMM_REGISTER_BY_INDEX[reg_index], size=128),
                    ),
                )
            if second in {0x12, 0x14, 0x15, 0x16}:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=128,
                )
                reg_operand = Operand.register(
                    XMM_REGISTER_BY_INDEX[reg_index],
                    size=128,
                )
                if second in {0x12, 0x16} and rm_operand.kind != "reg":
                    raise X86DecodeError(
                        f"unsupported packed-half memory source at {_hex32(address)}"
                    )
                mnemonic = {
                    0x12: "movhlps",
                    0x14: "unpcklps",
                    0x15: "unpckhps",
                    0x16: "movlhps",
                }[second]
                return inst(mnemonic, (reg_operand, rm_operand))
            if second in {0x28, 0x29, 0x51, 0x58, 0x59, 0x5D, 0x5F}:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=128,
                )
                reg_operand = Operand.register(
                    XMM_REGISTER_BY_INDEX[reg_index],
                    size=128,
                )
                if second == 0x28:
                    return inst("movaps", (reg_operand, rm_operand))
                if second == 0x29:
                    return inst("movaps", (rm_operand, reg_operand))
                if second == 0x51:
                    return inst("sqrtps", (reg_operand, rm_operand))
                if rm_operand.kind == "reg" or rm_operand.kind == "mem":
                    mnemonic = {
                        0x58: "addps",
                        0x59: "mulps",
                        0x5D: "minps",
                        0x5F: "maxps",
                    }[second]
                    return inst(mnemonic, (reg_operand, rm_operand))
            if second == 0xC6:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=128,
                )
                immediate = self._read_u8(code, offset)
                offset += 1
                return inst(
                    "shufps",
                    (
                        Operand.register(
                            XMM_REGISTER_BY_INDEX[reg_index],
                            size=128,
                        ),
                        rm_operand,
                        Operand.immediate_u32(immediate),
                    ),
                )
            if 0x80 <= second <= 0x8F:
                rel = _i32(_read_u32(code, offset))
                offset += 4
                condition = _condition_for_short_opcode(second - 0x10)
                return inst(
                    "jcc",
                    target=_u32(base_address + offset + rel),
                    condition=condition,
                )
            if second == 0xB6:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code, offset, operand_size=8
                )
                return inst(
                    "movzx",
                    (
                        Operand.register(
                            REGISTER_BY_INDEX[reg_index],
                            size=operand_size,
                        ),
                        rm_operand,
                    ),
                )
            if second in {0xB0, 0xB1}:
                bits = 8 if second == 0xB0 else operand_size
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=bits,
                )
                accumulator = "al" if bits == 8 else "eax"
                return inst(
                    "cmpxchg",
                    (
                        rm_operand,
                        Operand.register(REGISTER_BY_INDEX[reg_index], size=bits),
                        Operand.register(accumulator, size=bits),
                    ),
                )
            if second == 0xB7:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code, offset, operand_size=16
                )
                return inst(
                    "movzx",
                    (
                        Operand.register(
                            REGISTER_BY_INDEX[reg_index],
                            size=operand_size,
                        ),
                        rm_operand,
                    ),
                )
            if second == 0xBE:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code, offset, operand_size=8
                )
                return inst(
                    "movsx",
                    (
                        Operand.register(
                            REGISTER_BY_INDEX[reg_index],
                            size=operand_size,
                        ),
                        rm_operand,
                    ),
                )
            if second == 0xBF:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code, offset, operand_size=16
                )
                return inst(
                    "movsx",
                    (
                        Operand.register(
                            REGISTER_BY_INDEX[reg_index],
                            size=operand_size,
                        ),
                        rm_operand,
                    ),
                )
            if second == 0xBC:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=operand_size,
                )
                return inst(
                    "bsf",
                    (
                        Operand.register(
                            REGISTER_BY_INDEX[reg_index],
                            size=operand_size,
                        ),
                        rm_operand,
                    ),
                )
            if second == 0xAF:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=operand_size,
                )
                return inst(
                    "imul",
                    (
                        Operand.register(
                            REGISTER_BY_INDEX[reg_index],
                            size=operand_size,
                        ),
                        rm_operand,
                    ),
                )
            if second in {0xA4, 0xA5, 0xAC, 0xAD}:
                if operand_size != 32:
                    raise X86DecodeError(
                        f"unsupported 0F {second:02X} operand size at {_hex32(address)}"
                    )
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=operand_size,
                )
                if second in {0xA5, 0xAD}:
                    count_operand = Operand.register("cl", size=8)
                else:
                    count = self._read_u8(code, offset)
                    offset += 1
                    count_operand = Operand.immediate_u32(count)
                return inst(
                    "shld" if second in {0xA4, 0xA5} else "shrd",
                    (
                        rm_operand,
                        Operand.register(
                            REGISTER_BY_INDEX[reg_index],
                            size=operand_size,
                        ),
                        count_operand,
                    ),
                )
            if second == 0xC1:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=operand_size,
                )
                return inst(
                    "xadd",
                    (
                        rm_operand,
                        Operand.register(
                            REGISTER_BY_INDEX[reg_index],
                            size=operand_size,
                        ),
                    ),
                )
            if 0x90 <= second <= 0x9F:
                _, rm_operand, offset = self._decode_modrm(
                    code, offset, operand_size=8
                )
                return inst(
                    "setcc",
                    (rm_operand,),
                    condition=_condition_for_short_opcode(0x70 + (second - 0x90)),
                )
            if second == 0xAE:
                reg_index, rm_operand, offset = self._decode_modrm(
                    code,
                    offset,
                    operand_size=32,
                )
                if reg_index == 7 and rm_operand.kind == "reg":
                    return inst("sfence")
                if rm_operand.kind != "mem":
                    raise X86DecodeError(
                        f"unsupported 0F AE register form at {_hex32(address)}"
                    )
                if reg_index == 2:
                    return inst("ldmxcsr", (rm_operand,))
                if reg_index == 3:
                    return inst("stmxcsr", (rm_operand,))
                raise X86DecodeError(
                    f"unsupported 0F AE /{reg_index} at {_hex32(address)}"
                )
            raise X86DecodeError(f"unsupported two-byte opcode 0F {second:02X} at {_hex32(address)}")

        if opcode in {0x00, 0x02, 0x08, 0x0A, 0x10, 0x12, 0x18, 0x1A, 0x20, 0x22, 0x28, 0x2A, 0x30, 0x32}:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=8,
            )
            reg_operand = Operand.register(
                BYTE_REGISTER_BY_INDEX[reg_index],
                size=8,
            )
            if opcode in {0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30}:
                operands = (rm_operand, reg_operand)
            else:
                operands = (reg_operand, rm_operand)
            mnemonic = {
                0x00: "add",
                0x02: "add",
                0x08: "or",
                0x0A: "or",
                0x10: "adc",
                0x12: "adc",
                0x18: "sbb",
                0x1A: "sbb",
                0x20: "and",
                0x22: "and",
                0x28: "sub",
                0x2A: "sub",
                0x30: "xor",
                0x32: "xor",
            }[opcode]
            return inst(mnemonic, operands)

        if opcode in {0x01, 0x03, 0x09, 0x0B, 0x11, 0x13, 0x19, 0x1B, 0x21, 0x23, 0x29, 0x2B, 0x31, 0x33, 0x39, 0x3B, 0x85, 0x89, 0x8B, 0x8D}:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=operand_size,
            )
            reg_operand = Operand.register(
                REGISTER_BY_INDEX[reg_index],
                size=operand_size,
            )
            if opcode in {0x01, 0x09, 0x11, 0x19, 0x21, 0x29, 0x31, 0x39, 0x85, 0x89}:
                operands = (rm_operand, reg_operand)
            else:
                operands = (reg_operand, rm_operand)
            mnemonic = {
                0x01: "add",
                0x03: "add",
                0x09: "or",
                0x0B: "or",
                0x11: "adc",
                0x13: "adc",
                0x19: "sbb",
                0x1B: "sbb",
                0x21: "and",
                0x23: "and",
                0x29: "sub",
                0x2B: "sub",
                0x31: "xor",
                0x33: "xor",
                0x39: "cmp",
                0x3B: "cmp",
                0x85: "test",
                0x89: "mov",
                0x8B: "mov",
                0x8D: "lea",
            }[opcode]
            return inst(mnemonic, operands)

        if opcode in {0x05, 0x0D, 0x15, 0x1D, 0x25, 0x2D, 0x35, 0x3D, 0xA9}:
            if operand_size == 16:
                value = _read_u16(code, offset)
                offset += 2
            else:
                value = _read_u32(code, offset)
                offset += 4
            mnemonic = {
                0x05: "add",
                0x0D: "or",
                0x15: "adc",
                0x1D: "sbb",
                0x25: "and",
                0x2D: "sub",
                0x35: "xor",
                0x3D: "cmp",
                0xA9: "test",
            }[opcode]
            return inst(
                mnemonic,
                (
                    Operand.register("eax", size=operand_size),
                    Operand.immediate_u32(value),
                ),
            )

        if opcode in {0x81, 0x83}:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=operand_size,
            )
            if opcode == 0x81:
                if operand_size == 16:
                    value = _read_u16(code, offset)
                    offset += 2
                else:
                    value = _read_u32(code, offset)
                    offset += 4
            else:
                value = _u32(_i8(self._read_u8(code, offset)))
                offset += 1
            mnemonic = {
                0: "add",
                1: "or",
                2: "adc",
                3: "sbb",
                4: "and",
                5: "sub",
                6: "xor",
                7: "cmp",
            }.get(reg_index)
            if mnemonic is None:
                raise X86DecodeError(
                    f"unsupported group1 /{reg_index} at {_hex32(address)}"
                )
            return inst(mnemonic, (rm_operand, Operand.immediate_u32(value)))

        if opcode == 0x80:
            reg_index, rm_operand, offset = self._decode_modrm(
                code, offset, operand_size=8
            )
            value = self._read_u8(code, offset)
            offset += 1
            mnemonic = {
                0: "add",
                1: "or",
                2: "adc",
                3: "sbb",
                4: "and",
                5: "sub",
                6: "xor",
                7: "cmp",
            }.get(reg_index)
            if mnemonic is None:
                raise X86DecodeError(
                    f"unsupported byte immediate group 80 /{reg_index} at {_hex32(address)}"
                )
            return inst(mnemonic, (rm_operand, Operand.immediate_u32(value)))

        if opcode in {0xC0, 0xC1}:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=8 if opcode == 0xC0 else operand_size,
            )
            count = self._read_u8(code, offset)
            offset += 1
            mnemonic = {
                0: "rol",
                1: "ror",
                3: "rcr",
                4: "shl",
                5: "shr",
                7: "sar",
            }.get(reg_index)
            if mnemonic is None:
                raise X86DecodeError(
                    f"unsupported shift {opcode:02X} /{reg_index} at {_hex32(address)}"
                )
            return inst(mnemonic, (rm_operand, Operand.immediate_u32(count)))

        if opcode in {0xD0, 0xD1}:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=8 if opcode == 0xD0 else operand_size,
            )
            mnemonic = {
                0: "rol",
                1: "ror",
                3: "rcr",
                4: "shl",
                5: "shr",
                7: "sar",
            }.get(reg_index)
            if mnemonic is None:
                raise X86DecodeError(
                    f"unsupported single-bit shift {opcode:02X} /{reg_index} at {_hex32(address)}"
                )
            return inst(mnemonic, (rm_operand, Operand.immediate_u32(1)))

        if opcode in {0xD2, 0xD3}:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=8 if opcode == 0xD2 else operand_size,
            )
            mnemonic = {
                0: "rol",
                1: "ror",
                3: "rcr",
                4: "shl",
                5: "shr",
                7: "sar",
            }.get(reg_index)
            if mnemonic is None:
                raise X86DecodeError(
                    f"unsupported variable shift {opcode:02X} /{reg_index} at {_hex32(address)}"
                )
            return inst(mnemonic, (rm_operand, Operand.register("cl", size=8)))

        if opcode == 0xC7:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=operand_size,
            )
            if reg_index != 0:
                raise X86DecodeError(f"unsupported C7 /{reg_index} at {_hex32(address)}")
            if operand_size == 16:
                value = _read_u16(code, offset)
                offset += 2
            else:
                value = _read_u32(code, offset)
                offset += 4
            return inst("mov", (rm_operand, Operand.immediate_u32(value)))

        if opcode == 0xC6:
            reg_index, rm_operand, offset = self._decode_modrm(
                code, offset, operand_size=8
            )
            if reg_index != 0:
                raise X86DecodeError(f"unsupported C6 /{reg_index} at {_hex32(address)}")
            value = self._read_u8(code, offset)
            offset += 1
            return inst("mov", (rm_operand, Operand.immediate_u32(value)))

        if opcode == 0xF7:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=operand_size,
            )
            if reg_index == 0:
                if operand_size == 16:
                    value = _read_u16(code, offset)
                    offset += 2
                else:
                    value = _read_u32(code, offset)
                    offset += 4
                return inst("test", (rm_operand, Operand.immediate_u32(value)))
            if reg_index == 2:
                return inst("not", (rm_operand,))
            if reg_index == 3:
                return inst("neg", (rm_operand,))
            if reg_index == 4:
                return inst("mul", (rm_operand,))
            if reg_index == 5:
                return inst("imul", (rm_operand,))
            if reg_index == 6:
                return inst("div", (rm_operand,))
            if reg_index == 7:
                return inst("idiv", (rm_operand,))
            raise X86DecodeError(f"unsupported F7 /{reg_index} at {_hex32(address)}")

        if opcode == 0xF6:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=8,
            )
            if reg_index == 0:
                value = self._read_u8(code, offset)
                offset += 1
                return inst("test", (rm_operand, Operand.immediate_u32(value)))
            if reg_index == 2:
                return inst("not", (rm_operand,))
            if reg_index == 3:
                return inst("neg", (rm_operand,))
            if reg_index == 5:
                return inst("imul", (rm_operand,))
            raise X86DecodeError(f"unsupported F6 /{reg_index} at {_hex32(address)}")

        if opcode == 0xFE:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=8,
            )
            if reg_index == 0:
                return inst("inc", (rm_operand,))
            if reg_index == 1:
                return inst("dec", (rm_operand,))
            raise X86DecodeError(f"unsupported FE /{reg_index} at {_hex32(address)}")

        if opcode == 0xFF:
            reg_index, rm_operand, offset = self._decode_modrm(
                code,
                offset,
                operand_size=operand_size,
            )
            if reg_index == 0:
                return inst("inc", (rm_operand,))
            if reg_index == 1:
                return inst("dec", (rm_operand,))
            if reg_index == 2:
                return inst("call", (rm_operand,))
            if reg_index == 4:
                return inst("jmp", (rm_operand,))
            if reg_index == 6:
                return inst("push", (rm_operand,))
            raise X86DecodeError(f"unsupported FF /{reg_index} at {_hex32(address)}")

        raise X86DecodeError(f"unsupported opcode {opcode:02X} at {_hex32(address)}")

    def _decode_modrm(
        self, code: bytes, offset: int, *, operand_size: int = 32
    ) -> tuple[int, Operand, int]:
        modrm = self._read_u8(code, offset)
        offset += 1
        mod = (modrm >> 6) & 0b11
        reg = (modrm >> 3) & 0b111
        rm = modrm & 0b111

        if mod == 0b11:
            if operand_size == 8:
                register = BYTE_REGISTER_BY_INDEX[rm]
            elif operand_size == 128:
                register = XMM_REGISTER_BY_INDEX[rm]
            else:
                register = REGISTER_BY_INDEX[rm]
            return reg, Operand.register(register, size=operand_size), offset

        base: str | None = None
        index: str | None = None
        scale = 1
        displacement = 0
        absolute: int | None = None

        if rm == 4:
            sib = self._read_u8(code, offset)
            offset += 1
            scale = 1 << ((sib >> 6) & 0b11)
            index_bits = (sib >> 3) & 0b111
            base_bits = sib & 0b111
            if index_bits != 4:
                index = REGISTER_BY_INDEX[index_bits]
            if base_bits == 5 and mod == 0:
                displacement = _i32(_read_u32(code, offset))
                offset += 4
            else:
                base = REGISTER_BY_INDEX[base_bits]
        elif rm == 5 and mod == 0:
            absolute = _read_u32(code, offset)
            offset += 4
        else:
            base = REGISTER_BY_INDEX[rm]

        if mod == 1:
            displacement = _i8(self._read_u8(code, offset))
            offset += 1
        elif mod == 2:
            displacement = _i32(_read_u32(code, offset))
            offset += 4

        return reg, Operand.memory(
            base=base,
            index=index,
            scale=scale,
            displacement=displacement,
            absolute=absolute,
            size=operand_size,
            segment=getattr(self, "_segment_override", None),
        ), offset

    @staticmethod
    def _read_u8(code: bytes, offset: int) -> int:
        if offset >= len(code):
            raise X86DecodeError("truncated instruction")
        return code[offset]


===== tools/recomp/x86_lifter.py:2481-2493 | lift_x86_function =====

def lift_x86_function(
    code: bytes,
    *,
    base_address: int,
    symbol: str = "lifted_function",
    max_instructions: int = 256,
) -> LiftedFunction:
    return X86Decoder().decode_function(
        code,
        base_address=base_address,
        symbol=symbol,
        max_instructions=max_instructions,
    )


===== tools/recomp/x86_lifter.py:2496-2508 | lift_x86_block =====

def lift_x86_block(
    code: bytes,
    *,
    base_address: int,
    symbol: str = "lifted_block",
    max_instructions: int = 128,
) -> LiftedFunction:
    return X86Decoder().decode_block(
        code,
        base_address=base_address,
        symbol=symbol,
        max_instructions=max_instructions,
    )


===== tools/recomp/x86_lifter.py:2529-4992 | execute_lifted_function =====

def execute_lifted_function(
    function: LiftedFunction,
    *,
    state: CpuState | None = None,
    memory: SparseMemory | None = None,
    call_handlers: dict[int, CallHandler] | None = None,
    unhandled_call_handler: CallHandler | None = None,
    block_loader: BlockLoader | None = None,
    step_observer: StepObserver | None = None,
    max_steps: int = 1024,
    record_instruction_trace: bool = True,
    record_trace: bool = True,
    trace_max_events: int | None = None,
    return_on_missing_instruction: bool = False,
    call_handler_yield_predicate: Callable[[int], bool] | None = None,
    execution_yield_predicate: Callable[[int], bool] | None = None,
    preserve_initial_eip: bool = False,
) -> ExecutionResult:
    active_state = state or CpuState()
    active_memory = memory or SparseMemory()
    if not preserve_initial_eip or active_state.eip == 0:
        active_state.eip = function.base_address
    handlers = call_handlers or {}
    trace = ExecutionTrace(enabled=record_trace, max_events=trace_max_events)
    instructions = {instruction.address: instruction for instruction in function.instructions}
    valid_addresses = set(instructions)
    steps = 0

    def install_block(target: int) -> bool:
        if block_loader is None:
            return False
        loaded_block = block_loader(target)
        if loaded_block is None:
            return False
        for loaded_instruction in loaded_block.instructions:
            instructions.setdefault(loaded_instruction.address, loaded_instruction)
            valid_addresses.add(loaded_instruction.address)
        return target in valid_addresses

    while max_steps == 0 or steps < max_steps:
        if step_observer is not None:
            step_observer(active_state, active_memory, trace, steps)
        if (
            execution_yield_predicate is not None
            and execution_yield_predicate(steps)
        ):
            return ExecutionResult(
                active_state,
                active_memory,
                trace,
                return_address=active_state.eip,
                steps=steps,
            )
        instruction = instructions.get(active_state.eip)
        if instruction is None and install_block(active_state.eip):
            instruction = instructions.get(active_state.eip)
        if instruction is None:
            trace.add(
                active_state.eip,
                "missing_instruction",
                eip=active_state.eip,
                eip_hex=_hex32(active_state.eip),
            )
            if return_on_missing_instruction:
                return ExecutionResult(
                    active_state,
                    active_memory,
                    trace,
                    return_address=active_state.eip,
                    steps=steps,
                )
            raise X86ExecutionError(
                f"no lifted instruction at {_hex32(active_state.eip)}",
                state=active_state,
                trace=trace,
                steps=steps,
            )
        if record_instruction_trace:
            trace.add(instruction.address, "instruction", text=instruction.text())
        steps += 1
        next_eip = instruction.next_address

        if instruction.mnemonic == "nop":
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"cld", "std"}:
            active_state.flags.df = instruction.mnemonic == "std"
            trace.add(
                instruction.address,
                "direction_flag",
                set=active_state.flags.df,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"cli", "sti"}:
            active_state.flags.interrupt_enabled = instruction.mnemonic == "sti"
            trace.add(
                instruction.address,
                "interrupt_flag",
                enabled=active_state.flags.interrupt_enabled,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "sahf":
            value = _read_low_u8_register(active_state, "ah")
            active_state.flags.sf = bool(value & 0x80)
            active_state.flags.zf = bool(value & 0x40)
            active_state.flags.af = bool(value & 0x10)
            active_state.flags.pf = bool(value & 0x04)
            active_state.flags.cf = bool(value & 0x01)
            trace.add(
                instruction.address,
                "store_ah_into_flags",
                value=value,
                value_hex=_hex32(value),
                **active_state.flags.to_dict(),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {
            "prefetch",
            "prefetchnta",
            "prefetcht0",
            "prefetcht1",
            "prefetcht2",
        }:
            operand = instruction.operands[0] if instruction.operands else None
            address = (
                _effective_address(active_state, operand)
                if operand is not None and operand.kind == "mem"
                else None
            )
            trace.add(
                instruction.address,
                "cache_prefetch",
                hint=instruction.mnemonic,
                memory_address=address,
                memory_address_hex=_hex32(address) if address is not None else None,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "emms":
            trace.add(instruction.address, "mmx_empty_state")
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"movq", "movntq"}:
            value = _read_mmx_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[1],
            )
            _write_mmx_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                value,
                non_temporal=instruction.mnemonic == "movntq",
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "movd":
            destination, source = instruction.operands
            if destination.kind == "reg" and destination.reg in MMX_REGISTER_NAMES:
                value = _read_operand(
                    active_state,
                    active_memory,
                    trace,
                    instruction,
                    source,
                )
                _write_mmx_operand(
                    active_state,
                    active_memory,
                    trace,
                    instruction,
                    destination,
                    value & 0xFFFFFFFF,
                )
            else:
                value = _read_mmx_operand(
                    active_state,
                    active_memory,
                    trace,
                    instruction,
                    source,
                )
                _write_operand(
                    active_state,
                    active_memory,
                    trace,
                    instruction,
                    destination,
                    value & 0xFFFFFFFF,
                )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {
            "punpcklbw",
            "punpcklwd",
            "punpckldq",
            "punpckhbw",
            "punpckhwd",
            "punpckhdq",
            "paddd",
            "packssdw",
        }:
            destination, source = instruction.operands
            left = _read_mmx_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                destination,
            )
            right = _read_mmx_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                source,
            )
            if instruction.mnemonic.startswith("punpck"):
                lane_bits = {
                    "punpcklbw": 8,
                    "punpcklwd": 16,
                    "punpckldq": 32,
                    "punpckhbw": 8,
                    "punpckhwd": 16,
                    "punpckhdq": 32,
                }[instruction.mnemonic]
                value = _mmx_unpack(
                    left,
                    right,
                    lane_bits=lane_bits,
                    high="h" in instruction.mnemonic[6:8],
                )
            elif instruction.mnemonic == "paddd":
                value = _mmx_paddd(left, right)
            else:
                value = _mmx_packssdw(left, right)
            _write_mmx_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                destination,
                value,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "pshufw":
            source = _read_mmx_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[1],
            )
            value = _mmx_pshufw(source, instruction.operands[2].immediate or 0)
            _write_mmx_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                value,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"psraw", "psrld", "pslld"}:
            destination = instruction.operands[0]
            value = _read_mmx_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                destination,
            )
            count = instruction.operands[1].immediate or 0
            shifted = _mmx_shift(value, instruction.mnemonic, count)
            _write_mmx_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                destination,
                shifted,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fwait":
            trace.add(instruction.address, "fpu_wait")
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fnclex":
            trace.add(instruction.address, "fpu_clear_exceptions")
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fnstsw":
            value = active_state.fpu_status_word & 0xFFFF
            _write_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                value,
            )
            trace.add(instruction.address, "fpu_store_status_word", value=value)
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "wbinvd":
            trace.add(instruction.address, "cache_writeback_invalidate")
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "sfence":
            trace.add(instruction.address, "store_fence")
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "out":
            trace.add(
                instruction.address,
                "port_write",
                port=active_state.get_register("edx") & 0xFFFF,
                value=active_state.get_register("eax") & 0xFF,
                size=1,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "in":
            port = active_state.get_register("edx") & 0xFFFF
            value = 0
            _write_u8_register(active_state, "al", value)
            trace.add(
                instruction.address,
                "port_read",
                port=port,
                value=value,
                size=1,
                modeled_default=True,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "sgdt":
            address = _effective_address(active_state, instruction.operands[0])
            active_memory.write(
                address,
                struct.pack(
                    "<HI",
                    active_state.gdtr_limit & 0xFFFF,
                    active_state.gdtr_base,
                ),
            )
            trace.add(
                instruction.address,
                "store_gdtr",
                memory_address=address,
                memory_address_hex=_hex32(address),
                limit=active_state.gdtr_limit & 0xFFFF,
                base=active_state.gdtr_base,
                base_hex=_hex32(active_state.gdtr_base),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fnstcw":
            _write_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                active_state.fpu_control_word,
            )
            trace.add(
                instruction.address,
                "fpu_store_control_word",
                value=active_state.fpu_control_word,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fldcw":
            value = _read_operand(
                active_state, active_memory, trace, instruction, instruction.operands[0]
            )
            active_state.fpu_control_word = value & 0xFFFF
            trace.add(
                instruction.address,
                "fpu_load_control_word",
                value=active_state.fpu_control_word,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fnsave":
            address = _effective_address(active_state, instruction.operands[0])
            payload = _x87_save_image(active_state)
            active_memory.write(address, payload)
            trace.add(
                instruction.address,
                "fpu_save_state",
                memory_address=address,
                memory_address_hex=_hex32(address),
                size=len(payload),
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.fpu_control_word = DEFAULT_X87_CONTROL_WORD
            active_state.fpu_status_word = 0
            active_state.fpu_stack.clear()
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "frstor":
            address = _effective_address(active_state, instruction.operands[0])
            payload = active_memory.read(address, X87_SAVE_IMAGE_SIZE)
            _x87_restore_image(active_state, payload)
            trace.add(
                instruction.address,
                "fpu_restore_state",
                memory_address=address,
                memory_address_hex=_hex32(address),
                size=len(payload),
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fild":
            value = _read_x87_integer_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
            )
            active_state.fpu_stack.insert(0, float(value))
            trace.add(
                instruction.address,
                "fpu_integer_load",
                value=value,
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fistp":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            operand = instruction.operands[0]
            value = active_state.fpu_stack.pop(0)
            integer = _x87_float_to_int(value, operand.size)
            _write_x87_integer_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                operand,
                integer,
            )
            trace.add(
                instruction.address,
                "fpu_integer_store_pop",
                value=value,
                integer=integer,
                integer_hex=_hex64(integer) if operand.size == 64 else _hex32(integer),
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fld":
            value = _read_x87_float_operand(
                active_state, active_memory, trace, instruction, instruction.operands[0]
            )
            active_state.fpu_stack.insert(0, value)
            trace.add(
                instruction.address,
                "fpu_load",
                value=value,
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {
            "fld1",
            "fldl2t",
            "fldl2e",
            "fldpi",
            "fldlg2",
            "fldln2",
            "fldz",
        }:
            constants = {
                "fld1": 1.0,
                "fldl2t": math.log2(10.0),
                "fldl2e": math.log2(math.e),
                "fldpi": math.pi,
                "fldlg2": math.log10(2.0),
                "fldln2": math.log(2.0),
                "fldz": 0.0,
            }
            value = constants[instruction.mnemonic]
            active_state.fpu_stack.insert(0, value)
            trace.add(
                instruction.address,
                "fpu_load_constant",
                constant=instruction.mnemonic[3:],
                value=value,
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "frndint":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            active_state.fpu_stack[0] = float(round(active_state.fpu_stack[0]))
            trace.add(
                instruction.address,
                "fpu_round_integer",
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fscale":
            if len(active_state.fpu_stack) < 2:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            scale = math.trunc(active_state.fpu_stack[1])
            active_state.fpu_stack[0] = math.ldexp(active_state.fpu_stack[0], scale)
            trace.add(
                instruction.address,
                "fpu_scale",
                scale=scale,
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "f2xm1":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            active_state.fpu_stack[0] = math.pow(2.0, active_state.fpu_stack[0]) - 1.0
            trace.add(
                instruction.address,
                "fpu_two_to_x_minus_one",
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"fsqrt", "fsin", "fcos"}:
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            operations = {
                "fsqrt": math.sqrt,
                "fsin": math.sin,
                "fcos": math.cos,
            }
            active_state.fpu_stack[0] = operations[instruction.mnemonic](
                active_state.fpu_stack[0]
            )
            trace.add(
                instruction.address,
                "fpu_unary_math",
                function=instruction.mnemonic,
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fyl2x":
            if len(active_state.fpu_stack) < 2:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            x = active_state.fpu_stack.pop(0)
            y = active_state.fpu_stack[0]
            result = y * math.log2(x) if x > 0.0 else float("nan")
            active_state.fpu_stack[0] = result
            trace.add(
                instruction.address,
                "fpu_y_log2_x",
                x=x,
                y=y,
                result=result,
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fptan":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            argument = active_state.fpu_stack[0]
            result = math.tan(argument)
            active_state.fpu_stack[0] = result
            active_state.fpu_stack.insert(0, 1.0)
            trace.add(
                instruction.address,
                "fpu_partial_tangent",
                argument=argument,
                result=result,
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fpatan":
            if len(active_state.fpu_stack) < 2:
                raise X86ExecutionError(
                    f"x87 stack underflow at {_hex32(instruction.address)}"
                )
            x = active_state.fpu_stack.pop(0)
            y = active_state.fpu_stack[0]
            result = math.atan2(y, x)
            active_state.fpu_stack[0] = result
            trace.add(
                instruction.address,
                "fpu_partial_arctangent",
                x=x,
                y=y,
                result=result,
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"fcom", "fcomp"}:
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            value = _read_x87_float_operand(
                active_state, active_memory, trace, instruction, instruction.operands[0]
            )
            top = active_state.fpu_stack[0]
            comparison = _x87_compare(top, value)
            active_state.fpu_status_word = _x87_compare_status_word(
                active_state.fpu_status_word,
                comparison,
            )
            if instruction.mnemonic == "fcomp":
                active_state.fpu_stack.pop(0)
            trace.add(
                instruction.address,
                "fpu_compare_pop" if instruction.mnemonic == "fcomp" else "fpu_compare",
                value=value,
                top=top,
                comparison=comparison,
                status_word=active_state.fpu_status_word,
                status_word_hex=f"0x{active_state.fpu_status_word:04X}",
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fcompp":
            if len(active_state.fpu_stack) < 2:
                raise X86ExecutionError(
                    f"x87 stack underflow at {_hex32(instruction.address)}"
                )
            top = active_state.fpu_stack[0]
            value = active_state.fpu_stack[1]
            comparison = _x87_compare(top, value)
            active_state.fpu_status_word = _x87_compare_status_word(
                active_state.fpu_status_word,
                comparison,
            )
            del active_state.fpu_stack[:2]
            trace.add(
                instruction.address,
                "fpu_compare_pop_twice",
                value=value,
                top=top,
                comparison=comparison,
                status_word=active_state.fpu_status_word,
                status_word_hex=f"0x{active_state.fpu_status_word:04X}",
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fadd":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            value = _read_x87_float_operand(
                active_state, active_memory, trace, instruction, instruction.operands[0]
            )
            active_state.fpu_stack[0] += value
            trace.add(
                instruction.address,
                "fpu_add",
                value=value,
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fmul":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            value = _read_x87_float_operand(
                active_state, active_memory, trace, instruction, instruction.operands[0]
            )
            active_state.fpu_stack[0] *= value
            trace.add(
                instruction.address,
                "fpu_multiply",
                value=value,
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fsub":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            value = _read_x87_float_operand(
                active_state, active_memory, trace, instruction, instruction.operands[0]
            )
            active_state.fpu_stack[0] -= value
            trace.add(
                instruction.address,
                "fpu_subtract",
                value=value,
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"fiadd", "fimul"}:
            if not active_state.fpu_stack:
                raise X86ExecutionError(
                    f"x87 stack underflow at {_hex32(instruction.address)}"
                )
            value = _read_x87_integer_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
            )
            if instruction.mnemonic == "fiadd":
                active_state.fpu_stack[0] += float(value)
            else:
                active_state.fpu_stack[0] *= float(value)
            trace.add(
                instruction.address,
                "fpu_integer_add"
                if instruction.mnemonic == "fiadd"
                else "fpu_integer_multiply",
                value=value,
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fisub":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            value = _read_x87_integer_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
            )
            active_state.fpu_stack[0] -= float(value)
            trace.add(
                instruction.address,
                "fpu_integer_subtract",
                value=value,
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fidiv":
            if not active_state.fpu_stack:
                raise X86ExecutionError(
                    f"x87 stack underflow at {_hex32(instruction.address)}"
                )
            value = _read_x87_integer_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
            )
            active_state.fpu_stack[0] = _x87_divide(
                active_state.fpu_stack[0],
                float(value),
            )
            trace.add(
                instruction.address,
                "fpu_integer_divide",
                value=value,
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fsubr":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            value = _read_x87_float_operand(
                active_state, active_memory, trace, instruction, instruction.operands[0]
            )
            active_state.fpu_stack[0] = value - active_state.fpu_stack[0]
            trace.add(
                instruction.address,
                "fpu_reverse_subtract",
                value=value,
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fdiv":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            value = _read_x87_float_operand(
                active_state, active_memory, trace, instruction, instruction.operands[0]
            )
            active_state.fpu_stack[0] = _x87_divide(active_state.fpu_stack[0], value)
            trace.add(
                instruction.address,
                "fpu_divide",
                value=value,
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fdivr":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            value = _read_x87_float_operand(
                active_state, active_memory, trace, instruction, instruction.operands[0]
            )
            active_state.fpu_stack[0] = _x87_divide(value, active_state.fpu_stack[0])
            trace.add(
                instruction.address,
                "fpu_reverse_divide",
                value=value,
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {
            "fadd_st",
            "fmul_st",
            "fsubr_st",
            "fsub_st",
            "fdivr_st",
            "fdiv_st",
        }:
            index = _x87_stack_operand_index(
                active_state, instruction, instruction.operands[0]
            )
            top = active_state.fpu_stack[0]
            target = active_state.fpu_stack[index]
            if instruction.mnemonic == "fadd_st":
                result = target + top
            elif instruction.mnemonic == "fmul_st":
                result = target * top
            elif instruction.mnemonic == "fsubr_st":
                result = top - target
            elif instruction.mnemonic == "fsub_st":
                result = target - top
            elif instruction.mnemonic == "fdivr_st":
                result = _x87_divide(top, target)
            else:
                result = _x87_divide(target, top)
            active_state.fpu_stack[index] = result
            trace.add(
                instruction.address,
                "fpu_stack_arithmetic",
                arithmetic_kind=instruction.mnemonic,
                stack_index=index,
                top=top,
                target=target,
                result=result,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fchs":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            active_state.fpu_stack[0] = -active_state.fpu_stack[0]
            trace.add(
                instruction.address,
                "fpu_change_sign",
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fabs":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            active_state.fpu_stack[0] = abs(active_state.fpu_stack[0])
            trace.add(
                instruction.address,
                "fpu_absolute_value",
                result=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "ftst":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            top = active_state.fpu_stack[0]
            comparison = _x87_compare(top, 0.0)
            active_state.fpu_status_word = _x87_compare_status_word(
                active_state.fpu_status_word,
                comparison,
            )
            trace.add(
                instruction.address,
                "fpu_test",
                top=top,
                comparison=comparison,
                status_word=active_state.fpu_status_word,
                status_word_hex=f"0x{active_state.fpu_status_word:04X}",
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fxch":
            index = _x87_stack_operand_index(
                active_state, instruction, instruction.operands[0]
            )
            active_state.fpu_stack[0], active_state.fpu_stack[index] = (
                active_state.fpu_stack[index],
                active_state.fpu_stack[0],
            )
            trace.add(
                instruction.address,
                "fpu_exchange",
                stack_index=index,
                top=active_state.fpu_stack[0],
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "ffree":
            index = _x87_stack_operand_index(
                active_state,
                instruction,
                instruction.operands[0],
            )
            value = active_state.fpu_stack.pop(index)
            trace.add(
                instruction.address,
                "fpu_free",
                stack_index=index,
                value=value,
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "faddp":
            index = _x87_stack_operand_index(
                active_state, instruction, instruction.operands[0]
            )
            value = active_state.fpu_stack[0]
            active_state.fpu_stack[index] += value
            result = active_state.fpu_stack[index]
            active_state.fpu_stack.pop(0)
            trace.add(
                instruction.address,
                "fpu_add_pop",
                stack_index=index,
                value=value,
                result=result,
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fmulp":
            index = _x87_stack_operand_index(
                active_state, instruction, instruction.operands[0]
            )
            value = active_state.fpu_stack[0]
            active_state.fpu_stack[index] *= value
            result = active_state.fpu_stack[index]
            active_state.fpu_stack.pop(0)
            trace.add(
                instruction.address,
                "fpu_multiply_pop",
                stack_index=index,
                value=value,
                result=result,
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fsubp":
            index = _x87_stack_operand_index(
                active_state, instruction, instruction.operands[0]
            )
            value = active_state.fpu_stack[0]
            active_state.fpu_stack[index] -= value
            result = active_state.fpu_stack[index]
            active_state.fpu_stack.pop(0)
            trace.add(
                instruction.address,
                "fpu_subtract_pop",
                stack_index=index,
                value=value,
                result=result,
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fsubrp":
            index = _x87_stack_operand_index(
                active_state, instruction, instruction.operands[0]
            )
            top = active_state.fpu_stack[0]
            target = active_state.fpu_stack[index]
            active_state.fpu_stack[index] = top - target
            result = active_state.fpu_stack[index]
            active_state.fpu_stack.pop(0)
            trace.add(
                instruction.address,
                "fpu_reverse_subtract_pop",
                stack_index=index,
                top=top,
                target=target,
                result=result,
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fdivrp":
            index = _x87_stack_operand_index(
                active_state,
                instruction,
                instruction.operands[0],
            )
            top = active_state.fpu_stack[0]
            target = active_state.fpu_stack[index]
            active_state.fpu_stack[index] = _x87_divide(top, target)
            result = active_state.fpu_stack[index]
            active_state.fpu_stack.pop(0)
            trace.add(
                instruction.address,
                "fpu_reverse_divide_pop",
                stack_index=index,
                top=top,
                target=target,
                result=result,
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fdivp":
            index = _x87_stack_operand_index(
                active_state, instruction, instruction.operands[0]
            )
            value = active_state.fpu_stack[0]
            active_state.fpu_stack[index] = _x87_divide(
                active_state.fpu_stack[index],
                value,
            )
            result = active_state.fpu_stack[index]
            active_state.fpu_stack.pop(0)
            trace.add(
                instruction.address,
                "fpu_divide_pop",
                stack_index=index,
                value=value,
                result=result,
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fst":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            value = active_state.fpu_stack[0]
            operand = instruction.operands[0]
            if operand.kind == "imm":
                index = _x87_stack_operand_index(active_state, instruction, operand)
                active_state.fpu_stack[index] = value
                trace.add(
                    instruction.address,
                    "fpu_store_stack",
                    stack_index=index,
                    value=value,
                    stack_depth=len(active_state.fpu_stack),
                )
            else:
                _write_float32_operand(
                    active_state,
                    active_memory,
                    trace,
                    instruction,
                    operand,
                    value,
                )
                trace.add(
                    instruction.address,
                    "fpu_store",
                    value=value,
                    stack_depth=len(active_state.fpu_stack),
                )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "fstp":
            if not active_state.fpu_stack:
                raise X86ExecutionError(f"x87 stack underflow at {_hex32(instruction.address)}")
            operand = instruction.operands[0]
            value = active_state.fpu_stack[0]
            if operand.kind == "imm":
                index = _x87_stack_operand_index(active_state, instruction, operand)
                active_state.fpu_stack[index] = value
                active_state.fpu_stack.pop(0)
            else:
                active_state.fpu_stack.pop(0)
                _write_float32_operand(
                    active_state,
                    active_memory,
                    trace,
                    instruction,
                    operand,
                    value,
                )
            trace.add(
                instruction.address,
                "fpu_store_pop",
                value=value,
                stack_depth=len(active_state.fpu_stack),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "stmxcsr":
            _write_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                active_state.mxcsr,
            )
            trace.add(instruction.address, "sse_store_mxcsr", value=active_state.mxcsr)
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "ldmxcsr":
            value = _read_operand(
                active_state, active_memory, trace, instruction, instruction.operands[0]
            )
            active_state.mxcsr = _u32(value)
            trace.add(instruction.address, "sse_load_mxcsr", value=active_state.mxcsr)
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"cvttss2si", "cvtss2si"}:
            value = _read_xmm_scalar_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[1],
            )
            integer = (
                _sse_truncate_float32_to_i32(value)
                if instruction.mnemonic == "cvttss2si"
                else _sse_round_float32_to_i32(value, active_state.mxcsr)
            )
            _write_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                integer,
            )
            trace.add(
                instruction.address,
                "sse_truncate_scalar_float_to_i32"
                if instruction.mnemonic == "cvttss2si"
                else "sse_round_scalar_float_to_i32",
                value=value,
                integer=integer,
                integer_hex=_hex32(integer),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "cvtps2pi":
            lanes = _read_packed_float64_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[1],
            )
            low = _sse_round_float32_to_i32(lanes[0], active_state.mxcsr)
            high = _sse_round_float32_to_i32(lanes[1], active_state.mxcsr)
            _write_mmx_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                low | (high << 32),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"movaps", "movups", "movntps"}:
            value = _read_xmm_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[1],
            )
            _write_xmm_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                value,
                non_temporal=instruction.mnemonic == "movntps",
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "movss":
            destination = instruction.operands[0]
            source = instruction.operands[1]
            value = _read_xmm_scalar_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                source,
            )
            if destination.kind == "reg":
                current = active_state.get_xmm_register(destination.reg or "")
                vector = (
                    (value, 0.0, 0.0, 0.0)
                    if source.kind == "mem"
                    else (value, current[1], current[2], current[3])
                )
                _write_xmm_operand(
                    active_state,
                    active_memory,
                    trace,
                    instruction,
                    destination,
                    vector,
                )
            else:
                _write_float32_operand(
                    active_state,
                    active_memory,
                    trace,
                    instruction,
                    destination,
                    value,
                )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "rsqrtss":
            destination = instruction.operands[0]
            value = _read_xmm_scalar_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[1],
            )
            current = active_state.get_xmm_register(destination.reg or "")
            result = _sse_reciprocal_sqrt_approximation(value)
            _write_xmm_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                destination,
                (result, current[1], current[2], current[3]),
            )
            trace.add(
                instruction.address,
                "xmm_reciprocal_sqrt_scalar",
                value=value,
                result=result,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "sqrtps":
            source = _read_xmm_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[1],
            )
            result = tuple(math.sqrt(value) if value >= 0.0 else float("nan") for value in source)
            _write_xmm_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                result,
            )
            trace.add(instruction.address, "xmm_square_root_packed_float", result=list(result))
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"addps", "mulps", "minps", "maxps"}:
            destination = _read_xmm_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
            )
            source = _read_xmm_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[1],
            )
            if instruction.mnemonic == "addps":
                result = tuple(left + right for left, right in zip(destination, source))
                operation = "xmm_add_packed_float"
            elif instruction.mnemonic == "mulps":
                result = tuple(left * right for left, right in zip(destination, source))
                operation = "xmm_multiply_packed_float"
            else:
                minimum = instruction.mnemonic == "minps"
                result = tuple(
                    _sse_minmax_float32(left, right, minimum=minimum)
                    for left, right in zip(destination, source)
                )
                operation = (
                    "xmm_minimum_packed_float"
                    if minimum
                    else "xmm_maximum_packed_float"
                )
            _write_xmm_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                result,
            )
            trace.add(instruction.address, operation, result=list(result))
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "shufps":
            destination = _read_xmm_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
            )
            source = _read_xmm_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[1],
            )
            immediate = instruction.operands[2].immediate or 0
            result = _xmm_shuffle(destination, source, immediate)
            _write_xmm_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                result,
            )
            trace.add(
                instruction.address,
                "xmm_shuffle_packed_float",
                immediate=immediate,
                immediate_hex=_hex32(immediate),
                result=list(result),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"unpcklps", "unpckhps", "movlhps", "movhlps"}:
            destination = _read_xmm_operand(
                active_state, active_memory, trace, instruction, instruction.operands[0]
            )
            source = _read_xmm_operand(
                active_state, active_memory, trace, instruction, instruction.operands[1]
            )
            if instruction.mnemonic == "unpcklps":
                result = (destination[0], source[0], destination[1], source[1])
            elif instruction.mnemonic == "unpckhps":
                result = (destination[2], source[2], destination[3], source[3])
            elif instruction.mnemonic == "movlhps":
                result = (destination[0], destination[1], source[0], source[1])
            else:
                result = (source[2], source[3], destination[2], destination[3])
            _write_xmm_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                result,
            )
            trace.add(
                instruction.address,
                f"xmm_{instruction.mnemonic}",
                result=list(result),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"movlps_store", "movhps_store"}:
            source = _read_xmm_operand(
                active_state, active_memory, trace, instruction, instruction.operands[1]
            )
            lanes = source[:2] if instruction.mnemonic == "movlps_store" else source[2:]
            address = _effective_address(active_state, instruction.operands[0])
            active_memory.write(address, struct.pack("<2f", *lanes))
            trace.add(
                instruction.address,
                "xmm_store_low_packed_float" if instruction.mnemonic == "movlps_store"
                else "xmm_store_high_packed_float",
                memory_address=address,
                memory_address_hex=_hex32(address),
                value=list(lanes),
                size=8,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "mov":
            value = _read_operand(active_state, active_memory, trace, instruction, instruction.operands[1])
            _write_operand(active_state, active_memory, trace, instruction, instruction.operands[0], value)
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "xchg":
            left = _read_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
            )
            right = _read_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[1],
            )
            _write_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                right,
            )
            _write_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[1],
                left,
            )
            trace.add(
                instruction.address,
                "exchange",
                left=left,
                left_hex=_hex32(left),
                right=right,
                right_hex=_hex32(right),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "xadd":
            destination = instruction.operands[0]
            source = instruction.operands[1]
            left = _read_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                destination,
            )
            right = _read_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                source,
            )
            result = _binary_result("add", left, right)
            _write_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                destination,
                result,
            )
            _write_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                source,
                left,
            )
            _update_flags(
                active_state.flags,
                "add",
                left,
                right,
                result,
                size=destination.size,
            )
            trace.add(
                instruction.address,
                "exchange_add",
                left=left,
                right=right,
                result=result,
                **active_state.flags.to_dict(),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "cmpxchg":
            destination, source, accumulator = instruction.operands
            destination_value = _read_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                destination,
            )
            accumulator_value = _read_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                accumulator,
            )
            result = _binary_result("sub", accumulator_value, destination_value)
            _update_flags(
                active_state.flags,
                "sub",
                accumulator_value,
                destination_value,
                result,
                size=destination.size,
            )
            if active_state.flags.zf:
                source_value = _read_operand(
                    active_state,
                    active_memory,
                    trace,
                    instruction,
                    source,
                )
                _write_operand(
                    active_state,
                    active_memory,
                    trace,
                    instruction,
                    destination,
                    source_value,
                )
            else:
                _write_operand(
                    active_state,
                    active_memory,
                    trace,
                    instruction,
                    accumulator,
                    destination_value,
                )
            trace.add(
                instruction.address,
                "compare_exchange",
                accumulator=accumulator_value,
                destination=destination_value,
                exchanged=active_state.flags.zf,
                **active_state.flags.to_dict(),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "movzx":
            value = _read_operand(active_state, active_memory, trace, instruction, instruction.operands[1])
            _write_operand(active_state, active_memory, trace, instruction, instruction.operands[0], value)
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "movsx":
            source = instruction.operands[1]
            value = _read_operand(active_state, active_memory, trace, instruction, source)
            _write_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                _sign_extend(value, source.size),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "setcc":
            if instruction.condition is None:
                raise X86ExecutionError("setcc missing condition")
            value = 1 if _evaluate_condition(active_state.flags, instruction.condition) else 0
            _write_operand(active_state, active_memory, trace, instruction, instruction.operands[0], value)
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "lea":
            address = _effective_address(active_state, instruction.operands[1])
            _write_operand(active_state, active_memory, trace, instruction, instruction.operands[0], address)
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "bsf":
            value = _read_operand(active_state, active_memory, trace, instruction, instruction.operands[1])
            if value == 0:
                active_state.flags.zf = True
            else:
                mask = (1 << instruction.operands[1].size) - 1
                masked = value & mask
                index = (masked & -masked).bit_length() - 1
                _write_operand(
                    active_state,
                    active_memory,
                    trace,
                    instruction,
                    instruction.operands[0],
                    index,
                )
                active_state.flags.zf = False
            trace.add(instruction.address, "flags", **active_state.flags.to_dict())
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"add", "adc", "sub", "sbb", "xor", "and", "or"}:
            lhs = _read_operand(active_state, active_memory, trace, instruction, instruction.operands[0])
            rhs = _read_operand(active_state, active_memory, trace, instruction, instruction.operands[1])
            operation = {
                "adc": "add",
                "sbb": "sub",
            }.get(instruction.mnemonic, instruction.mnemonic)
            if instruction.mnemonic in {"adc", "sbb"}:
                rhs += 1 if active_state.flags.cf else 0
            result = _binary_result(operation, lhs, rhs)
            _write_operand(active_state, active_memory, trace, instruction, instruction.operands[0], result)
            _update_flags(
                active_state.flags,
                operation,
                lhs,
                rhs,
                result,
                size=instruction.operands[0].size,
            )
            trace.add(instruction.address, "flags", **active_state.flags.to_dict())
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "imul":
            if len(instruction.operands) == 1:
                operand = instruction.operands[0]
                if operand.size == 32:
                    lhs = _signed_int(active_state.get_register("eax"), 32)
                    rhs = _signed_int(
                        _read_operand(
                            active_state, active_memory, trace, instruction, operand
                        ),
                        32,
                    )
                    product = lhs * rhs
                    result = product & 0xFFFFFFFFFFFFFFFF
                    low = result & 0xFFFFFFFF
                    high = (result >> 32) & 0xFFFFFFFF
                    active_state.set_register("eax", low)
                    active_state.set_register("edx", high)
                    active_state.flags.cf = active_state.flags.of = (
                        product != _signed_int(low, 32)
                    )
                    trace.add(
                        instruction.address,
                        "signed_multiply",
                        lhs=lhs,
                        rhs=rhs,
                        product=product,
                        low=low,
                        low_hex=_hex32(low),
                        high=high,
                        high_hex=_hex32(high),
                    )
                    trace.add(
                        instruction.address, "flags", **active_state.flags.to_dict()
                    )
                    active_state.eip = next_eip
                    continue
                if operand.size != 8:
                    raise X86ExecutionError("unsupported one-operand imul size")
                lhs = _signed_int(active_state.get_register("eax") & 0xFF, 8)
                rhs = _signed_int(
                    _read_operand(
                        active_state, active_memory, trace, instruction, operand
                    ),
                    8,
                )
                product = lhs * rhs
                result = product & 0xFFFF
                active_state.set_register(
                    "eax",
                    (active_state.get_register("eax") & 0xFFFF0000) | result,
                )
                active_state.flags.cf = active_state.flags.of = (
                    product != _signed_int(result & 0xFF, 8)
                )
                trace.add(
                    instruction.address,
                    "signed_multiply",
                    lhs=lhs,
                    rhs=rhs,
                    product=product,
                    result=result,
                    result_hex=_hex32(result),
                )
                trace.add(
                    instruction.address, "flags", **active_state.flags.to_dict()
                )
                active_state.eip = next_eip
                continue
            destination = instruction.operands[0]
            size = destination.size
            lhs_operand = (
                instruction.operands[1]
                if len(instruction.operands) == 3
                else destination
            )
            rhs_operand = (
                instruction.operands[2]
                if len(instruction.operands) == 3
                else instruction.operands[1]
            )
            lhs = _signed_int(
                _read_operand(active_state, active_memory, trace, instruction, lhs_operand),
                lhs_operand.size,
            )
            rhs = _signed_int(
                _read_operand(active_state, active_memory, trace, instruction, rhs_operand),
                rhs_operand.size,
            )
            product = lhs * rhs
            mask = (1 << size) - 1
            result = product & mask
            _write_operand(active_state, active_memory, trace, instruction, destination, result)
            active_state.flags.cf = active_state.flags.of = (
                product != _signed_int(result, size)
            )
            trace.add(
                instruction.address,
                "signed_multiply",
                lhs=lhs,
                rhs=rhs,
                product=product,
                result=result,
                result_hex=_hex32(result),
            )
            trace.add(instruction.address, "flags", **active_state.flags.to_dict())
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"cmp", "test"}:
            lhs = _read_operand(active_state, active_memory, trace, instruction, instruction.operands[0])
            rhs = _read_operand(active_state, active_memory, trace, instruction, instruction.operands[1])
            result = _binary_result("sub" if instruction.mnemonic == "cmp" else "and", lhs, rhs)
            _update_flags(
                active_state.flags,
                "sub" if instruction.mnemonic == "cmp" else "and",
                lhs,
                rhs,
                result,
                size=instruction.operands[0].size,
            )
            trace.add(instruction.address, "flags", **active_state.flags.to_dict())
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"inc", "dec"}:
            lhs = _read_operand(active_state, active_memory, trace, instruction, instruction.operands[0])
            old_cf = active_state.flags.cf
            rhs = 1
            operation = "add" if instruction.mnemonic == "inc" else "sub"
            result = _binary_result(operation, lhs, rhs)
            _write_operand(active_state, active_memory, trace, instruction, instruction.operands[0], result)
            _update_flags(
                active_state.flags,
                operation,
                lhs,
                rhs,
                result,
                size=instruction.operands[0].size,
            )
            active_state.flags.cf = old_cf
            trace.add(instruction.address, "flags", **active_state.flags.to_dict())
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "neg":
            lhs = _read_operand(active_state, active_memory, trace, instruction, instruction.operands[0])
            result = _binary_result("sub", 0, lhs)
            _write_operand(active_state, active_memory, trace, instruction, instruction.operands[0], result)
            _update_flags(
                active_state.flags,
                "sub",
                0,
                lhs,
                result,
                size=instruction.operands[0].size,
            )
            trace.add(instruction.address, "flags", **active_state.flags.to_dict())
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "not":
            value = _read_operand(active_state, active_memory, trace, instruction, instruction.operands[0])
            _write_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                ~value,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"shl", "shr", "sar"}:
            lhs = _read_operand(active_state, active_memory, trace, instruction, instruction.operands[0])
            count = _read_operand(active_state, active_memory, trace, instruction, instruction.operands[1]) & 0x1F
            result = _shift_result(
                instruction.mnemonic,
                lhs,
                count,
                size=instruction.operands[0].size,
            )
            _write_operand(active_state, active_memory, trace, instruction, instruction.operands[0], result)
            _update_shift_flags(
                active_state.flags,
                instruction.mnemonic,
                lhs,
                count,
                result,
                size=instruction.operands[0].size,
            )
            trace.add(instruction.address, "flags", **active_state.flags.to_dict())
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"rol", "ror", "rcr"}:
            operand = instruction.operands[0]
            value = _read_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                operand,
            )
            raw_count = _read_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[1],
            )
            result, carry, overflow, effective_count = _rotate_result(
                instruction.mnemonic,
                value,
                raw_count,
                size=operand.size,
                carry=active_state.flags.cf,
            )
            _write_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                operand,
                result,
            )
            if effective_count:
                active_state.flags.cf = carry
                if effective_count == 1:
                    active_state.flags.of = overflow
            trace.add(
                instruction.address,
                {
                    "rol": "rotate_left",
                    "ror": "rotate_right",
                    "rcr": "rotate_right_through_carry",
                }[instruction.mnemonic],
                count=effective_count,
                result=result,
                result_hex=_hex32(result),
                **active_state.flags.to_dict(),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"shld", "shrd"}:
            destination = _read_operand(
                active_state, active_memory, trace, instruction, instruction.operands[0]
            )
            source = _read_operand(
                active_state, active_memory, trace, instruction, instruction.operands[1]
            )
            count = _read_operand(
                active_state, active_memory, trace, instruction, instruction.operands[2]
            ) & 0x1F
            result = _double_shift_result(
                instruction.mnemonic,
                destination,
                source,
                count,
            )
            _write_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
                result,
            )
            _update_double_shift_flags(
                active_state.flags,
                instruction.mnemonic,
                destination,
                count,
                result,
            )
            trace.add(instruction.address, "flags", **active_state.flags.to_dict())
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "push":
            value = _read_operand(active_state, active_memory, trace, instruction, instruction.operands[0])
            _push(active_state, active_memory, trace, instruction, value)
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "pushfd":
            flags = active_state.flags
            value = (
                0x00000002
                | int(flags.cf)
                | (int(flags.pf) << 2)
                | (int(flags.af) << 4)
                | (int(flags.zf) << 6)
                | (int(flags.sf) << 7)
                | (int(flags.interrupt_enabled) << 9)
                | (int(flags.df) << 10)
                | (int(flags.of) << 11)
            )
            _push(active_state, active_memory, trace, instruction, value)
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "pop":
            value = _pop(active_state, active_memory, trace, instruction)
            _write_operand(active_state, active_memory, trace, instruction, instruction.operands[0], value)
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "popfd":
            value = _pop(active_state, active_memory, trace, instruction)
            flags = active_state.flags
            flags.cf = bool(value & (1 << 0))
            flags.pf = bool(value & (1 << 2))
            flags.af = bool(value & (1 << 4))
            flags.zf = bool(value & (1 << 6))
            flags.sf = bool(value & (1 << 7))
            flags.interrupt_enabled = bool(value & (1 << 9))
            flags.df = bool(value & (1 << 10))
            flags.of = bool(value & (1 << 11))
            trace.add(instruction.address, "flags_restore", **flags.to_dict())
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "leave":
            active_state.set_register("esp", active_state.get_register("ebp"))
            value = _pop(active_state, active_memory, trace, instruction)
            active_state.set_register("ebp", value)
            trace.add(
                instruction.address,
                "stack_frame",
                esp=active_state.get_register("esp"),
                ebp=active_state.get_register("ebp"),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "cdq":
            eax = active_state.get_register("eax")
            edx = 0xFFFFFFFF if eax & 0x80000000 else 0
            active_state.set_register("edx", edx)
            trace.add(
                instruction.address,
                "register_write",
                register="edx",
                value=edx,
                value_hex=_hex32(edx),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "rdtsc":
            value = active_state.timestamp_counter & 0xFFFFFFFFFFFFFFFF
            active_state.set_register("eax", value & 0xFFFFFFFF)
            active_state.set_register("edx", value >> 32)
            active_state.timestamp_counter = (
                value + DETERMINISTIC_TSC_STEP
            ) & 0xFFFFFFFFFFFFFFFF
            trace.add(
                instruction.address,
                "timestamp_counter",
                value=value,
                value_hex=f"0x{value:016X}",
                next_value=active_state.timestamp_counter,
                next_value_hex=f"0x{active_state.timestamp_counter:016X}",
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "idiv":
            divisor = _i32(
                _read_operand(
                    active_state,
                    active_memory,
                    trace,
                    instruction,
                    instruction.operands[0],
                )
            )
            if divisor == 0:
                raise X86ExecutionError(f"signed division by zero at {_hex32(instruction.address)}")
            high = _i32(active_state.get_register("edx"))
            low = active_state.get_register("eax")
            dividend = (high << 32) | low
            quotient_abs = abs(dividend) // abs(divisor)
            quotient = -quotient_abs if (dividend < 0) ^ (divisor < 0) else quotient_abs
            if quotient < -0x80000000 or quotient > 0x7FFFFFFF:
                raise X86ExecutionError(f"signed division overflow at {_hex32(instruction.address)}")
            remainder = dividend - (quotient * divisor)
            active_state.set_register("eax", quotient)
            active_state.set_register("edx", remainder)
            trace.add(
                instruction.address,
                "signed_divide",
                dividend=dividend,
                divisor=divisor,
                quotient=quotient,
                quotient_hex=_hex32(quotient),
                remainder=remainder,
                remainder_hex=_hex32(remainder),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "div":
            divisor = _read_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
            )
            if divisor == 0:
                raise X86ExecutionError(f"unsigned division by zero at {_hex32(instruction.address)}")
            dividend = (
                (active_state.get_register("edx") << 32)
                | active_state.get_register("eax")
            )
            quotient = dividend // divisor
            remainder = dividend % divisor
            if quotient > 0xFFFFFFFF:
                raise X86ExecutionError(f"unsigned division overflow at {_hex32(instruction.address)}")
            active_state.set_register("eax", quotient)
            active_state.set_register("edx", remainder)
            trace.add(
                instruction.address,
                "unsigned_divide",
                dividend=dividend,
                divisor=divisor,
                quotient=quotient,
                quotient_hex=_hex32(quotient),
                remainder=remainder,
                remainder_hex=_hex32(remainder),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "mul":
            multiplier = _read_operand(
                active_state,
                active_memory,
                trace,
                instruction,
                instruction.operands[0],
            )
            multiplicand = active_state.get_register("eax")
            product = multiplicand * multiplier
            low = product & 0xFFFFFFFF
            high = (product >> 32) & 0xFFFFFFFF
            active_state.set_register("eax", low)
            active_state.set_register("edx", high)
            active_state.flags.cf = active_state.flags.of = high != 0
            trace.add(
                instruction.address,
                "unsigned_multiply",
                multiplicand=multiplicand,
                multiplier=multiplier,
                product=product,
                product_hex=_hex64(product),
                low=low,
                low_hex=_hex32(low),
                high=high,
                high_hex=_hex32(high),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"stosb", "rep_stosb"}:
            count = (
                active_state.get_register("ecx")
                if instruction.mnemonic == "rep_stosb"
                else 1
            )
            destination = active_state.get_register("edi")
            value = _read_low_u8_register(active_state, "al")
            step = -1 if active_state.flags.df else 1
            for index in range(count):
                memory.write(_u32(destination + index * step), bytes([value]))
            active_state.set_register("edi", destination + count * step)
            if instruction.mnemonic == "rep_stosb":
                active_state.set_register("ecx", 0)
            trace.add(
                instruction.address,
                "string_store",
                element_size=1,
                count=count,
                destination=destination,
                destination_hex=_hex32(destination),
                value=value,
                value_hex=_hex32(value),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"stosd", "rep_stosd"}:
            count = (
                active_state.get_register("ecx")
                if instruction.mnemonic == "rep_stosd"
                else 1
            )
            destination = active_state.get_register("edi")
            value = active_state.get_register("eax")
            step = -4 if active_state.flags.df else 4
            for index in range(count):
                memory.write_u32(_u32(destination + index * step), value)
            active_state.set_register("edi", destination + count * step)
            if instruction.mnemonic == "rep_stosd":
                active_state.set_register("ecx", 0)
            trace.add(
                instruction.address,
                "string_store",
                element_size=4,
                count=count,
                destination=destination,
                destination_hex=_hex32(destination),
                value=value,
                value_hex=_hex32(value),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"movsb", "rep_movsb"}:
            count = (
                active_state.get_register("ecx")
                if instruction.mnemonic == "rep_movsb"
                else 1
            )
            source = active_state.get_register("esi")
            destination = active_state.get_register("edi")
            step = -1 if active_state.flags.df else 1
            for index in range(count):
                value = active_memory.read(_u32(source + index * step), 1)[0]
                active_memory.write(
                    _u32(destination + index * step),
                    bytes([value]),
                )
            active_state.set_register("esi", source + count * step)
            active_state.set_register("edi", destination + count * step)
            if instruction.mnemonic == "rep_movsb":
                active_state.set_register("ecx", 0)
            trace.add(
                instruction.address,
                "string_move",
                element_size=1,
                count=count,
                source=source,
                source_hex=_hex32(source),
                destination=destination,
                destination_hex=_hex32(destination),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"movsd", "rep_movsd"}:
            count = (
                active_state.get_register("ecx")
                if instruction.mnemonic == "rep_movsd"
                else 1
            )
            source = active_state.get_register("esi")
            destination = active_state.get_register("edi")
            step = -4 if active_state.flags.df else 4
            for index in range(count):
                value = active_memory.read_u32(_u32(source + index * step))
                active_memory.write_u32(
                    _u32(destination + index * step),
                    value,
                )
            active_state.set_register("esi", source + count * step)
            active_state.set_register("edi", destination + count * step)
            if instruction.mnemonic == "rep_movsd":
                active_state.set_register("ecx", 0)
            trace.add(
                instruction.address,
                "string_move",
                element_size=4,
                count=count,
                source=source,
                source_hex=_hex32(source),
                destination=destination,
                destination_hex=_hex32(destination),
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"cmpsb", "rep_cmpsb", "cmpsd", "rep_cmpsd"}:
            repeated = instruction.mnemonic in {"rep_cmpsb", "rep_cmpsd"}
            element_size = 4 if instruction.mnemonic in {"cmpsd", "rep_cmpsd"} else 1
            operand_size = element_size * 8
            requested_count = (
                active_state.get_register("ecx")
                if repeated
                else 1
            )
            source = active_state.get_register("esi")
            destination = active_state.get_register("edi")
            remaining = requested_count
            compared = 0
            last_lhs = 0
            last_rhs = 0
            step = -element_size if active_state.flags.df else element_size
            while remaining:
                source_address = _u32(source + compared * step)
                destination_address = _u32(destination + compared * step)
                if element_size == 4:
                    last_lhs = active_memory.read_u32(source_address)
                    last_rhs = active_memory.read_u32(destination_address)
                    result = _u32(last_lhs - last_rhs)
                else:
                    last_lhs = active_memory.read(source_address, 1)[0]
                    last_rhs = active_memory.read(destination_address, 1)[0]
                    result = _u32(last_lhs - last_rhs) & 0xFF
                _update_flags(
                    active_state.flags,
                    "sub",
                    last_lhs,
                    last_rhs,
                    result,
                    size=operand_size,
                )
                compared += 1
                remaining -= 1
                if not repeated or not active_state.flags.zf:
                    break
            active_state.set_register("esi", source + compared * step)
            active_state.set_register("edi", destination + compared * step)
            if repeated:
                active_state.set_register("ecx", remaining)
            trace.add(
                instruction.address,
                "string_compare",
                element_size=element_size,
                requested_count=requested_count,
                compared_count=compared,
                source=source,
                source_hex=_hex32(source),
                destination=destination,
                destination_hex=_hex32(destination),
                last_lhs=last_lhs,
                last_lhs_hex=_hex32(last_lhs),
                last_rhs=last_rhs,
                last_rhs_hex=_hex32(last_rhs),
                equal=active_state.flags.zf,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic in {"scasb", "repne_scasb"}:
            requested_count = (
                active_state.get_register("ecx")
                if instruction.mnemonic == "repne_scasb"
                else 1
            )
            source = active_state.get_register("edi")
            needle = active_state.get_register("eax") & 0xFF
            remaining = requested_count
            scanned = 0
            last_value = 0
            step = -1 if active_state.flags.df else 1
            while remaining:
                last_value = active_memory.read(
                    _u32(source + scanned * step),
                    1,
                )[0]
                result = _u32(needle - last_value) & 0xFF
                _update_flags(
                    active_state.flags,
                    "sub",
                    needle,
                    last_value,
                    result,
                    size=8,
                )
                scanned += 1
                remaining -= 1
                if instruction.mnemonic != "repne_scasb" or active_state.flags.zf:
                    break
            active_state.set_register("edi", source + scanned * step)
            if instruction.mnemonic == "repne_scasb":
                active_state.set_register("ecx", remaining)
            trace.add(
                instruction.address,
                "string_scan",
                element_size=1,
                requested_count=requested_count,
                scanned_count=scanned,
                source=source,
                source_hex=_hex32(source),
                needle=needle,
                needle_hex=_hex32(needle),
                last_value=last_value,
                last_value_hex=_hex32(last_value),
                remaining=remaining,
            )
            active_state.eip = next_eip
            continue
        if instruction.mnemonic == "int3":
            raise X86ExecutionError(f"debug trap at {_hex32(instruction.address)}")
        if instruction.mnemonic == "int":
            vector = instruction.operands[0].immediate if instruction.operands else 0
            raise X86ExecutionError(
                f"software interrupt {_hex32(vector or 0)} at {_hex32(instruction.address)}"
            )
        if instruction.mnemonic == "call":
            target = instruction.target
            if target is None:
                target = _read_operand(
                    active_state, active_memory, trace, instruction, instruction.operands[0]
                )
            _push(active_state, active_memory, trace, instruction, next_eip)
            trace.add(instruction.address, "call", target=target, target_hex=_hex32(target))
            handler = handlers.get(target)
            if handler is not None:
                handler(active_state, active_memory, target, trace)
                returned_to = _pop(active_state, active_memory, trace, instruction)
                if returned_to != next_eip:
                    raise X86ExecutionError(
                        f"external call returned to {_hex32(returned_to)}, "
                        f"expected {_hex32(next_eip)}"
                    )
                active_state.eip = returned_to
                if (
                    call_handler_yield_predicate is not None
                    and call_handler_yield_predicate(target)
                ):
                    return ExecutionResult(
                        active_state,
                        active_memory,
                        trace,
                        return_address=returned_to,
                        steps=steps,
                    )
            elif target in valid_addresses:
                active_state.eip = target
            elif install_block(target):
                active_state.eip = target
            elif unhandled_call_handler is not None:
                unhandled_call_handler(active_state, active_memory, target, trace)
                returned_to = _pop(active_state, active_memory, trace, instruction)
                if returned_to != next_eip:
                    raise X86ExecutionError(
                        f"external call returned to {_hex32(returned_to)}, "
                        f"expected {_hex32(next_eip)}"
                )
                active_state.eip = returned_to
            elif return_on_missing_instruction:
                active_state.eip = target
                return ExecutionResult(
                    active_state,
                    active_memory,
                    trace,
                    return_address=target,
                    steps=steps,
                )
            else:
                raise X86ExecutionError(f"unhandled external call target {_hex32(target)}")
            continue
        if instruction.mnemonic == "jmp":
            target = instruction.target
            if target is None:
                target = _read_operand(
                    active_state, active_memory, trace, instruction, instruction.operands[0]
                )
            trace.add(instruction.address, "jump", target=target, target_hex=_hex32(target))
            handler = handlers.get(target)
            if handler is not None:
                handler(active_state, active_memory, target, trace)
                returned_to = _pop(active_state, active_memory, trace, instruction)
                active_state.eip = returned_to
                if returned_to in valid_addresses:
                    continue
                return ExecutionResult(
                    active_state,
                    active_memory,
                    trace,
                    return_address=returned_to,
                    steps=steps,
                )
            active_state.eip = target
            continue
        if instruction.mnemonic == "jmp_far":
            if instruction.target is None:
                raise X86ExecutionError("far jump missing target")
            selector = instruction.operands[0].immediate or 0
            active_state.cs_selector = selector & 0xFFFF
            trace.add(
                instruction.address,
                "far_jump",
                selector=active_state.cs_selector,
                selector_hex=f"0x{active_state.cs_selector:04X}",
                target=instruction.target,
                target_hex=_hex32(instruction.target),
            )
            active_state.eip = instruction.target
            continue
        if instruction.mnemonic == "jcc":
            if instruction.target is None or instruction.condition is None:
                raise X86ExecutionError("conditional branch missing target or condition")
            taken = (
                active_state.get_register("ecx") == 0
                if instruction.condition == "ecx_zero"
                else _evaluate_condition(active_state.flags, instruction.condition)
            )
            trace.add(
                instruction.address,
                "branch",
                condition=instruction.condition,
                taken=taken,
                target=instruction.target,
                target_hex=_hex32(instruction.target),
            )
            active_state.eip = instruction.target if taken else next_eip
            continue
        if instruction.mnemonic == "ret":
            return_address = _pop(active_state, active_memory, trace, instruction)
            if instruction.ret_stack_adjust:
                active_state.set_register(
                    "esp",
                    active_state.get_register("esp") + instruction.ret_stack_adjust,
                )
            trace.add(
                instruction.address,
                "return",
                return_address=return_address,
                return_address_hex=_hex32(return_address),
                stack_adjust=instruction.ret_stack_adjust,
                esp=active_state.get_register("esp"),
            )
            active_state.eip = return_address
            if return_address in valid_addresses or install_block(return_address):
                continue
            return ExecutionResult(
                active_state,
                active_memory,
                trace,
                return_address=return_address,
                steps=steps,
            )
        raise X86ExecutionError(f"unsupported lifted mnemonic: {instruction.mnemonic}")

    raise X86ExecutionError(
        "execution step limit reached",
        state=active_state,
        trace=trace,
        steps=steps,
    )


===== tools/recomp/x86_lifter.py:4995-5027 | _read_operand =====

def _read_operand(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
    operand: Operand,
) -> int:
    if operand.kind == "reg":
        if operand.size == 8:
            return _read_low_u8_register(state, operand.reg or "")
        if operand.size == 16:
            return state.get_register(operand.reg or "") & 0xFFFF
        return state.get_register(operand.reg or "")
    if operand.kind == "imm":
        return operand.immediate or 0
    if operand.kind == "mem":
        address = _effective_address(state, operand)
        if operand.size == 8:
            value = memory.read(address, 1)[0]
        elif operand.size == 16:
            value = struct.unpack("<H", memory.read(address, 2))[0]
        else:
            value = memory.read_u32(address)
        trace.add(
            instruction.address,
            "memory_read",
            memory_address=address,
            memory_address_hex=_hex32(address),
            value=value,
            value_hex=_hex32(value),
        )
        return value
    raise X86ExecutionError(f"cannot read operand kind {operand.kind}")


===== tools/recomp/x86_lifter.py:5030-5051 | _read_float32_operand =====

def _read_float32_operand(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
    operand: Operand,
) -> float:
    if operand.kind != "mem":
        raise X86ExecutionError("x87 float operand must be memory-backed")
    address = _effective_address(state, operand)
    size = 8 if operand.size == 64 else 4
    payload = memory.read(address, size)
    raw = int.from_bytes(payload, "little")
    trace.add(
        instruction.address,
        "memory_read",
        memory_address=address,
        memory_address_hex=_hex32(address),
        value=raw,
        value_hex=_hex64(raw) if size == 8 else _hex32(raw),
    )
    return struct.unpack("<d" if size == 8 else "<f", payload)[0]


===== tools/recomp/x86_lifter.py:5054-5085 | _read_xmm_operand =====

def _read_xmm_operand(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
    operand: Operand,
) -> tuple[float, float, float, float]:
    if operand.kind == "reg":
        if operand.reg not in XMM_REGISTER_NAMES:
            raise X86ExecutionError(f"unsupported XMM register read: {operand.reg}")
        value = state.get_xmm_register(operand.reg)
        trace.add(
            instruction.address,
            "xmm_register_read",
            register=operand.reg,
            value=list(value),
        )
        return value
    if operand.kind == "mem":
        address = _effective_address(state, operand)
        payload = memory.read(address, 16)
        value = struct.unpack("<4f", payload)
        trace.add(
            instruction.address,
            "xmm_memory_read",
            memory_address=address,
            memory_address_hex=_hex32(address),
            value=list(value),
            size=16,
        )
        return value
    raise X86ExecutionError(f"cannot read XMM operand kind {operand.kind}")


===== tools/recomp/x86_lifter.py:5088-5126 | _write_xmm_operand =====

def _write_xmm_operand(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
    operand: Operand,
    value: Iterable[float],
    *,
    non_temporal: bool = False,
) -> None:
    lanes = tuple(float(lane) for lane in value)
    if len(lanes) != 4:
        raise X86ExecutionError("XMM operand writes require four lanes")
    vector = (lanes[0], lanes[1], lanes[2], lanes[3])
    if operand.kind == "reg":
        if operand.reg not in XMM_REGISTER_NAMES:
            raise X86ExecutionError(f"unsupported XMM register write: {operand.reg}")
        state.set_xmm_register(operand.reg, vector)
        trace.add(
            instruction.address,
            "xmm_register_write",
            register=operand.reg,
            value=list(vector),
        )
        return
    if operand.kind == "mem":
        address = _effective_address(state, operand)
        memory.write(address, struct.pack("<4f", *vector))
        trace.add(
            instruction.address,
            "xmm_memory_write",
            memory_address=address,
            memory_address_hex=_hex32(address),
            value=list(vector),
            size=16,
            non_temporal=non_temporal,
        )
        return
    raise X86ExecutionError(f"cannot write XMM operand kind {operand.kind}")


===== tools/recomp/x86_lifter.py:5129-5162 | _read_mmx_operand =====

def _read_mmx_operand(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
    operand: Operand,
) -> int:
    if operand.kind == "reg":
        if operand.reg not in MMX_REGISTER_NAMES:
            raise X86ExecutionError(f"unsupported MMX register read: {operand.reg}")
        value = state.get_mmx_register(operand.reg)
        trace.add(
            instruction.address,
            "mmx_register_read",
            register=operand.reg,
            value=value,
            value_hex=_hex64(value),
        )
        return value
    if operand.kind == "mem":
        address = _effective_address(state, operand)
        payload = memory.read(address, 8)
        value = struct.unpack("<Q", payload)[0]
        trace.add(
            instruction.address,
            "memory_read",
            memory_address=address,
            memory_address_hex=_hex32(address),
            value=value,
            value_hex=_hex64(value),
            size=8,
        )
        return value
    raise X86ExecutionError(f"cannot read MMX operand kind {operand.kind}")


===== tools/recomp/x86_lifter.py:5165-5202 | _write_mmx_operand =====

def _write_mmx_operand(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
    operand: Operand,
    value: int,
    *,
    non_temporal: bool = False,
) -> None:
    value &= 0xFFFFFFFFFFFFFFFF
    if operand.kind == "reg":
        if operand.reg not in MMX_REGISTER_NAMES:
            raise X86ExecutionError(f"unsupported MMX register write: {operand.reg}")
        state.set_mmx_register(operand.reg, value)
        trace.add(
            instruction.address,
            "mmx_register_write",
            register=operand.reg,
            value=value,
            value_hex=_hex64(value),
        )
        return
    if operand.kind == "mem":
        address = _effective_address(state, operand)
        memory.write(address, struct.pack("<Q", value))
        trace.add(
            instruction.address,
            "memory_write",
            memory_address=address,
            memory_address_hex=_hex32(address),
            value=value,
            value_hex=_hex64(value),
            size=8,
            non_temporal=non_temporal,
        )
        return
    raise X86ExecutionError(f"cannot write MMX operand kind {operand.kind}")


===== tools/recomp/x86_lifter.py:5205-5209 | _mmx_lanes =====

def _mmx_lanes(value: int, lane_bits: int) -> tuple[int, ...]:
    mask = (1 << lane_bits) - 1
    return tuple(
        (value >> offset) & mask for offset in range(0, 64, lane_bits)
    )


===== tools/recomp/x86_lifter.py:5212-5217 | _mmx_pack_lanes =====

def _mmx_pack_lanes(lanes: Iterable[int], lane_bits: int) -> int:
    mask = (1 << lane_bits) - 1
    value = 0
    for index, lane in enumerate(lanes):
        value |= (int(lane) & mask) << (index * lane_bits)
    return value & 0xFFFFFFFFFFFFFFFF


===== tools/recomp/x86_lifter.py:5220-5234 | _mmx_unpack =====

def _mmx_unpack(
    left: int,
    right: int,
    *,
    lane_bits: int,
    high: bool,
) -> int:
    left_lanes = _mmx_lanes(left, lane_bits)
    right_lanes = _mmx_lanes(right, lane_bits)
    half = len(left_lanes) // 2
    start = half if high else 0
    lanes: list[int] = []
    for index in range(start, start + half):
        lanes.extend((left_lanes[index], right_lanes[index]))
    return _mmx_pack_lanes(lanes, lane_bits)


===== tools/recomp/x86_lifter.py:5237-5246 | _mmx_paddd =====

def _mmx_paddd(left: int, right: int) -> int:
    left_lanes = _mmx_lanes(left, 32)
    right_lanes = _mmx_lanes(right, 32)
    return _mmx_pack_lanes(
        (
            (left_lanes[0] + right_lanes[0]) & 0xFFFFFFFF,
            (left_lanes[1] + right_lanes[1]) & 0xFFFFFFFF,
        ),
        32,
    )


===== tools/recomp/x86_lifter.py:5249-5254 | _mmx_pshufw =====

def _mmx_pshufw(value: int, immediate: int) -> int:
    lanes = _mmx_lanes(value, 16)
    return _mmx_pack_lanes(
        (lanes[(immediate >> (index * 2)) & 0x03] for index in range(4)),
        16,
    )


===== tools/recomp/x86_lifter.py:5257-5272 | _mmx_shift =====

def _mmx_shift(value: int, mnemonic: str, count: int) -> int:
    if mnemonic == "psraw":
        lanes = _mmx_lanes(value, 16)
        shift = min(count, 15)
        return _mmx_pack_lanes(
            (_i16(lane) >> shift for lane in lanes),
            16,
        )
    if mnemonic not in {"psrld", "pslld"}:
        raise X86ExecutionError(f"unsupported MMX shift {mnemonic}")
    lanes = _mmx_lanes(value, 32)
    if count > 31:
        return 0
    if mnemonic == "psrld":
        return _mmx_pack_lanes((lane >> count for lane in lanes), 32)
    return _mmx_pack_lanes((lane << count for lane in lanes), 32)


===== tools/recomp/x86_lifter.py:5275-5286 | _mmx_packssdw =====

def _mmx_packssdw(left: int, right: int) -> int:
    def saturate(value: int) -> int:
        signed = _i32(value)
        return max(-32768, min(32767, signed))

    return _mmx_pack_lanes(
        (
            *(saturate(lane) for lane in _mmx_lanes(left, 32)),
            *(saturate(lane) for lane in _mmx_lanes(right, 32)),
        ),
        16,
    )


===== tools/recomp/x86_lifter.py:5289-5314 | _read_packed_float64_operand =====

def _read_packed_float64_operand(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
    operand: Operand,
) -> tuple[float, float]:
    if operand.kind == "reg":
        if operand.reg not in XMM_REGISTER_NAMES:
            raise X86ExecutionError(f"unsupported packed float read: {operand.reg}")
        lanes = state.get_xmm_register(operand.reg)
        return lanes[0], lanes[1]
    if operand.kind == "mem":
        address = _effective_address(state, operand)
        payload = memory.read(address, 8)
        lanes = struct.unpack("<2f", payload)
        trace.add(
            instruction.address,
            "xmm_memory_read",
            memory_address=address,
            memory_address_hex=_hex32(address),
            value=list(lanes),
            size=8,
        )
        return lanes
    raise X86ExecutionError(f"cannot read packed float operand kind {operand.kind}")


===== tools/recomp/x86_lifter.py:5317-5335 | _read_xmm_scalar_operand =====

def _read_xmm_scalar_operand(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
    operand: Operand,
) -> float:
    if operand.kind == "reg":
        if operand.reg not in XMM_REGISTER_NAMES:
            raise X86ExecutionError(f"unsupported XMM scalar read: {operand.reg}")
        value = state.get_xmm_register(operand.reg)[0]
        trace.add(
            instruction.address,
            "xmm_scalar_register_read",
            register=operand.reg,
            value=value,
        )
        return value
    return _read_float32_operand(state, memory, trace, instruction, operand)


===== tools/recomp/x86_lifter.py:5338-5348 | _xmm_shuffle =====

def _xmm_shuffle(
    destination: tuple[float, float, float, float],
    source: tuple[float, float, float, float],
    immediate: int,
) -> tuple[float, float, float, float]:
    return (
        destination[immediate & 0x03],
        destination[(immediate >> 2) & 0x03],
        source[(immediate >> 4) & 0x03],
        source[(immediate >> 6) & 0x03],
    )


===== tools/recomp/x86_lifter.py:5351-5377 | _read_x87_integer_operand =====

def _read_x87_integer_operand(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
    operand: Operand,
) -> int:
    if operand.kind != "mem":
        raise X86ExecutionError("x87 integer operand must be memory-backed")
    if operand.size == 32:
        return _i32(_read_operand(state, memory, trace, instruction, operand))
    if operand.size != 64:
        raise X86ExecutionError(f"unsupported x87 integer size {operand.size}")
    address = _effective_address(state, operand)
    payload = memory.read(address, 8)
    raw = struct.unpack("<Q", payload)[0]
    value = struct.unpack("<q", payload)[0]
    trace.add(
        instruction.address,
        "memory_read",
        memory_address=address,
        memory_address_hex=_hex32(address),
        value=raw,
        value_hex=_hex64(raw),
        size=8,
    )
    return value


===== tools/recomp/x86_lifter.py:5380-5405 | _write_x87_integer_operand =====

def _write_x87_integer_operand(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
    operand: Operand,
    value: int,
) -> None:
    if operand.kind != "mem":
        raise X86ExecutionError("x87 integer operand must be memory-backed")
    if operand.size != 64:
        _write_operand(state, memory, trace, instruction, operand, value)
        return
    address = _effective_address(state, operand)
    payload = struct.pack("<q", int(value))
    raw = struct.unpack("<Q", payload)[0]
    memory.write(address, payload)
    trace.add(
        instruction.address,
        "memory_write",
        memory_address=address,
        memory_address_hex=_hex32(address),
        value=raw,
        value_hex=_hex64(raw),
        size=8,
    )


===== tools/recomp/x86_lifter.py:5408-5416 | _x87_float_to_int =====

def _x87_float_to_int(value: float, bits: int) -> int:
    minimum = -(1 << (bits - 1))
    maximum = (1 << (bits - 1)) - 1
    if not math.isfinite(value):
        return minimum
    rounded = int(round(value))
    if rounded < minimum or rounded > maximum:
        return minimum
    return rounded


===== tools/recomp/x86_lifter.py:5419-5422 | _sse_truncate_float32_to_i32 =====

def _sse_truncate_float32_to_i32(value: float) -> int:
    if not math.isfinite(value) or value < -2147483648.0 or value > 2147483647.0:
        return 0x80000000
    return _u32(int(value))


===== tools/recomp/x86_lifter.py:5425-5439 | _sse_round_float32_to_i32 =====

def _sse_round_float32_to_i32(value: float, mxcsr: int) -> int:
    if not math.isfinite(value):
        return 0x80000000
    rounding_mode = (mxcsr >> 13) & 0x03
    if rounding_mode == 0:
        rounded = round(value)
    elif rounding_mode == 1:
        rounded = math.floor(value)
    elif rounding_mode == 2:
        rounded = math.ceil(value)
    else:
        rounded = math.trunc(value)
    if rounded < -2147483648 or rounded > 2147483647:
        return 0x80000000
    return _u32(int(rounded))


===== tools/recomp/x86_lifter.py:5442-5469 | _sse_reciprocal_sqrt_approximation =====

def _sse_reciprocal_sqrt_approximation(value: float) -> float:
    bits = struct.unpack("<I", struct.pack("<f", value))[0]
    sign = bits & 0x80000000
    exponent = bits & 0x7F800000
    fraction = bits & 0x007FFFFF

    def float_from_bits(result_bits: int) -> float:
        return struct.unpack("<f", struct.pack("<I", result_bits))[0]

    if exponent == 0:
        return float_from_bits(sign | 0x7F800000)
    if exponent == 0x7F800000:
        if fraction != 0:
            return float_from_bits(bits | 0x00400000)
        return float_from_bits(0xFFC00000 if sign else 0)
    if sign:
        return float_from_bits(0xFFC00000)

    # Intel RSQRTSS selects one of 1024 mantissa buckets for each exponent
    # parity, then rounds its estimate to 11 fraction bits. Evaluating the
    # bucket midpoint reproduces that deterministic lookup without depending
    # on the host CPU's vendor-specific reciprocal-square-root estimate.
    midpoint_bits = (bits & 0xFFFFE000) | 0x00001000
    midpoint = float_from_bits(midpoint_bits)
    estimate_bits = struct.unpack(
        "<I", struct.pack("<f", 1.0 / math.sqrt(midpoint))
    )[0]
    return float_from_bits((estimate_bits + 0x00000400) & 0xFFFFF800)


===== tools/recomp/x86_lifter.py:5472-5477 | _sse_minmax_float32 =====

def _sse_minmax_float32(left: float, right: float, *, minimum: bool) -> float:
    if math.isnan(left) or math.isnan(right) or left == right:
        return right
    if minimum:
        return left if left < right else right
    return left if left > right else right


===== tools/recomp/x86_lifter.py:5480-5492 | _x87_stack_operand_index =====

def _x87_stack_operand_index(
    state: CpuState,
    instruction: X86Instruction,
    operand: Operand,
) -> int:
    if operand.kind != "imm":
        raise X86ExecutionError("x87 stack operand must be an encoded ST index")
    index = operand.immediate or 0
    if index >= len(state.fpu_stack):
        raise X86ExecutionError(
            f"x87 stack underflow reading st({index}) at {_hex32(instruction.address)}"
        )
    return index


===== tools/recomp/x86_lifter.py:5495-5539 | _read_x87_float_operand =====

def _read_x87_float_operand(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
    operand: Operand,
) -> float:
    if operand.kind == "imm":
        index = _x87_stack_operand_index(state, instruction, operand)
        value = state.fpu_stack[index]
        trace.add(
            instruction.address,
            "fpu_stack_read",
            stack_index=index,
            value=value,
        )
        return value
    if operand.size == 80:
        address = _effective_address(state, operand)
        payload = memory.read(address, 10)
        value = _x87_decode_extended80(payload)
        trace.add(
            instruction.address,
            "memory_read",
            memory_address=address,
            memory_address_hex=_hex32(address),
            value=payload.hex().upper(),
            size=10,
        )
        return value
    if operand.size != 64:
        return _read_float32_operand(state, memory, trace, instruction, operand)
    address = _effective_address(state, operand)
    payload = memory.read(address, 8)
    raw = struct.unpack("<Q", payload)[0]
    trace.add(
        instruction.address,
        "memory_read",
        memory_address=address,
        memory_address_hex=_hex32(address),
        value=raw,
        value_hex=_hex64(raw),
        size=8,
    )
    return struct.unpack("<d", payload)[0]


===== tools/recomp/x86_lifter.py:5542-5567 | _x87_decode_extended80 =====

def _x87_decode_extended80(payload: bytes) -> float:
    if len(payload) != 10:
        raise X86ExecutionError("x87 extended value must contain ten bytes")
    significand = int.from_bytes(payload[:8], "little")
    exponent_sign = int.from_bytes(payload[8:], "little")
    negative = bool(exponent_sign & 0x8000)
    exponent = exponent_sign & 0x7FFF
    if exponent == 0x7FFF:
        if significand == 0x8000000000000000:
            value = float("inf")
        else:
            value = float("nan")
    elif exponent == 0:
        if significand == 0:
            value = 0.0
        else:
            value = math.ldexp(
                significand / float(1 << 63),
                1 - 16383,
            )
    else:
        value = math.ldexp(
            significand / float(1 << 63),
            exponent - 16383,
        )
    return -value if negative else value


===== tools/recomp/x86_lifter.py:5570-5587 | _x87_encode_extended80 =====

def _x87_encode_extended80(value: float) -> bytes:
    negative = math.copysign(1.0, value) < 0.0
    magnitude = abs(value)
    if math.isnan(value):
        significand = 0xC000000000000000
        exponent = 0x7FFF
    elif math.isinf(value):
        significand = 0x8000000000000000
        exponent = 0x7FFF
    elif magnitude == 0.0:
        significand = 0
        exponent = 0
    else:
        fraction, binary_exponent = math.frexp(magnitude)
        exponent = binary_exponent - 1 + 16383
        significand = int(math.ldexp(fraction, 64)) & 0xFFFFFFFFFFFFFFFF
    exponent_sign = exponent | (0x8000 if negative else 0)
    return significand.to_bytes(8, "little") + exponent_sign.to_bytes(2, "little")


===== tools/recomp/x86_lifter.py:5590-5595 | _x87_tag =====

def _x87_tag(value: float) -> int:
    if math.isnan(value) or math.isinf(value):
        return 2
    if value == 0.0:
        return 1
    return 0


===== tools/recomp/x86_lifter.py:5598-5612 | _x87_save_image =====

def _x87_save_image(state: CpuState) -> bytes:
    payload = bytearray(X87_SAVE_IMAGE_SIZE)
    struct.pack_into("<H", payload, 0, state.fpu_control_word & 0xFFFF)
    struct.pack_into("<H", payload, 4, state.fpu_status_word & 0xFFFF)
    tag_word = 0
    for index in range(8):
        tag = _x87_tag(state.fpu_stack[index]) if index < len(state.fpu_stack) else 3
        tag_word |= tag << (index * 2)
        if index < len(state.fpu_stack):
            start = 28 + index * 10
            payload[start : start + 10] = _x87_encode_extended80(
                state.fpu_stack[index]
            )
    struct.pack_into("<H", payload, 8, tag_word)
    return bytes(payload)


===== tools/recomp/x86_lifter.py:5615-5627 | _x87_restore_image =====

def _x87_restore_image(state: CpuState, payload: bytes) -> None:
    if len(payload) != X87_SAVE_IMAGE_SIZE:
        raise X86ExecutionError("x87 save image must contain 108 bytes")
    state.fpu_control_word = struct.unpack_from("<H", payload, 0)[0]
    state.fpu_status_word = struct.unpack_from("<H", payload, 4)[0]
    tag_word = struct.unpack_from("<H", payload, 8)[0]
    restored: list[float] = []
    for index in range(8):
        if ((tag_word >> (index * 2)) & 0x03) == 3:
            continue
        start = 28 + index * 10
        restored.append(_x87_decode_extended80(payload[start : start + 10]))
    state.fpu_stack = restored


===== tools/recomp/x86_lifter.py:5630-5637 | _x87_compare =====

def _x87_compare(left: float, right: float) -> str:
    if math.isnan(left) or math.isnan(right):
        return "unordered"
    if left < right:
        return "less"
    if left > right:
        return "greater"
    return "equal"


===== tools/recomp/x86_lifter.py:5640-5648 | _x87_compare_status_word =====

def _x87_compare_status_word(status_word: int, comparison: str) -> int:
    status_word &= ~X87_STATUS_CONDITION_MASK
    if comparison == "less":
        status_word |= X87_STATUS_C0
    elif comparison == "equal":
        status_word |= X87_STATUS_C3
    elif comparison == "unordered":
        status_word |= X87_STATUS_C0 | X87_STATUS_C2 | X87_STATUS_C3
    return status_word & 0xFFFF


===== tools/recomp/x86_lifter.py:5651-5657 | _x87_divide =====

def _x87_divide(numerator: float, denominator: float) -> float:
    if denominator == 0.0:
        if numerator == 0.0:
            return float("nan")
        negative = math.copysign(1.0, numerator) != math.copysign(1.0, denominator)
        return float("-inf") if negative else float("inf")
    return numerator / denominator


===== tools/recomp/x86_lifter.py:5660-5684 | _read_low_u8_register =====

def _read_low_u8_register(state: CpuState, name: str) -> int:
    low_map = {
        "al": "eax",
        "cl": "ecx",
        "dl": "edx",
        "bl": "ebx",
        "eax": "eax",
        "ecx": "ecx",
        "edx": "edx",
        "ebx": "ebx",
    }
    high_map = {
        "ah": "eax",
        "ch": "ecx",
        "dh": "edx",
        "bh": "ebx",
    }
    normalized = name.casefold()
    parent = low_map.get(normalized)
    if parent is not None:
        return state.get_register(parent) & 0xFF
    parent = high_map.get(normalized)
    if parent is None:
        raise X86ExecutionError(f"unsupported 8-bit register read: {name}")
    return (state.get_register(parent) >> 8) & 0xFF


===== tools/recomp/x86_lifter.py:5687-5715 | _write_u8_register =====

def _write_u8_register(state: CpuState, name: str, value: int) -> None:
    low_map = {
        "al": "eax",
        "cl": "ecx",
        "dl": "edx",
        "bl": "ebx",
        "eax": "eax",
        "ecx": "ecx",
        "edx": "edx",
        "ebx": "ebx",
    }
    high_map = {
        "ah": "eax",
        "ch": "ecx",
        "dh": "edx",
        "bh": "ebx",
    }
    normalized = name.casefold()
    parent = low_map.get(normalized)
    if parent is not None:
        current = state.get_register(parent)
        state.set_register(parent, (current & 0xFFFFFF00) | (value & 0xFF))
        return
    parent = high_map.get(normalized)
    if parent is not None:
        current = state.get_register(parent)
        state.set_register(parent, (current & 0xFFFF00FF) | ((value & 0xFF) << 8))
        return
    raise X86ExecutionError(f"unsupported 8-bit register write: {name}")


===== tools/recomp/x86_lifter.py:5718-5723 | _write_u16_register =====

def _write_u16_register(state: CpuState, name: str, value: int) -> None:
    normalized = name.casefold()
    if normalized not in REGISTER_NAMES:
        raise X86ExecutionError(f"unsupported 16-bit register write: {name}")
    current = state.get_register(normalized)
    state.set_register(normalized, (current & 0xFFFF0000) | (value & 0xFFFF))


===== tools/recomp/x86_lifter.py:5726-5768 | _write_operand =====

def _write_operand(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
    operand: Operand,
    value: int,
) -> None:
    value = _u32(value)
    if operand.kind == "reg":
        if operand.size == 8:
            _write_u8_register(state, operand.reg or "", value)
        elif operand.size == 16:
            _write_u16_register(state, operand.reg or "", value)
        else:
            state.set_register(operand.reg or "", value)
        trace.add(
            instruction.address,
            "register_write",
            register=operand.reg,
            value=value,
            value_hex=_hex32(value),
        )
        return
    if operand.kind == "mem":
        address = _effective_address(state, operand)
        if operand.size == 8:
            memory.write(address, bytes([value & 0xFF]))
        elif operand.size == 16:
            memory.write(address, struct.pack("<H", value & 0xFFFF))
        else:
            memory.write_u32(address, value)
        trace.add(
            instruction.address,
            "memory_write",
            memory_address=address,
            memory_address_hex=_hex32(address),
            value=value,
            value_hex=_hex32(value),
            size=operand.size // 8,
        )
        return
    raise X86ExecutionError(f"cannot write operand kind {operand.kind}")


===== tools/recomp/x86_lifter.py:5771-5794 | _write_float32_operand =====

def _write_float32_operand(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
    operand: Operand,
    value: float,
) -> None:
    if operand.kind != "mem":
        raise X86ExecutionError("x87 float operand must be memory-backed")
    address = _effective_address(state, operand)
    size = 8 if operand.size == 64 else 4
    payload = struct.pack("<d" if size == 8 else "<f", float(value))
    raw = int.from_bytes(payload, "little")
    memory.write(address, payload)
    trace.add(
        instruction.address,
        "memory_write",
        memory_address=address,
        memory_address_hex=_hex32(address),
        value=raw,
        value_hex=_hex64(raw) if size == 8 else _hex32(raw),
        size=size,
    )


===== tools/recomp/x86_lifter.py:5797-5812 | _effective_address =====

def _effective_address(state: CpuState, operand: Operand) -> int:
    if operand.kind != "mem":
        raise X86ExecutionError("effective address requested for non-memory operand")
    if operand.absolute is not None:
        base = operand.absolute
    else:
        base = 0
        if operand.base:
            base += state.get_register(operand.base)
        if operand.index:
            base += state.get_register(operand.index) * operand.scale
    if operand.segment == "fs":
        base += state.fs_base
    elif operand.segment is not None:
        raise X86ExecutionError(f"unsupported segment override {operand.segment}")
    return _u32(base + operand.displacement)


===== tools/recomp/x86_lifter.py:5815-5832 | _push =====

def _push(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
    value: int,
) -> None:
    esp = _u32(state.get_register("esp") - 4)
    state.set_register("esp", esp)
    memory.write_u32(esp, value)
    trace.add(
        instruction.address,
        "stack_push",
        memory_address=esp,
        memory_address_hex=_hex32(esp),
        value=_u32(value),
        value_hex=_hex32(value),
    )


===== tools/recomp/x86_lifter.py:5835-5852 | _pop =====

def _pop(
    state: CpuState,
    memory: SparseMemory,
    trace: ExecutionTrace,
    instruction: X86Instruction,
) -> int:
    esp = state.get_register("esp")
    value = memory.read_u32(esp)
    state.set_register("esp", esp + 4)
    trace.add(
        instruction.address,
        "stack_pop",
        memory_address=esp,
        memory_address_hex=_hex32(esp),
        value=value,
        value_hex=_hex32(value),
    )
    return value


===== tools/recomp/x86_lifter.py:5855-5866 | _binary_result =====

def _binary_result(operation: str, lhs: int, rhs: int) -> int:
    if operation == "add":
        return _u32(lhs + rhs)
    if operation == "sub":
        return _u32(lhs - rhs)
    if operation == "xor":
        return _u32(lhs ^ rhs)
    if operation == "and":
        return _u32(lhs & rhs)
    if operation == "or":
        return _u32(lhs | rhs)
    raise X86ExecutionError(f"unsupported binary operation {operation}")


===== tools/recomp/x86_lifter.py:5869-5873 | _sign_extend =====

def _sign_extend(value: int, bits: int) -> int:
    mask = (1 << bits) - 1
    sign_bit = 1 << (bits - 1)
    value &= mask
    return _u32((value ^ sign_bit) - sign_bit)


===== tools/recomp/x86_lifter.py:5876-5880 | _signed_int =====

def _signed_int(value: int, bits: int) -> int:
    mask = (1 << bits) - 1
    sign_bit = 1 << (bits - 1)
    value &= mask
    return (value ^ sign_bit) - sign_bit


===== tools/recomp/x86_lifter.py:5883-5894 | _shift_result =====

def _shift_result(operation: str, value: int, count: int, *, size: int = 32) -> int:
    mask = (1 << size) - 1
    value = _u32(value) & mask
    if count == 0:
        return value
    if operation == "shl":
        return _u32(value << count) & mask
    if operation == "shr":
        return _u32(value >> count) & mask
    if operation == "sar":
        return _u32(_i32(_sign_extend(value, size)) >> count) & mask
    raise X86ExecutionError(f"unsupported shift operation {operation}")


===== tools/recomp/x86_lifter.py:5897-5946 | _rotate_result =====

def _rotate_result(
    operation: str,
    value: int,
    count: int,
    *,
    size: int,
    carry: bool,
) -> tuple[int, bool, bool, int]:
    mask = (1 << size) - 1
    value &= mask
    masked_count = count & 0x1F
    if operation == "rol":
        effective_count = masked_count % size
        if effective_count == 0:
            return value, carry, False, 0
        result = (
            (value << effective_count)
            | (value >> (size - effective_count))
        ) & mask
        next_carry = bool(result & 1)
        overflow = bool(((result >> (size - 1)) ^ int(next_carry)) & 1)
        return result, next_carry, overflow, effective_count
    if operation == "ror":
        effective_count = masked_count % size
        if effective_count == 0:
            return value, carry, False, 0
        result = (
            (value >> effective_count)
            | (value << (size - effective_count))
        ) & mask
        next_carry = bool(result & (1 << (size - 1)))
    elif operation == "rcr":
        width = size + 1
        effective_count = masked_count % width
        if effective_count == 0:
            return value, carry, False, 0
        ring_mask = (1 << width) - 1
        ring = (int(carry) << size) | value
        ring = (
            (ring >> effective_count)
            | (ring << (width - effective_count))
        ) & ring_mask
        result = ring & mask
        next_carry = bool(ring & (1 << size))
    else:
        raise X86ExecutionError(f"unsupported rotate operation {operation}")
    overflow = bool(
        ((result >> (size - 1)) ^ (result >> (size - 2))) & 1
    )
    return result, next_carry, overflow, effective_count


===== tools/recomp/x86_lifter.py:5949-5964 | _double_shift_result =====

def _double_shift_result(
    operation: str,
    destination: int,
    source: int,
    count: int,
) -> int:
    destination = _u32(destination)
    source = _u32(source)
    count &= 0x1F
    if count == 0:
        return destination
    if operation == "shld":
        return _u32((destination << count) | (source >> (32 - count)))
    if operation == "shrd":
        return _u32((destination >> count) | (source << (32 - count)))
    raise X86ExecutionError(f"unsupported double shift operation {operation}")


===== tools/recomp/x86_lifter.py:5967-5998 | _update_flags =====

def _update_flags(
    flags: CpuFlags,
    operation: str,
    lhs: int,
    rhs: int,
    result: int,
    *,
    size: int = 32,
) -> None:
    mask = (1 << size) - 1
    sign_bit = 1 << (size - 1)
    rhs_raw = rhs
    lhs = _u32(lhs) & mask
    rhs = _u32(rhs) & mask
    result = _u32(result) & mask
    flags.zf = result == 0
    flags.sf = bool(result & sign_bit)
    flags.pf = _parity8(result)
    if operation == "add":
        flags.cf = lhs + rhs_raw > mask
        flags.of = bool((~(lhs ^ rhs) & (lhs ^ result) & sign_bit) != 0)
        flags.af = bool((lhs ^ rhs ^ result) & 0x10)
    elif operation == "sub":
        flags.cf = lhs < rhs_raw
        flags.of = bool(((lhs ^ rhs) & (lhs ^ result) & sign_bit) != 0)
        flags.af = bool((lhs ^ rhs ^ result) & 0x10)
    elif operation in {"xor", "and", "or"}:
        flags.cf = False
        flags.of = False
        flags.af = False
    else:
        raise X86ExecutionError(f"cannot update flags for {operation}")


===== tools/recomp/x86_lifter.py:6001-6030 | _update_shift_flags =====

def _update_shift_flags(
    flags: CpuFlags,
    operation: str,
    lhs: int,
    count: int,
    result: int,
    *,
    size: int = 32,
) -> None:
    mask = (1 << size) - 1
    sign_bit = 1 << (size - 1)
    lhs = _u32(lhs) & mask
    result = _u32(result) & mask
    if count == 0:
        return
    if operation == "shl":
        flags.cf = bool(lhs & (1 << (size - count))) if count <= size else False
        flags.of = bool(((result >> 31) & 1) ^ int(flags.cf)) if count == 1 else False
    elif operation == "shr":
        flags.cf = bool(lhs & (1 << (count - 1)))
        flags.of = bool(lhs & sign_bit) if count == 1 else False
    elif operation == "sar":
        flags.cf = bool(lhs & (1 << (count - 1)))
        flags.of = False
    else:
        raise X86ExecutionError(f"cannot update shift flags for {operation}")
    flags.zf = result == 0
    flags.sf = bool(result & sign_bit)
    flags.pf = _parity8(result)
    flags.af = False


===== tools/recomp/x86_lifter.py:6033-6056 | _update_double_shift_flags =====

def _update_double_shift_flags(
    flags: CpuFlags,
    operation: str,
    destination: int,
    count: int,
    result: int,
) -> None:
    count &= 0x1F
    if count == 0:
        return
    destination = _u32(destination)
    result = _u32(result)
    if operation == "shld":
        flags.cf = bool(destination & (1 << (32 - count)))
        flags.of = bool(((result >> 31) & 1) ^ int(flags.cf)) if count == 1 else False
    elif operation == "shrd":
        flags.cf = bool(destination & (1 << (count - 1)))
        flags.of = bool(((destination ^ result) >> 31) & 1) if count == 1 else False
    else:
        raise X86ExecutionError(f"cannot update double shift flags for {operation}")
    flags.zf = result == 0
    flags.sf = bool(result & 0x80000000)
    flags.pf = _parity8(result)
    flags.af = False


===== tools/recomp/x86_lifter.py:6059-6077 | _condition_for_short_opcode =====

def _condition_for_short_opcode(opcode: int) -> str:
    return {
        0x70: "o",
        0x71: "no",
        0x72: "b",
        0x73: "ae",
        0x74: "e",
        0x75: "ne",
        0x76: "be",
        0x77: "a",
        0x78: "s",
        0x79: "ns",
        0x7A: "p",
        0x7B: "np",
        0x7C: "l",
        0x7D: "ge",
        0x7E: "le",
        0x7F: "g",
    }[opcode]


===== tools/recomp/x86_lifter.py:6080-6113 | _evaluate_condition =====

def _evaluate_condition(flags: CpuFlags, condition: str) -> bool:
    if condition == "o":
        return flags.of
    if condition == "no":
        return not flags.of
    if condition == "b":
        return flags.cf
    if condition == "ae":
        return not flags.cf
    if condition == "e":
        return flags.zf
    if condition == "ne":
        return not flags.zf
    if condition == "be":
        return flags.cf or flags.zf
    if condition == "a":
        return not flags.cf and not flags.zf
    if condition == "s":
        return flags.sf
    if condition == "ns":
        return not flags.sf
    if condition == "p":
        return flags.pf
    if condition == "np":
        return not flags.pf
    if condition == "l":
        return flags.sf != flags.of
    if condition == "ge":
        return flags.sf == flags.of
    if condition == "le":
        return flags.zf or flags.sf != flags.of
    if condition == "g":
        return not flags.zf and flags.sf == flags.of
    raise X86ExecutionError(f"unsupported condition {condition}")

