Apex › Systems & OS

The compiler’s last polish (peephole optimization)

The final local-rewrite pass: slide a small window over consecutive instructions and replace patterns with cheaper equivalents. Strength reduction (mul r,4 → shl r,2), algebraic identities and dead ops (add r,0 and mul r,1 vanish; xor r,r → mov r,0), and combining adjacent ops (add r,1; add r,1 → add r,2). Every rule is a proven semantics-preserving identity, and it iterates to a fixpoint since one rewrite can expose another — the closing pass in GCC and LLVM. Verified in node: all rewrites preserve semantics for every 32-bit input, and a 6-instruction sequence optimizes to 3 with identical output. Slide the peephole and watch the program shrink while the result stays 8x+4.

More in Systems & OS