The Zero Idiom Recognition: How CPUs Turn XOR Into a Free Instruction

2026-07-14

Every x86 compiler emits xor eax, eax instead of mov eax, 0. The encoding is shorter (2 bytes vs 5), but that's only half the reason. The real payoff happens inside the rename stage, where the CPU recognizes this specific pattern as a zero idiom and executes it without ever touching an execution unit.

Normally, an instruction like xor eax, eax would be a read-modify-write on EAX: two source register reads, one destination write, dispatched to an ALU port, one cycle of latency, and a dependency on the previous value of EAX. That last part matters — a naive implementation would serialize on whatever produced EAX earlier, even though the result doesn't actually depend on it.

The renamer catches specific "self-zeroing" patterns during decode: xor r, r, sub r, r, pxor xmm, xmm (same register), vpxor ymm, ymm, ymm, and a handful of others. When it sees one, it:

This is why xor-zeroing shows up as effectively free in perf counters even though it looks like a normal instruction. Intel's optimization manual documents this behavior explicitly for Sandy Bridge and later; AMD Zen implements it too.

Concrete example: A tight loop that zeros a counter each iteration:

loop:
  xor  eax, eax     ; recognized as zero idiom - free
  add  eax, [rdi]   ; no wait for prior eax value
  add  rdi, 8
  cmp  rdi, rsi
  jne  loop

Without idiom recognition, the xor would serialize against the previous iteration's add eax, [rdi], forming a false dependency chain across the whole loop. With it, each iteration's xor is dependency-free, and the CPU can overlap multiple iterations in the OoO window.

Rule of thumb: Only the exact canonical patterns are recognized. mov eax, 0 is not a zero idiom — it still executes on an ALU port and has real latency (though move elimination handles it separately). and eax, 0 is not recognized either. If you're writing hand-assembly, stick to xor for zeroing scalar registers and pxor/vpxor for vector ones.

The same mechanism extends to ones idioms on some CPUs — pcmpeqd xmm, xmm is recognized as producing all-ones without executing.

Key Takeaway: Zero idioms like xor eax, eax are handled entirely in the rename stage — zero latency, zero execution port pressure, and no false dependency on the register's prior value, which is why compilers use them universally.

All newsletters