Compiler Design
Intermediate Code & Optimisation
Learn to write three-address code for an expression, find leaders and basic blocks, build a DAG, and recall the data-flow equations. These mechanical tasks give reliable marks and link the front end to the back end.
GATE CSE intermediate code generation and optimisation — three-address code, quadruples, triples, DAGs, basic blocks and leaders, local optimisation, data-flow equations and register counting, with sample questions, flashcards and drills.
Learning outcomes
- Generate three-address code and represent it as quadruples, triples and indirect triples
- Identify leaders, basic blocks and the flow graph of a code fragment
- Build a DAG for a block and apply common local optimisations (CSE, constant folding, strength reduction, dead-code elimination)
- Write gen/kill and IN/OUT equations for reaching definitions, live variables and available expressions, and count registers with Sethi–Ullman
Three-address code, quadruples and triples
- Intermediate representation (IR) is machine-independent code between the front end and the back end: syntax trees, DAGs, postfix notation and THREE-ADDRESS CODE (TAC). It lets one front end target many machines and enables machine-independent optimisation.
- TAC has at most one operator on the right: x = y op z, x = op y, x = y, goto L, if x relop y goto L, param x / call p, n / return x, indexed x = a[i] and a[i] = x, and pointer forms x = *p, x = &y. Complex expressions use compiler-generated temporaries t1, t2, …
- QUADRUPLES have four fields (op, arg1, arg2, result): the result is a named temporary, so instructions can be moved around easily during optimisation. TRIPLES have three fields (op, arg1, arg2): the result is referred to by the index of the triple, which saves space but makes reordering hard.
- INDIRECT TRIPLES keep a separate list of pointers to triples, so the instruction order can be changed by reordering the pointer list without renumbering triples. They need more space than triples but allow easy optimisation and share common triples.
- Translation of boolean expressions and control flow uses jumping code with labels (short circuit evaluation) and BACKPATCHING: forward jumps are emitted with unfilled targets, collected in lists (truelist, falselist, nextlist) and filled when the target label becomes known — allowing one-pass translation.
- Counting question: for a = b * −c + b * −c the quadruple form has 6 rows and uses 5 temporaries t1 … t5; the triple form has 6 rows and no temporaries; the DAG form needs only 4 instructions because b * −c is computed once (t3 = t2 + t2).
- Space and flexibility: a quadruple has 4 fields, a triple 3 and an indirect triple 3 plus a pointer. Moving a quadruple changes only its position; moving a triple forces renumbering of every reference to it, which is why indirect triples exist.
- Other IRs: a syntax tree for an expression with n operands and binary operators has 2n − 1 nodes; the DAG may have fewer because common subexpressions share nodes; postfix notation is a linearised tree.
- Array references: for a 1-D array A with element width w and lower bound low, address(A[i]) = base + (i − low) × w. For a 2-D array stored in row-major order with n2 columns: address(A[i][j]) = base + ((i − low1) × n2 + (j − low2)) × w; column-major swaps the roles.
- Statement forms: if (a < b) x = 1; else x = 2; becomes if a < b goto L1; x = 2; goto L2; L1: x = 1; L2: … . while (c) S becomes L1: if c == 0 goto L2; S; goto L1; L2: …
Formulas to remember
-
A[i] (1-D) : base + (i − low) × w -
A[i][j] (2-D, row-major): base + ((i − low1) × n2 + (j − low2)) × w
| Instruction a = b * -c + b * -c | Quadruple (op, arg1, arg2, result) | Triple |
|---|---|---|
| t1 = minus c | (minus, c, —, t1) | (0) minus c |
| t2 = b * t1 | (*, b, t1, t2) | (1) * b (0) |
| t3 = minus c | (minus, c, —, t3) | (2) minus c |
| t4 = b * t3 | (*, b, t3, t4) | (3) * b (2) |
| t5 = t2 + t4 | (+, t2, t4, t5) | (4) + (1) (3) |
| a = t5 | (=, t5, —, a) | (5) = a (4) |
Worked example
Problem. Find the address of A[3][5] if A is declared A[10][20] (indices from 0), stored in row-major order, element width 4, base address 1000.
Solution. address = 1000 + (3 × 20 + 5) × 4 = 1000 + 65 × 4 = 1000 + 260 = 1260.
Translating expressions and control flow to TAC
- Expression translation is a post-order walk of the syntax tree: each interior node receives a fresh temporary. x = a + b * c − d gives t1 = b * c ; t2 = a + t1 ; t3 = t2 − d ; x = t3. An expression with n binary operators needs n temporaries.
- if-else uses two labels and a conditional jump to the THEN part; while uses a label before the test, a conditional exit jump and an unconditional jump back; for = initialisation + while with the step at the end of the body.
- Boolean expressions are translated either numerically (0/1 in a temporary) or as flow of control with short-circuit jumps. A || B && C compiled as jumping code needs no boolean temporaries.
- Backpatching: for B1 || B2, backpatch(B1.falselist, M.instr), truelist = merge(B1.truelist, B2.truelist), falselist = B2.falselist. For B1 && B2, backpatch(B1.truelist, M.instr), truelist = B2.truelist, falselist = merge(B1.falselist, B2.falselist). The marker M records the next instruction number.
| Source | Three-address pattern |
|---|---|
| x = y op z | t = y op z ; x = t (or directly x = y op z) |
| if (c) S1 else S2 | if c goto L1 ; S2 ; goto L2 ; L1: S1 ; L2: |
| while (c) S | L1: if c == 0 goto L2 ; S ; goto L1 ; L2: |
| a[i] = x | t = i * w ; a[t] = x |
| a || b (short circuit) | if a goto Ltrue ; if b goto Ltrue ; goto Lfalse |
Worked example
Problem. Write three-address code for while (i < n) { s = s + i; i = i + 1; } and count the instructions.
Solution. L1: if i >= n goto L2 ; s = s + i ; i = i + 1 ; goto L1 ; L2: … . The loop needs 4 instructions (test, two assignments, back jump). If every assignment goes through a temporary (t1 = s + i ; s = t1 ; t2 = i + 1 ; i = t2) there are 6.
Basic blocks, leaders and flow graphs
- A BASIC BLOCK is a maximal sequence of consecutive three-address instructions with a single entry (the first instruction) and a single exit (the last instruction): control enters only at the top and leaves only at the bottom, with no jumps in between.
- LEADER rules: (1) the first instruction of the program is a leader; (2) any instruction that is the TARGET of a conditional or unconditional jump is a leader; (3) any instruction that IMMEDIATELY FOLLOWS a conditional or unconditional jump is a leader. Each basic block runs from a leader up to (not including) the next leader.
- The FLOW GRAPH has the basic blocks as nodes and an edge B1 → B2 if control can pass from the end of B1 to the start of B2: either a jump from B1 to the leader of B2, or B2 follows B1 in program order and B1 does not end in an unconditional jump. Add ENTRY and EXIT nodes.
- Loops in the flow graph: a loop has a single entry node (header) that dominates all nodes in the loop. Node d DOMINATES n if every path from entry to n goes through d. A back edge n → d has d dominating n and defines a natural loop.
- Number of basic blocks = number of leaders. A common exam trap: an instruction after a conditional jump is a leader even if no jump targets it.
- Reading the figure: leaders 1, 3, 4, 7 give B1 = {1, 2}, B2 = {3}, B3 = {4, 5, 6}, B4 = {7}. The edges are ENTRY → B1, B1 → B2, B2 → B3 (fall through), B2 → B4 (jump), B3 → B2 (goto 3) and B4 → EXIT: 6 edges with ENTRY and EXIT, 4 without them.
- Successor rule: a block ending in a conditional jump has two successors (the target and the fall-through block); a block ending in an unconditional jump has one (the target); any other block flows into the next block.
- Counting trap: the jump instruction belongs to the block it ends (line 6 is in B3); the instruction after it starts a new block only if it is a leader.
- Optimizations are done per block (LOCAL: inside one basic block), per procedure (GLOBAL: using data-flow analysis across blocks) and per loop (LOOP optimisations: code motion, induction-variable elimination, strength reduction).
| Line | Three-address code | Leader? |
|---|---|---|
| 1 | i = 1 | Yes (first) |
| 2 | j = 1 | Yes (target of 11) |
| 3 | t1 = 10 * i | Yes (target of 9) |
| 4–8 | t2 = t1 + j … j = j + 1 | No |
| 9 | if j <= 10 goto 3 | No |
| 10 | i = i + 1 | Yes (follows jump 9) |
| 11 | if i <= 10 goto 2 | No |
| 12 | i = 1 | Yes (follows jump 11) |
| 13 | t5 = i - 1 | Yes (target of 17) |
| 14–17 | … if i <= 10 goto 13 | No |
Worked example
Problem. How many basic blocks does this fragment have? (1) x = 0 (2) i = 1 (3) if i > 10 goto (7) (4) x = x + i (5) i = i + 1 (6) goto (3) (7) y = x
Solution. Leaders: line 1 (first), line 3 (target of the goto in line 6), line 4 (follows the conditional jump in 3), line 7 (target of line 3 and follows the jump in 6). Blocks: {1,2}, {3}, {4,5,6}, {7} — 4 basic blocks. The edge from line 6 returns to block {3}.
Dominators and natural loops
- Node d DOMINATES node n if every path from ENTRY to n goes through d. Every node dominates itself and ENTRY dominates every node. The immediate dominator is the closest strict dominator, and the immediate dominators form the dominator tree.
- A BACK EDGE is an edge n → d whose head d dominates its tail n. The NATURAL LOOP of the back edge is d plus every node that can reach n without passing through d; d is the loop header and the only entry to the loop.
- The number of natural loops equals the number of back edges (loops that share a header are usually merged). In a reducible flow graph every retreating edge of a depth-first search is a back edge, which is what makes loop optimisation tractable.
- For the flow graph of the figure: Dom(B1) = {B1}, Dom(B2) = {B1, B2}, Dom(B3) = {B1, B2, B3}, Dom(B4) = {B1, B2, B4}. B2 dominates B3, so B3 → B2 is a back edge; B4 does not dominate B2, so B2 → B4 is not.
| Node | Dominators | Immediate dominator |
|---|---|---|
| B1 | { B1 } | none (entry block) |
| B2 | { B1, B2 } | B1 |
| B3 | { B1, B2, B3 } | B2 |
| B4 | { B1, B2, B4 } | B2 |
Worked example
Problem. In the flow graph of the figure, name the back edge and the natural loop.
Solution. B3 → B2 is the back edge because B2 dominates B3. The natural loop is the header B2 plus the nodes that reach B3 without going through B2 — only B3 itself. The loop is {B2, B3}.
DAGs and local optimisation
- A DAG for a basic block has a node for each distinct value: leaves for initial values (variables and constants) and interior nodes for operators. Identical subexpressions share a node, so DAG construction detects COMMON SUBEXPRESSIONS and DEAD code automatically.
- Number of DAG nodes: for a + a * (b − c) + (b − c) * d the leaves are a, b, c, d (4) and the interior nodes are b − c, a * (b − c), a + that, (b − c) * d and the final + : 5 interior nodes, 9 nodes in total. The DAG yields 5 TAC instructions (the tree would need 6, because b − c would be computed twice).
- Local (basic-block) optimisations: common subexpression elimination, copy propagation (replace x by y after x = y), dead-code elimination (remove assignments to variables never used again), constant folding (evaluate 2 + 3 at compile time), algebraic simplification (x + 0, x * 1), and STRENGTH REDUCTION (replace x * 2 by x + x or x << 1).
- Loop optimisations: code motion (move loop-invariant computations out of the loop), induction-variable elimination, and strength reduction inside loops (replace multiplication of the index by repeated addition).
- PEEPHOLE optimisation looks at a small sliding window of (target) instructions and replaces patterns: redundant load/store removal, algebraic simplification, jump-to-jump elimination, unreachable-code removal, use of machine idioms. It is machine dependent and usually the last step.
- Code that is generated for a = b * -c + b * -c by a DAG: t1 = minus c; t2 = b * t1; t3 = t2 + t2; a = t3 — 4 instructions instead of 6.
| Optimisation | Before | After |
|---|---|---|
| Constant folding | x = 3 + 4 | x = 7 |
| Common subexpression | t1 = b - c ... t4 = b - c | t4 replaced by t1 |
| Copy propagation | x = y ; z = x + 1 | x = y ; z = y + 1 |
| Dead-code elimination | x = a + b (x never used) | removed |
| Strength reduction | x = y * 2 | x = y + y (or y << 1) |
| Code motion | loop: t = n * 5 (n unchanged) | t = n * 5 before the loop |
Worked example
Problem. Write the optimal three-address code for a + a * (b - c) + (b - c) * d using a DAG.
Solution. t1 = b - c; t2 = a * t1; t3 = a + t2; t4 = t1 * d; t5 = t3 + t4. The subexpression b − c is computed once (shared node), so 5 instructions suffice.
Data-flow analysis basics
- Data-flow analysis computes facts that hold at program points of the flow graph by solving equations over basic blocks. Each block B has summary sets: gen[B] (facts generated in B) and kill[B] (facts invalidated by B).
- REACHING DEFINITIONS (forward, union): OUT[B] = gen[B] ∪ (IN[B] − kill[B]); IN[B] = ∪ OUT[P] over predecessors P. A definition d: x = … reaches a point if there is a path from d to that point on which x is not redefined. Used for constant propagation and detecting uninitialised variables.
- LIVE VARIABLES (backward, union): IN[B] = use[B] ∪ (OUT[B] − def[B]); OUT[B] = ∪ IN[S] over successors S. A variable is live at a point if its current value may be used later. Used for register allocation and dead-code elimination.
- AVAILABLE EXPRESSIONS (forward, INTERSECTION): OUT[B] = e_gen[B] ∪ (IN[B] − e_kill[B]); IN[B] = ∩ OUT[P] over predecessors. An expression x op y is available if it has been computed on every path and neither x nor y has been redefined since. Used for global common-subexpression elimination.
- Direction and meet: forward problems propagate from entry along edges; backward problems from exit against edges. “May” problems (reaching definitions, liveness) use union; “must” problems (available expressions, very busy expressions) use intersection. The iterative algorithm converges because the transfer functions are monotone over a finite lattice.
- Initialisation: for union problems start with ∅ for every block; for intersection problems start with the universal set for all blocks except the entry (whose IN is ∅).
- Register allocation: variables that are live at the same time interfere. Build an interference graph and colour it with k colours (registers); the minimum number of registers needed without spilling is the chromatic number of the graph. Graph colouring is NP-complete, so heuristics are used.
| Analysis | Direction | Meet | Equation |
|---|---|---|---|
| Reaching definitions | forward | union | OUT = gen ∪ (IN − kill) |
| Live variables | backward | union | IN = use ∪ (OUT − def) |
| Available expressions | forward | intersection | OUT = e_gen ∪ (IN − e_kill) |
| Very busy expressions | backward | intersection | IN = e_use ∪ (OUT − e_kill) |
Worked example
Problem. In the block (1) x = 1 (2) y = x + 2 (3) x = 5 (4) z = y + x, with z the only variable live at the exit, which variables are live immediately after statement (2)?
Solution. Work backward. After (4): {z}. Before (4): {y, x}. Before (3): x is redefined, so remove x: {y}. That is also the set live after (2): live after (2) = live before (3) = {y}. x is not live because statement (3) overwrites it before any use.
Register needs and code-generation basics
- Code generation maps TAC to target instructions using instruction selection, register allocation/assignment and instruction ordering. A register descriptor tracks what each register holds; an address descriptor tracks where each variable’s current value is (register, memory, both).
- SETHI–ULLMAN numbering gives the minimum number of registers needed to evaluate an expression TREE without spilling (for machines with instructions R ← R op M). Label leaves: left child 1, right child 0 (for a leaf operand in memory). Interior node with children labels l1 and l2: label = max(l1, l2) if l1 ≠ l2, otherwise l1 + 1. The root label is the register count.
- Example: (a − b) + ((c + d) * (e − f)). c + d has label 1 (left leaf 1, right leaf 0), e − f has label 1, their product has label 2 (equal labels, 1 + 1). a − b has label 1. The root has children labels 1 and 2, so its label is max = 2: two registers suffice.
- Basic target operations: LD R, x (load), ST x, R (store), op R1, R2, R3 (arithmetic), BR L, Bcond R, L (branches). Addressing modes: absolute, register, indirect, indexed, immediate — the code generator chooses the cheapest.
- Heuristic code-generation function getReg(x = y op z) chooses a register for the result: prefer a register already holding y (if y is dead after the instruction), otherwise a free register, otherwise spill a register.
- Optimal register use for a basic block is NP-complete in general, but optimal for trees by Sethi–Ullman and for a DAG with heuristics.
Formulas to remember
-
label(leaf) = 1 (left) or 0 (right) -
label(node) = max(l1, l2) if l1 ≠ l2 ; l1 + 1 if l1 = l2
| Expression | Sethi–Ullman label (registers) |
|---|---|
| a + b | 1 |
| (a + b) * (c + d) | 2 |
| (a − b) + ((c + d) * (e − f)) | 2 |
| ((a + b) * (c + d)) + ((e + f) * (g + h)) | 3 |
Worked example
Problem. Compute the Sethi–Ullman label for ((a + b) * (c + d)) + ((e + f) * (g + h)).
Solution. Each a + b, c + d, e + f, g + h has label 1. Each product of two label-1 nodes has label 1 + 1 = 2. The root adds two label-2 nodes: equal labels, so label = 2 + 1 = 3. Three registers are needed.
Exam tips
- Leaders: first instruction, jump targets, instructions right after jumps. Blocks = leaders.
- Quadruples are easy to reorder; triples save space; indirect triples allow reordering with triples.
- Reaching defs: forward/union. Live variables: backward/union. Available expressions: forward/intersection.
- DAG nodes: leaves for distinct names plus one interior node per distinct operation; shared subexpressions are counted once.
- Row-major 2-D address: base + ((i − low1) × columns + (j − low2)) × width.
10 GATE-style MCQs for Intermediate Code & Optimisation with full explanations. Attempt each question before revealing the answer.
The number of basic blocks in (1) x = 0 (2) i = 1 (3) if i > 10 goto (7) (4) x = x + i (5) i = i + 1 (6) goto (3) (7) y = x is:
Show answer & explanation
Answer: B
Leaders are lines 1, 3, 4 and 7, so the blocks are {1,2}, {3}, {4,5,6}, {7}.
The number of three-address instructions (including the final assignment) generated for x = a + b * c − d / e is:
Show answer & explanation
Answer: C
t1 = b * c; t2 = a + t1; t3 = d / e; t4 = t2 − t3; x = t4 — five instructions.
Which intermediate representation makes it easiest to reorder instructions during optimisation without changing references?
Show answer & explanation
Answer: B
Quadruples name their results explicitly, so moving an instruction does not invalidate references (unlike triples that refer by index).
Live-variable analysis is a:
Show answer & explanation
Answer: B
Liveness depends on future uses (backward) and a variable is live if it is live along ANY successor path (union).
Available-expressions analysis is a:
Show answer & explanation
Answer: C
An expression must be available along ALL paths (intersection), computed from predecessors (forward).
The DAG for a + a * (b − c) + (b − c) * d has how many interior (operator) nodes?
Show answer & explanation
Answer: B
b − c, a * (b − c), a + (…), (b − c) * d and the final + are the 5 distinct operations.
The minimum number of registers (by Sethi–Ullman) needed to evaluate (a − b) + ((c + d) * (e − f)) is:
Show answer & explanation
Answer: B
c + d and e − f have label 1, so their product has label 2; a − b has label 1; the root takes max(1, 2) = 2.
A[10][20] is stored in row-major order with 4-byte elements and base address 1000, indices starting at 0. The address of A[3][5] is:
Show answer & explanation
Answer: B
1000 + (3 × 20 + 5) × 4 = 1000 + 260 = 1260.
Replacing the expression x * 2 by x + x (or x << 1) is an example of:
Show answer & explanation
Answer: C
A costly operation (multiplication) is replaced by a cheaper one.
Which of the following instructions is always a leader in basic-block construction?
Show answer & explanation
Answer: B
The three leader rules are: first instruction, target of a jump, and instruction immediately after a jump.
Extra page-specific practice beyond the GATE samples. Attempt all 8, then reveal answers to check your reasoning.
The number of leaders in a program with 12 instructions where instruction 5 is an unconditional jump to instruction 2 and instruction 9 is a conditional jump to instruction 11 is:
Show answer & explanation
Answer: B) 5
Leaders: 1 (first), 2 (target of 5), 6 (follows jump 5), 10 (follows jump 9), 11 (target of 9). That is 5 leaders, hence 5 basic blocks.
For a = b * −c + b * −c, the number of three-address instructions after removing common subexpressions using a DAG is:
Show answer & explanation
Answer: B) 4
t1 = minus c; t2 = b * t1; t3 = t2 + t2; a = t3.
In the reaching-definitions equations the meet operator is:
Show answer & explanation
Answer: A) union
A definition reaches a block if it reaches along any predecessor path.
Which statement about triples is TRUE?
Show answer & explanation
Answer: B) they refer to results by the position of the triple
Triples have three fields and use instruction numbers as implicit temporaries, which makes reordering harder.
A variable is live at a point if:
Show answer & explanation
Answer: B) its value may be used on some path after the point before being redefined
This is the definition of liveness; it is a “may” property computed backward with union.
The minimum number of registers by Sethi–Ullman for ((a + b) * (c + d)) + ((e + f) * (g + h)) is:
Show answer & explanation
Answer: B) 3
Products have label 2 each; the root has equal children labels, so label 3.
The address of A[2][3] for A[5][4] stored in column-major order (indices from 0, width 2, base 100) is:
Show answer & explanation
Answer: C) 134
Column-major: base + (j × rows + i) × w = 100 + (3 × 5 + 2) × 2 = 100 + 34 = 134.
Moving the computation t = n * 5 out of a loop where n does not change is called:
Show answer & explanation
Answer: B) code motion
Loop-invariant computations are hoisted before the loop (invariant code motion).
Topic FAQs
Why use three-address code instead of generating machine code directly?
TAC is machine independent, so the same front end can serve many targets and optimisations can be done once. It also gives simple instructions with at most one operator, which is easy to analyse and transform.
What is the difference between quadruples and triples?
Quadruples store an explicit result name, so instructions can be moved freely; triples omit it and refer to other results by instruction index, saving space but making reordering difficult. Indirect triples add a level of indirection to restore easy reordering.
How do I find basic blocks quickly?
Mark leaders (first instruction, jump targets and the instruction after any jump), then cut the code just before each leader. The number of leaders is the number of blocks.
Why is available expressions an intersection problem?
An expression is available at a point only if it is available along EVERY path reaching that point, so IN[B] is the intersection of the OUT sets of all predecessors.
Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.