Code Generation for Expressions
What you'll learn: How compilers translate arithmetic and logical expressions into sequences of machine instructions while respecting evaluation order and managing temporary values.
When a compiler encounters an expression like (a + b) * (c - d), it must generate actual machine instructions that compute the result. This involves more than simple translation—it requires carefully orchestrating the order of operations and managing where intermediate results are stored.
The Core Process
Expression code generation follows these key steps:
- Traverse the expression tree (usually the AST) to determine evaluation order
- Generate instructions for each operation in sequence
- Allocate temporary storage (registers or memory) for intermediate results
- Produce the final result in a designated location
Example Walkthrough
Consider x = (a + b) * c generating three-address code:
t1 = a + b // Compute addition first, store in temporary t1
t2 = t1 * c // Multiply result by c, store in temporary t2
x = t2 // Assign final result to x
The compiler must:
- Evaluate
a + bbefore the multiplication (respecting precedence) - Store the intermediate sum somewhere (
t1) so it's available for the next operation - Chain operations using temporaries until reaching the final destination
Why Temporaries Matter
Like a chef using bowls for intermediate ingredients, the compiler needs places to hold partial results. Without t1, we couldn't bridge the gap between computing the sum and using it in multiplication. These temporaries later get mapped to actual registers during register allocation.
The generator respects evaluation order (parentheses, operator precedence, left-to-right rules) by walking the AST in post-order: children before parents, ensuring operands are computed before operators use them.
Key Takeaway: Code generation for expressions produces instruction sequences that compute values in the correct order, using temporary storage to preserve intermediate results until they're needed by subsequent operations.