This pages serves as a public log what I did for my GHC internship from 21 Jan 2013 to 12 April 2013.

Plan for my internship summary

Compared to 351a8c6bbd53ce07d687b5a96afff77c4c9910cc, we implemented OPTIMIZATIONS with a cumulative effect of EFFECT on the generated code as well as EFFECT on the compiler's code. The hope is for the optimizations to have beneficial non-trivial interactions and to simplify/tidy the GHC code base.

general core knowledge

Late Lambda Float

LLF = Late Lambda Float

As the GHC optimization papers explain, it is an early design decision to *not* perform lambda lifting. My initial project was to investigate the effects of aggressively floating lambdas to the top-level at the end of the core2core pipeline.

The main reason to not perform lambda lifting is that abstracting over free variables loses information and thereby inhibits *downstream* optimization.

Doing it *late* (ie just before CorePrep) circumvents this issue.

The original conjecture was that doing it would save allocation: a dynamically allocated closure becomes a static top-level function.

Max Bolingbroke did a quick implementation of this idea some years ago (~mid 2000s), but it seems it was abandoned. I don't know why.

Method

We decided to implement LLF by re-using most of the FloatOut machinery.

FloatOut is structured in three phases.

Annotate all expressions with their free variables.

Consume those annotations while annotating each binder with the target "level" (essentially a depth wrt value lambdas) to which we want to float it.

Consume those annotations while actually relocating the bindings.

We wholesale re-use the third phase (compiler/simplCore/FloatOut) with no changes, add logic to the middle phase, and enrich the first phase with more analyses.

Implementing the LLF logic in the first two FloatOut phases (compiler/simplCore/SetLevels)

Adding LLF to the core2core pipeline (compiler/simplCore/SimplCore)

Overview

In order to minimize factors, I decided to float only lambdas during LLF. Thus there is no need to perform FloatIn afterwards: all of our floats are to the top-level, so there will be nothing to FloatIn.

We placed LLF as the last pass before CorePrep. After experimentation, we decided to follow it with a simplifier pass.

The basic shape of things:

outer = CTX[let f x = RHS[x]
in BODY[f]]

where outer is a top-level binding. LLF transforms this to:

poly_f FVS x = RHS[x]
outer = CTX[BODY[f FVS]]

wbere FVS are the free variables of RHS[x]. We'll use a, b, c, ... for particular variables in FVS.

The poly prefix is vestigial: in the past, floated bindings could never cross lambdas, so the abstracted variables were only type variables. Hence the machinery that adds the new parameters was only ever adding type parameters; it was creating polymorphic functions. This scheme was not updated even when the machinery was enriched to also abstract over values.

Background

join points

let-no-escape

Note [join point abstraction]

Discovered Detriments of LLF

These are the various negative consequences that we discovered on the way. We discuss mitigation below.

Unapplied occurrences of f in BODY results in the creation of PAPs, which increases allocation. For example: map f xs becomes map (poly_f a b c) xs. Max had identified this issue earlier.

Abstracting over a known function might change a fast entry call in RHS to a slow entry call. For example, if CTX binds a to a lambda, that information is lost in the right-hand side of poly_f. This can increase runtime.

Mitigating PAP Creation

This is the simplest to mitigate: we do not float f if it ever occurs unapplied.

Mitigating Thunk Growth

In nucleic2, we floated a binding with 11 free variables. But this binder occurred in about 60 thunks, so many closures grew by ~11 pointers, giving a +2.2% allocation change (as opposed to -0.9%).

We've considered three heuristics for avoiding this. In ascending complexity:

(easy) Limit the number of free variables the binding is allowed.

in-thunk: If f occurs inside of a thunk in BODY, then limit its free variables.

thunk-growth: Approximate the maximum number of free variables that floating f would add to a thunk in BODY, and limit that.

We did not implement the first one, since in-thunk is not very complicated. thunk-growth is significantly more complicated.

The question of whether f occurs in a thunk is not simple.

We count non-trivial arguments as thunks; but not all non-trivial arguments end up as thunks.

We do not count lambda-forms as thunks, since the lambda will hopefully be floated.

Estimating the effect of floating f on such a thunk's (call it t) closure size is more complicated.

Another floated function (say g) may also add some of f's free variables to t; we shouldn't penal both f and g for that.

If f itself has a free variable, say h, which is a binder that gets floated, then floating f will also add h's free variables to t.

Therefore, these are rough approximations. Being more accurate would require changing the setLevels pass instead of just the simpler first pass (the one that only analyzes the original term).

We tried limits of 32, 16, 8, and 4 to differentiate between the last two. At a limit of 8, the allocation increase in ida and puzzle were 1.3 and 2.9 percentage points better with thunk-growth than with in-thunk. But there were no differences around 10 --- which is the lowest we can go while improving nucleic2, anyway --- so we're adopting in-thunk for now.

There might have been some potential benefits to run-time from thunk-growth versus in-thunk (with limit=8, 35 percentage points better on constraint, eg), but we're not confident in those measurements.

Preserving Fast Entries

TODO

Discovered Benefits of LLF

We didn't see as much decrease in allocation as we would have liked.

nice demonstration of the basic effect in puzzle

#7663 - simulates having the inliner discount for free variables like it discounts for parameters

Floating functions to the top-level creates more opportunities for the simplifier.

CTX[case a of [p1 -> let f x = ... in case a of ...]]

The let prevents the cases from being merged. Since LLF is so aggressive, it floats f when it otherwise wouldn't be.

Miscellaneous Findings

Thunk Join Points

We discovered that the worker-wrapper was removing the void argument from join points (eg knights and mandel2). This ultimately resulted in LLF *increasing* allocation. A thunk was let-no-escape before LLF but not after, since it occurred free in the right-hand side of a floated binding and hence now occurred (escapingly) as an argument.

SPJ was expecting no such non-lambda join points to exist. We identified where it was happening (WwLib.mkWorkerArgs) and switched it off. Here are the programs that with affected allocation.

Simon explained that it is probably the simplifier floating d out of the unprotected x binding *in order to reveal x as let-bound to a constructor*. Thus revealed, x is immediately inlined. Because of the \_void, this doesn't happen when the last argument is protected.

With protection, d isn't allocated unless x is entered, which might not always happen in CTX. This is a potential win because x might be let-no-escape.

A potential detriment of protection is that x is not exposed as a let-bound constructor. Simon conjectures that's not actually harmful because ... I CANNOT REMEMBER.

Continuation

SPJ thought this may be another means of hoisting the let-no-escape functionality from the code generator into the core2core pipeline. LLF would handle let-no-escape lambdas, but it does not handle let-no-escape thunks (which we didn't initially realize were being identified).

Changing the let-no-escape thunks to \void -> ... closures upstream would then subject the binding to more optimisations. Formerly, it's non-lambda status meant that inlining it, eg, would lose sharing.