Optimization Phases and Safety
You'll learn when optimizations happen in the compilation pipeline and what makes them safe to apply.
When Do Optimizations Occur?
Compiler optimizations don't happen all at once—they're organized into distinct phases throughout the compilation pipeline. After parsing and semantic analysis, optimizations typically run on the intermediate representation (IR) in multiple passes:
- Early optimizations work on high-level IR or ASTs (constant folding, dead code elimination)
- Middle-end optimizations operate on lower-level IR like SSA form (common subexpression elimination, loop transformations)
- Late optimizations happen during or after code generation (peephole optimization, register allocation improvements)
This phased approach allows each optimization to leverage the best representation for its task—some are easier on SSA form, others need control flow graphs, and some work best on nearly-final machine code.
What Makes an Optimization Safe?
An optimization is safe (or correctness-preserving) if it never changes the observable behavior of a correct program. Think of it like refactoring code—you can rearrange, simplify, or speed things up, but the program must still produce the same outputs for the same inputs.
Safe transformations must preserve:
- Program semantics: Same results for all valid inputs
- Side effects: Memory writes, I/O operations happen in the correct order
- Exception behavior: Errors occur at the same program points
For example, reordering two independent arithmetic operations is safe, but reordering two memory writes is not—another thread might observe the difference.
Some optimizations are conservative: they only apply when the compiler can prove safety through static analysis, even if they might be safe more often in practice.
Key Takeaway: Optimizations are applied in phases across the compilation pipeline, and each transformation must be provably correctness-preserving to maintain program semantics.