Three-Address Code (TAC)
You'll learn how compilers simplify complex expressions into instructions with at most three operands, making optimization and code generation much easier.
What is Three-Address Code?
Three-Address Code (TAC) is a classic intermediate representation that breaks down every computation into simple instructions. Each instruction has at most three addresses (operands): typically two sources and one destination. Think of it as translating a complex recipe into individual, atomic steps—each step does exactly one thing.
The Form
A TAC instruction looks like:
result = operand1 op operand2
For example, the expression x = a * b + c * d becomes:
t1 = a * b
t2 = c * d
x = t1 + t2
Notice how each line performs just one operation. Temporary variables (t1, t2) hold intermediate results.
Why TAC Matters
Simplicity: Complex expressions become sequences of elementary operations. This uniformity makes writing compiler passes straightforward—you don't need to handle deeply nested expressions.
Optimization-Friendly: Because each instruction is simple and independent, optimizers can easily analyze data flow, eliminate dead code, or rearrange instructions for better performance.
Code Generation: Converting TAC to machine code is mechanical. Each TAC instruction maps cleanly to one or a few machine instructions.
Common TAC Operations
- Assignments:
x = y - Binary operations:
x = y + z - Unary operations:
x = -y - Jumps:
goto L1 - Conditional jumps:
if x < y goto L1 - Function calls:
call func, arg1, arg2
Key Takeaway: Three-Address Code linearizes complex expressions into simple, three-operand instructions, providing a uniform structure that simplifies both optimization passes and final code generation.