CAPSTONE: A TINY OPTIMIZING PASS
Everything in this path, in one pass over three-address code
x = 5; y = x * 2; p = &x; *p = 7; z = x + y; print z. A constant propagation pass replaces each variable with its known value. It tracks constants by name only and ignores stores through pointers. What does the optimised program print?
An optimiser rewrites three-address code into cheaper code with the same behaviour. Constant propagation and folding walk forward, remember which variables hold known constants, and compute x * 2 at compile time. Dead-code elimination walks backward with a live set and deletes definitions nobody reads.
Both rules need a safety condition. A store through a pointer, or a call, can change any variable whose address was taken, so the pass forgets those constants. A call can print, so it is never dead just because its result is unused.
// fold: remember constants by NAME only
x = 5; p = &x; *p = 7;
z = x + y // 'x is 5' => z = 15 (x is 7)
// dce: drop any def whose result is unused
t = call tick() // t unused => deleted, and so is the print// fold: a store or a call may write any address-taken variable
if (op === 'store' || op === 'call') for (v of addrTaken) forget(v);
// dce: only PURE definitions may go
pure = op in { const, bin, addr };
if (dst && pure && !live.has(dst)) remove(); The invariant strip compares outputs and watches what DCE removes. UNSAFE: FOLD THROUGH *p prints 15 instead of 17. UNSAFE: DROP UNUSED CALLS loses the tick line. SAFE PASS prints the same three lines with 7 of 9 instructions and one fewer value live at the peak.
Turn on one unsafe rule at a point in the pass where it changes what the program prints. Then try it after the step it would affect.
GOAL: the optimised program prints something different
This pass folds and removes dead code, and breaks two programs. Make it safe: a store or a call may change any variable whose address was taken, and only const, bin and addr instructions may be deleted. The grader runs original and optimised on six programs, and still expects the pure one to shrink.
LLVM's SCCP, InstCombine and DCE, GCC's tree-ssa passes, V8's TurboFan, and the “works in debug, wrong in release” bug report. Alias analysis and the C strict-aliasing rule decide how much a real optimiser may assume about pointers.
“Implement constant folding and dead-code elimination over this IR” or “Why might this optimisation be unsafe?” Show the forward constant map and the backward live set, then name aliasing through pointers and side-effecting calls as the two places the pass must give up.