def arm_mrs(cpu: CPU, instr: int):
    """
    Execute an MRS instruction
    (transfer PSR contents to general-purpose register)
    """
    rd = get_bits(instr, 12, 15)
    psr = get_bit(instr, 22)
    cpu.regs.set(rd, cpu.regs.spsr.reg if psr else cpu.regs.cpsr.reg)
    cpu.advance_pc_arm()
    cpu.next_fetch_access = MemoryAccess.SEQUENTIAL

def arm_msr(cpu: CPU, instr: int):
    """
    Execute an MSR instruction
    (transfer general-purpose register contents or immediate value to PSR)
    """
    immediate = get_bit(instr, 25)
    if immediate:
        value = get_bits(instr, 0, 7)
        ror_amount = get_bits(instr, 8, 11) * 2
        value = ror_32(value, ror_amount)
    else:
        value = cpu.regs.get(get_bits(instr, 0, 3))
    write_to_flags_field = get_bit(instr, 19)
    write_to_status_field = get_bit(instr, 18)
    write_to_extension_field = get_bit(instr, 17)
    write_to_control_field = get_bit(instr, 16)
    flags_mask = 4278190080
    status_mask = 16711680
    extension_mask = 65280
    control_mask = 255
    mask = 0
    mask |= flags_mask if write_to_flags_field else 0
    mask |= status_mask if write_to_status_field else 0
    mask |= extension_mask if write_to_extension_field else 0
    mask |= control_mask if write_to_control_field else 0
    psr = get_bit(instr, 22)
    if psr:
        cpu.regs.spsr.reg = cpu.regs.spsr.reg & ~mask | value & mask
    else:
        if cpu.regs.cpsr.get_mode() == CPUMode.USER:
            mask &= flags_mask
        new_cpsr = cpu.regs.cpsr.reg & ~mask | value & mask
        new_cpsr_mode = new_cpsr & 31
        cpu.switch_mode(new_cpsr_mode)
        cpu.regs.cpsr.reg = new_cpsr
    cpu.advance_pc_arm()
    cpu.next_fetch_access = MemoryAccess.SEQUENTIAL