GHC has a lot of optimizations that it can perform, but I don't know what they all are, nor how likely they are to be performed and under what circumstances.
My question is: what transformations can I expect it to apply every time, or nearly so? If I look at a piece of code that's going to be executed (evaluated) frequently and my first thought is "hmm, maybe I should optimize that", in which cases should my second thought be, "don't even think about it, GHC got this"?
I was reading the paper Stream Fusion: From Lists to Streams to Nothing at All, and the technique they used of rewriting list processing into a different form which GHC's normal optimizations would then reliably optimize down into simple loops was novel to me. How can I tell when my own programs are eligible for that kind of optimization?
There's some information in the GHC manual, but it only goes part of the way towards answering the question.
EDIT: I'm starting a bounty. What I would like is a list of lower-level transformations like lambda/let/case-floating, type/constructor/function argument specialization, strictness analysis and unboxing, worker/wrapper, and whatever else significant GHC does that I've left out, along with explanations and examples of input and output code, and ideally illustrations of situations when the total effect is more than the sum of its parts. And ideally some mention of when transformations won't happen. I'm not expecting novel-length explanations of every transformation, a couple of sentences and inline one-liner code examples could be enough (or a link, if it's not to twenty pages of scientific paper), as long as the big picture is clear by the end of it. I want to be able to look at a piece of code and be able to make a good guess about whether it will compile down to a tight loop, or why not, or what I would have to change to make it. (I'm not interested so much here in the big optimization frameworks like stream fusion (I just read a paper about that); more in the kind of knowledge that people who write these frameworks have.)
Laziness
It's not a "compiler optimisation", but it's something guaranteed by the language specification, so you can always count on it happening. Essentially, this means that work is not performed until you "do something" with the result. (Unless you do one of several things to deliberately turn off laziness.)
This, obviously, is an entire topic in its own right, and SO has lots of questions and answers about it already.
In my limited experience, making your code too lazy or too strict has vastly larger performance penalties (in time and space) than any of the other stuff I'm about to talk about...
Strictness analysis
Laziness is about avoiding work unless it's necessary. If the compiler can determine that a given result will "always" be needed, then it won't bother storing the calculation and performing it later; it'll just perform it directly, because that is more efficient. This is so-called "strictness analysis".
The gotcha, obviously, is that the compiler cannot always detect when something could be made strict. Sometimes you need to give the compiler little hints. (I'm not aware of any easy way to determine whether strictness analysis has done what you think it has, other than wading through the Core output.)
Inlining
If you call a function, and the compiler can tell which function you're calling, it may try to "inline" that function - that is, to replace the function call with a copy of the function itself. The overhead of a function call is usually pretty small, but inlining often enables other optimisations to happen which wouldn't have happened otherwise, so inlining can be a big win.
Functions are only inlined if they are "small enough" (or if you add a pragma specifically asking for inlining). Also, functions can only be inlined if the compiler can tell what function you're calling. There are two main ways that the compiler could be unable to tell:
If the function you're calling is passed in from somewhere else. E.g., when the
filter
function is compiled, you can't inline the filter predicate, because it's a user-supplied argument.If the function you're calling is a class method and the compiler doesn't know what type is involved. E.g., when the
sum
function is compiled, the compiler can't inline the+
function, becausesum
works with several different number types, each of which has a different+
function.In the latter case, you can use the
{-# SPECIALIZE #-}
pragma to generate versions of a function that are hard-coded to a particular type. E.g.,{-# SPECIALIZE sum :: [Int] -> Int #-}
would compile a version ofsum
hard-coded for theInt
type, meaning that+
can be inlined in this version.Note, though, that our new special-
sum
function will only be called when the compiler can tell that we're working withInt
. Otherwise the original, polymorphicsum
gets called. Again, the actual function call overhead is fairly small. It's the additional optimisations that inlining can enable which are beneficial.Common subexpression elimination
If a certain block of code calculates the same value twice, the compiler may replace that with a single instance of the same computation. For example, if you do
then the compiler might optimise this to
You might expect that the compiler would always do this. However, apparently in some situations this can result in worse performance, not better, so GHC does not always do this. Frankly, I don't really understand the details behind this one. But the bottom line is, if this transformation is important to you, it's not hard to do it manually. (And if it's not important, why are you worrying about it?)
Case expressions
Consider the following:
The first three equations all check whether the list is non-empty (among other things). But checking the same thing thrice is wasteful. Fortunately, it's very easy for the compiler to optimise this into several nested case expressions. In this case, something like
This is rather less intuitive, but more efficient. Because the compiler can easily do this transformation, you don't have to worry about it. Just write your pattern matching in the most intuitive way possible; the compiler is very good at reordering and rearranging this to make it as fast as possible.
Fusion
The standard Haskell idiom for list processing is to chain together functions that take one list and produce a new list. The canonical example being
Unfortunately, while laziness guarantees skipping unecessary work, all the allocations and deallocations for the intermediate list sap performance. "Fusion" or "deforestation" is where the compiler tries to eliminate these intermediate steps.
The trouble is, most of these functions are recursive. Without the recursion, it would be an elementary exercise in inlining to squish all the functions into one big code block, run the simplifier over it and produce really optimal code with no intermediate lists. But because of the recursion, that won't work.
You can use
{-# RULE #-}
pragmas to fix some of this. For example,Now every time GHC sees
map
applied tomap
, it squishes it into a single pass over the list, eliminating the intermediate list.Trouble is, this works only for
map
followed bymap
. There are many other possibilities -map
followed byfilter
,filter
followed bymap
, etc. Rather than hand-code a solution for each of them, so-called "stream fusion" was invented. This is a more complicated trick, which I won't describe here.The long and short of it is: These are all special optimisation tricks written by the programmer. GHC itself knows nothing about fusion; it's all in the list librarys and other container libraries. So what optimisations happen depends on how your container libraries are written (or, more realistically, which libraries you choose to use).
For example, if you work with Haskell '98 arrays, don't expect any fusion of any kind. But I understand that the
vector
library has extensive fusion capabilities. It's all about the libraries; the compiler just provides theRULES
pragma. (Which is extremely powerful, by the way. As a library author, you can use it to rewrite client code!)Meta:
I agree with the people saying "code first, profile second, optimise third".
I also agree with the people saying "it is useful to have a mental model for how much cost a given design decision has".
Balance in all things, and all that...
If a let binding v = rhs is used in only one place you can count on the compiler to inline it, even if rhs is big.
The exception (that almost isn't one in the context of the current question) is lambdas risking work duplication. Consider:
there inlining v would be dangerous because the one (syntactic) use would translate into 99 extra evaluations of rhs. However, in this case, you would be very unlikely to want to inline it manually either. So essentially you can use the rule:
If you'd consider inlining a name that only appears once, the compiler will do it anyway.
As a happy corollary, using a let binding simply to decompose a long statement (with hope of gaining clarity) is essentially free.
This comes from community.haskell.org/~simonmar/papers/inline.pdf which includes a lot more information about inlining.
This GHC Trac page also explains the passes fairly well. This page explains the optimization ordering, though, like the majority of the Trac Wiki, it is out of date.
For specifics, the best thing to do is probably to look at how a specific program is compiled. The best way to see which optimizations are being performed is to compile the program verbosely, using the
-v
flag. Taking as an example the first piece of Haskell I could find on my computer:Looking from the first
*** Simplifier:
to the last, where all the optimization phases happen, we see quite a lot.First of all, the Simplifier runs between almost all the phases. This makes writing many passes much easier. For example, when implementing many optimizations, they simply create rewrite rules to propagate the changes instead of having to do it manually. The simplifier encompasses a number of simple optimizations, including inlining and fusion. The main limitation of this that I know is that GHC refuses to inline recursive functions, and that things have to be named correctly for fusion to work.
Next, we see a full list of all the optimizations performed:
Specialise
The basic idea of specialization is to remove polymorphism and overloading by identifying places where the function is called and creating versions of the function that aren't polymorphic - they are specific to the types they are called with. You can also tell the compiler to do this with the
SPECIALISE
pragma. As an example, take a factorial function:As the compiler doesn't know any properties of the multiplication that is to be used, it cannot optimize this at all. If however, it sees that it is used on an
Int
, it now can create a new version, differing only in the type:Next, rules mentioned below can fire, and you end up with something working on unboxed
Int
s, which is much faster than the original. Another way to look at specialisation is partial application on type class dictionaries and type variables.The source here has a load of notes in it.
Float out
EDIT: I apparently misunderstood this before. My explanation has completely changed.
The basic idea of this is to move computations that shouldn't be repeated out of functions. For example, suppose we had this:
In the above lambda, every time the function is called,
y
is recomputed. A better function, which floating out produces, isTo facilitate the process, other transformations may be applied. For example, this happens:
Again, repeated computation is saved.
The source is very readable in this case.
At the moment bindings between two adjacent lambdas are not floated. For example, this does not happen:
going to
Float inwards
Quoting the source code,
The main purpose of
floatInwards
is floating into branches of a case, so that we don't allocate things, save them on the stack, and then discover that they aren't needed in the chosen branch.As an example, suppose we had this expression:
If
v
evaluates toFalse
, then by allocatingx
, which is presumably some big thunk, we have wasted time and space. Floating inwards fixes this, producing this:, which is subsequently replaced by the simplifier with
This paper, although covering other topics, gives a fairly clear introduction. Note that despite their names, floating in and floating out don't get in an infinite loop for two reasons:
case
statements, while float out deals with functions.Demand analysis
Demand analysis, or strictness analysis is less of a transformation and more, like the name suggests, of an information gathering pass. The compiler finds functions that always evaluate their arguments (or at least some of them), and passes those arguments using call-by-value, instead of call-by-need. Since you get to evade the overheads of thunks, this is often much faster. Many performance problems in Haskell arise from either this pass failing, or code simply not being strict enough. A simple example is the difference between using
foldr
,foldl
, andfoldl'
to sum a list of integers - the first causes stack overflow, the second causes heap overflow, and the last runs fine, because of strictness. This is probably the easiest to understand and best documented of all of these. I believe that polymorphism and CPS code often defeat this.Worker Wrapper binds
The basic idea of the worker/wrapper transformation is to do a tight loop on a simple structure, converting to and from that structure at the ends. For example, take this function, which calculates the factorial of a number.
Using the definition of
Int
in GHC, we haveNotice how the code is covered in
I#
s? We can remove them by doing this:Although this specific example could have also been done by SpecConstr, the worker/wrapper transformation is very general in the things it can do.
Common sub-expression
This is another really simple optimization that is very effective, like strictness analysis. The basic idea is that if you have two expressions that are the same, they will have the same value. For example, if
fib
is a Fibonacci number calculator, CSE will transforminto
which cuts the computation in half. Unfortunately, this can occasionally get in the way of other optimizations. Another problem is that the two expressions have to be in the same place and that they have to be syntactically the same, not the same by value. For example, CSE won't fire in the following code without a bunch of inlining:
However, if you compile via llvm, you may get some of this combined, due to its Global Value Numbering pass.
Liberate case
This seems to be a terribly documented transformation, besides the fact that it can cause code explosion. Here is a reformatted (and slightly rewritten) version of the little documentation I found:
This module walks over
Core
, and looks forcase
on free variables. The criterion is: if there is acase
on a free variable on the route to the recursive call, then the recursive call is replaced with an unfolding. For example, inthe inner
f
is replaced. to makeNote the need for shadowing. Simplifying, we get
This is better code, because
a
is free inside the innerletrec
, rather than needing projection fromv
. Note that this deals with free variables, unlike SpecConstr, which deals with arguments that are of known form.See below for more information about SpecConstr.
SpecConstr - this transforms programs like
into
As an extended example, take this definition of
last
:We first transform it to
Next, the simplifier runs, and we have
Note that the program is now faster, as we are not repeatedly boxing and unboxing the front of the list. Also note that the inlining is crucial, as it allows the new, more efficient definitions to actually be used, as well as making recursive definitions better.
SpecConstr is controlled by a number of heuristics. The ones mentioned in the paper are as such:
a
.However, the heuristics have almost certainly changed. In fact, the paper mentions an alternative sixth heuristic:
Specialise on an argument
x
only ifx
is only scrutinised by acase
, and is not passed to an ordinary function, or returned as part of the result.This was a very small file (12 lines) and so possibly didn't trigger that many optimizations (though I think it did them all). This also doesn't tell you why it picked those passes and why it put them in that order.