Skip to content

Instantly share code, notes, and snippets.

@monadplus
Last active April 13, 2020 11:50
Show Gist options
  • Save monadplus/f7ee94fbdac2c2a4b8fb20538c2d7c09 to your computer and use it in GitHub Desktop.
Save monadplus/f7ee94fbdac2c2a4b8fb20538c2d7c09 to your computer and use it in GitHub Desktop.
GHC: Inline Pragma
## INLINEABLE vs INLINE
INLINEABLE is prefered. (Source: <https://wiki.haskell.org/Inlining_and_Specialisation>

{-# INLINE ⟨name⟩ #-}

Source: https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#inline-pragma

key_function :: Int -> String -> (Bool, Double)
{-# INLINE key_function #-}

Pointless inline are not applied

map key_function xs
# key_function is not inlined because it's the same as calling the function
map (\x -> body) xs

Only fully applied functions are inlined!

comp1 :: (b -> c) -> (a -> b) -> a -> c
{-# INLINE comp1 #-}
comp1 f g = \x -> f (g x)

comp2 :: (b -> c) -> (a -> b) -> a -> c
{-# INLINE comp2 #-}
comp2 f g x = f (g x)

# INLINED
map (not `comp1` not) xs

# NOT
map (not `comp2` not) xs

We don't optimize before inline (otherwise rewrite rules may not be applied). GHC guarantees to inline precisely the code that you wrote.

{-# INLINABLE ⟨name⟩ #-}

"Feel free to inline me".

That decision is made at the call site, and will therefore be affected by the inlining threshold, optimisation level etc.

{-# NOINLINE ⟨name⟩ #-}

Phase Control

Inlining happens only during runs of the simplifier. Each run of the simplifier has a different phase number; the phase number decreases towards zero.

  • INLINE[k] f means: do not inline f until phase k, but from phase k onwards be very keen to inline it.

  • INLINE[~k] f means: be very keen to inline f until phase k, but from phase k onwards do not inline it.

The same phase-numbering control is available for RULEs (Rewrite rules).

You usually want to INLINE before REWRITE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment