Sub topic 14
Local and peephole optimization
This chapter assumes you can split three-address code into basic blocks and read a simple DAG. Both were covered in earlier chapters. It also assumes you know what a live variable is, at the level of "its value may be read later".
Two scopes of optimization
A local optimization looks at one basic block. A block has one entry and one exit and no internal jumps, so every instruction in it runs in order, exactly once. That lets the compiler reason without a control flow graph or any data flow equations.
A peephole optimization looks at a small sliding window of instructions, often two to five. The window may be over target code or intermediate code. It may cross block boundaries, but each rewrite must still be safe.
Both are cheap, and both are weaker than the global analyses later in this tutorial.
Local transformations inside a block
| Transformation | Before | After |
|---|---|---|
| Common subexpression elimination | `x = a + b` ... `y = a + b` | `y = x` |
| Copy propagation | `t = a; u = t + 1` | `u = a + 1` |
| Constant folding | `t = 3 * 4` | `t = 12` |
| Dead code elimination | `t = a + b` with `t` never used | removed |
| Algebraic simplification | `x = y + 0`, `x = y * 1` | `x = y` |
| Strength reduction | `x = y * 2` | `x = y + y` or `x = y << 1` |
Each rewrite needs a safety condition. A repeated expression is a common subexpression only if neither operand is reassigned between the two occurrences. A statement is dead only if its result is not used later. Inside one block you can see every later use. After the block ends, you must know which variables are live on exit. Without that analysis, assume every non-temporary variable is live.
Building the DAG for a block
The DAG method finds local common subexpressions systematically. For each statement x = y op z:
- Find the DAG nodes for the current values of
yandz. Create a leaf for any operand with no node yet. - Look for an existing node with operator
opand exactly those children. If it exists, reuse it. Otherwise create it. - Attach
xto that node's label list, and removexfrom any other node's label list.
Take this block:
1: a = b + c
2: b = a - d
3: c = b + c
4: d = a - dStatement 3 uses the new b from statement 2, not the original b. So b + c there is a different node from statement 1. Statement 4 matches statement 2 exactly, because a and d have not changed in between. Statement 4 therefore adds the label d to the existing minus node.
Reading the DAG back out in order gives the optimized block:
a = b + c
b = a - d
c = b + c
d = bStatement 4 became a copy. Note that the two b + c expressions were not merged. Statement 2 redefined b between them, so merging them would be wrong.
The same idea as value numbering
Compilers often implement the DAG as value numbering. Each distinct value gets a number, and a table maps (op, vn1, vn2) to the value number of the result. This program runs on the block above.
def value_number(block):
counter = 0
vn_of, home, table = {}, {}, {}
def number(x):
nonlocal counter
if x not in vn_of:
vn_of[x] = counter
home[counter] = x
counter += 1
return vn_of[x]
out = []
for dest, op, x, y in block:
key = (op, number(x), number(y))
if key in table and table[key] in home:
vn = table[key]
out.append((dest, "copy", home[vn], None))
else:
vn = counter
counter += 1
table[key] = vn
out.append((dest, op, x, y))
old = vn_of.get(dest)
if old is not None and home.get(old) == dest:
del home[old]
vn_of[dest] = vn
home.setdefault(vn, dest)
return out
block = [("a", "+", "b", "c"), ("b", "-", "a", "d"),
("c", "+", "b", "c"), ("d", "-", "a", "d")]
for dest, op, x, y in value_number(block):
print(f"{dest} = {x}" if op == "copy" else f"{dest} = {x} {op} {y}")The output is the four lines shown earlier. The home map records which variable currently holds each value. When a variable is overwritten, it stops being the home of its old value. That is why the two b + c expressions stay separate.
Peephole optimization
A peephole optimizer slides a small window over the code and replaces known patterns with cheaper ones. Common patterns:
- Redundant loads and stores. In
ST R0, afollowed byLD R0, a, the load is redundant. It is safe only if the load carries no label, so no jump can reach it separately. - Unreachable code. An instruction after an unconditional jump, with no label, can be deleted.
- Flow-of-control optimization. A jump to a jump,
goto L1whereL1: goto L2, becomesgoto L2. IfL1is then unused, its code can be deleted. - Algebraic simplification and strength reduction, as in the table above.
- Machine idioms. Use
INCforADD #1, or an addressing mode that folds an add into a load.
Rewrites feed each other. Replacing if a < b goto L1 followed by goto L2 and L1: with if a >= b goto L2 can leave code unreachable. So the optimizer repeats passes until nothing changes.
Common errors
- Merging expressions across a redefinition of an operand, as with
b + cabove. - Removing a "dead" assignment to a variable that is live at the block exit.
- Counting temporaries as live at exit. Compiler temporaries usually are not.
- Applying a peephole rewrite across a labeled instruction, where a jump can enter the middle of the pattern.
Exercise
Optimize this block using the DAG method. Assume only x and w are live on exit. t1 = a * 4, t2 = a * 4, t3 = t1 + t2, x = t3, u = t3 - t3, w = a.
Show answer
Both a * 4 statements share one node, so t2 becomes t1. Then t3 = t1 + t1 and x = t3. The value u is dead, since it is not live on exit. The result is t1 = a * 4, t3 = t1 + t1, x = t3, w = a. Copy propagation may shorten this further to x = t1 + t1.
Exercise
Why can a peephole optimizer not delete LD R0, a after ST R0, a if the load carries a label?
Show answer
A jump from elsewhere may land on the labeled load. On that path R0 may not hold the value of a, so the load is needed.