xchg

Exchange register/memory with register

Exchanges the values of its two operands.

8086 and later

Intel's reference: XCHG

CFPFAFZFSFDFOF –––––––
  • Leaves every flag unchanged

Forms

Operands

reg
A general-purpose register matching the operation’s size, for example al, ax, eax or rax.
r/m
A general-purpose register or memory location matching the operation’s size, for example rax or qword [rbp-8].
acc
The accumulator: al, ax, eax or rax, whichever matches the operation’s size. The form accepts no other register in this position.

When one of them is in memory, the exchange is always atomic, lock prefix or not, so xchg with memory is a ready-made synchronisation primitive, and slower than an ordinary move for that reason. A lock prefix on an exchange of two registers raises an invalid-opcode fault.

In 64-bit code a 32-bit exchange clears the upper halves of both 64-bit registers, xchg eax, eax included: NASM assembles that as a real exchange rather than as 90h, which in 64-bit mode is always a nop.

global _start

section .text
_start:
        mov rax, 12
        mov rbx, 5
        mov rcx, 3
        mov rsi, 9

        xchg rax, rbx

        mov rax, 60         ; syscall 60: exit
        xor rdi, rdi
        syscall