Back Original

You Can't Fool the Optimizer

Written by me, proof-read by an LLM.

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 routines1 - 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, w02 instruction. Even the recursive add_v4 - which calls itself - gets optimised down to the same single instruction3.

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 optimiser4.

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.


This post is day 3 of Advent of Compiler Optimisations 2025, a 25-day series exploring how compilers transform our code.

This post was written by a human (Matt Godbolt) and reviewed and proof-read by LLMs and humans.

Support Compiler Explorer on Patreon or GitHub, or by buying CE products in the Compiler Explorer Shop.