# Using GHC

## Getting started: compiling programs

In this chapter you'll find a complete reference to the GHC command-line syntax, including all 400+ flags. It's a large and complex system, and there are lots of details, so it can be quite hard to figure out how to get started. With that in mind, this introductory section provides a quick introduction to the basic usage of GHC for compiling a Haskell program, before the following sections dive into the full syntax.

Let's create a Hello World program, and compile and run it. First, create a file `hello.hs` containing the Haskell code:

    main = putStrLn "Hello, World!"

To compile the program, use GHC like this:

    $ ghc hello.hs

(where `$` represents the prompt: don't type it). GHC will compile the source file `hello.hs`, producing an object file `hello.o` and an interface file `hello.hi`, and then it will link the object file to the libraries that come with GHC to produce an executable called `hello` on Unix/Linux/Mac, or `hello.exe` on Windows.

By default GHC will be very quiet about what it is doing, only printing error messages. If you want to see in more detail what's going on behind the scenes, add `-v` to the command line.

Then we can run the program like this:

    $ ./hello
    Hello World!

If your program contains multiple modules, then you only need to tell GHC the name of the source file containing the `Main` module, and GHC will examine the `import` declarations to find the other modules that make up the program and find their source files. This means that, with the exception of the `Main` module, every source file should be named after the module name that it contains (with dots replaced by directory separators). For example, the module `Data.Person` would be in the file `Data/Person.hs` on Unix/Linux/Mac, or `Data\Person.hs` on Windows.

## Options overview

GHC's behaviour is controlled by options, which for historical reasons are also sometimes referred to as command-line flags or arguments. Options can be specified in three ways:

### Command-line arguments

An invocation of GHC takes the following form:

    ghc [argument...]

Command-line arguments are either options or file names.

Command-line options begin with `-`. They may not be grouped: `-vO` is different from `-v -O`. Options need not precede filenames: e.g., `ghc *.o -o foo`. All options are processed and then applied to all files; you cannot, for example, invoke `ghc -c -O1 Foo.hs -O2 Bar.hs` to apply different optimisation levels to the files `Foo.hs` and `Bar.hs`.

### Command line options in source files

Sometimes it is useful to make the connection between a source file and the command-line options it requires quite tight. For instance, if a Haskell source file deliberately uses name shadowing, it should be compiled with the `-fno-warn-name-shadowing` option. Rather than maintaining the list of per-file options in a `Makefile`, it is possible to do this directly in the source file using the `OPTIONS_GHC` pragma
:

    {-# OPTIONS_GHC -fno-warn-name-shadowing #-}
    module X where
    ...

`OPTIONS_GHC` is a file-header pragma (see ).

Only dynamic flags can be used in an `OPTIONS_GHC` pragma (see ).

Note that your command shell does not get to the source file options, they are just included literally in the array of command-line arguments the compiler maintains internally, so you'll be desperately disappointed if you try to glob etc. inside `OPTIONS_GHC`.

NOTE: the contents of OPTIONS_GHC are appended to the command-line options, so options given in the source file override those given on the command-line.

It is not recommended to move all the contents of your Makefiles into your source files, but in some circumstances, the `OPTIONS_GHC` pragma is the Right Thing. (If you use `-keep-hc-file` and have OPTION flags in your module, the OPTIONS_GHC will get put into the generated .hc file).

### Setting options in GHCi

Options may also be modified from within GHCi, using the `:set` command. See for more details.

## Static, Dynamic, and Mode options

Each of GHC's command line options is classified as static, dynamic or mode:

Mode flags

  For example, `--make` or `-E`. There may only be a single mode flag on the command line. The available modes are listed in .

Dynamic Flags

  Most non-mode flags fall into this category. A dynamic flag may be used on the command line, in a `OPTIONS_GHC` pragma in a source file, or set using `:set` in GHCi.

Static Flags

  A few flags are "static", which means they can only be used on the command-line, and remain in force over the entire GHC/GHCi run.

The flag reference tables () lists the status of each flag.

There are a few flags that are static except that they can also be used with GHCi's `:set` command; these are listed as “static/`:set`” in the table.

## Meaningful file suffixes

File names with “meaningful” suffixes (e.g., `.lhs` or `.o`) cause the “right thing” to happen to those files.

`.hs`

  A Haskell module.

`.lhs`

  A “literate Haskell” module.

`.hspp`

  A file created by the preprocessor.

`.hi`

  A Haskell interface file, probably compiler-generated.

`.hc`

  Intermediate C file produced by the Haskell compiler.

`.c`

  A C file not produced by the Haskell compiler.

`.ll`

  An llvm-intermediate-language source file, usually produced by the compiler.

`.bc`

  An llvm-intermediate-language bitcode file, usually produced by the compiler.

`.s`

  An assembly-language source file, usually produced by the compiler.

`.o`

  An object file, produced by an assembler.

Files with other suffixes (or without suffixes) are passed straight to the linker.

## Modes of operation

GHC's behaviour is firstly controlled by a mode flag. Only one of these flags may be given, but it does not necessarily need to be the first option on the command-line.

If no mode flag is present, then GHC will enter make mode () if there are any Haskell source files given on the command line, or else it will link the objects named on the command line to produce an executable.

The available mode flags are:

    ghc --interactive

  Interactive mode, which is also available as `ghci`. Interactive mode is described in more detail in .

    ghc --make

  In this mode, GHC will build a multi-module Haskell program automatically, figuring out dependencies for itself. If you have a straightforward Haskell program, this is likely to be much easier, and faster, than using `make`. Make mode is described in .

  This mode is the default if there are any Haskell source files mentioned on the command line, and in this case the `--make` option can be omitted.

    ghc -e
                 expr

  Expression-evaluation mode. This is very similar to interactive mode, except that there is a single expression to evaluate (expr) which is given on the command line. See for more details.

                ghc -E
                ghc -C
                ghc -S
                ghc -c

  This is the traditional batch-compiler mode, in which GHC can compile source files one at a time, or link objects together into an executable. See .

                ghc -M

  Dependency-generation mode. In this mode, GHC can be used to generate dependency information suitable for use in a `Makefile`. See .

                ghc --mk-dll

  DLL-creation mode (Windows only). See .

              ghc --help ghc -?

  Cause GHC to spew a long usage message to standard output and then exit.

                ghc --show-iface file

  Read the interface in file and dump it as text to `stdout`. For example `ghc --show-iface M.hi`.

                ghc --supported-extensions
                ghc --supported-languages

  Print the supported language extensions.

                ghc --show-options

  Print the supported command line options. This flag can be used for autocompletion in a shell.

                ghc --info

  Print information about the compiler.

                ghc --version
                ghc -V

  Print a one-line string including GHC's version number.

                ghc --numeric-version

  Print GHC's numeric version number only.

                ghc --print-libdir

  Print the path to GHC's library directory. This is the top of the directory tree containing GHC's libraries, interfaces, and include files (usually something like `/usr/local/lib/ghc-5.04` on Unix). This is the value of `$libdir`
  in the package configuration file (see ).

### Using `ghc` `--make`

In this mode, GHC will build a multi-module Haskell program by following dependencies from one or more root modules (usually just `Main`). For example, if your `Main` module is in a file called `Main.hs`, you could compile and link the program like this:

    ghc --make Main.hs

In fact, GHC enters make mode automatically if there are any Haskell source files on the command line and no other mode is specified, so in this case we could just type

    ghc Main.hs

Any number of source file names or module names may be specified; GHC will figure out all the modules in the program by following the imports from these initial modules. It will then attempt to compile each module which is out of date, and finally, if there is a `Main` module, the program will also be linked into an executable.

The main advantages to using `ghc --make` over traditional `Makefile`s are:

- GHC doesn't have to be restarted for each compilation, which means it can cache information between compilations. Compiling a multi-module program with `ghc --make` can be up to twice as fast as running `ghc` individually on each source file.

- You don't have to write a `Makefile`.

- GHC re-calculates the dependencies each time it is invoked, so the dependencies never get out of sync with the source.

- Using the `-j` flag, you can compile modules in parallel. Specify `-jN` to compile N jobs in parallel.

Any of the command-line options described in the rest of this chapter can be used with `--make`, but note that any options you give on the command line will apply to all the source files compiled, so if you want any options to apply to a single source file only, you'll need to use an `OPTIONS_GHC` pragma (see ).

If the program needs to be linked with additional objects (say, some auxiliary C code), then the object files can be given on the command line and GHC will include them when linking the executable.

For backward compatibility with existing make scripts, when used in combination with `-c`, the linking phase is omitted (same as `--make` `-no-link`).

Note that GHC can only follow dependencies if it has the source file available, so if your program includes a module for which there is no source file, even if you have an object and an interface file for the module, then GHC will complain. The exception to this rule is for package modules, which may or may not have source files.

The source files for the program don't all need to be in the same directory; the `-i` option can be used to add directories to the search path (see ).

### Expression evaluation mode

This mode is very similar to interactive mode, except that there is a single expression to evaluate which is specified on the command line as an argument to the `-e` option:

    ghc -e expr

Haskell source files may be named on the command line, and they will be loaded exactly as in interactive mode. The expression is evaluated in the context of the loaded modules.

For example, to load and run a Haskell program containing a module `Main`, we might say

    ghc -e Main.main Main.hs

or we can just use this mode to evaluate expressions in the context of the `Prelude`:

    $ ghc -e "interact (unlines.map reverse.lines)"
    hello
    olleh

### Batch compiler mode

In batch mode, GHC will compile one or more source files given on the command line.

The first phase to run is determined by each input-file suffix, and the last phase is determined by a flag. If no relevant flag is present, then go all the way through to linking. This table summarises:

Phase of the compilation system | Suffix saying “start here” | Flag saying “stop after” | (suffix of) output file
--- | --- | --- | ---
literate pre-processor | `.lhs` | - | `.hs`
C pre-processor (opt.) | `.hs` (with `-cpp`) | `-E` | `.hspp`
Haskell compiler | `.hs` | `-C`, `-S` | `.hc`, `.s`
C compiler (opt.) | `.hc` or `.c` | `-S` | `.s`
assembler | `.s` | `-c` | `.o`
linker | other | - | `a.out`

Thus, a common invocation would be:

    ghc -c Foo.hs

to compile the Haskell source file `Foo.hs` to an object file `Foo.o`.

Note: What the Haskell compiler proper produces depends on what backend code generator is used. See for more details.

Note: C pre-processing is optional, the `-cpp`
flag turns it on. See for more details.

Note: The option `-E`
runs just the pre-processing passes of the compiler, dumping the result in a file.

Note: The option `-C` is only available when GHC is built in unregisterised mode. See for more details.

#### Overriding the default behaviour for a file

As described above, the way in which a file is processed by GHC depends on its suffix. This behaviour can be overridden using the `-x` option:

`-x` suffix

  Causes all files following this option on the command line to be processed as if they had the suffix suffix. For example, to compile a Haskell module in the file `M.my-hs`, use `ghc -c -x hs M.my-hs`.

## Verbosity options

See also the `--help`, `--version`, `--numeric-version`, and `--print-libdir` modes in .

`-v`

  The `-v` option makes GHC verbose: it reports its version number and shows (on stderr) exactly how it invokes each phase of the compilation system. Moreover, it passes the `-v` flag to most phases; each reports its version number (and possibly some other information).

  Please, oh please, use the `-v` option when reporting bugs! Knowing that you ran the right bits in the right order is always the first thing we want to verify.

`-v` n

  To provide more control over the compiler's verbosity, the `-v` flag takes an optional numeric argument. Specifying `-v` on its own is equivalent to `-v3`, and the other levels have the following meanings:

  `-v0`

    Disable all non-essential messages (this is the default).

  `-v1`

    Minimal verbosity: print one line per compilation (this is the default when `--make` or `--interactive` is on).

  `-v2`

    Print the name of each compilation phase as it is executed. (equivalent to `-dshow-passes`).

  `-v3`

    The same as `-v2`, except that in addition the full command line (if appropriate) for each compilation phase is also printed.

  `-v4`

    The same as `-v3` except that the intermediate program representation after each compilation phase is also printed (excluding preprocessed and C/assembly files).

`--fprint-explicit-foralls, -fprint-explicit-kinds`

  These two flags control the way in which GHC displays types, in error messages and in GHCi. Using `-fprint-explicit-foralls` makes GHC print explicit `forall` quantification at the top level of a type; normally this is suppressed. For example, in GHCi:

      ghci> let f x = x
      ghci> :t f
      f :: a -> a
      ghci> :set -fprint-explicit-foralls
      ghci> :t f
      f :: forall a. a -> a

  However, regardless of the flag setting, the quantifiers are printed under these circumstances:

  - For nested `foralls`, e.g.

        ghci> :t GHC.ST.runST
        GHC.ST.runST :: (forall s. GHC.ST.ST s a) -> a

  - If any of the quantified type variables has a kind that mentions a kind variable, e.g.

        ghci> :i Data.Type.Equality.sym
        Data.Type.Equality.sym ::
          forall (k :: BOX) (a :: k) (b :: k).
          (a Data.Type.Equality.:~: b) -> b Data.Type.Equality.:~: a
                -- Defined in Data.Type.Equality

  Using `-fprint-explicit-kinds` makes GHC print kind arguments in types, which are normally suppressed. This can be important when you are using kind polymorphism. For example:

      ghci> :set -XPolyKinds
      ghci> data T a = MkT
      ghci> :t MkT
      MkT :: forall (k :: BOX) (a :: k). T a
      ghci> :set -fprint-explicit-foralls
      ghci> :t MkT
      MkT :: forall (k :: BOX) (a :: k). T k a

`-ferror-spans`

  Causes GHC to emit the full source span of the syntactic entity relating to an error message. Normally, GHC emits the source location of the start of the syntactic entity only.

  For example:

      test.hs:3:6: parse error on input `where'

  becomes:

      test296.hs:3:6-10: parse error on input `where'

  And multi-line spans are possible too:

      test.hs:(5,4)-(6,7):
          Conflicting definitions for `a'
          Bound at: test.hs:5:4
                    test.hs:6:7
          In the binding group for: a, b, a

  Note that line numbers start counting at one, but column numbers start at zero. This choice was made to follow existing convention (i.e. this is how Emacs does it).

`-H` size

  Set the minimum size of the heap to size. This option is equivalent to `+RTS -Hsize`, see .

`-Rghc-timing`

  Prints a one-line summary of timing statistics for the GHC run. This option is equivalent to `+RTS -tstderr`, see .

&separate;

## Warnings and sanity-checking

GHC has a number of options that select which types of non-fatal error messages, otherwise known as warnings, can be generated during compilation. By default, you get a standard set of warnings which are generally likely to indicate bugs in your program. These are: `-fwarn-overlapping-patterns`, `-fwarn-warnings-deprecations`, `-fwarn-deprecated-flags`, `-fwarn-unrecognised-pragmas`, `-fwarn-pointless-pragmas`, `-fwarn-duplicate-constraints`, `-fwarn-duplicate-exports`, `-fwarn-overflowed-literals`, `-fwarn-empty-enumerations`, `-fwarn-missing-fields`, `-fwarn-missing-methods`, `-fwarn-wrong-do-bind`, `-fwarn-unsupported-calling-conventions`, `-fwarn-dodgy-foreign-imports`, `-fwarn-inline-rule-shadowing`, `-fwarn-unsupported-llvm-version`, `-fwarn-context-quantification`, and `-fwarn-tabs`. The following flags are simple ways to select standard “packages” of warnings:

`-W`:

  Provides the standard warnings plus `-fwarn-unused-binds`, `-fwarn-unused-matches`, `-fwarn-unused-imports`, `-fwarn-incomplete-patterns`, `-fwarn-dodgy-exports`, and `-fwarn-dodgy-imports`.

`-Wall`:

  Turns on all warning options that indicate potentially suspicious code. The warnings that are not enabled by `-Wall` are `-fwarn-incomplete-uni-patterns`, `-fwarn-incomplete-record-updates`, `-fwarn-monomorphism-restriction`, `-fwarn-auto-orphans`, `-fwarn-implicit-prelude`, `-fwarn-missing-local-sigs`, `-fwarn-missing-exported-sigs`, `-fwarn-missing-import-lists` and `-fwarn-identities`.

`-w`:

  Turns off all warnings, including the standard ones and those that `-Wall` doesn't enable.

`-Werror`:

  Makes any warning into a fatal error. Useful so that you don't miss warnings when doing batch compilation.

`-Wwarn`:

  Warnings are treated only as warnings, not as errors. This is the default, but can be useful to negate a `-Werror` flag.

The full set of warning options is described below. To turn off any warning, simply give the corresponding `-fno-warn-...` option on the command line.

`-fwarn-typed-holes`:

  Determines whether the compiler reports typed holes warnings. Has no effect unless typed holes errors are deferred until runtime. See and

  This warning is on by default.

`-fdefer-type-errors`:

  Defer as many type errors as possible until runtime. At compile time you get a warning (instead of an error). At runtime, if you use a value that depends on a type error, you get a runtime error; but you can run any type-correct parts of your code just fine. See

`-fdefer-typed-holes`:

  Defer typed holes errors until runtime. This will turn the errors produced by typed holes into warnings. Using a value that depends on a typed hole produces a runtime error, the same as `-fdefer-type-errors` (which implies this option). See and .

  Implied by `-fdefer-type-errors`. See also `-fwarn-typed-holes`.

`-fwarn-partial-type-signatures`:

  Determines whether the compiler reports holes in partial type signatures as warnings. Has no effect unless `-XPartialTypeSignatures` is enabled, which controls whether errors should be generated for holes in types or not. See .

  This warning is on by default.

`-fhelpful-errors`:

  When a name or package is not found in scope, make suggestions for the name or package you might have meant instead.

  This option is on by default.

`-fwarn-unrecognised-pragmas`:

  Causes a warning to be emitted when a pragma that GHC doesn't recognise is used. As well as pragmas that GHC itself uses, GHC also recognises pragmas known to be used by other tools, e.g. `OPTIONS_HUGS` and `DERIVE`.

  This option is on by default.

`-fwarn-pointless-pragmas`:

  Causes a warning to be emitted when GHC detects that a module contains a pragma that has no effect.

  This option is on by default.

`-fwarn-warnings-deprecations`:

  Causes a warning to be emitted when a module, function or type with a WARNING or DEPRECATED pragma is used. See for more details on the pragmas.

  This option is on by default.

`-fwarn-amp`:

  Causes a warning to be emitted when a definition is in conflict with the AMP (Applicative-Monad proosal), namely: 1. Instance of Monad without Applicative; 2. Instance of MonadPlus without Alternative; 3. Custom definitions of join/pure/<*>

  This option is on by default.

`-fwarn-deprecated-flags`:

  Causes a warning to be emitted when a deprecated commandline flag is used.

  This option is on by default.

`-fwarn-unsupported-calling-conventions`:

  Causes a warning to be emitted for foreign declarations that use unsupported calling conventions. In particular, if the `stdcall` calling convention is used on an architecture other than i386 then it will be treated as `ccall`.

`-fwarn-dodgy-foreign-imports`:

  Causes a warning to be emitted for foreign imports of the following form:

      foreign import "f" f :: FunPtr t

  on the grounds that it probably should be

      foreign import "&f" f :: FunPtr t

  The first form declares that `f` is a (pure) C function that takes no arguments and returns a pointer to a C function with type `t`, whereas the second form declares that `f` itself is a C function with type `t`. The first declaration is usually a mistake, and one that is hard to debug because it results in a crash, hence this warning.

`-fwarn-dodgy-exports`:

  Causes a warning to be emitted when a datatype `T` is exported with all constructors, i.e. `T(..)`, but is it just a type synonym.

  Also causes a warning to be emitted when a module is re-exported, but that module exports nothing.

`-fwarn-dodgy-imports`:

  Causes a warning to be emitted in the following cases:

  - When a datatype `T` is imported with all constructors, i.e. `T(..)`, but has been exported abstractly, i.e. `T`.

  - When an `import` statement hides an entity that is not exported.

`-fwarn-overflowed-literals`:

  Causes a warning to be emitted if a literal will overflow, e.g. `300 :: Word8`.

`-fwarn-empty-enumerations`:

  Causes a warning to be emitted if an enumeration is empty, e.g. `[5 .. 3]`.

`-fwarn-lazy-unlifted-bindings`:

  This flag is a no-op, and will be removed in GHC 7.10.

`-fwarn-duplicate-constraints`:

  Have the compiler warn about duplicate constraints in a type signature. For example

                   f :: (Eq a, Show a, Eq a) => a -> a

  The warning will indicate the duplicated `Eq a` constraint.

  This option is on by default.

`-fwarn-duplicate-exports`:

  Have the compiler warn about duplicate entries in export lists. This is useful information if you maintain large export lists, and want to avoid the continued export of a definition after you've deleted (one) mention of it in the export list.

  This option is on by default.

`-fwarn-hi-shadowing`:

  Causes the compiler to emit a warning when a module or interface file in the current directory is shadowing one with the same module name in a library or other directory.

`-fwarn-identities`:

  Causes the compiler to emit a warning when a Prelude numeric conversion converts a type T to the same type T; such calls are probably no-ops and can be omitted. The functions checked for are: `toInteger`, `toRational`, `fromIntegral`, and `realToFrac`.

`-fwarn-implicit-prelude`:

  Have the compiler warn if the Prelude is implicitly imported. This happens unless either the Prelude module is explicitly imported with an `import ... Prelude ...` line, or this implicit import is disabled (either by `-XNoImplicitPrelude` or a `LANGUAGE NoImplicitPrelude` pragma).

  Note that no warning is given for syntax that implicitly refers to the Prelude, even if `-XNoImplicitPrelude` would change whether it refers to the Prelude. For example, no warning is given when `368` means `Prelude.fromInteger (368::Prelude.Integer)` (where `Prelude` refers to the actual Prelude module, regardless of the imports of the module being compiled).

  This warning is off by default.

`-fwarn-incomplete-patterns`, `-fwarn-incomplete-uni-patterns`:

  The option `-fwarn-incomplete-patterns` warns about places where a pattern-match might fail at runtime. The function `g` below will fail when applied to non-empty lists, so the compiler will emit a warning about this when `-fwarn-incomplete-patterns` is enabled.

      g [] = 2

  This option isn't enabled by default because it can be a bit noisy, and it doesn't always indicate a bug in the program. However, it's generally considered good practice to cover all the cases in your functions, and it is switched on by `-W`.

  The flag `-fwarn-incomplete-uni-patterns` is similar, except that it applies only to lambda-expressions and pattern bindings, constructs that only allow a single pattern:

      h = \[] -> 2
      Just k = f y

`-fwarn-incomplete-record-updates`:

  The function `f` below will fail when applied to `Bar`, so the compiler will emit a warning about this when `-fwarn-incomplete-record-updates` is enabled.

      data Foo = Foo { x :: Int }
               | Bar

      f :: Foo -> Foo
      f foo = foo { x = 6 }

  This option isn't enabled by default because it can be very noisy, and it often doesn't indicate a bug in the program.

`-fwarn-missing-fields`:

  This option is on by default, and warns you whenever the construction of a labelled field constructor isn't complete, missing initializers for one or more fields. While not an error (the missing fields are initialised with bottoms), it is often an indication of a programmer error.

`-fwarn-missing-import-lists`:

  This flag warns if you use an unqualified `import` declaration that does not explicitly list the entities brought into scope. For example

      module M where
        import X( f )
        import Y
        import qualified Z
        p x = f x x

  The `-fwarn-import-lists` flag will warn about the import of `Y` but not `X` If module `Y` is later changed to export (say) `f`, then the reference to `f` in `M` will become ambiguous. No warning is produced for the import of `Z` because extending `Z`'s exports would be unlikely to produce ambiguity in `M`.

`-fwarn-missing-methods`:

  This option is on by default, and warns you whenever an instance declaration is missing one or more methods, and the corresponding class declaration has no default declaration for them.

  The warning is suppressed if the method name begins with an underscore. Here's an example where this is useful:

                    class C a where
                      _simpleFn :: a -> String
                      complexFn :: a -> a -> String
                      complexFn x y = ... _simpleFn ...

  The idea is that: (a) users of the class will only call `complexFn`; never `_simpleFn`; and (b) instance declarations can define either `complexFn` or `_simpleFn`.

  The MINIMAL pragma can be used to change which combination of methods will be required for instances of a particular class. See .

`-fwarn-missing-signatures`:

  If you would like GHC to check that every top-level function/value has a type signature, use the `-fwarn-missing-signatures` option. As part of the warning GHC also reports the inferred type. The option is off by default.

`-fwarn-missing-exported-sigs`:

  If you would like GHC to check that every exported top-level function/value has a type signature, but not check unexported values, use the `-fwarn-missing-exported-sigs` option. This option takes precedence over `-fwarn-missing-signatures`. As part of the warning GHC also reports the inferred type. The option is off by default.

`-fwarn-missing-local-sigs`:

  If you use the `-fwarn-missing-local-sigs` flag GHC will warn you about any polymorphic local bindings. As part of the warning GHC also reports the inferred type. The option is off by default.

`-fwarn-name-shadowing`:

  This option causes a warning to be emitted whenever an inner-scope value has the same name as an outer-scope value, i.e. the inner value shadows the outer one. This can catch typographical errors that turn into hard-to-find bugs, e.g., in the inadvertent capture of what would be a recursive call in `f = ... let f = id in ... f ...`.

  The warning is suppressed for names beginning with an underscore. For example

                   f x = do { _ignore <- this; _ignore <- that; return (the other) }

`-fwarn-orphans, -fwarn-auto-orphans`:

  These flags cause a warning to be emitted whenever the module contains an "orphan" instance declaration or rewrite rule. An instance declaration is an orphan if it appears in a module in which neither the class nor the type being instanced are declared in the same module. A rule is an orphan if it is a rule for a function declared in another module. A module containing any orphans is called an orphan module.

  The trouble with orphans is that GHC must pro-actively read the interface files for all orphan modules, just in case their instances or rules play a role, whether or not the module's interface would otherwise be of any use. See for details.

  The flag `-fwarn-orphans` warns about user-written orphan rules or instances. The flag `-fwarn-auto-orphans` warns about automatically-generated orphan rules, notably as a result of specialising functions, for type classes (`Specialise`) or argument values (`-fspec-constr`).

`-fwarn-overlapping-patterns`:

  By default, the compiler will warn you if a set of patterns are overlapping, e.g.,

      f :: String -> Int
      f []     = 0
      f (_:xs) = 1
      f "2"    = 2

  where the last pattern match in `f` won't ever be reached, as the second pattern overlaps it. More often than not, redundant patterns is a programmer mistake/error, so this option is enabled by default.

`-fwarn-tabs`:

  Have the compiler warn if there are tabs in your source file.

`-fwarn-type-defaults`:

  Have the compiler warn/inform you where in your source the Haskell defaulting mechanism for numeric types kicks in. This is useful information when converting code from a context that assumed one default into one with another, e.g., the ‘default default’ for Haskell 1.4 caused the otherwise unconstrained value `1` to be given the type `Int`, whereas Haskell 98 and later defaults it to `Integer`. This may lead to differences in performance and behaviour, hence the usefulness of being non-silent about this.

  This warning is off by default.

`-fwarn-monomorphism-restriction`:

  Have the compiler warn/inform you where in your source the Haskell Monomorphism Restriction is applied. If applied silently the MR can give rise to unexpected behaviour, so it can be helpful to have an explicit warning that it is being applied.

  This warning is off by default.

`-fwarn-unticked-promoted-constructors`:

  Warn if a promoted data constructor is used without a tick preceding it's name.

  For example:

      data Nat = Succ Nat | Zero

      data Vec n s where
        Nil  :: Vec Zero a
        Cons :: a -> Vec n a -> Vec (Succ n) a

  Will raise two warnings because `Zero` and `Succ` are not written as `'Zero` and `'Succ`.

  This warning is enabled by default in `-Wall` mode.

`-fwarn-unused-binds`:

  Report any function definitions (and local bindings) which are unused. More precisely:

  - Warn if a binding brings into scope a variable that is not used, except if the variable's name starts with an underscore. The "starts-with-underscore" condition provides a way to selectively disable the warning.

    A variable is regarded as "used" if

    - It is exported, or

    - It appears in the right hand side of a binding that binds at least one used variable that is used

    For example

        module A (f) where
        f = let (p,q) = rhs1 in t p  -- Warning about unused q
        t = rhs3                     -- No warning: f is used, and hence so is t
        g = h x                      -- Warning: g unused
        h = rhs2                     -- Warning: h is only used in the right-hand side of another unused binding
        _w = True                    -- No warning: _w starts with an underscore

  - Warn if a pattern binding binds no variables at all, unless it is a lone, possibly-banged, wild-card pattern. For example:

        Just _ = rhs3    -- Warning: unused pattern binding
        (_, _) = rhs4    -- Warning: unused pattern binding
        _  = rhs3        -- No warning: lone wild-card pattern
        !_ = rhs4        -- No warning: banged wild-card pattern; behaves like seq

    The motivation for allowing lone wild-card patterns is they are not very different from `_v = rhs3`, which elicits no warning; and they can be useful to add a type constraint, e.g. `_ = x::Int`. A lone banged wild-card pattern is is useful as an alternative (to `seq`) way to force evaluation.
`-fwarn-unused-imports`:

  Report any modules that are explicitly imported but never used. However, the form `import M()` is never reported as an unused import, because it is a useful idiom for importing instance declarations, which are anonymous in Haskell.

`-fwarn-unused-matches`:

  Report all unused variables which arise from pattern matches, including patterns consisting of a single variable. For instance `f x y = []` would report `x` and `y` as unused. The warning is suppressed if the variable name begins with an underscore, thus:

                     f _x = True

`-fwarn-unused-do-bind`:

  Report expressions occurring in `do` and `mdo` blocks that appear to silently throw information away. For instance `do { mapM popInt xs ; return 10 }` would report the first statement in the `do` block as suspicious, as it has the type `StackM [Int]` and not `StackM ()`, but that `[Int]` value is not bound to anything. The warning is suppressed by explicitly mentioning in the source code that your program is throwing something away:

                     do { _ <- mapM popInt xs ; return 10 }

  Of course, in this particular situation you can do even better:

                     do { mapM_ popInt xs ; return 10 }

`-fwarn-context-quantification`:

  Report if a variable is quantified only due to its presence in a context (see ). For example,

                    type T a = Monad m => a -> f a

  It is recommended to write this polymorphic type as

                    type T a = forall m. Monad m => a -> f a

  instead.
`-fwarn-wrong-do-bind`:

  Report expressions occurring in `do` and `mdo` blocks that appear to lack a binding. For instance `do { return (popInt 10) ; return 10 }` would report the first statement in the `do` block as suspicious, as it has the type `StackM (StackM Int)` (which consists of two nested applications of the same monad constructor), but which is not then "unpacked" by binding the result. The warning is suppressed by explicitly mentioning in the source code that your program is throwing something away:

                     do { _ <- return (popInt 10) ; return 10 }

  For almost all sensible programs this will indicate a bug, and you probably intended to write:

                     do { popInt 10 ; return 10 }

`-fwarn-inline-rule-shadowing`:

  Warn if a rewrite RULE might fail to fire because the function might be inlined before the rule has a chance to fire. See .

If you're feeling really paranoid, the `-dcore-lint` option
is a good choice. It turns on heavyweight intra-pass sanity-checking within GHC. (It checks GHC's sanity, not yours.)

&packages;

## Optimisation (code improvement)

The `-O*` options specify convenient “packages” of optimisation flags; the `-f*` options described later on specify individual optimisations to be turned on/off; the `-m*` options specify machine-specific optimisations to be turned on/off.

### `-O*`: convenient “packages” of optimisation flags.

There are many options that affect the quality of code produced by GHC. Most people only have a general goal, something like “Compile quickly” or “Make my program run like greased lightning.” The following “packages” of optimisations (or lack thereof) should suffice.

Note that higher optimisation levels cause more cross-module optimisation to be performed, which can have an impact on how much of your program needs to be recompiled when you change something. This is one reason to stick to no-optimisation when developing code.

No `-O*`-type option specified:

  This is taken to mean: “Please compile quickly; I'm not over-bothered about compiled-code quality.” So, for example: `ghc -c Foo.hs`

`-O0`:

  Means “turn off all optimisation”, reverting to the same settings as if no `-O` options had been specified. Saying `-O0` can be useful if eg. `make` has inserted a `-O` on the command line already.

`-O` or `-O1`:

  Means: “Generate good-quality code without taking too long about it.” Thus, for example: `ghc -c -O Main.lhs`

`-O2`:

  Means: “Apply every non-dangerous optimisation, even if it means significantly longer compile times.”

  The avoided “dangerous” optimisations are those that can make runtime or space worse if you're unlucky. They are normally turned on or off individually.

  At the moment, `-O2` is unlikely to produce better code than `-O`.

`-Odph`:

  Enables all `-O2` optimisation, sets `-fmax-simplifier-iterations=20` and `-fsimplifier-phases=3`. Designed for use with Data Parallel Haskell (DPH).

We don't use a `-O*` flag for day-to-day work. We use `-O` to get respectable speed; e.g., when we want to measure something. When we want to go for broke, we tend to use `-O2` (and we go for lots of coffee breaks).

The easiest way to see what `-O` (etc.) “really mean” is to run with `-v`, then stand back in amazement.

### `-f*`: platform-independent flags

These flags turn on and off individual optimisations. Flags marked as Enabled by default are enabled by `-O`, and as such you shouldn't need to set any of them explicitly. A flag `-fwombat` can be negated by saying `-fno-wombat`. See for a compact list.

`-fcase-merge`

  On by default. Merge immediately-nested case expressions that scrutinse the same variable. Example

        case x of
           Red -> e1
           _   -> case x of
                    Blue -> e2
                    Green -> e3
      ==>
        case x of
           Red -> e1
           Blue -> e2
           Green -> e2

`-fcall-arity`

  On by default..

`-fcmm-elim-common-blocks`

  On by default.. Enables the common block elimination optimisation in the code generator. This optimisation attempts to find identical Cmm blocks and eliminate the duplicates.

`-fcmm-sink`

  On by default.. Enables the sinking pass in the code generator. This optimisation attempts to find identical Cmm blocks and eliminate the duplicates attempts to move variable bindings closer to their usage sites. It also inlines simple expressions like literals or registers.

`-fcpr-off`

  Switch off CPR analysis in the demand analyser.

`-fcse`

  On by default.. Enables the common-sub-expression elimination optimisation. Switching this off can be useful if you have some `unsafePerformIO` expressions that you don't want commoned-up.

`-fdicts-cheap`

  A very experimental flag that makes dictionary-valued expressions seem cheap to the optimiser.

`-fdicts-strict`

  Make dictionaries strict.

`-fdmd-tx-dict-sel`

  On by default for `-O0`, `-O`, `-O2`.

  Use a special demand transformer for dictionary selectors.

`-fdo-eta-reduction`

  On by default. Eta-reduce lambda expressions, if doing so gets rid of a whole group of lambdas.

`-fdo-lambda-eta-expansion`

  On by default. Eta-expand let-bindings to increase their arity.

`-feager-blackholing`

  Usually GHC black-holes a thunk only when it switches threads. This flag makes it do so as soon as the thunk is entered. See Haskell on a shared-memory multiprocessor.

`-fexcess-precision`

  When this option is given, intermediate floating point values can have a greater precision/range than the final type. Generally this is a good thing, but some programs may rely on the exact precision/range of `Float`/`Double` values and should not use this option for their compilation.

  Note that the 32-bit x86 native code generator only supports excess-precision mode, so neither `-fexcess-precision` nor `-fno-excess-precision` has any effect. This is a known bug, see .

`-fexpose-all-unfoldings`

  An experimental flag to expose all unfoldings, even for very large or recursive functions. This allows for all functions to be inlined while usually GHC would avoid inlining larger functions.

`-ffloat-in`

  On by default. Float let-bindings inwards, nearer their binding site. See Let-floating: moving bindings to give faster programs (ICFP'96).

  This optimisation moves let bindings closer to their use site. The benefit here is that this may avoid unnecessary allocation if the branch the let is now on is never executed. It also enables other optimisation passes to work more effectively as they have more information locally.

  This optimisation isn't always beneficial though (so GHC applies some heuristics to decide when to apply it). The details get complicated but a simple example is that it is often beneficial to move let bindings outwards so that multiple let bindings can be grouped into a larger single let binding, effectively batching their allocation and helping the garbage collector and allocator.

`-ffull-laziness`

  On by default. Run the full laziness optimisation (also known as let-floating), which floats let-bindings outside enclosing lambdas, in the hope they will be thereby be computed less often. See Let-floating: moving bindings to give faster programs (ICFP'96). Full laziness increases sharing, which can lead to increased memory residency.

  NOTE: GHC doesn't implement complete full-laziness. When optimisation in on, and `-fno-full-laziness` is not given, some transformations that increase sharing are performed, such as extracting repeated computations from a loop. These are the same transformations that a fully lazy implementation would do, the difference is that GHC doesn't consistently apply full-laziness, so don't rely on it.

`-ffun-to-thunk`

  Worker-wrapper removes unused arguments, but usually we do not remove them all, lest it turn a function closure into a thunk, thereby perhaps creating a space leak and/or disrupting inlining. This flag allows worker/wrapper to remove all value lambdas. Off by default.

`-fignore-asserts`

  On by default.. Causes GHC to ignore uses of the function `Exception.assert` in source code (in other words, rewriting `Exception.assert p e` to `e` (see ).

`-fignore-interface-pragmas`

  Tells GHC to ignore all inessential information when reading interface files. That is, even if `M.hi` contains unfolding or strictness information for a function, GHC will ignore that information.

`-flate-dmd-anal`

  Run demand analysis again, at the end of the simplification pipeline. We found some opportunities for discovering strictness that were not visible earlier; and optimisations like `-fspec-constr` can create functions with unused arguments which are eliminated by late demand analysis. Improvements are modest, but so is the cost. See notes on the Trac wiki page.

`-fliberate-case`

  Off by default, but enabled by -O2. Turn on the liberate-case transformation. This unrolls recursive function once in its own RHS, to avoid repeated case analysis of free variables. It's a bit like the call-pattern specialiser (`-fspec-constr`) but for free variables rather than arguments.

`-fliberate-case-threshold=n`

  Set the size threshold for the liberate-case transformation. Default: 2000

`-floopification`

  On by default.

  When this optimisation is enabled the code generator will turn all self-recursive saturated tail calls into local jumps rather than function calls.

`-fmax-inline-alloc-size=n`

  Set the maximum size of inline array allocations to n bytes (default: 128). GHC will allocate non-pinned arrays of statically known size in the current nursery block if they're no bigger than n bytes, ignoring GC overheap. This value should be quite a bit smaller than the block size (typically: 4096).

`-fmax-inline-memcpy-insn=n`

  Inline memcpy calls if they would generate no more than n pseudo instructions (default: 32).

`-fmax-inline-memset-insns=n`

  Inline memset calls if they would generate no more than n pseudo instructions (default: 32).

`-fmax-relevant-binds=n`

  The type checker sometimes displays a fragment of the type environment in error messages, but only up to some maximum number, set by this flag. The default is 6. Turning it off with `-fno-max-relevant-bindings` gives an unlimited number. Syntactically top-level bindings are also usually excluded (since they may be numerous), but `-fno-max-relevant-bindings` includes them too.

`-fmax-simplifier-iterations=n`

  Sets the maximal number of iterations for the simplifier. Defult: 4.

`-fmax-worker-args=n`

  If a worker has that many arguments, none will be unpacked anymore (default: 10)

`-fno-opt-coercion`

  Turn off the coercion optimiser.

`-fno-pre-inlining`

  Turn off pre-inlining.

`-fno-state-hack`

  Turn off the "state hack" whereby any lambda with a `State#` token as argument is considered to be single-entry, hence it is considered OK to inline things inside it. This can improve performance of IO and ST monad code, but it runs the risk of reducing sharing.

`-fomit-interface-pragmas`

  Tells GHC to omit all inessential information from the interface file generated for the module being compiled (say M). This means that a module importing M will see only the types of the functions that M exports, but not their unfoldings, strictness info, etc. Hence, for example, no function exported by M will be inlined into an importing module. The benefit is that modules that import M will need to be recompiled less often (only when M's exports change their type, not when they change their implementation).

`-fomit-yields`

  On by default. Tells GHC to omit heap checks when no allocation is being performed. While this improves binary sizes by about 5%, it also means that threads run in tight non-allocating loops will not get preempted in a timely fashion. If it is important to always be able to interrupt such threads, you should turn this optimization off. Consider also recompiling all libraries with this optimization turned off, if you need to guarantee interruptibility.

`-fpedantic-bottoms`

  Make GHC be more precise about its treatment of bottom (but see also `-fno-state-hack`). In particular, stop GHC eta-expanding through a case expression, which is good for performance, but bad if you are using `seq` on partial applications.

`-fregs-graph`

  Off by default due to a performance regression bug. Only applies in combination with the native code generator. Use the graph colouring register allocator for register allocation in the native code generator. By default, GHC uses a simpler, faster linear register allocator. The downside being that the linear register allocator usually generates worse code.

`-fregs-iterative`

  Off by default, only applies in combination with the native code generator. Use the iterative coalescing graph colouring register allocator for register allocation in the native code generator. This is the same register allocator as the `-fregs-graph` one but also enables iterative coalescing during register allocation.

`-fsimplifier-phases=n`

  Set the number of phases for the simplifier (default 2). Ignored with -O0.

`-fsimpl-tick-factor=n`

  GHC's optimiser can diverge if you write rewrite rules ( ) that don't terminate, or (less satisfactorily) if you code up recursion through data types (). To avoid making the compiler fall into an infinite loop, the optimiser carries a "tick count" and stops inlining and applying rewrite rules when this count is exceeded. The limit is set as a multiple of the program size, so bigger programs get more ticks. The `-fsimpl-tick-factor` flag lets you change the multiplier. The default is 100; numbers larger than 100 give more ticks, and numbers smaller than 100 give fewer.

  If the tick-count expires, GHC summarises what simplifier steps it has done; you can use `-fddump-simpl-stats` to generate a much more detailed list. Usually that identifies the loop quite accurately, because some numbers are very large.

`-fspec-constr`

  Off by default, but enabled by -O2. Turn on call-pattern specialisation; see Call-pattern specialisation for Haskell programs.

  This optimisation specializes recursive functions according to their argument "shapes". This is best explained by example so consider:

      last :: [a] -> a
      last [] = error "last"
      last (x : []) = x
      last (x : xs) = last xs

  In this code, once we pass the initial check for an empty list we know that in the recursive case this pattern match is redundant. As such `-fspec-constr` will transform the above code to:

      last :: [a] -> a
      last []       = error "last"
      last (x : xs) = last' x xs
          where
            last' x []       = x
            last' x (y : ys) = last' y ys

  As well avoid unnecessary pattern matching it also helps avoid unnecessary allocation. This applies when a argument is strict in the recursive call to itself but not on the initial entry. As strict recursive branch of the function is created similar to the above example.

  It is also possible for library writers to instruct GHC to perform call-pattern specialisation extremely aggressively. This is necessary for some highly optimized libraries, where we may want to specialize regardless of the number of specialisations, or the size of the code. As an example, consider a simplified use-case from the `vector` library:

      import GHC.Types (SPEC(..))

      foldl :: (a -> b -> a) -> a -> Stream b -> a
      {-# INLINE foldl #-}
      foldl f z (Stream step s _) = foldl_loop SPEC z s
        where
          foldl_loop !sPEC z s = case step s of
                                  Yield x s' -> foldl_loop sPEC (f z x) s'
                                  Skip       -> foldl_loop sPEC z s'
                                  Done       -> z

  Here, after GHC inlines the body of `foldl` to a call site, it will perform call-pattern specialization very aggressively on `foldl_loop` due to the use of `SPEC` in the argument of the loop body. `SPEC` from `GHC.Types` is specifically recognized by the compiler.

  (NB: it is extremely important you use `seq` or a bang pattern on the `SPEC` argument!)

  In particular, after inlining this will expose `f` to the loop body directly, allowing heavy specialisation over the recursive cases.

`-fspec-constr-count=n`

  Set the maximum number of specialisations that will be created for any one function by the SpecConstr transformation (default: 3).

`-fspec-constr-threshold=n`

  Set the size threshold for the SpecConstr transformation (default: 2000).

`-fspecialise`

  On by default. Specialise each type-class-overloaded function defined in this module for the types at which it is called in this module. Also specialise imported functions that have an INLINABLE pragma () for the types at which they are called in this module.

`-fstatic-argument-transformation`

  Turn on the static argument transformation, which turns a recursive function into a non-recursive one with a local recursive loop. See Chapter 7 of Andre Santos's PhD thesis

`-fstrictness`

  On by default.. Switch on the strictness analyser. There is a very old paper about GHC's strictness analyser, Measuring the effectiveness of a simple strictness analyser, but the current one is quite a bit different.

  The strictness analyser figures out when arguments and variables in a function can be treated 'strictly' (that is they are always evaluated in the function at some point). This allow GHC to apply certain optimisations such as unboxing that otherwise don't apply as they change the semantics of the program when applied to lazy arguments.

`-fstrictness-before=n`

  Run an additional strictness analysis before simplifier phase n.

`-funbox-small-strict-fields`:

  On by default.. This option causes all constructor fields which are marked strict (i.e. “!”) and which representation is smaller or equal to the size of a pointer to be unpacked, if possible. It is equivalent to adding an `UNPACK` pragma (see ) to every strict constructor field that fulfils the size restriction.

  For example, the constructor fields in the following data types

      data A = A !Int
      data B = B !A
      newtype C = C B
      data D = D !C

  would all be represented by a single `Int#` (see ) value with `-funbox-small-strict-fields` enabled.

  This option is less of a sledgehammer than `-funbox-strict-fields`: it should rarely make things worse. If you use `-funbox-small-strict-fields` to turn on unboxing by default you can disable it for certain constructor fields using the `NOUNPACK` pragma (see ).

  Note that for consistency `Double`, `Word64`, and `Int64` constructor fields are unpacked on 32-bit platforms, even though they are technically larger than a pointer on those platforms.

`-funbox-strict-fields`:

  This option causes all constructor fields which are marked strict (i.e. “!”) to be unpacked if possible. It is equivalent to adding an `UNPACK` pragma to every strict constructor field (see ).

  This option is a bit of a sledgehammer: it might sometimes make things worse. Selectively unboxing fields by using `UNPACK` pragmas might be better. An alternative is to use `-funbox-strict-fields` to turn on unboxing by default but disable it for certain constructor fields using the `NOUNPACK` pragma (see ).

`-funfolding-creation-threshold=n`:

  (Default: 750) Governs the maximum size that GHC will allow a function unfolding to be. (An unfolding has a “size” that reflects the cost in terms of “code bloat” of expanding (aka inlining) that unfolding at a call site. A bigger function would be assigned a bigger cost.)

  Consequences: (a) nothing larger than this will be inlined (unless it has an INLINE pragma); (b) nothing larger than this will be spewed into an interface file.

  Increasing this figure is more likely to result in longer compile times than faster code. The `-funfolding-use-threshold` is more useful.

`-funfolding-dict-discount=n`:

  Default: 30

`-funfolding-fun-discount=n`:

  Default: 60

`-funfolding-keeness-factor=n`:

  Default: 1.5

`-funfolding-use-threshold=n`

  (Default: 60) This is the magic cut-off figure for unfolding (aka inlining): below this size, a function definition will be unfolded at the call-site, any bigger and it won't. The size computed for a function depends on two things: the actual size of the expression minus any discounts that apply depending on the context into which the expression is to be inlined.

  The difference between this and `-funfolding-creation-threshold` is that this one determines if a function definition will be inlined at a call site. The other option determines if a function definition will be kept around at all for potential inlining.

`-fvectorisation-avoidance`

  Part of Data Parallel Haskell (DPH).

  On by default. Enable the vectorisation avoidance optimisation. This optimisation only works when used in combination with the `-fvectorise` transformation.

  While vectorisation of code using DPH is often a big win, it can also produce worse results for some kinds of code. This optimisation modifies the vectorisation transformation to try to determine if a function would be better of unvectorised and if so, do just that.

`-fvectorise`

  Part of Data Parallel Haskell (DPH).

  Off by default. Enable the vectorisation optimisation transformation. This optimisation transforms the nested data parallelism code of programs using DPH into flat data parallelism. Flat data parallel programs should have better load balancing, enable SIMD parallelism and friendlier cache behaviour.

&code-gens;

&phases;

&shared_libs;

## Using Concurrent Haskell

GHC supports Concurrent Haskell by default, without requiring a special option or libraries compiled in a certain way. To get access to the support libraries for Concurrent Haskell, just import `Control.Concurrent`. More information on Concurrent Haskell is provided in the documentation for that module.

Optionally, the program may be linked with the `-threaded` option (see . This provides two benefits:

- It enables the `-N`
  RTS option to be used, which allows threads to run in parallel
  on a multiprocessor
  or multicore
  machine. See .

- If a thread makes a foreign call (and the call is not marked `unsafe`), then other Haskell threads in the program will continue to run while the foreign call is in progress. Additionally, `foreign export`ed Haskell functions may be called from multiple OS threads simultaneously. See .

The following RTS option(s) affect the behaviour of Concurrent Haskell programs:

`-Cs`

  Sets the context switch interval to s seconds. A context switch will occur at the next heap block allocation after the timer expires (a heap block allocation occurs every 4k of allocation). With `-C0` or `-C`, context switches will occur as often as possible (at every heap block allocation). By default, context switches occur every 20ms.

## Using SMP parallelism

GHC supports running Haskell programs in parallel on an SMP (symmetric multiprocessor).

There's a fine distinction between concurrency and parallelism: parallelism is all about making your program run faster by making use of multiple processors simultaneously. Concurrency, on the other hand, is a means of abstraction: it is a convenient way to structure a program that must respond to multiple asynchronous events.

However, the two terms are certainly related. By making use of multiple CPUs it is possible to run concurrent threads in parallel, and this is exactly what GHC's SMP parallelism support does. But it is also possible to obtain performance improvements with parallelism on programs that do not use concurrency. This section describes how to use GHC to compile and run parallel programs, in we describe the language features that affect parallelism.

### Compile-time options for SMP parallelism

In order to make use of multiple CPUs, your program must be linked with the `-threaded` option (see ). Additionally, the following compiler options affect parallelism:

`-feager-blackholing`

  Blackholing is the act of marking a thunk (lazy computuation) as being under evaluation. It is useful for three reasons: firstly it lets us detect certain kinds of infinite loop (the `NonTermination` exception), secondly it avoids certain kinds of space leak, and thirdly it avoids repeating a computation in a parallel program, because we can tell when a computation is already in progress.

  The option `-feager-blackholing` causes each thunk to be blackholed as soon as evaluation begins. The default is "lazy blackholing", whereby thunks are only marked as being under evaluation when a thread is paused for some reason. Lazy blackholing is typically more efficient (by 1-2&percnt; or so), because most thunks don't need to be blackholed. However, eager blackholing can avoid more repeated computation in a parallel program, and this often turns out to be important for parallelism.

  We recommend compiling any code that is intended to be run in parallel with the `-feager-blackholing` flag.

### RTS options for SMP parallelism

There are two ways to run a program on multiple processors: call `Control.Concurrent.setNumCapabilities` from your program, or use the RTS `-N` option.

`-Nx`

  Use x simultaneous threads when running the program.

  The runtime manages a set of virtual processors, which we call capabilities, the number of which is determined by the `-N` option. Each capability can run one Haskell thread at a time, so the number of capabilities is equal to the number of Haskell threads that can run physically in parallel. A capability is animated by one or more OS threads; the runtime manages a pool of OS threads for each capability, so that if a Haskell thread makes a foreign call (see ) another OS thread can take over that capability.

  Normally x should be chosen to match the number of CPU cores on the machine Whether hyperthreading cores should be counted or not is an open question; please feel free to experiment and let us know what results you find.. For example, on a dual-core machine we would probably use `+RTS -N2 -RTS`.

  Omitting x, i.e. `+RTS -N -RTS`, lets the runtime choose the value of x itself based on how many processors are in your machine.

  Be careful when using all the processors in your machine: if some of your processors are in use by other programs, this can actually harm performance rather than improve it.

  Setting `-N` also has the effect of enabling the parallel garbage collector (see ).

  The current value of the `-N` option is available to the Haskell program via `Control.Concurrent.getNumCapabilities`, and it may be changed while the program is running by calling `Control.Concurrent.setNumCapabilities`.

The following options affect the way the runtime schedules threads on CPUs:

`-qa`

  Use the OS's affinity facilities to try to pin OS threads to CPU cores.

  When this option is enabled, the OS threads for a capability i are bound to the CPU core i using the API provided by the OS for setting thread affinity. e.g. on Linux GHC uses `sched_setaffinity()`.

  Depending on your workload and the other activity on the machine, this may or may not result in a performance improvement. We recommend trying it out and measuring the difference.

`-qm`

  Disable automatic migration for load balancing. Normally the runtime will automatically try to schedule threads across the available CPUs to make use of idle CPUs; this option disables that behaviour. Note that migration only applies to threads; sparks created by `par` are load-balanced separately by work-stealing.

  This option is probably only of use for concurrent programs that explicitly schedule threads onto CPUs with `Control.Concurrent.forkOn`.

### Hints for using SMP parallelism

Add the `-s` RTS option when running the program to see timing stats, which will help to tell you whether your program got faster by using more CPUs or not. If the user time is greater than the elapsed time, then the program used more than one CPU. You should also run the program without `-N` for comparison.

The output of `+RTS -s` tells you how many “sparks” were created and executed during the run of the program (see ), which will give you an idea how well your `par` annotations are working.

GHC's parallelism support has improved in 6.12.1 as a result of much experimentation and tuning in the runtime system. We'd still be interested to hear how well it works for you, and we're also interested in collecting parallel programs to add to our benchmarking suite.

## Platform-specific Flags

Some flags only make sense for particular target platforms.

`-msse2`:

  (x86 only, added in GHC 7.0.1) Use the SSE2 registers and instruction set to implement floating point operations when using the native code generator. This gives a substantial performance improvement for floating point, but the resulting compiled code will only run on processors that support SSE2 (Intel Pentium 4 and later, or AMD Athlon 64 and later). The LLVM backend will also use SSE2 if your processor supports it but detects this automatically so no flag is required.

  SSE2 is unconditionally used on x86-64 platforms.

`-msse4.2`:

  (x86 only, added in GHC 7.4.1) Use the SSE4.2 instruction set to implement some floating point and bit operations when using the native code generator. The resulting compiled code will only run on processors that support SSE4.2 (Intel Core i7 and later). The LLVM backend will also use SSE4.2 if your processor supports it but detects this automatically so no flag is required.

&runtime; &debug; &flags;