Sunday, March 22, 2009

Ease of implementation.

Developing a usable compiler for a high-level language such as Haskell isn't a trivial thing to do. Any effort to trade developer time against CPU time is likely to be a wise choice. In this post I will outline a few attempts to deal with the complexity of LHC in high-level ways. Hopefully the end result won't be too slow.


Case short-circuiting.
Since case expressions in GRIN do not force the evaluation of the scrutinized value, they are usually preceded by a call to 'eval'. Then, after the 'eval' calls have been inlined, case-of-case patterns like this are very common:

do val <- case x of
[] -> unit []
CCons x xs -> unit (CCons x xs)
Ffunc a -> func a
case val of
[] -> jumpToNilCase
CCons x xs -> jumpToConsCase x xs

This is obviously inefficient since the case for Nil and Cons will be scrutinized twice. In the GRIN paper, Boquist deals with this by implementing a case short-circuiting optimization after the GRIN code has been translated to machine code. However, dealing with optimizations on the machine code level is quite a tricky thing to do and I'd much rather implement this optimization in GRIN. By making aggressive use of small functions we can do exactly that:

do case x of
[] -> jumpToNilCase
CCons x xs -> jumpToConsCase x xs
Ffunc a -> do val <- func a; checkCase val

checkCase val =
case val of
[] -> jumpToNilCase
CCons x xs -> jumpToConsCase x xs



Register allocation and tail calls.
Using a fixed calling convention is not necessary for whole-program compilers like LHC. Instead, we choose to create a new calling method for each procedure (this is easier than it sounds).
This has the obvious consequence of requiring the convention for return values to be identical for procedures that invoke each other with tail-calls. This was deemed an unacceptable restriction in the GRIN paper, and all tail-calls were subsequently removed before register allocation took place. Afterwards, another optimization step reintroduced tail-calls where possible.
I believe this is too much trouble for too little gain. The possible performance hit is out-weighed by the ease of implementation and the guarantee of tail-calls.


Simple node layout.
An unevaluated value is represented simply by a function name (or tag) and a fixed number of arguments. This value is then overwritten once it has been evaluated. However, the new value may be bigger than what was allocated to represent the unevaluated function.
One way to deal with this is to have two different node layouts: a fixed size node for small values, and a variable size node for big values. This is the approach taken in the GRIN paper and it understandably adds quite a bit of complexity.
Another method is to use indirections. This trades smaller average node size and ease of implementation against more heap allocations.

Thursday, February 5, 2009

Grin a little.

It has come to my attention that we are not using GRIN to it fullest. More specifically, it seems that the 'eval' and 'update' operations are handled by the RTS. This has unfortunate consequences for both the optimizer and the backend code.
Without an explicit control-flow graph (given by inlining eval/apply), many of our more important transformations cannot be performed. Even worse than the lost optimization opportunities is the increased complexity of the RTS. Dealing with issues of correctness is an annoying distraction from the more enjoyable endeavour of applying optimizations.

Moving away from the magical implementation of 'update' means we have to starting thinking about our memory model. The GRIN paper suggests using a fixed node size with a tail pointer for additional space if necessary. With this scheme we can update common-case nodes without allocating more heap space. However, since we're most likely to encounter complications with respect to concurrency and certain forms of garbage collection, I think a simpler approach is more apt.
Replacing nodes with indirections is very easy to implement, it doesn't clash with any optimizations (the original GRIN approach interfere with fetch movement), and it opens the door for advanced features such as concurrency.

So this is what I'll be working on in the near future. All magic has to be purged from the kingdom so logic and reason can reign supreme.

Tuesday, January 27, 2009

Release notes.

Version 0.6.20090126 has been released. It has been more than a month since our last release and we've made a lot of progress. The code is available from Hackage and can be installed as such:

cabal install lhc -fwith-base

Here's our changelog:
  • Fixed type classes.
  • Better variable ids.
  • Base library reorganization.
  • Better support for non-Linux systems.
  • Removed tagging on Int and Word.
  • Got Control.Arrow and Control.Applicative working by improving the handling of (->) as well as fixing type classes.
  • More extensive testsuite.
  • Lots of code clean-up.
Future effort will be directed at adding Integer support in the base library, improving the efficiency of LHC and restoring control-flow analysis.

