Day 1 of Advent of Compiler Optimisations!

Why do compilers love `xor eax, eax` for zeroing registers? It's brilliant: saves bytes compared to `mov eax, 0`, AND x86 CPUs recognise this "zeroing idiom" early in the pipeline—breaking register dependencies and removing it from execution entirely. Even better: writing to `eax` zeroes the top 32 bits of `rax` for free, handling 64-bit longs in one instruction.

Read more: https://xania.org/202512/01-xor-eax-eax
Watch: https://youtu.be/eLjZ48gqbyg

#AoCO2025

Why xor eax, eax? — Matt Godbolt’s blog

Why do compilers love xor-ing registers so much?

@mattgodbolt wait xor eax, eax clears the top of rax?

I never knew that, and also that seems pretty bad. Does xor ax, ax also clear ALL of eax and rax?

@hp any write to a 32-bit register clears the top 32-bits. That's not true of the other writes. When AMD expanded the registers to 64b, they changed the behaviour for those only. So xor ax, ax only clears the bottom 16b, leaving the other 48 alone.

@mattgodbolt @hp bit annoying… I often use something like mov eax,[foo]; mov ah,[bar] on i386.

Haven’t actually got into amd64 asm much, despite owning some for a couple of years now. (Oops, over half a decade.) This is one of the reasons that make me hesitate.