Constant Propagation: Computing Before the Program Runs

If a value can be proven to always be the same constant, the compiler computes it at compile time. What happens when branches get involved?

Optimization2 min read
Optimization

If the compiler can prove that a variable always holds the same constant, it replaces the variable with that value. This is called constant propagation. Computing an operation made only of constants at compile time is called constant folding.

area.rsRust
fn area() -> i32 { let w = 4; let h = w * 2; w * h}

w is 4, so h is 8 and the result is 32. After folding, the whole function body is a single constant:

IRIR
define i32 @area() { ret i32 32}

When Paths Join

A variable can take different values along different paths. Where the paths join, the compiler combines what it knows: if both paths bring the same constant, the value is still constant; if they bring different constants, it no longer is.

Conditional Constant Propagation

Wegman and Zadeck's sparse conditional constant propagation (SCCP) also tracks which blocks can execute at all. It starts by assuming that values are constant and blocks are unreachable until proven otherwise. If a branch condition turns out to be constant, only one side is marked reachable, and values from the dead side do not spoil the result.

flag.rsRust
let debug = false;let mut level = 1;if debug { level = 3; }// level is still 1 here

A simpler analysis would merge 1 and 3 at the end and give up. SCCP sees that the if block never runs, so level stays the constant 1 and the whole if can be removed.

The algorithm is fast because it works on SSA form, where every name has a single definition. LLVM provides it as the sccp pass. Its documentation notes that the pass tends to leave dead definitions behind, so a dead code elimination pass usually runs afterwards.

Constant folding must follow the language rules: integer overflow, floating-point rounding and division by zero must give the same result at compile time as at run time. Otherwise the program's behaviour changes.

Sources

  1. M. N. Wegman, F. K. Zadeck. “Constant propagation with conditional branches.” ACM TOPLAS 13(2), 1991, 181–210. doi:10.1145/103135.103136
  2. LLVM’s Analysis and Transform Passes, “sccp: Sparse Conditional Constant Propagation”. llvm.org/docs/Passes
  3. K. D. Cooper, L. Torczon. Engineering a Compiler, 2nd ed., Morgan Kaufmann, 2011, ch. 9.
  4. A. V. Aho, M. S. Lam, R. Sethi, J. D. Ullman. Compilers: Principles, Techniques, and Tools, 2nd ed., Addison-Wesley, 2006, ch. 9.