tact icon indicating copy to clipboard operation
tact copied to clipboard

Partial evaluation for const-eval optimization

Open anton-trunov opened this issue 8 months ago • 6 comments

As of now, the constant evaluator's usage is two-fold:

  • evaluate compile-time constants' initializers to their values and stop compilation if this cannot be done;
  • as an optimization technique: try to evaluate expressions to their values to use the values to produce target code.

The type of the constant evaluator is Expression -> Value.

As an optimization technique, the simple interpreter we use is quite limited, e.g. 2 * 3 * 7 * x where x is an arbitrary variable won't be simplified to 42 * x because evaluation gets stuck on variables. Instead we can try to produce a simplified AST, so we need a partial evaluator of type Expression -> Expression where the return expression should have the same semantics but is (non-strictly) smaller.

We can even apply some algebraic transformations, so that even x * 2 * 3 * 7 (which gets parsed as ((x * 2) * 3 * )7) gets transformed to x * 42 or 42 * x. However, this should be done with caution, because in the presence of overflows some arithmetic operations, for instance +, are not associative.

anton-trunov avatar Jun 18 '24 12:06 anton-trunov