Sub topic 21
Optimizations that use data flow results
This chapter assumes you can build a control flow graph (CFG) from three-address code. It also assumes you know the gen/kill setup for reaching definitions, live variables and available expressions, and the iterative solver. Here we use their results. Each optimization below is only safe when a specific analysis proves a specific fact.
Which analysis justifies which optimization
| Optimization | Analysis it needs | Fact that makes it safe |
|---|---|---|
| Common subexpression elimination (global) | Available expressions | The expression `x op y` is available at the point, so no operand changed on any path |
| Dead code elimination | Live variables | The assigned variable is not live after the statement, and the statement has no side effects |
| Constant propagation and folding | Reaching definitions | Every definition of the variable that reaches the use assigns the same constant |
| Loop-invariant code motion | Reaching definitions and dominators | The operands are defined outside the loop, or by an already-moved invariant, and the move is legal |
| Copy propagation | Reaching definitions (copy statements) | Only one copy `x = y` reaches the use, and `y` is not redefined on any path from it |
Common subexpression elimination
Local CSE works inside one basic block. Global CSE uses the available expressions sets. An expression x + y is available at a point if every path from the entry to that point evaluates it, and neither x nor y is assigned after the last evaluation on any path.
If x + y is in IN[B] and block B computes x + y before changing x or y, the compiler can reuse the earlier value. It does this by saving the earlier result in a new temporary t at each earlier evaluation, then replacing the later computation with t.
Available expressions is a must-analysis, so it uses intersection. If one path does not compute the expression, it is not available, and CSE is not allowed.
Dead code elimination
A statement x = e is dead if x is not live immediately after it. Use the live variable result: walk each block backward from OUT[B]. Remove an assignment whose target is not in the current live set. Otherwise, update the set as live = (live - def) U use.
Removal can expose more dead code. If t1 = a + b was used only by a removed statement, t1 is now dead too. Repeating the pass handles this, or one backward pass can handle it if you update the live set only for statements you keep.
Check for side effects before removing. A statement such as x = f(y) may do output or change memory. Only remove it if the call is known to be pure.
Constant propagation
Suppose the use u = x + 1 is reached by definitions of x. If all of them are x = 4, the compiler replaces x with 4 and folds 4 + 1 into 5. If one definition is x = 4 and another is x = 5, nothing is replaced.
A reaching definitions set tells you which definitions arrive. A single reaching definition x = 4 is enough. Several reaching definitions are enough only if they all give the same constant. Many compilers instead use a dedicated constant propagation framework, where the values form a small lattice (unknown, a constant, or not-a-constant). The reaching definitions version is simpler and is what GATE questions usually expect.
# Folding after constants are propagated: a tiny block-local version.
def propagate(block):
env = {}
out = []
for dest, op, a, b in block:
a = env.get(a, a)
b = env.get(b, b)
if op == "=":
if isinstance(a, int):
env[dest] = a
else:
env.pop(dest, None)
out.append((dest, "=", a, None))
elif isinstance(a, int) and isinstance(b, int):
val = a + b if op == "+" else a * b
env[dest] = val
out.append((dest, "=", val, None))
else:
env.pop(dest, None)
out.append((dest, op, a, b))
return out
block = [("x", "=", 4, None), ("y", "+", "x", 1), ("z", "*", "y", "w")]
for ins in propagate(block):
print(ins)The output is ('x', '=', 4, None), ('y', '=', 5, None) and ('z', '*', 5, 'w'). This code works within one block only. It does not handle joins, which is where reaching definitions is needed.
Loop-invariant code motion
A statement in a loop is invariant if each operand is a constant, is defined only outside the loop, or has exactly one reaching definition that is itself invariant. Dominators and natural loops supply the loop body and the preheader, a block placed just before the loop header.
Moving t = a * b to the preheader is safe when:
- The statement's block dominates all loop exits, so it runs on every iteration that leaves the loop. This keeps the move from introducing a computation the original program might skip.
tis assigned only once in the loop.tis not live on entry to the loop header from outside, so no earlier value is overwritten.
Condition 1 can be relaxed if the statement cannot raise an exception and t is dead after the loop.
Edge cases
- Redefinition between evaluation and use. If
achanges aftert = a + bbut before the latera + b, the expression is killed and CSE is unsafe. - Aliasing and pointers. A store through a pointer may kill any expression or definition it might alias. Without alias information, analyses must be conservative.
- Procedure calls. An unknown call can modify globals and anything reachable by reference, so it kills those facts.
- May versus must. Use must-information (available expressions) when the optimization needs a fact on every path. Use may-information (liveness, reaching definitions) to prove something cannot happen, such as "no use remains".
Worked example
Consider this code:
B1: a = 2
b = a + 3
c = b * 2
if c > 0 goto B2
B2: d = a + 3
e = d
return bConstant propagation gives a = 2 at the use in b = a + 3, so b = 5. Then c = 10. In B2, d = 5. The copy e = d becomes e = 5. Liveness shows that c is live only until the branch (it is used there), d and e are not live after B2's assignments, and a is not used after propagation. After the branch condition is also folded, dead code elimination removes d, e and a, leaving b = 5 and return b.
Order matters: propagation and folding create dead code, and removing code can reveal further constants. Compilers run these passes repeatedly until nothing changes.
Exercise
In a CFG, block B3 computes t = x + y. Its predecessors are B1, which computes x + y and does not change x or y, and B2, which does not compute x + y. Can B3 reuse the value from B1? Explain using available expressions.
Show answer
No. x + y is in OUT[B1] but not in OUT[B2]. Because available expressions intersects over predecessors, x + y is not in IN[B3], so it is not available on every path and the computation must stay.
Exercise
In a block, x = a + b is followed by y = x * 2, and the block's OUT set does not contain x or y. No later statement uses either variable, and a + b has no side effects. Which statements are dead, and in what order does a backward pass find them?
Show answer
Both. Working backward from the empty live set, y = x * 2 assigns y, which is not live, so it is removed and x is not added to the live set. Then x = a + b assigns x, which is not live, so it is removed too.