Tech News
← Back to articles

You Can't Fool the Optimizer

read original related products more articles

You can't fool the optimiser

Written by me, proof-read by an LLM.

Details at end.

Sometimes you’ll step through code in a debugger and find a complex-looking loop… that executes as a single instruction. The compiler saw through the obfuscation and generated the obvious code anyway.

Consider this assortment of highly questionable unsigned addition routines - for variety, here compiled for ARM (unlike yesterday’s addition example).

Despite these all being very different ways of returning x + y , the compiler sees through it all and recognises that it’s just a single add w0, w1, w0 instruction. Even the recursive add_v4 - which calls itself - gets optimised down to the same single instruction.

The compiler’s ability to recognise patterns and replace them with efficient alternatives - even when the code is pretty obfuscated - is a superpower. It lets programmers choose how to write their code that’s intention-revealing (not like these contrived examples, obviously!) and leave the code generation up to the compiler, knowing that most of the time it’ll do the right thing.

So how does the compiler spot these patterns? Is it maintaining a database of “silly ways to add numbers”? Not quite. Internally, it translates your code into an intermediate representation - a simplified, abstract form that’s easier to analyse. When the compiler sees the while loop in add_v3 , it transforms it into something like “increment y by x, then return y”, which it then recognises as mathematically equivalent to “return x + y”. This process of converting different code patterns into a standard, canonical form is what lets the compiler treat them all identically. By the time code generation happens, all four functions look the same to the optimiser.

This pattern recognition is remarkably robust - the compiler will happily optimise code you’d never want to write in the first place. Throughout this series we’ll see how far this canonicalisation can take us.

See the video that accompanies this post.

... continue reading