Sub topic 9
Three-address code
This chapter assumes you can read C-style expressions, know what a syntax tree is, and have seen syntax-directed translation at an introductory level. It covers the instruction forms of three-address code (TAC), how expressions are translated into it, and the mistakes that cost marks in GATE questions. How TAC is stored (quadruples, triples) and how jumps are generated come in later chapters.
What three-address code is
Three-address code is an intermediate representation in which each instruction has at most one operator on the right-hand side and at most three addresses: two operands and one result. A long expression is broken into a sequence of small steps, and the compiler invents names called temporaries to hold the intermediate values.
For a = b * -c + b * -c, the source has one statement and the TAC has six instructions:
t1 = minus c
t2 = b * t1
t3 = minus c
t4 = b * t3
t5 = t2 + t4
a = t5An address in TAC can be:
- A source name, such as
borc. In a real compiler this is a pointer to its symbol-table entry. - A constant, such as
4or3.14. - A compiler-generated temporary, such as
t1. Each temporary is normally assigned once, so a fresh name is created each time.
TAC is close to machine code, since each instruction becomes a few machine operations. It is also independent of any particular machine. That combination makes it a good place to run optimizations.
Common instruction forms
| Form | Example | Meaning |
|---|---|---|
| Binary assignment | `x = y op z` | Apply a binary operator |
| Unary assignment | `x = minus y` | Unary operator or conversion |
| Copy | `x = y` | Copy a value |
| Unconditional jump | `goto L` | Transfer control to label `L` |
| Conditional jump | `if x relop y goto L` | Jump if the test is true |
| Procedure call | `param x1` … `call p, n` | Pass `n` parameters, then call |
| Return | `return y` | Return a value |
| Indexed copy | `x = y[i]`, `x[i] = y` | Memory at address `y + i` |
| Address and pointer | `x = &y`, `x = *y`, `*x = y` | Take an address or dereference |
The indexed forms use a byte offset, not an element number. For x = a[i] with 4-byte integers, the compiler first computes the offset:
t1 = i * 4
x = a[t1]A procedure call f(a, b + 1) becomes one param per argument, in order, followed by the call and the argument count:
t1 = b + 1
param a
param t1
call f, 2If the result is used, the call is written as r = call f, 2.
Translating expressions
The standard syntax-directed scheme gives each expression node an attribute addr, the address that holds its value, and a list code of the instructions that compute it. For E → E1 + E2:
- Create a new temporary
tand setE.addr = t. - Set
E.codetoE1.code, thenE2.code, thent = E1.addr + E2.addr.
For an identifier, E.addr is the name itself and E.code is empty. Only operators produce instructions. The program below applies this scheme by a post-order walk of an expression tree.
from itertools import count
def translate(tree):
code = []
temps = count(1)
def gen(node):
if isinstance(node, str):
return node
if node[0] == "minus":
arg = gen(node[1])
t = f"t{next(temps)}"
code.append(f"{t} = minus {arg}")
return t
op, left, right = node
l = gen(left)
r = gen(right)
t = f"t{next(temps)}"
code.append(f"{t} = {l} {op} {r}")
return t
return gen(tree), code
tree = ("+", ("*", "b", ("minus", "c")), ("*", "b", ("minus", "c")))
result, code = translate(tree)
code.append(f"a = {result}")
print("\n".join(code))Running it prints exactly the six instructions shown earlier. The tree contains b * -c twice, and the walk translates both copies, so the work is duplicated.
From tree to DAG to TAC
A syntax tree repeats common subexpressions. A DAG (directed acyclic graph) shares them, so each distinct value appears once. Generating TAC from the DAG removes the duplicate work:
t1 = minus c
t2 = b * t1
t5 = t2 + t2
a = t5The same expression now takes four instructions instead of six.
Common errors
- Counting the final copy.
a = t5is a separate instruction when the translation scheme creates a temporary for the whole right side. Check whether the question allows a smarter generator that writesa = t2 + t4directly. The scheme in the question decides the count. - Forgetting the element size.
a[i]needsi * w, wherewis the element width. A two-dimensional array needs two multiplications and an addition, for examplei * n2 * w + j * wfor ann1 × n2array in row-major order. - Reusing a temporary. A temporary written twice breaks the one-assignment convention. Optimizations such as DAG sharing depend on that convention.
- Wrong evaluation order. Operands are translated left to right, so temporaries are numbered in post-order. Questions that ask "what is
t3?" depend on this. - Mixing up
paramandcall.parampushes one argument. Thenincall p, nis the number ofparaminstructions that belong to this call.
Why this form helps later phases
Each instruction touches few values, so later analyses can handle each one in turn. Basic blocks, the data flow sets gen and kill, and common subexpression elimination all work by scanning single instructions. Jump targets are explicit labels, so the program can later be cut into blocks at those labels.
Exercise
Translate x = a[i] + b * c into three-address code with a naive generator, where a is an array of 4-byte integers. How many temporaries are used, and how many instructions result?
Show answer
The code is t1 = i * 4, t2 = a[t1], t3 = b * c, t4 = t2 + t3, x = t4. That is 4 temporaries and 5 instructions. If the generator assigns the final sum directly to x, it uses 3 temporaries and 4 instructions.
Exercise
A DAG for p = (u + v) * (u + v) - (u + v) shares the node for u + v. Write the TAC generated from the DAG and give the instruction count.
Show answer
t1 = u + v, t2 = t1 * t1, t3 = t2 - t1, p = t3. That is 4 instructions. The tree-based translation would need 3 additions, giving 6 instructions in total plus the copy to p, which is 7.