Cheers,
The LHC Team.

Sunday, January 25, 2009

Thoughts on a new code generator

Code selection through object code optimization by Davidson and Fraser describes a compiler architecture where instead of taking an AST and optimizing it, then generating code for a target machine, we instead take the AST and immediately generate worst-case instructions which we then subsequently optimize, and then emit into assembly language. These instructions we generate and optimize are called register-transfer lists or RTLs.

RTLs are quite simple - a solitary RTL is just a single abstract machine instruction. A sequence of RTLs might look like so:
t[1] := reg[12]
t[2] := mem[8] * reg[0]
t[3] := t[1] + reg[3]
t[4] := t[2] * 10
An RTL must specify a simple property - the machine invariant, which states that any RTL maps to a single instruction on the target machine.

The compilation process is like so, the input language (for example, C--, GRIN or any AST for that matter) is taken and fed to the code expander which takes the input AST and generates a simple sequence of RTLs representing the AST - no attention at this point is paid to the generated code, and this keeps the code expander's job simple and easy. The code expander, however is a machine-dependent part of the backend - it requires knowledge of the target machine so that it may establish the machine invariant.

After expansion, the code is subsequently optimized using e.g peephole optimization, constant subexpression elimination and dead code elimination. These optimizer parts are machine independent. Every optimization must make sure it does not violate the machine invariant.

After optimization, we perform the task of code emission, it being the only other machine-dependent part of the compiler.

In application to LHC, it is quite obvious a new backend is necessary. I believe this compilation method is applicable and preferable. Combined with whole program analysis, and my plans for a small and simple as possible runtime, this makes the compiler easier to retarget, and I wish for LHC to be a cross-compiler as well. It's obvious C is not the way to go, so minimizing burden on retargeting seems like a good strategy. My inevitable plans are for you to be able to take a haskell application, use LHC to compile it and get nice ASM code for whatever architecture you wish.

The overall structure of the new backend I am thinking of is something like this (drawn very badly using Project Draw):





We will perform as many optimizations as possible on the whole-program while it is in GRIN form, leaving the backend to do the task of peephole optimization/DCE/etc. in a machine-independent way, and then emit assembly code.

On the note of the implementing an optimization engine for which to perform these operations, the approach described in An Applicative Control-flow Graph based on Huet's Zipper seems promising as well. Garbage collection as well needs definite addressing before we can get LHC to compile truly serious programs; this will take a little more time to think and talk about with David. Eventually, we may even look into using Joao Dias' thesis research to automatically generate compiler backends, like I believe GHC HQ wants to do.

Thursday, January 22, 2009

Typeclasses are working, now we're missing a bunch of instances...

Well, I finally figured out why the only two test cases that were working were HelloWorld and Kleisli. The compiler had been implicitly generating a lot of hard-wired instances for Int,Word,CInt, and all their numerous cousins -- but it was generating the methods too late (during conversion from HsSyn language to the E intermediate language) for the methods to be properly associated with their classes (which FrontEnd.Class does before typechecking even properly begins). Since none of us much liked the idea of having all this hardwired into the compiler, we decided that rather than try to adjust the machinery to work with the new handling of methods, we'd rather implement the instances in the library. So, that is what we have to do for every type in the following list:
  • Lhc.Prim.Int
  • Lhc.Basics.Integer
  • Data.Int.Int8
  • Data.Int.Int16
  • Data.Int.Int32
  • Data.Int.Int64
  • Data.Int.IntMax
  • Data.Int.IntPtr
  • Data.Word.Word
  • Data.Word.Word8
  • Data.Word.Word16
  • Data.Word.Word32
  • Data.Word.Word64
  • Data.Word.WordMax
  • Data.Word.WordPtr
  • Foreign.C.Types.CChar
  • Foreign.C.Types.CShort
  • Foreign.C.Types.CInt
  • Foreign.C.Types.CUInt
  • Foreign.C.Types.CSize
  • Foreign.C.Types.CWchar
  • Foreign.C.Types.CWint
  • Foreign.C.Types.CTime

So bear with us if this takes a while to iron out. We have managed to get mini-base to build and many of the tests to run now, though getArgs apparantly doesn't compile yet.

