Intermediate code: syntax trees, postfix and three-address code
How to represent expressions and simple control in intermediate code using syntax (parse) trees, postfix (RPN), and three-address code; convert step-by-step and generate quadruples/triples for code-generation and optimisation passes.
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 translate high-level programs into lower-level code in several steps. Intermediate code representations such as syntax trees, postfix notation, and three-address code are used by the compiler back-end for optimisation (e.g. common subexpression elimination, dead code removal) and for final code generation (register allocation and instruction selection). Engineers use these representations when writing or debugging compilers, JITs, or code-analysis tools.
Key ideas
Start from first principles and simple definitions.
- Grammar: a formal set of production rules describing the language syntax. (Assume a context-free grammar unless otherwise stated.)
- Parse tree (or concrete syntax tree): the full tree produced by applying grammar productions to a sentence; internal nodes are grammar nonterminals; leaf nodes are terminals (tokens). Drawn for syntactic structure including all grouping parentheses and possibly punctuation.
- Abstract syntax tree (AST) or syntax tree: a simplified tree that captures the syntactic structure relevant for semantics and code generation. Internal nodes are operators; leaves are operands (identifiers, constants). It omits grammar-specific nodes (like parentheses, punctuation) and flattens associative constructs if desired.
- Postfix notation (Reverse Polish Notation, RPN): a linear representation of an expression where operators follow their operands. It directly matches stack-based evaluation: push operands, apply operator by popping required operands, push result.
- Three-address code (TAC): an intermediate representation where each instruction has at most three address fields (typically: a result and up to two operands). Typical form:
x = y op z; for unary ops and assignments use forms with fewer address fields (e.g.,x = op y,x = y). Each binary operation usually produces a temporary variable. - Temporary: a compiler-generated name (e.g.
t1, t2) holding an intermediate result in TAC. - Quadruple: a common TAC implementation with four fields:
op, arg1, arg2, result. - Triple: a TAC variant where instructions are numbered and operands may refer to instruction numbers instead of temporaries:
(op, arg1, arg2)and instruction index is implicit result. Useful before introducing temporaries. - Indirect triple: uses a table of pointers to triples to allow cheap reordering; useful for code motion in basic blocks.
Exact statements students are asked to give or use:
Construction of a parse tree (concrete syntax tree) from a grammar derivation: given a derivation of an expression using productions, the parse tree has a node for each applied production; children correspond to symbols on RHS in order. Assumption: grammar is unambiguous or a particular parse (leftmost/rightmost) is chosen.
Postfix conversion algorithm (shunting-yard concept): given infix expression with parentheses and operators of known precedence and associativity, produce postfix by scanning left-to-right, using an operator stack; on seeing operand, output it; on seeing operator, pop from stack to output while top has operator of higher precedence (or equal precedence and left-associative), then push current operator; on
(push; on)pop until(, then discard the(; after the scan, pop any remaining operators from the stack to the output.Generating TAC from syntax tree (post-order traversal): for each node:
- If leaf (operand), return its name.
- If binary operator with left child L and right child R, recursively generate code for L and R returning operand names (or temporaries), then emit
t = L op R, returnt. This assumes unlimited temporaries; register allocation handled later.
Diagrams to draw in exams (describe exactly):
To show a syntax tree for
a + b * c: draw a rooted tree with root labelled+. Two children: left child leafa; right child an internal node*with childrenbandc. Label edges from parent to children. Underneath write that postfix isa b c * +and TAC sequence will computet1 = b * cthent2 = a + t1.To show postfix evaluation: draw a stack (vertical rectangle) and show steps: push
a, pushb, pushc, see*-> popc,b, compute, pusht1, then see+-> popt1,a, computet2.
Assumptions to state in answers: operator precedence and associativity known; temporaries are fresh and unique; expressions are side-effect free unless told otherwise.
Formulas
Assignment-TAC: t = x op y — means a three-address code instruction with operator op, operands x and y, result stored in temporary or variable t. Applies for binary ops.
Unary-TAC: t = op x — unary operation; t is temporary result.
Copy/assign: x = y — a move instruction (result placed in x). Use when lowering high-level assignment.
Quadruple format: (op, arg1, arg2, result) — op is operator, arg1,arg2 are operands or - if unused, result is destination name.
Triple format: i: (op, arg1, arg2) — instruction numbered i; result is considered to be instruction i.
Postfix evaluation: push operand; on operator op with k-arity, pop k operands (for binary pop 2 in order: first pop gives right), compute, push result — stack machine rule.
Each symbol meaning: t, x, y are variable or temporary names (no physical units). op is an operator like +,-,*,/.
Worked examples
Example 1 — pure expression
Expression: a + b * c - d / e.
Assume standard precedence: * and / higher than + and -, left-associative.
Step 1: build syntax (abstract) tree. Draw root -.
- Left child of
-is+with childrenaand (*node withb,c). - Right child of
-is (/node withd,e).
Step 2: postfix (do post-order): a b c * + d e / -.
Step 3: generate TAC with temporaries, post-order traversal and numbering freshly.
t1 = b * c(compute right subtree of left+)t2 = a + t1(left subtree of-)t3 = d / e(right subtree of-)t4 = t2 - t3(root)
Quadruples (one row per instruction):
- (
*,b,c,t1) - (
+,a,t1,t2) - (
/,d,e,t3) - (
-,t2,t3,t4)
Example 2 — assignment with parentheses
Statement: x = (a + b) * (c - d).
Syntax tree: root = with left child x and right child *. The * node has left + with a,b and right - with c,d.
Postfix for right-hand side: a b + c d - *.
TAC generation (post-order):
t1 = a + bt2 = c - dt3 = t1 * t2x = t3
Quadruples:
- (
+,a,b,t1) - (
-,c,d,t2) - (
*,t1,t2,t3) - (
=,t3,-,x)
Example 3 — simple conditional (control flow)
High-level: if (a < b) c = a + b; else c = a - b;
Approach: produce TAC with labels and conditional jump.
Assume relational operators produce boolean condition and ifFalse form jumps when condition is false.
TAC (one correct variant):
if a >= b goto L1(note:ifFalse a<b goto L1is equivalent)t1 = a + bc = t1goto L2L1:t2 = a - bc = t2L2:
Triples/quadruples would mirror these instructions; when asked to draw flow graph, show basic blocks: for example, B1 [1]; B2 [2-4]; B3 [5] (often merged with B4); B4 [6-7]; B5 [8]. Any equivalent partition that respects leaders (first statement, targets of jumps, and statements following any jump) is acceptable.
Common mistakes
- Reusing the same temporary name for different values in a single linear TAC sequence without noting redefinition; temporaries must be fresh or liveness must be considered.
- Forgetting to emit a final move to the target variable for assignment statements (
x = t3). - Using precedence rules inconsistently when converting to postfix — always state precedence and associativity used.
- Producing TAC with more than three addresses per instruction; stick to one op and up to two source operands.
For your exam
Typical question types:
- Definitions and distinctions (define AST, parse tree, postfix, TAC; state differences).
- Short notes (advantages of TAC, quadruples vs triples, uses of postfix).
- Conversions (convert infix to postfix, draw syntax tree, generate TAC and quadruples/triples).
- Traces (show stack evolution during postfix evaluation; step-by-step code emission).
- Diagrams (draw tree and label nodes; draw flow graph of basic blocks for conditional code).
What a full-marks answer includes:
- Precise definitions with bold term use and clear assumptions (operator precedence, associativity).
- Correctly drawn tree (root operator, internal nodes operators, leaves operands) — label nodes and edges; mention traversal order used.
- Postfix string produced by post-order traversal and operator precedence justification if conversion done directly.
- TAC sequence with fresh temporaries numbered, and corresponding quadruples/triples if requested. For control flow, include labels and correct conditional/unconditional jumps.
- For trace questions, show every stack or temporary state step-by-step.
Quick check
- Convert the infix expression
x = a * (b + c)to postfix and give TAC. - In postfix evaluation, when seeing operator
-, you pop operands r then l; if stack top order islthenr, which is used as left and right? (short conceptual) - Give the quadruple for instruction
t = p / q.
Answers: 1) Postfix for RHS: a b c + *; TAC: t1 = b + c, t2 = a * t1, x = t2. 2) Pop twice: first pop is right operand r, second pop is left operand l — use as l - r. 3) (/, p, q, t).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?