A modern optimizing compiler is one of the most sophisticated pieces of systems software ever engineered. Rather than translating source code directly into machine language in a single monolithic pass, modern compilers decompose compilation into six distinct, modular phases.
1. Analysis vs. Synthesis
The compilation process is split into two macro-phases:
- Analysis (Front-End): Analyzes the source program, verifies syntactic and semantic correctness, and produces an intermediate representation.
- Synthesis (Back-End): Takes the intermediate representation and constructs the target machine language program, allocating hardware resources like physical CPU registers.
The 6 Sequential Phases
- Lexical Analysis (Scanning): Scans characters from the source text and groups them into meaningful sequences called lexemes, returning a stream of tokens using Regular Expressions and Finite Automata.
- Syntax Analysis (Parsing): Imposes a hierarchical tree structure on the token stream based on a Context-Free Grammar (CFG), generating an Abstract Syntax Tree (AST).
- Semantic Analysis: Inspects the AST for semantic consistency: type checking, array bound compatibility, identifier declarations, and implicit type conversions (coercions).
- Intermediate Code Generation: Translates the decorated AST into an explicit, machine-independent low-level language, typically Three-Address Code (TAC).
- Code Optimization: Improves intermediate code performance: common subexpression elimination, dead code removal, constant propagation, and loop-invariant hoisting.
- Target Code Generation: Maps intermediate variables into physical CPU registers (using Graph Coloring) and emits target architecture assembly instructions.
Explore the full interactive Compiler Design curriculum on Binary Dose.