NASM中为何可对双64位寄存器执行XOR,却无法对寄存器与QWORD执行?
Great question—this boils down to x86-64 instruction set limitations and how NASM translates your assembly into machine code. Let’s break it down clearly:
First, let’s clarify the examples
Let’s anchor this with concrete code snippets to match what you’re seeing:
- Working code (register-to-register):
xor rax, rbx ; Two 64-bit registers XORed together—fully valid - Non-working code (register-to-64-bit immediate):
xor rax, 0x123456789ABCDEF0 ; Fails with "invalid combination of opcode and operands"
The core reason: x86-64 doesn’t support 64-bit immediates for XOR
The x86-64 instruction set has strict rules for what operands each instruction can accept. For the XOR instruction:
- Register-to-register operations are fully supported for all register sizes (8-bit, 16-bit, 32-bit, 64-bit). The CPU has dedicated machine code encodings for these cases, so NASM can easily translate your code into valid bytes the CPU understands.
- Immediate operands (literal values like
0x123456789ABCDEF0) are limited to 32 bits forXORin 64-bit mode. Any 32-bit immediate you use is automatically sign-extended to 64 bits, but if your value exceeds the 32-bit signed range (-2^31to2^31-1), there’s no way to encode it as an immediate forXOR—the instruction set simply doesn’t include a machine code for a 64-bit immediate operand here.
Wait, what about QWORDs in memory?
If you’re referring to a QWORD stored in memory (not a literal immediate), that does work! For example:
my_qword dq 0x123456789ABCDEF0 ; Define a 64-bit variable in memory xor rax, [my_qword] ; XOR rax with the QWORD value from memory—valid
The confusion often comes from mixing up "QWORD immediate" and "QWORD memory operand"—only the former is unsupported for XOR.
How to work around the 64-bit immediate limitation?
If you need to XOR a register with a full 64-bit literal value, just load the value into another register first:
mov rbx, 0x123456789ABCDEF0 ; Load the 64-bit immediate into rbx xor rax, rbx ; Now XOR rax with rbx—works perfectly
内容的提问来源于stack exchange,提问作者Wealot

