IR & Optimisation

Intermediate representations (three-address code, control-flow graphs, SSA form, LLVM IR) and the classic optimisations — constant folding, dead code elimination, CSE, inlining, loop optimisations, vectorisation and escape analysis.

Advanced 4 min readLesson 5 of 8

After semantic analysis, the compiler lowers the AST into an intermediate representation (IR) that's easier to analyse and transform. Most of a modern compiler's code and compile time goes into optimising this IR.

Kinds of IR

IRShapeUsed by
ASTTree, close to the sourceFront ends, linters, transpilers
Three-address code (TAC)Linear instructions, at most one operator each: t1 = a + bTextbooks, many compilers internally
Control-flow graph (CFG)Basic blocks (straight-line code) connected by jumpsEvery optimising compiler
SSA formEach variable assigned exactly onceLLVM, GCC (GIMPLE), HotSpot C2, V8 TurboFan, Go
Stack bytecodePush/pop operationsJVM, CPython, WebAssembly

Control-flow graph

A basic block is a maximal sequence of instructions with one entry (the top) and one exit (the bottom). Edges are possible jumps.

int abs_sum(int a, int b) {
    int s = a + b;
    if (s < 0) s = -s;
    return s;
}
truefalseB0: s = a + bif s < 0 goto B1 else B2B1: s = -sB2: return s

Static single assignment (SSA)

In SSA, every variable is assigned once; reassignments create new versions. Where control flow merges, a φ (phi) function picks the version from whichever predecessor ran:

B0:  s1 = a + b
     if s1 < 0 goto B1 else B2
B1:  s2 = -s1
     goto B2
B2:  s3 = φ(s1 from B0, s2 from B1)
     return s3

Why SSA? Each use has exactly one definition, so "where does this value come from?" is trivial, which makes many optimisations simpler and faster (constant propagation, dead code elimination, register allocation).

LLVM IR

LLVM IR is a typed, SSA-based, assembly-like language:

define i32 @abs_sum(i32 %a, i32 %b) {
entry:
  %s = add nsw i32 %a, %b
  %neg = icmp slt i32 %s, 0
  br i1 %neg, label %flip, label %done
flip:
  %ns = sub nsw i32 0, %s
  br label %done
done:
  %r = phi i32 [ %s, %entry ], [ %ns, %flip ]
  ret i32 %r
}

At -O2, LLVM turns the branch into a branchless select (or a single abs-style instruction sequence) — see for yourself with clang -O2 -S -emit-llvm.

Classic optimisations

OptimisationBeforeAfter
Constant foldingx = 60 * 60 * 24x = 86400
Constant propagationn = 4; y = n * 2y = 8
Dead code eliminationt = a * b; (t never used)removed
Common subexpression eliminationx = a*b + c; y = a*b + dt = a*b; x = t + c; y = t + d
Copy propagationy = x; z = y + 1z = x + 1
Strength reductionx * 8, i * 4 in a loopx << 3, a running += 4
Algebraic simplificationx + 0, x * 1, x - xx, x, 0
Unreachable code eliminationif (false) { … }removed

Inlining — the most important one

Inlining replaces a call with the callee's body. It removes call overhead, but more importantly it exposes other optimisations: after inlining, constants propagate into the body, branches fold away, and values stay in registers.

C
static int square(int x) { return x * x; }
int f() { return square(5) + 1; }
// after inlining + constant folding:
int f() { return 26; }

The cost is code size, so compilers use heuristics (callee size, call frequency, hotness from profiles).

Loop optimisations

Programs spend most of their time in loops:

  • Loop-invariant code motion (LICM): move computations that don't change across iterations out of the loop.
  • Induction variable simplification / strength reduction: replace a[i*stride] address computation with an incrementing pointer.
  • Loop unrolling: do 4 iterations per loop trip to reduce branch overhead and enable scheduling.
  • Vectorisation: use SIMD instructions to process 4–16 elements at once (Instruction-level parallelism).
  • Loop fusion / interchange / tiling: improve cache locality (Cache memory).
C
// Before LICM
for (int i = 0; i < n; i++) a[i] = x * y + i;
// After
int t = x * y;
for (int i = 0; i < n; i++) a[i] = t + i;      // and then vectorised

Other important analyses

  • Escape analysis: if an object never escapes a function, allocate it on the stack or eliminate it (scalar replacement) — big wins in Java and Go.
  • Alias analysis: can two pointers refer to the same memory? If not, loads can be reordered and cached in registers. (C's restrict and Rust's &mut uniqueness give the compiler this guarantee.)
  • Devirtualisation: turn a virtual call into a direct (inlinable) call when the receiver type is known.
  • Tail-call elimination: turn a call in tail position into a jump, so recursion uses constant stack.

Optimisation levels and passes

Optimisers are a pipeline of passes, each doing one analysis or transform, repeated because one enables another:

FlagMeaning
-O0No optimisation; fast compile, easy debugging
-O1 / -O2Standard optimisations (release builds usually use -O2)
-O3Aggressive inlining and vectorisation; bigger code, not always faster
-Os / -OzOptimise for size
-fltoLink-time optimisation across translation units
PGO (-fprofile-use)Profile-guided: optimise using data from real runs
Key takeaways
  • IRs (three-address code, CFGs of basic blocks, SSA) make analysis and transformation tractable.
  • SSA gives every variable one definition, with φ functions at merge points.
  • Classic optimisations: constant folding/propagation, dead code elimination, CSE, strength reduction.
  • Inlining is the most important optimisation because it enables others.
  • Loop optimisations (LICM, unrolling, vectorisation) and escape/alias analysis deliver major speedups.
  • Optimisers are pass pipelines; -O levels, LTO and PGO control how aggressive they are.