{-
(c) The University of Glasgow, 1994-2006


Core pass to saturate constructors and PrimOps
-}

{-# LANGUAGE BangPatterns, CPP, MultiWayIf #-}

{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}

module GHC.CoreToStg.Prep (
      corePrepPgm, corePrepExpr, cvtLitInteger, cvtLitNatural,
      lookupMkIntegerName, lookupIntegerSDataConName,
      lookupMkNaturalName, lookupNaturalSDataConName
  ) where

#include "HsVersions.h"

import GHC.Prelude
import GHC.Platform

import GHC.Core.Opt.OccurAnal

import GHC.Driver.Types
import GHC.Builtin.Names
import GHC.Types.Id.Make ( realWorldPrimId )
import GHC.Core.Utils
import GHC.Core.Opt.Arity
import GHC.Core.FVs
import GHC.Core.Opt.Monad ( CoreToDo(..) )
import GHC.Core.Lint    ( endPassIO )
import GHC.Core
import GHC.Core.Make hiding( FloatBind(..) )   -- We use our own FloatBind here
import GHC.Core.Type
import GHC.Types.Literal
import GHC.Core.Coercion
import GHC.Tc.Utils.Env
import GHC.Core.TyCon
import GHC.Types.Demand
import GHC.Types.Var
import GHC.Types.Var.Set
import GHC.Types.Var.Env
import GHC.Types.Id
import GHC.Types.Id.Info
import GHC.Builtin.Types
import GHC.Core.DataCon
import GHC.Types.Basic
import GHC.Unit.Module
import GHC.Types.Unique.Supply
import GHC.Data.Maybe
import GHC.Data.OrdList
import GHC.Utils.Error
import GHC.Driver.Session
import GHC.Driver.Ways
import GHC.Utils.Misc
import GHC.Utils.Outputable
import GHC.Data.FastString
import GHC.Types.Name   ( NamedThing(..), nameSrcSpan, isInternalName )
import GHC.Types.SrcLoc ( SrcSpan(..), realSrcLocSpan, mkRealSrcLoc )
import Data.Bits
import GHC.Utils.Monad      ( mapAccumLM )
import Control.Monad
import GHC.Types.CostCentre ( CostCentre, ccFromThisModule )
import qualified Data.Set as S

{-
-- ---------------------------------------------------------------------------
-- Note [CorePrep Overview]
-- ---------------------------------------------------------------------------

The goal of this pass is to prepare for code generation.

1.  Saturate constructor applications.

2.  Convert to A-normal form; that is, function arguments
    are always variables.

    * Use case for strict arguments:
        f E ==> case E of x -> f x
        (where f is strict)

    * Use let for non-trivial lazy arguments
        f E ==> let x = E in f x
        (were f is lazy and x is non-trivial)

3.  Similarly, convert any unboxed lets into cases.
    [I'm experimenting with leaving 'ok-for-speculation'
     rhss in let-form right up to this point.]

4.  Ensure that *value* lambdas only occur as the RHS of a binding
    (The code generator can't deal with anything else.)
    Type lambdas are ok, however, because the code gen discards them.

5.  [Not any more; nuked Jun 2002] Do the seq/par munging.

6.  Clone all local Ids.
    This means that all such Ids are unique, rather than the
    weaker guarantee of no clashes which the simplifier provides.
    And that is what the code generator needs.

    We don't clone TyVars or CoVars. The code gen doesn't need that,
    and doing so would be tiresome because then we'd need
    to substitute in types and coercions.

7.  Give each dynamic CCall occurrence a fresh unique; this is
    rather like the cloning step above.

8.  Inject bindings for the "implicit" Ids:
        * Constructor wrappers
        * Constructor workers
    We want curried definitions for all of these in case they
    aren't inlined by some caller.

9.  Replace (lazy e) by e.  See Note [lazyId magic] in GHC.Types.Id.Make
    Also replace (noinline e) by e.

10. Convert (LitInteger i t) into the core representation
    for the Integer i. Normally this uses mkInteger, but if
    we are using the integer-gmp implementation then there is a
    special case where we use the S# constructor for Integers that
    are in the range of Int.

11. Same for LitNatural.

12. Uphold tick consistency while doing this: We move ticks out of
    (non-type) applications where we can, and make sure that we
    annotate according to scoping rules when floating.

13. Collect cost centres (including cost centres in unfoldings) if we're in
    profiling mode. We have to do this here beucase we won't have unfoldings
    after this pass (see `zapUnfolding` and Note [Drop unfoldings and rules].

This is all done modulo type applications and abstractions, so that
when type erasure is done for conversion to STG, we don't end up with
any trivial or useless bindings.


Note [CorePrep invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is the syntax of the Core produced by CorePrep:

    Trivial expressions
       arg ::= lit |  var
              | arg ty  |  /\a. arg
              | truv co  |  /\c. arg  |  arg |> co

    Applications
       app ::= lit  |  var  |  app arg  |  app ty  | app co | app |> co

    Expressions
       body ::= app
              | let(rec) x = rhs in body     -- Boxed only
              | case body of pat -> body
              | /\a. body | /\c. body
              | body |> co

    Right hand sides (only place where value lambdas can occur)
       rhs ::= /\a.rhs  |  \x.rhs  |  body

We define a synonym for each of these non-terminals.  Functions
with the corresponding name produce a result in that syntax.
-}

type CpeArg  = CoreExpr    -- Non-terminal 'arg'
type CpeApp  = CoreExpr    -- Non-terminal 'app'
type CpeBody = CoreExpr    -- Non-terminal 'body'
type CpeRhs  = CoreExpr    -- Non-terminal 'rhs'

{-
************************************************************************
*                                                                      *
                Top level stuff
*                                                                      *
************************************************************************
-}

corePrepPgm :: HscEnv -> Module -> ModLocation -> CoreProgram -> [TyCon]
            -> IO (CoreProgram, S.Set CostCentre)
corePrepPgm :: HscEnv
-> Module
-> ModLocation
-> CoreProgram
-> [TyCon]
-> IO (CoreProgram, Set CostCentre)
corePrepPgm HscEnv
hsc_env Module
this_mod ModLocation
mod_loc CoreProgram
binds [TyCon]
data_tycons =
    DynFlags
-> SDoc
-> ((CoreProgram, Set CostCentre) -> ())
-> IO (CoreProgram, Set CostCentre)
-> IO (CoreProgram, Set CostCentre)
forall (m :: * -> *) a.
MonadIO m =>
DynFlags -> SDoc -> (a -> ()) -> m a -> m a
External instance of the constraint type MonadIO IO
withTiming DynFlags
dflags
               (String -> SDoc
text String
"CorePrep"SDoc -> SDoc -> SDoc
<+>SDoc -> SDoc
brackets (Module -> SDoc
forall a. Outputable a => a -> SDoc
External instance of the constraint type Outputable Module
ppr Module
this_mod))
               (() -> (CoreProgram, Set CostCentre) -> ()
forall a b. a -> b -> a
const ()) (IO (CoreProgram, Set CostCentre)
 -> IO (CoreProgram, Set CostCentre))
-> IO (CoreProgram, Set CostCentre)
-> IO (CoreProgram, Set CostCentre)
forall a b. (a -> b) -> a -> b
$ do
    UniqSupply
us <- Char -> IO UniqSupply
mkSplitUniqSupply Char
's'
    CorePrepEnv
initialCorePrepEnv <- DynFlags -> HscEnv -> IO CorePrepEnv
mkInitialCorePrepEnv DynFlags
dflags HscEnv
hsc_env

    let cost_centres :: Set CostCentre
cost_centres
          | Way
WayProf Way -> Set Way -> Bool
forall a. Ord a => a -> Set a -> Bool
External instance of the constraint type Ord Way
`S.member` DynFlags -> Set Way
ways DynFlags
dflags
          = Module -> CoreProgram -> Set CostCentre
collectCostCentres Module
this_mod CoreProgram
binds
          | Bool
otherwise
          = Set CostCentre
forall a. Set a
S.empty

        implicit_binds :: CoreProgram
implicit_binds = DynFlags -> ModLocation -> [TyCon] -> CoreProgram
mkDataConWorkers DynFlags
dflags ModLocation
mod_loc [TyCon]
data_tycons
            -- NB: we must feed mkImplicitBinds through corePrep too
            -- so that they are suitably cloned and eta-expanded

        binds_out :: CoreProgram
binds_out = UniqSupply -> UniqSM CoreProgram -> CoreProgram
forall a. UniqSupply -> UniqSM a -> a
initUs_ UniqSupply
us (UniqSM CoreProgram -> CoreProgram)
-> UniqSM CoreProgram -> CoreProgram
forall a b. (a -> b) -> a -> b
$ do
                      Floats
floats1 <- CorePrepEnv -> CoreProgram -> UniqSM Floats
corePrepTopBinds CorePrepEnv
initialCorePrepEnv CoreProgram
binds
                      Floats
floats2 <- CorePrepEnv -> CoreProgram -> UniqSM Floats
corePrepTopBinds CorePrepEnv
initialCorePrepEnv CoreProgram
implicit_binds
                      CoreProgram -> UniqSM CoreProgram
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats -> CoreProgram
deFloatTop (Floats
floats1 Floats -> Floats -> Floats
`appendFloats` Floats
floats2))

    HscEnv
-> PrintUnqualified
-> CoreToDo
-> CoreProgram
-> [CoreRule]
-> IO ()
endPassIO HscEnv
hsc_env PrintUnqualified
alwaysQualify CoreToDo
CorePrep CoreProgram
binds_out []
    (CoreProgram, Set CostCentre) -> IO (CoreProgram, Set CostCentre)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad IO
return (CoreProgram
binds_out, Set CostCentre
cost_centres)
  where
    dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env

corePrepExpr :: DynFlags -> HscEnv -> CoreExpr -> IO CoreExpr
corePrepExpr :: DynFlags -> HscEnv -> CpeRhs -> IO CpeRhs
corePrepExpr DynFlags
dflags HscEnv
hsc_env CpeRhs
expr =
    DynFlags -> SDoc -> (CpeRhs -> ()) -> IO CpeRhs -> IO CpeRhs
forall (m :: * -> *) a.
MonadIO m =>
DynFlags -> SDoc -> (a -> ()) -> m a -> m a
External instance of the constraint type MonadIO IO
withTiming DynFlags
dflags (String -> SDoc
text String
"CorePrep [expr]") (() -> CpeRhs -> ()
forall a b. a -> b -> a
const ()) (IO CpeRhs -> IO CpeRhs) -> IO CpeRhs -> IO CpeRhs
forall a b. (a -> b) -> a -> b
$ do
    UniqSupply
us <- Char -> IO UniqSupply
mkSplitUniqSupply Char
's'
    CorePrepEnv
initialCorePrepEnv <- DynFlags -> HscEnv -> IO CorePrepEnv
mkInitialCorePrepEnv DynFlags
dflags HscEnv
hsc_env
    let new_expr :: CpeRhs
new_expr = UniqSupply -> UniqSM CpeRhs -> CpeRhs
forall a. UniqSupply -> UniqSM a -> a
initUs_ UniqSupply
us (CorePrepEnv -> CpeRhs -> UniqSM CpeRhs
cpeBodyNF CorePrepEnv
initialCorePrepEnv CpeRhs
expr)
    DynFlags -> DumpFlag -> String -> DumpFormat -> SDoc -> IO ()
dumpIfSet_dyn DynFlags
dflags DumpFlag
Opt_D_dump_prep String
"CorePrep" DumpFormat
FormatCore (CpeRhs -> SDoc
forall a. Outputable a => a -> SDoc
External instance of the constraint type forall b. OutputableBndr b => Outputable (Expr b)
External instance of the constraint type OutputableBndr Id
ppr CpeRhs
new_expr)
    CpeRhs -> IO CpeRhs
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad IO
return CpeRhs
new_expr

corePrepTopBinds :: CorePrepEnv -> [CoreBind] -> UniqSM Floats
-- Note [Floating out of top level bindings]
corePrepTopBinds :: CorePrepEnv -> CoreProgram -> UniqSM Floats
corePrepTopBinds CorePrepEnv
initialCorePrepEnv CoreProgram
binds
  = CorePrepEnv -> CoreProgram -> UniqSM Floats
go CorePrepEnv
initialCorePrepEnv CoreProgram
binds
  where
    go :: CorePrepEnv -> CoreProgram -> UniqSM Floats
go CorePrepEnv
_   []             = Floats -> UniqSM Floats
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return Floats
emptyFloats
    go CorePrepEnv
env (CoreBind
bind : CoreProgram
binds) = do (CorePrepEnv
env', Floats
floats, Maybe CoreBind
maybe_new_bind)
                                 <- TopLevelFlag
-> CorePrepEnv
-> CoreBind
-> UniqSM (CorePrepEnv, Floats, Maybe CoreBind)
cpeBind TopLevelFlag
TopLevel CorePrepEnv
env CoreBind
bind
                               MASSERT(isNothing maybe_new_bind)
                                 -- Only join points get returned this way by
                                 -- cpeBind, and no join point may float to top
                               Floats
floatss <- CorePrepEnv -> CoreProgram -> UniqSM Floats
go CorePrepEnv
env' CoreProgram
binds
                               Floats -> UniqSM Floats
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
floats Floats -> Floats -> Floats
`appendFloats` Floats
floatss)

mkDataConWorkers :: DynFlags -> ModLocation -> [TyCon] -> [CoreBind]
-- See Note [Data constructor workers]
-- c.f. Note [Injecting implicit bindings] in GHC.Iface.Tidy
mkDataConWorkers :: DynFlags -> ModLocation -> [TyCon] -> CoreProgram
mkDataConWorkers DynFlags
dflags ModLocation
mod_loc [TyCon]
data_tycons
  = [ Id -> CpeRhs -> CoreBind
forall b. b -> Expr b -> Bind b
NonRec Id
id (Name -> CpeRhs -> CpeRhs
forall {b}. Name -> Expr b -> Expr b
tick_it (DataCon -> Name
forall a. NamedThing a => a -> Name
External instance of the constraint type NamedThing DataCon
getName DataCon
data_con) (Id -> CpeRhs
forall b. Id -> Expr b
Var Id
id))
                                -- The ice is thin here, but it works
    | TyCon
tycon <- [TyCon]
data_tycons,     -- CorePrep will eta-expand it
      DataCon
data_con <- TyCon -> [DataCon]
tyConDataCons TyCon
tycon,
      let id :: Id
id = DataCon -> Id
dataConWorkId DataCon
data_con
    ]
 where
   -- If we want to generate debug info, we put a source note on the
   -- worker. This is useful, especially for heap profiling.
   tick_it :: Name -> Expr b -> Expr b
tick_it Name
name
     | DynFlags -> Int
debugLevel DynFlags
dflags Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
External instance of the constraint type Eq Int
== Int
0                = Expr b -> Expr b
forall a. a -> a
id
     | RealSrcSpan RealSrcSpan
span Maybe BufSpan
_ <- Name -> SrcSpan
nameSrcSpan Name
name = RealSrcSpan -> Expr b -> Expr b
forall {b}. RealSrcSpan -> Expr b -> Expr b
tick RealSrcSpan
span
     | Just String
file <- ModLocation -> Maybe String
ml_hs_file ModLocation
mod_loc       = RealSrcSpan -> Expr b -> Expr b
forall {b}. RealSrcSpan -> Expr b -> Expr b
tick (String -> RealSrcSpan
span1 String
file)
     | Bool
otherwise                             = RealSrcSpan -> Expr b -> Expr b
forall {b}. RealSrcSpan -> Expr b -> Expr b
tick (String -> RealSrcSpan
span1 String
"???")
     where tick :: RealSrcSpan -> Expr b -> Expr b
tick RealSrcSpan
span  = Tickish Id -> Expr b -> Expr b
forall b. Tickish Id -> Expr b -> Expr b
Tick (RealSrcSpan -> String -> Tickish Id
forall id. RealSrcSpan -> String -> Tickish id
SourceNote RealSrcSpan
span (String -> Tickish Id) -> String -> Tickish Id
forall a b. (a -> b) -> a -> b
$ DynFlags -> SDoc -> String
showSDoc DynFlags
dflags (Name -> SDoc
forall a. Outputable a => a -> SDoc
External instance of the constraint type Outputable Name
ppr Name
name))
           span1 :: String -> RealSrcSpan
span1 String
file = RealSrcLoc -> RealSrcSpan
realSrcLocSpan (RealSrcLoc -> RealSrcSpan) -> RealSrcLoc -> RealSrcSpan
forall a b. (a -> b) -> a -> b
$ FastString -> Int -> Int -> RealSrcLoc
mkRealSrcLoc (String -> FastString
mkFastString String
file) Int
1 Int
1

{-
Note [Floating out of top level bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NB: we do need to float out of top-level bindings
Consider        x = length [True,False]
We want to get
                s1 = False : []
                s2 = True  : s1
                x  = length s2

We return a *list* of bindings, because we may start with
        x* = f (g y)
where x is demanded, in which case we want to finish with
        a = g y
        x* = f a
And then x will actually end up case-bound

Note [Join points and floating]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Join points can float out of other join points but not out of value bindings:

  let z =
    let  w = ... in -- can float
    join k = ... in -- can't float
    ... jump k ...
  join j x1 ... xn =
    let  y = ... in -- can float (but don't want to)
    join h = ... in -- can float (but not much point)
    ... jump h ...
  in ...

Here, the jump to h remains valid if h is floated outward, but the jump to k
does not.

We don't float *out* of join points. It would only be safe to float out of
nullary join points (or ones where the arguments are all either type arguments
or dead binders). Nullary join points aren't ever recursive, so they're always
effectively one-shot functions, which we don't float out of. We *could* float
join points from nullary join points, but there's no clear benefit at this
stage.

Note [Data constructor workers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create any necessary "implicit" bindings for data con workers.  We
create the rather strange (non-recursive!) binding

        $wC = \x y -> $wC x y

i.e. a curried constructor that allocates.  This means that we can
treat the worker for a constructor like any other function in the rest
of the compiler.  The point here is that CoreToStg will generate a
StgConApp for the RHS, rather than a call to the worker (which would
give a loop).  As Lennart says: the ice is thin here, but it works.

Hmm.  Should we create bindings for dictionary constructors?  They are
always fully applied, and the bindings are just there to support
partial applications. But it's easier to let them through.


Note [Dead code in CorePrep]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Imagine that we got an input program like this (see #4962):

  f :: Show b => Int -> (Int, b -> Maybe Int -> Int)
  f x = (g True (Just x) + g () (Just x), g)
    where
      g :: Show a => a -> Maybe Int -> Int
      g _ Nothing = x
      g y (Just z) = if z > 100 then g y (Just (z + length (show y))) else g y unknown

After specialisation and SpecConstr, we would get something like this:

  f :: Show b => Int -> (Int, b -> Maybe Int -> Int)
  f x = (g$Bool_True_Just x + g$Unit_Unit_Just x, g)
    where
      {-# RULES g $dBool = g$Bool
                g $dUnit = g$Unit #-}
      g = ...
      {-# RULES forall x. g$Bool True (Just x) = g$Bool_True_Just x #-}
      g$Bool = ...
      {-# RULES forall x. g$Unit () (Just x) = g$Unit_Unit_Just x #-}
      g$Unit = ...
      g$Bool_True_Just = ...
      g$Unit_Unit_Just = ...

Note that the g$Bool and g$Unit functions are actually dead code: they
are only kept alive by the occurrence analyser because they are
referred to by the rules of g, which is being kept alive by the fact
that it is used (unspecialised) in the returned pair.

However, at the CorePrep stage there is no way that the rules for g
will ever fire, and it really seems like a shame to produce an output
program that goes to the trouble of allocating a closure for the
unreachable g$Bool and g$Unit functions.

The way we fix this is to:
 * In cloneBndr, drop all unfoldings/rules

 * In deFloatTop, run a simple dead code analyser on each top-level
   RHS to drop the dead local bindings.

The reason we don't just OccAnal the whole output of CorePrep is that
the tidier ensures that all top-level binders are GlobalIds, so they
don't show up in the free variables any longer. So if you run the
occurrence analyser on the output of CoreTidy (or later) you e.g. turn
this program:

  Rec {
  f = ... f ...
  }

Into this one:

  f = ... f ...

(Since f is not considered to be free in its own RHS.)


************************************************************************
*                                                                      *
                The main code
*                                                                      *
************************************************************************
-}

cpeBind :: TopLevelFlag -> CorePrepEnv -> CoreBind
        -> UniqSM (CorePrepEnv,
                   Floats,         -- Floating value bindings
                   Maybe CoreBind) -- Just bind' <=> returned new bind; no float
                                   -- Nothing <=> added bind' to floats instead
cpeBind :: TopLevelFlag
-> CorePrepEnv
-> CoreBind
-> UniqSM (CorePrepEnv, Floats, Maybe CoreBind)
cpeBind TopLevelFlag
top_lvl CorePrepEnv
env (NonRec Id
bndr CpeRhs
rhs)
  | Bool -> Bool
not (Id -> Bool
isJoinId Id
bndr)
  = do { (CorePrepEnv
env1, Id
bndr1) <- CorePrepEnv -> Id -> UniqSM (CorePrepEnv, Id)
cpCloneBndr CorePrepEnv
env Id
bndr
       ; let dmd :: Demand
dmd         = Id -> Demand
idDemandInfo Id
bndr
             is_unlifted :: Bool
is_unlifted = HasDebugCallStack => Type -> Bool
Type -> Bool
External instance of the constraint type HasDebugCallStack
isUnliftedType (Id -> Type
idType Id
bndr)
       ; (Floats
floats, CpeRhs
rhs1) <- TopLevelFlag
-> RecFlag
-> Demand
-> Bool
-> CorePrepEnv
-> Id
-> CpeRhs
-> UniqSM (Floats, CpeRhs)
cpePair TopLevelFlag
top_lvl RecFlag
NonRecursive
                                   Demand
dmd Bool
is_unlifted
                                   CorePrepEnv
env Id
bndr1 CpeRhs
rhs
       -- See Note [Inlining in CorePrep]
       ; let triv_rhs :: Bool
triv_rhs = CpeRhs -> Bool
cpExprIsTrivial CpeRhs
rhs1
             env2 :: CorePrepEnv
env2    | Bool
triv_rhs  = CorePrepEnv -> Id -> CpeRhs -> CorePrepEnv
extendCorePrepEnvExpr CorePrepEnv
env1 Id
bndr CpeRhs
rhs1
                     | Bool
otherwise = CorePrepEnv
env1
             floats1 :: Floats
floats1 | Bool
triv_rhs, Name -> Bool
isInternalName (Id -> Name
idName Id
bndr)
                     = Floats
floats
                     | Bool
otherwise
                     = Floats -> FloatingBind -> Floats
addFloat Floats
floats FloatingBind
new_float

             new_float :: FloatingBind
new_float = Demand -> Bool -> Id -> CpeRhs -> FloatingBind
mkFloat Demand
dmd Bool
is_unlifted Id
bndr1 CpeRhs
rhs1

       ; (CorePrepEnv, Floats, Maybe CoreBind)
-> UniqSM (CorePrepEnv, Floats, Maybe CoreBind)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (CorePrepEnv
env2, Floats
floats1, Maybe CoreBind
forall a. Maybe a
Nothing) }

  | Bool
otherwise -- A join point; see Note [Join points and floating]
  = ASSERT(not (isTopLevel top_lvl)) -- can't have top-level join point
    do { (CorePrepEnv
_, Id
bndr1) <- CorePrepEnv -> Id -> UniqSM (CorePrepEnv, Id)
cpCloneBndr CorePrepEnv
env Id
bndr
       ; (Id
bndr2, CpeRhs
rhs1) <- CorePrepEnv -> Id -> CpeRhs -> UniqSM (Id, CpeRhs)
cpeJoinPair CorePrepEnv
env Id
bndr1 CpeRhs
rhs
       ; (CorePrepEnv, Floats, Maybe CoreBind)
-> UniqSM (CorePrepEnv, Floats, Maybe CoreBind)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (CorePrepEnv -> Id -> Id -> CorePrepEnv
extendCorePrepEnv CorePrepEnv
env Id
bndr Id
bndr2,
                 Floats
emptyFloats,
                 CoreBind -> Maybe CoreBind
forall a. a -> Maybe a
Just (Id -> CpeRhs -> CoreBind
forall b. b -> Expr b -> Bind b
NonRec Id
bndr2 CpeRhs
rhs1)) }

cpeBind TopLevelFlag
top_lvl CorePrepEnv
env (Rec [(Id, CpeRhs)]
pairs)
  | Bool -> Bool
not (Id -> Bool
isJoinId ([Id] -> Id
forall a. [a] -> a
head [Id]
bndrs))
  = do { (CorePrepEnv
env', [Id]
bndrs1) <- CorePrepEnv -> [Id] -> UniqSM (CorePrepEnv, [Id])
cpCloneBndrs CorePrepEnv
env [Id]
bndrs
       ; [(Floats, CpeRhs)]
stuff <- (Id -> CpeRhs -> UniqSM (Floats, CpeRhs))
-> [Id] -> [CpeRhs] -> UniqSM [(Floats, CpeRhs)]
forall (m :: * -> *) a b c.
Applicative m =>
(a -> b -> m c) -> [a] -> [b] -> m [c]
External instance of the constraint type Applicative UniqSM
zipWithM (TopLevelFlag
-> RecFlag
-> Demand
-> Bool
-> CorePrepEnv
-> Id
-> CpeRhs
-> UniqSM (Floats, CpeRhs)
cpePair TopLevelFlag
top_lvl RecFlag
Recursive Demand
topDmd Bool
False CorePrepEnv
env')
                           [Id]
bndrs1 [CpeRhs]
rhss

       ; let ([Floats]
floats_s, [CpeRhs]
rhss1) = [(Floats, CpeRhs)] -> ([Floats], [CpeRhs])
forall a b. [(a, b)] -> ([a], [b])
unzip [(Floats, CpeRhs)]
stuff
             all_pairs :: [(Id, CpeRhs)]
all_pairs = (FloatingBind -> [(Id, CpeRhs)] -> [(Id, CpeRhs)])
-> [(Id, CpeRhs)] -> OrdList FloatingBind -> [(Id, CpeRhs)]
forall a b. (a -> b -> b) -> b -> OrdList a -> b
foldrOL FloatingBind -> [(Id, CpeRhs)] -> [(Id, CpeRhs)]
add_float ([Id]
bndrs1 [Id] -> [CpeRhs] -> [(Id, CpeRhs)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [CpeRhs]
rhss1)
                                           ([Floats] -> OrdList FloatingBind
concatFloats [Floats]
floats_s)

       ; (CorePrepEnv, Floats, Maybe CoreBind)
-> UniqSM (CorePrepEnv, Floats, Maybe CoreBind)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (CorePrepEnv -> [(Id, Id)] -> CorePrepEnv
extendCorePrepEnvList CorePrepEnv
env ([Id]
bndrs [Id] -> [Id] -> [(Id, Id)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [Id]
bndrs1),
                 FloatingBind -> Floats
unitFloat (CoreBind -> FloatingBind
FloatLet ([(Id, CpeRhs)] -> CoreBind
forall b. [(b, Expr b)] -> Bind b
Rec [(Id, CpeRhs)]
all_pairs)),
                 Maybe CoreBind
forall a. Maybe a
Nothing) }

  | Bool
otherwise -- See Note [Join points and floating]
  = do { (CorePrepEnv
env', [Id]
bndrs1) <- CorePrepEnv -> [Id] -> UniqSM (CorePrepEnv, [Id])
cpCloneBndrs CorePrepEnv
env [Id]
bndrs
       ; [(Id, CpeRhs)]
pairs1 <- (Id -> CpeRhs -> UniqSM (Id, CpeRhs))
-> [Id] -> [CpeRhs] -> UniqSM [(Id, CpeRhs)]
forall (m :: * -> *) a b c.
Applicative m =>
(a -> b -> m c) -> [a] -> [b] -> m [c]
External instance of the constraint type Applicative UniqSM
zipWithM (CorePrepEnv -> Id -> CpeRhs -> UniqSM (Id, CpeRhs)
cpeJoinPair CorePrepEnv
env') [Id]
bndrs1 [CpeRhs]
rhss

       ; let bndrs2 :: [Id]
bndrs2 = ((Id, CpeRhs) -> Id) -> [(Id, CpeRhs)] -> [Id]
forall a b. (a -> b) -> [a] -> [b]
map (Id, CpeRhs) -> Id
forall a b. (a, b) -> a
fst [(Id, CpeRhs)]
pairs1
       ; (CorePrepEnv, Floats, Maybe CoreBind)
-> UniqSM (CorePrepEnv, Floats, Maybe CoreBind)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (CorePrepEnv -> [(Id, Id)] -> CorePrepEnv
extendCorePrepEnvList CorePrepEnv
env' ([Id]
bndrs [Id] -> [Id] -> [(Id, Id)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [Id]
bndrs2),
                 Floats
emptyFloats,
                 CoreBind -> Maybe CoreBind
forall a. a -> Maybe a
Just ([(Id, CpeRhs)] -> CoreBind
forall b. [(b, Expr b)] -> Bind b
Rec [(Id, CpeRhs)]
pairs1)) }
  where
    ([Id]
bndrs, [CpeRhs]
rhss) = [(Id, CpeRhs)] -> ([Id], [CpeRhs])
forall a b. [(a, b)] -> ([a], [b])
unzip [(Id, CpeRhs)]
pairs

        -- Flatten all the floats, and the current
        -- group into a single giant Rec
    add_float :: FloatingBind -> [(Id, CpeRhs)] -> [(Id, CpeRhs)]
add_float (FloatLet (NonRec Id
b CpeRhs
r)) [(Id, CpeRhs)]
prs2 = (Id
b,CpeRhs
r) (Id, CpeRhs) -> [(Id, CpeRhs)] -> [(Id, CpeRhs)]
forall a. a -> [a] -> [a]
: [(Id, CpeRhs)]
prs2
    add_float (FloatLet (Rec [(Id, CpeRhs)]
prs1))   [(Id, CpeRhs)]
prs2 = [(Id, CpeRhs)]
prs1 [(Id, CpeRhs)] -> [(Id, CpeRhs)] -> [(Id, CpeRhs)]
forall a. [a] -> [a] -> [a]
++ [(Id, CpeRhs)]
prs2
    add_float FloatingBind
b                       [(Id, CpeRhs)]
_    = String -> SDoc -> [(Id, CpeRhs)]
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"cpeBind" (FloatingBind -> SDoc
forall a. Outputable a => a -> SDoc
Instance of class: Outputable of the constraint type Outputable FloatingBind
ppr FloatingBind
b)

---------------
cpePair :: TopLevelFlag -> RecFlag -> Demand -> Bool
        -> CorePrepEnv -> OutId -> CoreExpr
        -> UniqSM (Floats, CpeRhs)
-- Used for all bindings
-- The binder is already cloned, hence an OutId
cpePair :: TopLevelFlag
-> RecFlag
-> Demand
-> Bool
-> CorePrepEnv
-> Id
-> CpeRhs
-> UniqSM (Floats, CpeRhs)
cpePair TopLevelFlag
top_lvl RecFlag
is_rec Demand
dmd Bool
is_unlifted CorePrepEnv
env Id
bndr CpeRhs
rhs
  = ASSERT(not (isJoinId bndr)) -- those should use cpeJoinPair
    do { (Floats
floats1, CpeRhs
rhs1) <- CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeRhsE CorePrepEnv
env CpeRhs
rhs

       -- See if we are allowed to float this stuff out of the RHS
       ; (Floats
floats2, CpeRhs
rhs2) <- Floats -> CpeRhs -> UniqSM (Floats, CpeRhs)
float_from_rhs Floats
floats1 CpeRhs
rhs1

       -- Make the arity match up
       ; (Floats
floats3, CpeRhs
rhs3)
            <- if CpeRhs -> Int
manifestArity CpeRhs
rhs1 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
External instance of the constraint type Ord Int
<= Int
arity
               then (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
floats2, Int -> CpeRhs -> CpeRhs
cpeEtaExpand Int
arity CpeRhs
rhs2)
               else WARN(True, text "CorePrep: silly extra arguments:" <+> ppr bndr)
                               -- Note [Silly extra arguments]
                    (do { Id
v <- Type -> UniqSM Id
newVar (Id -> Type
idType Id
bndr)
                        ; let float :: FloatingBind
float = Demand -> Bool -> Id -> CpeRhs -> FloatingBind
mkFloat Demand
topDmd Bool
False Id
v CpeRhs
rhs2
                        ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return ( Floats -> FloatingBind -> Floats
addFloat Floats
floats2 FloatingBind
float
                                 , Int -> CpeRhs -> CpeRhs
cpeEtaExpand Int
arity (Id -> CpeRhs
forall b. Id -> Expr b
Var Id
v)) })

        -- Wrap floating ticks
       ; let (Floats
floats4, CpeRhs
rhs4) = Floats -> CpeRhs -> (Floats, CpeRhs)
wrapTicks Floats
floats3 CpeRhs
rhs3

       ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
floats4, CpeRhs
rhs4) }
  where
    arity :: Int
arity = Id -> Int
idArity Id
bndr        -- We must match this arity

    ---------------------
    float_from_rhs :: Floats -> CpeRhs -> UniqSM (Floats, CpeRhs)
float_from_rhs Floats
floats CpeRhs
rhs
      | Floats -> Bool
isEmptyFloats Floats
floats = (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
emptyFloats, CpeRhs
rhs)
      | TopLevelFlag -> Bool
isTopLevel TopLevelFlag
top_lvl   = Floats -> CpeRhs -> UniqSM (Floats, CpeRhs)
float_top    Floats
floats CpeRhs
rhs
      | Bool
otherwise            = Floats -> CpeRhs -> UniqSM (Floats, CpeRhs)
float_nested Floats
floats CpeRhs
rhs

    ---------------------
    float_nested :: Floats -> CpeRhs -> UniqSM (Floats, CpeRhs)
float_nested Floats
floats CpeRhs
rhs
      | RecFlag -> Demand -> Bool -> Floats -> CpeRhs -> Bool
wantFloatNested RecFlag
is_rec Demand
dmd Bool
is_unlifted Floats
floats CpeRhs
rhs
                  = (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
floats, CpeRhs
rhs)
      | Bool
otherwise = Floats -> CpeRhs -> UniqSM (Floats, CpeRhs)
dontFloat Floats
floats CpeRhs
rhs

    ---------------------
    float_top :: Floats -> CpeRhs -> UniqSM (Floats, CpeRhs)
float_top Floats
floats CpeRhs
rhs
      | Floats -> Bool
allLazyTop Floats
floats
      = (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
floats, CpeRhs
rhs)

      | Just (Floats, CpeRhs)
floats <- Floats -> CpeRhs -> Maybe (Floats, CpeRhs)
canFloat Floats
floats CpeRhs
rhs
      = (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats, CpeRhs)
floats

      | Bool
otherwise
      = Floats -> CpeRhs -> UniqSM (Floats, CpeRhs)
dontFloat Floats
floats CpeRhs
rhs

dontFloat :: Floats -> CpeRhs -> UniqSM (Floats, CpeBody)
-- Non-empty floats, but do not want to float from rhs
-- So wrap the rhs in the floats
-- But: rhs1 might have lambdas, and we can't
--      put them inside a wrapBinds
dontFloat :: Floats -> CpeRhs -> UniqSM (Floats, CpeRhs)
dontFloat Floats
floats1 CpeRhs
rhs
  = do { (Floats
floats2, CpeRhs
body) <- CpeRhs -> UniqSM (Floats, CpeRhs)
rhsToBody CpeRhs
rhs
        ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
emptyFloats, Floats -> CpeRhs -> CpeRhs
wrapBinds Floats
floats1 (CpeRhs -> CpeRhs) -> CpeRhs -> CpeRhs
forall a b. (a -> b) -> a -> b
$
                               Floats -> CpeRhs -> CpeRhs
wrapBinds Floats
floats2 CpeRhs
body) }

{- Note [Silly extra arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we had this
        f{arity=1} = \x\y. e
We *must* match the arity on the Id, so we have to generate
        f' = \x\y. e
        f  = \x. f' x

It's a bizarre case: why is the arity on the Id wrong?  Reason
(in the days of __inline_me__):
        f{arity=0} = __inline_me__ (let v = expensive in \xy. e)
When InlineMe notes go away this won't happen any more.  But
it seems good for CorePrep to be robust.
-}

---------------
cpeJoinPair :: CorePrepEnv -> JoinId -> CoreExpr
            -> UniqSM (JoinId, CpeRhs)
-- Used for all join bindings
-- No eta-expansion: see Note [Do not eta-expand join points] in GHC.Core.Opt.Simplify.Utils
cpeJoinPair :: CorePrepEnv -> Id -> CpeRhs -> UniqSM (Id, CpeRhs)
cpeJoinPair CorePrepEnv
env Id
bndr CpeRhs
rhs
  = ASSERT(isJoinId bndr)
    do { let Just Int
join_arity = Id -> Maybe Int
isJoinId_maybe Id
bndr
             ([Id]
bndrs, CpeRhs
body)   = Int -> CpeRhs -> ([Id], CpeRhs)
forall b. Int -> Expr b -> ([b], Expr b)
collectNBinders Int
join_arity CpeRhs
rhs

       ; (CorePrepEnv
env', [Id]
bndrs') <- CorePrepEnv -> [Id] -> UniqSM (CorePrepEnv, [Id])
cpCloneBndrs CorePrepEnv
env [Id]
bndrs

       ; CpeRhs
body' <- CorePrepEnv -> CpeRhs -> UniqSM CpeRhs
cpeBodyNF CorePrepEnv
env' CpeRhs
body -- Will let-bind the body if it starts
                                      -- with a lambda

       ; let rhs' :: CpeRhs
rhs'  = [Id] -> CpeRhs -> CpeRhs
mkCoreLams [Id]
bndrs' CpeRhs
body'
             bndr' :: Id
bndr' = Id
bndr Id -> Unfolding -> Id
`setIdUnfolding` Unfolding
evaldUnfolding
                          Id -> Int -> Id
`setIdArity` (Id -> Bool) -> [Id] -> Int
forall a. (a -> Bool) -> [a] -> Int
count Id -> Bool
isId [Id]
bndrs
                            -- See Note [Arity and join points]

       ; (Id, CpeRhs) -> UniqSM (Id, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Id
bndr', CpeRhs
rhs') }

{-
Note [Arity and join points]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Up to now, we've allowed a join point to have an arity greater than its join
arity (minus type arguments), since this is what's useful for eta expansion.
However, for code gen purposes, its arity must be exactly the number of value
arguments it will be called with, and it must have exactly that many value
lambdas. Hence if there are extra lambdas we must let-bind the body of the RHS:

  join j x y z = \w -> ... in ...
    =>
  join j x y z = (let f = \w -> ... in f) in ...

This is also what happens with Note [Silly extra arguments]. Note that it's okay
for us to mess with the arity because a join point is never exported.
-}

-- ---------------------------------------------------------------------------
--              CpeRhs: produces a result satisfying CpeRhs
-- ---------------------------------------------------------------------------

cpeRhsE :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
-- If
--      e  ===>  (bs, e')
-- then
--      e = let bs in e'        (semantically, that is!)
--
-- For example
--      f (g x)   ===>   ([v = g x], f v)

cpeRhsE :: CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeRhsE CorePrepEnv
_env expr :: CpeRhs
expr@(Type {})      = (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
emptyFloats, CpeRhs
expr)
cpeRhsE CorePrepEnv
_env expr :: CpeRhs
expr@(Coercion {})  = (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
emptyFloats, CpeRhs
expr)
cpeRhsE CorePrepEnv
env (Lit (LitNumber LitNumType
LitNumInteger Integer
i Type
_))
    = CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeRhsE CorePrepEnv
env (Platform -> Id -> Maybe DataCon -> Integer -> CpeRhs
cvtLitInteger (DynFlags -> Platform
targetPlatform (CorePrepEnv -> DynFlags
cpe_dynFlags CorePrepEnv
env)) (CorePrepEnv -> Id
getMkIntegerId CorePrepEnv
env)
                   (CorePrepEnv -> Maybe DataCon
cpe_integerSDataCon CorePrepEnv
env) Integer
i)
cpeRhsE CorePrepEnv
env (Lit (LitNumber LitNumType
LitNumNatural Integer
i Type
_))
    = CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeRhsE CorePrepEnv
env (Platform -> Id -> Maybe DataCon -> Integer -> CpeRhs
cvtLitNatural (DynFlags -> Platform
targetPlatform (CorePrepEnv -> DynFlags
cpe_dynFlags CorePrepEnv
env)) (CorePrepEnv -> Id
getMkNaturalId CorePrepEnv
env)
                   (CorePrepEnv -> Maybe DataCon
cpe_naturalSDataCon CorePrepEnv
env) Integer
i)
cpeRhsE CorePrepEnv
_env expr :: CpeRhs
expr@(Lit {}) = (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
emptyFloats, CpeRhs
expr)
cpeRhsE CorePrepEnv
env expr :: CpeRhs
expr@(Var {})  = CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeApp CorePrepEnv
env CpeRhs
expr
cpeRhsE CorePrepEnv
env expr :: CpeRhs
expr@(App {}) = CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeApp CorePrepEnv
env CpeRhs
expr

cpeRhsE CorePrepEnv
env (Let CoreBind
bind CpeRhs
body)
  = do { (CorePrepEnv
env', Floats
bind_floats, Maybe CoreBind
maybe_bind') <- TopLevelFlag
-> CorePrepEnv
-> CoreBind
-> UniqSM (CorePrepEnv, Floats, Maybe CoreBind)
cpeBind TopLevelFlag
NotTopLevel CorePrepEnv
env CoreBind
bind
       ; (Floats
body_floats, CpeRhs
body') <- CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeRhsE CorePrepEnv
env' CpeRhs
body
       ; let expr' :: CpeRhs
expr' = case Maybe CoreBind
maybe_bind' of Just CoreBind
bind' -> CoreBind -> CpeRhs -> CpeRhs
forall b. Bind b -> Expr b -> Expr b
Let CoreBind
bind' CpeRhs
body'
                                         Maybe CoreBind
Nothing    -> CpeRhs
body'
       ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
bind_floats Floats -> Floats -> Floats
`appendFloats` Floats
body_floats, CpeRhs
expr') }

cpeRhsE CorePrepEnv
env (Tick Tickish Id
tickish CpeRhs
expr)
  | Tickish Id -> TickishPlacement
forall id. Tickish id -> TickishPlacement
tickishPlace Tickish Id
tickish TickishPlacement -> TickishPlacement -> Bool
forall a. Eq a => a -> a -> Bool
External instance of the constraint type Eq TickishPlacement
== TickishPlacement
PlaceNonLam Bool -> Bool -> Bool
&& Tickish Id
tickish Tickish Id -> TickishScoping -> Bool
forall id. Tickish id -> TickishScoping -> Bool
`tickishScopesLike` TickishScoping
SoftScope
  = do { (Floats
floats, CpeRhs
body) <- CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeRhsE CorePrepEnv
env CpeRhs
expr
         -- See [Floating Ticks in CorePrep]
       ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (FloatingBind -> Floats
unitFloat (Tickish Id -> FloatingBind
FloatTick Tickish Id
tickish) Floats -> Floats -> Floats
`appendFloats` Floats
floats, CpeRhs
body) }
  | Bool
otherwise
  = do { CpeRhs
body <- CorePrepEnv -> CpeRhs -> UniqSM CpeRhs
cpeBodyNF CorePrepEnv
env CpeRhs
expr
       ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
emptyFloats, Tickish Id -> CpeRhs -> CpeRhs
mkTick Tickish Id
tickish' CpeRhs
body) }
  where
    tickish' :: Tickish Id
tickish' | Breakpoint Int
n [Id]
fvs <- Tickish Id
tickish
             -- See also 'substTickish'
             = Int -> [Id] -> Tickish Id
forall id. Int -> [id] -> Tickish id
Breakpoint Int
n ((Id -> Id) -> [Id] -> [Id]
forall a b. (a -> b) -> [a] -> [b]
map (HasDebugCallStack => CpeRhs -> Id
CpeRhs -> Id
External instance of the constraint type HasDebugCallStack
getIdFromTrivialExpr (CpeRhs -> Id) -> (Id -> CpeRhs) -> Id -> Id
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CorePrepEnv -> Id -> CpeRhs
lookupCorePrepEnv CorePrepEnv
env) [Id]
fvs)
             | Bool
otherwise
             = Tickish Id
tickish

cpeRhsE CorePrepEnv
env (Cast CpeRhs
expr Coercion
co)
   = do { (Floats
floats, CpeRhs
expr') <- CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeRhsE CorePrepEnv
env CpeRhs
expr
        ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
floats, CpeRhs -> Coercion -> CpeRhs
forall b. Expr b -> Coercion -> Expr b
Cast CpeRhs
expr' Coercion
co) }

cpeRhsE CorePrepEnv
env expr :: CpeRhs
expr@(Lam {})
   = do { let ([Id]
bndrs,CpeRhs
body) = CpeRhs -> ([Id], CpeRhs)
forall b. Expr b -> ([b], Expr b)
collectBinders CpeRhs
expr
        ; (CorePrepEnv
env', [Id]
bndrs') <- CorePrepEnv -> [Id] -> UniqSM (CorePrepEnv, [Id])
cpCloneBndrs CorePrepEnv
env [Id]
bndrs
        ; CpeRhs
body' <- CorePrepEnv -> CpeRhs -> UniqSM CpeRhs
cpeBodyNF CorePrepEnv
env' CpeRhs
body
        ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
emptyFloats, [Id] -> CpeRhs -> CpeRhs
forall b. [b] -> Expr b -> Expr b
mkLams [Id]
bndrs' CpeRhs
body') }

cpeRhsE CorePrepEnv
env (Case CpeRhs
scrut Id
bndr Type
ty [Alt Id]
alts)
  | CpeRhs -> Bool
isUnsafeEqualityProof CpeRhs
scrut
  , [(AltCon
con, [Id]
bs, CpeRhs
rhs)] <- [Alt Id]
alts
  = do { (Floats
floats1, CpeRhs
scrut') <- CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeBody CorePrepEnv
env CpeRhs
scrut
       ; (CorePrepEnv
env1, Id
bndr')     <- CorePrepEnv -> Id -> UniqSM (CorePrepEnv, Id)
cpCloneBndr CorePrepEnv
env Id
bndr
       ; (CorePrepEnv
env2, [Id]
bs')       <- CorePrepEnv -> [Id] -> UniqSM (CorePrepEnv, [Id])
cpCloneBndrs CorePrepEnv
env1 [Id]
bs
       ; (Floats
floats2, CpeRhs
rhs')   <- CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeBody CorePrepEnv
env2 CpeRhs
rhs
       ; let case_float :: FloatingBind
case_float = CpeRhs -> Id -> AltCon -> [Id] -> Bool -> FloatingBind
FloatCase CpeRhs
scrut' Id
bndr' AltCon
con [Id]
bs' Bool
True
             floats' :: Floats
floats'    = (Floats
floats1 Floats -> FloatingBind -> Floats
`addFloat` FloatingBind
case_float)
                          Floats -> Floats -> Floats
`appendFloats` Floats
floats2
       ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
floats', CpeRhs
rhs') }

  | Bool
otherwise
  = do { (Floats
floats, CpeRhs
scrut') <- CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeBody CorePrepEnv
env CpeRhs
scrut
       ; (CorePrepEnv
env', Id
bndr2) <- CorePrepEnv -> Id -> UniqSM (CorePrepEnv, Id)
cpCloneBndr CorePrepEnv
env Id
bndr
       ; let alts' :: [Alt Id]
alts'
                 -- This flag is intended to aid in debugging strictness
                 -- analysis bugs. These are particularly nasty to chase down as
                 -- they may manifest as segmentation faults. When this flag is
                 -- enabled we instead produce an 'error' expression to catch
                 -- the case where a function we think should bottom
                 -- unexpectedly returns.
               | GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_CatchBottoms (CorePrepEnv -> DynFlags
cpe_dynFlags CorePrepEnv
env)
               , Bool -> Bool
not ([Alt Id] -> Bool
forall b. [Alt b] -> Bool
altsAreExhaustive [Alt Id]
alts)
               = [Alt Id] -> Maybe CpeRhs -> [Alt Id]
forall a b. [(AltCon, [a], b)] -> Maybe b -> [(AltCon, [a], b)]
addDefault [Alt Id]
alts (CpeRhs -> Maybe CpeRhs
forall a. a -> Maybe a
Just CpeRhs
err)
               | Bool
otherwise = [Alt Id]
alts
               where err :: CpeRhs
err = Id -> Type -> String -> CpeRhs
mkRuntimeErrorApp Id
rUNTIME_ERROR_ID Type
ty
                                             String
"Bottoming expression returned"
       ; [Alt Id]
alts'' <- (Alt Id -> UniqSM (Alt Id)) -> [Alt Id] -> UniqSM [Alt Id]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
External instance of the constraint type Monad UniqSM
External instance of the constraint type Traversable []
mapM (CorePrepEnv -> Alt Id -> UniqSM (Alt Id)
forall {a}.
CorePrepEnv -> (a, [Id], CpeRhs) -> UniqSM (a, [Id], CpeRhs)
sat_alt CorePrepEnv
env') [Alt Id]
alts'

       ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
floats, CpeRhs -> Id -> Type -> [Alt Id] -> CpeRhs
forall b. Expr b -> b -> Type -> [Alt b] -> Expr b
Case CpeRhs
scrut' Id
bndr2 Type
ty [Alt Id]
alts'') }
  where
    sat_alt :: CorePrepEnv -> (a, [Id], CpeRhs) -> UniqSM (a, [Id], CpeRhs)
sat_alt CorePrepEnv
env (a
con, [Id]
bs, CpeRhs
rhs)
       = do { (CorePrepEnv
env2, [Id]
bs') <- CorePrepEnv -> [Id] -> UniqSM (CorePrepEnv, [Id])
cpCloneBndrs CorePrepEnv
env [Id]
bs
            ; CpeRhs
rhs' <- CorePrepEnv -> CpeRhs -> UniqSM CpeRhs
cpeBodyNF CorePrepEnv
env2 CpeRhs
rhs
            ; (a, [Id], CpeRhs) -> UniqSM (a, [Id], CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (a
con, [Id]
bs', CpeRhs
rhs') }

cvtLitInteger :: Platform -> Id -> Maybe DataCon -> Integer -> CoreExpr
-- Here we convert a literal Integer to the low-level
-- representation. Exactly how we do this depends on the
-- library that implements Integer.  If it's GMP we
-- use the S# data constructor for small literals.
-- See Note [Integer literals] in GHC.Types.Literal
cvtLitInteger :: Platform -> Id -> Maybe DataCon -> Integer -> CpeRhs
cvtLitInteger Platform
platform Id
_ (Just DataCon
sdatacon) Integer
i
  | Platform -> Integer -> Bool
platformInIntRange Platform
platform Integer
i -- Special case for small integers
    = DataCon -> [CpeRhs] -> CpeRhs
forall b. DataCon -> [Arg b] -> Arg b
mkConApp DataCon
sdatacon [Literal -> CpeRhs
forall b. Literal -> Expr b
Lit (Platform -> Integer -> Literal
mkLitInt Platform
platform Integer
i)]

cvtLitInteger Platform
platform Id
mk_integer Maybe DataCon
_ Integer
i
    = CpeRhs -> [CpeRhs] -> CpeRhs
forall b. Expr b -> [Expr b] -> Expr b
mkApps (Id -> CpeRhs
forall b. Id -> Expr b
Var Id
mk_integer) [CpeRhs
forall {b}. Expr b
isNonNegative, CpeRhs
ints]
  where isNonNegative :: Expr b
isNonNegative = if Integer
i Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
External instance of the constraint type Ord Integer
< Integer
0 then DataCon -> [Expr b] -> Expr b
forall b. DataCon -> [Arg b] -> Arg b
mkConApp DataCon
falseDataCon []
                                 else DataCon -> [Expr b] -> Expr b
forall b. DataCon -> [Arg b] -> Arg b
mkConApp DataCon
trueDataCon  []
        ints :: CpeRhs
ints = Type -> [CpeRhs] -> CpeRhs
mkListExpr Type
intTy (Integer -> [CpeRhs]
forall {b}. Integer -> [Expr b]
f (Integer -> Integer
forall a. Num a => a -> a
External instance of the constraint type Num Integer
abs Integer
i))
        f :: Integer -> [Expr b]
f Integer
0 = []
        f Integer
x = let low :: Integer
low  = Integer
x Integer -> Integer -> Integer
forall a. Bits a => a -> a -> a
External instance of the constraint type Bits Integer
.&. Integer
mask
                  high :: Integer
high = Integer
x Integer -> Int -> Integer
forall a. Bits a => a -> Int -> a
External instance of the constraint type Bits Integer
`shiftR` Int
bits
              in DataCon -> [Expr b] -> Expr b
forall b. DataCon -> [Arg b] -> Arg b
mkConApp DataCon
intDataCon [Literal -> Expr b
forall b. Literal -> Expr b
Lit (Platform -> Integer -> Literal
mkLitInt Platform
platform Integer
low)] Expr b -> [Expr b] -> [Expr b]
forall a. a -> [a] -> [a]
: Integer -> [Expr b]
f Integer
high
        bits :: Int
bits = Int
31
        mask :: Integer
mask = Integer
2 Integer -> Int -> Integer
forall a b. (Num a, Integral b) => a -> b -> a
External instance of the constraint type Integral Int
External instance of the constraint type Num Integer
^ Int
bits Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
External instance of the constraint type Num Integer
- Integer
1

cvtLitNatural :: Platform -> Id -> Maybe DataCon -> Integer -> CoreExpr
-- Here we convert a literal Natural to the low-level
-- representation.
-- See Note [Natural literals] in GHC.Types.Literal
cvtLitNatural :: Platform -> Id -> Maybe DataCon -> Integer -> CpeRhs
cvtLitNatural Platform
platform Id
_ (Just DataCon
sdatacon) Integer
i
  | Platform -> Integer -> Bool
platformInWordRange Platform
platform Integer
i -- Special case for small naturals
    = DataCon -> [CpeRhs] -> CpeRhs
forall b. DataCon -> [Arg b] -> Arg b
mkConApp DataCon
sdatacon [Literal -> CpeRhs
forall b. Literal -> Expr b
Lit (Platform -> Integer -> Literal
mkLitWord Platform
platform Integer
i)]

cvtLitNatural Platform
platform Id
mk_natural Maybe DataCon
_ Integer
i
    = CpeRhs -> [CpeRhs] -> CpeRhs
forall b. Expr b -> [Expr b] -> Expr b
mkApps (Id -> CpeRhs
forall b. Id -> Expr b
Var Id
mk_natural) [CpeRhs
words]
  where words :: CpeRhs
words = Type -> [CpeRhs] -> CpeRhs
mkListExpr Type
wordTy (Integer -> [CpeRhs]
forall {b}. Integer -> [Expr b]
f Integer
i)
        f :: Integer -> [Expr b]
f Integer
0 = []
        f Integer
x = let low :: Integer
low  = Integer
x Integer -> Integer -> Integer
forall a. Bits a => a -> a -> a
External instance of the constraint type Bits Integer
.&. Integer
mask
                  high :: Integer
high = Integer
x Integer -> Int -> Integer
forall a. Bits a => a -> Int -> a
External instance of the constraint type Bits Integer
`shiftR` Int
bits
              in DataCon -> [Expr b] -> Expr b
forall b. DataCon -> [Arg b] -> Arg b
mkConApp DataCon
wordDataCon [Literal -> Expr b
forall b. Literal -> Expr b
Lit (Platform -> Integer -> Literal
mkLitWord Platform
platform Integer
low)] Expr b -> [Expr b] -> [Expr b]
forall a. a -> [a] -> [a]
: Integer -> [Expr b]
f Integer
high
        bits :: Int
bits = Int
32
        mask :: Integer
mask = Integer
2 Integer -> Int -> Integer
forall a b. (Num a, Integral b) => a -> b -> a
External instance of the constraint type Integral Int
External instance of the constraint type Num Integer
^ Int
bits Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
External instance of the constraint type Num Integer
- Integer
1

-- ---------------------------------------------------------------------------
--              CpeBody: produces a result satisfying CpeBody
-- ---------------------------------------------------------------------------

-- | Convert a 'CoreExpr' so it satisfies 'CpeBody', without
-- producing any floats (any generated floats are immediately
-- let-bound using 'wrapBinds').  Generally you want this, esp.
-- when you've reached a binding form (e.g., a lambda) and
-- floating any further would be incorrect.
cpeBodyNF :: CorePrepEnv -> CoreExpr -> UniqSM CpeBody
cpeBodyNF :: CorePrepEnv -> CpeRhs -> UniqSM CpeRhs
cpeBodyNF CorePrepEnv
env CpeRhs
expr
  = do { (Floats
floats, CpeRhs
body) <- CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeBody CorePrepEnv
env CpeRhs
expr
       ; CpeRhs -> UniqSM CpeRhs
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats -> CpeRhs -> CpeRhs
wrapBinds Floats
floats CpeRhs
body) }

-- | Convert a 'CoreExpr' so it satisfies 'CpeBody'; also produce
-- a list of 'Floats' which are being propagated upwards.  In
-- fact, this function is used in only two cases: to
-- implement 'cpeBodyNF' (which is what you usually want),
-- and in the case when a let-binding is in a case scrutinee--here,
-- we can always float out:
--
--      case (let x = y in z) of ...
--      ==> let x = y in case z of ...
--
cpeBody :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeBody)
cpeBody :: CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeBody CorePrepEnv
env CpeRhs
expr
  = do { (Floats
floats1, CpeRhs
rhs) <- CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeRhsE CorePrepEnv
env CpeRhs
expr
       ; (Floats
floats2, CpeRhs
body) <- CpeRhs -> UniqSM (Floats, CpeRhs)
rhsToBody CpeRhs
rhs
       ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
floats1 Floats -> Floats -> Floats
`appendFloats` Floats
floats2, CpeRhs
body) }

--------
rhsToBody :: CpeRhs -> UniqSM (Floats, CpeBody)
-- Remove top level lambdas by let-binding

rhsToBody :: CpeRhs -> UniqSM (Floats, CpeRhs)
rhsToBody (Tick Tickish Id
t CpeRhs
expr)
  | Tickish Id -> TickishScoping
forall id. Tickish id -> TickishScoping
tickishScoped Tickish Id
t TickishScoping -> TickishScoping -> Bool
forall a. Eq a => a -> a -> Bool
External instance of the constraint type Eq TickishScoping
== TickishScoping
NoScope  -- only float out of non-scoped annotations
  = do { (Floats
floats, CpeRhs
expr') <- CpeRhs -> UniqSM (Floats, CpeRhs)
rhsToBody CpeRhs
expr
       ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
floats, Tickish Id -> CpeRhs -> CpeRhs
mkTick Tickish Id
t CpeRhs
expr') }

rhsToBody (Cast CpeRhs
e Coercion
co)
        -- You can get things like
        --      case e of { p -> coerce t (\s -> ...) }
  = do { (Floats
floats, CpeRhs
e') <- CpeRhs -> UniqSM (Floats, CpeRhs)
rhsToBody CpeRhs
e
       ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
floats, CpeRhs -> Coercion -> CpeRhs
forall b. Expr b -> Coercion -> Expr b
Cast CpeRhs
e' Coercion
co) }

rhsToBody expr :: CpeRhs
expr@(Lam {})
  | Just CpeRhs
no_lam_result <- [Id] -> CpeRhs -> Maybe CpeRhs
tryEtaReducePrep [Id]
bndrs CpeRhs
body
  = (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
emptyFloats, CpeRhs
no_lam_result)
  | (Id -> Bool) -> [Id] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
External instance of the constraint type Foldable []
all Id -> Bool
isTyVar [Id]
bndrs           -- Type lambdas are ok
  = (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
emptyFloats, CpeRhs
expr)
  | Bool
otherwise                   -- Some value lambdas
  = do { Id
fn <- Type -> UniqSM Id
newVar (CpeRhs -> Type
exprType CpeRhs
expr)
       ; let rhs :: CpeRhs
rhs   = Int -> CpeRhs -> CpeRhs
cpeEtaExpand (CpeRhs -> Int
exprArity CpeRhs
expr) CpeRhs
expr
             float :: FloatingBind
float = CoreBind -> FloatingBind
FloatLet (Id -> CpeRhs -> CoreBind
forall b. b -> Expr b -> Bind b
NonRec Id
fn CpeRhs
rhs)
       ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (FloatingBind -> Floats
unitFloat FloatingBind
float, Id -> CpeRhs
forall b. Id -> Expr b
Var Id
fn) }
  where
    ([Id]
bndrs,CpeRhs
body) = CpeRhs -> ([Id], CpeRhs)
forall b. Expr b -> ([b], Expr b)
collectBinders CpeRhs
expr

rhsToBody CpeRhs
expr = (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
emptyFloats, CpeRhs
expr)



-- ---------------------------------------------------------------------------
--              CpeApp: produces a result satisfying CpeApp
-- ---------------------------------------------------------------------------

data ArgInfo = CpeApp  CoreArg
             | CpeCast Coercion
             | CpeTick (Tickish Id)

{- Note [runRW arg]
~~~~~~~~~~~~~~~~~~~
If we got, say
   runRW# (case bot of {})
which happened in #11291, we do /not/ want to turn it into
   (case bot of {}) realWorldPrimId#
because that gives a panic in CoreToStg.myCollectArgs, which expects
only variables in function position.  But if we are sure to make
runRW# strict (which we do in GHC.Types.Id.Make), this can't happen
-}

cpeApp :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
-- May return a CpeRhs because of saturating primops
cpeApp :: CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeApp CorePrepEnv
top_env CpeRhs
expr
  = do { let (CpeRhs
terminal, [ArgInfo]
args, Int
depth) = CpeRhs -> (CpeRhs, [ArgInfo], Int)
collect_args CpeRhs
expr
       ; CorePrepEnv
-> CpeRhs -> [ArgInfo] -> Int -> UniqSM (Floats, CpeRhs)
cpe_app CorePrepEnv
top_env CpeRhs
terminal [ArgInfo]
args Int
depth
       }

  where
    -- We have a nested data structure of the form
    -- e `App` a1 `App` a2 ... `App` an, convert it into
    -- (e, [CpeApp a1, CpeApp a2, ..., CpeApp an], depth)
    -- We use 'ArgInfo' because we may also need to
    -- record casts and ticks.  Depth counts the number
    -- of arguments that would consume strictness information
    -- (so, no type or coercion arguments.)
    collect_args :: CoreExpr -> (CoreExpr, [ArgInfo], Int)
    collect_args :: CpeRhs -> (CpeRhs, [ArgInfo], Int)
collect_args CpeRhs
e = CpeRhs -> [ArgInfo] -> Int -> (CpeRhs, [ArgInfo], Int)
forall {c}.
Num c =>
CpeRhs -> [ArgInfo] -> c -> (CpeRhs, [ArgInfo], c)
External instance of the constraint type Num Int
go CpeRhs
e [] Int
0
      where
        go :: CpeRhs -> [ArgInfo] -> c -> (CpeRhs, [ArgInfo], c)
go (App CpeRhs
fun CpeRhs
arg)      [ArgInfo]
as !c
depth
            = CpeRhs -> [ArgInfo] -> c -> (CpeRhs, [ArgInfo], c)
go CpeRhs
fun (CpeRhs -> ArgInfo
CpeApp CpeRhs
arg ArgInfo -> [ArgInfo] -> [ArgInfo]
forall a. a -> [a] -> [a]
: [ArgInfo]
as)
                (if CpeRhs -> Bool
forall b. Expr b -> Bool
isTyCoArg CpeRhs
arg then c
depth else c
depth c -> c -> c
forall a. Num a => a -> a -> a
Evidence bound by a type signature of the constraint type Num c
+ c
1)
        go (Cast CpeRhs
fun Coercion
co)      [ArgInfo]
as c
depth
            = CpeRhs -> [ArgInfo] -> c -> (CpeRhs, [ArgInfo], c)
go CpeRhs
fun (Coercion -> ArgInfo
CpeCast Coercion
co ArgInfo -> [ArgInfo] -> [ArgInfo]
forall a. a -> [a] -> [a]
: [ArgInfo]
as) c
depth
        go (Tick Tickish Id
tickish CpeRhs
fun) [ArgInfo]
as c
depth
            | Tickish Id -> TickishPlacement
forall id. Tickish id -> TickishPlacement
tickishPlace Tickish Id
tickish TickishPlacement -> TickishPlacement -> Bool
forall a. Eq a => a -> a -> Bool
External instance of the constraint type Eq TickishPlacement
== TickishPlacement
PlaceNonLam
            Bool -> Bool -> Bool
&& Tickish Id
tickish Tickish Id -> TickishScoping -> Bool
forall id. Tickish id -> TickishScoping -> Bool
`tickishScopesLike` TickishScoping
SoftScope
            = CpeRhs -> [ArgInfo] -> c -> (CpeRhs, [ArgInfo], c)
go CpeRhs
fun (Tickish Id -> ArgInfo
CpeTick Tickish Id
tickish ArgInfo -> [ArgInfo] -> [ArgInfo]
forall a. a -> [a] -> [a]
: [ArgInfo]
as) c
depth
        go CpeRhs
terminal [ArgInfo]
as c
depth = (CpeRhs
terminal, [ArgInfo]
as, c
depth)

    cpe_app :: CorePrepEnv
            -> CoreExpr
            -> [ArgInfo]
            -> Int
            -> UniqSM (Floats, CpeRhs)
    cpe_app :: CorePrepEnv
-> CpeRhs -> [ArgInfo] -> Int -> UniqSM (Floats, CpeRhs)
cpe_app CorePrepEnv
env (Var Id
f) (CpeApp Type{} : CpeApp CpeRhs
arg : [ArgInfo]
args) Int
depth
        | Id
f Id -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
External instance of the constraint type Uniquable Id
`hasKey` Unique
lazyIdKey          -- Replace (lazy a) with a, and
       Bool -> Bool -> Bool
|| Id
f Id -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
External instance of the constraint type Uniquable Id
`hasKey` Unique
noinlineIdKey      -- Replace (noinline a) with a
        -- Consider the code:
        --
        --      lazy (f x) y
        --
        -- We need to make sure that we need to recursively collect arguments on
        -- "f x", otherwise we'll float "f x" out (it's not a variable) and
        -- end up with this awful -ddump-prep:
        --
        --      case f x of f_x {
        --        __DEFAULT -> f_x y
        --      }
        --
        -- rather than the far superior "f x y".  Test case is par01.
        = let (CpeRhs
terminal, [ArgInfo]
args', Int
depth') = CpeRhs -> (CpeRhs, [ArgInfo], Int)
collect_args CpeRhs
arg
          in CorePrepEnv
-> CpeRhs -> [ArgInfo] -> Int -> UniqSM (Floats, CpeRhs)
cpe_app CorePrepEnv
env CpeRhs
terminal ([ArgInfo]
args' [ArgInfo] -> [ArgInfo] -> [ArgInfo]
forall a. [a] -> [a] -> [a]
++ [ArgInfo]
args) (Int
depth Int -> Int -> Int
forall a. Num a => a -> a -> a
External instance of the constraint type Num Int
+ Int
depth' Int -> Int -> Int
forall a. Num a => a -> a -> a
External instance of the constraint type Num Int
- Int
1)
    cpe_app CorePrepEnv
env (Var Id
f) [CpeApp _runtimeRep :: CpeRhs
_runtimeRep@Type{}, CpeApp _type :: CpeRhs
_type@Type{}, CpeApp CpeRhs
arg] Int
1
        | Id
f Id -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
External instance of the constraint type Uniquable Id
`hasKey` Unique
runRWKey
        -- See Note [runRW magic]
        -- Replace (runRW# f) by (f realWorld#), beta reducing if possible (this
        -- is why we return a CorePrepEnv as well)
        = case CpeRhs
arg of
            Lam Id
s CpeRhs
body -> CorePrepEnv
-> CpeRhs -> [ArgInfo] -> Int -> UniqSM (Floats, CpeRhs)
cpe_app (CorePrepEnv -> Id -> Id -> CorePrepEnv
extendCorePrepEnv CorePrepEnv
env Id
s Id
realWorldPrimId) CpeRhs
body [] Int
0
            CpeRhs
_          -> CorePrepEnv
-> CpeRhs -> [ArgInfo] -> Int -> UniqSM (Floats, CpeRhs)
cpe_app CorePrepEnv
env CpeRhs
arg [CpeRhs -> ArgInfo
CpeApp (Id -> CpeRhs
forall b. Id -> Expr b
Var Id
realWorldPrimId)] Int
1
    cpe_app CorePrepEnv
env (Var Id
v) [ArgInfo]
args Int
depth
      = do { Id
v1 <- Id -> UniqSM Id
fiddleCCall Id
v
           ; let e2 :: CpeRhs
e2 = CorePrepEnv -> Id -> CpeRhs
lookupCorePrepEnv CorePrepEnv
env Id
v1
                 hd :: Maybe Id
hd = CpeRhs -> Maybe Id
getIdFromTrivialExpr_maybe CpeRhs
e2
           -- NB: depth from collect_args is right, because e2 is a trivial expression
           -- and thus its embedded Id *must* be at the same depth as any
           -- Apps it is under are type applications only (c.f.
           -- exprIsTrivial).  But note that we need the type of the
           -- expression, not the id.
           ; (CpeRhs
app, Floats
floats) <- [ArgInfo]
-> CpeRhs -> Type -> Floats -> [Demand] -> UniqSM (CpeRhs, Floats)
rebuild_app [ArgInfo]
args CpeRhs
e2 (CpeRhs -> Type
exprType CpeRhs
e2) Floats
emptyFloats [Demand]
stricts
           ; Maybe Id -> CpeRhs -> Floats -> Int -> UniqSM (Floats, CpeRhs)
forall {a}. Maybe Id -> CpeRhs -> a -> Int -> UniqSM (a, CpeRhs)
mb_saturate Maybe Id
hd CpeRhs
app Floats
floats Int
depth }
        where
          stricts :: [Demand]
stricts = case Id -> StrictSig
idStrictness Id
v of
                            StrictSig (DmdType DmdEnv
_ [Demand]
demands Divergence
_)
                              | [Demand] -> Int -> Ordering
forall a. [a] -> Int -> Ordering
listLengthCmp [Demand]
demands Int
depth Ordering -> Ordering -> Bool
forall a. Eq a => a -> a -> Bool
External instance of the constraint type Eq Ordering
/= Ordering
GT -> [Demand]
demands
                                    -- length demands <= depth
                              | Bool
otherwise                         -> []
                -- If depth < length demands, then we have too few args to
                -- satisfy strictness  info so we have to  ignore all the
                -- strictness info, e.g. + (error "urk")
                -- Here, we can't evaluate the arg strictly, because this
                -- partial application might be seq'd

        -- We inlined into something that's not a var and has no args.
        -- Bounce it back up to cpeRhsE.
    cpe_app CorePrepEnv
env CpeRhs
fun [] Int
_ = CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeRhsE CorePrepEnv
env CpeRhs
fun

        -- N-variable fun, better let-bind it
    cpe_app CorePrepEnv
env CpeRhs
fun [ArgInfo]
args Int
depth
      = do { (Floats
fun_floats, CpeRhs
fun') <- CorePrepEnv -> Demand -> CpeRhs -> Type -> UniqSM (Floats, CpeRhs)
cpeArg CorePrepEnv
env Demand
evalDmd CpeRhs
fun Type
ty
                          -- The evalDmd says that it's sure to be evaluated,
                          -- so we'll end up case-binding it
           ; (CpeRhs
app, Floats
floats) <- [ArgInfo]
-> CpeRhs -> Type -> Floats -> [Demand] -> UniqSM (CpeRhs, Floats)
rebuild_app [ArgInfo]
args CpeRhs
fun' Type
ty Floats
fun_floats []
           ; Maybe Id -> CpeRhs -> Floats -> Int -> UniqSM (Floats, CpeRhs)
forall {a}. Maybe Id -> CpeRhs -> a -> Int -> UniqSM (a, CpeRhs)
mb_saturate Maybe Id
forall a. Maybe a
Nothing CpeRhs
app Floats
floats Int
depth }
        where
          ty :: Type
ty = CpeRhs -> Type
exprType CpeRhs
fun

    -- Saturate if necessary
    mb_saturate :: Maybe Id -> CpeRhs -> a -> Int -> UniqSM (a, CpeRhs)
mb_saturate Maybe Id
head CpeRhs
app a
floats Int
depth =
       case Maybe Id
head of
         Just Id
fn_id -> do { CpeRhs
sat_app <- Id -> CpeRhs -> Int -> UniqSM CpeRhs
maybeSaturate Id
fn_id CpeRhs
app Int
depth
                          ; (a, CpeRhs) -> UniqSM (a, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (a
floats, CpeRhs
sat_app) }
         Maybe Id
_other              -> (a, CpeRhs) -> UniqSM (a, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (a
floats, CpeRhs
app)

    -- Deconstruct and rebuild the application, floating any non-atomic
    -- arguments to the outside.  We collect the type of the expression,
    -- the head of the application, and the number of actual value arguments,
    -- all of which are used to possibly saturate this application if it
    -- has a constructor or primop at the head.
    rebuild_app
        :: [ArgInfo]                  -- The arguments (inner to outer)
        -> CpeApp
        -> Type
        -> Floats
        -> [Demand]
        -> UniqSM (CpeApp, Floats)
    rebuild_app :: [ArgInfo]
-> CpeRhs -> Type -> Floats -> [Demand] -> UniqSM (CpeRhs, Floats)
rebuild_app [] CpeRhs
app Type
_ Floats
floats [Demand]
ss = do
      MASSERT(null ss) -- make sure we used all the strictness info
      (CpeRhs, Floats) -> UniqSM (CpeRhs, Floats)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (CpeRhs
app, Floats
floats)
    rebuild_app (ArgInfo
a : [ArgInfo]
as) CpeRhs
fun' Type
fun_ty Floats
floats [Demand]
ss = case ArgInfo
a of
      CpeApp arg :: CpeRhs
arg@(Type Type
arg_ty) ->
        [ArgInfo]
-> CpeRhs -> Type -> Floats -> [Demand] -> UniqSM (CpeRhs, Floats)
rebuild_app [ArgInfo]
as (CpeRhs -> CpeRhs -> CpeRhs
forall b. Expr b -> Expr b -> Expr b
App CpeRhs
fun' CpeRhs
arg) (HasDebugCallStack => Type -> Type -> Type
Type -> Type -> Type
External instance of the constraint type HasDebugCallStack
piResultTy Type
fun_ty Type
arg_ty) Floats
floats [Demand]
ss
      CpeApp arg :: CpeRhs
arg@(Coercion {}) ->
        [ArgInfo]
-> CpeRhs -> Type -> Floats -> [Demand] -> UniqSM (CpeRhs, Floats)
rebuild_app [ArgInfo]
as (CpeRhs -> CpeRhs -> CpeRhs
forall b. Expr b -> Expr b -> Expr b
App CpeRhs
fun' CpeRhs
arg) (Type -> Type
funResultTy Type
fun_ty) Floats
floats [Demand]
ss
      CpeApp CpeRhs
arg -> do
        let (Demand
ss1, [Demand]
ss_rest)  -- See Note [lazyId magic] in GHC.Types.Id.Make
               = case ([Demand]
ss, CpeRhs -> Bool
isLazyExpr CpeRhs
arg) of
                   (Demand
_   : [Demand]
ss_rest, Bool
True)  -> (Demand
topDmd, [Demand]
ss_rest)
                   (Demand
ss1 : [Demand]
ss_rest, Bool
False) -> (Demand
ss1,    [Demand]
ss_rest)
                   ([],            Bool
_)     -> (Demand
topDmd, [])
            (Type
arg_ty, Type
res_ty) =
              case Type -> Maybe (Type, Type)
splitFunTy_maybe Type
fun_ty of
                Just (Type, Type)
as -> (Type, Type)
as
                Maybe (Type, Type)
Nothing -> String -> SDoc -> (Type, Type)
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"cpeBody" (Type -> SDoc
forall a. Outputable a => a -> SDoc
External instance of the constraint type Outputable Type
ppr Type
fun_ty SDoc -> SDoc -> SDoc
$$ CpeRhs -> SDoc
forall a. Outputable a => a -> SDoc
External instance of the constraint type forall b. OutputableBndr b => Outputable (Expr b)
External instance of the constraint type OutputableBndr Id
ppr CpeRhs
expr)
        (Floats
fs, CpeRhs
arg') <- CorePrepEnv -> Demand -> CpeRhs -> Type -> UniqSM (Floats, CpeRhs)
cpeArg CorePrepEnv
top_env Demand
ss1 CpeRhs
arg Type
arg_ty
        [ArgInfo]
-> CpeRhs -> Type -> Floats -> [Demand] -> UniqSM (CpeRhs, Floats)
rebuild_app [ArgInfo]
as (CpeRhs -> CpeRhs -> CpeRhs
forall b. Expr b -> Expr b -> Expr b
App CpeRhs
fun' CpeRhs
arg') Type
res_ty (Floats
fs Floats -> Floats -> Floats
`appendFloats` Floats
floats) [Demand]
ss_rest
      CpeCast Coercion
co ->
        let ty2 :: Type
ty2 = Coercion -> Type
coercionRKind Coercion
co
        in [ArgInfo]
-> CpeRhs -> Type -> Floats -> [Demand] -> UniqSM (CpeRhs, Floats)
rebuild_app [ArgInfo]
as (CpeRhs -> Coercion -> CpeRhs
forall b. Expr b -> Coercion -> Expr b
Cast CpeRhs
fun' Coercion
co) Type
ty2 Floats
floats [Demand]
ss
      CpeTick Tickish Id
tickish ->
        -- See [Floating Ticks in CorePrep]
        [ArgInfo]
-> CpeRhs -> Type -> Floats -> [Demand] -> UniqSM (CpeRhs, Floats)
rebuild_app [ArgInfo]
as CpeRhs
fun' Type
fun_ty (Floats -> FloatingBind -> Floats
addFloat Floats
floats (Tickish Id -> FloatingBind
FloatTick Tickish Id
tickish)) [Demand]
ss

isLazyExpr :: CoreExpr -> Bool
-- See Note [lazyId magic] in GHC.Types.Id.Make
isLazyExpr :: CpeRhs -> Bool
isLazyExpr (Cast CpeRhs
e Coercion
_)              = CpeRhs -> Bool
isLazyExpr CpeRhs
e
isLazyExpr (Tick Tickish Id
_ CpeRhs
e)              = CpeRhs -> Bool
isLazyExpr CpeRhs
e
isLazyExpr (Var Id
f `App` CpeRhs
_ `App` CpeRhs
_) = Id
f Id -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
External instance of the constraint type Uniquable Id
`hasKey` Unique
lazyIdKey
isLazyExpr CpeRhs
_                       = Bool
False

{- Note [runRW magic]
~~~~~~~~~~~~~~~~~~~~~
Some definitions, for instance @runST@, must have careful control over float out
of the bindings in their body. Consider this use of @runST@,

    f x = runST ( \ s -> let (a, s')  = newArray# 100 [] s
                             (_, s'') = fill_in_array_or_something a x s'
                         in freezeArray# a s'' )

If we inline @runST@, we'll get:

    f x = let (a, s')  = newArray# 100 [] realWorld#{-NB-}
              (_, s'') = fill_in_array_or_something a x s'
          in freezeArray# a s''

And now if we allow the @newArray#@ binding to float out to become a CAF,
we end up with a result that is totally and utterly wrong:

    f = let (a, s')  = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
        in \ x ->
            let (_, s'') = fill_in_array_or_something a x s'
            in freezeArray# a s''

All calls to @f@ will share a {\em single} array! Clearly this is nonsense and
must be prevented.

This is what @runRW#@ gives us: by being inlined extremely late in the
optimization (right before lowering to STG, in CorePrep), we can ensure that
no further floating will occur. This allows us to safely inline things like
@runST@, which are otherwise needlessly expensive (see #10678 and #5916).

'runRW' is defined (for historical reasons) in GHC.Magic, with a NOINLINE
pragma.  It is levity-polymorphic.

    runRW# :: forall (r1 :: RuntimeRep). (o :: TYPE r)
           => (State# RealWorld -> (# State# RealWorld, o #))
                              -> (# State# RealWorld, o #)

It needs no special treatment in GHC except this special inlining here
in CorePrep (and in GHC.CoreToByteCode).

-- ---------------------------------------------------------------------------
--      CpeArg: produces a result satisfying CpeArg
-- ---------------------------------------------------------------------------

Note [ANF-ising literal string arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Consider a program like,

    data Foo = Foo Addr#

    foo = Foo "turtle"#

When we go to ANFise this we might think that we want to float the string
literal like we do any other non-trivial argument. This would look like,

    foo = u\ [] case "turtle"# of s { __DEFAULT__ -> Foo s }

However, this 1) isn't necessary since strings are in a sense "trivial"; and 2)
wreaks havoc on the CAF annotations that we produce here since we the result
above is caffy since it is updateable. Ideally at some point in the future we
would like to just float the literal to the top level as suggested in #11312,

    s = "turtle"#
    foo = Foo s

However, until then we simply add a special case excluding literals from the
floating done by cpeArg.
-}

-- | Is an argument okay to CPE?
okCpeArg :: CoreExpr -> Bool
-- Don't float literals. See Note [ANF-ising literal string arguments].
okCpeArg :: CpeRhs -> Bool
okCpeArg (Lit Literal
_) = Bool
False
-- Do not eta expand a trivial argument
okCpeArg CpeRhs
expr    = Bool -> Bool
not (CpeRhs -> Bool
cpExprIsTrivial CpeRhs
expr)

cpExprIsTrivial :: CoreExpr -> Bool
cpExprIsTrivial :: CpeRhs -> Bool
cpExprIsTrivial CpeRhs
e
  | Tick Tickish Id
t CpeRhs
e <- CpeRhs
e
  , Bool -> Bool
not (Tickish Id -> Bool
forall id. Tickish id -> Bool
tickishIsCode Tickish Id
t)
  = CpeRhs -> Bool
cpExprIsTrivial CpeRhs
e
  | Case CpeRhs
scrut Id
_ Type
_ [Alt Id]
alts <- CpeRhs
e
  , CpeRhs -> Bool
isUnsafeEqualityProof CpeRhs
scrut
  , [(AltCon
_,[Id]
_,CpeRhs
rhs)] <- [Alt Id]
alts
  = CpeRhs -> Bool
cpExprIsTrivial CpeRhs
rhs
  | Bool
otherwise
  = CpeRhs -> Bool
exprIsTrivial CpeRhs
e

isUnsafeEqualityProof :: CoreExpr -> Bool
-- See (U3) and (U4) in
-- Note [Implementing unsafeCoerce] in base:Unsafe.Coerce
isUnsafeEqualityProof :: CpeRhs -> Bool
isUnsafeEqualityProof CpeRhs
e
  | Var Id
v `App` Type Type
_ `App` Type Type
_ `App` Type Type
_ <- CpeRhs
e
  = Id -> Name
idName Id
v Name -> Name -> Bool
forall a. Eq a => a -> a -> Bool
External instance of the constraint type Eq Name
== Name
unsafeEqualityProofName
  | Bool
otherwise
  = Bool
False

-- This is where we arrange that a non-trivial argument is let-bound
cpeArg :: CorePrepEnv -> Demand
       -> CoreArg -> Type -> UniqSM (Floats, CpeArg)
cpeArg :: CorePrepEnv -> Demand -> CpeRhs -> Type -> UniqSM (Floats, CpeRhs)
cpeArg CorePrepEnv
env Demand
dmd CpeRhs
arg Type
arg_ty
  = do { (Floats
floats1, CpeRhs
arg1) <- CorePrepEnv -> CpeRhs -> UniqSM (Floats, CpeRhs)
cpeRhsE CorePrepEnv
env CpeRhs
arg     -- arg1 can be a lambda
       ; (Floats
floats2, CpeRhs
arg2) <- if Floats -> CpeRhs -> Bool
want_float Floats
floats1 CpeRhs
arg1
                            then (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
floats1, CpeRhs
arg1)
                            else Floats -> CpeRhs -> UniqSM (Floats, CpeRhs)
dontFloat Floats
floats1 CpeRhs
arg1
                -- Else case: arg1 might have lambdas, and we can't
                --            put them inside a wrapBinds

       ; if CpeRhs -> Bool
okCpeArg CpeRhs
arg2
         then do { Id
v <- Type -> UniqSM Id
newVar Type
arg_ty
                 ; let arg3 :: CpeRhs
arg3      = Int -> CpeRhs -> CpeRhs
cpeEtaExpand (CpeRhs -> Int
exprArity CpeRhs
arg2) CpeRhs
arg2
                       arg_float :: FloatingBind
arg_float = Demand -> Bool -> Id -> CpeRhs -> FloatingBind
mkFloat Demand
dmd Bool
is_unlifted Id
v CpeRhs
arg3
                 ; (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats -> FloatingBind -> Floats
addFloat Floats
floats2 FloatingBind
arg_float, Id -> CpeRhs
forall b. Id -> Expr b
varToCoreExpr Id
v) }
         else (Floats, CpeRhs) -> UniqSM (Floats, CpeRhs)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (Floats
floats2, CpeRhs
arg2)
       }
  where
    is_unlifted :: Bool
is_unlifted = HasDebugCallStack => Type -> Bool
Type -> Bool
External instance of the constraint type HasDebugCallStack
isUnliftedType Type
arg_ty
    want_float :: Floats -> CpeRhs -> Bool
want_float  = RecFlag -> Demand -> Bool -> Floats -> CpeRhs -> Bool
wantFloatNested RecFlag
NonRecursive Demand
dmd Bool
is_unlifted

{-
Note [Floating unlifted arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider    C (let v* = expensive in v)

where the "*" indicates "will be demanded".  Usually v will have been
inlined by now, but let's suppose it hasn't (see #2756).  Then we
do *not* want to get

     let v* = expensive in C v

because that has different strictness.  Hence the use of 'allLazy'.
(NB: the let v* turns into a FloatCase, in mkLocalNonRec.)


------------------------------------------------------------------------------
-- Building the saturated syntax
-- ---------------------------------------------------------------------------

Note [Eta expansion of hasNoBinding things in CorePrep]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
maybeSaturate deals with eta expanding to saturate things that can't deal with
unsaturated applications (identified by 'hasNoBinding', currently just
foreign calls and unboxed tuple/sum constructors).

Note that eta expansion in CorePrep is very fragile due to the "prediction" of
CAFfyness made during tidying (see Note [CAFfyness inconsistencies due to eta
expansion in CorePrep] in GHC.Iface.Tidy for details.  We previously saturated primop
applications here as well but due to this fragility (see #16846) we now deal
with this another way, as described in Note [Primop wrappers] in GHC.Builtin.PrimOps.

It's quite likely that eta expansion of constructor applications will
eventually break in a similar way to how primops did. We really should
eliminate this case as well.
-}

maybeSaturate :: Id -> CpeApp -> Int -> UniqSM CpeRhs
maybeSaturate :: Id -> CpeRhs -> Int -> UniqSM CpeRhs
maybeSaturate Id
fn CpeRhs
expr Int
n_args
  | Id -> Bool
hasNoBinding Id
fn        -- There's no binding
  = CpeRhs -> UniqSM CpeRhs
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return CpeRhs
sat_expr

  | Bool
otherwise
  = CpeRhs -> UniqSM CpeRhs
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return CpeRhs
expr
  where
    fn_arity :: Int
fn_arity     = Id -> Int
idArity Id
fn
    excess_arity :: Int
excess_arity = Int
fn_arity Int -> Int -> Int
forall a. Num a => a -> a -> a
External instance of the constraint type Num Int
- Int
n_args
    sat_expr :: CpeRhs
sat_expr     = Int -> CpeRhs -> CpeRhs
cpeEtaExpand Int
excess_arity CpeRhs
expr

{-
************************************************************************
*                                                                      *
                Simple GHC.Core operations
*                                                                      *
************************************************************************
-}

{-
-- -----------------------------------------------------------------------------
--      Eta reduction
-- -----------------------------------------------------------------------------

Note [Eta expansion]
~~~~~~~~~~~~~~~~~~~~~
Eta expand to match the arity claimed by the binder Remember,
CorePrep must not change arity

Eta expansion might not have happened already, because it is done by
the simplifier only when there at least one lambda already.

NB1:we could refrain when the RHS is trivial (which can happen
    for exported things).  This would reduce the amount of code
    generated (a little) and make things a little words for
    code compiled without -O.  The case in point is data constructor
    wrappers.

NB2: we have to be careful that the result of etaExpand doesn't
   invalidate any of the assumptions that CorePrep is attempting
   to establish.  One possible cause is eta expanding inside of
   an SCC note - we're now careful in etaExpand to make sure the
   SCC is pushed inside any new lambdas that are generated.

Note [Eta expansion and the CorePrep invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It turns out to be much much easier to do eta expansion
*after* the main CorePrep stuff.  But that places constraints
on the eta expander: given a CpeRhs, it must return a CpeRhs.

For example here is what we do not want:
                f = /\a -> g (h 3)      -- h has arity 2
After ANFing we get
                f = /\a -> let s = h 3 in g s
and now we do NOT want eta expansion to give
                f = /\a -> \ y -> (let s = h 3 in g s) y

Instead GHC.Core.Opt.Arity.etaExpand gives
                f = /\a -> \y -> let s = h 3 in g s y

-}

cpeEtaExpand :: Arity -> CpeRhs -> CpeRhs
cpeEtaExpand :: Int -> CpeRhs -> CpeRhs
cpeEtaExpand Int
arity CpeRhs
expr
  | Int
arity Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
External instance of the constraint type Eq Int
== Int
0 = CpeRhs
expr
  | Bool
otherwise  = Int -> CpeRhs -> CpeRhs
etaExpand Int
arity CpeRhs
expr

{-
-- -----------------------------------------------------------------------------
--      Eta reduction
-- -----------------------------------------------------------------------------

Why try eta reduction?  Hasn't the simplifier already done eta?
But the simplifier only eta reduces if that leaves something
trivial (like f, or f Int).  But for deLam it would be enough to
get to a partial application:
        case x of { p -> \xs. map f xs }
    ==> case x of { p -> map f }
-}

-- When updating this function, make sure it lines up with
-- GHC.Core.Utils.tryEtaReduce!
tryEtaReducePrep :: [CoreBndr] -> CoreExpr -> Maybe CoreExpr
tryEtaReducePrep :: [Id] -> CpeRhs -> Maybe CpeRhs
tryEtaReducePrep [Id]
bndrs expr :: CpeRhs
expr@(App CpeRhs
_ CpeRhs
_)
  | CpeRhs -> Bool
forall b. Expr b -> Bool
ok_to_eta_reduce CpeRhs
f
  , Int
n_remaining Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
External instance of the constraint type Ord Int
>= Int
0
  , [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
External instance of the constraint type Foldable []
and ((Id -> CpeRhs -> Bool) -> [Id] -> [CpeRhs] -> [Bool]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Id -> CpeRhs -> Bool
forall {b}. Id -> Expr b -> Bool
ok [Id]
bndrs [CpeRhs]
last_args)
  , Bool -> Bool
not ((Id -> Bool) -> [Id] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
External instance of the constraint type Foldable []
any (Id -> VarSet -> Bool
`elemVarSet` VarSet
fvs_remaining) [Id]
bndrs)
  , CpeRhs -> Bool
exprIsHNF CpeRhs
remaining_expr   -- Don't turn value into a non-value
                               -- else the behaviour with 'seq' changes
  = CpeRhs -> Maybe CpeRhs
forall a. a -> Maybe a
Just CpeRhs
remaining_expr
  where
    (CpeRhs
f, [CpeRhs]
args) = CpeRhs -> (CpeRhs, [CpeRhs])
forall b. Expr b -> (Expr b, [Expr b])
collectArgs CpeRhs
expr
    remaining_expr :: CpeRhs
remaining_expr = CpeRhs -> [CpeRhs] -> CpeRhs
forall b. Expr b -> [Expr b] -> Expr b
mkApps CpeRhs
f [CpeRhs]
remaining_args
    fvs_remaining :: VarSet
fvs_remaining = CpeRhs -> VarSet
exprFreeVars CpeRhs
remaining_expr
    ([CpeRhs]
remaining_args, [CpeRhs]
last_args) = Int -> [CpeRhs] -> ([CpeRhs], [CpeRhs])
forall a. Int -> [a] -> ([a], [a])
splitAt Int
n_remaining [CpeRhs]
args
    n_remaining :: Int
n_remaining = [CpeRhs] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
External instance of the constraint type Foldable []
length [CpeRhs]
args Int -> Int -> Int
forall a. Num a => a -> a -> a
External instance of the constraint type Num Int
- [Id] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
External instance of the constraint type Foldable []
length [Id]
bndrs

    ok :: Id -> Expr b -> Bool
ok Id
bndr (Var Id
arg) = Id
bndr Id -> Id -> Bool
forall a. Eq a => a -> a -> Bool
External instance of the constraint type Eq Id
== Id
arg
    ok Id
_    Expr b
_         = Bool
False

    -- We can't eta reduce something which must be saturated.
    ok_to_eta_reduce :: Expr b -> Bool
ok_to_eta_reduce (Var Id
f) = Bool -> Bool
not (Id -> Bool
hasNoBinding Id
f)
    ok_to_eta_reduce Expr b
_       = Bool
False -- Safe. ToDo: generalise


tryEtaReducePrep [Id]
bndrs (Tick Tickish Id
tickish CpeRhs
e)
  | Tickish Id -> Bool
forall id. Tickish id -> Bool
tickishFloatable Tickish Id
tickish
  = (CpeRhs -> CpeRhs) -> Maybe CpeRhs -> Maybe CpeRhs
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
External instance of the constraint type Functor Maybe
fmap (Tickish Id -> CpeRhs -> CpeRhs
mkTick Tickish Id
tickish) (Maybe CpeRhs -> Maybe CpeRhs) -> Maybe CpeRhs -> Maybe CpeRhs
forall a b. (a -> b) -> a -> b
$ [Id] -> CpeRhs -> Maybe CpeRhs
tryEtaReducePrep [Id]
bndrs CpeRhs
e

tryEtaReducePrep [Id]
_ CpeRhs
_ = Maybe CpeRhs
forall a. Maybe a
Nothing

{-
************************************************************************
*                                                                      *
                Floats
*                                                                      *
************************************************************************

Note [Pin demand info on floats]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We pin demand info on floated lets, so that we can see the one-shot thunks.
-}

data FloatingBind
  = FloatLet CoreBind    -- Rhs of bindings are CpeRhss
                         -- They are always of lifted type;
                         -- unlifted ones are done with FloatCase

 | FloatCase
      CpeBody         -- Always ok-for-speculation
      Id              -- Case binder
      AltCon [Var]    -- Single alternative
      Bool            -- Ok-for-speculation; False of a strict,
                      -- but lifted binding

 -- | See Note [Floating Ticks in CorePrep]
 | FloatTick (Tickish Id)

data Floats = Floats OkToSpec (OrdList FloatingBind)

instance Outputable FloatingBind where
  ppr :: FloatingBind -> SDoc
ppr (FloatLet CoreBind
b) = CoreBind -> SDoc
forall a. Outputable a => a -> SDoc
External instance of the constraint type forall b. OutputableBndr b => Outputable (Bind b)
External instance of the constraint type OutputableBndr Id
ppr CoreBind
b
  ppr (FloatCase CpeRhs
r Id
b AltCon
k [Id]
bs Bool
ok) = String -> SDoc
text String
"case" SDoc -> SDoc -> SDoc
<> SDoc -> SDoc
braces (Bool -> SDoc
forall a. Outputable a => a -> SDoc
External instance of the constraint type Outputable Bool
ppr Bool
ok) SDoc -> SDoc -> SDoc
<+> CpeRhs -> SDoc
forall a. Outputable a => a -> SDoc
External instance of the constraint type forall b. OutputableBndr b => Outputable (Expr b)
External instance of the constraint type OutputableBndr Id
ppr CpeRhs
r
                                SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
"of"SDoc -> SDoc -> SDoc
<+> Id -> SDoc
forall a. Outputable a => a -> SDoc
External instance of the constraint type Outputable Id
ppr Id
b SDoc -> SDoc -> SDoc
<> String -> SDoc
text String
"@"
                                SDoc -> SDoc -> SDoc
<> case [Id]
bs of
                                   [] -> AltCon -> SDoc
forall a. Outputable a => a -> SDoc
External instance of the constraint type Outputable AltCon
ppr AltCon
k
                                   [Id]
_  -> SDoc -> SDoc
parens (AltCon -> SDoc
forall a. Outputable a => a -> SDoc
External instance of the constraint type Outputable AltCon
ppr AltCon
k SDoc -> SDoc -> SDoc
<+> [Id] -> SDoc
forall a. Outputable a => a -> SDoc
External instance of the constraint type forall a. Outputable a => Outputable [a]
External instance of the constraint type Outputable Id
ppr [Id]
bs)
  ppr (FloatTick Tickish Id
t) = Tickish Id -> SDoc
forall a. Outputable a => a -> SDoc
External instance of the constraint type forall id. Outputable id => Outputable (Tickish id)
External instance of the constraint type Outputable Id
ppr Tickish Id
t

instance Outputable Floats where
  ppr :: Floats -> SDoc
ppr (Floats OkToSpec
flag OrdList FloatingBind
fs) = String -> SDoc
text String
"Floats" SDoc -> SDoc -> SDoc
<> SDoc -> SDoc
brackets (OkToSpec -> SDoc
forall a. Outputable a => a -> SDoc
Instance of class: Outputable of the constraint type Outputable OkToSpec
ppr OkToSpec
flag) SDoc -> SDoc -> SDoc
<+>
                         SDoc -> SDoc
braces ([SDoc] -> SDoc
vcat ((FloatingBind -> SDoc) -> [FloatingBind] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map FloatingBind -> SDoc
forall a. Outputable a => a -> SDoc
Instance of class: Outputable of the constraint type Outputable FloatingBind
ppr (OrdList FloatingBind -> [FloatingBind]
forall a. OrdList a -> [a]
fromOL OrdList FloatingBind
fs)))

instance Outputable OkToSpec where
  ppr :: OkToSpec -> SDoc
ppr OkToSpec
OkToSpec    = String -> SDoc
text String
"OkToSpec"
  ppr OkToSpec
IfUnboxedOk = String -> SDoc
text String
"IfUnboxedOk"
  ppr OkToSpec
NotOkToSpec = String -> SDoc
text String
"NotOkToSpec"

-- Can we float these binds out of the rhs of a let?  We cache this decision
-- to avoid having to recompute it in a non-linear way when there are
-- deeply nested lets.
data OkToSpec
   = OkToSpec           -- Lazy bindings of lifted type
   | IfUnboxedOk        -- A mixture of lazy lifted bindings and n
                        -- ok-to-speculate unlifted bindings
   | NotOkToSpec        -- Some not-ok-to-speculate unlifted bindings

mkFloat :: Demand -> Bool -> Id -> CpeRhs -> FloatingBind
mkFloat :: Demand -> Bool -> Id -> CpeRhs -> FloatingBind
mkFloat Demand
dmd Bool
is_unlifted Id
bndr CpeRhs
rhs
  | Bool
is_strict
  , Bool -> Bool
not Bool
is_hnf  = CpeRhs -> Id -> AltCon -> [Id] -> Bool -> FloatingBind
FloatCase CpeRhs
rhs Id
bndr AltCon
DEFAULT [] (CpeRhs -> Bool
exprOkForSpeculation CpeRhs
rhs)
    -- Don't make a case for a HNF binding, even if it's strict
    -- Otherwise we get  case (\x -> e) of ...!

  | Bool
is_unlifted = ASSERT2( exprOkForSpeculation rhs, ppr rhs )
                  CpeRhs -> Id -> AltCon -> [Id] -> Bool -> FloatingBind
FloatCase CpeRhs
rhs Id
bndr AltCon
DEFAULT [] Bool
True
  | Bool
is_hnf    = CoreBind -> FloatingBind
FloatLet (Id -> CpeRhs -> CoreBind
forall b. b -> Expr b -> Bind b
NonRec Id
bndr                       CpeRhs
rhs)
  | Bool
otherwise = CoreBind -> FloatingBind
FloatLet (Id -> CpeRhs -> CoreBind
forall b. b -> Expr b -> Bind b
NonRec (Id -> Demand -> Id
setIdDemandInfo Id
bndr Demand
dmd) CpeRhs
rhs)
                   -- See Note [Pin demand info on floats]
  where
    is_hnf :: Bool
is_hnf    = CpeRhs -> Bool
exprIsHNF CpeRhs
rhs
    is_strict :: Bool
is_strict = Demand -> Bool
forall s u. JointDmd (Str s) (Use u) -> Bool
isStrictDmd Demand
dmd

emptyFloats :: Floats
emptyFloats :: Floats
emptyFloats = OkToSpec -> OrdList FloatingBind -> Floats
Floats OkToSpec
OkToSpec OrdList FloatingBind
forall a. OrdList a
nilOL

isEmptyFloats :: Floats -> Bool
isEmptyFloats :: Floats -> Bool
isEmptyFloats (Floats OkToSpec
_ OrdList FloatingBind
bs) = OrdList FloatingBind -> Bool
forall a. OrdList a -> Bool
isNilOL OrdList FloatingBind
bs

wrapBinds :: Floats -> CpeBody -> CpeBody
wrapBinds :: Floats -> CpeRhs -> CpeRhs
wrapBinds (Floats OkToSpec
_ OrdList FloatingBind
binds) CpeRhs
body
  = (FloatingBind -> CpeRhs -> CpeRhs)
-> CpeRhs -> OrdList FloatingBind -> CpeRhs
forall a b. (a -> b -> b) -> b -> OrdList a -> b
foldrOL FloatingBind -> CpeRhs -> CpeRhs
mk_bind CpeRhs
body OrdList FloatingBind
binds
  where
    mk_bind :: FloatingBind -> CpeRhs -> CpeRhs
mk_bind (FloatCase CpeRhs
rhs Id
bndr AltCon
con [Id]
bs Bool
_) CpeRhs
body = CpeRhs -> Id -> Type -> [Alt Id] -> CpeRhs
forall b. Expr b -> b -> Type -> [Alt b] -> Expr b
Case CpeRhs
rhs Id
bndr (CpeRhs -> Type
exprType CpeRhs
body) [(AltCon
con,[Id]
bs,CpeRhs
body)]
    mk_bind (FloatLet CoreBind
bind)               CpeRhs
body = CoreBind -> CpeRhs -> CpeRhs
forall b. Bind b -> Expr b -> Expr b
Let CoreBind
bind CpeRhs
body
    mk_bind (FloatTick Tickish Id
tickish)           CpeRhs
body = Tickish Id -> CpeRhs -> CpeRhs
mkTick Tickish Id
tickish CpeRhs
body

addFloat :: Floats -> FloatingBind -> Floats
addFloat :: Floats -> FloatingBind -> Floats
addFloat (Floats OkToSpec
ok_to_spec OrdList FloatingBind
floats) FloatingBind
new_float
  = OkToSpec -> OrdList FloatingBind -> Floats
Floats (OkToSpec -> OkToSpec -> OkToSpec
combine OkToSpec
ok_to_spec (FloatingBind -> OkToSpec
check FloatingBind
new_float)) (OrdList FloatingBind
floats OrdList FloatingBind -> FloatingBind -> OrdList FloatingBind
forall a. OrdList a -> a -> OrdList a
`snocOL` FloatingBind
new_float)
  where
    check :: FloatingBind -> OkToSpec
check (FloatLet {})  = OkToSpec
OkToSpec
    check (FloatCase CpeRhs
_ Id
_ AltCon
_ [Id]
_ Bool
ok_for_spec)
      | Bool
ok_for_spec = OkToSpec
IfUnboxedOk
      | Bool
otherwise   = OkToSpec
NotOkToSpec
    check FloatTick{}    = OkToSpec
OkToSpec
        -- The ok-for-speculation flag says that it's safe to
        -- float this Case out of a let, and thereby do it more eagerly
        -- We need the top-level flag because it's never ok to float
        -- an unboxed binding to the top level

unitFloat :: FloatingBind -> Floats
unitFloat :: FloatingBind -> Floats
unitFloat = Floats -> FloatingBind -> Floats
addFloat Floats
emptyFloats

appendFloats :: Floats -> Floats -> Floats
appendFloats :: Floats -> Floats -> Floats
appendFloats (Floats OkToSpec
spec1 OrdList FloatingBind
floats1) (Floats OkToSpec
spec2 OrdList FloatingBind
floats2)
  = OkToSpec -> OrdList FloatingBind -> Floats
Floats (OkToSpec -> OkToSpec -> OkToSpec
combine OkToSpec
spec1 OkToSpec
spec2) (OrdList FloatingBind
floats1 OrdList FloatingBind
-> OrdList FloatingBind -> OrdList FloatingBind
forall a. OrdList a -> OrdList a -> OrdList a
`appOL` OrdList FloatingBind
floats2)

concatFloats :: [Floats] -> OrdList FloatingBind
concatFloats :: [Floats] -> OrdList FloatingBind
concatFloats = (Floats -> OrdList FloatingBind -> OrdList FloatingBind)
-> OrdList FloatingBind -> [Floats] -> OrdList FloatingBind
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
External instance of the constraint type Foldable []
foldr (\ (Floats OkToSpec
_ OrdList FloatingBind
bs1) OrdList FloatingBind
bs2 -> OrdList FloatingBind
-> OrdList FloatingBind -> OrdList FloatingBind
forall a. OrdList a -> OrdList a -> OrdList a
appOL OrdList FloatingBind
bs1 OrdList FloatingBind
bs2) OrdList FloatingBind
forall a. OrdList a
nilOL

combine :: OkToSpec -> OkToSpec -> OkToSpec
combine :: OkToSpec -> OkToSpec -> OkToSpec
combine OkToSpec
NotOkToSpec OkToSpec
_ = OkToSpec
NotOkToSpec
combine OkToSpec
_ OkToSpec
NotOkToSpec = OkToSpec
NotOkToSpec
combine OkToSpec
IfUnboxedOk OkToSpec
_ = OkToSpec
IfUnboxedOk
combine OkToSpec
_ OkToSpec
IfUnboxedOk = OkToSpec
IfUnboxedOk
combine OkToSpec
_ OkToSpec
_           = OkToSpec
OkToSpec

deFloatTop :: Floats -> [CoreBind]
-- For top level only; we don't expect any FloatCases
deFloatTop :: Floats -> CoreProgram
deFloatTop (Floats OkToSpec
_ OrdList FloatingBind
floats)
  = (FloatingBind -> CoreProgram -> CoreProgram)
-> CoreProgram -> OrdList FloatingBind -> CoreProgram
forall a b. (a -> b -> b) -> b -> OrdList a -> b
foldrOL FloatingBind -> CoreProgram -> CoreProgram
get [] OrdList FloatingBind
floats
  where
    get :: FloatingBind -> CoreProgram -> CoreProgram
get (FloatLet CoreBind
b)               CoreProgram
bs = CoreBind -> CoreBind
get_bind CoreBind
b                 CoreBind -> CoreProgram -> CoreProgram
forall a. a -> [a] -> [a]
: CoreProgram
bs
    get (FloatCase CpeRhs
body Id
var AltCon
_ [Id]
_ Bool
_) CoreProgram
bs = CoreBind -> CoreBind
get_bind (Id -> CpeRhs -> CoreBind
forall b. b -> Expr b -> Bind b
NonRec Id
var CpeRhs
body) CoreBind -> CoreProgram -> CoreProgram
forall a. a -> [a] -> [a]
: CoreProgram
bs
    get FloatingBind
b CoreProgram
_ = String -> SDoc -> CoreProgram
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"corePrepPgm" (FloatingBind -> SDoc
forall a. Outputable a => a -> SDoc
Instance of class: Outputable of the constraint type Outputable FloatingBind
ppr FloatingBind
b)

    -- See Note [Dead code in CorePrep]
    get_bind :: CoreBind -> CoreBind
get_bind (NonRec Id
x CpeRhs
e) = Id -> CpeRhs -> CoreBind
forall b. b -> Expr b -> Bind b
NonRec Id
x (CpeRhs -> CpeRhs
occurAnalyseExpr CpeRhs
e)
    get_bind (Rec [(Id, CpeRhs)]
xes)    = [(Id, CpeRhs)] -> CoreBind
forall b. [(b, Expr b)] -> Bind b
Rec [(Id
x, CpeRhs -> CpeRhs
occurAnalyseExpr CpeRhs
e) | (Id
x, CpeRhs
e) <- [(Id, CpeRhs)]
xes]

---------------------------------------------------------------------------

canFloat :: Floats -> CpeRhs -> Maybe (Floats, CpeRhs)
canFloat :: Floats -> CpeRhs -> Maybe (Floats, CpeRhs)
canFloat (Floats OkToSpec
ok_to_spec OrdList FloatingBind
fs) CpeRhs
rhs
  | OkToSpec
OkToSpec <- OkToSpec
ok_to_spec           -- Worth trying
  , Just OrdList FloatingBind
fs' <- OrdList FloatingBind
-> [FloatingBind] -> Maybe (OrdList FloatingBind)
go OrdList FloatingBind
forall a. OrdList a
nilOL (OrdList FloatingBind -> [FloatingBind]
forall a. OrdList a -> [a]
fromOL OrdList FloatingBind
fs)
  = (Floats, CpeRhs) -> Maybe (Floats, CpeRhs)
forall a. a -> Maybe a
Just (OkToSpec -> OrdList FloatingBind -> Floats
Floats OkToSpec
OkToSpec OrdList FloatingBind
fs', CpeRhs
rhs)
  | Bool
otherwise
  = Maybe (Floats, CpeRhs)
forall a. Maybe a
Nothing
  where
    go :: OrdList FloatingBind -> [FloatingBind]
       -> Maybe (OrdList FloatingBind)

    go :: OrdList FloatingBind
-> [FloatingBind] -> Maybe (OrdList FloatingBind)
go (OrdList FloatingBind
fbs_out) [] = OrdList FloatingBind -> Maybe (OrdList FloatingBind)
forall a. a -> Maybe a
Just OrdList FloatingBind
fbs_out

    go OrdList FloatingBind
fbs_out (fb :: FloatingBind
fb@(FloatLet CoreBind
_) : [FloatingBind]
fbs_in)
      = OrdList FloatingBind
-> [FloatingBind] -> Maybe (OrdList FloatingBind)
go (OrdList FloatingBind
fbs_out OrdList FloatingBind -> FloatingBind -> OrdList FloatingBind
forall a. OrdList a -> a -> OrdList a
`snocOL` FloatingBind
fb) [FloatingBind]
fbs_in

    go OrdList FloatingBind
fbs_out (ft :: FloatingBind
ft@FloatTick{} : [FloatingBind]
fbs_in)
      = OrdList FloatingBind
-> [FloatingBind] -> Maybe (OrdList FloatingBind)
go (OrdList FloatingBind
fbs_out OrdList FloatingBind -> FloatingBind -> OrdList FloatingBind
forall a. OrdList a -> a -> OrdList a
`snocOL` FloatingBind
ft) [FloatingBind]
fbs_in

    go OrdList FloatingBind
_ (FloatCase{} : [FloatingBind]
_) = Maybe (OrdList FloatingBind)
forall a. Maybe a
Nothing


wantFloatNested :: RecFlag -> Demand -> Bool -> Floats -> CpeRhs -> Bool
wantFloatNested :: RecFlag -> Demand -> Bool -> Floats -> CpeRhs -> Bool
wantFloatNested RecFlag
is_rec Demand
dmd Bool
is_unlifted Floats
floats CpeRhs
rhs
  =  Floats -> Bool
isEmptyFloats Floats
floats
  Bool -> Bool -> Bool
|| Demand -> Bool
forall s u. JointDmd (Str s) (Use u) -> Bool
isStrictDmd Demand
dmd
  Bool -> Bool -> Bool
|| Bool
is_unlifted
  Bool -> Bool -> Bool
|| (RecFlag -> Floats -> Bool
allLazyNested RecFlag
is_rec Floats
floats Bool -> Bool -> Bool
&& CpeRhs -> Bool
exprIsHNF CpeRhs
rhs)
        -- Why the test for allLazyNested?
        --      v = f (x `divInt#` y)
        -- we don't want to float the case, even if f has arity 2,
        -- because floating the case would make it evaluated too early

allLazyTop :: Floats -> Bool
allLazyTop :: Floats -> Bool
allLazyTop (Floats OkToSpec
OkToSpec OrdList FloatingBind
_) = Bool
True
allLazyTop Floats
_                   = Bool
False

allLazyNested :: RecFlag -> Floats -> Bool
allLazyNested :: RecFlag -> Floats -> Bool
allLazyNested RecFlag
_      (Floats OkToSpec
OkToSpec    OrdList FloatingBind
_) = Bool
True
allLazyNested RecFlag
_      (Floats OkToSpec
NotOkToSpec OrdList FloatingBind
_) = Bool
False
allLazyNested RecFlag
is_rec (Floats OkToSpec
IfUnboxedOk OrdList FloatingBind
_) = RecFlag -> Bool
isNonRec RecFlag
is_rec

{-
************************************************************************
*                                                                      *
                Cloning
*                                                                      *
************************************************************************
-}

-- ---------------------------------------------------------------------------
--                      The environment
-- ---------------------------------------------------------------------------

{- Note [Inlining in CorePrep]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is a subtle but important invariant that must be upheld in the output
of CorePrep: there are no "trivial" updatable thunks.  Thus, this Core
is impermissible:

     let x :: ()
         x = y

(where y is a reference to a GLOBAL variable).  Thunks like this are silly:
they can always be profitably replaced by inlining x with y. Consequently,
the code generator/runtime does not bother implementing this properly
(specifically, there is no implementation of stg_ap_0_upd_info, which is the
stack frame that would be used to update this thunk.  The "0" means it has
zero free variables.)

In general, the inliner is good at eliminating these let-bindings.  However,
there is one case where these trivial updatable thunks can arise: when
we are optimizing away 'lazy' (see Note [lazyId magic], and also
'cpeRhsE'.)  Then, we could have started with:

     let x :: ()
         x = lazy @ () y

which is a perfectly fine, non-trivial thunk, but then CorePrep will
drop 'lazy', giving us 'x = y' which is trivial and impermissible.
The solution is CorePrep to have a miniature inlining pass which deals
with cases like this.  We can then drop the let-binding altogether.

Why does the removal of 'lazy' have to occur in CorePrep?
The gory details are in Note [lazyId magic] in GHC.Types.Id.Make, but the
main reason is that lazy must appear in unfoldings (optimizer
output) and it must prevent call-by-value for catch# (which
is implemented by CorePrep.)

An alternate strategy for solving this problem is to have the
inliner treat 'lazy e' as a trivial expression if 'e' is trivial.
We decided not to adopt this solution to keep the definition
of 'exprIsTrivial' simple.

There is ONE caveat however: for top-level bindings we have
to preserve the binding so that we float the (hacky) non-recursive
binding for data constructors; see Note [Data constructor workers].

Note [CorePrep inlines trivial CoreExpr not Id]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Why does cpe_env need to be an IdEnv CoreExpr, as opposed to an
IdEnv Id?  Naively, we might conjecture that trivial updatable thunks
as per Note [Inlining in CorePrep] always have the form
'lazy @ SomeType gbl_id'.  But this is not true: the following is
perfectly reasonable Core:

     let x :: ()
         x = lazy @ (forall a. a) y @ Bool

When we inline 'x' after eliminating 'lazy', we need to replace
occurrences of 'x' with 'y @ bool', not just 'y'.  Situations like
this can easily arise with higher-rank types; thus, cpe_env must
map to CoreExprs, not Ids.

-}

data CorePrepEnv
  = CPE { CorePrepEnv -> DynFlags
cpe_dynFlags        :: DynFlags
        , CorePrepEnv -> IdEnv CpeRhs
cpe_env             :: IdEnv CoreExpr   -- Clone local Ids
        -- ^ This environment is used for three operations:
        --
        --      1. To support cloning of local Ids so that they are
        --      all unique (see item (6) of CorePrep overview).
        --
        --      2. To support beta-reduction of runRW, see
        --      Note [runRW magic] and Note [runRW arg].
        --
        --      3. To let us inline trivial RHSs of non top-level let-bindings,
        --      see Note [lazyId magic], Note [Inlining in CorePrep]
        --      and Note [CorePrep inlines trivial CoreExpr not Id] (#12076)
        , CorePrepEnv -> Id
cpe_mkIntegerId     :: Id
        , CorePrepEnv -> Id
cpe_mkNaturalId     :: Id
        , CorePrepEnv -> Maybe DataCon
cpe_integerSDataCon :: Maybe DataCon
        , CorePrepEnv -> Maybe DataCon
cpe_naturalSDataCon :: Maybe DataCon
    }

lookupMkIntegerName :: DynFlags -> HscEnv -> IO Id
lookupMkIntegerName :: DynFlags -> HscEnv -> IO Id
lookupMkIntegerName DynFlags
dflags HscEnv
hsc_env
    = DynFlags -> IO Id -> IO Id
forall a. DynFlags -> IO a -> IO a
guardIntegerUse DynFlags
dflags (IO Id -> IO Id) -> IO Id -> IO Id
forall a b. (a -> b) -> a -> b
$ (TyThing -> Id) -> IO TyThing -> IO Id
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
External instance of the constraint type Monad IO
liftM HasDebugCallStack => TyThing -> Id
TyThing -> Id
External instance of the constraint type HasDebugCallStack
tyThingId (IO TyThing -> IO Id) -> IO TyThing -> IO Id
forall a b. (a -> b) -> a -> b
$
      HscEnv -> Name -> IO TyThing
lookupGlobal HscEnv
hsc_env Name
mkIntegerName

lookupMkNaturalName :: DynFlags -> HscEnv -> IO Id
lookupMkNaturalName :: DynFlags -> HscEnv -> IO Id
lookupMkNaturalName DynFlags
dflags HscEnv
hsc_env
    = DynFlags -> IO Id -> IO Id
forall a. DynFlags -> IO a -> IO a
guardNaturalUse DynFlags
dflags (IO Id -> IO Id) -> IO Id -> IO Id
forall a b. (a -> b) -> a -> b
$ (TyThing -> Id) -> IO TyThing -> IO Id
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
External instance of the constraint type Monad IO
liftM HasDebugCallStack => TyThing -> Id
TyThing -> Id
External instance of the constraint type HasDebugCallStack
tyThingId (IO TyThing -> IO Id) -> IO TyThing -> IO Id
forall a b. (a -> b) -> a -> b
$
      HscEnv -> Name -> IO TyThing
lookupGlobal HscEnv
hsc_env Name
mkNaturalName

-- See Note [The integer library] in GHC.Builtin.Names
lookupIntegerSDataConName :: DynFlags -> HscEnv -> IO (Maybe DataCon)
lookupIntegerSDataConName :: DynFlags -> HscEnv -> IO (Maybe DataCon)
lookupIntegerSDataConName DynFlags
dflags HscEnv
hsc_env = case DynFlags -> IntegerLibrary
integerLibrary DynFlags
dflags of
    IntegerLibrary
IntegerGMP -> DynFlags -> IO (Maybe DataCon) -> IO (Maybe DataCon)
forall a. DynFlags -> IO a -> IO a
guardIntegerUse DynFlags
dflags (IO (Maybe DataCon) -> IO (Maybe DataCon))
-> IO (Maybe DataCon) -> IO (Maybe DataCon)
forall a b. (a -> b) -> a -> b
$ (TyThing -> Maybe DataCon) -> IO TyThing -> IO (Maybe DataCon)
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
External instance of the constraint type Monad IO
liftM (DataCon -> Maybe DataCon
forall a. a -> Maybe a
Just (DataCon -> Maybe DataCon)
-> (TyThing -> DataCon) -> TyThing -> Maybe DataCon
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HasDebugCallStack => TyThing -> DataCon
TyThing -> DataCon
External instance of the constraint type HasDebugCallStack
tyThingDataCon) (IO TyThing -> IO (Maybe DataCon))
-> IO TyThing -> IO (Maybe DataCon)
forall a b. (a -> b) -> a -> b
$
                  HscEnv -> Name -> IO TyThing
lookupGlobal HscEnv
hsc_env Name
integerSDataConName
    IntegerLibrary
IntegerSimple -> Maybe DataCon -> IO (Maybe DataCon)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad IO
return Maybe DataCon
forall a. Maybe a
Nothing

lookupNaturalSDataConName :: DynFlags -> HscEnv -> IO (Maybe DataCon)
lookupNaturalSDataConName :: DynFlags -> HscEnv -> IO (Maybe DataCon)
lookupNaturalSDataConName DynFlags
dflags HscEnv
hsc_env = case DynFlags -> IntegerLibrary
integerLibrary DynFlags
dflags of
    IntegerLibrary
IntegerGMP -> DynFlags -> IO (Maybe DataCon) -> IO (Maybe DataCon)
forall a. DynFlags -> IO a -> IO a
guardNaturalUse DynFlags
dflags (IO (Maybe DataCon) -> IO (Maybe DataCon))
-> IO (Maybe DataCon) -> IO (Maybe DataCon)
forall a b. (a -> b) -> a -> b
$ (TyThing -> Maybe DataCon) -> IO TyThing -> IO (Maybe DataCon)
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
External instance of the constraint type Monad IO
liftM (DataCon -> Maybe DataCon
forall a. a -> Maybe a
Just (DataCon -> Maybe DataCon)
-> (TyThing -> DataCon) -> TyThing -> Maybe DataCon
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HasDebugCallStack => TyThing -> DataCon
TyThing -> DataCon
External instance of the constraint type HasDebugCallStack
tyThingDataCon) (IO TyThing -> IO (Maybe DataCon))
-> IO TyThing -> IO (Maybe DataCon)
forall a b. (a -> b) -> a -> b
$
                  HscEnv -> Name -> IO TyThing
lookupGlobal HscEnv
hsc_env Name
naturalSDataConName
    IntegerLibrary
IntegerSimple -> Maybe DataCon -> IO (Maybe DataCon)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad IO
return Maybe DataCon
forall a. Maybe a
Nothing

-- | Helper for 'lookupMkIntegerName', 'lookupIntegerSDataConName'
guardIntegerUse :: DynFlags -> IO a -> IO a
guardIntegerUse :: DynFlags -> IO a -> IO a
guardIntegerUse DynFlags
dflags IO a
act
  | DynFlags -> Unit
thisPackage DynFlags
dflags Unit -> Unit -> Bool
forall a. Eq a => a -> a -> Bool
External instance of the constraint type Eq Unit
== Unit
primUnitId
  = a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad IO
return (a -> IO a) -> a -> IO a
forall a b. (a -> b) -> a -> b
$ String -> a
forall a. String -> a
panic String
"Can't use Integer in ghc-prim"
  | DynFlags -> Unit
thisPackage DynFlags
dflags Unit -> Unit -> Bool
forall a. Eq a => a -> a -> Bool
External instance of the constraint type Eq Unit
== Unit
integerUnitId
  = a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad IO
return (a -> IO a) -> a -> IO a
forall a b. (a -> b) -> a -> b
$ String -> a
forall a. String -> a
panic String
"Can't use Integer in integer-*"
  | Bool
otherwise = IO a
act

-- | Helper for 'lookupMkNaturalName', 'lookupNaturalSDataConName'
--
-- Just like we can't use Integer literals in `integer-*`, we can't use Natural
-- literals in `base`. If we do, we get interface loading error for GHC.Natural.
guardNaturalUse :: DynFlags -> IO a -> IO a
guardNaturalUse :: DynFlags -> IO a -> IO a
guardNaturalUse DynFlags
dflags IO a
act
  | DynFlags -> Unit
thisPackage DynFlags
dflags Unit -> Unit -> Bool
forall a. Eq a => a -> a -> Bool
External instance of the constraint type Eq Unit
== Unit
primUnitId
  = a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad IO
return (a -> IO a) -> a -> IO a
forall a b. (a -> b) -> a -> b
$ String -> a
forall a. String -> a
panic String
"Can't use Natural in ghc-prim"
  | DynFlags -> Unit
thisPackage DynFlags
dflags Unit -> Unit -> Bool
forall a. Eq a => a -> a -> Bool
External instance of the constraint type Eq Unit
== Unit
integerUnitId
  = a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad IO
return (a -> IO a) -> a -> IO a
forall a b. (a -> b) -> a -> b
$ String -> a
forall a. String -> a
panic String
"Can't use Natural in integer-*"
  | DynFlags -> Unit
thisPackage DynFlags
dflags Unit -> Unit -> Bool
forall a. Eq a => a -> a -> Bool
External instance of the constraint type Eq Unit
== Unit
baseUnitId
  = a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad IO
return (a -> IO a) -> a -> IO a
forall a b. (a -> b) -> a -> b
$ String -> a
forall a. String -> a
panic String
"Can't use Natural in base"
  | Bool
otherwise = IO a
act

mkInitialCorePrepEnv :: DynFlags -> HscEnv -> IO CorePrepEnv
mkInitialCorePrepEnv :: DynFlags -> HscEnv -> IO CorePrepEnv
mkInitialCorePrepEnv DynFlags
dflags HscEnv
hsc_env
    = do Id
mkIntegerId <- DynFlags -> HscEnv -> IO Id
lookupMkIntegerName DynFlags
dflags HscEnv
hsc_env
         Id
mkNaturalId <- DynFlags -> HscEnv -> IO Id
lookupMkNaturalName DynFlags
dflags HscEnv
hsc_env
         Maybe DataCon
integerSDataCon <- DynFlags -> HscEnv -> IO (Maybe DataCon)
lookupIntegerSDataConName DynFlags
dflags HscEnv
hsc_env
         Maybe DataCon
naturalSDataCon <- DynFlags -> HscEnv -> IO (Maybe DataCon)
lookupNaturalSDataConName DynFlags
dflags HscEnv
hsc_env
         CorePrepEnv -> IO CorePrepEnv
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad IO
return (CorePrepEnv -> IO CorePrepEnv) -> CorePrepEnv -> IO CorePrepEnv
forall a b. (a -> b) -> a -> b
$ CPE :: DynFlags
-> IdEnv CpeRhs
-> Id
-> Id
-> Maybe DataCon
-> Maybe DataCon
-> CorePrepEnv
CPE {
                      cpe_dynFlags :: DynFlags
cpe_dynFlags = DynFlags
dflags,
                      cpe_env :: IdEnv CpeRhs
cpe_env = IdEnv CpeRhs
forall a. VarEnv a
emptyVarEnv,
                      cpe_mkIntegerId :: Id
cpe_mkIntegerId = Id
mkIntegerId,
                      cpe_mkNaturalId :: Id
cpe_mkNaturalId = Id
mkNaturalId,
                      cpe_integerSDataCon :: Maybe DataCon
cpe_integerSDataCon = Maybe DataCon
integerSDataCon,
                      cpe_naturalSDataCon :: Maybe DataCon
cpe_naturalSDataCon = Maybe DataCon
naturalSDataCon
                  }

extendCorePrepEnv :: CorePrepEnv -> Id -> Id -> CorePrepEnv
extendCorePrepEnv :: CorePrepEnv -> Id -> Id -> CorePrepEnv
extendCorePrepEnv CorePrepEnv
cpe Id
id Id
id'
    = CorePrepEnv
cpe { cpe_env :: IdEnv CpeRhs
cpe_env = IdEnv CpeRhs -> Id -> CpeRhs -> IdEnv CpeRhs
forall a. VarEnv a -> Id -> a -> VarEnv a
extendVarEnv (CorePrepEnv -> IdEnv CpeRhs
cpe_env CorePrepEnv
cpe) Id
id (Id -> CpeRhs
forall b. Id -> Expr b
Var Id
id') }

extendCorePrepEnvExpr :: CorePrepEnv -> Id -> CoreExpr -> CorePrepEnv
extendCorePrepEnvExpr :: CorePrepEnv -> Id -> CpeRhs -> CorePrepEnv
extendCorePrepEnvExpr CorePrepEnv
cpe Id
id CpeRhs
expr
    = CorePrepEnv
cpe { cpe_env :: IdEnv CpeRhs
cpe_env = IdEnv CpeRhs -> Id -> CpeRhs -> IdEnv CpeRhs
forall a. VarEnv a -> Id -> a -> VarEnv a
extendVarEnv (CorePrepEnv -> IdEnv CpeRhs
cpe_env CorePrepEnv
cpe) Id
id CpeRhs
expr }

extendCorePrepEnvList :: CorePrepEnv -> [(Id,Id)] -> CorePrepEnv
extendCorePrepEnvList :: CorePrepEnv -> [(Id, Id)] -> CorePrepEnv
extendCorePrepEnvList CorePrepEnv
cpe [(Id, Id)]
prs
    = CorePrepEnv
cpe { cpe_env :: IdEnv CpeRhs
cpe_env = IdEnv CpeRhs -> [(Id, CpeRhs)] -> IdEnv CpeRhs
forall a. VarEnv a -> [(Id, a)] -> VarEnv a
extendVarEnvList (CorePrepEnv -> IdEnv CpeRhs
cpe_env CorePrepEnv
cpe)
                        (((Id, Id) -> (Id, CpeRhs)) -> [(Id, Id)] -> [(Id, CpeRhs)]
forall a b. (a -> b) -> [a] -> [b]
map (\(Id
id, Id
id') -> (Id
id, Id -> CpeRhs
forall b. Id -> Expr b
Var Id
id')) [(Id, Id)]
prs) }

lookupCorePrepEnv :: CorePrepEnv -> Id -> CoreExpr
lookupCorePrepEnv :: CorePrepEnv -> Id -> CpeRhs
lookupCorePrepEnv CorePrepEnv
cpe Id
id
  = case IdEnv CpeRhs -> Id -> Maybe CpeRhs
forall a. VarEnv a -> Id -> Maybe a
lookupVarEnv (CorePrepEnv -> IdEnv CpeRhs
cpe_env CorePrepEnv
cpe) Id
id of
        Maybe CpeRhs
Nothing  -> Id -> CpeRhs
forall b. Id -> Expr b
Var Id
id
        Just CpeRhs
exp -> CpeRhs
exp

getMkIntegerId :: CorePrepEnv -> Id
getMkIntegerId :: CorePrepEnv -> Id
getMkIntegerId = CorePrepEnv -> Id
cpe_mkIntegerId

getMkNaturalId :: CorePrepEnv -> Id
getMkNaturalId :: CorePrepEnv -> Id
getMkNaturalId = CorePrepEnv -> Id
cpe_mkNaturalId

------------------------------------------------------------------------------
-- Cloning binders
-- ---------------------------------------------------------------------------

cpCloneBndrs :: CorePrepEnv -> [InVar] -> UniqSM (CorePrepEnv, [OutVar])
cpCloneBndrs :: CorePrepEnv -> [Id] -> UniqSM (CorePrepEnv, [Id])
cpCloneBndrs CorePrepEnv
env [Id]
bs = (CorePrepEnv -> Id -> UniqSM (CorePrepEnv, Id))
-> CorePrepEnv -> [Id] -> UniqSM (CorePrepEnv, [Id])
forall (m :: * -> *) acc x y.
Monad m =>
(acc -> x -> m (acc, y)) -> acc -> [x] -> m (acc, [y])
External instance of the constraint type Monad UniqSM
mapAccumLM CorePrepEnv -> Id -> UniqSM (CorePrepEnv, Id)
cpCloneBndr CorePrepEnv
env [Id]
bs

cpCloneBndr  :: CorePrepEnv -> InVar -> UniqSM (CorePrepEnv, OutVar)
cpCloneBndr :: CorePrepEnv -> Id -> UniqSM (CorePrepEnv, Id)
cpCloneBndr CorePrepEnv
env Id
bndr
  | Bool -> Bool
not (Id -> Bool
isId Id
bndr)
  = (CorePrepEnv, Id) -> UniqSM (CorePrepEnv, Id)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (CorePrepEnv
env, Id
bndr)

  | Bool
otherwise
  = do { Id
bndr' <- Id -> UniqSM Id
forall {m :: * -> *}. MonadUnique m => Id -> m Id
External instance of the constraint type MonadUnique UniqSM
clone_it Id
bndr

       -- Drop (now-useless) rules/unfoldings
       -- See Note [Drop unfoldings and rules]
       -- and Note [Preserve evaluatedness] in GHC.Core.Tidy
       ; let unfolding' :: Unfolding
unfolding' = Unfolding -> Unfolding
zapUnfolding (Id -> Unfolding
realIdUnfolding Id
bndr)
                          -- Simplifier will set the Id's unfolding

             bndr'' :: Id
bndr'' = Id
bndr' Id -> Unfolding -> Id
`setIdUnfolding`      Unfolding
unfolding'
                            Id -> RuleInfo -> Id
`setIdSpecialisation` RuleInfo
emptyRuleInfo

       ; (CorePrepEnv, Id) -> UniqSM (CorePrepEnv, Id)
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (CorePrepEnv -> Id -> Id -> CorePrepEnv
extendCorePrepEnv CorePrepEnv
env Id
bndr Id
bndr'', Id
bndr'') }
  where
    clone_it :: Id -> m Id
clone_it Id
bndr
      | Id -> Bool
isLocalId Id
bndr, Bool -> Bool
not (Id -> Bool
isCoVar Id
bndr)
      = do { Unique
uniq <- m Unique
forall (m :: * -> *). MonadUnique m => m Unique
Evidence bound by a type signature of the constraint type MonadUnique m
getUniqueM; Id -> m Id
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type forall (m :: * -> *). MonadUnique m => Monad m
Evidence bound by a type signature of the constraint type MonadUnique m
return (Id -> Unique -> Id
setVarUnique Id
bndr Unique
uniq) }
      | Bool
otherwise   -- Top level things, which we don't want
                    -- to clone, have become GlobalIds by now
                    -- And we don't clone tyvars, or coercion variables
      = Id -> m Id
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type forall (m :: * -> *). MonadUnique m => Monad m
Evidence bound by a type signature of the constraint type MonadUnique m
return Id
bndr

{- Note [Drop unfoldings and rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We want to drop the unfolding/rules on every Id:

  - We are now past interface-file generation, and in the
    codegen pipeline, so we really don't need full unfoldings/rules

  - The unfolding/rule may be keeping stuff alive that we'd like
    to discard.  See  Note [Dead code in CorePrep]

  - Getting rid of unnecessary unfoldings reduces heap usage

  - We are changing uniques, so if we didn't discard unfoldings/rules
    we'd have to substitute in them

HOWEVER, we want to preserve evaluated-ness;
see Note [Preserve evaluatedness] in GHC.Core.Tidy.
-}

------------------------------------------------------------------------------
-- Cloning ccall Ids; each must have a unique name,
-- to give the code generator a handle to hang it on
-- ---------------------------------------------------------------------------

fiddleCCall :: Id -> UniqSM Id
fiddleCCall :: Id -> UniqSM Id
fiddleCCall Id
id
  | Id -> Bool
isFCallId Id
id = (Id
id Id -> Unique -> Id
`setVarUnique`) (Unique -> Id) -> UniqSM Unique -> UniqSM Id
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
External instance of the constraint type Functor UniqSM
<$> UniqSM Unique
forall (m :: * -> *). MonadUnique m => m Unique
External instance of the constraint type MonadUnique UniqSM
getUniqueM
  | Bool
otherwise    = Id -> UniqSM Id
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return Id
id

------------------------------------------------------------------------------
-- Generating new binders
-- ---------------------------------------------------------------------------

newVar :: Type -> UniqSM Id
newVar :: Type -> UniqSM Id
newVar Type
ty
 = Type -> ()
seqType Type
ty () -> UniqSM Id -> UniqSM Id
`seq` do
     Unique
uniq <- UniqSM Unique
forall (m :: * -> *). MonadUnique m => m Unique
External instance of the constraint type MonadUnique UniqSM
getUniqueM
     Id -> UniqSM Id
forall (m :: * -> *) a. Monad m => a -> m a
External instance of the constraint type Monad UniqSM
return (FastString -> Unique -> Type -> Id
mkSysLocalOrCoVar (String -> FastString
fsLit String
"sat") Unique
uniq Type
ty)


------------------------------------------------------------------------------
-- Floating ticks
-- ---------------------------------------------------------------------------
--
-- Note [Floating Ticks in CorePrep]
--
-- It might seem counter-intuitive to float ticks by default, given
-- that we don't actually want to move them if we can help it. On the
-- other hand, nothing gets very far in CorePrep anyway, and we want
-- to preserve the order of let bindings and tick annotations in
-- relation to each other. For example, if we just wrapped let floats
-- when they pass through ticks, we might end up performing the
-- following transformation:
--
--   src<...> let foo = bar in baz
--   ==>  let foo = src<...> bar in src<...> baz
--
-- Because the let-binding would float through the tick, and then
-- immediately materialize, achieving nothing but decreasing tick
-- accuracy. The only special case is the following scenario:
--
--   let foo = src<...> (let a = b in bar) in baz
--   ==>  let foo = src<...> bar; a = src<...> b in baz
--
-- Here we would not want the source tick to end up covering "baz" and
-- therefore refrain from pushing ticks outside. Instead, we copy them
-- into the floating binds (here "a") in cpePair. Note that where "b"
-- or "bar" are (value) lambdas we have to push the annotations
-- further inside in order to uphold our rules.
--
-- All of this is implemented below in @wrapTicks@.

-- | Like wrapFloats, but only wraps tick floats
wrapTicks :: Floats -> CoreExpr -> (Floats, CoreExpr)
wrapTicks :: Floats -> CpeRhs -> (Floats, CpeRhs)
wrapTicks (Floats OkToSpec
flag OrdList FloatingBind
floats0) CpeRhs
expr =
    (OkToSpec -> OrdList FloatingBind -> Floats
Floats OkToSpec
flag ([FloatingBind] -> OrdList FloatingBind
forall a. [a] -> OrdList a
toOL ([FloatingBind] -> OrdList FloatingBind)
-> [FloatingBind] -> OrdList FloatingBind
forall a b. (a -> b) -> a -> b
$ [FloatingBind] -> [FloatingBind]
forall a. [a] -> [a]
reverse [FloatingBind]
floats1), (Tickish Id -> CpeRhs -> CpeRhs)
-> CpeRhs -> [Tickish Id] -> CpeRhs
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
External instance of the constraint type Foldable []
foldr Tickish Id -> CpeRhs -> CpeRhs
mkTick CpeRhs
expr ([Tickish Id] -> [Tickish Id]
forall a. [a] -> [a]
reverse [Tickish Id]
ticks1))
  where ([FloatingBind]
floats1, [Tickish Id]
ticks1) = (([FloatingBind], [Tickish Id])
 -> FloatingBind -> ([FloatingBind], [Tickish Id]))
-> ([FloatingBind], [Tickish Id])
-> OrdList FloatingBind
-> ([FloatingBind], [Tickish Id])
forall b a. (b -> a -> b) -> b -> OrdList a -> b
foldlOL ([FloatingBind], [Tickish Id])
-> FloatingBind -> ([FloatingBind], [Tickish Id])
go ([], []) (OrdList FloatingBind -> ([FloatingBind], [Tickish Id]))
-> OrdList FloatingBind -> ([FloatingBind], [Tickish Id])
forall a b. (a -> b) -> a -> b
$ OrdList FloatingBind
floats0
        -- Deeply nested constructors will produce long lists of
        -- redundant source note floats here. We need to eliminate
        -- those early, as relying on mkTick to spot it after the fact
        -- can yield O(n^3) complexity [#11095]
        go :: ([FloatingBind], [Tickish Id])
-> FloatingBind -> ([FloatingBind], [Tickish Id])
go ([FloatingBind]
floats, [Tickish Id]
ticks) (FloatTick Tickish Id
t)
          = ASSERT(tickishPlace t == PlaceNonLam)
            ([FloatingBind]
floats, if (Tickish Id -> Bool) -> [Tickish Id] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
External instance of the constraint type Foldable []
any ((Tickish Id -> Tickish Id -> Bool)
-> Tickish Id -> Tickish Id -> Bool
forall a b c. (a -> b -> c) -> b -> a -> c
flip Tickish Id -> Tickish Id -> Bool
forall b. Eq b => Tickish b -> Tickish b -> Bool
External instance of the constraint type Eq Id
tickishContains Tickish Id
t) [Tickish Id]
ticks
                     then [Tickish Id]
ticks else Tickish Id
tTickish Id -> [Tickish Id] -> [Tickish Id]
forall a. a -> [a] -> [a]
:[Tickish Id]
ticks)
        go ([FloatingBind]
floats, [Tickish Id]
ticks) FloatingBind
f
          = ((Tickish Id -> FloatingBind -> FloatingBind)
-> FloatingBind -> [Tickish Id] -> FloatingBind
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
External instance of the constraint type Foldable []
foldr Tickish Id -> FloatingBind -> FloatingBind
wrap FloatingBind
f ([Tickish Id] -> [Tickish Id]
forall a. [a] -> [a]
reverse [Tickish Id]
ticks)FloatingBind -> [FloatingBind] -> [FloatingBind]
forall a. a -> [a] -> [a]
:[FloatingBind]
floats, [Tickish Id]
ticks)

        wrap :: Tickish Id -> FloatingBind -> FloatingBind
wrap Tickish Id
t (FloatLet CoreBind
bind)           = CoreBind -> FloatingBind
FloatLet (Tickish Id -> CoreBind -> CoreBind
wrapBind Tickish Id
t CoreBind
bind)
        wrap Tickish Id
t (FloatCase CpeRhs
r Id
b AltCon
con [Id]
bs Bool
ok) = CpeRhs -> Id -> AltCon -> [Id] -> Bool -> FloatingBind
FloatCase (Tickish Id -> CpeRhs -> CpeRhs
mkTick Tickish Id
t CpeRhs
r) Id
b AltCon
con [Id]
bs Bool
ok
        wrap Tickish Id
_ FloatingBind
other                     = String -> SDoc -> FloatingBind
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"wrapTicks: unexpected float!"
                                             (FloatingBind -> SDoc
forall a. Outputable a => a -> SDoc
Instance of class: Outputable of the constraint type Outputable FloatingBind
ppr FloatingBind
other)
        wrapBind :: Tickish Id -> CoreBind -> CoreBind
wrapBind Tickish Id
t (NonRec Id
binder CpeRhs
rhs) = Id -> CpeRhs -> CoreBind
forall b. b -> Expr b -> Bind b
NonRec Id
binder (Tickish Id -> CpeRhs -> CpeRhs
mkTick Tickish Id
t CpeRhs
rhs)
        wrapBind Tickish Id
t (Rec [(Id, CpeRhs)]
pairs)         = [(Id, CpeRhs)] -> CoreBind
forall b. [(b, Expr b)] -> Bind b
Rec ((CpeRhs -> CpeRhs) -> [(Id, CpeRhs)] -> [(Id, CpeRhs)]
forall b c a. (b -> c) -> [(a, b)] -> [(a, c)]
mapSnd (Tickish Id -> CpeRhs -> CpeRhs
mkTick Tickish Id
t) [(Id, CpeRhs)]
pairs)

------------------------------------------------------------------------------
-- Collecting cost centres
-- ---------------------------------------------------------------------------

-- | Collect cost centres defined in the current module, including those in
-- unfoldings.
collectCostCentres :: Module -> CoreProgram -> S.Set CostCentre
collectCostCentres :: Module -> CoreProgram -> Set CostCentre
collectCostCentres Module
mod_name
  = (Set CostCentre -> CoreBind -> Set CostCentre)
-> Set CostCentre -> CoreProgram -> Set CostCentre
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
External instance of the constraint type Foldable []
foldl' Set CostCentre -> CoreBind -> Set CostCentre
go_bind Set CostCentre
forall a. Set a
S.empty
  where
    go :: Set CostCentre -> CpeRhs -> Set CostCentre
go Set CostCentre
cs CpeRhs
e = case CpeRhs
e of
      Var{} -> Set CostCentre
cs
      Lit{} -> Set CostCentre
cs
      App CpeRhs
e1 CpeRhs
e2 -> Set CostCentre -> CpeRhs -> Set CostCentre
go (Set CostCentre -> CpeRhs -> Set CostCentre
go Set CostCentre
cs CpeRhs
e1) CpeRhs
e2
      Lam Id
_ CpeRhs
e -> Set CostCentre -> CpeRhs -> Set CostCentre
go Set CostCentre
cs CpeRhs
e
      Let CoreBind
b CpeRhs
e -> Set CostCentre -> CpeRhs -> Set CostCentre
go (Set CostCentre -> CoreBind -> Set CostCentre
go_bind Set CostCentre
cs CoreBind
b) CpeRhs
e
      Case CpeRhs
scrt Id
_ Type
_ [Alt Id]
alts -> Set CostCentre -> [Alt Id] -> Set CostCentre
go_alts (Set CostCentre -> CpeRhs -> Set CostCentre
go Set CostCentre
cs CpeRhs
scrt) [Alt Id]
alts
      Cast CpeRhs
e Coercion
_ -> Set CostCentre -> CpeRhs -> Set CostCentre
go Set CostCentre
cs CpeRhs
e
      Tick (ProfNote CostCentre
cc Bool
_ Bool
_) CpeRhs
e ->
        Set CostCentre -> CpeRhs -> Set CostCentre
go (if CostCentre -> Module -> Bool
ccFromThisModule CostCentre
cc Module
mod_name then CostCentre -> Set CostCentre -> Set CostCentre
forall a. Ord a => a -> Set a -> Set a
External instance of the constraint type Ord CostCentre
S.insert CostCentre
cc Set CostCentre
cs else Set CostCentre
cs) CpeRhs
e
      Tick Tickish Id
_ CpeRhs
e -> Set CostCentre -> CpeRhs -> Set CostCentre
go Set CostCentre
cs CpeRhs
e
      Type{} -> Set CostCentre
cs
      Coercion{} -> Set CostCentre
cs

    go_alts :: Set CostCentre -> [Alt Id] -> Set CostCentre
go_alts = (Set CostCentre -> Alt Id -> Set CostCentre)
-> Set CostCentre -> [Alt Id] -> Set CostCentre
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
External instance of the constraint type Foldable []
foldl' (\Set CostCentre
cs (AltCon
_con, [Id]
_bndrs, CpeRhs
e) -> Set CostCentre -> CpeRhs -> Set CostCentre
go Set CostCentre
cs CpeRhs
e)

    go_bind :: S.Set CostCentre -> CoreBind -> S.Set CostCentre
    go_bind :: Set CostCentre -> CoreBind -> Set CostCentre
go_bind Set CostCentre
cs (NonRec Id
b CpeRhs
e) =
      Set CostCentre -> CpeRhs -> Set CostCentre
go (Set CostCentre
-> (CpeRhs -> Set CostCentre) -> Maybe CpeRhs -> Set CostCentre
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Set CostCentre
cs (Set CostCentre -> CpeRhs -> Set CostCentre
go Set CostCentre
cs) (Id -> Maybe CpeRhs
get_unf Id
b)) CpeRhs
e
    go_bind Set CostCentre
cs (Rec [(Id, CpeRhs)]
bs) =
      (Set CostCentre -> (Id, CpeRhs) -> Set CostCentre)
-> Set CostCentre -> [(Id, CpeRhs)] -> Set CostCentre
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
External instance of the constraint type Foldable []
foldl' (\Set CostCentre
cs' (Id
b, CpeRhs
e) -> Set CostCentre -> CpeRhs -> Set CostCentre
go (Set CostCentre
-> (CpeRhs -> Set CostCentre) -> Maybe CpeRhs -> Set CostCentre
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Set CostCentre
cs' (Set CostCentre -> CpeRhs -> Set CostCentre
go Set CostCentre
cs') (Id -> Maybe CpeRhs
get_unf Id
b)) CpeRhs
e) Set CostCentre
cs [(Id, CpeRhs)]
bs

    -- Unfoldings may have cost centres that in the original definion are
    -- optimized away, see #5889.
    get_unf :: Id -> Maybe CpeRhs
get_unf = Unfolding -> Maybe CpeRhs
maybeUnfoldingTemplate (Unfolding -> Maybe CpeRhs)
-> (Id -> Unfolding) -> Id -> Maybe CpeRhs
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Id -> Unfolding
realIdUnfolding