11.1. What is a compiler?
When people hear the word "compiler," they usually think of traditional programming language compilers, such as a C++ compiler. A traditional compiler takes source files, which are text files like .cc and .h containing functions, loops, and class definitions, and translates them into executable machine code.
Older compilers, such as early versions of GCC, were built as large, tightly integrated programs whose internal stages were difficult to reuse independently. Modern compilers, popularized by designs like LLVM, are much more modular. Instead of a single rigid block, they are split into decoupled stages that you can mix and match. You can keep the parts you need, replace the parts you do not, and target new hardware without rewriting everything from scratch.
The following figure illustrates the main components of a modern compiler.
Let's see an example of a line of C code going through this pipeline to produce assembly code. In this example, the code multiplies an integer x by four and assigns the result to y.
// 1. Source code
y = x * 4;
// 2. Frontend output
%y = mul i32 %x, 4
// 3. Optimizer output
%y = shl i32 %x, 2
// 4. Backend output
shl eax, 2
Notice that the outputs of both the frontend and the optimizer use a specialized format called Intermediate Representation (IR). The IR is a shared format used by the different stages of the compiler to communicate with each other. It is much more compiler- and optimizer-friendly than raw source code: it strips away the messy syntax of human-oriented programming languages and breaks logic down into clean, explicit instructions.
The optimizer modified the IR to help it run faster. It changed mul to a bitwise shift shl, which is equivalent to multiplying by four (x << 2) but requires fewer CPU cycles to execute.
The backend then performs code generation (often called codegen). It translates the optimized IR into concrete, hardware-specific assembly instructions, mapping virtual variables to physical CPU registers such as eax. These assembly instructions are ultimately assembled into binary machine code that the processor executes directly.