Tech News
← Back to articles

Why xor eax, eax?

read original related products more articles

Why xor eax, eax?

Written by me, proof-read by an LLM.

Details at end.

In one of my talks on assembly, I show a list of the 20 most executed instructions on an average x86 Linux desktop. All the usual culprits are there, mov , add , lea , sub , jmp , call and so on, but the surprise interloper is xor - “eXclusive OR”. In my 6502 hacking days, the presence of an exclusive OR was a sure-fire indicator you’d either found the encryption part of the code, or some kind of sprite routine. It’s surprising then, that a Linux machine just minding its own business, would be executing so many.

That is, until you remember that compilers love to emit a xor when setting a register to zero:

We know that exclusive-OR-ing anything with itself generates zero, but why does the compiler emit this sequence? Is it just showing off?

In the example above, I’ve compiled with -O2 and enabled Compiler Explorer’s “Compile to binary object” so you can view the machine code that the CPU sees, specifically:

31 c0 xor eax , eax c3 ret

If you change GCC’s optimisation level down to -O1 you’ll see:

b8 00 00 00 00 mov eax , 0x0 c3 ret

... continue reading