In this article at OpenGenus, we have explained the concept of XCHG instruction in x86 processor that is used to swap contents between two registers or memory locations.
Table of contents:
- XCHG instruction
- Alternative to XCHG
- Uses of XCHG
- Disadvantages of using XCHG
- Addressing mode in XCHG
- Difference between MOV and XCHG
XCHG stands for eXCHanGe. It is an assembly instruction that is used to exchange the memory contents of two registers or memory locations.
XCHG is a 1-byte instructions and requires 1-byte in memory for execution with 4 Clock Cycles (4 opcode fetch + 4 T-states).
XCHG instruction was introduced in 8086 processor in 1978 and is available in all x86 and x86-64 CPUs.
The syntax of using XCHG is as follows:
xchg destination source
- destination and source can be a register or a memory location (any combination)
- The instruction exchanges the content of the two operands
- The size of operand can eb a byte, word, double word or quad word.
XCHG is used for atomic operations in multi-threading programming and efficient register swap in algorithms.
Following is a sample use of XCHG:
mov eax, 123 mov ebx, 456 xchg eax, ebx
The content of eax and ebx will be as follows after execution:
- eax: 456
- ebx: 123
Alternative to XCHG
In x86 assembly, the alternative to XCHG instruction is to use 3 XOR instructions. Both can swap contents of two registers or memory location. To understand, how XOR can swap contents, go through this article.
In terms of functionality,
xchg eax, ebx
is equivalent to:
xor eax, ebx xor ebx, eax xor eax, ebx
Uses of XCHG
There are two main usecases of XCHG:
- Swap the content of two registers or memory location
- Implement synchronization primitives in multi-threaded code
Disadvantages of using XCHG
The 3 disadvantages of using XCHG are:
- Slow execution: When data needs to be moved and not swapped, then faster alternatives exist like MOV and ADD.
- Deadlock:In case of synchronization, XCHG face the issue of deadlock that is thread execution being stuck.
- Memory ordering: XCHG does not guarantee the order of memory accesses which means the compiler can reorder it in unexpected ways.
Addressing mode in XCHG
XCHG uses Register Addressing Mode.
This is because XCHG performs register to register or register to memory data transfer where the register is specified.
Difference between MOV and XCHG
The differences between MOV and XCHG are:
- MOV is uni-directional instruction that it moves data from source to destination operand. On the other hand, XCHG is a bi-directional instruction that moves data from source to destination and destination to source.
- MOV is faster than XCHG.
- MOV can be used to set value to an operand while XCHG requires both operands to hold valid values.
With this article at OpenGenus, you must have the complete idea of XCHG instruction.