ghc-dump
is a library, GHC plugin, and set of tools for recording and
analysing GHC's Core representation. The plugin is compatible with GHC 7.10
through 8.10, exporting a consistent (albeit somewhat lossy) representation
across these versions. The AST is encoded as CBOR, which is small and easy to
deserialise.
The GHC plugin GhcDump.Plugin
provides a Core-to-Core plugin which dumps a
representation of the Core AST to a file after every Core-to-Core pass. To use
it, first install the ghc-dump-core
package,
$ cabal install ghc-dump-core
And then invoke GHC with the -fplugin GhcDump.Plugin
flag,
$ ghc -fplugin GhcDump.Plugin -dumpdir=dump -O Test.hs
[1 of 1] Compiling Main ( Test.hs, Test.o )
Linking Test ...
$ cd dump
$ ls
Test Test.pass-0011.cbor Test.pass-0017.cbor Test.pass-0006.cbor
Test.hi Test.pass-0012.cbor Test.pass-0001.cbor Test.pass-0007.cbor
Test.hs Test.pass-0013.cbor Test.pass-0002.cbor Test.pass-0008.cbor
Test.o Test.pass-0014.cbor Test.pass-0003.cbor Test.pass-0009.cbor
Test.pass-0000.cbor Test.pass-0015.cbor Test.pass-0004.cbor
Test.pass-0010.cbor Test.pass-0016.cbor Test.pass-0005.cbor
Here we see a pass-N.cbor
file was produced for each Core-to-Core pass.
One can then load this into ghci
for analysis,
$ ghci
GHCi, version 8.3.20170413: http://www.haskell.org/ghc/ :? for help
Loaded GHCi configuration from /home/ben/.ghci
λ> import GhcDump.Repl as Dump
λ> mod <- readDump "Test.pass-0.cbor"
λ> pretty mod
module Main where
nsoln :: Int-> Int
{- Core Size{terms=98 types=66 cos=0 vbinds=0 jbinds=0} -}
nsoln =
λ nq →
let safe =
λ x d ds →
case ds of wild {
[] → GHC.Types.True
: q l →
GHC.Classes.&&
...
Alternatively, the ghc-dump
utility can be used to render the representation
in human-readable form. For instance, we can filter the dump to include only
top-level binders containing main
in its name,
$ ghc-dump show --filter='.*main.*' Test.pass-0.cbor
You can conveniently summarize the top-level bindings of the program,
$ ghc-dump list-bindings --sort=terms Test.pass-0.cbor
Name Terms Types Coerc. Type
nsoln 98 66 0 Int-> Int
main 30 28 0 IO ()
$trModule 5 0 0 Module
main 2 1 0 IO ()
...