Hi! I’m Reiden.

Writing a (Simple) Partial Evaluator

Why do partial evaluation?

After reading up about partial evaluation (see: Partial Evaluation and Automatic Program Generation (Jones, Gomard, Sestoft)), I wanted to implement a simple partial evaluator. Consider a program which has some constants and some user input, e.g. printing the cube of a number chosen by the user:

def power(a, b):
    '''a to the power of b.'''
    return 1 if b == 0 else a * power(a, b - 1)

a = int(input())
print(power(a, 3))

Here, a is a user input that we don't know until we run the program, but we know that b = 3. Partial evaluation is a program optimization technique that takes advantage of known information to transform a program into a more efficient one. Our partial evaluator is able to transform the program above into a equivalent one:

a = int(input())
print(a * (a * (a * 1)))

This new program is much simpler and has a much lower interpretation overhead:

It's not that our program has been magically improved, just that we have specialized the general recursive power into the specific cube function and inlined it. More generally, in partial evaluation we start off with a program p, and some static input s and some dynamic input d. We attempt to specialize p with respect to s to form a specialized program sp, which intuitively has the static information from s baked in, which also allows us to perform some optimizations. We can then apply d to sp to get the final result.

How do we do partial evaluation?

There probably exist a wide range of techniques to specialize different types of programs. We follow some of the steps outlined in Jones et al.'s book on partial evaluation and write a simple offline partial evaluator. From the book, we see that offline partial evaluation is a 2-stage process: We first need to perform Binding-Time-Analysis (BTA) to determine a division of the variables (that is, which variables are static and which variables are dynamic, and implictly so). Once we have that information, we can then run our second stage, which is the partial evaluation pass on the original program. Here we perform the computations which we can (static parts) and then simplify the parts we can, with the main goal of making the program more efficient to run.

On dclang, a simple language

Our partial evaluator will transform progams written in dclang, a simple language implemented in Python that I made up for the purpose of this exercise. dclang stands for dataclass language, and is named so because of how we implement it:

class Expr: pass

@dataclass
class IntExpr(Expr):
    val: int 

@dataclass
class BinOpExpr(Expr):
    lhs: Expr
    op: BinOp
    rhs: Expr

@dataclass
class IfExpr(Expr):
    cond: Expr
    then_branch: Expr
    else_branch: Expr

While dclang is not winning any awards for sophistication anytime soon, it exactly fits our needs of being simple to write and simple to manipulate. dclang is a bit like scheme, where the code revolves around composing expressions, with an imperative twist of having statements to make our lives a bit easier. We write our code directly through the language's AST nodes, which will make processing the code later a breeze.

dclang is small but (somewhat) powerful. For example, we can program fast exponentiation:

FAST_EXPONENTIATION_PROGRAM = Program(
    stmts=[
        FunctionDefStmt("mod", ["a", "b"], BinOpExpr(VarExpr("a"), BinOp.AddOp, BinOpExpr(IntExpr(-1), BinOp.MulOp, BinOpExpr(VarExpr("b"), BinOp.MulOp, BinOpExpr(VarExpr("a"), BinOp.FloorDivOp, VarExpr("b")))))),
        FunctionDefStmt("fast_power", ["a", "n"], IfExpr(BinOpExpr(VarExpr("n"), BinOp.EqOp, IntExpr(0)), IntExpr(1), IfExpr(BinOpExpr(CallExpr("mod", [VarExpr("n"), IntExpr(2)]), BinOp.EqOp, IntExpr(0)), CallExpr("fast_power", [BinOpExpr(VarExpr("a"), BinOp.MulOp, VarExpr("a")), BinOpExpr(VarExpr("n"), BinOp.FloorDivOp, IntExpr(2))]), BinOpExpr(VarExpr("a"), BinOp.MulOp, CallExpr("fast_power", [VarExpr("a"), BinOpExpr(VarExpr("n"), BinOp.AddOp, IntExpr(-1))]))))),
        PrintStmt(CallExpr("fast_power", [VarExpr("x"), IntExpr(13)])),
    ],
)

In it's raw form, dclang code is quite the eyesore, but since it's so easy to parse and manipulate it's quite easy to write a pretty printer in Python (I prefer the infix style, sorry to the scheme people) and suddenly things are much better.

