{-
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998

\section[Specialise]{Stamping out overloading, and (optionally) polymorphism}
-}

{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE ViewPatterns #-}
module Specialise ( specProgram, specUnfolding ) where

#include "HsVersions.h"

import GhcPrelude

import Id
import TcType hiding( substTy )
import Type   hiding( substTy, extendTvSubstList )
import Predicate
import Module( Module, HasModule(..) )
import Coercion( Coercion )
import CoreMonad
import qualified CoreSubst as Core
import CoreUnfold
import Var              ( isLocalVar )
import VarSet
import VarEnv
import CoreSyn
import Rules
import CoreOpt          ( collectBindersPushingCo )
import CoreUtils        ( exprIsTrivial, mkCast, exprType, getIdFromTrivialExpr_maybe )
import CoreFVs
import CoreArity        ( etaExpandToJoinPointRule )
import UniqSupply
import Name
import MkId             ( voidArgId, voidPrimId )
import TysPrim            ( voidPrimTy )
import Maybes           ( mapMaybe, maybeToList, isJust )
import MonadUtils       ( foldlM )
import BasicTypes
import HscTypes
import Bag
import DynFlags
import Util
import Outputable
import FastString
import State
import UniqDFM
import TyCoRep (TyCoBinder (..))

import Control.Monad
import qualified Control.Monad.Fail as MonadFail

{-
************************************************************************
*                                                                      *
\subsection[notes-Specialise]{Implementation notes [SLPJ, Aug 18 1993]}
*                                                                      *
************************************************************************

These notes describe how we implement specialisation to eliminate
overloading.

The specialisation pass works on Core
syntax, complete with all the explicit dictionary application,
abstraction and construction as added by the type checker.  The
existing type checker remains largely as it is.

One important thought: the {\em types} passed to an overloaded
function, and the {\em dictionaries} passed are mutually redundant.
If the same function is applied to the same type(s) then it is sure to
be applied to the same dictionary(s)---or rather to the same {\em
values}.  (The arguments might look different but they will evaluate
to the same value.)

Second important thought: we know that we can make progress by
treating dictionary arguments as static and worth specialising on.  So
we can do without binding-time analysis, and instead specialise on
dictionary arguments and no others.

The basic idea
~~~~~~~~~~~~~~
Suppose we have

        let f = <f_rhs>
        in <body>

and suppose f is overloaded.

STEP 1: CALL-INSTANCE COLLECTION

We traverse <body>, accumulating all applications of f to types and
dictionaries.

(Might there be partial applications, to just some of its types and
dictionaries?  In principle yes, but in practice the type checker only
builds applications of f to all its types and dictionaries, so partial
applications could only arise as a result of transformation, and even
then I think it's unlikely.  In any case, we simply don't accumulate such
partial applications.)


STEP 2: EQUIVALENCES

So now we have a collection of calls to f:
        f t1 t2 d1 d2
        f t3 t4 d3 d4
        ...
Notice that f may take several type arguments.  To avoid ambiguity, we
say that f is called at type t1/t2 and t3/t4.

We take equivalence classes using equality of the *types* (ignoring
the dictionary args, which as mentioned previously are redundant).

STEP 3: SPECIALISATION

For each equivalence class, choose a representative (f t1 t2 d1 d2),
and create a local instance of f, defined thus:

        f@t1/t2 = <f_rhs> t1 t2 d1 d2

f_rhs presumably has some big lambdas and dictionary lambdas, so lots
of simplification will now result.  However we don't actually *do* that
simplification.  Rather, we leave it for the simplifier to do.  If we
*did* do it, though, we'd get more call instances from the specialised
RHS.  We can work out what they are by instantiating the call-instance
set from f's RHS with the types t1, t2.

Add this new id to f's IdInfo, to record that f has a specialised version.

Before doing any of this, check that f's IdInfo doesn't already
tell us about an existing instance of f at the required type/s.
(This might happen if specialisation was applied more than once, or
it might arise from user SPECIALIZE pragmas.)

Recursion
~~~~~~~~~
Wait a minute!  What if f is recursive?  Then we can't just plug in
its right-hand side, can we?

But it's ok.  The type checker *always* creates non-recursive definitions
for overloaded recursive functions.  For example:

        f x = f (x+x)           -- Yes I know its silly

becomes

        f a (d::Num a) = let p = +.sel a d
                         in
                         letrec fl (y::a) = fl (p y y)
                         in
                         fl

We still have recursion for non-overloaded functions which we
specialise, but the recursive call should get specialised to the
same recursive version.


Polymorphism 1
~~~~~~~~~~~~~~

All this is crystal clear when the function is applied to *constant
types*; that is, types which have no type variables inside.  But what if
it is applied to non-constant types?  Suppose we find a call of f at type
t1/t2.  There are two possibilities:

(a) The free type variables of t1, t2 are in scope at the definition point
of f.  In this case there's no problem, we proceed just as before.  A common
example is as follows.  Here's the Haskell:

        g y = let f x = x+x
              in f y + f y

After typechecking we have

        g a (d::Num a) (y::a) = let f b (d'::Num b) (x::b) = +.sel b d' x x
                                in +.sel a d (f a d y) (f a d y)

Notice that the call to f is at type type "a"; a non-constant type.
Both calls to f are at the same type, so we can specialise to give:

        g a (d::Num a) (y::a) = let f@a (x::a) = +.sel a d x x
                                in +.sel a d (f@a y) (f@a y)


(b) The other case is when the type variables in the instance types
are *not* in scope at the definition point of f.  The example we are
working with above is a good case.  There are two instances of (+.sel a d),
but "a" is not in scope at the definition of +.sel.  Can we do anything?
Yes, we can "common them up", a sort of limited common sub-expression deal.
This would give:

        g a (d::Num a) (y::a) = let +.sel@a = +.sel a d
                                    f@a (x::a) = +.sel@a x x
                                in +.sel@a (f@a y) (f@a y)

This can save work, and can't be spotted by the type checker, because
the two instances of +.sel weren't originally at the same type.

Further notes on (b)

* There are quite a few variations here.  For example, the defn of
  +.sel could be floated ouside the \y, to attempt to gain laziness.
  It certainly mustn't be floated outside the \d because the d has to
  be in scope too.

* We don't want to inline f_rhs in this case, because
that will duplicate code.  Just commoning up the call is the point.

* Nothing gets added to +.sel's IdInfo.

* Don't bother unless the equivalence class has more than one item!

Not clear whether this is all worth it.  It is of course OK to
simply discard call-instances when passing a big lambda.

Polymorphism 2 -- Overloading
~~~~~~~~~~~~~~
Consider a function whose most general type is

        f :: forall a b. Ord a => [a] -> b -> b

There is really no point in making a version of g at Int/Int and another
at Int/Bool, because it's only instantiating the type variable "a" which
buys us any efficiency. Since g is completely polymorphic in b there
ain't much point in making separate versions of g for the different
b types.

That suggests that we should identify which of g's type variables
are constrained (like "a") and which are unconstrained (like "b").
Then when taking equivalence classes in STEP 2, we ignore the type args
corresponding to unconstrained type variable.  In STEP 3 we make
polymorphic versions.  Thus:

        f@t1/ = /\b -> <f_rhs> t1 b d1 d2

We do this.


Dictionary floating
~~~~~~~~~~~~~~~~~~~
Consider this

        f a (d::Num a) = let g = ...
                         in
                         ...(let d1::Ord a = Num.Ord.sel a d in g a d1)...

Here, g is only called at one type, but the dictionary isn't in scope at the
definition point for g.  Usually the type checker would build a
definition for d1 which enclosed g, but the transformation system
might have moved d1's defn inward.  Solution: float dictionary bindings
outwards along with call instances.

Consider

        f x = let g p q = p==q
                  h r s = (r+s, g r s)
              in
              h x x


Before specialisation, leaving out type abstractions we have

        f df x = let g :: Eq a => a -> a -> Bool
                     g dg p q = == dg p q
                     h :: Num a => a -> a -> (a, Bool)
                     h dh r s = let deq = eqFromNum dh
                                in (+ dh r s, g deq r s)
              in
              h df x x

After specialising h we get a specialised version of h, like this:

                    h' r s = let deq = eqFromNum df
                             in (+ df r s, g deq r s)

But we can't naively make an instance for g from this, because deq is not in scope
at the defn of g.  Instead, we have to float out the (new) defn of deq
to widen its scope.  Notice that this floating can't be done in advance -- it only
shows up when specialisation is done.

User SPECIALIZE pragmas
~~~~~~~~~~~~~~~~~~~~~~~
Specialisation pragmas can be digested by the type checker, and implemented
by adding extra definitions along with that of f, in the same way as before

        f@t1/t2 = <f_rhs> t1 t2 d1 d2

Indeed the pragmas *have* to be dealt with by the type checker, because
only it knows how to build the dictionaries d1 and d2!  For example

        g :: Ord a => [a] -> [a]
        {-# SPECIALIZE f :: [Tree Int] -> [Tree Int] #-}

Here, the specialised version of g is an application of g's rhs to the
Ord dictionary for (Tree Int), which only the type checker can conjure
up.  There might not even *be* one, if (Tree Int) is not an instance of
Ord!  (All the other specialision has suitable dictionaries to hand
from actual calls.)

Problem.  The type checker doesn't have to hand a convenient <f_rhs>, because
it is buried in a complex (as-yet-un-desugared) binding group.
Maybe we should say

        f@t1/t2 = f* t1 t2 d1 d2

where f* is the Id f with an IdInfo which says "inline me regardless!".
Indeed all the specialisation could be done in this way.
That in turn means that the simplifier has to be prepared to inline absolutely
any in-scope let-bound thing.


Again, the pragma should permit polymorphism in unconstrained variables:

        h :: Ord a => [a] -> b -> b
        {-# SPECIALIZE h :: [Int] -> b -> b #-}

We *insist* that all overloaded type variables are specialised to ground types,
(and hence there can be no context inside a SPECIALIZE pragma).
We *permit* unconstrained type variables to be specialised to
        - a ground type
        - or left as a polymorphic type variable
but nothing in between.  So

        {-# SPECIALIZE h :: [Int] -> [c] -> [c] #-}

is *illegal*.  (It can be handled, but it adds complication, and gains the
programmer nothing.)


SPECIALISING INSTANCE DECLARATIONS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider

        instance Foo a => Foo [a] where
                ...
        {-# SPECIALIZE instance Foo [Int] #-}

The original instance decl creates a dictionary-function
definition:

        dfun.Foo.List :: forall a. Foo a -> Foo [a]

The SPECIALIZE pragma just makes a specialised copy, just as for
ordinary function definitions:

        dfun.Foo.List@Int :: Foo [Int]
        dfun.Foo.List@Int = dfun.Foo.List Int dFooInt

The information about what instance of the dfun exist gets added to
the dfun's IdInfo in the same way as a user-defined function too.


Automatic instance decl specialisation?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Can instance decls be specialised automatically?  It's tricky.
We could collect call-instance information for each dfun, but
then when we specialised their bodies we'd get new call-instances
for ordinary functions; and when we specialised their bodies, we might get
new call-instances of the dfuns, and so on.  This all arises because of
the unrestricted mutual recursion between instance decls and value decls.

Still, there's no actual problem; it just means that we may not do all
the specialisation we could theoretically do.

Furthermore, instance decls are usually exported and used non-locally,
so we'll want to compile enough to get those specialisations done.

Lastly, there's no such thing as a local instance decl, so we can
survive solely by spitting out *usage* information, and then reading that
back in as a pragma when next compiling the file.  So for now,
we only specialise instance decls in response to pragmas.


SPITTING OUT USAGE INFORMATION
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To spit out usage information we need to traverse the code collecting
call-instance information for all imported (non-prelude?) functions
and data types. Then we equivalence-class it and spit it out.

This is done at the top-level when all the call instances which escape
must be for imported functions and data types.

*** Not currently done ***


Partial specialisation by pragmas
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What about partial specialisation:

        k :: (Ord a, Eq b) => [a] -> b -> b -> [a]
        {-# SPECIALIZE k :: Eq b => [Int] -> b -> b -> [a] #-}

or even

        {-# SPECIALIZE k :: Eq b => [Int] -> [b] -> [b] -> [a] #-}

Seems quite reasonable.  Similar things could be done with instance decls:

        instance (Foo a, Foo b) => Foo (a,b) where
                ...
        {-# SPECIALIZE instance Foo a => Foo (a,Int) #-}
        {-# SPECIALIZE instance Foo b => Foo (Int,b) #-}

Ho hum.  Things are complex enough without this.  I pass.


Requirements for the simplifier
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The simplifier has to be able to take advantage of the specialisation.

* When the simplifier finds an application of a polymorphic f, it looks in
f's IdInfo in case there is a suitable instance to call instead.  This converts

        f t1 t2 d1 d2   ===>   f_t1_t2

Note that the dictionaries get eaten up too!

* Dictionary selection operations on constant dictionaries must be
  short-circuited:

        +.sel Int d     ===>  +Int

The obvious way to do this is in the same way as other specialised
calls: +.sel has inside it some IdInfo which tells that if it's applied
to the type Int then it should eat a dictionary and transform to +Int.

In short, dictionary selectors need IdInfo inside them for constant
methods.

* Exactly the same applies if a superclass dictionary is being
  extracted:

        Eq.sel Int d   ===>   dEqInt

* Something similar applies to dictionary construction too.  Suppose
dfun.Eq.List is the function taking a dictionary for (Eq a) to
one for (Eq [a]).  Then we want

        dfun.Eq.List Int d      ===> dEq.List_Int

Where does the Eq [Int] dictionary come from?  It is built in
response to a SPECIALIZE pragma on the Eq [a] instance decl.

In short, dfun Ids need IdInfo with a specialisation for each
constant instance of their instance declaration.

All this uses a single mechanism: the SpecEnv inside an Id


What does the specialisation IdInfo look like?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The SpecEnv of an Id maps a list of types (the template) to an expression

        [Type]  |->  Expr

For example, if f has this RuleInfo:

        [Int, a]  ->  \d:Ord Int. f' a

it means that we can replace the call

        f Int t  ===>  (\d. f' t)

This chucks one dictionary away and proceeds with the
specialised version of f, namely f'.


What can't be done this way?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is no way, post-typechecker, to get a dictionary for (say)
Eq a from a dictionary for Eq [a].  So if we find

        ==.sel [t] d

we can't transform to

        eqList (==.sel t d')

where
        eqList :: (a->a->Bool) -> [a] -> [a] -> Bool

Of course, we currently have no way to automatically derive
eqList, nor to connect it to the Eq [a] instance decl, but you
can imagine that it might somehow be possible.  Taking advantage
of this is permanently ruled out.

Still, this is no great hardship, because we intend to eliminate
overloading altogether anyway!

A note about non-tyvar dictionaries
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some Ids have types like

        forall a,b,c. Eq a -> Ord [a] -> tau

This seems curious at first, because we usually only have dictionary
args whose types are of the form (C a) where a is a type variable.
But this doesn't hold for the functions arising from instance decls,
which sometimes get arguments with types of form (C (T a)) for some
type constructor T.

Should we specialise wrt this compound-type dictionary?  We used to say
"no", saying:
        "This is a heuristic judgement, as indeed is the fact that we
        specialise wrt only dictionaries.  We choose *not* to specialise
        wrt compound dictionaries because at the moment the only place
        they show up is in instance decls, where they are simply plugged
        into a returned dictionary.  So nothing is gained by specialising
        wrt them."

But it is simpler and more uniform to specialise wrt these dicts too;
and in future GHC is likely to support full fledged type signatures
like
        f :: Eq [(a,b)] => ...


************************************************************************
*                                                                      *
\subsubsection{The new specialiser}
*                                                                      *
************************************************************************

Our basic game plan is this.  For let(rec) bound function
        f :: (C a, D c) => (a,b,c,d) -> Bool

* Find any specialised calls of f, (f ts ds), where
  ts are the type arguments t1 .. t4, and
  ds are the dictionary arguments d1 .. d2.

* Add a new definition for f1 (say):

        f1 = /\ b d -> (..body of f..) t1 b t3 d d1 d2

  Note that we abstract over the unconstrained type arguments.

* Add the mapping

        [t1,b,t3,d]  |->  \d1 d2 -> f1 b d

  to the specialisations of f.  This will be used by the
  simplifier to replace calls
                (f t1 t2 t3 t4) da db
  by
                (\d1 d1 -> f1 t2 t4) da db

  All the stuff about how many dictionaries to discard, and what types
  to apply the specialised function to, are handled by the fact that the
  SpecEnv contains a template for the result of the specialisation.

We don't build *partial* specialisations for f.  For example:

  f :: Eq a => a -> a -> Bool
  {-# SPECIALISE f :: (Eq b, Eq c) => (b,c) -> (b,c) -> Bool #-}

Here, little is gained by making a specialised copy of f.
There's a distinct danger that the specialised version would
first build a dictionary for (Eq b, Eq c), and then select the (==)
method from it!  Even if it didn't, not a great deal is saved.

We do, however, generate polymorphic, but not overloaded, specialisations:

  f :: Eq a => [a] -> b -> b -> b
  ... SPECIALISE f :: [Int] -> b -> b -> b ...

Hence, the invariant is this:

        *** no specialised version is overloaded ***


************************************************************************
*                                                                      *
\subsubsection{The exported function}
*                                                                      *
************************************************************************
-}

-- | Specialise calls to type-class overloaded functions occuring in a program.
specProgram :: ModGuts -> CoreM ModGuts
specProgram :: ModGuts -> CoreM ModGuts
specProgram guts :: ModGuts
guts@(ModGuts { mg_module :: ModGuts -> Module
mg_module = Module
this_mod
                          , mg_rules :: ModGuts -> [CoreRule]
mg_rules = [CoreRule]
local_rules
                          , mg_binds :: ModGuts -> CoreProgram
mg_binds = CoreProgram
binds })
  = do { DynFlags
dflags <- CoreM DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags

             -- Specialise the bindings of this module
       ; (CoreProgram
binds', UsageDetails
uds) <- DynFlags
-> Module
-> SpecM (CoreProgram, UsageDetails)
-> CoreM (CoreProgram, UsageDetails)
forall a. DynFlags -> Module -> SpecM a -> CoreM a
runSpecM DynFlags
dflags Module
this_mod (CoreProgram -> SpecM (CoreProgram, UsageDetails)
go CoreProgram
binds)

             -- Specialise imported functions
       ; RuleBase
hpt_rules <- CoreM RuleBase
getRuleBase
       ; let rule_base :: RuleBase
rule_base = RuleBase -> [CoreRule] -> RuleBase
extendRuleBaseList RuleBase
hpt_rules [CoreRule]
local_rules
       ; ([CoreRule]
new_rules, CoreProgram
spec_binds) <- DynFlags
-> Module
-> SpecEnv
-> VarSet
-> [Id]
-> RuleBase
-> UsageDetails
-> CoreM ([CoreRule], CoreProgram)
specImports DynFlags
dflags Module
this_mod SpecEnv
top_env VarSet
emptyVarSet
                                                [] RuleBase
rule_base UsageDetails
uds

       ; let final_binds :: CoreProgram
final_binds
               | CoreProgram -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null CoreProgram
spec_binds = CoreProgram
binds'
               | Bool
otherwise       = [(Id, Expr Id)] -> Bind Id
forall b. [(b, Expr b)] -> Bind b
Rec (CoreProgram -> [(Id, Expr Id)]
forall b. [Bind b] -> [(b, Expr b)]
flattenBinds CoreProgram
spec_binds) Bind Id -> CoreProgram -> CoreProgram
forall a. a -> [a] -> [a]
: CoreProgram
binds'
                   -- Note [Glom the bindings if imported functions are specialised]

       ; ModGuts -> CoreM ModGuts
forall (m :: * -> *) a. Monad m => a -> m a
return (ModGuts
guts { mg_binds :: CoreProgram
mg_binds = CoreProgram
final_binds
                      , mg_rules :: [CoreRule]
mg_rules = [CoreRule]
new_rules [CoreRule] -> [CoreRule] -> [CoreRule]
forall a. [a] -> [a] -> [a]
++ [CoreRule]
local_rules }) }
  where
        -- We need to start with a Subst that knows all the things
        -- that are in scope, so that the substitution engine doesn't
        -- accidentally re-use a unique that's already in use
        -- Easiest thing is to do it all at once, as if all the top-level
        -- decls were mutually recursive
    top_env :: SpecEnv
top_env = SE :: Subst -> VarSet -> SpecEnv
SE { se_subst :: Subst
se_subst = InScopeSet -> Subst
Core.mkEmptySubst (InScopeSet -> Subst) -> InScopeSet -> Subst
forall a b. (a -> b) -> a -> b
$ VarSet -> InScopeSet
mkInScopeSet (VarSet -> InScopeSet) -> VarSet -> InScopeSet
forall a b. (a -> b) -> a -> b
$ [Id] -> VarSet
mkVarSet ([Id] -> VarSet) -> [Id] -> VarSet
forall a b. (a -> b) -> a -> b
$
                              CoreProgram -> [Id]
forall b. [Bind b] -> [b]
bindersOfBinds CoreProgram
binds
                 , se_interesting :: VarSet
se_interesting = VarSet
emptyVarSet }

    go :: CoreProgram -> SpecM (CoreProgram, UsageDetails)
go []           = (CoreProgram, UsageDetails) -> SpecM (CoreProgram, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ([], UsageDetails
emptyUDs)
    go (Bind Id
bind:CoreProgram
binds) = do (CoreProgram
binds', UsageDetails
uds) <- CoreProgram -> SpecM (CoreProgram, UsageDetails)
go CoreProgram
binds
                         (CoreProgram
bind', UsageDetails
uds') <- SpecEnv
-> Bind Id -> UsageDetails -> SpecM (CoreProgram, UsageDetails)
specBind SpecEnv
top_env Bind Id
bind UsageDetails
uds
                         (CoreProgram, UsageDetails) -> SpecM (CoreProgram, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return (CoreProgram
bind' CoreProgram -> CoreProgram -> CoreProgram
forall a. [a] -> [a] -> [a]
++ CoreProgram
binds', UsageDetails
uds')

{-
Note [Wrap bindings returned by specImports]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'specImports' returns a set of specialized bindings. However, these are lacking
necessary floated dictionary bindings, which are returned by
UsageDetails(ud_binds). These dictionaries need to be brought into scope with
'wrapDictBinds' before the bindings returned by 'specImports' can be used. See,
for instance, the 'specImports' call in 'specProgram'.


Note [Disabling cross-module specialisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Since GHC 7.10 we have performed specialisation of INLINABLE bindings living
in modules outside of the current module. This can sometimes uncover user code
which explodes in size when aggressively optimized. The
-fno-cross-module-specialise option was introduced to allow users to being
bitten by such instances to revert to the pre-7.10 behavior.

See #10491
-}


{- *********************************************************************
*                                                                      *
                   Specialising imported functions
*                                                                      *
********************************************************************* -}

-- | Specialise a set of calls to imported bindings
specImports :: DynFlags
            -> Module
            -> SpecEnv          -- Passed in so that all top-level Ids are in scope
            -> VarSet           -- Don't specialise these ones
                                -- See Note [Avoiding recursive specialisation]
            -> [Id]             -- Stack of imported functions being specialised
            -> RuleBase         -- Rules from this module and the home package
                                -- (but not external packages, which can change)
            -> UsageDetails     -- Calls for imported things, and floating bindings
            -> CoreM ( [CoreRule]   -- New rules
                     , [CoreBind] ) -- Specialised bindings
                                    -- See Note [Wrapping bindings returned by specImports]
specImports :: DynFlags
-> Module
-> SpecEnv
-> VarSet
-> [Id]
-> RuleBase
-> UsageDetails
-> CoreM ([CoreRule], CoreProgram)
specImports DynFlags
dflags Module
this_mod SpecEnv
top_env VarSet
done [Id]
callers RuleBase
rule_base
            (MkUD { ud_binds :: UsageDetails -> Bag DictBind
ud_binds = Bag DictBind
dict_binds, ud_calls :: UsageDetails -> CallDetails
ud_calls = CallDetails
calls })
  -- See Note [Disabling cross-module specialisation]
  | Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_CrossModuleSpecialise DynFlags
dflags
  = ([CoreRule], CoreProgram) -> CoreM ([CoreRule], CoreProgram)
forall (m :: * -> *) a. Monad m => a -> m a
return ([], [])

  | Bool
otherwise
  = do { let import_calls :: [CallInfoSet]
import_calls = CallDetails -> [CallInfoSet]
forall a. DVarEnv a -> [a]
dVarEnvElts CallDetails
calls
       ; ([CoreRule]
rules, CoreProgram
spec_binds) <- RuleBase -> [CallInfoSet] -> CoreM ([CoreRule], CoreProgram)
go RuleBase
rule_base [CallInfoSet]
import_calls

             -- Don't forget to wrap the specialized bindings with
             -- bindings for the needed dictionaries.
             -- See Note [Wrap bindings returned by specImports]
       ; let spec_binds' :: CoreProgram
spec_binds' = Bag DictBind -> CoreProgram -> CoreProgram
wrapDictBinds Bag DictBind
dict_binds CoreProgram
spec_binds

       ; ([CoreRule], CoreProgram) -> CoreM ([CoreRule], CoreProgram)
forall (m :: * -> *) a. Monad m => a -> m a
return ([CoreRule]
rules, CoreProgram
spec_binds') }
  where
    go :: RuleBase -> [CallInfoSet] -> CoreM ([CoreRule], [CoreBind])
    go :: RuleBase -> [CallInfoSet] -> CoreM ([CoreRule], CoreProgram)
go RuleBase
_ [] = ([CoreRule], CoreProgram) -> CoreM ([CoreRule], CoreProgram)
forall (m :: * -> *) a. Monad m => a -> m a
return ([], [])
    go RuleBase
rb (cis :: CallInfoSet
cis@(CIS Id
fn Bag CallInfo
_) : [CallInfoSet]
other_calls)
      = do { let ok_calls :: [CallInfo]
ok_calls = CallInfoSet -> Bag DictBind -> [CallInfo]
filterCalls CallInfoSet
cis Bag DictBind
dict_binds
                     -- Drop calls that (directly or indirectly) refer to fn
                     -- See Note [Avoiding loops]
--           ; debugTraceMsg (text "specImport" <+> vcat [ ppr fn
--                                                       , text "calls" <+> ppr cis
--                                                       , text "ud_binds =" <+> ppr dict_binds
--                                                       , text "dump set =" <+> ppr dump_set
--                                                       , text "filtered calls =" <+> ppr ok_calls ])
           ; ([CoreRule]
rules1, CoreProgram
spec_binds1) <- DynFlags
-> Module
-> SpecEnv
-> VarSet
-> [Id]
-> RuleBase
-> Id
-> [CallInfo]
-> CoreM ([CoreRule], CoreProgram)
specImport DynFlags
dflags Module
this_mod SpecEnv
top_env
                                                 VarSet
done [Id]
callers RuleBase
rb Id
fn [CallInfo]
ok_calls

           ; ([CoreRule]
rules2, CoreProgram
spec_binds2) <- RuleBase -> [CallInfoSet] -> CoreM ([CoreRule], CoreProgram)
go (RuleBase -> [CoreRule] -> RuleBase
extendRuleBaseList RuleBase
rb [CoreRule]
rules1) [CallInfoSet]
other_calls
           ; ([CoreRule], CoreProgram) -> CoreM ([CoreRule], CoreProgram)
forall (m :: * -> *) a. Monad m => a -> m a
return ([CoreRule]
rules1 [CoreRule] -> [CoreRule] -> [CoreRule]
forall a. [a] -> [a] -> [a]
++ [CoreRule]
rules2, CoreProgram
spec_binds1 CoreProgram -> CoreProgram -> CoreProgram
forall a. [a] -> [a] -> [a]
++ CoreProgram
spec_binds2) }

specImport :: DynFlags
           -> Module
           -> SpecEnv               -- Passed in so that all top-level Ids are in scope
           -> VarSet                -- Don't specialise these
                                    -- See Note [Avoiding recursive specialisation]
           -> [Id]                  -- Stack of imported functions being specialised
           -> RuleBase              -- Rules from this module
           -> Id -> [CallInfo]      -- Imported function and calls for it
           -> CoreM ( [CoreRule]    -- New rules
                    , [CoreBind] )  -- Specialised bindings
specImport :: DynFlags
-> Module
-> SpecEnv
-> VarSet
-> [Id]
-> RuleBase
-> Id
-> [CallInfo]
-> CoreM ([CoreRule], CoreProgram)
specImport DynFlags
dflags Module
this_mod SpecEnv
top_env VarSet
done [Id]
callers RuleBase
rb Id
fn [CallInfo]
calls_for_fn
  | Id
fn Id -> VarSet -> Bool
`elemVarSet` VarSet
done
  = ([CoreRule], CoreProgram) -> CoreM ([CoreRule], CoreProgram)
forall (m :: * -> *) a. Monad m => a -> m a
return ([], [])     -- No warning.  This actually happens all the time
                        -- when specialising a recursive function, because
                        -- the RHS of the specialised function contains a recursive
                        -- call to the original function

  | [CallInfo] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [CallInfo]
calls_for_fn   -- We filtered out all the calls in deleteCallsMentioning
  = ([CoreRule], CoreProgram) -> CoreM ([CoreRule], CoreProgram)
forall (m :: * -> *) a. Monad m => a -> m a
return ([], [])

  | DynFlags -> Unfolding -> Bool
wantSpecImport DynFlags
dflags Unfolding
unfolding
  , Just Expr Id
rhs <- Unfolding -> Maybe (Expr Id)
maybeUnfoldingTemplate Unfolding
unfolding
  = do {     -- Get rules from the external package state
             -- We keep doing this in case we "page-fault in"
             -- more rules as we go along
       ; HscEnv
hsc_env <- CoreM HscEnv
getHscEnv
       ; ExternalPackageState
eps <- IO ExternalPackageState -> CoreM ExternalPackageState
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO ExternalPackageState -> CoreM ExternalPackageState)
-> IO ExternalPackageState -> CoreM ExternalPackageState
forall a b. (a -> b) -> a -> b
$ HscEnv -> IO ExternalPackageState
hscEPS HscEnv
hsc_env
       ; ModuleSet
vis_orphs <- CoreM ModuleSet
getVisibleOrphanMods
       ; let full_rb :: RuleBase
full_rb = RuleBase -> RuleBase -> RuleBase
unionRuleBase RuleBase
rb (ExternalPackageState -> RuleBase
eps_rule_base ExternalPackageState
eps)
             rules_for_fn :: [CoreRule]
rules_for_fn = RuleEnv -> Id -> [CoreRule]
getRules (RuleBase -> ModuleSet -> RuleEnv
RuleEnv RuleBase
full_rb ModuleSet
vis_orphs) Id
fn

       ; ([CoreRule]
rules1, [(Id, Expr Id)]
spec_pairs, UsageDetails
uds)
             <- -- pprTrace "specImport1" (vcat [ppr fn, ppr calls_for_fn, ppr rhs]) $
                DynFlags
-> Module
-> SpecM ([CoreRule], [(Id, Expr Id)], UsageDetails)
-> CoreM ([CoreRule], [(Id, Expr Id)], UsageDetails)
forall a. DynFlags -> Module -> SpecM a -> CoreM a
runSpecM DynFlags
dflags Module
this_mod (SpecM ([CoreRule], [(Id, Expr Id)], UsageDetails)
 -> CoreM ([CoreRule], [(Id, Expr Id)], UsageDetails))
-> SpecM ([CoreRule], [(Id, Expr Id)], UsageDetails)
-> CoreM ([CoreRule], [(Id, Expr Id)], UsageDetails)
forall a b. (a -> b) -> a -> b
$
                Maybe Module
-> SpecEnv
-> [CoreRule]
-> [CallInfo]
-> Id
-> Expr Id
-> SpecM ([CoreRule], [(Id, Expr Id)], UsageDetails)
specCalls (Module -> Maybe Module
forall a. a -> Maybe a
Just Module
this_mod) SpecEnv
top_env [CoreRule]
rules_for_fn [CallInfo]
calls_for_fn Id
fn Expr Id
rhs
       ; let spec_binds1 :: CoreProgram
spec_binds1 = [Id -> Expr Id -> Bind Id
forall b. b -> Expr b -> Bind b
NonRec Id
b Expr Id
r | (Id
b,Expr Id
r) <- [(Id, Expr Id)]
spec_pairs]
             -- After the rules kick in we may get recursion, but
             -- we rely on a global GlomBinds to sort that out later
             -- See Note [Glom the bindings if imported functions are specialised]

              -- Now specialise any cascaded calls
       ; ([CoreRule]
rules2, CoreProgram
spec_binds2) <- -- pprTrace "specImport 2" (ppr fn $$ ppr rules1 $$ ppr spec_binds1) $
                                  DynFlags
-> Module
-> SpecEnv
-> VarSet
-> [Id]
-> RuleBase
-> UsageDetails
-> CoreM ([CoreRule], CoreProgram)
specImports DynFlags
dflags Module
this_mod SpecEnv
top_env
                                              (VarSet -> Id -> VarSet
extendVarSet VarSet
done Id
fn)
                                              (Id
fnId -> [Id] -> [Id]
forall a. a -> [a] -> [a]
:[Id]
callers)
                                              (RuleBase -> [CoreRule] -> RuleBase
extendRuleBaseList RuleBase
rb [CoreRule]
rules1)
                                              UsageDetails
uds

       ; let final_binds :: CoreProgram
final_binds = CoreProgram
spec_binds2 CoreProgram -> CoreProgram -> CoreProgram
forall a. [a] -> [a] -> [a]
++ CoreProgram
spec_binds1

       ; ([CoreRule], CoreProgram) -> CoreM ([CoreRule], CoreProgram)
forall (m :: * -> *) a. Monad m => a -> m a
return ([CoreRule]
rules2 [CoreRule] -> [CoreRule] -> [CoreRule]
forall a. [a] -> [a] -> [a]
++ [CoreRule]
rules1, CoreProgram
final_binds) }

  | Bool
otherwise = do { DynFlags -> [Id] -> Id -> [CallInfo] -> CoreM ()
tryWarnMissingSpecs DynFlags
dflags [Id]
callers Id
fn [CallInfo]
calls_for_fn
                   ; ([CoreRule], CoreProgram) -> CoreM ([CoreRule], CoreProgram)
forall (m :: * -> *) a. Monad m => a -> m a
return ([], [])}

  where
    unfolding :: Unfolding
unfolding = Id -> Unfolding
realIdUnfolding Id
fn   -- We want to see the unfolding even for loop breakers

-- | Returns whether or not to show a missed-spec warning.
-- If -Wall-missed-specializations is on, show the warning.
-- Otherwise, if -Wmissed-specializations is on, only show a warning
-- if there is at least one imported function being specialized,
-- and if all imported functions are marked with an inline pragma
-- Use the most specific warning as the reason.
tryWarnMissingSpecs :: DynFlags -> [Id] -> Id -> [CallInfo] -> CoreM ()
-- See Note [Warning about missed specialisations]
tryWarnMissingSpecs :: DynFlags -> [Id] -> Id -> [CallInfo] -> CoreM ()
tryWarnMissingSpecs DynFlags
dflags [Id]
callers Id
fn [CallInfo]
calls_for_fn
  | WarningFlag -> DynFlags -> Bool
wopt WarningFlag
Opt_WarnMissedSpecs DynFlags
dflags
    Bool -> Bool -> Bool
&& Bool -> Bool
not ([Id] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Id]
callers)
    Bool -> Bool -> Bool
&& Bool
allCallersInlined                  = WarnReason -> CoreM ()
doWarn (WarnReason -> CoreM ()) -> WarnReason -> CoreM ()
forall a b. (a -> b) -> a -> b
$ WarningFlag -> WarnReason
Reason WarningFlag
Opt_WarnMissedSpecs
  | WarningFlag -> DynFlags -> Bool
wopt WarningFlag
Opt_WarnAllMissedSpecs DynFlags
dflags    = WarnReason -> CoreM ()
doWarn (WarnReason -> CoreM ()) -> WarnReason -> CoreM ()
forall a b. (a -> b) -> a -> b
$ WarningFlag -> WarnReason
Reason WarningFlag
Opt_WarnAllMissedSpecs
  | Bool
otherwise                             = () -> CoreM ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  where
    allCallersInlined :: Bool
allCallersInlined = (Id -> Bool) -> [Id] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (InlinePragma -> Bool
isAnyInlinePragma (InlinePragma -> Bool) -> (Id -> InlinePragma) -> Id -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Id -> InlinePragma
idInlinePragma) [Id]
callers
    doWarn :: WarnReason -> CoreM ()
doWarn WarnReason
reason =
      WarnReason -> SDoc -> CoreM ()
warnMsg WarnReason
reason
        ([SDoc] -> SDoc
vcat [ SDoc -> Int -> SDoc -> SDoc
hang (String -> SDoc
text (String
"Could not specialise imported function") SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
quotes (Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
fn))
                Int
2 ([SDoc] -> SDoc
vcat [ String -> SDoc
text String
"when specialising" SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
quotes (Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
caller)
                        | Id
caller <- [Id]
callers])
          , SDoc -> SDoc
whenPprDebug (String -> SDoc
text String
"calls:" SDoc -> SDoc -> SDoc
<+> [SDoc] -> SDoc
vcat ((CallInfo -> SDoc) -> [CallInfo] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map (Id -> CallInfo -> SDoc
pprCallInfo Id
fn) [CallInfo]
calls_for_fn))
          , String -> SDoc
text String
"Probable fix: add INLINABLE pragma on" SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
quotes (Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
fn) ])

wantSpecImport :: DynFlags -> Unfolding -> Bool
-- See Note [Specialise imported INLINABLE things]
wantSpecImport :: DynFlags -> Unfolding -> Bool
wantSpecImport DynFlags
dflags Unfolding
unf
 = case Unfolding
unf of
     Unfolding
NoUnfolding      -> Bool
False
     Unfolding
BootUnfolding    -> Bool
False
     OtherCon {}      -> Bool
False
     DFunUnfolding {} -> Bool
True
     CoreUnfolding { uf_src :: Unfolding -> UnfoldingSource
uf_src = UnfoldingSource
src, uf_guidance :: Unfolding -> UnfoldingGuidance
uf_guidance = UnfoldingGuidance
_guidance }
       | GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_SpecialiseAggressively DynFlags
dflags -> Bool
True
       | UnfoldingSource -> Bool
isStableSource UnfoldingSource
src -> Bool
True
               -- Specialise even INLINE things; it hasn't inlined yet,
               -- so perhaps it never will.  Moreover it may have calls
               -- inside it that we want to specialise
       | Bool
otherwise -> Bool
False    -- Stable, not INLINE, hence INLINABLE

{- Note [Warning about missed specialisations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose
 * In module Lib, you carefully mark a function 'foo' INLINABLE
 * Import Lib(foo) into another module M
 * Call 'foo' at some specialised type in M
Then you jolly well expect it to be specialised in M.  But what if
'foo' calls another function 'Lib.bar'.  Then you'd like 'bar' to be
specialised too.  But if 'bar' is not marked INLINABLE it may well
not be specialised.  The warning Opt_WarnMissedSpecs warns about this.

It's more noisy to warning about a missed specialisation opportunity
for /every/ overloaded imported function, but sometimes useful. That
is what Opt_WarnAllMissedSpecs does.

ToDo: warn about missed opportunities for local functions.

Note [Specialise imported INLINABLE things]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What imported functions do we specialise?  The basic set is
 * DFuns and things with INLINABLE pragmas.
but with -fspecialise-aggressively we add
 * Anything with an unfolding template

#8874 has a good example of why we want to auto-specialise DFuns.

We have the -fspecialise-aggressively flag (usually off), because we
risk lots of orphan modules from over-vigorous specialisation.
However it's not a big deal: anything non-recursive with an
unfolding-template will probably have been inlined already.

Note [Glom the bindings if imported functions are specialised]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have an imported, *recursive*, INLINABLE function
   f :: Eq a => a -> a
   f = /\a \d x. ...(f a d)...
In the module being compiled we have
   g x = f (x::Int)
Now we'll make a specialised function
   f_spec :: Int -> Int
   f_spec = \x -> ...(f Int dInt)...
   {-# RULE  f Int _ = f_spec #-}
   g = \x. f Int dInt x
Note that f_spec doesn't look recursive
After rewriting with the RULE, we get
   f_spec = \x -> ...(f_spec)...
BUT since f_spec was non-recursive before it'll *stay* non-recursive.
The occurrence analyser never turns a NonRec into a Rec.  So we must
make sure that f_spec is recursive.  Easiest thing is to make all
the specialisations for imported bindings recursive.


Note [Avoiding recursive specialisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we specialise 'f' we may find new overloaded calls to 'g', 'h' in
'f's RHS.  So we want to specialise g,h.  But we don't want to
specialise f any more!  It's possible that f's RHS might have a
recursive yet-more-specialised call, so we'd diverge in that case.
And if the call is to the same type, one specialisation is enough.
Avoiding this recursive specialisation loop is the reason for the
'done' VarSet passed to specImports and specImport.

************************************************************************
*                                                                      *
\subsubsection{@specExpr@: the main function}
*                                                                      *
************************************************************************
-}

data SpecEnv
  = SE { SpecEnv -> Subst
se_subst :: Core.Subst
             -- We carry a substitution down:
             -- a) we must clone any binding that might float outwards,
             --    to avoid name clashes
             -- b) we carry a type substitution to use when analysing
             --    the RHS of specialised bindings (no type-let!)


       , SpecEnv -> VarSet
se_interesting :: VarSet
             -- Dict Ids that we know something about
             -- and hence may be worth specialising against
             -- See Note [Interesting dictionary arguments]
     }

instance Outputable SpecEnv where
  ppr :: SpecEnv -> SDoc
ppr (SE { se_subst :: SpecEnv -> Subst
se_subst = Subst
subst, se_interesting :: SpecEnv -> VarSet
se_interesting = VarSet
interesting })
    = String -> SDoc
text String
"SE" SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
braces ([SDoc] -> SDoc
sep ([SDoc] -> SDoc) -> [SDoc] -> SDoc
forall a b. (a -> b) -> a -> b
$ SDoc -> [SDoc] -> [SDoc]
punctuate SDoc
comma
        [ String -> SDoc
text String
"subst =" SDoc -> SDoc -> SDoc
<+> Subst -> SDoc
forall a. Outputable a => a -> SDoc
ppr Subst
subst
        , String -> SDoc
text String
"interesting =" SDoc -> SDoc -> SDoc
<+> VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr VarSet
interesting ])

specVar :: SpecEnv -> Id -> CoreExpr
specVar :: SpecEnv -> Id -> Expr Id
specVar SpecEnv
env Id
v = SDoc -> Subst -> Id -> Expr Id
Core.lookupIdSubst (String -> SDoc
text String
"specVar") (SpecEnv -> Subst
se_subst SpecEnv
env) Id
v

specExpr :: SpecEnv -> CoreExpr -> SpecM (CoreExpr, UsageDetails)

---------------- First the easy cases --------------------
specExpr :: SpecEnv -> Expr Id -> SpecM (Expr Id, UsageDetails)
specExpr SpecEnv
env (Type Type
ty)     = (Expr Id, UsageDetails) -> SpecM (Expr Id, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return (Type -> Expr Id
forall b. Type -> Expr b
Type     (SpecEnv -> Type -> Type
substTy SpecEnv
env Type
ty), UsageDetails
emptyUDs)
specExpr SpecEnv
env (Coercion Coercion
co) = (Expr Id, UsageDetails) -> SpecM (Expr Id, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> Expr Id
forall b. Coercion -> Expr b
Coercion (SpecEnv -> Coercion -> Coercion
substCo SpecEnv
env Coercion
co), UsageDetails
emptyUDs)
specExpr SpecEnv
env (Var Id
v)       = (Expr Id, UsageDetails) -> SpecM (Expr Id, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return (SpecEnv -> Id -> Expr Id
specVar SpecEnv
env Id
v, UsageDetails
emptyUDs)
specExpr SpecEnv
_   (Lit Literal
lit)     = (Expr Id, UsageDetails) -> SpecM (Expr Id, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return (Literal -> Expr Id
forall b. Literal -> Expr b
Lit Literal
lit,       UsageDetails
emptyUDs)
specExpr SpecEnv
env (Cast Expr Id
e Coercion
co)
  = do { (Expr Id
e', UsageDetails
uds) <- SpecEnv -> Expr Id -> SpecM (Expr Id, UsageDetails)
specExpr SpecEnv
env Expr Id
e
       ; (Expr Id, UsageDetails) -> SpecM (Expr Id, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ((Expr Id -> Coercion -> Expr Id
mkCast Expr Id
e' (SpecEnv -> Coercion -> Coercion
substCo SpecEnv
env Coercion
co)), UsageDetails
uds) }
specExpr SpecEnv
env (Tick Tickish Id
tickish Expr Id
body)
  = do { (Expr Id
body', UsageDetails
uds) <- SpecEnv -> Expr Id -> SpecM (Expr Id, UsageDetails)
specExpr SpecEnv
env Expr Id
body
       ; (Expr Id, UsageDetails) -> SpecM (Expr Id, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return (Tickish Id -> Expr Id -> Expr Id
forall b. Tickish Id -> Expr b -> Expr b
Tick (SpecEnv -> Tickish Id -> Tickish Id
specTickish SpecEnv
env Tickish Id
tickish) Expr Id
body', UsageDetails
uds) }

---------------- Applications might generate a call instance --------------------
specExpr SpecEnv
env expr :: Expr Id
expr@(App {})
  = Expr Id -> [Expr Id] -> SpecM (Expr Id, UsageDetails)
go Expr Id
expr []
  where
    go :: Expr Id -> [Expr Id] -> SpecM (Expr Id, UsageDetails)
go (App Expr Id
fun Expr Id
arg) [Expr Id]
args = do (Expr Id
arg', UsageDetails
uds_arg) <- SpecEnv -> Expr Id -> SpecM (Expr Id, UsageDetails)
specExpr SpecEnv
env Expr Id
arg
                               (Expr Id
fun', UsageDetails
uds_app) <- Expr Id -> [Expr Id] -> SpecM (Expr Id, UsageDetails)
go Expr Id
fun (Expr Id
arg'Expr Id -> [Expr Id] -> [Expr Id]
forall a. a -> [a] -> [a]
:[Expr Id]
args)
                               (Expr Id, UsageDetails) -> SpecM (Expr Id, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return (Expr Id -> Expr Id -> Expr Id
forall b. Expr b -> Expr b -> Expr b
App Expr Id
fun' Expr Id
arg', UsageDetails
uds_arg UsageDetails -> UsageDetails -> UsageDetails
`plusUDs` UsageDetails
uds_app)

    go (Var Id
f)       [Expr Id]
args = case SpecEnv -> Id -> Expr Id
specVar SpecEnv
env Id
f of
                                Var Id
f' -> (Expr Id, UsageDetails) -> SpecM (Expr Id, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return (Id -> Expr Id
forall b. Id -> Expr b
Var Id
f', SpecEnv -> Id -> [Expr Id] -> UsageDetails
mkCallUDs SpecEnv
env Id
f' [Expr Id]
args)
                                Expr Id
e'     -> (Expr Id, UsageDetails) -> SpecM (Expr Id, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return (Expr Id
e', UsageDetails
emptyUDs) -- I don't expect this!
    go Expr Id
other         [Expr Id]
_    = SpecEnv -> Expr Id -> SpecM (Expr Id, UsageDetails)
specExpr SpecEnv
env Expr Id
other

---------------- Lambda/case require dumping of usage details --------------------
specExpr SpecEnv
env e :: Expr Id
e@(Lam Id
_ Expr Id
_) = do
    (Expr Id
body', UsageDetails
uds) <- SpecEnv -> Expr Id -> SpecM (Expr Id, UsageDetails)
specExpr SpecEnv
env' Expr Id
body
    let (UsageDetails
free_uds, Bag DictBind
dumped_dbs) = [Id] -> UsageDetails -> (UsageDetails, Bag DictBind)
dumpUDs [Id]
bndrs' UsageDetails
uds
    (Expr Id, UsageDetails) -> SpecM (Expr Id, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ([Id] -> Expr Id -> Expr Id
forall b. [b] -> Expr b -> Expr b
mkLams [Id]
bndrs' (Bag DictBind -> Expr Id -> Expr Id
wrapDictBindsE Bag DictBind
dumped_dbs Expr Id
body'), UsageDetails
free_uds)
  where
    ([Id]
bndrs, Expr Id
body) = Expr Id -> ([Id], Expr Id)
forall b. Expr b -> ([b], Expr b)
collectBinders Expr Id
e
    (SpecEnv
env', [Id]
bndrs') = SpecEnv -> [Id] -> (SpecEnv, [Id])
substBndrs SpecEnv
env [Id]
bndrs
        -- More efficient to collect a group of binders together all at once
        -- and we don't want to split a lambda group with dumped bindings

specExpr SpecEnv
env (Case Expr Id
scrut Id
case_bndr Type
ty [Alt Id]
alts)
  = do { (Expr Id
scrut', UsageDetails
scrut_uds) <- SpecEnv -> Expr Id -> SpecM (Expr Id, UsageDetails)
specExpr SpecEnv
env Expr Id
scrut
       ; (Expr Id
scrut'', Id
case_bndr', [Alt Id]
alts', UsageDetails
alts_uds)
             <- SpecEnv
-> Expr Id
-> Id
-> [Alt Id]
-> SpecM (Expr Id, Id, [Alt Id], UsageDetails)
specCase SpecEnv
env Expr Id
scrut' Id
case_bndr [Alt Id]
alts
       ; (Expr Id, UsageDetails) -> SpecM (Expr Id, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return (Expr Id -> Id -> Type -> [Alt Id] -> Expr Id
forall b. Expr b -> b -> Type -> [Alt b] -> Expr b
Case Expr Id
scrut'' Id
case_bndr' (SpecEnv -> Type -> Type
substTy SpecEnv
env Type
ty) [Alt Id]
alts'
                , UsageDetails
scrut_uds UsageDetails -> UsageDetails -> UsageDetails
`plusUDs` UsageDetails
alts_uds) }

---------------- Finally, let is the interesting case --------------------
specExpr SpecEnv
env (Let Bind Id
bind Expr Id
body)
  = do { -- Clone binders
         (SpecEnv
rhs_env, SpecEnv
body_env, Bind Id
bind') <- SpecEnv -> Bind Id -> SpecM (SpecEnv, SpecEnv, Bind Id)
cloneBindSM SpecEnv
env Bind Id
bind

         -- Deal with the body
       ; (Expr Id
body', UsageDetails
body_uds) <- SpecEnv -> Expr Id -> SpecM (Expr Id, UsageDetails)
specExpr SpecEnv
body_env Expr Id
body

        -- Deal with the bindings
      ; (CoreProgram
binds', UsageDetails
uds) <- SpecEnv
-> Bind Id -> UsageDetails -> SpecM (CoreProgram, UsageDetails)
specBind SpecEnv
rhs_env Bind Id
bind' UsageDetails
body_uds

        -- All done
      ; (Expr Id, UsageDetails) -> SpecM (Expr Id, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ((Bind Id -> Expr Id -> Expr Id)
-> Expr Id -> CoreProgram -> Expr Id
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Bind Id -> Expr Id -> Expr Id
forall b. Bind b -> Expr b -> Expr b
Let Expr Id
body' CoreProgram
binds', UsageDetails
uds) }

--------------
specLam :: SpecEnv -> [OutBndr] -> InExpr -> SpecM (OutExpr, UsageDetails)
-- The binders have been substituted, but the body has not
specLam :: SpecEnv -> [Id] -> Expr Id -> SpecM (Expr Id, UsageDetails)
specLam SpecEnv
env [Id]
bndrs Expr Id
body
  | [Id] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Id]
bndrs
  = SpecEnv -> Expr Id -> SpecM (Expr Id, UsageDetails)
specExpr SpecEnv
env Expr Id
body
  | Bool
otherwise
  = do { (Expr Id
body', UsageDetails
uds) <- SpecEnv -> Expr Id -> SpecM (Expr Id, UsageDetails)
specExpr SpecEnv
env Expr Id
body
       ; let (UsageDetails
free_uds, Bag DictBind
dumped_dbs) = [Id] -> UsageDetails -> (UsageDetails, Bag DictBind)
dumpUDs [Id]
bndrs UsageDetails
uds
       ; (Expr Id, UsageDetails) -> SpecM (Expr Id, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ([Id] -> Expr Id -> Expr Id
forall b. [b] -> Expr b -> Expr b
mkLams [Id]
bndrs (Bag DictBind -> Expr Id -> Expr Id
wrapDictBindsE Bag DictBind
dumped_dbs Expr Id
body'), UsageDetails
free_uds) }

--------------
specTickish :: SpecEnv -> Tickish Id -> Tickish Id
specTickish :: SpecEnv -> Tickish Id -> Tickish Id
specTickish SpecEnv
env (Breakpoint Int
ix [Id]
ids)
  = Int -> [Id] -> Tickish Id
forall id. Int -> [id] -> Tickish id
Breakpoint Int
ix [ Id
id' | Id
id <- [Id]
ids, Var Id
id' <- [SpecEnv -> Id -> Expr Id
specVar SpecEnv
env Id
id]]
  -- drop vars from the list if they have a non-variable substitution.
  -- should never happen, but it's harmless to drop them anyway.
specTickish SpecEnv
_ Tickish Id
other_tickish = Tickish Id
other_tickish

--------------
specCase :: SpecEnv
         -> CoreExpr            -- Scrutinee, already done
         -> Id -> [CoreAlt]
         -> SpecM ( CoreExpr    -- New scrutinee
                  , Id
                  , [CoreAlt]
                  , UsageDetails)
specCase :: SpecEnv
-> Expr Id
-> Id
-> [Alt Id]
-> SpecM (Expr Id, Id, [Alt Id], UsageDetails)
specCase SpecEnv
env Expr Id
scrut' Id
case_bndr [(AltCon
con, [Id]
args, Expr Id
rhs)]
  | Id -> Bool
isDictId Id
case_bndr           -- See Note [Floating dictionaries out of cases]
  , SpecEnv -> Expr Id -> Bool
interestingDict SpecEnv
env Expr Id
scrut'
  , Bool -> Bool
not (Id -> Bool
isDeadBinder Id
case_bndr Bool -> Bool -> Bool
&& [Id] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Id]
sc_args')
  = do { (Id
case_bndr_flt : [Id]
sc_args_flt) <- (Id -> SpecM Id) -> [Id] -> SpecM [Id]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Id -> SpecM Id
forall (m :: * -> *). MonadUnique m => Id -> m Id
clone_me (Id
case_bndr' Id -> [Id] -> [Id]
forall a. a -> [a] -> [a]
: [Id]
sc_args')

       ; let sc_rhss :: [Expr Id]
sc_rhss = [ Expr Id -> Id -> Type -> [Alt Id] -> Expr Id
forall b. Expr b -> b -> Type -> [Alt b] -> Expr b
Case (Id -> Expr Id
forall b. Id -> Expr b
Var Id
case_bndr_flt) Id
case_bndr' (Id -> Type
idType Id
sc_arg')
                              [(AltCon
con, [Id]
args', Id -> Expr Id
forall b. Id -> Expr b
Var Id
sc_arg')]
                       | Id
sc_arg' <- [Id]
sc_args' ]

             -- Extend the substitution for RHS to map the *original* binders
             -- to their floated versions.
             mb_sc_flts :: [Maybe DictId]
             mb_sc_flts :: [Maybe Id]
mb_sc_flts = (Id -> Maybe Id) -> [Id] -> [Maybe Id]
forall a b. (a -> b) -> [a] -> [b]
map (VarEnv Id -> Id -> Maybe Id
forall a. VarEnv a -> Id -> Maybe a
lookupVarEnv VarEnv Id
clone_env) [Id]
args'
             clone_env :: VarEnv Id
clone_env  = [Id] -> [Id] -> VarEnv Id
forall a. [Id] -> [a] -> VarEnv a
zipVarEnv [Id]
sc_args' [Id]
sc_args_flt
             subst_prs :: [(Id, Expr b)]
subst_prs  = (Id
case_bndr, Id -> Expr b
forall b. Id -> Expr b
Var Id
case_bndr_flt)
                        (Id, Expr b) -> [(Id, Expr b)] -> [(Id, Expr b)]
forall a. a -> [a] -> [a]
: [ (Id
arg, Id -> Expr b
forall b. Id -> Expr b
Var Id
sc_flt)
                          | (Id
arg, Just Id
sc_flt) <- [Id]
args [Id] -> [Maybe Id] -> [(Id, Maybe Id)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [Maybe Id]
mb_sc_flts ]
             env_rhs' :: SpecEnv
env_rhs' = SpecEnv
env_rhs { se_subst :: Subst
se_subst = Subst -> [(Id, Expr Id)] -> Subst
Core.extendIdSubstList (SpecEnv -> Subst
se_subst SpecEnv
env_rhs) [(Id, Expr Id)]
forall b. [(Id, Expr b)]
subst_prs
                                , se_interesting :: VarSet
se_interesting = SpecEnv -> VarSet
se_interesting SpecEnv
env_rhs VarSet -> [Id] -> VarSet
`extendVarSetList`
                                                   (Id
case_bndr_flt Id -> [Id] -> [Id]
forall a. a -> [a] -> [a]
: [Id]
sc_args_flt) }

       ; (Expr Id
rhs', UsageDetails
rhs_uds)   <- SpecEnv -> Expr Id -> SpecM (Expr Id, UsageDetails)
specExpr SpecEnv
env_rhs' Expr Id
rhs
       ; let scrut_bind :: DictBind
scrut_bind    = Bind Id -> DictBind
mkDB (Id -> Expr Id -> Bind Id
forall b. b -> Expr b -> Bind b
NonRec Id
case_bndr_flt Expr Id
scrut')
             case_bndr_set :: VarSet
case_bndr_set = Id -> VarSet
unitVarSet Id
case_bndr_flt
             sc_binds :: [DictBind]
sc_binds      = [(Id -> Expr Id -> Bind Id
forall b. b -> Expr b -> Bind b
NonRec Id
sc_arg_flt Expr Id
sc_rhs, VarSet
case_bndr_set)
                             | (Id
sc_arg_flt, Expr Id
sc_rhs) <- [Id]
sc_args_flt [Id] -> [Expr Id] -> [(Id, Expr Id)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [Expr Id]
sc_rhss ]
             flt_binds :: [DictBind]
flt_binds     = DictBind
scrut_bind DictBind -> [DictBind] -> [DictBind]
forall a. a -> [a] -> [a]
: [DictBind]
sc_binds
             (UsageDetails
free_uds, Bag DictBind
dumped_dbs) = [Id] -> UsageDetails -> (UsageDetails, Bag DictBind)
dumpUDs (Id
case_bndr'Id -> [Id] -> [Id]
forall a. a -> [a] -> [a]
:[Id]
args') UsageDetails
rhs_uds
             all_uds :: UsageDetails
all_uds = [DictBind]
flt_binds [DictBind] -> UsageDetails -> UsageDetails
`addDictBinds` UsageDetails
free_uds
             alt' :: Alt Id
alt'    = (AltCon
con, [Id]
args', Bag DictBind -> Expr Id -> Expr Id
wrapDictBindsE Bag DictBind
dumped_dbs Expr Id
rhs')
       ; (Expr Id, Id, [Alt Id], UsageDetails)
-> SpecM (Expr Id, Id, [Alt Id], UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return (Id -> Expr Id
forall b. Id -> Expr b
Var Id
case_bndr_flt, Id
case_bndr', [Alt Id
alt'], UsageDetails
all_uds) }
  where
    (SpecEnv
env_rhs, (Id
case_bndr':[Id]
args')) = SpecEnv -> [Id] -> (SpecEnv, [Id])
substBndrs SpecEnv
env (Id
case_bndrId -> [Id] -> [Id]
forall a. a -> [a] -> [a]
:[Id]
args)
    sc_args' :: [Id]
sc_args' = (Id -> Bool) -> [Id] -> [Id]
forall a. (a -> Bool) -> [a] -> [a]
filter Id -> Bool
is_flt_sc_arg [Id]
args'

    clone_me :: Id -> m Id
clone_me Id
bndr = do { Unique
uniq <- m Unique
forall (m :: * -> *). MonadUnique m => m Unique
getUniqueM
                       ; Id -> m Id
forall (m :: * -> *) a. Monad m => a -> m a
return (OccName -> Unique -> Type -> SrcSpan -> Id
mkUserLocalOrCoVar OccName
occ Unique
uniq Type
ty SrcSpan
loc) }
       where
         name :: Name
name = Id -> Name
idName Id
bndr
         ty :: Type
ty   = Id -> Type
idType Id
bndr
         occ :: OccName
occ  = Name -> OccName
nameOccName Name
name
         loc :: SrcSpan
loc  = Name -> SrcSpan
forall a. NamedThing a => a -> SrcSpan
getSrcSpan Name
name

    arg_set :: VarSet
arg_set = [Id] -> VarSet
mkVarSet [Id]
args'
    is_flt_sc_arg :: Id -> Bool
is_flt_sc_arg Id
var =  Id -> Bool
isId Id
var
                      Bool -> Bool -> Bool
&& Bool -> Bool
not (Id -> Bool
isDeadBinder Id
var)
                      Bool -> Bool -> Bool
&& Type -> Bool
isDictTy Type
var_ty
                      Bool -> Bool -> Bool
&& Bool -> Bool
not (Type -> VarSet
tyCoVarsOfType Type
var_ty VarSet -> VarSet -> Bool
`intersectsVarSet` VarSet
arg_set)
       where
         var_ty :: Type
var_ty = Id -> Type
idType Id
var


specCase SpecEnv
env Expr Id
scrut Id
case_bndr [Alt Id]
alts
  = do { ([Alt Id]
alts', UsageDetails
uds_alts) <- (Alt Id -> SpecM (Alt Id, UsageDetails))
-> [Alt Id] -> SpecM ([Alt Id], UsageDetails)
forall a b.
(a -> SpecM (b, UsageDetails)) -> [a] -> SpecM ([b], UsageDetails)
mapAndCombineSM Alt Id -> SpecM (Alt Id, UsageDetails)
forall a.
(a, [Id], Expr Id) -> SpecM ((a, [Id], Expr Id), UsageDetails)
spec_alt [Alt Id]
alts
       ; (Expr Id, Id, [Alt Id], UsageDetails)
-> SpecM (Expr Id, Id, [Alt Id], UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return (Expr Id
scrut, Id
case_bndr', [Alt Id]
alts', UsageDetails
uds_alts) }
  where
    (SpecEnv
env_alt, Id
case_bndr') = SpecEnv -> Id -> (SpecEnv, Id)
substBndr SpecEnv
env Id
case_bndr
    spec_alt :: (a, [Id], Expr Id) -> SpecM ((a, [Id], Expr Id), UsageDetails)
spec_alt (a
con, [Id]
args, Expr Id
rhs) = do
          (Expr Id
rhs', UsageDetails
uds) <- SpecEnv -> Expr Id -> SpecM (Expr Id, UsageDetails)
specExpr SpecEnv
env_rhs Expr Id
rhs
          let (UsageDetails
free_uds, Bag DictBind
dumped_dbs) = [Id] -> UsageDetails -> (UsageDetails, Bag DictBind)
dumpUDs (Id
case_bndr' Id -> [Id] -> [Id]
forall a. a -> [a] -> [a]
: [Id]
args') UsageDetails
uds
          ((a, [Id], Expr Id), UsageDetails)
-> SpecM ((a, [Id], Expr Id), UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ((a
con, [Id]
args', Bag DictBind -> Expr Id -> Expr Id
wrapDictBindsE Bag DictBind
dumped_dbs Expr Id
rhs'), UsageDetails
free_uds)
        where
          (SpecEnv
env_rhs, [Id]
args') = SpecEnv -> [Id] -> (SpecEnv, [Id])
substBndrs SpecEnv
env_alt [Id]
args

{-
Note [Floating dictionaries out of cases]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
   g = \d. case d of { MkD sc ... -> ...(f sc)... }
Naively we can't float d2's binding out of the case expression,
because 'sc' is bound by the case, and that in turn means we can't
specialise f, which seems a pity.

So we invert the case, by floating out a binding
for 'sc_flt' thus:
    sc_flt = case d of { MkD sc ... -> sc }
Now we can float the call instance for 'f'.  Indeed this is just
what'll happen if 'sc' was originally bound with a let binding,
but case is more efficient, and necessary with equalities. So it's
good to work with both.

You might think that this won't make any difference, because the
call instance will only get nuked by the \d.  BUT if 'g' itself is
specialised, then transitively we should be able to specialise f.

In general, given
   case e of cb { MkD sc ... -> ...(f sc)... }
we transform to
   let cb_flt = e
       sc_flt = case cb_flt of { MkD sc ... -> sc }
   in
   case cb_flt of bg { MkD sc ... -> ....(f sc_flt)... }

The "_flt" things are the floated binds; we use the current substitution
to substitute sc -> sc_flt in the RHS

************************************************************************
*                                                                      *
                     Dealing with a binding
*                                                                      *
************************************************************************
-}

specBind :: SpecEnv                     -- Use this for RHSs
         -> CoreBind                    -- Binders are already cloned by cloneBindSM,
                                        -- but RHSs are un-processed
         -> UsageDetails                -- Info on how the scope of the binding
         -> SpecM ([CoreBind],          -- New bindings
                   UsageDetails)        -- And info to pass upstream

-- Returned UsageDetails:
--    No calls for binders of this bind
specBind :: SpecEnv
-> Bind Id -> UsageDetails -> SpecM (CoreProgram, UsageDetails)
specBind SpecEnv
rhs_env (NonRec Id
fn Expr Id
rhs) UsageDetails
body_uds
  = do { (Expr Id
rhs', UsageDetails
rhs_uds) <- SpecEnv -> Expr Id -> SpecM (Expr Id, UsageDetails)
specExpr SpecEnv
rhs_env Expr Id
rhs

        ; let zapped_fn :: Id
zapped_fn = Id -> Id
zapIdDemandInfo Id
fn
              -- We zap the demand info because the binding may float,
              -- which would invaidate the demand info (see #17810 for example).
              -- Destroying demand info is not terrible; specialisation is
              -- always followed soon by demand analysis.
      ; (Id
fn', [(Id, Expr Id)]
spec_defns, UsageDetails
body_uds1) <- SpecEnv
-> UsageDetails
-> Id
-> Expr Id
-> SpecM (Id, [(Id, Expr Id)], UsageDetails)
specDefn SpecEnv
rhs_env UsageDetails
body_uds Id
zapped_fn Expr Id
rhs

       ; let pairs :: [(Id, Expr Id)]
pairs = [(Id, Expr Id)]
spec_defns [(Id, Expr Id)] -> [(Id, Expr Id)] -> [(Id, Expr Id)]
forall a. [a] -> [a] -> [a]
++ [(Id
fn', Expr Id
rhs')]
                        -- fn' mentions the spec_defns in its rules,
                        -- so put the latter first

             combined_uds :: UsageDetails
combined_uds = UsageDetails
body_uds1 UsageDetails -> UsageDetails -> UsageDetails
`plusUDs` UsageDetails
rhs_uds

             (UsageDetails
free_uds, Bag DictBind
dump_dbs, Bool
float_all) = [Id] -> UsageDetails -> (UsageDetails, Bag DictBind, Bool)
dumpBindUDs [Id
fn] UsageDetails
combined_uds

             final_binds :: [DictBind]
             -- See Note [From non-recursive to recursive]
             final_binds :: [DictBind]
final_binds
               | Bool -> Bool
not (Bag DictBind -> Bool
forall a. Bag a -> Bool
isEmptyBag Bag DictBind
dump_dbs)
               , Bool -> Bool
not ([(Id, Expr Id)] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(Id, Expr Id)]
spec_defns)
               = [[(Id, Expr Id)] -> Bag DictBind -> DictBind
recWithDumpedDicts [(Id, Expr Id)]
pairs Bag DictBind
dump_dbs]
               | Bool
otherwise
               = [Bind Id -> DictBind
mkDB (Bind Id -> DictBind) -> Bind Id -> DictBind
forall a b. (a -> b) -> a -> b
$ Id -> Expr Id -> Bind Id
forall b. b -> Expr b -> Bind b
NonRec Id
b Expr Id
r | (Id
b,Expr Id
r) <- [(Id, Expr Id)]
pairs]
                 [DictBind] -> [DictBind] -> [DictBind]
forall a. [a] -> [a] -> [a]
++ Bag DictBind -> [DictBind]
forall a. Bag a -> [a]
bagToList Bag DictBind
dump_dbs

       ; if Bool
float_all then
             -- Rather than discard the calls mentioning the bound variables
             -- we float this (dictionary) binding along with the others
              (CoreProgram, UsageDetails) -> SpecM (CoreProgram, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ([], UsageDetails
free_uds UsageDetails -> [DictBind] -> UsageDetails
`snocDictBinds` [DictBind]
final_binds)
         else
             -- No call in final_uds mentions bound variables,
             -- so we can just leave the binding here
              (CoreProgram, UsageDetails) -> SpecM (CoreProgram, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ((DictBind -> Bind Id) -> [DictBind] -> CoreProgram
forall a b. (a -> b) -> [a] -> [b]
map DictBind -> Bind Id
forall a b. (a, b) -> a
fst [DictBind]
final_binds, UsageDetails
free_uds) }


specBind SpecEnv
rhs_env (Rec [(Id, Expr Id)]
pairs) UsageDetails
body_uds
       -- Note [Specialising a recursive group]
  = do { let ([Id]
bndrs,[Expr Id]
rhss) = [(Id, Expr Id)] -> ([Id], [Expr Id])
forall a b. [(a, b)] -> ([a], [b])
unzip [(Id, Expr Id)]
pairs
       ; ([Expr Id]
rhss', UsageDetails
rhs_uds) <- (Expr Id -> SpecM (Expr Id, UsageDetails))
-> [Expr Id] -> SpecM ([Expr Id], UsageDetails)
forall a b.
(a -> SpecM (b, UsageDetails)) -> [a] -> SpecM ([b], UsageDetails)
mapAndCombineSM (SpecEnv -> Expr Id -> SpecM (Expr Id, UsageDetails)
specExpr SpecEnv
rhs_env) [Expr Id]
rhss
       ; let scope_uds :: UsageDetails
scope_uds = UsageDetails
body_uds UsageDetails -> UsageDetails -> UsageDetails
`plusUDs` UsageDetails
rhs_uds
                       -- Includes binds and calls arising from rhss

       ; ([Id]
bndrs1, [(Id, Expr Id)]
spec_defns1, UsageDetails
uds1) <- SpecEnv
-> UsageDetails
-> [(Id, Expr Id)]
-> SpecM ([Id], [(Id, Expr Id)], UsageDetails)
specDefns SpecEnv
rhs_env UsageDetails
scope_uds [(Id, Expr Id)]
pairs

       ; ([Id]
bndrs3, [(Id, Expr Id)]
spec_defns3, UsageDetails
uds3)
             <- if [(Id, Expr Id)] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(Id, Expr Id)]
spec_defns1  -- Common case: no specialisation
                then ([Id], [(Id, Expr Id)], UsageDetails)
-> SpecM ([Id], [(Id, Expr Id)], UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ([Id]
bndrs1, [], UsageDetails
uds1)
                else do {            -- Specialisation occurred; do it again
                          ([Id]
bndrs2, [(Id, Expr Id)]
spec_defns2, UsageDetails
uds2)
                              <- SpecEnv
-> UsageDetails
-> [(Id, Expr Id)]
-> SpecM ([Id], [(Id, Expr Id)], UsageDetails)
specDefns SpecEnv
rhs_env UsageDetails
uds1 ([Id]
bndrs1 [Id] -> [Expr Id] -> [(Id, Expr Id)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [Expr Id]
rhss)
                        ; ([Id], [(Id, Expr Id)], UsageDetails)
-> SpecM ([Id], [(Id, Expr Id)], UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ([Id]
bndrs2, [(Id, Expr Id)]
spec_defns2 [(Id, Expr Id)] -> [(Id, Expr Id)] -> [(Id, Expr Id)]
forall a. [a] -> [a] -> [a]
++ [(Id, Expr Id)]
spec_defns1, UsageDetails
uds2) }

       ; let (UsageDetails
final_uds, Bag DictBind
dumped_dbs, Bool
float_all) = [Id] -> UsageDetails -> (UsageDetails, Bag DictBind, Bool)
dumpBindUDs [Id]
bndrs UsageDetails
uds3
             final_bind :: DictBind
final_bind = [(Id, Expr Id)] -> Bag DictBind -> DictBind
recWithDumpedDicts ([(Id, Expr Id)]
spec_defns3 [(Id, Expr Id)] -> [(Id, Expr Id)] -> [(Id, Expr Id)]
forall a. [a] -> [a] -> [a]
++ [Id] -> [Expr Id] -> [(Id, Expr Id)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Id]
bndrs3 [Expr Id]
rhss')
                                             Bag DictBind
dumped_dbs

       ; if Bool
float_all then
              (CoreProgram, UsageDetails) -> SpecM (CoreProgram, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ([], UsageDetails
final_uds UsageDetails -> DictBind -> UsageDetails
`snocDictBind` DictBind
final_bind)
         else
              (CoreProgram, UsageDetails) -> SpecM (CoreProgram, UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ([DictBind -> Bind Id
forall a b. (a, b) -> a
fst DictBind
final_bind], UsageDetails
final_uds) }


---------------------------
specDefns :: SpecEnv
          -> UsageDetails               -- Info on how it is used in its scope
          -> [(OutId,InExpr)]           -- The things being bound and their un-processed RHS
          -> SpecM ([OutId],            -- Original Ids with RULES added
                    [(OutId,OutExpr)],  -- Extra, specialised bindings
                    UsageDetails)       -- Stuff to fling upwards from the specialised versions

-- Specialise a list of bindings (the contents of a Rec), but flowing usages
-- upwards binding by binding.  Example: { f = ...g ...; g = ...f .... }
-- Then if the input CallDetails has a specialised call for 'g', whose specialisation
-- in turn generates a specialised call for 'f', we catch that in this one sweep.
-- But not vice versa (it's a fixpoint problem).

specDefns :: SpecEnv
-> UsageDetails
-> [(Id, Expr Id)]
-> SpecM ([Id], [(Id, Expr Id)], UsageDetails)
specDefns SpecEnv
_env UsageDetails
uds []
  = ([Id], [(Id, Expr Id)], UsageDetails)
-> SpecM ([Id], [(Id, Expr Id)], UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ([], [], UsageDetails
uds)
specDefns SpecEnv
env UsageDetails
uds ((Id
bndr,Expr Id
rhs):[(Id, Expr Id)]
pairs)
  = do { ([Id]
bndrs1, [(Id, Expr Id)]
spec_defns1, UsageDetails
uds1) <- SpecEnv
-> UsageDetails
-> [(Id, Expr Id)]
-> SpecM ([Id], [(Id, Expr Id)], UsageDetails)
specDefns SpecEnv
env UsageDetails
uds [(Id, Expr Id)]
pairs
       ; (Id
bndr1, [(Id, Expr Id)]
spec_defns2, UsageDetails
uds2)  <- SpecEnv
-> UsageDetails
-> Id
-> Expr Id
-> SpecM (Id, [(Id, Expr Id)], UsageDetails)
specDefn SpecEnv
env UsageDetails
uds1 Id
bndr Expr Id
rhs
       ; ([Id], [(Id, Expr Id)], UsageDetails)
-> SpecM ([Id], [(Id, Expr Id)], UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return (Id
bndr1 Id -> [Id] -> [Id]
forall a. a -> [a] -> [a]
: [Id]
bndrs1, [(Id, Expr Id)]
spec_defns1 [(Id, Expr Id)] -> [(Id, Expr Id)] -> [(Id, Expr Id)]
forall a. [a] -> [a] -> [a]
++ [(Id, Expr Id)]
spec_defns2, UsageDetails
uds2) }

---------------------------
specDefn :: SpecEnv
         -> UsageDetails                -- Info on how it is used in its scope
         -> OutId -> InExpr             -- The thing being bound and its un-processed RHS
         -> SpecM (Id,                  -- Original Id with added RULES
                   [(Id,CoreExpr)],     -- Extra, specialised bindings
                   UsageDetails)        -- Stuff to fling upwards from the specialised versions

specDefn :: SpecEnv
-> UsageDetails
-> Id
-> Expr Id
-> SpecM (Id, [(Id, Expr Id)], UsageDetails)
specDefn SpecEnv
env UsageDetails
body_uds Id
fn Expr Id
rhs
  = do { let (UsageDetails
body_uds_without_me, [CallInfo]
calls_for_me) = Id -> UsageDetails -> (UsageDetails, [CallInfo])
callsForMe Id
fn UsageDetails
body_uds
             rules_for_me :: [CoreRule]
rules_for_me = Id -> [CoreRule]
idCoreRules Id
fn
       ; ([CoreRule]
rules, [(Id, Expr Id)]
spec_defns, UsageDetails
spec_uds) <- Maybe Module
-> SpecEnv
-> [CoreRule]
-> [CallInfo]
-> Id
-> Expr Id
-> SpecM ([CoreRule], [(Id, Expr Id)], UsageDetails)
specCalls Maybe Module
forall a. Maybe a
Nothing SpecEnv
env [CoreRule]
rules_for_me
                                                    [CallInfo]
calls_for_me Id
fn Expr Id
rhs
       ; (Id, [(Id, Expr Id)], UsageDetails)
-> SpecM (Id, [(Id, Expr Id)], UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ( Id
fn Id -> [CoreRule] -> Id
`addIdSpecialisations` [CoreRule]
rules
                , [(Id, Expr Id)]
spec_defns
                , UsageDetails
body_uds_without_me UsageDetails -> UsageDetails -> UsageDetails
`plusUDs` UsageDetails
spec_uds) }
                -- It's important that the `plusUDs` is this way
                -- round, because body_uds_without_me may bind
                -- dictionaries that are used in calls_for_me passed
                -- to specDefn.  So the dictionary bindings in
                -- spec_uds may mention dictionaries bound in
                -- body_uds_without_me

---------------------------
specCalls :: Maybe Module      -- Just this_mod  =>  specialising imported fn
                               -- Nothing        =>  specialising local fn
          -> SpecEnv
          -> [CoreRule]        -- Existing RULES for the fn
          -> [CallInfo]
          -> OutId -> InExpr
          -> SpecM SpecInfo    -- New rules, specialised bindings, and usage details

-- This function checks existing rules, and does not create
-- duplicate ones. So the caller does not need to do this filtering.
-- See 'already_covered'

type SpecInfo = ( [CoreRule]       -- Specialisation rules
                , [(Id,CoreExpr)]  -- Specialised definition
                , UsageDetails )   -- Usage details from specialised RHSs

specCalls :: Maybe Module
-> SpecEnv
-> [CoreRule]
-> [CallInfo]
-> Id
-> Expr Id
-> SpecM ([CoreRule], [(Id, Expr Id)], UsageDetails)
specCalls Maybe Module
mb_mod SpecEnv
env [CoreRule]
existing_rules [CallInfo]
calls_for_me Id
fn Expr Id
rhs
        -- The first case is the interesting one
  |  [CallInfo] -> Bool
forall a. [a] -> Bool
notNull [CallInfo]
calls_for_me               -- And there are some calls to specialise
  Bool -> Bool -> Bool
&& Bool -> Bool
not (Activation -> Bool
isNeverActive (Id -> Activation
idInlineActivation Id
fn))
        -- Don't specialise NOINLINE things
        -- See Note [Auto-specialisation and RULES]

--   && not (certainlyWillInline (idUnfolding fn))      -- And it's not small
--      See Note [Inline specialisation] for why we do not
--      switch off specialisation for inline functions

  = -- pprTrace "specDefn: some" (ppr fn $$ ppr calls_for_me $$ ppr existing_rules) $
    (([CoreRule], [(Id, Expr Id)], UsageDetails)
 -> CallInfo -> SpecM ([CoreRule], [(Id, Expr Id)], UsageDetails))
-> ([CoreRule], [(Id, Expr Id)], UsageDetails)
-> [CallInfo]
-> SpecM ([CoreRule], [(Id, Expr Id)], UsageDetails)
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM ([CoreRule], [(Id, Expr Id)], UsageDetails)
-> CallInfo -> SpecM ([CoreRule], [(Id, Expr Id)], UsageDetails)
spec_call ([], [], UsageDetails
emptyUDs) [CallInfo]
calls_for_me

  | Bool
otherwise   -- No calls or RHS doesn't fit our preconceptions
  = WARN( not (exprIsTrivial rhs) && notNull calls_for_me,
          text "Missed specialisation opportunity for"
                                 <+> ppr fn $$ _trace_doc )
          -- Note [Specialisation shape]
    -- pprTrace "specDefn: none" (ppr fn <+> ppr calls_for_me) $
    ([CoreRule], [(Id, Expr Id)], UsageDetails)
-> SpecM ([CoreRule], [(Id, Expr Id)], UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ([], [], UsageDetails
emptyUDs)
  where
    _trace_doc :: SDoc
_trace_doc = [SDoc] -> SDoc
sep [ [Id] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Id]
rhs_bndrs, Activation -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Id -> Activation
idInlineActivation Id
fn) ]

    fn_type :: Type
fn_type   = Id -> Type
idType Id
fn
    fn_arity :: Int
fn_arity  = Id -> Int
idArity Id
fn
    fn_unf :: Unfolding
fn_unf    = Id -> Unfolding
realIdUnfolding Id
fn  -- Ignore loop-breaker-ness here
    inl_prag :: InlinePragma
inl_prag  = Id -> InlinePragma
idInlinePragma Id
fn
    inl_act :: Activation
inl_act   = InlinePragma -> Activation
inlinePragmaActivation InlinePragma
inl_prag
    is_local :: Bool
is_local  = Id -> Bool
isLocalId Id
fn
    is_dfun :: Bool
is_dfun   = Id -> Bool
isDFunId Id
fn

        -- Figure out whether the function has an INLINE pragma
        -- See Note [Inline specialisations]

    ([Id]
rhs_bndrs, Expr Id
rhs_body) = Expr Id -> ([Id], Expr Id)
collectBindersPushingCo Expr Id
rhs
                            -- See Note [Account for casts in binding]

    in_scope :: InScopeSet
in_scope = Subst -> InScopeSet
Core.substInScope (SpecEnv -> Subst
se_subst SpecEnv
env)

    already_covered :: DynFlags -> [CoreRule] -> [CoreExpr] -> Bool
    already_covered :: DynFlags -> [CoreRule] -> [Expr Id] -> Bool
already_covered DynFlags
dflags [CoreRule]
new_rules [Expr Id]
args      -- Note [Specialisations already covered]
       = Maybe (CoreRule, Expr Id) -> Bool
forall a. Maybe a -> Bool
isJust (DynFlags
-> InScopeEnv
-> (Activation -> Bool)
-> Id
-> [Expr Id]
-> [CoreRule]
-> Maybe (CoreRule, Expr Id)
lookupRule DynFlags
dflags (InScopeSet
in_scope, Id -> Unfolding
realIdUnfolding)
                            (Bool -> Activation -> Bool
forall a b. a -> b -> a
const Bool
True) Id
fn [Expr Id]
args
                            ([CoreRule]
new_rules [CoreRule] -> [CoreRule] -> [CoreRule]
forall a. [a] -> [a] -> [a]
++ [CoreRule]
existing_rules))
         -- NB: we look both in the new_rules (generated by this invocation
         --     of specCalls), and in existing_rules (passed in to specCalls)

    ----------------------------------------------------------
        -- Specialise to one particular call pattern
    spec_call :: SpecInfo                         -- Accumulating parameter
              -> CallInfo                         -- Call instance
              -> SpecM SpecInfo
    spec_call :: ([CoreRule], [(Id, Expr Id)], UsageDetails)
-> CallInfo -> SpecM ([CoreRule], [(Id, Expr Id)], UsageDetails)
spec_call spec_acc :: ([CoreRule], [(Id, Expr Id)], UsageDetails)
spec_acc@([CoreRule]
rules_acc, [(Id, Expr Id)]
pairs_acc, UsageDetails
uds_acc) _ci :: CallInfo
_ci@(CI { ci_key :: CallInfo -> [SpecArg]
ci_key = [SpecArg]
call_args })
      = -- See Note [Specialising Calls]
        do { let all_call_args :: [SpecArg]
all_call_args | Bool
is_dfun   = [SpecArg]
call_args [SpecArg] -> [SpecArg] -> [SpecArg]
forall a. [a] -> [a] -> [a]
++ SpecArg -> [SpecArg]
forall a. a -> [a]
repeat SpecArg
UnspecArg
                               | Bool
otherwise = [SpecArg]
call_args
                               -- See Note [Specialising DFuns]
           ; ( Bool
useful, SpecEnv
rhs_env2, [Id]
leftover_bndrs
             , [Id]
rule_bndrs, [Expr Id]
rule_lhs_args
             , [Id]
spec_bndrs1, [DictBind]
dx_binds, [Expr Id]
spec_args) <- SpecEnv
-> [Id]
-> [SpecArg]
-> SpecM
     (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
specHeader SpecEnv
env [Id]
rhs_bndrs [SpecArg]
all_call_args

--           ; pprTrace "spec_call" (vcat [ text "call info: " <+> ppr _ci
--                                        , text "useful:    " <+> ppr useful
--                                        , text "rule_bndrs:" <+> ppr rule_bndrs
--                                        , text "lhs_args:  " <+> ppr rule_lhs_args
--                                        , text "spec_bndrs:" <+> ppr spec_bndrs1
--                                        , text "spec_args: " <+> ppr spec_args
--                                        , text "dx_binds:  " <+> ppr dx_binds
--                                        , text "rhs_env2:  " <+> ppr (se_subst rhs_env2)
--                                        , ppr dx_binds ]) $
--             return ()

           ; DynFlags
dflags <- SpecM DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
           ; if Bool -> Bool
not Bool
useful  -- No useful specialisation
                Bool -> Bool -> Bool
|| DynFlags -> [CoreRule] -> [Expr Id] -> Bool
already_covered DynFlags
dflags [CoreRule]
rules_acc [Expr Id]
rule_lhs_args
             then ([CoreRule], [(Id, Expr Id)], UsageDetails)
-> SpecM ([CoreRule], [(Id, Expr Id)], UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ([CoreRule], [(Id, Expr Id)], UsageDetails)
spec_acc
             else
        do { -- Run the specialiser on the specialised RHS
             -- The "1" suffix is before we maybe add the void arg
           ; (Expr Id
spec_rhs1, UsageDetails
rhs_uds) <- SpecEnv -> [Id] -> Expr Id -> SpecM (Expr Id, UsageDetails)
specLam SpecEnv
rhs_env2 ([Id]
spec_bndrs1 [Id] -> [Id] -> [Id]
forall a. [a] -> [a] -> [a]
++ [Id]
leftover_bndrs) Expr Id
rhs_body
           ; let spec_fn_ty1 :: Type
spec_fn_ty1 = Expr Id -> Type
exprType Expr Id
spec_rhs1

                 -- Maybe add a void arg to the specialised function,
                 -- to avoid unlifted bindings
                 -- See Note [Specialisations Must Be Lifted]
                 -- C.f. GHC.Core.Op.WorkWrap.Lib.mkWorkerArgs
                 add_void_arg :: Bool
add_void_arg = HasDebugCallStack => Type -> Bool
Type -> Bool
isUnliftedType Type
spec_fn_ty1 Bool -> Bool -> Bool
&& Bool -> Bool
not (Id -> Bool
isJoinId Id
fn)
                 ([Id]
spec_bndrs, Expr Id
spec_rhs, Type
spec_fn_ty)
                   | Bool
add_void_arg = ( Id
voidPrimId Id -> [Id] -> [Id]
forall a. a -> [a] -> [a]
: [Id]
spec_bndrs1
                                    , Id -> Expr Id -> Expr Id
forall b. b -> Expr b -> Expr b
Lam        Id
voidArgId  Expr Id
spec_rhs1
                                    , Type -> Type -> Type
mkVisFunTy Type
voidPrimTy Type
spec_fn_ty1)
                   | Bool
otherwise   = ([Id]
spec_bndrs1, Expr Id
spec_rhs1, Type
spec_fn_ty1)

                 join_arity_decr :: Int
join_arity_decr = [Expr Id] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Expr Id]
rule_lhs_args Int -> Int -> Int
forall a. Num a => a -> a -> a
- [Id] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Id]
spec_bndrs
                 spec_join_arity :: Maybe Int
spec_join_arity | Just Int
orig_join_arity <- Id -> Maybe Int
isJoinId_maybe Id
fn
                                 = Int -> Maybe Int
forall a. a -> Maybe a
Just (Int
orig_join_arity Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
join_arity_decr)
                                 | Bool
otherwise
                                 = Maybe Int
forall a. Maybe a
Nothing

           ; Id
spec_fn <- Id -> Type -> Maybe Int -> SpecM Id
newSpecIdSM Id
fn Type
spec_fn_ty Maybe Int
spec_join_arity
           ; Module
this_mod <- SpecM Module
forall (m :: * -> *). HasModule m => m Module
getModule
           ; let
                -- The rule to put in the function's specialisation is:
                --      forall x @b d1' d2'.
                --          f x @T1 @b @T2 d1' d2' = f1 x @b
                -- See Note [Specialising Calls]
                herald :: SDoc
herald = case Maybe Module
mb_mod of
                           Maybe Module
Nothing        -- Specialising local fn
                               -> String -> SDoc
text String
"SPEC"
                           Just Module
this_mod  -- Specialising imported fn
                               -> String -> SDoc
text String
"SPEC/" SDoc -> SDoc -> SDoc
<> Module -> SDoc
forall a. Outputable a => a -> SDoc
ppr Module
this_mod

                rule_name :: FastString
rule_name = String -> FastString
mkFastString (String -> FastString) -> String -> FastString
forall a b. (a -> b) -> a -> b
$ DynFlags -> SDoc -> String
showSDoc DynFlags
dflags (SDoc -> String) -> SDoc -> String
forall a b. (a -> b) -> a -> b
$
                            SDoc
herald SDoc -> SDoc -> SDoc
<+> FastString -> SDoc
ftext (OccName -> FastString
occNameFS (Id -> OccName
forall a. NamedThing a => a -> OccName
getOccName Id
fn))
                                   SDoc -> SDoc -> SDoc
<+> [SDoc] -> SDoc
hsep ((SpecArg -> Maybe SDoc) -> [SpecArg] -> [SDoc]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe SpecArg -> Maybe SDoc
ppr_call_key_ty [SpecArg]
call_args)
                            -- This name ends up in interface files, so use occNameString.
                            -- Otherwise uniques end up there, making builds
                            -- less deterministic (See #4012 comment:61 ff)

                rule_wout_eta :: CoreRule
rule_wout_eta = Module
-> Bool
-> Bool
-> FastString
-> Activation
-> Name
-> [Id]
-> [Expr Id]
-> Expr Id
-> CoreRule
mkRule
                                  Module
this_mod
                                  Bool
True {- Auto generated -}
                                  Bool
is_local
                                  FastString
rule_name
                                  Activation
inl_act       -- Note [Auto-specialisation and RULES]
                                  (Id -> Name
idName Id
fn)
                                  [Id]
rule_bndrs
                                  [Expr Id]
rule_lhs_args
                                  (Expr Id -> [Id] -> Expr Id
forall b. Expr b -> [Id] -> Expr b
mkVarApps (Id -> Expr Id
forall b. Id -> Expr b
Var Id
spec_fn) [Id]
spec_bndrs)

                spec_rule :: CoreRule
spec_rule
                  = case Id -> Maybe Int
isJoinId_maybe Id
fn of
                      Just Int
join_arity -> Int -> CoreRule -> CoreRule
etaExpandToJoinPointRule Int
join_arity CoreRule
rule_wout_eta
                      Maybe Int
Nothing -> CoreRule
rule_wout_eta

                -- Add the { d1' = dx1; d2' = dx2 } usage stuff
                -- See Note [Specialising Calls]
                spec_uds :: UsageDetails
spec_uds = (DictBind -> UsageDetails -> UsageDetails)
-> UsageDetails -> [DictBind] -> UsageDetails
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr DictBind -> UsageDetails -> UsageDetails
consDictBind UsageDetails
rhs_uds [DictBind]
dx_binds

                --------------------------------------
                -- Add a suitable unfolding if the spec_inl_prag says so
                -- See Note [Inline specialisations]
                (InlinePragma
spec_inl_prag, Unfolding
spec_unf)
                  | Bool -> Bool
not Bool
is_local Bool -> Bool -> Bool
&& OccInfo -> Bool
isStrongLoopBreaker (Id -> OccInfo
idOccInfo Id
fn)
                  = (InlinePragma
neverInlinePragma, Unfolding
noUnfolding)
                        -- See Note [Specialising imported functions] in OccurAnal

                  | InlinePragma { inl_inline :: InlinePragma -> InlineSpec
inl_inline = InlineSpec
Inlinable } <- InlinePragma
inl_prag
                  = (InlinePragma
inl_prag { inl_inline :: InlineSpec
inl_inline = InlineSpec
NoUserInline }, Unfolding
noUnfolding)

                  | Bool
otherwise
                  = (InlinePragma
inl_prag, DynFlags
-> [Id]
-> (Expr Id -> Expr Id)
-> [Expr Id]
-> Unfolding
-> Unfolding
specUnfolding DynFlags
dflags [Id]
spec_bndrs (Expr Id -> [Expr Id] -> Expr Id
forall b. Expr b -> [Expr b] -> Expr b
`mkApps` [Expr Id]
spec_args)
                                             [Expr Id]
rule_lhs_args Unfolding
fn_unf)

                --------------------------------------
                -- Adding arity information just propagates it a bit faster
                --      See Note [Arity decrease] in Simplify
                -- Copy InlinePragma information from the parent Id.
                -- So if f has INLINE[1] so does spec_fn
                arity_decr :: Int
arity_decr     = (Expr Id -> Bool) -> [Expr Id] -> Int
forall a. (a -> Bool) -> [a] -> Int
count Expr Id -> Bool
forall b. Expr b -> Bool
isValArg [Expr Id]
rule_lhs_args Int -> Int -> Int
forall a. Num a => a -> a -> a
- (Id -> Bool) -> [Id] -> Int
forall a. (a -> Bool) -> [a] -> Int
count Id -> Bool
isId [Id]
spec_bndrs
                spec_f_w_arity :: Id
spec_f_w_arity = Id
spec_fn Id -> Int -> Id
`setIdArity`      Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 (Int
fn_arity Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
arity_decr)
                                         Id -> InlinePragma -> Id
`setInlinePragma` InlinePragma
spec_inl_prag
                                         Id -> Unfolding -> Id
`setIdUnfolding`  Unfolding
spec_unf
                                         Id -> Maybe Int -> Id
`asJoinId_maybe`  Maybe Int
spec_join_arity

                _rule_trace_doc :: SDoc
_rule_trace_doc = [SDoc] -> SDoc
vcat [ Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
fn SDoc -> SDoc -> SDoc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
fn_type
                                       , Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
spec_fn  SDoc -> SDoc -> SDoc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
spec_fn_ty
                                       , [Id] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Id]
rhs_bndrs, [SpecArg] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [SpecArg]
call_args
                                       , CoreRule -> SDoc
forall a. Outputable a => a -> SDoc
ppr CoreRule
spec_rule
                                       ]

           ; -- pprTrace "spec_call: rule" _rule_trace_doc
             ([CoreRule], [(Id, Expr Id)], UsageDetails)
-> SpecM ([CoreRule], [(Id, Expr Id)], UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ( CoreRule
spec_rule                  CoreRule -> [CoreRule] -> [CoreRule]
forall a. a -> [a] -> [a]
: [CoreRule]
rules_acc
                    , (Id
spec_f_w_arity, Expr Id
spec_rhs) (Id, Expr Id) -> [(Id, Expr Id)] -> [(Id, Expr Id)]
forall a. a -> [a] -> [a]
: [(Id, Expr Id)]
pairs_acc
                    , UsageDetails
spec_uds           UsageDetails -> UsageDetails -> UsageDetails
`plusUDs` UsageDetails
uds_acc
                    ) } }

{- Note [Specialising DFuns]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DFuns have a special sort of unfolding (DFunUnfolding), and these are
hard to specialise a DFunUnfolding to give another DFunUnfolding
unless the DFun is fully applied (#18120).  So, in the case of DFunIds
we simply extend the CallKey with trailing UnspecArgs, so we'll
generate a rule that completely saturates the DFun.

There is an ASSERT that checks this, in the DFunUnfolding case of
GHC.Core.Unfold.specUnfolding.

Note [Specialisation Must Preserve Sharing]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider a function:

    f :: forall a. Eq a => a -> blah
    f =
      if expensive
         then f1
         else f2

As written, all calls to 'f' will share 'expensive'. But if we specialise 'f'
at 'Int', eg:

    $sfInt = SUBST[a->Int,dict->dEqInt] (if expensive then f1 else f2)

    RULE "SPEC f"
      forall (d :: Eq Int).
        f Int _ = $sfIntf

We've now lost sharing between 'f' and '$sfInt' for 'expensive'. Yikes!

To avoid this, we only generate specialisations for functions whose arity is
enough to bind all of the arguments we need to specialise.  This ensures our
specialised functions don't do any work before receiving all of their dicts,
and thus avoids the 'f' case above.

Note [Specialisations Must Be Lifted]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider a function 'f':

    f = forall a. Eq a => Array# a

used like

    case x of
      True -> ...f @Int dEqInt...
      False -> 0

Naively, we might generate an (expensive) specialisation

    $sfInt :: Array# Int

even in the case that @x = False@! Instead, we add a dummy 'Void#' argument to
the specialisation '$sfInt' ($sfInt :: Void# -> Array# Int) in order to
preserve laziness.

Note [Specialising Calls]
~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have a function with a complicated type:

    f :: forall a b c. Int -> Eq a => Show b => c -> Blah
    f @a @b @c i dEqA dShowA x = blah

and suppose it is called at:

    f 7 @T1 @T2 @T3 dEqT1 ($dfShow dShowT2) t3

This call is described as a 'CallInfo' whose 'ci_key' is:

    [ SpecType T1, SpecType T2, UnspecType, UnspecArg, SpecDict dEqT1
    , SpecDict ($dfShow dShowT2), UnspecArg ]

Why are 'a' and 'b' identified as 'SpecType', while 'c' is 'UnspecType'?
Because we must specialise the function on type variables that appear
free in its *dictionary* arguments; but not on type variables that do not
appear in any dictionaries, i.e. are fully polymorphic.

Because this call has dictionaries applied, we'd like to specialise
the call on any type argument that appears free in those dictionaries.
In this case, those are [a :-> T1, b :-> T2].

We also need to substitute the dictionary binders with their
specialised dictionaries. The simplest substitution would be
[dEqA :-> dEqT1, dShowA :-> $dfShow dShowT2], but this duplicates
work, since `$dfShow dShowT2` is a function application. Therefore, we
also want to *float the dictionary out* (via bindAuxiliaryDict),
creating a new dict binding

    dShow1 = $dfShow dShowT2

and the substitution [dEqA :-> dEqT1, dShowA :-> dShow1].

With the substitutions in hand, we can generate a specialised function:

    $sf :: forall c. Int -> c -> Blah
    $sf = SUBST[a :-> T1, b :-> T2, dEqA :-> dEqT1, dShowA :-> dShow1] (\@c i x -> blah)

Note that the substitution is applied to the whole thing.  This is
convenient, but just slightly fragile.  Notably:
  * There had better be no name clashes in a/b/c

We must construct a rewrite rule:

    RULE "SPEC f @T1 @T2 _"
      forall (@c :: Type) (i :: Int) (d1 :: Eq T1) (d2 :: Show T2).
        f @T1 @T2 @c i d1 d2 = $sf @c i

In the rule, d1 and d2 are just wildcards, not used in the RHS.  Note
additionally that 'x' isn't captured by this rule --- we bind only
enough etas in order to capture all of the *specialised* arguments.

Note [Drop dead args from specialisations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When specialising a function, it’s possible some of the arguments may
actually be dead. For example, consider:

    f :: forall a. () -> Show a => a -> String
    f x y = show y ++ "!"

We might generate the following CallInfo for `f @Int`:

    [SpecType Int, UnspecArg, SpecDict $dShowInt, UnspecArg]

Normally we’d include both the x and y arguments in the
specialisation, since we’re not specialising on either of them. But
that’s silly, since x is actually unused! So we might as well drop it
in the specialisation:

    $sf :: Int -> String
    $sf y = show y ++ "!"

    {-# RULE "SPEC f @Int" forall x. f @Int x $dShow = $sf #-}

This doesn’t save us much, since the arg would be removed later by
worker/wrapper, anyway, but it’s easy to do. Note, however, that we
only drop dead arguments if:

  1. We don’t specialise on them.
  2. They come before an argument we do specialise on.

Doing the latter would require eta-expanding the RULE, which could
make it match less often, so it’s not worth it. Doing the former could
be more useful --- it would stop us from generating pointless
specialisations --- but it’s more involved to implement and unclear if
it actually provides much benefit in practice.

Note [Zap occ info in rule binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we generate a specialisation RULE, we need to drop occurrence
info on the binders. If we don’t, things go wrong when we specialise a
function like

    f :: forall a. () -> Show a => a -> String
    f x y = show y ++ "!"

since we’ll generate a RULE like

    RULE "SPEC f @Int" forall x [Occ=Dead].
      f @Int x $dShow = $sf

and Core Lint complains, even though x only appears on the LHS (due to
Note [Drop dead args from specialisations]).

Why is that a Lint error? Because the arguments on the LHS of a rule
are syntactically expressions, not patterns, so Lint treats the
appearance of x as a use rather than a binding. Fortunately, the
solution is simple: we just make sure to zap the occ info before
using ids as wildcard binders in a rule.

Note [Account for casts in binding]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
   f :: Eq a => a -> IO ()
   {-# INLINABLE f
       StableUnf = (/\a \(d:Eq a) (x:a). blah) |> g
     #-}
   f = ...

In f's stable unfolding we have done some modest simplification which
has pushed the cast to the outside.  (I wonder if this is the Right
Thing, but it's what happens now; see SimplUtils Note [Casts and
lambdas].)  Now that stable unfolding must be specialised, so we want
to push the cast back inside. It would be terrible if the cast
defeated specialisation!  Hence the use of collectBindersPushingCo.

Note [Evidence foralls]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose (#12212) that we are specialising
   f :: forall a b. (Num a, F a ~ F b) => blah
with a=b=Int. Then the RULE will be something like
   RULE forall (d:Num Int) (g :: F Int ~ F Int).
        f Int Int d g = f_spec
But both varToCoreExpr (when constructing the LHS args), and the
simplifier (when simplifying the LHS args), will transform to
   RULE forall (d:Num Int) (g :: F Int ~ F Int).
        f Int Int d <F Int> = f_spec
by replacing g with Refl.  So now 'g' is unbound, which results in a later
crash. So we use Refl right off the bat, and do not forall-quantify 'g':
 * varToCoreExpr generates a Refl
 * exprsFreeIdsList returns the Ids bound by the args,
   which won't include g

You might wonder if this will match as often, but the simplifier replaces
complicated Refl coercions with Refl pretty aggressively.

Note [Orphans and auto-generated rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we specialise an INLINABLE function, or when we have
-fspecialise-aggressively, we auto-generate RULES that are orphans.
We don't want to warn about these, or we'd generate a lot of warnings.
Thus, we only warn about user-specified orphan rules.

Indeed, we don't even treat the module as an orphan module if it has
auto-generated *rule* orphans.  Orphan modules are read every time we
compile, so they are pretty obtrusive and slow down every compilation,
even non-optimised ones.  (Reason: for type class instances it's a
type correctness issue.)  But specialisation rules are strictly for
*optimisation* only so it's fine not to read the interface.

What this means is that a SPEC rules from auto-specialisation in
module M will be used in other modules only if M.hi has been read for
some other reason, which is actually pretty likely.

Note [From non-recursive to recursive]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Even in the non-recursive case, if any dict-binds depend on 'fn' we might
have built a recursive knot

      f a d x = <blah>
      MkUD { ud_binds = NonRec d7  (MkD ..f..)
           , ud_calls = ...(f T d7)... }

The we generate

     Rec { fs x = <blah>[T/a, d7/d]
           f a d x = <blah>
               RULE f T _ = fs
           d7 = ...f... }

Here the recursion is only through the RULE.

However we definitely should /not/ make the Rec in this wildly common
case:
      d = ...
      MkUD { ud_binds = NonRec d7 (...d...)
           , ud_calls = ...(f T d7)... }

Here we want simply to add d to the floats, giving
      MkUD { ud_binds = NonRec d (...)
                        NonRec d7 (...d...)
           , ud_calls = ...(f T d7)... }

In general, we need only make this Rec if
  - there are some specialisations (spec_binds non-empty)
  - there are some dict_binds that depend on f (dump_dbs non-empty)

Note [Avoiding loops]
~~~~~~~~~~~~~~~~~~~~~
When specialising /dictionary functions/ we must be very careful to
avoid building loops. Here is an example that bit us badly: #3591

     class Eq a => C a
     instance Eq [a] => C [a]

This translates to
     dfun :: Eq [a] -> C [a]
     dfun a d = MkD a d (meth d)

     d4 :: Eq [T] = <blah>
     d2 ::  C [T] = dfun T d4
     d1 :: Eq [T] = $p1 d2
     d3 ::  C [T] = dfun T d1

None of these definitions is recursive. What happened was that we
generated a specialisation:

     RULE forall d. dfun T d = dT  :: C [T]
     dT = (MkD a d (meth d)) [T/a, d1/d]
        = MkD T d1 (meth d1)

But now we use the RULE on the RHS of d2, to get

    d2 = dT = MkD d1 (meth d1)
    d1 = $p1 d2

and now d1 is bottom!  The problem is that when specialising 'dfun' we
should first dump "below" the binding all floated dictionary bindings
that mention 'dfun' itself.  So d2 and d3 (and hence d1) must be
placed below 'dfun', and thus unavailable to it when specialising
'dfun'.  That in turn means that the call (dfun T d1) must be
discarded.  On the other hand, the call (dfun T d4) is fine, assuming
d4 doesn't mention dfun.

Solution:
  Discard all calls that mention dictionaries that depend
  (directly or indirectly) on the dfun we are specialising.
  This is done by 'filterCalls'

--------------
Here's another example, this time for an imported dfun, so the call
to filterCalls is in specImports (#13429). Suppose we have
  class Monoid v => C v a where ...

We start with a call
   f @ [Integer] @ Integer $fC[]Integer

Specialising call to 'f' gives dict bindings
   $dMonoid_1 :: Monoid [Integer]
   $dMonoid_1 = M.$p1C @ [Integer] $fC[]Integer

   $dC_1 :: C [Integer] (Node [Integer] Integer)
   $dC_1 = M.$fCvNode @ [Integer] $dMonoid_1

...plus a recursive call to
   f @ [Integer] @ (Node [Integer] Integer) $dC_1

Specialising that call gives
   $dMonoid_2  :: Monoid [Integer]
   $dMonoid_2  = M.$p1C @ [Integer] $dC_1

   $dC_2 :: C [Integer] (Node [Integer] Integer)
   $dC_2 = M.$fCvNode @ [Integer] $dMonoid_2

Now we have two calls to the imported function
  M.$fCvNode :: Monoid v => C v a
  M.$fCvNode @v @a m = C m some_fun

But we must /not/ use the call (M.$fCvNode @ [Integer] $dMonoid_2)
for specialisation, else we get:

  $dC_1 = M.$fCvNode @ [Integer] $dMonoid_1
  $dMonoid_2 = M.$p1C @ [Integer] $dC_1
  $s$fCvNode = C $dMonoid_2 ...
    RULE M.$fCvNode [Integer] _ _ = $s$fCvNode

Now use the rule to rewrite the call in the RHS of $dC_1
and we get a loop!

--------------
Here's yet another example

  class C a where { foo,bar :: [a] -> [a] }

  instance C Int where
     foo x = r_bar x
     bar xs = reverse xs

  r_bar :: C a => [a] -> [a]
  r_bar xs = bar (xs ++ xs)

That translates to:

    r_bar a (c::C a) (xs::[a]) = bar a d (xs ++ xs)

    Rec { $fCInt :: C Int = MkC foo_help reverse
          foo_help (xs::[Int]) = r_bar Int $fCInt xs }

The call (r_bar $fCInt) mentions $fCInt,
                        which mentions foo_help,
                        which mentions r_bar
But we DO want to specialise r_bar at Int:

    Rec { $fCInt :: C Int = MkC foo_help reverse
          foo_help (xs::[Int]) = r_bar Int $fCInt xs

          r_bar a (c::C a) (xs::[a]) = bar a d (xs ++ xs)
            RULE r_bar Int _ = r_bar_Int

          r_bar_Int xs = bar Int $fCInt (xs ++ xs)
           }

Note that, because of its RULE, r_bar joins the recursive
group.  (In this case it'll unravel a short moment later.)


Note [Specialising a recursive group]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
    let rec { f x = ...g x'...
            ; g y = ...f y'.... }
    in f 'a'
Here we specialise 'f' at Char; but that is very likely to lead to
a specialisation of 'g' at Char.  We must do the latter, else the
whole point of specialisation is lost.

But we do not want to keep iterating to a fixpoint, because in the
presence of polymorphic recursion we might generate an infinite number
of specialisations.

So we use the following heuristic:
  * Arrange the rec block in dependency order, so far as possible
    (the occurrence analyser already does this)

  * Specialise it much like a sequence of lets

  * Then go through the block a second time, feeding call-info from
    the RHSs back in the bottom, as it were

In effect, the ordering maxmimises the effectiveness of each sweep,
and we do just two sweeps.   This should catch almost every case of
monomorphic recursion -- the exception could be a very knotted-up
recursion with multiple cycles tied up together.

This plan is implemented in the Rec case of specBindItself.

Note [Specialisations already covered]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We obviously don't want to generate two specialisations for the same
argument pattern.  There are two wrinkles

1. We do the already-covered test in specDefn, not when we generate
the CallInfo in mkCallUDs.  We used to test in the latter place, but
we now iterate the specialiser somewhat, and the Id at the call site
might therefore not have all the RULES that we can see in specDefn

2. What about two specialisations where the second is an *instance*
of the first?  If the more specific one shows up first, we'll generate
specialisations for both.  If the *less* specific one shows up first,
we *don't* currently generate a specialisation for the more specific
one.  (See the call to lookupRule in already_covered.)  Reasons:
  (a) lookupRule doesn't say which matches are exact (bad reason)
  (b) if the earlier specialisation is user-provided, it's
      far from clear that we should auto-specialise further

Note [Auto-specialisation and RULES]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider:
   g :: Num a => a -> a
   g = ...

   f :: (Int -> Int) -> Int
   f w = ...
   {-# RULE f g = 0 #-}

Suppose that auto-specialisation makes a specialised version of
g::Int->Int That version won't appear in the LHS of the RULE for f.
So if the specialisation rule fires too early, the rule for f may
never fire.

It might be possible to add new rules, to "complete" the rewrite system.
Thus when adding
        RULE forall d. g Int d = g_spec
also add
        RULE f g_spec = 0

But that's a bit complicated.  For now we ask the programmer's help,
by *copying the INLINE activation pragma* to the auto-specialised
rule.  So if g says {-# NOINLINE[2] g #-}, then the auto-spec rule
will also not be active until phase 2.  And that's what programmers
should jolly well do anyway, even aside from specialisation, to ensure
that g doesn't inline too early.

This in turn means that the RULE would never fire for a NOINLINE
thing so not much point in generating a specialisation at all.

Note [Specialisation shape]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
We only specialise a function if it has visible top-level lambdas
corresponding to its overloading.  E.g. if
        f :: forall a. Eq a => ....
then its body must look like
        f = /\a. \d. ...

Reason: when specialising the body for a call (f ty dexp), we want to
substitute dexp for d, and pick up specialised calls in the body of f.

This doesn't always work.  One example I came across was this:
        newtype Gen a = MkGen{ unGen :: Int -> a }

        choose :: Eq a => a -> Gen a
        choose n = MkGen (\r -> n)

        oneof = choose (1::Int)

It's a silly example, but we get
        choose = /\a. g `cast` co
where choose doesn't have any dict arguments.  Thus far I have not
tried to fix this (wait till there's a real example).

Mind you, then 'choose' will be inlined (since RHS is trivial) so
it doesn't matter.  This comes up with single-method classes

   class C a where { op :: a -> a }
   instance C a => C [a] where ....
==>
   $fCList :: C a => C [a]
   $fCList = $copList |> (...coercion>...)
   ....(uses of $fCList at particular types)...

So we suppress the WARN if the rhs is trivial.

Note [Inline specialisations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is what we do with the InlinePragma of the original function
  * Activation/RuleMatchInfo: both transferred to the
                              specialised function
  * InlineSpec:
       (a) An INLINE pragma is transferred
       (b) An INLINABLE pragma is *not* transferred

Why (a): transfer INLINE pragmas? The point of INLINE was precisely to
specialise the function at its call site, and arguably that's not so
important for the specialised copies.  BUT *pragma-directed*
specialisation now takes place in the typechecker/desugarer, with
manually specified INLINEs.  The specialisation here is automatic.
It'd be very odd if a function marked INLINE was specialised (because
of some local use), and then forever after (including importing
modules) the specialised version wasn't INLINEd.  After all, the
programmer said INLINE!

You might wonder why we specialise INLINE functions at all.  After
all they should be inlined, right?  Two reasons:

 * Even INLINE functions are sometimes not inlined, when they aren't
   applied to interesting arguments.  But perhaps the type arguments
   alone are enough to specialise (even though the args are too boring
   to trigger inlining), and it's certainly better to call the
   specialised version.

 * The RHS of an INLINE function might call another overloaded function,
   and we'd like to generate a specialised version of that function too.
   This actually happens a lot. Consider
      replicateM_ :: (Monad m) => Int -> m a -> m ()
      {-# INLINABLE replicateM_ #-}
      replicateM_ d x ma = ...
   The strictness analyser may transform to
      replicateM_ :: (Monad m) => Int -> m a -> m ()
      {-# INLINE replicateM_ #-}
      replicateM_ d x ma = case x of I# x' -> $wreplicateM_ d x' ma

      $wreplicateM_ :: (Monad m) => Int# -> m a -> m ()
      {-# INLINABLE $wreplicateM_ #-}
      $wreplicateM_ = ...
   Now an importing module has a specialised call to replicateM_, say
   (replicateM_ dMonadIO).  We certainly want to specialise $wreplicateM_!
   This particular example had a huge effect on the call to replicateM_
   in nofib/shootout/n-body.

Why (b): discard INLINABLE pragmas? See #4874 for persuasive examples.
Suppose we have
    {-# INLINABLE f #-}
    f :: Ord a => [a] -> Int
    f xs = letrec f' = ...f'... in f'
Then, when f is specialised and optimised we might get
    wgo :: [Int] -> Int#
    wgo = ...wgo...
    f_spec :: [Int] -> Int
    f_spec xs = case wgo xs of { r -> I# r }
and we clearly want to inline f_spec at call sites.  But if we still
have the big, un-optimised of f (albeit specialised) captured in an
INLINABLE pragma for f_spec, we won't get that optimisation.

So we simply drop INLINABLE pragmas when specialising. It's not really
a complete solution; ignoring specialisation for now, INLINABLE functions
don't get properly strictness analysed, for example. But it works well
for examples involving specialisation, which is the dominant use of
INLINABLE.  See #4874.
-}

{- *********************************************************************
*                                                                      *
                   SpecArg, and specHeader
*                                                                      *
********************************************************************* -}

-- | An argument that we might want to specialise.
-- See Note [Specialising Calls] for the nitty gritty details.
data SpecArg
  =
    -- | Type arguments that should be specialised, due to appearing
    -- free in the type of a 'SpecDict'.
    SpecType Type

    -- | Type arguments that should remain polymorphic.
  | UnspecType

    -- | Dictionaries that should be specialised. mkCallUDs ensures
    -- that only "interesting" dictionary arguments get a SpecDict;
    -- see Note [Interesting dictionary arguments]
  | SpecDict DictExpr

    -- | Value arguments that should not be specialised.
  | UnspecArg

instance Outputable SpecArg where
  ppr :: SpecArg -> SDoc
ppr (SpecType Type
t) = String -> SDoc
text String
"SpecType" SDoc -> SDoc -> SDoc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
t
  ppr SpecArg
UnspecType   = String -> SDoc
text String
"UnspecType"
  ppr (SpecDict Expr Id
d) = String -> SDoc
text String
"SpecDict" SDoc -> SDoc -> SDoc
<+> Expr Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Expr Id
d
  ppr SpecArg
UnspecArg    = String -> SDoc
text String
"UnspecArg"

specArgFreeVars :: SpecArg -> VarSet
specArgFreeVars :: SpecArg -> VarSet
specArgFreeVars (SpecType Type
ty) = Type -> VarSet
tyCoVarsOfType Type
ty
specArgFreeVars (SpecDict Expr Id
dx) = Expr Id -> VarSet
exprFreeVars Expr Id
dx
specArgFreeVars SpecArg
UnspecType    = VarSet
emptyVarSet
specArgFreeVars SpecArg
UnspecArg     = VarSet
emptyVarSet

isSpecDict :: SpecArg -> Bool
isSpecDict :: SpecArg -> Bool
isSpecDict (SpecDict {}) = Bool
True
isSpecDict SpecArg
_             = Bool
False

-- | Given binders from an original function 'f', and the 'SpecArg's
-- corresponding to its usage, compute everything necessary to build
-- a specialisation.
--
-- We will use the running example from Note [Specialising Calls]:
--
--     f :: forall a b c. Int -> Eq a => Show b => c -> Blah
--     f @a @b @c i dEqA dShowA x = blah
--
-- Suppose we decide to specialise it at the following pattern:
--
--     [ SpecType T1, SpecType T2, UnspecType, UnspecArg
--     , SpecDict dEqT1, SpecDict ($dfShow dShowT2), UnspecArg ]
--
-- We'd eventually like to build the RULE
--
--     RULE "SPEC f @T1 @T2 _"
--       forall (@c :: Type) (i :: Int) (d1 :: Eq T1) (d2 :: Show T2).
--         f @T1 @T2 @c i d1 d2 = $sf @c i
--
-- and the specialisation '$sf'
--
--     $sf :: forall c. Int -> c -> Blah
--     $sf = SUBST[a :-> T1, b :-> T2, dEqA :-> dEqT1, dShowA :-> dShow1] (\@c i x -> blah)
--
-- where dShow1 is a floated binding created by bindAuxiliaryDict.
--
-- The cases for 'specHeader' below are presented in the same order as this
-- running example. The result of 'specHeader' for this example is as follows:
--
--    ( -- Returned arguments
--      env + [a :-> T1, b :-> T2, dEqA :-> dEqT1, dShowA :-> dShow1]
--    , [x]
--
--      -- RULE helpers
--    , [c, i, d1, d2]
--    , [T1, T2, c, i, d1, d2]
--
--      -- Specialised function helpers
--    , [c, i, x]
--    , [dShow1 = $dfShow dShowT2]
--    , [T1, T2, c, i, dEqT1, dShow1]
--    )
specHeader
     :: SpecEnv
     -> [InBndr]    -- The binders from the original function 'f'
     -> [SpecArg]   -- From the CallInfo
     -> SpecM ( Bool     -- True <=> some useful specialisation happened
                         -- Not the same as any (isSpecDict args) because
                         -- the args might be longer than bndrs

                -- Returned arguments
              , SpecEnv      -- Substitution to apply to the body of 'f'
              , [OutBndr]    -- Leftover binders from the original function 'f'
                             --   that don’t have a corresponding SpecArg

                -- RULE helpers
              , [OutBndr]    -- Binders for the RULE
              , [OutExpr]    -- Args for the LHS of the rule

                -- Specialised function helpers
              , [OutBndr]    -- Binders for $sf
              , [DictBind]   -- Auxiliary dictionary bindings
              , [OutExpr]    -- Specialised arguments for unfolding
                             -- Same length as "args for LHS of rule"
              )

-- We want to specialise on type 'T1', and so we must construct a substitution
-- 'a->T1', as well as a LHS argument for the resulting RULE and unfolding
-- details.
specHeader :: SpecEnv
-> [Id]
-> [SpecArg]
-> SpecM
     (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
specHeader SpecEnv
env (Id
bndr : [Id]
bndrs) (SpecType Type
t : [SpecArg]
args)
  = do { let env' :: SpecEnv
env' = SpecEnv -> [(Id, Type)] -> SpecEnv
extendTvSubstList SpecEnv
env [(Id
bndr, Type
t)]
       ; (Bool
useful, SpecEnv
env'', [Id]
leftover_bndrs, [Id]
rule_bs, [Expr Id]
rule_es, [Id]
bs', [DictBind]
dx, [Expr Id]
spec_args)
            <- SpecEnv
-> [Id]
-> [SpecArg]
-> SpecM
     (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
specHeader SpecEnv
env' [Id]
bndrs [SpecArg]
args
       ; (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
-> SpecM
     (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
forall (f :: * -> *) a. Applicative f => a -> f a
pure ( Bool
useful
              , SpecEnv
env''
              , [Id]
leftover_bndrs
              , [Id]
rule_bs
              , Type -> Expr Id
forall b. Type -> Expr b
Type Type
t Expr Id -> [Expr Id] -> [Expr Id]
forall a. a -> [a] -> [a]
: [Expr Id]
rule_es
              , [Id]
bs'
              , [DictBind]
dx
              , Type -> Expr Id
forall b. Type -> Expr b
Type Type
t Expr Id -> [Expr Id] -> [Expr Id]
forall a. a -> [a] -> [a]
: [Expr Id]
spec_args
              )
       }

-- Next we have a type that we don't want to specialise. We need to perform
-- a substitution on it (in case the type refers to 'a'). Additionally, we need
-- to produce a binder, LHS argument and RHS argument for the resulting rule,
-- /and/ a binder for the specialised body.
specHeader SpecEnv
env (Id
bndr : [Id]
bndrs) (SpecArg
UnspecType : [SpecArg]
args)
  = do { let (SpecEnv
env', Id
bndr') = SpecEnv -> Id -> (SpecEnv, Id)
substBndr SpecEnv
env Id
bndr
       ; (Bool
useful, SpecEnv
env'', [Id]
leftover_bndrs, [Id]
rule_bs, [Expr Id]
rule_es, [Id]
bs', [DictBind]
dx, [Expr Id]
spec_args)
            <- SpecEnv
-> [Id]
-> [SpecArg]
-> SpecM
     (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
specHeader SpecEnv
env' [Id]
bndrs [SpecArg]
args
       ; (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
-> SpecM
     (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
forall (f :: * -> *) a. Applicative f => a -> f a
pure ( Bool
useful
              , SpecEnv
env''
              , [Id]
leftover_bndrs
              , Id
bndr' Id -> [Id] -> [Id]
forall a. a -> [a] -> [a]
: [Id]
rule_bs
              , Id -> Expr Id
forall b. Id -> Expr b
varToCoreExpr Id
bndr' Expr Id -> [Expr Id] -> [Expr Id]
forall a. a -> [a] -> [a]
: [Expr Id]
rule_es
              , Id
bndr' Id -> [Id] -> [Id]
forall a. a -> [a] -> [a]
: [Id]
bs'
              , [DictBind]
dx
              , Id -> Expr Id
forall b. Id -> Expr b
varToCoreExpr Id
bndr' Expr Id -> [Expr Id] -> [Expr Id]
forall a. a -> [a] -> [a]
: [Expr Id]
spec_args
              )
       }

-- Next we want to specialise the 'Eq a' dict away. We need to construct
-- a wildcard binder to match the dictionary (See Note [Specialising Calls] for
-- the nitty-gritty), as a LHS rule and unfolding details.
specHeader SpecEnv
env (Id
bndr : [Id]
bndrs) (SpecDict Expr Id
d : [SpecArg]
args)
  = do { Id
bndr' <- SpecEnv -> Id -> SpecM Id
newDictBndr SpecEnv
env Id
bndr -- See Note [Zap occ info in rule binders]
       ; let (SpecEnv
env', Maybe DictBind
dx_bind, Expr Id
spec_dict) = SpecEnv
-> Id -> Id -> Expr Id -> (SpecEnv, Maybe DictBind, Expr Id)
bindAuxiliaryDict SpecEnv
env Id
bndr Id
bndr' Expr Id
d
       ; (Bool
_, SpecEnv
env'', [Id]
leftover_bndrs, [Id]
rule_bs, [Expr Id]
rule_es, [Id]
bs', [DictBind]
dx, [Expr Id]
spec_args)
             <- SpecEnv
-> [Id]
-> [SpecArg]
-> SpecM
     (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
specHeader SpecEnv
env' [Id]
bndrs [SpecArg]
args
       ; (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
-> SpecM
     (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
forall (f :: * -> *) a. Applicative f => a -> f a
pure ( Bool
True      -- Ha!  A useful specialisation!
              , SpecEnv
env''
              , [Id]
leftover_bndrs
              -- See Note [Evidence foralls]
              , Expr Id -> [Id]
exprFreeIdsList (Id -> Expr Id
forall b. Id -> Expr b
varToCoreExpr Id
bndr') [Id] -> [Id] -> [Id]
forall a. [a] -> [a] -> [a]
++ [Id]
rule_bs
              , Id -> Expr Id
forall b. Id -> Expr b
varToCoreExpr Id
bndr' Expr Id -> [Expr Id] -> [Expr Id]
forall a. a -> [a] -> [a]
: [Expr Id]
rule_es
              , [Id]
bs'
              , Maybe DictBind -> [DictBind]
forall a. Maybe a -> [a]
maybeToList Maybe DictBind
dx_bind [DictBind] -> [DictBind] -> [DictBind]
forall a. [a] -> [a] -> [a]
++ [DictBind]
dx
              , Expr Id
spec_dict Expr Id -> [Expr Id] -> [Expr Id]
forall a. a -> [a] -> [a]
: [Expr Id]
spec_args
              )
       }

-- Finally, we have the unspecialised argument 'i'. We need to produce
-- a binder, LHS and RHS argument for the RULE, and a binder for the
-- specialised body.
--
-- NB: Calls to 'specHeader' will trim off any trailing 'UnspecArg's, which is
-- why 'i' doesn't appear in our RULE above. But we have no guarantee that
-- there aren't 'UnspecArg's which come /before/ all of the dictionaries, so
-- this case must be here.
specHeader SpecEnv
env (Id
bndr : [Id]
bndrs) (SpecArg
UnspecArg : [SpecArg]
args)
  = do { -- see Note [Zap occ info in rule binders]
         let (SpecEnv
env', Id
bndr') = SpecEnv -> Id -> (SpecEnv, Id)
substBndr SpecEnv
env (Id -> Id
zapIdOccInfo Id
bndr)
       ; (Bool
useful, SpecEnv
env'', [Id]
leftover_bndrs, [Id]
rule_bs, [Expr Id]
rule_es, [Id]
bs', [DictBind]
dx, [Expr Id]
spec_args)
             <- SpecEnv
-> [Id]
-> [SpecArg]
-> SpecM
     (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
specHeader SpecEnv
env' [Id]
bndrs [SpecArg]
args
       ; (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
-> SpecM
     (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
forall (f :: * -> *) a. Applicative f => a -> f a
pure ( Bool
useful
              , SpecEnv
env''
              , [Id]
leftover_bndrs
              , Id
bndr' Id -> [Id] -> [Id]
forall a. a -> [a] -> [a]
: [Id]
rule_bs
              , Id -> Expr Id
forall b. Id -> Expr b
varToCoreExpr Id
bndr' Expr Id -> [Expr Id] -> [Expr Id]
forall a. a -> [a] -> [a]
: [Expr Id]
rule_es
              , if Id -> Bool
isDeadBinder Id
bndr
                  then [Id]
bs' -- see Note [Drop dead args from specialisations]
                  else Id
bndr' Id -> [Id] -> [Id]
forall a. a -> [a] -> [a]
: [Id]
bs'
              , [DictBind]
dx
              , Id -> Expr Id
forall b. Id -> Expr b
varToCoreExpr Id
bndr' Expr Id -> [Expr Id] -> [Expr Id]
forall a. a -> [a] -> [a]
: [Expr Id]
spec_args
              )
       }

-- If we run out of binders, stop immediately
-- See Note [Specialisation Must Preserve Sharing]
specHeader SpecEnv
env [] [SpecArg]
_ = (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
-> SpecM
     (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Bool
False, SpecEnv
env, [], [], [], [], [], [])

-- Return all remaining binders from the original function. These have the
-- invariant that they should all correspond to unspecialised arguments, so
-- it's safe to stop processing at this point.
specHeader SpecEnv
env [Id]
bndrs []
  = (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
-> SpecM
     (Bool, SpecEnv, [Id], [Id], [Expr Id], [Id], [DictBind], [Expr Id])
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Bool
False, SpecEnv
env', [Id]
bndrs', [], [], [], [], [])
  where
    (SpecEnv
env', [Id]
bndrs') = SpecEnv -> [Id] -> (SpecEnv, [Id])
substBndrs SpecEnv
env [Id]
bndrs


-- | Binds a dictionary argument to a fresh name, to preserve sharing
bindAuxiliaryDict
  :: SpecEnv
  -> InId -> OutId -> OutExpr -- Original dict binder, and the witnessing expression
  -> ( SpecEnv        -- Substitute for orig_dict_id
     , Maybe DictBind -- Auxiliary dict binding, if any
     , OutExpr)        -- Witnessing expression (always trivial)
bindAuxiliaryDict :: SpecEnv
-> Id -> Id -> Expr Id -> (SpecEnv, Maybe DictBind, Expr Id)
bindAuxiliaryDict env :: SpecEnv
env@(SE { se_subst :: SpecEnv -> Subst
se_subst = Subst
subst, se_interesting :: SpecEnv -> VarSet
se_interesting = VarSet
interesting })
                  Id
orig_dict_id Id
fresh_dict_id Expr Id
dict_expr

  -- If the dictionary argument is trivial,
  -- don’t bother creating a new dict binding; just substitute
  | Just Id
dict_id <- Expr Id -> Maybe Id
getIdFromTrivialExpr_maybe Expr Id
dict_expr
  = let env' :: SpecEnv
env' = SpecEnv
env { se_subst :: Subst
se_subst = Subst -> Id -> Expr Id -> Subst
Core.extendSubst Subst
subst Id
orig_dict_id Expr Id
dict_expr
                                Subst -> Id -> Subst
`Core.extendInScope` Id
dict_id
                          -- See Note [Keep the old dictionaries interesting]
                   , se_interesting :: VarSet
se_interesting = VarSet
interesting VarSet -> Id -> VarSet
`extendVarSet` Id
dict_id }
    in (SpecEnv
env', Maybe DictBind
forall a. Maybe a
Nothing, Expr Id
dict_expr)

  | Bool
otherwise  -- Non-trivial dictionary arg; make an auxiliary binding
  = let dict_bind :: DictBind
dict_bind = Bind Id -> DictBind
mkDB (Id -> Expr Id -> Bind Id
forall b. b -> Expr b -> Bind b
NonRec Id
fresh_dict_id Expr Id
dict_expr)
        env' :: SpecEnv
env' = SpecEnv
env { se_subst :: Subst
se_subst = Subst -> Id -> Expr Id -> Subst
Core.extendSubst Subst
subst Id
orig_dict_id (Id -> Expr Id
forall b. Id -> Expr b
Var Id
fresh_dict_id)
                                Subst -> Id -> Subst
`Core.extendInScope` Id
fresh_dict_id
                      -- See Note [Make the new dictionaries interesting]
                   , se_interesting :: VarSet
se_interesting = VarSet
interesting VarSet -> Id -> VarSet
`extendVarSet` Id
fresh_dict_id }
    in (SpecEnv
env', DictBind -> Maybe DictBind
forall a. a -> Maybe a
Just DictBind
dict_bind, Id -> Expr Id
forall b. Id -> Expr b
Var Id
fresh_dict_id)

{-
Note [Make the new dictionaries interesting]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Important!  We're going to substitute dx_id1 for d
and we want it to look "interesting", else we won't gather *any*
consequential calls. E.g.
    f d = ...g d....
If we specialise f for a call (f (dfun dNumInt)), we'll get
a consequent call (g d') with an auxiliary definition
    d' = df dNumInt
We want that consequent call to look interesting

Note [Keep the old dictionaries interesting]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In bindAuxiliaryDict, we don’t bother creating a new dict binding if
the dict expression is trivial. For example, if we have

    f = \ @m1 (d1 :: Monad m1) -> ...

and we specialize it at the pattern

    [SpecType IO, SpecArg $dMonadIO]

it would be silly to create a new binding for $dMonadIO; it’s already
a binding! So we just extend the substitution directly:

    m1 :-> IO
    d1 :-> $dMonadIO

But this creates a new subtlety: the dict expression might be a dict
binding we floated out while specializing another function. For
example, we might have

    d2 = $p1Monad $dMonadIO -- floated out by bindAuxiliaryDict
    $sg = h @IO d2
    h = \ @m2 (d2 :: Applicative m2) -> ...

and end up specializing h at the following pattern:

    [SpecType IO, SpecArg d2]

When we created the d2 binding in the first place, we locally marked
it as interesting while specializing g as described above by
Note [Make the new dictionaries interesting]. But when we go to
specialize h, it isn’t in the SpecEnv anymore, so we’ve lost the
knowledge that we should specialize on it.

To fix this, we have to explicitly add d2 *back* to the interesting
set. That way, it will still be considered interesting while
specializing the body of h. See !2913.
-}


{- *********************************************************************
*                                                                      *
            UsageDetails and suchlike
*                                                                      *
********************************************************************* -}

data UsageDetails
  = MkUD {
      UsageDetails -> Bag DictBind
ud_binds :: !(Bag DictBind),
               -- See Note [Floated dictionary bindings]
               -- The order is important;
               -- in ds1 `union` ds2, bindings in ds2 can depend on those in ds1
               -- (Remember, Bags preserve order in GHC.)

      UsageDetails -> CallDetails
ud_calls :: !CallDetails

      -- INVARIANT: suppose bs = bindersOf ud_binds
      -- Then 'calls' may *mention* 'bs',
      -- but there should be no calls *for* bs
    }

-- | A 'DictBind' is a binding along with a cached set containing its free
-- variables (both type variables and dictionaries)
type DictBind = (CoreBind, VarSet)

{- Note [Floated dictionary bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We float out dictionary bindings for the reasons described under
"Dictionary floating" above.  But not /just/ dictionary bindings.
Consider

   f :: Eq a => blah
   f a d = rhs

   $c== :: T -> T -> Bool
   $c== x y = ...

   $df :: Eq T
   $df = Eq $c== ...

   gurgle = ...(f @T $df)...

We gather the call info for (f @T $df), and we don't want to drop it
when we come across the binding for $df.  So we add $df to the floats
and continue.  But then we have to add $c== to the floats, and so on.
These all float above the binding for 'f', and and now we can
successfully specialise 'f'.

So the DictBinds in (ud_binds :: Bag DictBind) may contain
non-dictionary bindings too.
-}

instance Outputable UsageDetails where
  ppr :: UsageDetails -> SDoc
ppr (MkUD { ud_binds :: UsageDetails -> Bag DictBind
ud_binds = Bag DictBind
dbs, ud_calls :: UsageDetails -> CallDetails
ud_calls = CallDetails
calls })
        = String -> SDoc
text String
"MkUD" SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
braces ([SDoc] -> SDoc
sep (SDoc -> [SDoc] -> [SDoc]
punctuate SDoc
comma
                [String -> SDoc
text String
"binds" SDoc -> SDoc -> SDoc
<+> SDoc
equals SDoc -> SDoc -> SDoc
<+> Bag DictBind -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bag DictBind
dbs,
                 String -> SDoc
text String
"calls" SDoc -> SDoc -> SDoc
<+> SDoc
equals SDoc -> SDoc -> SDoc
<+> CallDetails -> SDoc
forall a. Outputable a => a -> SDoc
ppr CallDetails
calls]))

emptyUDs :: UsageDetails
emptyUDs :: UsageDetails
emptyUDs = MkUD :: Bag DictBind -> CallDetails -> UsageDetails
MkUD { ud_binds :: Bag DictBind
ud_binds = Bag DictBind
forall a. Bag a
emptyBag, ud_calls :: CallDetails
ud_calls = CallDetails
forall a. DVarEnv a
emptyDVarEnv }

------------------------------------------------------------
type CallDetails  = DIdEnv CallInfoSet
  -- The order of specialized binds and rules depends on how we linearize
  -- CallDetails, so to get determinism we must use a deterministic set here.
  -- See Note [Deterministic UniqFM] in UniqDFM

data CallInfoSet = CIS Id (Bag CallInfo)
  -- The list of types and dictionaries is guaranteed to
  -- match the type of f
  -- The Bag may contain duplicate calls (i.e. f @T and another f @T)
  -- These dups are eliminated by already_covered in specCalls

data CallInfo
  = CI { CallInfo -> [SpecArg]
ci_key  :: [SpecArg]   -- All arguments
       , CallInfo -> VarSet
ci_fvs  :: VarSet      -- Free vars of the ci_key
                                -- call (including tyvars)
                                -- [*not* include the main id itself, of course]
    }

type DictExpr = CoreExpr

ciSetFilter :: (CallInfo -> Bool) -> CallInfoSet -> CallInfoSet
ciSetFilter :: (CallInfo -> Bool) -> CallInfoSet -> CallInfoSet
ciSetFilter CallInfo -> Bool
p (CIS Id
id Bag CallInfo
a) = Id -> Bag CallInfo -> CallInfoSet
CIS Id
id ((CallInfo -> Bool) -> Bag CallInfo -> Bag CallInfo
forall a. (a -> Bool) -> Bag a -> Bag a
filterBag CallInfo -> Bool
p Bag CallInfo
a)

instance Outputable CallInfoSet where
  ppr :: CallInfoSet -> SDoc
ppr (CIS Id
fn Bag CallInfo
map) = SDoc -> Int -> SDoc -> SDoc
hang (String -> SDoc
text String
"CIS" SDoc -> SDoc -> SDoc
<+> Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
fn)
                        Int
2 (Bag CallInfo -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bag CallInfo
map)

pprCallInfo :: Id -> CallInfo -> SDoc
pprCallInfo :: Id -> CallInfo -> SDoc
pprCallInfo Id
fn (CI { ci_key :: CallInfo -> [SpecArg]
ci_key = [SpecArg]
key })
  = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
fn SDoc -> SDoc -> SDoc
<+> [SpecArg] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [SpecArg]
key

ppr_call_key_ty :: SpecArg -> Maybe SDoc
ppr_call_key_ty :: SpecArg -> Maybe SDoc
ppr_call_key_ty (SpecType Type
ty) = SDoc -> Maybe SDoc
forall a. a -> Maybe a
Just (SDoc -> Maybe SDoc) -> SDoc -> Maybe SDoc
forall a b. (a -> b) -> a -> b
$ Char -> SDoc
char Char
'@' SDoc -> SDoc -> SDoc
<+> Type -> SDoc
pprParendType Type
ty
ppr_call_key_ty SpecArg
UnspecType    = SDoc -> Maybe SDoc
forall a. a -> Maybe a
Just (SDoc -> Maybe SDoc) -> SDoc -> Maybe SDoc
forall a b. (a -> b) -> a -> b
$ Char -> SDoc
char Char
'_'
ppr_call_key_ty (SpecDict Expr Id
_)  = Maybe SDoc
forall a. Maybe a
Nothing
ppr_call_key_ty SpecArg
UnspecArg     = Maybe SDoc
forall a. Maybe a
Nothing

instance Outputable CallInfo where
  ppr :: CallInfo -> SDoc
ppr (CI { ci_key :: CallInfo -> [SpecArg]
ci_key = [SpecArg]
key, ci_fvs :: CallInfo -> VarSet
ci_fvs = VarSet
fvs })
    = String -> SDoc
text String
"CI" SDoc -> SDoc -> SDoc
<> SDoc -> SDoc
braces ([SDoc] -> SDoc
hsep [ [SDoc] -> SDoc
fsep ((SpecArg -> Maybe SDoc) -> [SpecArg] -> [SDoc]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe SpecArg -> Maybe SDoc
ppr_call_key_ty [SpecArg]
key), VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr VarSet
fvs ])

unionCalls :: CallDetails -> CallDetails -> CallDetails
unionCalls :: CallDetails -> CallDetails -> CallDetails
unionCalls CallDetails
c1 CallDetails
c2 = (CallInfoSet -> CallInfoSet -> CallInfoSet)
-> CallDetails -> CallDetails -> CallDetails
forall a. (a -> a -> a) -> DVarEnv a -> DVarEnv a -> DVarEnv a
plusDVarEnv_C CallInfoSet -> CallInfoSet -> CallInfoSet
unionCallInfoSet CallDetails
c1 CallDetails
c2

unionCallInfoSet :: CallInfoSet -> CallInfoSet -> CallInfoSet
unionCallInfoSet :: CallInfoSet -> CallInfoSet -> CallInfoSet
unionCallInfoSet (CIS Id
f Bag CallInfo
calls1) (CIS Id
_ Bag CallInfo
calls2) =
  Id -> Bag CallInfo -> CallInfoSet
CIS Id
f (Bag CallInfo
calls1 Bag CallInfo -> Bag CallInfo -> Bag CallInfo
forall a. Bag a -> Bag a -> Bag a
`unionBags` Bag CallInfo
calls2)

callDetailsFVs :: CallDetails -> VarSet
callDetailsFVs :: CallDetails -> VarSet
callDetailsFVs CallDetails
calls =
  (CallInfoSet -> VarSet -> VarSet)
-> VarSet -> CallDetails -> VarSet
forall elt a. (elt -> a -> a) -> a -> UniqDFM elt -> a
nonDetFoldUDFM (VarSet -> VarSet -> VarSet
unionVarSet (VarSet -> VarSet -> VarSet)
-> (CallInfoSet -> VarSet) -> CallInfoSet -> VarSet -> VarSet
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CallInfoSet -> VarSet
callInfoFVs) VarSet
emptyVarSet CallDetails
calls
  -- It's OK to use nonDetFoldUDFM here because we forget the ordering
  -- immediately by converting to a nondeterministic set.

callInfoFVs :: CallInfoSet -> VarSet
callInfoFVs :: CallInfoSet -> VarSet
callInfoFVs (CIS Id
_ Bag CallInfo
call_info) =
  (CallInfo -> VarSet -> VarSet) -> VarSet -> Bag CallInfo -> VarSet
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (\(CI { ci_fvs :: CallInfo -> VarSet
ci_fvs = VarSet
fv }) VarSet
vs -> VarSet -> VarSet -> VarSet
unionVarSet VarSet
fv VarSet
vs) VarSet
emptyVarSet Bag CallInfo
call_info

getTheta :: [TyCoBinder] -> [PredType]
getTheta :: [TyCoBinder] -> [Type]
getTheta = (TyCoBinder -> Type) -> [TyCoBinder] -> [Type]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap TyCoBinder -> Type
tyBinderType ([TyCoBinder] -> [Type])
-> ([TyCoBinder] -> [TyCoBinder]) -> [TyCoBinder] -> [Type]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TyCoBinder -> Bool) -> [TyCoBinder] -> [TyCoBinder]
forall a. (a -> Bool) -> [a] -> [a]
filter TyCoBinder -> Bool
isInvisibleBinder ([TyCoBinder] -> [TyCoBinder])
-> ([TyCoBinder] -> [TyCoBinder]) -> [TyCoBinder] -> [TyCoBinder]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TyCoBinder -> Bool) -> [TyCoBinder] -> [TyCoBinder]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (TyCoBinder -> Bool) -> TyCoBinder -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TyCoBinder -> Bool
isNamedBinder)


------------------------------------------------------------
singleCall :: Id -> [SpecArg] -> UsageDetails
singleCall :: Id -> [SpecArg] -> UsageDetails
singleCall Id
id [SpecArg]
args
  = MkUD :: Bag DictBind -> CallDetails -> UsageDetails
MkUD {ud_binds :: Bag DictBind
ud_binds = Bag DictBind
forall a. Bag a
emptyBag,
          ud_calls :: CallDetails
ud_calls = Id -> CallInfoSet -> CallDetails
forall a. Id -> a -> DVarEnv a
unitDVarEnv Id
id (CallInfoSet -> CallDetails) -> CallInfoSet -> CallDetails
forall a b. (a -> b) -> a -> b
$ Id -> Bag CallInfo -> CallInfoSet
CIS Id
id (Bag CallInfo -> CallInfoSet) -> Bag CallInfo -> CallInfoSet
forall a b. (a -> b) -> a -> b
$
                     CallInfo -> Bag CallInfo
forall a. a -> Bag a
unitBag (CI :: [SpecArg] -> VarSet -> CallInfo
CI { ci_key :: [SpecArg]
ci_key  = [SpecArg]
args -- used to be tys
                                 , ci_fvs :: VarSet
ci_fvs  = VarSet
call_fvs }) }
  where
    call_fvs :: VarSet
call_fvs = (SpecArg -> VarSet -> VarSet) -> VarSet -> [SpecArg] -> VarSet
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (VarSet -> VarSet -> VarSet
unionVarSet (VarSet -> VarSet -> VarSet)
-> (SpecArg -> VarSet) -> SpecArg -> VarSet -> VarSet
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SpecArg -> VarSet
specArgFreeVars) VarSet
emptyVarSet [SpecArg]
args
        -- The type args (tys) are guaranteed to be part of the dictionary
        -- types, because they are just the constrained types,
        -- and the dictionary is therefore sure to be bound
        -- inside the binding for any type variables free in the type;
        -- hence it's safe to neglect tyvars free in tys when making
        -- the free-var set for this call
        -- BUT I don't trust this reasoning; play safe and include tys_fvs
        --
        -- We don't include the 'id' itself.

mkCallUDs, mkCallUDs' :: SpecEnv -> Id -> [CoreExpr] -> UsageDetails
mkCallUDs :: SpecEnv -> Id -> [Expr Id] -> UsageDetails
mkCallUDs SpecEnv
env Id
f [Expr Id]
args
  = -- pprTrace "mkCallUDs" (vcat [ ppr f, ppr args, ppr res ])
    UsageDetails
res
  where
    res :: UsageDetails
res = SpecEnv -> Id -> [Expr Id] -> UsageDetails
mkCallUDs' SpecEnv
env Id
f [Expr Id]
args

mkCallUDs' :: SpecEnv -> Id -> [Expr Id] -> UsageDetails
mkCallUDs' SpecEnv
env Id
f [Expr Id]
args
  |  Bool -> Bool
not (Id -> Bool
want_calls_for Id
f)  -- Imported from elsewhere
  Bool -> Bool -> Bool
|| [SpecArg] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [SpecArg]
ci_key             -- No useful specialisation
   -- See also Note [Specialisations already covered]
  = -- pprTrace "mkCallUDs: discarding" _trace_doc
    UsageDetails
emptyUDs

  | Bool
otherwise
  = -- pprTrace "mkCallUDs: keeping" _trace_doc
    Id -> [SpecArg] -> UsageDetails
singleCall Id
f [SpecArg]
ci_key
  where
    _trace_doc :: SDoc
_trace_doc = [SDoc] -> SDoc
vcat [Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
f, [Expr Id] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Expr Id]
args, [SpecArg] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [SpecArg]
ci_key]
    pis :: [TyCoBinder]
pis                = ([TyCoBinder], Type) -> [TyCoBinder]
forall a b. (a, b) -> a
fst (([TyCoBinder], Type) -> [TyCoBinder])
-> ([TyCoBinder], Type) -> [TyCoBinder]
forall a b. (a -> b) -> a -> b
$ Type -> ([TyCoBinder], Type)
splitPiTys (Type -> ([TyCoBinder], Type)) -> Type -> ([TyCoBinder], Type)
forall a b. (a -> b) -> a -> b
$ Id -> Type
idType Id
f
    constrained_tyvars :: VarSet
constrained_tyvars = [Type] -> VarSet
tyCoVarsOfTypes ([Type] -> VarSet) -> [Type] -> VarSet
forall a b. (a -> b) -> a -> b
$ [TyCoBinder] -> [Type]
getTheta [TyCoBinder]
pis

    ci_key :: [SpecArg]
    ci_key :: [SpecArg]
ci_key = (SpecArg -> Bool) -> [SpecArg] -> [SpecArg]
forall a. (a -> Bool) -> [a] -> [a]
dropWhileEndLE (Bool -> Bool
not (Bool -> Bool) -> (SpecArg -> Bool) -> SpecArg -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SpecArg -> Bool
isSpecDict) ([SpecArg] -> [SpecArg]) -> [SpecArg] -> [SpecArg]
forall a b. (a -> b) -> a -> b
$
             (Expr Id -> TyCoBinder -> SpecArg)
-> [Expr Id] -> [TyCoBinder] -> [SpecArg]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Expr Id -> TyCoBinder -> SpecArg
mk_spec_arg [Expr Id]
args [TyCoBinder]
pis
             -- Drop trailing args until we get to a SpecDict
             -- In this way the RULE has as few args as possible,
             -- which broadens its applicability, since rules only
             -- fire when saturated

    mk_spec_arg :: CoreExpr -> TyCoBinder -> SpecArg
    mk_spec_arg :: Expr Id -> TyCoBinder -> SpecArg
mk_spec_arg Expr Id
arg (Named TyCoVarBinder
bndr)
      |  TyCoVarBinder -> Id
forall tv argf. VarBndr tv argf -> tv
binderVar TyCoVarBinder
bndr Id -> VarSet -> Bool
`elemVarSet` VarSet
constrained_tyvars
      = case Expr Id
arg of
          Type Type
ty -> Type -> SpecArg
SpecType Type
ty
          Expr Id
_       -> String -> SDoc -> SpecArg
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"ci_key" (SDoc -> SpecArg) -> SDoc -> SpecArg
forall a b. (a -> b) -> a -> b
$ Expr Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Expr Id
arg
      |  Bool
otherwise = SpecArg
UnspecType

    -- For "InvisArg", which are the type-class dictionaries,
    -- we decide on a case by case basis if we want to specialise
    -- on this argument; if so, SpecDict, if not UnspecArg
    mk_spec_arg Expr Id
arg (Anon AnonArgFlag
InvisArg Type
pred)
      | Type -> Bool
type_determines_value Type
pred
      , SpecEnv -> Expr Id -> Bool
interestingDict SpecEnv
env Expr Id
arg -- Note [Interesting dictionary arguments]
      = Expr Id -> SpecArg
SpecDict Expr Id
arg
      | Bool
otherwise = SpecArg
UnspecArg

    mk_spec_arg Expr Id
_ (Anon AnonArgFlag
VisArg Type
_)
      = SpecArg
UnspecArg

    want_calls_for :: Id -> Bool
want_calls_for Id
f = Id -> Bool
isLocalId Id
f Bool -> Bool -> Bool
|| Maybe (Expr Id) -> Bool
forall a. Maybe a -> Bool
isJust (Unfolding -> Maybe (Expr Id)
maybeUnfoldingTemplate (Id -> Unfolding
realIdUnfolding Id
f))
         -- For imported things, we gather call instances if
         -- there is an unfolding that we could in principle specialise
         -- We might still decide not to use it (consulting dflags)
         -- in specImports
         -- Use 'realIdUnfolding' to ignore the loop-breaker flag!

    type_determines_value :: Type -> Bool
type_determines_value Type
pred    -- See Note [Type determines value]
        = case Type -> Pred
classifyPredType Type
pred of
            ClassPred Class
cls [Type]
_ -> Bool -> Bool
not (Class -> Bool
isIPClass Class
cls)  -- Superclasses can't be IPs
            EqPred {}       -> Bool
True
            IrredPred {}    -> Bool
True   -- Things like (D []) where D is a
                                      -- Constraint-ranged family; #7785
            ForAllPred {}   -> Bool
True

{-
Note [Type determines value]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Only specialise on non-IP *class* params, because these are the ones
whose *type* determines their *value*.  In particular, with implicit
params, the type args *don't* say what the value of the implicit param
is!  See #7101.

So we treat implicit params just like ordinary arguments for the
purposes of specialisation.  Note that we still want to specialise
functions with implicit params if they have *other* dicts which are
class params; see #17930.

One apparent additional complexity involves type families. For
example, consider
         type family D (v::*->*) :: Constraint
         type instance D [] = ()
         f :: D v => v Char -> Int
If we see a call (f "foo"), we'll pass a "dictionary"
  () |> (g :: () ~ D [])
and it's good to specialise f at this dictionary.

So the question is: can an implicit parameter "hide inside" a
type-family constraint like (D a).  Well, no.  We don't allow
        type instance D Maybe = ?x:Int
Hence the IrredPred case in type_determines_value.  See #7785.

Note [Interesting dictionary arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this
         \a.\d:Eq a.  let f = ... in ...(f d)...
There really is not much point in specialising f wrt the dictionary d,
because the code for the specialised f is not improved at all, because
d is lambda-bound.  We simply get junk specialisations.

What is "interesting"?  Just that it has *some* structure.  But what about
variables?

 * A variable might be imported, in which case its unfolding
   will tell us whether it has useful structure

 * Local variables are cloned on the way down (to avoid clashes when
   we float dictionaries), and cloning drops the unfolding
   (cloneIdBndr).  Moreover, we make up some new bindings, and it's a
   nuisance to give them unfoldings.  So we keep track of the
   "interesting" dictionaries as a VarSet in SpecEnv.
   We have to take care to put any new interesting dictionary
   bindings in the set.

We accidentally lost accurate tracking of local variables for a long
time, because cloned variables don't have unfoldings. But makes a
massive difference in a few cases, eg #5113. For nofib as a
whole it's only a small win: 2.2% improvement in allocation for ansi,
1.2% for bspt, but mostly 0.0!  Average 0.1% increase in binary size.
-}

interestingDict :: SpecEnv -> CoreExpr -> Bool
-- A dictionary argument is interesting if it has *some* structure
-- NB: "dictionary" arguments include constraints of all sorts,
--     including equality constraints; hence the Coercion case
interestingDict :: SpecEnv -> Expr Id -> Bool
interestingDict SpecEnv
env (Var Id
v) =  Unfolding -> Bool
hasSomeUnfolding (Id -> Unfolding
idUnfolding Id
v)
                            Bool -> Bool -> Bool
|| Id -> Bool
isDataConWorkId Id
v
                            Bool -> Bool -> Bool
|| Id
v Id -> VarSet -> Bool
`elemVarSet` SpecEnv -> VarSet
se_interesting SpecEnv
env
interestingDict SpecEnv
_ (Type Type
_)                = Bool
False
interestingDict SpecEnv
_ (Coercion Coercion
_)            = Bool
False
interestingDict SpecEnv
env (App Expr Id
fn (Type Type
_))     = SpecEnv -> Expr Id -> Bool
interestingDict SpecEnv
env Expr Id
fn
interestingDict SpecEnv
env (App Expr Id
fn (Coercion Coercion
_)) = SpecEnv -> Expr Id -> Bool
interestingDict SpecEnv
env Expr Id
fn
interestingDict SpecEnv
env (Tick Tickish Id
_ Expr Id
a)            = SpecEnv -> Expr Id -> Bool
interestingDict SpecEnv
env Expr Id
a
interestingDict SpecEnv
env (Cast Expr Id
e Coercion
_)            = SpecEnv -> Expr Id -> Bool
interestingDict SpecEnv
env Expr Id
e
interestingDict SpecEnv
_ Expr Id
_                       = Bool
True

plusUDs :: UsageDetails -> UsageDetails -> UsageDetails
plusUDs :: UsageDetails -> UsageDetails -> UsageDetails
plusUDs (MkUD {ud_binds :: UsageDetails -> Bag DictBind
ud_binds = Bag DictBind
db1, ud_calls :: UsageDetails -> CallDetails
ud_calls = CallDetails
calls1})
        (MkUD {ud_binds :: UsageDetails -> Bag DictBind
ud_binds = Bag DictBind
db2, ud_calls :: UsageDetails -> CallDetails
ud_calls = CallDetails
calls2})
  = MkUD :: Bag DictBind -> CallDetails -> UsageDetails
MkUD { ud_binds :: Bag DictBind
ud_binds = Bag DictBind
db1    Bag DictBind -> Bag DictBind -> Bag DictBind
forall a. Bag a -> Bag a -> Bag a
`unionBags`   Bag DictBind
db2
         , ud_calls :: CallDetails
ud_calls = CallDetails
calls1 CallDetails -> CallDetails -> CallDetails
`unionCalls`  CallDetails
calls2 }

-----------------------------
_dictBindBndrs :: Bag DictBind -> [Id]
_dictBindBndrs :: Bag DictBind -> [Id]
_dictBindBndrs Bag DictBind
dbs = (DictBind -> [Id] -> [Id]) -> [Id] -> Bag DictBind -> [Id]
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr ([Id] -> [Id] -> [Id]
forall a. [a] -> [a] -> [a]
(++) ([Id] -> [Id] -> [Id])
-> (DictBind -> [Id]) -> DictBind -> [Id] -> [Id]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bind Id -> [Id]
forall b. Bind b -> [b]
bindersOf (Bind Id -> [Id]) -> (DictBind -> Bind Id) -> DictBind -> [Id]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DictBind -> Bind Id
forall a b. (a, b) -> a
fst) [] Bag DictBind
dbs

-- | Construct a 'DictBind' from a 'CoreBind'
mkDB :: CoreBind -> DictBind
mkDB :: Bind Id -> DictBind
mkDB Bind Id
bind = (Bind Id
bind, Bind Id -> VarSet
bind_fvs Bind Id
bind)

-- | Identify the free variables of a 'CoreBind'
bind_fvs :: CoreBind -> VarSet
bind_fvs :: Bind Id -> VarSet
bind_fvs (NonRec Id
bndr Expr Id
rhs) = (Id, Expr Id) -> VarSet
pair_fvs (Id
bndr,Expr Id
rhs)
bind_fvs (Rec [(Id, Expr Id)]
prs)         = (VarSet -> Id -> VarSet) -> VarSet -> [Id] -> VarSet
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' VarSet -> Id -> VarSet
delVarSet VarSet
rhs_fvs [Id]
bndrs
                           where
                             bndrs :: [Id]
bndrs = ((Id, Expr Id) -> Id) -> [(Id, Expr Id)] -> [Id]
forall a b. (a -> b) -> [a] -> [b]
map (Id, Expr Id) -> Id
forall a b. (a, b) -> a
fst [(Id, Expr Id)]
prs
                             rhs_fvs :: VarSet
rhs_fvs = [VarSet] -> VarSet
unionVarSets (((Id, Expr Id) -> VarSet) -> [(Id, Expr Id)] -> [VarSet]
forall a b. (a -> b) -> [a] -> [b]
map (Id, Expr Id) -> VarSet
pair_fvs [(Id, Expr Id)]
prs)

pair_fvs :: (Id, CoreExpr) -> VarSet
pair_fvs :: (Id, Expr Id) -> VarSet
pair_fvs (Id
bndr, Expr Id
rhs) = (Id -> Bool) -> Expr Id -> VarSet
exprSomeFreeVars Id -> Bool
interesting Expr Id
rhs
                       VarSet -> VarSet -> VarSet
`unionVarSet` Id -> VarSet
idFreeVars Id
bndr
        -- idFreeVars: don't forget variables mentioned in
        -- the rules of the bndr.  C.f. OccAnal.addRuleUsage
        -- Also tyvars mentioned in its type; they may not appear
        -- in the RHS
        --      type T a = Int
        --      x :: T a = 3
  where
    interesting :: InterestingVarFun
    interesting :: Id -> Bool
interesting Id
v = Id -> Bool
isLocalVar Id
v Bool -> Bool -> Bool
|| (Id -> Bool
isId Id
v Bool -> Bool -> Bool
&& Id -> Bool
isDFunId Id
v)
        -- Very important: include DFunIds /even/ if it is imported
        -- Reason: See Note [Avoiding loops], the second exmaple
        --         involving an imported dfun.  We must know whether
        --         a dictionary binding depends on an imported dfun,
        --         in case we try to specialise that imported dfun
        --         #13429 illustrates

-- | Flatten a set of "dumped" 'DictBind's, and some other binding
-- pairs, into a single recursive binding.
recWithDumpedDicts :: [(Id,CoreExpr)] -> Bag DictBind ->DictBind
recWithDumpedDicts :: [(Id, Expr Id)] -> Bag DictBind -> DictBind
recWithDumpedDicts [(Id, Expr Id)]
pairs Bag DictBind
dbs
  = ([(Id, Expr Id)] -> Bind Id
forall b. [(b, Expr b)] -> Bind b
Rec [(Id, Expr Id)]
bindings, VarSet
fvs)
  where
    ([(Id, Expr Id)]
bindings, VarSet
fvs) = (DictBind
 -> ([(Id, Expr Id)], VarSet) -> ([(Id, Expr Id)], VarSet))
-> ([(Id, Expr Id)], VarSet)
-> Bag DictBind
-> ([(Id, Expr Id)], VarSet)
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr DictBind -> ([(Id, Expr Id)], VarSet) -> ([(Id, Expr Id)], VarSet)
forall a.
(Bind a, VarSet)
-> ([(a, Expr a)], VarSet) -> ([(a, Expr a)], VarSet)
add
                               ([], VarSet
emptyVarSet)
                               (Bag DictBind
dbs Bag DictBind -> DictBind -> Bag DictBind
forall a. Bag a -> a -> Bag a
`snocBag` Bind Id -> DictBind
mkDB ([(Id, Expr Id)] -> Bind Id
forall b. [(b, Expr b)] -> Bind b
Rec [(Id, Expr Id)]
pairs))
    add :: (Bind a, VarSet)
-> ([(a, Expr a)], VarSet) -> ([(a, Expr a)], VarSet)
add (NonRec a
b Expr a
r, VarSet
fvs') ([(a, Expr a)]
pairs, VarSet
fvs) =
      ((a
b,Expr a
r) (a, Expr a) -> [(a, Expr a)] -> [(a, Expr a)]
forall a. a -> [a] -> [a]
: [(a, Expr a)]
pairs, VarSet
fvs VarSet -> VarSet -> VarSet
`unionVarSet` VarSet
fvs')
    add (Rec [(a, Expr a)]
prs1,   VarSet
fvs') ([(a, Expr a)]
pairs, VarSet
fvs) =
      ([(a, Expr a)]
prs1 [(a, Expr a)] -> [(a, Expr a)] -> [(a, Expr a)]
forall a. [a] -> [a] -> [a]
++ [(a, Expr a)]
pairs, VarSet
fvs VarSet -> VarSet -> VarSet
`unionVarSet` VarSet
fvs')

snocDictBinds :: UsageDetails -> [DictBind] -> UsageDetails
-- Add ud_binds to the tail end of the bindings in uds
snocDictBinds :: UsageDetails -> [DictBind] -> UsageDetails
snocDictBinds UsageDetails
uds [DictBind]
dbs
  = UsageDetails
uds { ud_binds :: Bag DictBind
ud_binds = UsageDetails -> Bag DictBind
ud_binds UsageDetails
uds Bag DictBind -> Bag DictBind -> Bag DictBind
forall a. Bag a -> Bag a -> Bag a
`unionBags` [DictBind] -> Bag DictBind
forall a. [a] -> Bag a
listToBag [DictBind]
dbs }

consDictBind :: DictBind -> UsageDetails -> UsageDetails
consDictBind :: DictBind -> UsageDetails -> UsageDetails
consDictBind DictBind
bind UsageDetails
uds = UsageDetails
uds { ud_binds :: Bag DictBind
ud_binds = DictBind
bind DictBind -> Bag DictBind -> Bag DictBind
forall a. a -> Bag a -> Bag a
`consBag` UsageDetails -> Bag DictBind
ud_binds UsageDetails
uds }

addDictBinds :: [DictBind] -> UsageDetails -> UsageDetails
addDictBinds :: [DictBind] -> UsageDetails -> UsageDetails
addDictBinds [DictBind]
binds UsageDetails
uds = UsageDetails
uds { ud_binds :: Bag DictBind
ud_binds = [DictBind] -> Bag DictBind
forall a. [a] -> Bag a
listToBag [DictBind]
binds Bag DictBind -> Bag DictBind -> Bag DictBind
forall a. Bag a -> Bag a -> Bag a
`unionBags` UsageDetails -> Bag DictBind
ud_binds UsageDetails
uds }

snocDictBind :: UsageDetails -> DictBind -> UsageDetails
snocDictBind :: UsageDetails -> DictBind -> UsageDetails
snocDictBind UsageDetails
uds DictBind
bind = UsageDetails
uds { ud_binds :: Bag DictBind
ud_binds = UsageDetails -> Bag DictBind
ud_binds UsageDetails
uds Bag DictBind -> DictBind -> Bag DictBind
forall a. Bag a -> a -> Bag a
`snocBag` DictBind
bind }

wrapDictBinds :: Bag DictBind -> [CoreBind] -> [CoreBind]
wrapDictBinds :: Bag DictBind -> CoreProgram -> CoreProgram
wrapDictBinds Bag DictBind
dbs CoreProgram
binds
  = (DictBind -> CoreProgram -> CoreProgram)
-> CoreProgram -> Bag DictBind -> CoreProgram
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr DictBind -> CoreProgram -> CoreProgram
forall a b. (a, b) -> [a] -> [a]
add CoreProgram
binds Bag DictBind
dbs
  where
    add :: (a, b) -> [a] -> [a]
add (a
bind,b
_) [a]
binds = a
bind a -> [a] -> [a]
forall a. a -> [a] -> [a]
: [a]
binds

wrapDictBindsE :: Bag DictBind -> CoreExpr -> CoreExpr
wrapDictBindsE :: Bag DictBind -> Expr Id -> Expr Id
wrapDictBindsE Bag DictBind
dbs Expr Id
expr
  = (DictBind -> Expr Id -> Expr Id)
-> Expr Id -> Bag DictBind -> Expr Id
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr DictBind -> Expr Id -> Expr Id
forall b b. (Bind b, b) -> Expr b -> Expr b
add Expr Id
expr Bag DictBind
dbs
  where
    add :: (Bind b, b) -> Expr b -> Expr b
add (Bind b
bind,b
_) Expr b
expr = Bind b -> Expr b -> Expr b
forall b. Bind b -> Expr b -> Expr b
Let Bind b
bind Expr b
expr

----------------------
dumpUDs :: [CoreBndr] -> UsageDetails -> (UsageDetails, Bag DictBind)
-- Used at a lambda or case binder; just dump anything mentioning the binder
dumpUDs :: [Id] -> UsageDetails -> (UsageDetails, Bag DictBind)
dumpUDs [Id]
bndrs uds :: UsageDetails
uds@(MkUD { ud_binds :: UsageDetails -> Bag DictBind
ud_binds = Bag DictBind
orig_dbs, ud_calls :: UsageDetails -> CallDetails
ud_calls = CallDetails
orig_calls })
  | [Id] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Id]
bndrs = (UsageDetails
uds, Bag DictBind
forall a. Bag a
emptyBag)  -- Common in case alternatives
  | Bool
otherwise  = -- pprTrace "dumpUDs" (ppr bndrs $$ ppr free_uds $$ ppr dump_dbs) $
                 (UsageDetails
free_uds, Bag DictBind
dump_dbs)
  where
    free_uds :: UsageDetails
free_uds = MkUD :: Bag DictBind -> CallDetails -> UsageDetails
MkUD { ud_binds :: Bag DictBind
ud_binds = Bag DictBind
free_dbs, ud_calls :: CallDetails
ud_calls = CallDetails
free_calls }
    bndr_set :: VarSet
bndr_set = [Id] -> VarSet
mkVarSet [Id]
bndrs
    (Bag DictBind
free_dbs, Bag DictBind
dump_dbs, VarSet
dump_set) = Bag DictBind -> VarSet -> (Bag DictBind, Bag DictBind, VarSet)
splitDictBinds Bag DictBind
orig_dbs VarSet
bndr_set
    free_calls :: CallDetails
free_calls = VarSet -> CallDetails -> CallDetails
deleteCallsMentioning VarSet
dump_set (CallDetails -> CallDetails) -> CallDetails -> CallDetails
forall a b. (a -> b) -> a -> b
$   -- Drop calls mentioning bndr_set on the floor
                 [Id] -> CallDetails -> CallDetails
deleteCallsFor [Id]
bndrs CallDetails
orig_calls    -- Discard calls for bndr_set; there should be
                                                    -- no calls for any of the dicts in dump_dbs

dumpBindUDs :: [CoreBndr] -> UsageDetails -> (UsageDetails, Bag DictBind, Bool)
-- Used at a let(rec) binding.
-- We return a boolean indicating whether the binding itself is mentioned,
-- directly or indirectly, by any of the ud_calls; in that case we want to
-- float the binding itself;
-- See Note [Floated dictionary bindings]
dumpBindUDs :: [Id] -> UsageDetails -> (UsageDetails, Bag DictBind, Bool)
dumpBindUDs [Id]
bndrs (MkUD { ud_binds :: UsageDetails -> Bag DictBind
ud_binds = Bag DictBind
orig_dbs, ud_calls :: UsageDetails -> CallDetails
ud_calls = CallDetails
orig_calls })
  = -- pprTrace "dumpBindUDs" (ppr bndrs $$ ppr free_uds $$ ppr dump_dbs) $
    (UsageDetails
free_uds, Bag DictBind
dump_dbs, Bool
float_all)
  where
    free_uds :: UsageDetails
free_uds = MkUD :: Bag DictBind -> CallDetails -> UsageDetails
MkUD { ud_binds :: Bag DictBind
ud_binds = Bag DictBind
free_dbs, ud_calls :: CallDetails
ud_calls = CallDetails
free_calls }
    bndr_set :: VarSet
bndr_set = [Id] -> VarSet
mkVarSet [Id]
bndrs
    (Bag DictBind
free_dbs, Bag DictBind
dump_dbs, VarSet
dump_set) = Bag DictBind -> VarSet -> (Bag DictBind, Bag DictBind, VarSet)
splitDictBinds Bag DictBind
orig_dbs VarSet
bndr_set
    free_calls :: CallDetails
free_calls = [Id] -> CallDetails -> CallDetails
deleteCallsFor [Id]
bndrs CallDetails
orig_calls
    float_all :: Bool
float_all = VarSet
dump_set VarSet -> VarSet -> Bool
`intersectsVarSet` CallDetails -> VarSet
callDetailsFVs CallDetails
free_calls

callsForMe :: Id -> UsageDetails -> (UsageDetails, [CallInfo])
callsForMe :: Id -> UsageDetails -> (UsageDetails, [CallInfo])
callsForMe Id
fn (MkUD { ud_binds :: UsageDetails -> Bag DictBind
ud_binds = Bag DictBind
orig_dbs, ud_calls :: UsageDetails -> CallDetails
ud_calls = CallDetails
orig_calls })
  = -- pprTrace ("callsForMe")
    --          (vcat [ppr fn,
    --                 text "Orig dbs ="     <+> ppr (_dictBindBndrs orig_dbs),
    --                 text "Orig calls ="   <+> ppr orig_calls,
    --                 text "Dep set ="      <+> ppr dep_set,
    --                 text "Calls for me =" <+> ppr calls_for_me]) $
    (UsageDetails
uds_without_me, [CallInfo]
calls_for_me)
  where
    uds_without_me :: UsageDetails
uds_without_me = MkUD :: Bag DictBind -> CallDetails -> UsageDetails
MkUD { ud_binds :: Bag DictBind
ud_binds = Bag DictBind
orig_dbs
                          , ud_calls :: CallDetails
ud_calls = CallDetails -> Id -> CallDetails
forall a. DVarEnv a -> Id -> DVarEnv a
delDVarEnv CallDetails
orig_calls Id
fn }
    calls_for_me :: [CallInfo]
calls_for_me = case CallDetails -> Id -> Maybe CallInfoSet
forall a. DVarEnv a -> Id -> Maybe a
lookupDVarEnv CallDetails
orig_calls Id
fn of
                        Maybe CallInfoSet
Nothing -> []
                        Just CallInfoSet
cis -> CallInfoSet -> Bag DictBind -> [CallInfo]
filterCalls CallInfoSet
cis Bag DictBind
orig_dbs
         -- filterCalls: drop calls that (directly or indirectly)
         -- refer to fn.  See Note [Avoiding loops]

----------------------
filterCalls :: CallInfoSet -> Bag DictBind -> [CallInfo]
-- See Note [Avoiding loops]
filterCalls :: CallInfoSet -> Bag DictBind -> [CallInfo]
filterCalls (CIS Id
fn Bag CallInfo
call_bag) Bag DictBind
dbs
  = (CallInfo -> Bool) -> [CallInfo] -> [CallInfo]
forall a. (a -> Bool) -> [a] -> [a]
filter CallInfo -> Bool
ok_call (Bag CallInfo -> [CallInfo]
forall a. Bag a -> [a]
bagToList Bag CallInfo
call_bag)
  where
    dump_set :: VarSet
dump_set = (VarSet -> DictBind -> VarSet) -> VarSet -> Bag DictBind -> VarSet
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' VarSet -> DictBind -> VarSet
go (Id -> VarSet
unitVarSet Id
fn) Bag DictBind
dbs
      -- This dump-set could also be computed by splitDictBinds
      --   (_,_,dump_set) = splitDictBinds dbs {fn}
      -- But this variant is shorter

    go :: VarSet -> DictBind -> VarSet
go VarSet
so_far (Bind Id
db,VarSet
fvs) | VarSet
fvs VarSet -> VarSet -> Bool
`intersectsVarSet` VarSet
so_far
                       = VarSet -> [Id] -> VarSet
extendVarSetList VarSet
so_far (Bind Id -> [Id]
forall b. Bind b -> [b]
bindersOf Bind Id
db)
                       | Bool
otherwise = VarSet
so_far

    ok_call :: CallInfo -> Bool
ok_call (CI { ci_fvs :: CallInfo -> VarSet
ci_fvs = VarSet
fvs }) = Bool -> Bool
not (VarSet
fvs VarSet -> VarSet -> Bool
`intersectsVarSet` VarSet
dump_set)

----------------------
splitDictBinds :: Bag DictBind -> IdSet -> (Bag DictBind, Bag DictBind, IdSet)
-- splitDictBinds dbs bndrs returns
--   (free_dbs, dump_dbs, dump_set)
-- where
--   * dump_dbs depends, transitively on bndrs
--   * free_dbs does not depend on bndrs
--   * dump_set = bndrs `union` bndrs(dump_dbs)
splitDictBinds :: Bag DictBind -> VarSet -> (Bag DictBind, Bag DictBind, VarSet)
splitDictBinds Bag DictBind
dbs VarSet
bndr_set
   = ((Bag DictBind, Bag DictBind, VarSet)
 -> DictBind -> (Bag DictBind, Bag DictBind, VarSet))
-> (Bag DictBind, Bag DictBind, VarSet)
-> Bag DictBind
-> (Bag DictBind, Bag DictBind, VarSet)
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (Bag DictBind, Bag DictBind, VarSet)
-> DictBind -> (Bag DictBind, Bag DictBind, VarSet)
split_db (Bag DictBind
forall a. Bag a
emptyBag, Bag DictBind
forall a. Bag a
emptyBag, VarSet
bndr_set) Bag DictBind
dbs
                -- Important that it's foldl' not foldr;
                -- we're accumulating the set of dumped ids in dump_set
   where
    split_db :: (Bag DictBind, Bag DictBind, VarSet)
-> DictBind -> (Bag DictBind, Bag DictBind, VarSet)
split_db (Bag DictBind
free_dbs, Bag DictBind
dump_dbs, VarSet
dump_idset) db :: DictBind
db@(Bind Id
bind, VarSet
fvs)
        | VarSet
dump_idset VarSet -> VarSet -> Bool
`intersectsVarSet` VarSet
fvs     -- Dump it
        = (Bag DictBind
free_dbs, Bag DictBind
dump_dbs Bag DictBind -> DictBind -> Bag DictBind
forall a. Bag a -> a -> Bag a
`snocBag` DictBind
db,
           VarSet -> [Id] -> VarSet
extendVarSetList VarSet
dump_idset (Bind Id -> [Id]
forall b. Bind b -> [b]
bindersOf Bind Id
bind))

        | Bool
otherwise     -- Don't dump it
        = (Bag DictBind
free_dbs Bag DictBind -> DictBind -> Bag DictBind
forall a. Bag a -> a -> Bag a
`snocBag` DictBind
db, Bag DictBind
dump_dbs, VarSet
dump_idset)


----------------------
deleteCallsMentioning :: VarSet -> CallDetails -> CallDetails
-- Remove calls *mentioning* bs in any way
deleteCallsMentioning :: VarSet -> CallDetails -> CallDetails
deleteCallsMentioning VarSet
bs CallDetails
calls
  = (CallInfoSet -> CallInfoSet) -> CallDetails -> CallDetails
forall a b. (a -> b) -> DVarEnv a -> DVarEnv b
mapDVarEnv ((CallInfo -> Bool) -> CallInfoSet -> CallInfoSet
ciSetFilter CallInfo -> Bool
keep_call) CallDetails
calls
  where
    keep_call :: CallInfo -> Bool
keep_call (CI { ci_fvs :: CallInfo -> VarSet
ci_fvs = VarSet
fvs }) = Bool -> Bool
not (VarSet
fvs VarSet -> VarSet -> Bool
`intersectsVarSet` VarSet
bs)

deleteCallsFor :: [Id] -> CallDetails -> CallDetails
-- Remove calls *for* bs
deleteCallsFor :: [Id] -> CallDetails -> CallDetails
deleteCallsFor [Id]
bs CallDetails
calls = CallDetails -> [Id] -> CallDetails
forall a. DVarEnv a -> [Id] -> DVarEnv a
delDVarEnvList CallDetails
calls [Id]
bs

{-
************************************************************************
*                                                                      *
\subsubsection{Boring helper functions}
*                                                                      *
************************************************************************
-}

newtype SpecM a = SpecM (State SpecState a) deriving (a -> SpecM b -> SpecM a
(a -> b) -> SpecM a -> SpecM b
(forall a b. (a -> b) -> SpecM a -> SpecM b)
-> (forall a b. a -> SpecM b -> SpecM a) -> Functor SpecM
forall a b. a -> SpecM b -> SpecM a
forall a b. (a -> b) -> SpecM a -> SpecM b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
<$ :: a -> SpecM b -> SpecM a
$c<$ :: forall a b. a -> SpecM b -> SpecM a
fmap :: (a -> b) -> SpecM a -> SpecM b
$cfmap :: forall a b. (a -> b) -> SpecM a -> SpecM b
Functor)

data SpecState = SpecState {
                     SpecState -> UniqSupply
spec_uniq_supply :: UniqSupply,
                     SpecState -> Module
spec_module :: Module,
                     SpecState -> DynFlags
spec_dflags :: DynFlags
                 }

instance Applicative SpecM where
    pure :: a -> SpecM a
pure a
x = State SpecState a -> SpecM a
forall a. State SpecState a -> SpecM a
SpecM (State SpecState a -> SpecM a) -> State SpecState a -> SpecM a
forall a b. (a -> b) -> a -> b
$ a -> State SpecState a
forall (m :: * -> *) a. Monad m => a -> m a
return a
x
    <*> :: SpecM (a -> b) -> SpecM a -> SpecM b
(<*>) = SpecM (a -> b) -> SpecM a -> SpecM b
forall (m :: * -> *) a b. Monad m => m (a -> b) -> m a -> m b
ap

instance Monad SpecM where
    SpecM State SpecState a
x >>= :: SpecM a -> (a -> SpecM b) -> SpecM b
>>= a -> SpecM b
f = State SpecState b -> SpecM b
forall a. State SpecState a -> SpecM a
SpecM (State SpecState b -> SpecM b) -> State SpecState b -> SpecM b
forall a b. (a -> b) -> a -> b
$ do a
y <- State SpecState a
x
                               case a -> SpecM b
f a
y of
                                   SpecM State SpecState b
z ->
                                       State SpecState b
z
#if !MIN_VERSION_base(4,13,0)
    fail = MonadFail.fail
#endif

instance MonadFail.MonadFail SpecM where
   fail :: String -> SpecM a
fail String
str = State SpecState a -> SpecM a
forall a. State SpecState a -> SpecM a
SpecM (State SpecState a -> SpecM a) -> State SpecState a -> SpecM a
forall a b. (a -> b) -> a -> b
$ String -> State SpecState a
forall a. HasCallStack => String -> a
error String
str

instance MonadUnique SpecM where
    getUniqueSupplyM :: SpecM UniqSupply
getUniqueSupplyM
        = State SpecState UniqSupply -> SpecM UniqSupply
forall a. State SpecState a -> SpecM a
SpecM (State SpecState UniqSupply -> SpecM UniqSupply)
-> State SpecState UniqSupply -> SpecM UniqSupply
forall a b. (a -> b) -> a -> b
$ do SpecState
st <- State SpecState SpecState
forall s. State s s
get
                     let (UniqSupply
us1, UniqSupply
us2) = UniqSupply -> (UniqSupply, UniqSupply)
splitUniqSupply (UniqSupply -> (UniqSupply, UniqSupply))
-> UniqSupply -> (UniqSupply, UniqSupply)
forall a b. (a -> b) -> a -> b
$ SpecState -> UniqSupply
spec_uniq_supply SpecState
st
                     SpecState -> State SpecState ()
forall s. s -> State s ()
put (SpecState -> State SpecState ())
-> SpecState -> State SpecState ()
forall a b. (a -> b) -> a -> b
$ SpecState
st { spec_uniq_supply :: UniqSupply
spec_uniq_supply = UniqSupply
us2 }
                     UniqSupply -> State SpecState UniqSupply
forall (m :: * -> *) a. Monad m => a -> m a
return UniqSupply
us1

    getUniqueM :: SpecM Unique
getUniqueM
        = State SpecState Unique -> SpecM Unique
forall a. State SpecState a -> SpecM a
SpecM (State SpecState Unique -> SpecM Unique)
-> State SpecState Unique -> SpecM Unique
forall a b. (a -> b) -> a -> b
$ do SpecState
st <- State SpecState SpecState
forall s. State s s
get
                     let (Unique
u,UniqSupply
us') = UniqSupply -> (Unique, UniqSupply)
takeUniqFromSupply (UniqSupply -> (Unique, UniqSupply))
-> UniqSupply -> (Unique, UniqSupply)
forall a b. (a -> b) -> a -> b
$ SpecState -> UniqSupply
spec_uniq_supply SpecState
st
                     SpecState -> State SpecState ()
forall s. s -> State s ()
put (SpecState -> State SpecState ())
-> SpecState -> State SpecState ()
forall a b. (a -> b) -> a -> b
$ SpecState
st { spec_uniq_supply :: UniqSupply
spec_uniq_supply = UniqSupply
us' }
                     Unique -> State SpecState Unique
forall (m :: * -> *) a. Monad m => a -> m a
return Unique
u

instance HasDynFlags SpecM where
    getDynFlags :: SpecM DynFlags
getDynFlags = State SpecState DynFlags -> SpecM DynFlags
forall a. State SpecState a -> SpecM a
SpecM (State SpecState DynFlags -> SpecM DynFlags)
-> State SpecState DynFlags -> SpecM DynFlags
forall a b. (a -> b) -> a -> b
$ (SpecState -> DynFlags)
-> State SpecState SpecState -> State SpecState DynFlags
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM SpecState -> DynFlags
spec_dflags State SpecState SpecState
forall s. State s s
get

instance HasModule SpecM where
    getModule :: SpecM Module
getModule = State SpecState Module -> SpecM Module
forall a. State SpecState a -> SpecM a
SpecM (State SpecState Module -> SpecM Module)
-> State SpecState Module -> SpecM Module
forall a b. (a -> b) -> a -> b
$ (SpecState -> Module)
-> State SpecState SpecState -> State SpecState Module
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM SpecState -> Module
spec_module State SpecState SpecState
forall s. State s s
get

runSpecM :: DynFlags -> Module -> SpecM a -> CoreM a
runSpecM :: DynFlags -> Module -> SpecM a -> CoreM a
runSpecM DynFlags
dflags Module
this_mod (SpecM State SpecState a
spec)
    = do UniqSupply
us <- CoreM UniqSupply
forall (m :: * -> *). MonadUnique m => m UniqSupply
getUniqueSupplyM
         let initialState :: SpecState
initialState = SpecState :: UniqSupply -> Module -> DynFlags -> SpecState
SpecState {
                                spec_uniq_supply :: UniqSupply
spec_uniq_supply = UniqSupply
us,
                                spec_module :: Module
spec_module = Module
this_mod,
                                spec_dflags :: DynFlags
spec_dflags = DynFlags
dflags
                            }
         a -> CoreM a
forall (m :: * -> *) a. Monad m => a -> m a
return (a -> CoreM a) -> a -> CoreM a
forall a b. (a -> b) -> a -> b
$ State SpecState a -> SpecState -> a
forall s a. State s a -> s -> a
evalState State SpecState a
spec SpecState
initialState

mapAndCombineSM :: (a -> SpecM (b, UsageDetails)) -> [a] -> SpecM ([b], UsageDetails)
mapAndCombineSM :: (a -> SpecM (b, UsageDetails)) -> [a] -> SpecM ([b], UsageDetails)
mapAndCombineSM a -> SpecM (b, UsageDetails)
_ []     = ([b], UsageDetails) -> SpecM ([b], UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return ([], UsageDetails
emptyUDs)
mapAndCombineSM a -> SpecM (b, UsageDetails)
f (a
x:[a]
xs) = do (b
y, UsageDetails
uds1) <- a -> SpecM (b, UsageDetails)
f a
x
                              ([b]
ys, UsageDetails
uds2) <- (a -> SpecM (b, UsageDetails)) -> [a] -> SpecM ([b], UsageDetails)
forall a b.
(a -> SpecM (b, UsageDetails)) -> [a] -> SpecM ([b], UsageDetails)
mapAndCombineSM a -> SpecM (b, UsageDetails)
f [a]
xs
                              ([b], UsageDetails) -> SpecM ([b], UsageDetails)
forall (m :: * -> *) a. Monad m => a -> m a
return (b
yb -> [b] -> [b]
forall a. a -> [a] -> [a]
:[b]
ys, UsageDetails
uds1 UsageDetails -> UsageDetails -> UsageDetails
`plusUDs` UsageDetails
uds2)

extendTvSubstList :: SpecEnv -> [(TyVar,Type)] -> SpecEnv
extendTvSubstList :: SpecEnv -> [(Id, Type)] -> SpecEnv
extendTvSubstList SpecEnv
env [(Id, Type)]
tv_binds
  = SpecEnv
env { se_subst :: Subst
se_subst = Subst -> [(Id, Type)] -> Subst
Core.extendTvSubstList (SpecEnv -> Subst
se_subst SpecEnv
env) [(Id, Type)]
tv_binds }

substTy :: SpecEnv -> Type -> Type
substTy :: SpecEnv -> Type -> Type
substTy SpecEnv
env Type
ty = Subst -> Type -> Type
Core.substTy (SpecEnv -> Subst
se_subst SpecEnv
env) Type
ty

substCo :: SpecEnv -> Coercion -> Coercion
substCo :: SpecEnv -> Coercion -> Coercion
substCo SpecEnv
env Coercion
co = HasCallStack => Subst -> Coercion -> Coercion
Subst -> Coercion -> Coercion
Core.substCo (SpecEnv -> Subst
se_subst SpecEnv
env) Coercion
co

substBndr :: SpecEnv -> CoreBndr -> (SpecEnv, CoreBndr)
substBndr :: SpecEnv -> Id -> (SpecEnv, Id)
substBndr SpecEnv
env Id
bs = case Subst -> Id -> (Subst, Id)
Core.substBndr (SpecEnv -> Subst
se_subst SpecEnv
env) Id
bs of
                      (Subst
subst', Id
bs') -> (SpecEnv
env { se_subst :: Subst
se_subst = Subst
subst' }, Id
bs')

substBndrs :: SpecEnv -> [CoreBndr] -> (SpecEnv, [CoreBndr])
substBndrs :: SpecEnv -> [Id] -> (SpecEnv, [Id])
substBndrs SpecEnv
env [Id]
bs = case Subst -> [Id] -> (Subst, [Id])
Core.substBndrs (SpecEnv -> Subst
se_subst SpecEnv
env) [Id]
bs of
                      (Subst
subst', [Id]
bs') -> (SpecEnv
env { se_subst :: Subst
se_subst = Subst
subst' }, [Id]
bs')

cloneBindSM :: SpecEnv -> CoreBind -> SpecM (SpecEnv, SpecEnv, CoreBind)
-- Clone the binders of the bind; return new bind with the cloned binders
-- Return the substitution to use for RHSs, and the one to use for the body
cloneBindSM :: SpecEnv -> Bind Id -> SpecM (SpecEnv, SpecEnv, Bind Id)
cloneBindSM env :: SpecEnv
env@(SE { se_subst :: SpecEnv -> Subst
se_subst = Subst
subst, se_interesting :: SpecEnv -> VarSet
se_interesting = VarSet
interesting }) (NonRec Id
bndr Expr Id
rhs)
  = do { UniqSupply
us <- SpecM UniqSupply
forall (m :: * -> *). MonadUnique m => m UniqSupply
getUniqueSupplyM
       ; let (Subst
subst', Id
bndr') = Subst -> UniqSupply -> Id -> (Subst, Id)
Core.cloneIdBndr Subst
subst UniqSupply
us Id
bndr
             interesting' :: VarSet
interesting' | SpecEnv -> Expr Id -> Bool
interestingDict SpecEnv
env Expr Id
rhs
                          = VarSet
interesting VarSet -> Id -> VarSet
`extendVarSet` Id
bndr'
                          | Bool
otherwise = VarSet
interesting
       ; (SpecEnv, SpecEnv, Bind Id) -> SpecM (SpecEnv, SpecEnv, Bind Id)
forall (m :: * -> *) a. Monad m => a -> m a
return (SpecEnv
env, SpecEnv
env { se_subst :: Subst
se_subst = Subst
subst', se_interesting :: VarSet
se_interesting = VarSet
interesting' }
                , Id -> Expr Id -> Bind Id
forall b. b -> Expr b -> Bind b
NonRec Id
bndr' Expr Id
rhs) }

cloneBindSM env :: SpecEnv
env@(SE { se_subst :: SpecEnv -> Subst
se_subst = Subst
subst, se_interesting :: SpecEnv -> VarSet
se_interesting = VarSet
interesting }) (Rec [(Id, Expr Id)]
pairs)
  = do { UniqSupply
us <- SpecM UniqSupply
forall (m :: * -> *). MonadUnique m => m UniqSupply
getUniqueSupplyM
       ; let (Subst
subst', [Id]
bndrs') = Subst -> UniqSupply -> [Id] -> (Subst, [Id])
Core.cloneRecIdBndrs Subst
subst UniqSupply
us (((Id, Expr Id) -> Id) -> [(Id, Expr Id)] -> [Id]
forall a b. (a -> b) -> [a] -> [b]
map (Id, Expr Id) -> Id
forall a b. (a, b) -> a
fst [(Id, Expr Id)]
pairs)
             env' :: SpecEnv
env' = SpecEnv
env { se_subst :: Subst
se_subst = Subst
subst'
                        , se_interesting :: VarSet
se_interesting = VarSet
interesting VarSet -> [Id] -> VarSet
`extendVarSetList`
                                           [ Id
v | (Id
v,Expr Id
r) <- [(Id, Expr Id)]
pairs, SpecEnv -> Expr Id -> Bool
interestingDict SpecEnv
env Expr Id
r ] }
       ; (SpecEnv, SpecEnv, Bind Id) -> SpecM (SpecEnv, SpecEnv, Bind Id)
forall (m :: * -> *) a. Monad m => a -> m a
return (SpecEnv
env', SpecEnv
env', [(Id, Expr Id)] -> Bind Id
forall b. [(b, Expr b)] -> Bind b
Rec ([Id]
bndrs' [Id] -> [Expr Id] -> [(Id, Expr Id)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` ((Id, Expr Id) -> Expr Id) -> [(Id, Expr Id)] -> [Expr Id]
forall a b. (a -> b) -> [a] -> [b]
map (Id, Expr Id) -> Expr Id
forall a b. (a, b) -> b
snd [(Id, Expr Id)]
pairs)) }

newDictBndr :: SpecEnv -> CoreBndr -> SpecM CoreBndr
-- Make up completely fresh binders for the dictionaries
-- Their bindings are going to float outwards
newDictBndr :: SpecEnv -> Id -> SpecM Id
newDictBndr SpecEnv
env Id
b = do { Unique
uniq <- SpecM Unique
forall (m :: * -> *). MonadUnique m => m Unique
getUniqueM
                        ; let n :: Name
n   = Id -> Name
idName Id
b
                              ty' :: Type
ty' = SpecEnv -> Type -> Type
substTy SpecEnv
env (Id -> Type
idType Id
b)
                        ; Id -> SpecM Id
forall (m :: * -> *) a. Monad m => a -> m a
return (OccName -> Unique -> Type -> SrcSpan -> Id
mkUserLocalOrCoVar (Name -> OccName
nameOccName Name
n) Unique
uniq Type
ty' (Name -> SrcSpan
forall a. NamedThing a => a -> SrcSpan
getSrcSpan Name
n)) }

newSpecIdSM :: Id -> Type -> Maybe JoinArity -> SpecM Id
    -- Give the new Id a similar occurrence name to the old one
newSpecIdSM :: Id -> Type -> Maybe Int -> SpecM Id
newSpecIdSM Id
old_id Type
new_ty Maybe Int
join_arity_maybe
  = do  { Unique
uniq <- SpecM Unique
forall (m :: * -> *). MonadUnique m => m Unique
getUniqueM
        ; let name :: Name
name    = Id -> Name
idName Id
old_id
              new_occ :: OccName
new_occ = OccName -> OccName
mkSpecOcc (Name -> OccName
nameOccName Name
name)
              new_id :: Id
new_id  = OccName -> Unique -> Type -> SrcSpan -> Id
mkUserLocalOrCoVar OccName
new_occ Unique
uniq Type
new_ty (Name -> SrcSpan
forall a. NamedThing a => a -> SrcSpan
getSrcSpan Name
name)
                          Id -> Maybe Int -> Id
`asJoinId_maybe` Maybe Int
join_arity_maybe
        ; Id -> SpecM Id
forall (m :: * -> *) a. Monad m => a -> m a
return Id
new_id }

{-
                Old (but interesting) stuff about unboxed bindings
                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

What should we do when a value is specialised to a *strict* unboxed value?

        map_*_* f (x:xs) = let h = f x
                               t = map f xs
                           in h:t

Could convert let to case:

        map_*_Int# f (x:xs) = case f x of h# ->
                              let t = map f xs
                              in h#:t

This may be undesirable since it forces evaluation here, but the value
may not be used in all branches of the body. In the general case this
transformation is impossible since the mutual recursion in a letrec
cannot be expressed as a case.

There is also a problem with top-level unboxed values, since our
implementation cannot handle unboxed values at the top level.

Solution: Lift the binding of the unboxed value and extract it when it
is used:

        map_*_Int# f (x:xs) = let h = case (f x) of h# -> _Lift h#
                                  t = map f xs
                              in case h of
                                 _Lift h# -> h#:t

Now give it to the simplifier and the _Lifting will be optimised away.

The benefit is that we have given the specialised "unboxed" values a
very simple lifted semantics and then leave it up to the simplifier to
optimise it --- knowing that the overheads will be removed in nearly
all cases.

In particular, the value will only be evaluated in the branches of the
program which use it, rather than being forced at the point where the
value is bound. For example:

        filtermap_*_* p f (x:xs)
          = let h = f x
                t = ...
            in case p x of
                True  -> h:t
                False -> t
   ==>
        filtermap_*_Int# p f (x:xs)
          = let h = case (f x) of h# -> _Lift h#
                t = ...
            in case p x of
                True  -> case h of _Lift h#
                           -> h#:t
                False -> t

The binding for h can still be inlined in the one branch and the
_Lifting eliminated.


Question: When won't the _Lifting be eliminated?

Answer: When they at the top-level (where it is necessary) or when
inlining would duplicate work (or possibly code depending on
options). However, the _Lifting will still be eliminated if the
strictness analyser deems the lifted binding strict.
-}