Constant Folding (constFold.ml)

Once functions are inlined, many operations have arguments whose values are already known, as in x + y of let x = 3 in let y = 7 in x + y. Constant folding carries out such computations at compile-time and replaces them with constants like "10". MinCaml implements it in function ConstFold.g.

ConstFold.g takes expression e with a mapping env from variables to their values, and returns the expression after constant folding. For example, given integer addition x + y, it examines whether the values of x and y are integer constants. If so, it calculates and returns the result right away. Conversely, given variable definition let x = e in ..., it adds to env the mapping from x to e. This process is similar not only for integers but also for floating-point numbers and tuples.

Next