Techniqueadvanced
Partial evaluation
Also called program specialization, mixed computation.
Specializes a program to the part of its input known in advance, giving a residual program that takes only the rest of the input.
Partial evaluation takes a program and the values of some of its inputs, the static inputs, and makes a new program , the residual program, that takes only the other inputs, the dynamic inputs , and gives the same result as on . The program that does this is a specializer, often called . In the notation for the function that a program computes, it must satisfy the mix equation . The residual program does every computation that depends only on ahead of time and keeps only the work that needs . Ershov called this mixed computation, Futamura used it in 1971 to turn interpreters into compilers, and Jones, Sestoft and Søndergaard built the first self-applicable specializer in 1985. The common mistake is to think a specializer always stops. It does not: unfolding a recursion whose stop test is dynamic, or making one version for each of infinitely many static values, runs forever.
In plain words
Some inputs of a program are known long before the others. A program that draws a picture gets its settings once and its pixels millions of times. An interpreter gets the user's program once and its data many times.
A partial evaluator reads the program and the known inputs. It does all the work that needs only the known inputs, and writes down the rest as a new, smaller program. The new program asks only for the unknown inputs and gives the same answers as the old program.
If the known input is an exponent of 3, a general power function becomes "x times x times x". If the known input is a program for an interpreter, the interpreter becomes a translation of that program. The new program skips the tests and lookups that were decided ahead of time.
When it applies
- The input splits into a part that is fixed for many runs and a part that changes between runs, and the program does real work that depends on the fixed part alone: decoding a format, walking a configuration, interpreting a program, testing a pattern.
- The program can be read as data, in a language for which a specializer exists. The cleanest case is a first-order or higher-order functional language without side effects, which this page uses. Specializers also exist for C, Scheme and Prolog, and run-time specializers such as Truffle work inside language virtual machines.
- The residual program runs often enough to pay for the time of specialization. A program that runs once on its static input gains nothing.
The template
Language. A program is a list of first-order recursion equations . An expression is a constant, a variable, a primitive , a conditional , a call or . Evaluation is call by value. The outcome of a run is a value, an error (such as division by 0), or no end. The higher-order case, with fun x -> e, needs a binding-time analysis to be done well and is treated there.
Specialization values. During specialization each expression gets a specialization value: either , a value known now, or , a piece of residual code that computes the value later. A static environment maps each variable to a specialization value.
Step 1: the program points. A residual function is named by a pair : a function of the source and the values of its static parameters. The residual program has one function for each pair that is reached, and its parameters are the dynamic parameters of . This is polyvariant specialization: one source function can have many residual versions.
Step 2: the specializer of expressions. , where says whether is under a dynamic conditional:
- A constant gives . A variable gives .
- : if both operands give and , compute now. Otherwise give , where a static operand becomes the constant in the code.
- : if gives , specialize only the branch that selects. Otherwise specialize both branches with = dynamic and give .
- outside a dynamic conditional: unfold it. Specialize the body of with the parameters bound to the specialization values of the arguments. A dynamic argument that is not a variable is first bound by a residual to a fresh variable (let insertion), so it is computed once and in the right order.
- under a dynamic conditional: residualize it. Let be the values of the static arguments. Give with the dynamic arguments, and add to the pending list if it is new.
Step 3: the main loop. Start with the pending list for the entry function and the static input. Take a pending pair that has no residual function yet, and define , where or is of the body of with the static parameters bound to and the dynamic ones to of their own names. Repeat until no pair is pending. The memo table of pairs is what turns a loop of the source into a loop of the residual program.
The rule "unfold outside dynamic conditionals, memoize under them" is the classic one. A recursion that is controlled by static data, like the exponent of a power function, unfolds completely. A call under a dynamic test may be the back edge of a loop that runs a dynamic number of times, so it becomes a residual call.
Legality. The specializer may stop with a residual program, stop with an error (a static primitive failed), or not stop. Correctness theorem: if it stops with a residual program, then for every dynamic input , the residual program on and on have the same outcome: the same value, or both no value.
Proof. (a) Each case of Step 2 replaces an expression by one that is equal in the call-by-value semantics, when each residual call is read as the call . Computing a static primitive is the rule . A static test selects its branch by the rule for on a value. Unfolding replaces a call by the body with the parameters replaced by the arguments. This is valid in call by value when the arguments are values; static values and variables are values, and let insertion makes every other argument a variable bound by a that is evaluated first, as the call would do. So no dynamic computation is lost, copied or moved past another one. (b) Let be the function . By (a), the family of all satisfies every equation of the residual program. The meaning of a recursive program is the least solution of its equations, so whenever the residual function returns a value on , is that value. (c) Conversely, suppose returns after calls. Run the body of on . By (a), it does the dynamic steps of that run of in the same order, with the unfolded calls done inline. Each residual call that it meets is a call that the run of makes, with fewer than calls. By induction on , that residual call returns the same value. So returns . Parts (b) and (c) give the theorem.
Profit. The cost model is the number of operations that a run executes: calls, primitives and conditionals. A from let insertion costs nothing, since it only names a value that a call would pass. Every operation on static values alone is done once, at specialization time, and leaves nothing in the residual program. Every dynamic operation of the source stays, at most once per execution of the source operation, because of let insertion. So the residual program never does more operations than the source on the same input, and it does fewer by the number of static operations of the run. It does not pay when the residual program is much larger than the source (a static loop of a million rounds unfolds into a million operations of code), or when it runs only a few times.
Classic examples
Power. The source is power(n, x) = if n == 0 then 1 else x * power(n - 1, x), with static and dynamic. The test n == 0 is static, so every call unfolds, and the residual program is
power_3(x) = x * (x * (x * 1))
On , the source makes 4 calls and runs 10 primitive operations and 4 conditionals. The residual program runs 3 multiplications. A constant folder that knows would remove the last one; partial evaluation alone does not use algebra.
An interpreter. The source is an interpreter for a tiny machine with two registers and . A machine program is a list of instructions: jz t jumps to if , dec sets , inc sets , jmp t jumps, and halt stops with the value of .
run(prog, pc, a, b) =
if op(prog, pc) == "halt" then b
else if op(prog, pc) == "jz" then
(if a == 0 then run(prog, arg(prog, pc), a, b) else run(prog, pc + 1, a, b))
else if op(prog, pc) == "dec" then run(prog, pc + 1, a - 1, b)
else if op(prog, pc) == "inc" then run(prog, pc + 1, a, b + 1)
else run(prog, arg(prog, pc), a, b)
The machine program is 0: jz 5, 1: dec, 2: inc, 3: inc, 4: jmp 0, 5: halt, which computes . Specialize run with prog and pc = 0 static and , dynamic. The decoding tests op(prog, pc) == ... are all static. The only dynamic test is a == 0, so the calls in its branches are residualized, and the pending pairs are , then and . The residual program, as computed by a short script with the specializer of the template, is
run_0(a, b) = if a == 0 then run_5(a, b) else run_1(a, b)
run_5(a, b) = b
run_1(a, b) = let a0 = a - 1 in let b1 = b + 1 in let b2 = b1 + 1 in
if a0 == 0 then run_5(a0, b2) else run_1(a0, b2)
Here run_1 is the loop body of the machine program, compiled. The instruction decoding and the program counter are gone; only the work on the registers is left. The script counts the calls, primitives and conditionals of both programs on . The interpreter executes of them, and the residual program , plus lets that only name values. So it is faster by a factor that tends to 11. Both give on every input tried. This is the first of the Futamura projections: specializing an interpreter to a program compiles the program.
String matching. Consel and Danvy (1989) specialize a naive matcher, which compares a pattern with a text and restarts one place to the right after a mismatch, to a fixed pattern. After a rewriting of the matcher that keeps the matched prefix of the text static, the residual program never reads a text character twice. It is a matcher of the quality of Knuth-Morris-Pratt. Without the rewriting, the residual program is the naive matcher unrolled, which is the usual outcome: what the specializer can find depends on how the source keeps its static data apart.
Run-time specialization of interpreters. Truffle and Graal partially evaluate an AST interpreter for a hot user function at run time, with the AST as static input, and compile the residual program (Würthinger and others, 2017). The interpreter nodes rewrite themselves first, as in a self-optimizing AST interpreter, so the AST holds the speculations, and deoptimization goes back to the interpreter when one fails. This is just-in-time compilation by partial evaluation, the method-based counterpart of meta-tracing and tracing JIT compilation.
Variations
- Online and offline. The template is online: it looks at the specialization values as it goes. An offline specializer first runs a binding-time analysis that marks every expression static or dynamic from the split of the inputs alone, and then follows the marks. Offline specializers are simpler and are the ones that can be applied to themselves well; online ones can find more static values.
- Monovariant and polyvariant. A monovariant specializer makes one residual version per source function. A polyvariant one makes one per tuple of static values, as in Step 1.
- Generalization. To stop the growth of versions, a specializer can forget a static value and treat it as dynamic. Offline specializers do this when the analysis finds a static value that grows under dynamic control.
- Partially static data. A pair whose first part is static and second part dynamic, or a list of known length with unknown elements, can be kept split. This needs a richer domain of specialization values.
- Higher-order and imperative languages. Specializers for the lambda calculus (Gomard and Jones), Scheme (Similix), C (C-Mix, Tempo) and Prolog (partial deduction) follow the same plan with more cases.
- Stronger transformers. Supercompilation also uses what a dynamic test tells: in the true branch of
if x == 3, is 3. Deforestation removes intermediate data structures. Both can do things that a partial evaluator cannot, such as the matcher of Consel and Danvy without the rewriting. - Computability. The s-m-n theorem says that a specializer exists for any programming system that can compute all computable functions. It says nothing about speed: the trivial specializer that only wraps with as a constant satisfies the mix equation.
Pitfalls
- Infinite unfolding. Unfolding a recursion whose stop test is dynamic does not end. The rule of the template residualizes calls under dynamic tests, but a recursion with no test between the calls, such as
f(x) = f(x + 1), still unfolds forever ifxis static. - Infinitely many versions. For
f(n, d) = if d == 0 then n else f(n + 1, d - 1)with static, every residualized call has a new static value, so the pending list never empties: the script stops at its limit of 50 versions,f_0,f_1,f_2, and so on. The fix is to generalizento dynamic, which gives the single functionf(n, d)back. - Errors at specialization time. An online specializer computes static operations in both branches of a dynamic test. With
g(s, d) = if d == 0 then 0 else 10 / sand , it fails on10 / 0, though the source never divides when . A specializer must either leave a static operation that can fail as residual code or accept that it may stop with an error. - Lost or copied dynamic work. Unfolding by plain substitution can copy a dynamic argument into two places, so it is computed twice, or drop an argument that the body does not use, which removes an error or a loop of the source. Let insertion keeps call by value exact.
- Code growth. Each unfolding copies a body, and each new static tuple adds a version. A residual program can be exponentially larger than the source. Real specializers bound unfolding and the number of versions.
- Hoping for algebra. Partial evaluation computes with static values. It does not know that
x * 1isxor that the else branch ofif a == 0has . Constant folding after specialization, or a supercompiler, does that.
Exercises
- Specialize
power(n, x)with static and dynamic. Which calls are residualized, and what is the residual program? - Add an instruction
add2that sets to the tiny machine, change the machine program to use it, and give the new residual program. How many operations does it execute on input ? - Show that the pending list in the interpreter example can never hold more pairs than the machine program has instructions. What does this say about termination for every machine program?
- Give a source program of constant size and a family of static inputs for which the residual program of the template grows exponentially with the size of the static input.
- Write a version of
f(n, d)from the pitfalls where the static value grows but the number of versions stays finite. What property of the static values makes the difference?
References
- Neil D. Jones, Carsten K. Gomard and Peter Sestoft, Partial Evaluation and Automatic Program Generation, Prentice Hall, 1993, the mix equation, online and offline specialization, polyvariant specialization of program points, unfolding and termination, and the specialization of interpreters
- Neil D. Jones, An introduction to partial evaluation, ACM Computing Surveys 28(3), 1996, 480-503, the definition of a specializer by the mix equation, the power and interpreter examples, and the problems of termination and code growth
- Andrei P. Ershov, Mixed computation: potential applications and problems for study, Theoretical Computer Science 18(1), 1982, 41-67, mixed computation, the program that does the known part of a computation and emits the rest
- Yoshihiko Futamura, Partial evaluation of computation process, an approach to a compiler-compiler, Higher-Order and Symbolic Computation 12(4), 1999, 381-391, the reprint of the 1971 paper that specializes an interpreter to a program and names the projections
- Neil D. Jones, Peter Sestoft and Harald Søndergaard, An experiment in partial evaluation: the generation of a compiler generator, Rewriting Techniques and Applications (RTA 1985), LNCS 202, 124-140, the first self-applicable specializer, for first-order recursion equations, with memoization of specialized program points
- Charles Consel and Olivier Danvy, Partial evaluation of pattern matching in strings, Information Processing Letters 30(2), 1989, 79-86, a naive string matcher, rewritten so the matched prefix is static, specialized to a pattern into a matcher of Knuth-Morris-Pratt quality
- Thomas Würthinger and others (9 authors), Practical partial evaluation for high-performance dynamic language runtimes, PLDI 2017, 662-676, partial evaluation of AST interpreters at run time in Truffle and Graal, with deoptimization when a speculation fails
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag GRCVMW Edit this page History Report an error Markdown