Supercompilation by Evaluation
Paper · 2010 · Maximilian Bolingbroke and Simon Peyton Jones
Summary
A compiler can sometimes do work that a program would otherwise repeat every time it runs. The difficulty is deciding how far to go when some inputs are still unknown. An ordinary evaluator can take a program up to the point where it needs one of those inputs. A supercompiler can go further. It can preserve the decision that depends on the missing input, optimize what will happen under each outcome, and turn recurring computations into calls to specialized functions. In Supercompilation by Evaluation, Max Bolingbroke and Simon Peyton Jones show how to build such an optimizer around the evaluator of a lazy functional language.
Their design makes the evaluator’s state the unit of optimization. The state records the expression currently under evaluation, a heap of bindings that can be forced on demand, and a stack of pending operations. Separate components decide when to stop unfolding code, recognize states whose optimized versions can be reused, and split a blocked computation into pieces that can still be optimized. The separation lets the optimizer use a conventional call-by-need evaluator, where a binding is evaluated when demanded and its result is saved for later uses. It also gives the splitter access to the pending operations and the saved bindings, which matter when moving code across branches.
The main language extension is unrestricted recursive let. A local binding can refer back to itself, and a group of bindings can refer to one another. The authors demonstrate the extension with an infinite list of ones. Mapping an increment function over that list can be compiled into a self-referential list of twos, eliminating the intermediate list from the result. To handle such programs, the splitter must keep recursive bindings in scope when it moves pending work into case branches. The authors also give a termination argument that accounts for the fact that a split involving a recursive binding can lead to a subproblem just as large as its parent.
The prototype preprocesses a subset of Haskell before GHC compiles it at -O2. Across the reported benchmarks, the evaluator-based variant that leaves primitive operations unevaluated during supercompilation reduces runtime by a harmonic mean of 70% relative to GHC alone, with a best reduction of 95%. The reported mean reduction is 57% when the evaluator performs primitive arithmetic and 51% for Neil Mitchell’s supercompiler. Some programs run slower or allocate more after preprocessing, and several are prohibitively expensive to supercompile. The primitive-operation comparison helps explain one source of these setbacks. Computing a partial sum during optimization can make each new sum generate a different specialization, eventually interrupting the fusion that was supposed to eliminate intermediate trees.
Deep dive: Supercompilation by Evaluation
Supercompilation by Evaluation builds a lazy program optimizer around an evaluator, extends it to recursive bindings, and measures the runtime gains. · about 37 minutes to read
The problem and its context
When evaluation reaches an unknown input
Consider a function that applies a transformation to every element of a list. A caller may supply a particular transformation while leaving the list itself to be determined at runtime. There is already enough information to simplify the call. If the transformation increments an element, the compiled loop can perform that increment directly. The list is still unknown, so the program must retain the test that distinguishes an empty list from a nonempty one. A good transformation exposes everything that follows from knowing the function while preserving the decisions that depend on knowing the list.
This is a problem about the behavior of programs in programming languages. The authors approach it by asking what happens if the compiler starts evaluating an incomplete program. When the evaluator reaches the unknown list, it can take no further step at that position. A supercompiler can record the test that remains and investigate each branch separately. The empty branch has a result available immediately. In the nonempty branch, the transformation of the head and the recurring call on the tail can both be examined. More of the original computation moves to compile time because the optimizer can continue in contexts where the evaluator would normally wait.
The same idea applies to a sequence of functions that produce and consume data structures. A program can construct a list or tree in one function and traverse it in the next. The intermediate structure can make the source easier to organize. Its construction and traversal are work the compiled program may be able to avoid. Deforestation is the name the paper uses for eliminating such intermediate structures. A supercompiler can work through the producer and consumer together until the output expresses their combined computation directly. This puts deforestation alongside function specialization, where the optimizer exploits a known argument, and constructor specialization, where it exploits the known form of a piece of data.
The opportunity comes with a control problem. A recursive call may recreate the original optimization problem with new variable names. It may instead bring along a larger expression or a different particular value each time. In the former case, a compiler can reuse a specialization it has already started. In the latter, it needs a rule for recognizing when further unfolding is unproductive. Even a computation that yields a data constructor promptly can create an endless sequence of optimization problems if the compiler tries to optimize each successive tail of a lazy list. Termination is therefore a property the optimizer has to enforce at several points in its own execution.
The tradition the authors build on
The paper traces supercompilation to Valentin Turchin and describes renewed work for both call-by-value and call-by-need languages. Call-by-value evaluates an argument before passing its value into the call. Call-by-need suspends the argument until its value is required and keeps the result for reuse. The authors take Neil Mitchell’s work on supercompilation for lazy programs as their immediate point of departure. They retain the idea of tracking the origin of expressions to control unfolding and ask how the whole optimizer can be organized around an ordinary evaluator.
The paper places supercompilation near partial evaluation. Both can specialize a program when some information is available in advance. The supercompilers the authors discuss typically work on programs without annotations telling the optimizer which computations to perform. They specialize expressions in the context where they occur and decide during optimization when to stop. The paper cites theoretical work suggesting that some forms of partial evaluation propagate less information than supercompilation. It also notes that building a specializer around an evaluator has earlier precedents in partial evaluation. The contribution here is to make that arrangement explicit in a call-by-need supercompiler and show what can be built from it.
The authors discuss an earlier route to compiling lazy programs through partial evaluation. Jesper Jørgensen used a Scheme partial evaluator with an interpreter for a lazy language. The partial evaluator could deal with Scheme’s mutation operation, which the interpreter used to implement thunks that could be updated. A thunk is a suspended computation. Saving its value after evaluation allows later demands to reuse the result. Bolingbroke and Peyton Jones express these updates in the internal state of a call-by-need machine. The language being optimized can remain pure while the machine records the effects of demand on its heap.
The other important precedent concerns termination. Much of the literature discussed in the paper uses homeomorphic embedding, a structural test that checks whether an earlier expression can be found inside a later one in a suitable generalized sense. The authors cite reports in which this test accounted for most of a supercompiler’s running time. Their starting point is Mitchell’s tag-bag test, which compares collections of labels marking where pieces of the current computation originated. The choice matters because the test runs in the optimizer’s inner control loops. A test can be mathematically adequate for preventing divergence while its cost, or its tendency to call a halt early, changes the practical outcome.
Why local recursion changes the design
In a lazy language, a binding can describe a value by referring to itself. For instance, the tail of a list can be the list named by the very binding that creates it. Recursive scope also allows a group of local definitions to refer to each other. The compiler must preserve those relationships during transformation, even when evaluation has temporarily taken a binding apart to work on it. The paper characterizes preceding lazy supercompilers as supporting nonrecursive local let bindings. A design with unrestricted recursive let can treat program-level definitions and local definitions through the same mechanism. There is then no requirement to perform lambda lifting, which would move local functions outward and explicitly pass their formerly surrounding variables as arguments.
The key design choice is to keep the evaluator’s heap and stack available to the optimizer. A pending operation can then be moved or retained as an identifiable part of the computation. A heap binding can be included in a subproblem when it provides information needed there. A pending update can be recognized as the temporary representation of a binding whose scope must survive. The design makes these decisions part of the splitter, leaving the ordinary evaluation steps to follow the operational rules of the language.
The method, step by step
Following a specialization through the optimizer
The paper’s opening example applies a known increment function to every member of an unknown list. The evaluator can begin the call to map and reach a case distinction on the list’s shape. The list itself is a free variable, meaning that its value is supplied from outside the expression currently being optimized. At this point the supercompiler preserves the case and works on the alternatives. The empty-list branch already returns a constructor. In the other branch, the expression builds a new list cell whose head is the incremented element and whose tail is another call to map.
Both fields of that cell offer optimization opportunities. An ordinary call-by-need evaluation stops once the outer constructor is available. Looking inside a field is a decision for the supercompiler. It can optimize the first field by applying the known increment function to the head variable. It can then submit the tail call as a separate optimization problem, with the definitions needed to understand it. That new problem has the shape of the original call on an unknown list. The unknown list is now named by the tail variable. This is enough of a match to reuse the original specialization.
Reuse works even though the optimizer has yet to finish the original specialization. On its first encounter with the call, it reserved a name and recorded the variables that the finished function would need to receive. When the tail repeats the problem under a renaming, the optimizer emits a call to that reserved name with the tail as its argument. Rebuilding the branches eventually produces the definition for the reserved function. After a simple cleanup pass removes helper indirections, the result is a recursive traversal that tests the list, increments each head, and calls itself on the tail. The higher-order argument has disappeared from the recursive loop because the optimizing compiler already knew its definition.
How the supercompiler processes an evaluator state
The steps in order.
A successful lookup can end the process for that state at the second step. A stop at the outer termination check sends the current state directly to the splitter. The word residual refers to the parts of the program retained for execution after compilation. Splitting identifies which surrounding structure to retain and which pieces are worth trying to optimize separately. These decisions recur until the resulting expression and its specialized bindings can be assembled.
The state of a lazy evaluator
The core language in the paper is a small untyped calculus close to GHC’s intermediate language, Core. It has functions, recursive let, algebraic data types, literals, and strict primitive operations. An algebraic data type provides constructors that build values, and a case expression determines which constructor or literal is present. A strict primitive needs the relevant operand values before it can produce its result. The formal syntax uses A-normal form, which names intermediate expressions so that evaluation can proceed through simple operands and bindings. For readability the examples frequently place expressions directly where the normalized form would refer to a name.
s = ⟨H, e, K⟩
Here s is an evaluator state. The brackets enclose its three components. H is the heap, a mapping from variables to expressions. e is the expression currently in focus. K is the stack of frames, where each frame describes an operation waiting for the focus to produce a value.
An application frame, for instance, records an argument while the evaluator works out which function will receive it. A case frame stores the branches while evaluation determines the value being tested. Primitive frames record a pending operation and the operands still needed or already available. An update frame records the binding that should receive the value when a suspended expression finishes evaluating. These frames supply the continuation, meaning the part of the evaluation that will use the current result.
The initial state puts the whole input in focus and starts with an empty heap and stack. Program definitions can occur in an enclosing let, including at the top level. As evaluation progresses, the heap and stack make explicit the context that would otherwise be spread across the syntax of the term. An operation called rebuild goes in the other direction. It wraps the appropriate context around the focus to produce an expression with the same meaning as the state. This gives the optimizer a way to return ordinary code whenever it stops working on a state.
Call-by-need is especially visible when a variable refers to a suspended expression on the heap. On demand, the machine temporarily removes that binding, pushes its update frame, and makes the bound expression the focus. When the focus becomes a value, the evaluator installs the value under the original variable and resumes the pending computation. A subsequent demand for that variable can use the saved value. In the paper’s example, a heap binding holds 1 + 2 and the focus wants to add the bound variable to itself. The first demand computes 3 and updates the heap. The second uses the stored 3, and the combined expression produces 6.
Temporarily removing the binding also accounts for a black hole, a recursive demand that needs its own result before it can finish. If x is bound to x + 1, forcing x starts work on the addition and records an update for x. Evaluation encounters x again with the update still pending and the binding absent from the heap. At that point it is blocked. For the supercompiler, the pending update is indispensable context. The same absence from the heap can arise when a variable is genuinely free. A later reconstruction must preserve the fact that this x has a defining expression whose evaluation depends on itself.
The driver and its two histories
start(e) = runScpM(sc(emptyHistory, ⟨emptyHeap, e, []⟩))
start is the entry point and e is the input term. emptyHistory begins the driver’s record of previously accepted states, emptyHeap is a heap with no bindings, and [] denotes the empty stack. The angle brackets assemble a state. sc is the supercompilation driver. runScpM executes the driver with its bookkeeping initialized and places the optimized definitions it collects around the result.
sc(hist, s) = memo(sc′(hist), s)
hist is the outer history and s is the state submitted for optimization. memo either finds an existing specialization for s or creates a promise for one. sc′(hist) is the worker it runs on a new state with that history in force. The prime distinguishes the worker from the entry point that first checks for reuse.
sc′(hist, s) =
split(sc(hist′), reduce(s)) if terminate(hist, s) = Continue(hist′)
split(sc(hist), s) if terminate(hist, s) = Stop
terminate checks whether the state may be added to hist. Continue(hist′) carries the extended history hist′, while Stop leaves the old history in force. reduce takes as many ordinary evaluation steps as its own stopping rule permits. split decomposes its input state and calls its first argument on the selected pieces. The worker thus gives those recursive calls the extended history when it has performed reduction and the previous history when it has gone straight to splitting.
The driver’s history and the evaluator’s history prevent different infinite processes. Inside reduce, an expression can keep taking ordinary steps while failing to deliver a head result. The reducer uses a fresh history for that particular evaluation run. At the outer level, each run of reduce can finish, yet each call to the splitter can find a new subproblem that leads back to another round of reduction. The history passed among calls to sc controls that second process.
The paper illustrates the distinction with a function that produces a list of successive counts. The evaluator can expose the first list cell and finish its task. The splitter can then select the tail as a fresh problem, at which point the evaluator can expose another cell. Repeating those actions without an outer check would produce an infinite residual expression. The outer history eventually prevents a further unfolding and allows a recurring call to survive in the output. The runtime program can still supply successive elements lazily. By comparison, a function that keeps calling itself beneath a pending addition may fail to produce even the head result. It is the reducer’s local check that bounds the time spent on that attempt.
Deciding when to stop unfolding
The termination component needs a comparison with a particular guarantee. Any infinite sequence of states must eventually contain an earlier state related to a later one. A well-quasi-order provides this guarantee. The optimizer can use a positive comparison as its signal to stop extending the current history. This can happen even if the program would eventually reach a value. The comparison is designed to keep compilation finite while leaving room for productive evaluation steps.
∀ infinite sequences (s₀, s₁, …) in S, ∃ i, j such that i < j ∧ sᵢ ≼ sⱼ
S is the set being ordered, here the set of evaluator states. s₀, s₁, and the ellipsis denote successive members of a sequence, while sᵢ and sⱼ are the entries at positions i and j. ∀ means that the property applies to every such sequence, and ∃ says that a pair of positions exists. < puts the first position earlier in the sequence, ∧ requires both conditions, and ≼ denotes the comparison relation.
terminate(prevs, here) =
Stop if some old in prevs satisfies old ≼ here
Continue(here : prevs) otherwise
prevs is the history, here is the current state, and old ranges over the states in prevs. ≼ is the chosen comparison. Stop ends this attempt to extend the history. Continue carries a new list, with here : prevs denoting insertion of here at the front. An infinite chain of successful extensions would have to avoid every earlier-to-later pair required by the order, which is what the guarantee rules out.
For the actual comparison, each input subexpression gets a unique integer tag. Stack frames carry tags from the expressions that created them. When evaluation constructs a new literal, as it can when it performs arithmetic, it takes a tag from an operand. This lets the machine create a value that was absent from the input while using a finite supply of tag identities. The optimizer collects the tags in a bag, or multiset. A multiset keeps track of repeated occurrences, in addition to which distinct elements it contains.
t₁ ≼ₜᵦ t₂ ⇔ set(t₁) = set(t₂) ∧ |t₁| ≤ |t₂|
t₁ and t₂ are tag bags. ≼ₜᵦ is the tag-bag order, and ⇔ says that the conditions on the right define when it holds. set discards multiplicity, = compares the resulting sets, and ∧ requires the cardinality comparison as well. The bars give the total number of entries, counting repeated tags. ≤ allows equal sizes and sizes greater in the later bag. The test can therefore detect recurrence even when the state changes in ways that an exact syntactic comparison would distinguish.
tagBag(H, e, K) = {termTag(e) × 2} ⊎ scale(3, heapTagBag(H)) ⊎ scale(5, stackTagBag(K))
tagBag makes the multiset for the full state. H, e, and K are the heap, focus, and stack. termTag(e) is the tag of the focused expression, heapTagBag(H) gathers the heap tags, and stackTagBag(K) gathers the stack tags. Braces form a one-entry bag, × is multiplication, scale multiplies each entry of a bag by its first argument, and ⊎ joins bags with multiplicities preserved. The factors 2, 3, and 5 mark the different roles of focus, heap, and stack in the test.
s₁ ≼ s₂ ⇔ tagBag(s₁) ≼ₜᵦ tagBag(s₂)
s₁ and s₂ are whole evaluator states. ≼ compares them by applying tagBag to both and using the bag order ≼ₜᵦ. ⇔ again gives the defining equivalence. With a finite supply of tags, some set of distinct tags has to recur infinitely often in any infinite sequence of bags. Among bags with that same set there must be an earlier size no greater than a later one. That supplies the pair needed for the state comparison.
The component-specific treatment is meant to give the evaluator room to make ordinary progress. Forcing a heap binding changes the role of its tagged expression, which can place a tag on a frame instead. The test sees information about that change, in addition to the expressions involved. The paper contrasts this with Mitchell’s convention of tagging let-bound variables and keeping subexpressions in named bindings. Direct tags on the evaluator’s subterms and frames let the new design obtain the information from the machine state itself.
The reducer performs a standard machine transition and checks whether another transition is available. It returns the state it has reached if it has a value or is blocked, for example by a free variable. It also returns if the history test calls a halt. The implementation checks at states with a variable in focus. The justification is that any endless sequence of machine steps in this evaluator encounters variable focuses infinitely often. Checking only there saves work and gives consecutive checked states more opportunity to differ. Because the test is conservative, a state returned by reduce can still have an enabled evaluation step. The splitter must be able to work with such a state.
Turning repeated problems into calls
The memoizer keeps a collection of promises, a collection of completed optimized definitions, and a supply of fresh names. A promise associates a submitted state with its reserved name and a list of free variables. Those variables become parameters of the corresponding output function. The promise has to be visible before its definition is ready. That timing is what permits the optimizer to turn a recurring state into a recursive call.
match(s₁, s₂) = Just(rn) ⇒ meaning(s₂) = meaning(rn(s₁))
match compares a stored state s₁ with a requested state s₂. Just(rn) represents success and carries the variable renaming rn. rn(s₁) applies that renaming to the stored state. meaning denotes the program meaning of its argument, = asserts equality, and ⇒ states what a successful match guarantees. Matching must also succeed for states that have identical syntax up to renaming. The termination argument relies on that coverage.
At a match, the memoizer emits a call to the stored name. Its arguments are the promise’s free variables translated into the names of the current state. When there is no match, the memoizer takes a fresh name, records a promise, and asks the worker to optimize the state. The completed body is abstracted over the recorded variables and saved as the definition of that name. The memoizer then returns the corresponding call. This allows a specialized definition to serve callers whose variable names differ. The final run assembles the accumulated definitions around the result. The paper also notes that a definition with no free variables should take a dummy argument in the actual implementation to avoid accidentally extending the lifetime of a constant computation.
Matching states can take advantage of the partial normalization the evaluator has already performed. The implementation can compare heap bindings without requiring them to appear in the same order. It also has to respect sharing. A state with separate suspensions for the same costly operation and a state with one suspension referenced in several places differ in how frequently the operation may run. A match that changes one sharing pattern into the other can introduce duplicated work. With an already manifest value, the same issue is less restrictive because no further evaluation of that binding is required. The matching problem involves the cost consequences of the state representation as well as its meaning.
Splitting code while preserving what it knows
At a constructor, the splitter can designate its fields or their bindings for further optimization. At a blocked case, it can preserve the test and optimize the alternatives. It can also pass some of the original context to a selected piece. The paper gives the example of a constructor field bound to x + x, with x known to be 1 in the heap. If the optimizer submits just the addition, the new evaluator has no definition for x. Including the relevant heap binding lets it reduce the addition to 2. Which context moves with a subproblem determines how far the next reduction will go.
The stack supplies another opportunity. Suppose evaluation is blocked on a case whose possible results are known small literals, with a subsequent addition waiting on its result. The splitter can put the pending addition inside each case alternative. Once inside a particular alternative, both operands are available and the evaluator can finish the arithmetic. The residual case then selects among already computed outcomes. The stack makes it straightforward to identify the operations that would follow the case and attach them to its branches, subject to the binding constraints that recursive let introduces.
A branch can give the optimizer information about a variable as well as the result of the test. If a case checks x against 3 and 4, each corresponding branch can be optimized with a local heap entry for the appropriate value of x. An addition in one branch and a multiplication in the other can then be reduced with the facts established by their own tests. This is conditional information propagation. The unknown runtime value still determines which branch executes, while the work that depends on a branch’s known value can already be done.
Bracket = {holes : [State], assemble : [Term] → Term}
Bracket is the paper’s representation for residual code with positions still to be filled. holes lists the State values to optimize. assemble takes the resulting list of Term values and puts them into the surrounding expression, yielding a Term. Square brackets denote lists, : gives the type of each field, and → gives the input and output of the assembly function.
split(opt, s) = assemble(br)(mapM(opt, holes(br)))
Here s is the state being split and br is the bracket formed from its focus, stack, and heap. opt is the function used to optimize a hole. holes(br) retrieves the list of states, mapM applies opt to each while sequencing its bookkeeping, and assemble(br) combines the resulting terms. The split is required to preserve the meaning of s whenever opt preserves the meaning of each submitted state.
The sketch starts with the immediate subexpressions of the focused term and an assembly function that knows where to put them back. It then processes the stack. An application or a primitive frame can be represented by extending the residual expression. When a case frame is reached, the remaining frames can accompany the alternatives as their continuation. The splitter records any variables known to share the focus’s value so it can give them the corresponding bindings in the alternative heaps. When it encounters an update frame, it can extract a binding for the expression being evaluated and proceed with that variable in focus. The final heap processing combines these extracted bindings with those already present.
Moving a binding into a hole is also a decision about how frequently its computation may run. Consider an expensive calculation on a heap that is shared by both fields of a pair. Giving each field its own copy of the binding may run the calculation twice. Putting a suspension under a lambda can likewise cause its evaluation to recur with function calls even if the source expression occurs only once. A runtime case branch presents another situation. There may be copies in the two branch bodies, while execution takes only one branch. The paper’s policy favors pushing a manifest value into its uses and also allows movement when it can establish that the thunk will be allocated at most once in a possible use of the result.
Let-floating helps expose more opportunities under that policy. A binding may construct a value that contains a suspended expensive field. If the expensive field receives a separate binding outside the lambda, the constructor with a reference to that binding can be passed into the inner optimization problem. The optimizer can then see which constructor the case will encounter while the suspended field remains available for sharing. The paper sketches the bracket machinery and identifies the required work-duplication analysis and let-floating as additional implementation work beyond that sketch.
Recursive updates and the termination argument
An update frame makes a binding temporarily present on the stack instead of in the heap. Moving the frame into a case branch therefore moves the place where the splitter can reconstruct that binding. Sometimes this is precisely what is wanted. If the update is used only in a branch’s continuation, the resulting let can live in the branch. With recursive scope, the scrutinee itself can refer to the name being updated. Moving that binding into the branch would leave the reference in the scrutinee without its definition. The splitter then has to keep the binding outside, with the case expression forming part of its right-hand side.
The decision can propagate across several names. In the paper’s larger example, a test needs a variable whose update would initially have been moved into an alternative. Keeping that update outside exposes a dependency on a separate expensive binding. The latter must stay shared, and its right-hand side depends on another name whose update was going to move inward. The implementation uses a fixed point for this process. It repeatedly identifies additional update frames that must stay outside until another pass through the dependencies adds none. This allows valid continuation movement while keeping the bindings visible where the reconstructed code needs them.
The authors give separate termination arguments for splitting with and without recursive let. In the simpler case, once the outer check stops allowing reduction, every recursive split can be required to select a state with fewer syntax-tree nodes. That ensures the chain of split calls ends. Recursive let makes the size condition too restrictive. A hole can retain the recursive definition from the heap alongside a focus resembling the one in its parent state, making the child just as large. The replacement argument limits the syntactic material available to a chain of split calls.
h′ ⊆ h ∪ altHeap(e, k)
h is the parent heap and h′ is the heap in a selected child state. e and k are the parent focus and stack. altHeap(e, k) collects possible bindings learned from case alternatives, using variables associated with updates in k and the focus variable when e is a variable. ∪ combines those possibilities with the original heap bindings, and ⊆ says the child’s bindings come from that collection.
k′ isInfixOf k
k′ is the child stack and k is the parent stack. isInfixOf means that the child stack is a contiguous portion of the parent stack. Splitting can keep frames from that portion without adding new ones on the split-only path considered in the proof.
e′ ∈ subterms(h, e, k)
e′ is the child focus. subterms(h, e, k) collects expressions that appear syntactically in the parent heap h, focus e, or stack k. ∈ means that the child focus belongs to that collection.
Suppose there were an infinite path of recursive driver calls. If that path eventually consisted only of calls that split without reduction, the restrictions would confine it to a finite stock of states. Some state would then recur, and the memoizer would recognize it and return a call instead of recursing. If reduction kept being allowed along the path, the outer history would be extended infinitely often. The well-quasi-order rules out that sequence of successful extensions. The argument also uses the fact that each split submits only finitely many subproblems. Together these points explain why a bound on what the splitter can construct is sufficient even though its child states may fail to shrink.
This is the machinery behind the recursive list example in the paper’s overview. The input defines ones with a head of 1 and a tail referring back to ones, then maps an increment over it. The output can define xs with a head of 2 and a tail referring back to xs, and return xs. The recursion in the input is represented by a finite piece of syntax. The optimizer has enough access to that structure to combine producing the list and mapping over it without having to enumerate its elements. The paper uses this example to show what recursive local bindings make possible within the evaluator-based design.
Experiments and results
What the comparison measures
The authors implemented the supercompiler as a preprocessor for a subset of Haskell. GHC compiled the resulting programs at -O2. The reference for the relative figures was GHC without supercompilation. This measures the effect of adding the preprocessing stage to a compiler that already performs its own optimizations. The authors also report results for Mitchell’s supercompiler, giving a comparison with an earlier optimizer for lazy programs.
There are two evaluator-based settings. With primitive evaluation enabled, the supercompiler can perform operations such as arithmetic when the values it needs are known. The other setting leaves those primitive operations unevaluated during supercompilation. Both treat primitives as strict. Thus the comparison changes whether the evaluator computes their results at compile time while retaining the information that the operands are demanded.
The workloads are individual programs. append, factorial, sumtree, and treeflip come from earlier examples of supercompilation and deforestation, as does raytracer. The paper takes sumsquare from work on stream fusion. It draws other programs from the imaginary portion of the nofib suite, including bernouilli, digitsofe2, primes, and rfib. That portion also supplies exp3 8, tak, and x2n1. The two wheel sieve benchmarks use recursive bindings in a way that is fundamental to their implementation. There is no training phase or split into training and test sets. The compiler transforms each program by evaluating and specializing its code, and the measurements concern the resulting compilation and execution.
The results distinguish five quantities. Supercompilation time is given in seconds. The subsequent time GHC spends compiling is relative to GHC’s time on the original program. Execution time and allocation are relative to those of the original program compiled without the preprocessing step. Program size is measured in syntax-tree nodes and is also relative to the original. The runtime and allocation columns therefore answer different questions. A residual program can run quickly while allocating more, and a short preprocessor run can produce an expression that takes substantially longer for GHC to compile.
Runtime improvements and their spread
Harmonic mean runtime reduction on the reported benchmarks relative to GHC alone
The evaluator-based setting with primitive operations left unevaluated has the largest reported mean reduction.
The numbers
| System or setting | runtime reduction % |
|---|---|
| Mitchell | 51 |
| Evaluator-based with primitive evaluation | 57 |
| Evaluator-based with primitive operations left unevaluated (this paper) | 70 |
The paper reports a harmonic mean runtime reduction of 70% for the evaluator-based setting that leaves primitives unevaluated. With primitive evaluation enabled, the reported reduction is 57%. Mitchell’s supercompiler achieves a reported 51% reduction. These are aggregate figures relative to GHC alone. Individual results vary, and the benchmark table includes unavailable entries. The aggregate therefore needs to be read alongside the specific programs each setting could process and the results that dominate the practical interpretation.
Program runtime on sumsquare relative to GHC alone
Both evaluator-based settings improve on Mitchell’s runtime, with the best result from leaving primitives unevaluated.
The numbers
| System or setting | relative program runtime |
|---|---|
| Mitchell | 0.36 |
| Evaluator-based with primitive evaluation | 0.06 |
| Evaluator-based with primitive operations left unevaluated (this paper) | 0.05 |
sumsquare supplies the largest reported reduction in program runtime, 95%, under the evaluator-based setting that leaves primitives unevaluated. The effect is visible next to the compile-time costs. That setting takes 2.3s for supercompilation, and its subsequent GHC compile time is 1.97 relative to compiling the original program. Its program size is 20.78 relative to the original in syntax-tree nodes. Mitchell’s preprocessor takes 19.5s on the same workload and produces a relative size of 7.38. In this case the evaluator-based variant yields the faster executable and takes less time in its own preprocessing stage. Its output is larger and leaves GHC with more compilation work.
There are other workloads where the evaluator-based system yields a runtime improvement with different resource tradeoffs. On raytracer, relative program runtime is 0.57 for Mitchell, 0.52 for the evaluator-based setting without primitive evaluation, and 0.51 with it. Corresponding relative allocations are 0.44, 0.45, and 0.45. On rfib, the evaluator-based settings both reach relative runtime 0.67, while Mitchell reaches 0.93. The evaluator-based outputs each have relative size 2.00 in syntax-tree nodes. For the reader comparing optimizers, the time and size figures show which parts of the tradeoff recur and which depend on the particular program.
The comparison also contains small improvements and regressions. On primes, Mitchell has relative program runtime 0.63. The evaluator-based settings reach 0.72 with primitives left unevaluated and 0.71 with primitive evaluation. On factorial, Mitchell reaches 0.95 and the evaluator-based variant without primitive evaluation reaches 0.99. Enabling it gives 1.05. On digitsofe2, the performance gap is larger. Mitchell obtains runtime 0.32 and allocation 0.46, both relative to GHC alone. Without primitive evaluation the evaluator-based system gives runtime 1.17 and allocation 1.08, and with primitive evaluation it gives 1.18 and 1.09. The paper regards interference with GHC’s unboxing as a possible reason for the digitsofe2 regression and leaves the exact cause unresolved.
Recursive programs and the cost of compiling them
The wheel sieves distinguish coverage from performance. Mitchell’s entries for wheel-sieve1 and wheel-sieve2 are unavailable because those programs fundamentally depend on recursive let. The evaluator-based implementation processes both. For wheel-sieve1, the setting without primitive evaluation records relative runtime 0.90 and allocation 0.53. With it enabled, the relative runtime is 1.00 and allocation 0.54. The authors identify elimination of intermediate lists in wheel-sieve1 as the source of improvement. The preprocessor takes 22.2s with primitive evaluation disabled and 16.8s with it enabled. The corresponding relative sizes are 71.07 and 71.47. A program can thus demonstrate that a language feature is supported, show savings in execution, and still impose substantial costs at compilation.
For wheel-sieve2, both settings have relative runtime 1.55 and relative allocation 1.21. Its inclusion matters because support for a construct enables the compiler to attempt an optimization. The outcome then depends on the structure of the program and the definitions that survive specialization. The two wheel sieves are cases where the new language coverage is genuine and the effects on actual executables differ.
The tak result shows how a single metric can give an incomplete picture. With primitives left unevaluated, the evaluator-based system reports relative runtime 0.74, alongside relative allocation 18644.34. Mitchell’s corresponding values are 0.81 and 655.04. The paper describes the evaluator-based allocation increase as 18,000-fold from an original allocation of 13kB. GHC can use unboxed arithmetic in the original program. The authors trace the increase after supercompilation to large join points that take boxed integers as arguments. A join point is a shared destination to which several parts of the residual program can pass control and values. Boxing makes an integer available through a heap representation. The code recovered by supercompilation in this case changes the representation choices that GHC makes later.
tak is prohibitively expensive to supercompile with primitive evaluation enabled, so that setting supplies no runtime or allocation result for it. The authors also identify digitsofe1 and gen regexps as prohibitively expensive for both their system and Mitchell’s. These cases belong in the practical comparison even though they offer no runnable output to time. A finite algorithm can still require more preprocessing work than the experiment can afford, and those failures constrain which programs can benefit from the method.
What the ablations show
What changes when arithmetic is evaluated
The controlled switch in the evaluation is whether the evaluator computes primitive operations during supercompilation. Holding strict treatment of operands fixed lets the comparison focus on what happens when computed values enter states. The aggregate favors leaving primitives unevaluated, but the workload results show where that behavior comes from. On sumsquare there are large improvements with either choice. On treeflip and sumtree, enabling primitive evaluation substantially weakens the results. The paper relates that drop to the way the memoizer and the termination test interact with partial sums.
Program runtime on treeflip relative to GHC alone
Leaving primitive operations unevaluated lets the evaluator-based system obtain the strongest runtime result.
The numbers
| System or setting | relative program runtime |
|---|---|
| Mitchell | 0.56 |
| Evaluator-based with primitive evaluation | 0.81 |
| Evaluator-based with primitive operations left unevaluated (this paper) | 0.13 |
treeflip and sumtree first generate a binary tree and then consume it through a series of functions ending in a sum. The authors report that the initial tree construction is difficult to deforest cleanly. There are intermediate copies created by the consuming pipeline, however, and eliminating those copies allows the combined function to compute the sum directly. Mitchell’s approach and the evaluator-based setting without primitive evaluation both obtain this fusion. On sumtree, for example, Mitchell’s relative program runtime is 0.13 and the evaluator-based version with primitive operations left unevaluated reaches 0.14. Evaluating them gives 0.68. The relative allocation measurements reported for those settings are 0.00, 0.00, and 0.93, respectively, at the precision displayed by the paper.
A partial sum can turn into a literal when primitive evaluation is enabled. The stack can then contain a frame such as 2 + •, where the dot marks the expression still to be evaluated and 2 is the sum so far. Each result reached as progress through the tree changes that part of the pending work. A specialization that includes a frame with a particular literal does not match the corresponding state with a different literal just by renaming variables. The optimizer begins creating specialized versions of what would otherwise be the same fused pipeline.
Eventually the termination test interrupts this sequence. At that point the optimizer splits a state before it can finish fusing the functions involved. The authors describe the resulting structure as a small initial portion that enjoys complete deforestation, followed by a fallback retaining the intermediate structure of the original pipeline. The arithmetic being performed at compile time is valid. Its cost comes from making the state too specific to reuse and consuming unfolding opportunities on several versions of the same underlying computation.
The measurements beyond runtime fit that explanation. On treeflip, relative size is 2.53 when primitives are left unevaluated and 19.40 when they are evaluated. Relative allocation changes from 0.05 to 0.91. A setting that computes more during preprocessing can therefore produce larger output and leave the executable doing more allocation. On a different program such as raytracer, primitive evaluation gives the slightly lower reported runtime. The evidence favors examining how a computed value participates in recurring states. The primitive switch is a coarse way of changing that behavior across all programs.
What the diagnostics say about the optimizer
The paper also profiles its own implementation on the workload it calls digits-of-e2 in the profiling discussion. Managing names and renaming accounts for 42% of the supercompiler’s running time. Matching previous states accounts for 14%, and the termination test for 6%. These percentages refer to time spent supercompiling that program. They concern a different question from the relative runtime of the executable that comes out. In this profile, manipulating the names used throughout specialization consumes more of the optimizer’s time than deciding whether to stop unfolding.
The profile gives a point of comparison with earlier reports that homeomorphic-embedding checks could dominate a supercompiler’s runtime. It is a profile of the tag-bag implementation on one program, while those earlier observations concern other systems. Its direct evidence is that the tag-bag check accounts for a limited share of the measured work in this run. A replacement experiment within the same implementation would be needed to measure the effect of switching termination relations under otherwise matched conditions.
The tak investigation likewise explains a particular consequence of the output by examining the join points and the representation of their integer arguments. The paper gives a firmer diagnosis there than on digitsofe2, where it suggests a similar unboxing problem. The comparison with Mitchell combines changes in language support and optimizer design. The wheel sieves show a difference in which programs can be processed. They do not provide a paired experiment in which the same residual transformation is obtained with and without recursive local bindings. Taken together, the primitive switch, profile, and individual diagnoses locate several mechanisms behind the outcomes while leaving the contribution of individual design components open.
Limitations
Limits the authors identify
The authors describe the experiments as preliminary and identify code growth and compilation time as the main obstacles to practical use. The stopping argument ensures that the optimizer finishes in principle. The time needed before those checks bring a difficult program to a halt can still make optimization impractical. The missing results for digitsofe1, gen regexps, and one tak setting put a concrete boundary on the reported mean improvements. The large residual programs in some completed runs also show that having a finite bound on unfolding leaves a wide range of possible compilation costs.
The stopping criterion can cut off useful evaluation. As the authors explain, a head normal form may exist even when the check returns a state from which work remains. Their decision to check at variable focuses gives the evaluator room to make progress before comparing states. More frequent checks can produce closely similar successive states and encourage early stops. This is a tradeoff within the compilation strategy. The conservative check does its job even in cases where continued unfolding would have helped, so termination on its own is insufficient to judge the quality of the residual program.
The paper’s account of the splitter is explicitly a sketch. Its bracket representation shows how to separate subproblems from their residual surroundings, and the recursive update examples explain why scope dependencies must be followed to a fixed point. A complete implementation also needs decisions about which heap bindings can move without duplicating work, how to expose additional movable values, and when parts of the stack can enter alternatives. These choices are substantive because they determine which facts reach each subproblem and whether the output preserves sharing.
The authors also point out avoidable duplication of specialized code. Their example calls a list-repetition function with the same known length and two different characters. The evaluator inspects the length as it unfolds the list. It can construct the list shape without inspecting the character. The described supercompiler can nevertheless produce two separate specialized lists, one for each character. A shared specialization could take the character as a parameter and reuse the optimized list construction. That is an opportunity to reduce the size and number of specializations while preserving the knowledge that actually contributed to evaluation.
The prototype handles a subset of Haskell. The paper discusses a future extension to typed System FC and integration into GHC. Its experiments use preprocessing ahead of GHC, which also means that the final performance depends on how GHC handles the resulting program. The allocation problem in tak illustrates this dependency. The supercompiler’s reasoning about the lazy program can preserve its meaning and still leave the subsequent compiler with boxed values it would have avoided on the original source.
Limits visible in the evaluation
The benchmarks include examples selected from research on optimization and from one part of nofib. They establish that this design can achieve substantial gains on several particular programs, including programs that exercise recursive scope. The setup gives less evidence about routinely compiling larger Haskell applications or about how the preprocessor’s costs would be distributed across a broader workload. Programs with unavailable outputs further complicate comparison of the mean results. The figures for each successful row remain informative, alongside the failures that determined which rows could be measured.
The runtime column concerns the executable once compilation has finished. It cannot establish whether the preprocessing and subsequent compilation pay for themselves in a given use. That depends on both compile-time costs and how much the executable runs. The paper gives separate columns that allow readers to see this tension, as with the expanded residual code for sumsquare and wheel-sieve1. It does not measure a combined end-to-end workload that would resolve the tradeoff. Likewise, the allocation column measures the amount allocated. The table gives no separate measurement of peak live memory.
Most comparisons are between complete systems or between the two broad primitive settings. The benchmark results do not vary the stopping rule, frequency of termination checks, matcher, and splitter independently. The paper’s examples establish the motivations for these choices and give causal accounts for some programs. They do not quantify the share of the aggregate gain attributable to each component. The profile has a similarly specific scope. Its breakdown is a measurement on one program, so proportions such as the 6% for termination checking have that program and implementation as their conditions.
Finally, the argument for recursive termination concerns the specified state transitions, the properties of matching, and the restrictions imposed on split-only calls. Its implications for a new source language depend on whether corresponding components satisfy those conditions. Likewise, the successful recursive list example shows that the compiler can reach a compact transformation in a program with a simple cyclic structure. The contrast between the two wheel sieves shows how much the performance of other recursive programs can still depend on the producers, consumers, and sharing exposed by their particular definitions.
What came after
No subsequent work is documented here. The paper itself identifies several directions for extending the method, with different levels of progress at the time it was written.
The most concrete direction is to reuse a specialization based on the information evaluation actually consumes. In the list-repetition example, the length governs the unfolding and the character can remain a parameter. A specialization that keeps that distinction can serve both calls without retaining two copies of the unrolled structure. The authors report a partial implementation of a mechanism intended both to increase this kind of code sharing and to avoid excess allocation. They give the shared residual form as the intended outcome and leave its wider performance to future reporting.
A second direction is to use a different evaluator. The authors discuss adapting the architecture to a pure call-by-value language such as Timber. They expect much of the work to fall in the splitter, since it must understand the continuation frames that the evaluator actually creates. In the call-by-value and call-by-name settings they discuss, there is no call-by-need update frame to preserve across a case. The resulting rules for moving bindings and stacks would therefore have a different set of constraints. The paper presents comparable optimization power to the call-by-value work of Jonsson and Nordlander as an expectation for such an adaptation.
The proposed extension to System FC would take the design toward use inside GHC. The authors expect many of the changes for the typed language to be local to the evaluator. They also observe that specialization benefits from seeing as many of the program’s definitions as possible. GHC’s interface files provide a way to obtain definitions from imported modules, which would help make that information available across module boundaries. The paper leaves open how those extensions would affect compilation cost, the size of residual programs, and the gains measured on a broader set of workloads.
Cite
Cite as Maximilian Bolingbroke and Simon Peyton Jones. 2010. Supercompilation by Evaluation. Haskell Symposium 2010.
@inproceedings{bolingbroke2010supercompilation,
title = {{Supercompilation by Evaluation}},
author = {Maximilian Bolingbroke and Simon Peyton Jones},
booktitle = {Haskell Symposium 2010},
year = {2010},
url = {https://www.microsoft.com/en-us/research/wp-content/uploads/2016/07/supercomp-by-eval.pdf}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/bolingbroke-2010-supercompilation-evaluation/