CS153: Compilers Lecture 19: Optimization: Stephen Chong
CS153: Compilers Lecture 19: Optimization: Stephen Chong
Stephen Chong
https://www.seas.harvard.edu/courses/cs153
Contains content from lecture notes by Steve Zdancewic and Greg Morrisett
Announcements
➔ int z = a[10];
•Example:
x = y; x = y;
if (x > 1) { if (y > 1) {
x = x * f(x – 1); ➔ x = y * f(y – 1);
} }
•Can make the first assignment to x dead code (that can be eliminated).
Stephen Chong, Harvard University 16
Dead Code Elimination
•If a side-effect free statement can never be observed, it is safe to
eliminate the statement.
x = y * y // x is dead!
... // x never used ...
x = z * z ➔ x = z * z
function f(x,y) =
let function f’(x,y) = if x < 1 then y
else x * f’(x-1,y)
in f’(x,y)
Stephen Chong, Harvard University 29
Rewriting Recursive Functions for
Inlining
function f(x,y) =
let function f’(x,y) = if x < 1 then y
else x * f’(x-1,y)
in f’(x,y)
Without rewriting f,
6+f(4,5) becomes: 6+f(4,5) becomes:
6 + 6 +
(let function f’(x)= (if 4 < 1 then 5
if x < 1 then 5 else 4 *
else x * f’(x-1) f(3,5))
in f’(4))
Stephen Chong, Harvard University 31
Rewriting Recursive Functions for
Inlining
•Now inlining recursive function is more useful!
•Can specialize the recursive function!
• Additional optimizations for the specific arguments can be
enabled (e.g., copy propagation, dead code elimination).
Equivalent program in
an imperative language
IR •Constant folding
•Constant propagation
•Value numbering
Canonical IR •Dead code elimination
Mid level
•Register allocation
•Loop unrolling
Assembly •Cache optimization
Stephen Chong, Harvard University 37
Writing Fast Programs In Practice