Monday, January 19, 2009

Functions in Haskell.

Function calls in Haskell are typically far more numerous than in more traditional languages. This is in part due to laziness. Being lazy means that functions in Haskell do as little as possible to return a result. So to get all the data you need, you often have to call the functions multiple times.

Consider the following snippet of code:

upto :: Int -> Int -> [Int]
upto from to
= if from > to
then []
else from : upto (from+1) to

Here's what the compiled function would look like:

-- Arguments and results are (usually) kept in registers.
-- We generate a new calling convention for each function.
upto from to
= case from `gtInt` to of
1 -> do -- Return a single tag representing '[]'.
return [CNil]
0 -> do -- Allocate 5 heap cells.
heap <- allocate 5
-- CInt is the constructor for Int.
heap[0] := CInt
heap[1] := from
-- Fupto represents a suspended call to 'upto'.
heap[2] := Fupto
heap[3] := from+1
heap[4] := to
-- Return a node as three separate pieces.
-- &heap[0] is the head of the list and &heap[2] is the tail.
return [CCons, &heap[0], &heap[2]]

As we can see, calling this function will only give us a single node (the node in this case is either a CNil or a CCons with two arguments). We will have to call it again to get more information out of it. For example, fully computing 'upto 1 10' requires 11 calls to 'upto' (10 CCons nodes and 1 CNil).

Looking at the steps in 'upto' shows us that it isn't doing a whole lot. All variables (even arguments and results) are in registers and the data can easily fit in the cache. We could almost say that calling this function is as fast as looping in C. Let's add a bit more code and see what happens:

main = showMyList (upto 1 10)
showMyList [] = return ()
showMyList (x:xs)
= do print x
showMyList xs

The same code, now compiled to our intermediate language:

main = do heap <- allocate 3
heap[0] := Fupto
heap[1] := 1
heap[2] := 10
showMyList &heap[0]

showMyList lst
= do -- Read the arguments to 'upto' from the 'lst' pointer.
Fupto from to <- fetch lst
-- Call 'upto'. The results are kept in registers.
-- 'a' and 'b' are undefined if 't' is CNil.
[t, a, b] <- upto from to
-- Inspect the node tag.
case t of
CNil -> return [CUnit]
CCons -> do -- Call print on 'a'. This call might invoke the garbage collector.
print a
-- Recurse on the tail.
showMyList b


This looks rather well. We could be proud if this was the end. However, there is one thing that we haven't considered: garbage collection. The garbage collector may run when we call 'print' and if it does then the pointer we have in 'b' will no longer be valid.
A common solution is to push 'b' to a stack (which the GC can walk and modify) and reload it after 'print' has returned. However, a stack allocation cost about as much as the call to 'upto' and hence incurs an overhead of nearly 50%.

Fortunately there's a way around this. We can "simply" have the garbage collector update all registers that contain heap pointers. Doing so isn't exactly easy but it does allow us to keep pointers in registers and to avoid all unnecessary stack allocations.
The details of how to accomplish this will have to wait for another time.

Saturday, January 17, 2009

LLVM is great.

It seems that the LLVM crowd have mistaken my blog posts for criticism of LLVM. Let me make it clear that I have nothing but respect for LLVM.

I've previously mentioned that LLVM doesn't support zero-overhead garbage collection. Big deal. It's about the same as saying LLVM doesn't answer whether P=NP. I apparently failed in conveying that this is an unsolved problem in computer science.

Solving this problem isn't as simple as putting heap pointers in registers (although it is required). The real beef lies in determining which registers are heap pointers when it isn't known statically. Determining at run-time which registers are heap pointers is intimately tied to the data model of the high-level language. Doing this well in an agnostic way is an unsolved problem. (Note that pointer tagging is generally avoided).


Several people apparently took it personally when I mentioned writing yet another NCG. Let it be clear that I'd never rewrite any of LLVM nor wish to belittle the effort it takes to write a general compiler. I was merely talking about writing a non-optimizing translator from an extremely limited IR to machine code.


So:
  • LLVM is great. I do not wish to criticise any part of it.
  • What you guys have created is impressive. I do not wish to belittle your efforts.
  • LLVM is not a silver bullet. It does not solve all open questions in the academic world and no one expects it to.