How a compiler turns code into machine code
A processor cannot run Swift or C source code; it runs machine instructions. A compiler translates one into the other in stages, and the idea to keep is that every stage hands a simpler form to the next.
The short version
A compiler is usually described in three parts. The front end reads your source, reports errors and builds a syntax tree (AST) for that language. The optimizer improves the code, mostly independent of the language and the machine. The back end maps the code to the instruction set of one processor. Between them sits a shared intermediate representation (IR): LLVM IR, for example, is a low-level, strongly typed virtual instruction set.
Step by step
- The front end parses the source, reports mistakes and builds the AST.
- The AST is lowered to the IR. Swift adds a layer here: its own IR, called SIL, comes first, then LLVM IR.
- The optimizer rewrites the IR to improve it.
- The back end turns the IR into machine code for one instruction set.
- The linker joins the pieces into one executable.
GCC can stop after each stage:
| Flag | Stops after | You get |
|---|---|---|
-E |
preprocessing | preprocessed source on standard output |
-S |
compiling | an assembly file (.s) |
-c |
assembling | an object file (.o) |
| none | linking | an executable (a.out) |
Why it matters
Because the IR is shared, a new language needs only a new front end and a new processor only a new back end. Without it, every pair of language and processor would need its own compiler.
Sources
- Overall Options — GCC documentation — the order of stages, what
-E,-Sand-cstop at, and that linking producesa.outby default - LLVM — The Architecture of Open Source Applications — front end, optimizer and back end, the shared IR, and the language-times-target argument
- Swift Compiler — swift.org — parsing to AST, type checking, SIL, then LLVM IR