Compiler structure and phases
Overview of a compiler's purpose, structure and each phase from lexical analysis to code generation and optimisation, with clear definitions, examples and exam-focused notes.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Compilers are the programs engineers use to translate high-level source code into machine code or another target form. Understanding compiler structure helps when debugging language tools, improving performance (optimisation), writing language front-ends (lexers/parsers), or implementing back-end tasks such as code generation and linking.
Key ideas
Start from first principles and define each key term before using it.
Compiler: a program that performs a translation from a source language to a target language. Exact statement used in exams: a compiler C is correct if for every source program S, the observable behaviour of S under the source-language semantics equals the observable behaviour of C(S) under the target-language semantics (assumes both semantics are well-defined).
Translation: a mapping T: SourcePrograms -> TargetPrograms. Assumption: semantics are preserved, or a defined approximation (e.g., optimisations may change non-observable behaviour like register allocation).
Front end: the part of a compiler that analyses the source program. It usually includes lexical analysis, syntax analysis, and semantic analysis. The front end is language-specific but machine-independent.
Back end: the part that maps intermediate representation to target machine code and performs target-dependent optimisations and register allocation.
Phase: one stage in the compiler pipeline that performs a well-defined task and produces a concrete output consumed by the next phase. Standard phases (each defined below) are: lexical analysis, syntax analysis (parsing), semantic analysis, intermediate code generation, code optimisation, code generation; cross-cutting concerns include symbol table management and error handling/recovery.
Lexical analysis (scanner): converts a sequence of characters into a sequence of tokens. A token is a pair (token-type, attribute) where token-type is a syntactic category (e.g., IDENTIFIER, NUMBER, PLUS) and attribute carries details (lexeme, numeric value). Lexical rules are usually specified by regular expressions and implemented with finite automata.
Syntax analysis (parsing): converts tokens into a parse tree according to a grammar (usually context-free). Exams often ask: draw the parse tree and label nodes with grammar non-terminals and terminals. For a derivation, show the rightmost or leftmost derivation steps and the production rules used.
Semantic analysis: enforces language rules not captured by grammar, e.g., type checking, scope rules, definite assignment. Uses symbol table entries (name, type, scope, memory attributes). Attribute grammars attach attributes to parse-tree nodes to compute types and other properties.
Intermediate Representation (IR): a form between source and target. Common IRs: three-address code (TAC), abstract syntax tree (AST), control-flow graph (CFG). An AST is a condensed, operator-centric tree that omits most surface syntax compared to the parse tree; a CFG is a graph over basic blocks constructed from IR. IR should be easy for optimisations and target-independent.
Code optimisation: transformations on IR to improve performance or space. Example transformations: constant folding, common subexpression elimination, dead code elimination, loop-invariant code motion. Many optimisations operate on basic blocks and the control-flow graph. A basic block is a maximal sequence of instructions with single entry and single exit.
Code generation: convert IR to target assembly/machine code. Tasks: instruction selection, instruction scheduling, register allocation. Register allocation often reduces to graph colouring on the interference graph (approximate algorithms used in practice).
Symbol table: data structure that maps identifiers to information (type, scope level, memory location). Implemented with hash tables or scoped stacks. Used throughout front end and code generation.
Exact exam-style derivation often asked: show the output of each phase on a small program and justify why each phase produced that output. When a diagram is needed (e.g., compiler architecture), draw boxes for phases in sequence left-to-right: Source code -> [Lexical analyser] -> [Parser] -> [Semantic analyser] -> [IR generator] -> [Optimiser] -> [Code generator] -> Target code. Optionally (to show the full toolchain), include [Preprocessor] before the lexical analyser, and [Assembler] -> [Linker/Loader] after code generation. Label arrows with the kind of data passed (characters -> tokens -> parse tree -> annotated tree/IR -> optimized IR -> machine code).
Formulas
(For compiler topics we list syntax and small formal notations to remember.)
- Token for identifier:
IDENTIFIER: [a-zA-Z_][a-zA-Z0-9_]*— pattern for most C-like languages (lexeme is the matched character sequence). - Integer literal:
NUMBER: [0-9]+(attribute: numeric value as integer) — adjust for language-specific bases and suffixes. - Regular expression union, concatenation, Kleene star:
R | S,RS,R*— used to specify lexical tokens. - BNF form for a simple expression grammar (remember):
E -> E + T | TT -> T * F | FF -> ( E ) | id | number - Three-address code forms to remember:
x = y op z,x = op y,goto L,if x relop y goto L,param x,call p, n,return x. - Basic block: maximal sequence of instructions I1..Ik where control enters at I1 and exits at Ik with no other entry or exit. Control-flow graph (CFG): a directed graph whose nodes are basic blocks and edges represent possible control transfers between blocks.
Worked examples
Example 1 — full-phase trace for a single statement
Source line: int sum = a + 42;
Lexical analysis: produce tokens (token-type(attribute)) — show each token
INT_KEYWORD("int")IDENTIFIER("sum")ASSIGN("=")IDENTIFIER("a")PLUS("+")NUMBER("42", value=42)SEMICOLON(";")Symbol table updates: addsumwith typeint, storage not yet allocated (scope entry). Do not allocate forahere if it is external; lookupain symbol table and record use.
Parsing: using the expression grammar, show a parse tree. Describe what to draw: draw root node
declarationwith childrentype(leafint),init-declarator-list->init-declarator-> nodesidentifier(sum),=,initializer->assignment-expression-> subtreea + 42. Label leaves with tokens and interior with grammar non-terminals.Semantic analysis: check types. Attribute computations (if using an attribute grammar): type(a) must be
int; type(42) isint; result type ofa + 42isint; assignment targetsumtypeintmatches. If mismatch report error. Update symbol table:sumhas storage class, offset, typeint.IR generation (three-address code): Generate temp t1 = 42 t2 = a + t1 sum = t2 Example TAC lines:
t1 = 42t2 = a + t1sum = t2Code generation (simple): map to an assembly-like sequence (assume target has LOAD, ADD, STORE):
LOAD r1, a; r1 = aLOADI r2, 42; r2 = 42ADD r3, r1, r2; r3 = r1 + r2STORE sum, r3; sum = r3
Final answer: show tokens, parse-tree sketch, symbol-table entries, TAC, and assembly. This is what examiners expect.
Example 2 — small optimisation: constant folding and common subexpression
IR before optimisation:
t1 = b * 2
t2 = 3 + 4
t3 = a + t1
t4 = a + t1 ; common subexpression
t5 = t2 * t3
Optimisation steps:
- Constant folding:
t2 = 7(replace3+4with7). - Common subexpression elimination: note
t3andt4identical, removet4and uset3instead. Resulting IR:t1 = b * 2t2 = 7t3 = a + t1t5 = t2 * t3Explain briefly how a value-numbering or DAG algorithm would find the redundancy in a basic block and eliminate it.
Common mistakes
- Forgetting to check scopes during semantic analysis: duplicate declarations or undeclared identifiers are frequent errors.
- Mixing up IR instruction forms — three-address code has at most three operands;
x = y + z + wmust be broken into temporaries. - Thinking all optimisations preserve every aspect of program behaviour; emphasise they must preserve observable semantics (undefined-behaviour cases may be exploited).
- Not labelling diagrams clearly: when asked to draw compiler architecture, label boxes and arrows and state data passed between phases.
For your exam
Question types you will see:
- Definitions: define compiler, token, lexeme, AST, basic block, CFG. Full-marks answer: concise definition plus one short example.
- Short notes: roles of lexing, parsing, semantic analysis, IR, optimisations. Full-marks answer: list responsibilities, typical algorithms, and one example transformation.
- Derivations / traces: given source code, show tokens, parse tree, symbol-table entries, attribute computation and generated TAC. Full-marks answer: show each phase output clearly and correct type/attribute computations.
- Numericals/algorithms: small examples of optimisation (constant folding, CSE), or register allocation by graph colouring on a small interference graph. Full-marks answer: step-by-step algorithm trace and final result.
- Diagrams: draw compiler pipeline or a CFG for given code. Full-marks answer: labelled diagram with nodes/edges, and brief explanation.
How to write full-marks answers: Always state assumptions (e.g., grammar used, starting symbol); give intermediate outputs for each compiler phase; if asked to draw, describe shapes and labels; if asked for proofs, start from definitions and show each step.
Quick check
- What is a token?
- Name two optimisations that operate at the basic-block level.
- What is the main difference between front end and back end of a compiler?
Answers: Token = a pair (token-type, attribute) representing a syntactic category and its data; optimisations: constant folding, common subexpression elimination (also dead-code elimination); front end analyses source (lexing/parsing/semantics) and is language-specific, back end generates machine code and performs target-specific optimisations.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?