def mod(a, b):
    a + (-1 * (b * (a // b)))

def fast_power(a, n):
    if n == 0 then 1
    else if mod(n, 2) == 0 then fast_power(a * a, n // 2)
    else a * fast_power(a, n + -1)

print fast_power(x, 13)

Introducing our ~30 LoC tree-walk interpreter:

def eval_expr(expr: Expr, env: dict) -> int:
    '''
    Evaluates a expression to a integer value.
    '''
    match expr:
        case IntExpr(val):
            return val

        case VarExpr(name):
            return env[name]

        case BinOpExpr(lhs, op, rhs):
            lhs_val = eval_expr(lhs, env)
            rhs_val = eval_expr(rhs, env)
            if op == BinOp.AddOp: return lhs_val + rhs_val
            if op == BinOp.MulOp: return lhs_val * rhs_val
            if op == BinOp.FloorDivOp: return lhs_val // rhs_val
            if op == BinOp.EqOp: return lhs_val == rhs_val
            raise ValueError("Unknown binary operator")

        case IfExpr(cond, then_branch, else_branch):
            cond_val = eval_expr(cond, env)
            if cond_val:
                return eval_expr(then_branch, env)
            else:
                return eval_expr(else_branch, env)

def eval_program(stmts: list[Stmt], input: dict) -> None:
    '''
    Evaluates a series of expressions.
    '''
    env = input.copy()
    for stmt in stmts:
        match stmt:
            case AssignStmt(var_name, expr):
                env[var_name] = eval_expr(expr, env)

            case PrintStmt(expr):
                print(eval_expr(expr, env))

That's about it for dclang, and now we can move on to the partial evaluation part.

Beginning on the partial evaluator (without functions (for now))

The goal of a partial evaluator is that given a program and some static input, we want to produce a residual program which will run with the dynamic input later on. Let us first assume that we know the program's division, which means to say which variables are static and which are dynamic. As we recall, dclang dosen't support scope or variable reuse here so this is easily represented by each variable name being mapped to a Static or Dynamic symbol. We also have the values of the static side of the input. Now we can begin working on generating the residual code. Let us first look at some pseudocode first that specializes a program that without function calls or definitions.

def mixed_evaluation(
        statements: list[Stmt],     # The program to specialize
        div: dict[str, S | D],      # Mapping of each variable to [Static | Dynamic]
        static: dict[str, int]      # The values of our static variables (constants)
    ) -> list[Stmt]:
    '''
    Produces a specialized residual program.
    '''
    residual = []
    for statement in statements:
        match statement:

            case AssignStmt(var_name, expr):
                if not is_static_expr(expr, div, static):
                    # Variable is dynamic, keep in residual code
                    residual.append(
                        AssignStmt(var_name, reduce_expr(expr, div, static))
                    )
                else:
                    # Variable is static, find its value now
                    static[var_name] = eval_expr(expr, static)

            case PrintStmt(expr):
                residual.append(
                    PrintStmt(reduce_expr(expr, div, static))
                )

    return residual

The partial evaluator is quite straightforward; Essentially we step through the original program and generate the residual equivalent statement by statement.

is_static_expr(expr, div, static) tells us if expr is static by recursively checking the parts needed to evaluate it. A binary operation needs both operands to be static. For a conditional, we first require a static condition, evaluate it, and check only the selected branch; the unselected branch can contain dynamic expressions. This is complemented by eval_expr(expr, store), borrowed from the interpreter, which evaluates an expression to a value using the known static bindings. We guard evaluation with is_static_expr().

reduce_expr(expr, div, static) is where most of the partial evaluation magic happens. Essentially reducing an expression means to evaluate what we can and to leave what we cannot. In practice we recursively go through each subexpression and try to evaluate it to a value if we can, otherwise we just leave it in the residual code.

def reduce_expr(expr, div, static):
    '''
    Evaluate what we can with static, and leave the rest to runtime
    '''
    if is_static_expr(expr, div, static):
        return IntExpr(eval_expr(expr, static))

    match expr:
        case IntExpr():
            return expr

        case VarExpr(var_name):
            if div[var_name] == Abst.Static:
                return IntExpr(static[var_name])
            return expr

        case BinOpExpr(lhs, op, rhs):
            lhs_r = reduce_expr(lhs, div, static)
            rhs_r = reduce_expr(rhs, div, static)
            return BinOpExpr(lhs_r, op, rhs_r)

        case IfExpr(cond, then_branch, else_branch):
            if not is_static_expr(cond, div, static):
                return IfExpr(
                    reduce_expr(cond, div, static),
                    reduce_expr(then_branch, div, static),
                    reduce_expr(else_branch, div, static),
                )
            cond = eval_expr(cond, static)
            if cond:
                return reduce_expr(then_branch, div, static)
            else:
                return reduce_expr(else_branch, div, static)

There are a number of code optimizations seen here. case VarExpr() allows us to do constant folding, where previously we had to perform variable lookup we can replace it with its value directly when it is static and known. case IfExpr() allows us to remove the branch entirely if we know which direction we are taking in advance, that is to say cond is static and known. The effectiveness of these optimizations really show when they compound on top of each other. Let us see what we can do so far with the optimizations we have seen thus far. Consider the program fragment where we have static input a = 2, and want to print e

# static a = 2
# dynamic d = input()
b = a * 2
c = b + 1
e = d * c
print e

In the first statement, we can reduce VarExpr('a') to 2 directly as its value is known. Then a * 2 is evaluated to 4, and b = 4 is stored directly. Now the first line does not appear in the residual code at all. We can apply something similar to the next line to store c = 5. Now for the last line we can't evaluate e because d is dynamic, so all we can do is to perform substition for c. We end up with the residual program:

e = d * 5
print e

Effectively, we have removed the interpretation overhead of all those lookups for variables a, b, c and now at runtime all we need to do is to perform some arithmetic and print.

So far we have a simple partial evaluator that works for dclang without functions. However, to get here we have glossed over one important portion: how do we know which variables are static and which are dynamic? Let us look at that now.

Binding-Time Analysis

Binding time analysis is one of our preprocessing steps before we carry out partial evaluation. We know the static values of the input, but for all of the variables the user added in the program code usually we don't know if they are static or dynamic. This is where BTA comes in, where given a program and the static input, we want to find division of the variables in the abstract domain.

We classify expressions by recursively checking their dependencies. For binary operations, both operands must be static. For a conditional with a known condition, we only need to analyze the selected branch. This is quite similar to the partial evaluator's own is_static_expr(expr, ...) except here we must both check if the expr is static and note down the variables which are not. We call this resolve_expr() and it goes something like this.

def resolve_expr(expr, div, sstore) -> Abst:
    """
    Return if an expression is static or dynamic
    """
    match expr:
        case IntExpr():
            return Abst.Static

        case VarExpr(var_name):
            if var_name not in div:
                div[var_name] = Abst.Dynamic
            return div[var_name]

        case BinOpExpr(lhs, op, rhs):
            lhs_sym = resolve_expr(lhs, div, sstore)
            rhs_sym = resolve_expr(rhs, div, sstore)
            return Abst.Static if lhs_sym == rhs_sym == Abst.Static else Abst.Dynamic

        case IfExpr(cond, then_branch, else_branch):
            c_sym = resolve_expr(cond, div, sstore)
            if c_sym == Abst.Static:
                cond_val = eval_expr(cond, sstore)
                return resolve_expr(
                    then_branch if cond_val else else_branch, div, sstore
                )
            t_sym = resolve_expr(then_branch, div, sstore)
            e_sym = resolve_expr(else_branch, div, sstore)
            return Abst.Static if c_sym == t_sym == e_sym == Abst.Static else Abst.Dynamic

This routine is called by a harness of its own similar to the mixed_evaluation() one seen above.

def preprocess(stmts: list[Stmt], static: dict) -> dict[str, S | D]:
    """
    Something is then static if everything that it depends on is static.
    else it is dynamic.
    Return the division of the program
    """
    div = {var: Abst.Static for var in static}
    for stmt in stmts:
        match stmt:
            case AssignStmt(var_name, expr):
                div[var_name] = resolve_expr(expr, div, static)

            case PrintStmt(expr):
                resolve_expr(expr, div, static)

    return Program(target), div

So there we have it. We first run our program with static into preprocess to perform BTA. With our division, we then carry out mixed evaluation to get our residual program.

Functions!

Really, most of the complexities come when we add functions into the mix. We take this one step at a time, where we first add functions into dclang. We have a simple function definition, which basically has a function name, a list of parameters, and a return expression. We also add a new expression for the function call.

@dataclass
class FunctionDefStmt(Stmt):
    name: str
    params: list[str]
    body: Expr

@dataclass
class CallExpr(Expr):
    func_name: str
    args: list[Expr]

Interpreting this is not too complex either. Function definition in particular is very straightforward, we just store the expression like any other variable.

    case FunctionDefStmt(name, params, body):
        env[name] = (params, body)

When we do a function call, we simply substitute in the arguments into the parameters, and then use this expanded environment to evaluate the expression.

def eval_expr(expr: Expr, env: dict) -> int:

    ...

    case CallExpr(func_name, args):
        params, body = env[func_name]

        # Parameter binding
        new_env = {}
        for name, expr in zip(params, args):
            new_env[name] = eval_expr(expr, env)
        call_env = env.copy()
        call_env.update(new_env)

        return eval_expr(body, call_env)

Now, on to the partial evaluation of functions. Let us consider the function that we encountered at the start of the program.

def power(a, b):
    if b == 0 then 1
    else a * power(a, b - 1)

Note that our program can use power with all kinds of variables, both static and dynamic. Some of these expressions are more reducible than others:

program:    print power(2, 5)
residual:   print 32
# Everything is static, we can precomute at specialization time, good!

program:    print power(2, n)
residual:   print power(2, n)
# Can't precompute anything, bad :(

program:    print power(x, 5)
residual:   print (x * (x * (x * (x * (x * 1)))))
# We can unroll into a specialized program, good! 

program:    print power(x, n)
residual:   print power(x, n)
# Can't precompute anything, bad :(

Observe that for different combinations of parameters being static and dynamic, we can get wildly different results. The key issue here is that a function may be called with different divisions of its parameters, even in the same program. If we extended our conservative BTA to analyzing the function, our function would tend towards having dynamic parameters much of the time, and we would lose out many specialization opportunities here.

One solution is a technique called polyvariant specialization. Essentially, different invocations of the same function can have different binding-times of the parameters, making the function behave differently, so we can just invent sufficiently many versions of each function during preprocess.

def power__SS(a__S, b__S):
        if (b__S == 0) then 1 else (a__S * power__SS(a__S, (b__S + -1)))
def power__SD(a__S, b__D):
        if (b__D == 0) then 1 else (a__S * power__SD(a__S, (b__D + -1)))
def power__DS(a__D, b__S):
        if (b__S == 0) then 1 else (a__D * power__DS(a__D, (b__S + -1)))
def power__DD(a__D, b__D):
        if (b__D == 0) then 1 else (a__D * power__DD(a__D, (b__D + -1)))

Here, a__S is always static and a__D is always dynamic, so within each function we have monovariant binding times! During preprocess we can also accurately analyze the call site with resolve_expr(), specifically the call argument expressions to see if they are static or dynamic, and then we can replace the call with the correct binding function.

The function variants give each parameter a fixed binding time. During specialization, we bind static parameters to values and dynamic parameters to residual argument expressions, then reduce the function body in that environment. This is where the earlier power(x, 3) example starts to work nicely: We realize that the correct function to use here is power__DS(x, 3), and x remains dynamic, but 3 is static, so the recursive calls can be unrolled until the static exponent reaches zero. To limit recursive expansion, the implementation tries unfolding up to a fixed depth of 10; if that limit is reached, it abandons the expansion and leaves the call residual to be performed at runtime.

Wrapping up

This implementation has some main drawbacks: dclang has no proper scope, the BTA is simple, and the function specialization strategy is only good because the language is small enough that we can get away with it. The implementation also does not full cover all runtime exceptions, which generally require additional machinery. Richer data types and side effects introduce further challenges.

Still, I'd say this small version was able to demonstrate the main idea. We first use binding-time analysis to separate what we know at specialization time. Then mixed evaluation walks the program, evaluates the static parts, simplifies whatever it can, and emits the residual dynamic program. Adding functions makes the implementation a bit more tricky, but the same principle still holds: specialize around the information that is available, and avoid doing the same work again at runtime.

Appendix

Some notes about dclang: