The compiler pipeline
The previous note ended with a C loop the compiler deleted at -O2: twenty million iterations took no time because the result was known in advance. This topic opens that compiler. Follow one small function through LLVM — the infrastructure behind Clang, Rust, Swift and many others — from text to SSA IR, through optimization passes, out as machine code of the kind the assembly half of the course wrote by hand.
Notation. IR is the compiler’s intermediate representation. SSA is static single assignment form. A pass reads IR and writes IR (or an analysis). LLVM IR text uses %name for values, i32 for a 32-bit integer, ptr for a pointer, and a label ending in : for a basic block.
The running example is the sum :
int sum_to(int n) {
int s = 0;
for (int i = 1; i <= n; i++)
s += i;
return s;
}The simplest compiler translates one language straight into the assembly of one processor. For one pair it works. It breaks in two ways. First, the pairs multiply: with languages and processors there are compilers, and each repeats the same work — the C parser once per CPU, the RISC-V tables once per language. Three languages and three processors need nine compilers; ten of each need a hundred. Second, optimization has no home: keeping values in registers, folding constants and moving work out of loops are almost the same for every language and target, yet a per-pair compiler rewrites them times or not at all.
Key idea. Put one representation in the middle. A front end per language translates source into a common IR; an optimizer rewrites IR into better IR as a sequence of independent passes that know nothing about the source language or the target; a back end per processor translates IR into machine code. Then languages and processors need parts instead of , and every optimization is written once.
Clang’s driver prints the plan with -ccc-print-phases (trimmed): input → preprocessor → compiler (to IR) → backend (to assembler) → assembler (to object). Front ends include Clang for C/C++/Objective-C, rustc for Rust, swiftc for Swift. LLVM IR exists as in-memory data structures, readable .ll text and compact .bc bitcode. The -O2 pipeline runs dozens of passes, some several times. Back ends cover x86-64, AArch64, RISC-V, GPU targets and others.