Sub topic 11
Local and Peephole Optimization
Assume you know basic three-address code, basic blocks, control-flow graphs, and set operations. This chapter shows how to optimize instructions inside one block and how dominators help identify loops.
Local optimization inside a basic block
A local optimization changes code within one basic block. A basic block has one entry and one exit, so its instructions execute sequentially unless an instruction leaves the block.
Consider this three-address code:
t1 = a + b
t2 = a + b
t3 = t2 * 4
x = t3The expression a + b is computed twice. If a and b do not change between the two computations, the second computation can reuse t1.
t1 = a + b
t2 = t1
t3 = t2 * 4
x = t3This is common subexpression elimination. The compiler must prove that the operands still have the same values. A function call, memory write, or assignment to a or b can make reuse unsafe.
Other common local transformations include:
- Constant folding: replace
3 * 4with12. - Constant propagation: replace a variable known to equal a constant with that constant.
- Copy propagation: after
x = y, replace later uses ofxwithywhen safe. - Dead code elimination: remove an assignment whose result is never used.
- Algebraic simplification: replace
x + 0withxorx * 1withx.
A peephole optimization examines a small window of adjacent target instructions. For example:
LOAD R1, x
STORE x, R1If the store writes back the value just loaded and no observable event occurs between them, the pair can be removed. Another example is replacing an instruction sequence with a shorter equivalent instruction:
ADD R1, 0can become no instruction if the processor flags do not matter.
Dominators and natural loops
In a control-flow graph, node D dominates node N if every path from the entry node to N passes through D. The entry node dominates every reachable node. Each node also dominates itself.
A back edge goes from node B to an earlier node H where H dominates B. The edge B → H identifies H as a loop header. The associated natural loop contains H, B, and nodes that can reach B without passing through H.
Dominators support loop-invariant code motion. If an expression inside a loop uses values that do not change in the loop, and moving it to a preheader is safe, the compiler can compute it once before the loop.
Exercise
Exercise
In a block containing t1 = x + y, x = 4, and t2 = x + y, can t2 reuse t1?
Show answer
No. The assignment x = 4 changes an operand, so the second expression may have a different value.