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

\section[CoreMonad]{The core pipeline monad}
-}

{-# LANGUAGE CPP #-}

module CoreMonad (
    -- * Configuration of the core-to-core passes
    CoreToDo(..), runWhen, runMaybe,
    SimplMode(..),
    FloatOutSwitches(..),
    pprPassDetails,

    -- * Plugins
    CorePluginPass, bindsOnlyPass,

    -- * Counting
    SimplCount, doSimplTick, doFreeSimplTick, simplCountN,
    pprSimplCount, plusSimplCount, zeroSimplCount,
    isZeroSimplCount, hasDetailedCounts, Tick(..),

    -- * The monad
    CoreM, runCoreM,

    -- ** Reading from the monad
    getHscEnv, getRuleBase, getModule,
    getDynFlags, getOrigNameCache, getPackageFamInstEnv,
    getVisibleOrphanMods,
    getPrintUnqualified, getSrcSpanM,

    -- ** Writing to the monad
    addSimplCount,

    -- ** Lifting into the monad
    liftIO, liftIOWithCount,
    liftIO1, liftIO2, liftIO3, liftIO4,

    -- ** Global initialization
    reinitializeGlobals,

    -- ** Dealing with annotations
    getAnnotations, getFirstAnnotations,

    -- ** Screen output
    putMsg, putMsgS, errorMsg, errorMsgS, warnMsg,
    fatalErrorMsg, fatalErrorMsgS,
    debugTraceMsg, debugTraceMsgS,
    dumpIfSet_dyn
  ) where

import GhcPrelude hiding ( read )

import CoreSyn
import HscTypes
import Module
import DynFlags
import BasicTypes       ( CompilerPhase(..) )
import Annotations

import IOEnv hiding     ( liftIO, failM, failWithM )
import qualified IOEnv  ( liftIO )
import Var
import Outputable
import FastString
import qualified ErrUtils as Err
import ErrUtils( Severity(..) )
import UniqSupply
import UniqFM       ( UniqFM, mapUFM, filterUFM )
import MonadUtils
import NameCache
import SrcLoc
import Data.List
import Data.Ord
import Data.Dynamic
import Data.IORef
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.Map.Strict as MapStrict
import Data.Word
import Control.Monad
import Control.Applicative ( Alternative(..) )

{-
************************************************************************
*                                                                      *
              The CoreToDo type and related types
          Abstraction of core-to-core passes to run.
*                                                                      *
************************************************************************
-}

data CoreToDo           -- These are diff core-to-core passes,
                        -- which may be invoked in any order,
                        -- as many times as you like.

  = CoreDoSimplify      -- The core-to-core simplifier.
        Int                    -- Max iterations
        SimplMode
  | CoreDoPluginPass String CorePluginPass
  | CoreDoFloatInwards
  | CoreDoFloatOutwards FloatOutSwitches
  | CoreLiberateCase
  | CoreDoPrintCore
  | CoreDoStaticArgs
  | CoreDoCallArity
  | CoreDoExitify
  | CoreDoStrictness
  | CoreDoWorkerWrapper
  | CoreDoSpecialising
  | CoreDoSpecConstr
  | CoreCSE
  | CoreDoRuleCheck CompilerPhase String   -- Check for non-application of rules
                                           -- matching this string
  | CoreDoNothing                -- Useful when building up
  | CoreDoPasses [CoreToDo]      -- lists of these things

  | CoreDesugar    -- Right after desugaring, no simple optimisation yet!
  | CoreDesugarOpt -- CoreDesugarXXX: Not strictly a core-to-core pass, but produces
                       --                 Core output, and hence useful to pass to endPass

  | CoreTidy
  | CorePrep
  | CoreOccurAnal

instance Outputable CoreToDo where
  ppr :: CoreToDo -> SDoc
ppr (CoreDoSimplify _ _)     = String -> SDoc
text "Simplifier"
  ppr (CoreDoPluginPass s :: String
s _)   = String -> SDoc
text "Core plugin: " SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
s
  ppr CoreDoFloatInwards       = String -> SDoc
text "Float inwards"
  ppr (CoreDoFloatOutwards f :: FloatOutSwitches
f)  = String -> SDoc
text "Float out" SDoc -> SDoc -> SDoc
<> SDoc -> SDoc
parens (FloatOutSwitches -> SDoc
forall a. Outputable a => a -> SDoc
ppr FloatOutSwitches
f)
  ppr CoreLiberateCase         = String -> SDoc
text "Liberate case"
  ppr CoreDoStaticArgs         = String -> SDoc
text "Static argument"
  ppr CoreDoCallArity          = String -> SDoc
text "Called arity analysis"
  ppr CoreDoExitify            = String -> SDoc
text "Exitification transformation"
  ppr CoreDoStrictness         = String -> SDoc
text "Demand analysis"
  ppr CoreDoWorkerWrapper      = String -> SDoc
text "Worker Wrapper binds"
  ppr CoreDoSpecialising       = String -> SDoc
text "Specialise"
  ppr CoreDoSpecConstr         = String -> SDoc
text "SpecConstr"
  ppr CoreCSE                  = String -> SDoc
text "Common sub-expression"
  ppr CoreDesugar              = String -> SDoc
text "Desugar (before optimization)"
  ppr CoreDesugarOpt           = String -> SDoc
text "Desugar (after optimization)"
  ppr CoreTidy                 = String -> SDoc
text "Tidy Core"
  ppr CorePrep                 = String -> SDoc
text "CorePrep"
  ppr CoreOccurAnal            = String -> SDoc
text "Occurrence analysis"
  ppr CoreDoPrintCore          = String -> SDoc
text "Print core"
  ppr (CoreDoRuleCheck {})     = String -> SDoc
text "Rule check"
  ppr CoreDoNothing            = String -> SDoc
text "CoreDoNothing"
  ppr (CoreDoPasses passes :: [CoreToDo]
passes)    = String -> SDoc
text "CoreDoPasses" SDoc -> SDoc -> SDoc
<+> [CoreToDo] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [CoreToDo]
passes

pprPassDetails :: CoreToDo -> SDoc
pprPassDetails :: CoreToDo -> SDoc
pprPassDetails (CoreDoSimplify n :: Int
n md :: SimplMode
md) = [SDoc] -> SDoc
vcat [ String -> SDoc
text "Max iterations =" SDoc -> SDoc -> SDoc
<+> Int -> SDoc
int Int
n
                                            , SimplMode -> SDoc
forall a. Outputable a => a -> SDoc
ppr SimplMode
md ]
pprPassDetails _ = SDoc
Outputable.empty

data SimplMode             -- See comments in SimplMonad
  = SimplMode
        { SimplMode -> [String]
sm_names      :: [String] -- Name(s) of the phase
        , SimplMode -> CompilerPhase
sm_phase      :: CompilerPhase
        , SimplMode -> DynFlags
sm_dflags     :: DynFlags -- Just for convenient non-monadic
                                    -- access; we don't override these
        , SimplMode -> Bool
sm_rules      :: Bool     -- Whether RULES are enabled
        , SimplMode -> Bool
sm_inline     :: Bool     -- Whether inlining is enabled
        , SimplMode -> Bool
sm_case_case  :: Bool     -- Whether case-of-case is enabled
        , SimplMode -> Bool
sm_eta_expand :: Bool     -- Whether eta-expansion is enabled
        }

instance Outputable SimplMode where
    ppr :: SimplMode -> SDoc
ppr (SimplMode { sm_phase :: SimplMode -> CompilerPhase
sm_phase = CompilerPhase
p, sm_names :: SimplMode -> [String]
sm_names = [String]
ss
                   , sm_rules :: SimplMode -> Bool
sm_rules = Bool
r, sm_inline :: SimplMode -> Bool
sm_inline = Bool
i
                   , sm_eta_expand :: SimplMode -> Bool
sm_eta_expand = Bool
eta, sm_case_case :: SimplMode -> Bool
sm_case_case = Bool
cc })
       = String -> SDoc
text "SimplMode" SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
braces (
         [SDoc] -> SDoc
sep [ String -> SDoc
text "Phase =" SDoc -> SDoc -> SDoc
<+> CompilerPhase -> SDoc
forall a. Outputable a => a -> SDoc
ppr CompilerPhase
p SDoc -> SDoc -> SDoc
<+>
               SDoc -> SDoc
brackets (String -> SDoc
text ([String] -> String
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ String -> [String] -> [String]
forall a. a -> [a] -> [a]
intersperse "," [String]
ss)) SDoc -> SDoc -> SDoc
<> SDoc
comma
             , Bool -> PtrString -> SDoc
pp_flag Bool
i   (String -> PtrString
sLit "inline") SDoc -> SDoc -> SDoc
<> SDoc
comma
             , Bool -> PtrString -> SDoc
pp_flag Bool
r   (String -> PtrString
sLit "rules") SDoc -> SDoc -> SDoc
<> SDoc
comma
             , Bool -> PtrString -> SDoc
pp_flag Bool
eta (String -> PtrString
sLit "eta-expand") SDoc -> SDoc -> SDoc
<> SDoc
comma
             , Bool -> PtrString -> SDoc
pp_flag Bool
cc  (String -> PtrString
sLit "case-of-case") ])
         where
           pp_flag :: Bool -> PtrString -> SDoc
pp_flag f :: Bool
f s :: PtrString
s = Bool -> SDoc -> SDoc
ppUnless Bool
f (String -> SDoc
text "no") SDoc -> SDoc -> SDoc
<+> PtrString -> SDoc
ptext PtrString
s

data FloatOutSwitches = FloatOutSwitches {
  FloatOutSwitches -> Maybe Int
floatOutLambdas   :: Maybe Int,  -- ^ Just n <=> float lambdas to top level, if
                                   -- doing so will abstract over n or fewer
                                   -- value variables
                                   -- Nothing <=> float all lambdas to top level,
                                   --             regardless of how many free variables
                                   -- Just 0 is the vanilla case: float a lambda
                                   --    iff it has no free vars

  FloatOutSwitches -> Bool
floatOutConstants :: Bool,       -- ^ True <=> float constants to top level,
                                   --            even if they do not escape a lambda
  FloatOutSwitches -> Bool
floatOutOverSatApps :: Bool,
                             -- ^ True <=> float out over-saturated applications
                             --            based on arity information.
                             -- See Note [Floating over-saturated applications]
                             -- in SetLevels
  FloatOutSwitches -> Bool
floatToTopLevelOnly :: Bool      -- ^ Allow floating to the top level only.
  }
instance Outputable FloatOutSwitches where
    ppr :: FloatOutSwitches -> SDoc
ppr = FloatOutSwitches -> SDoc
pprFloatOutSwitches

pprFloatOutSwitches :: FloatOutSwitches -> SDoc
pprFloatOutSwitches :: FloatOutSwitches -> SDoc
pprFloatOutSwitches sw :: FloatOutSwitches
sw
  = String -> SDoc
text "FOS" SDoc -> SDoc -> SDoc
<+> (SDoc -> SDoc
braces (SDoc -> SDoc) -> SDoc -> SDoc
forall a b. (a -> b) -> a -> b
$
     [SDoc] -> SDoc
sep ([SDoc] -> SDoc) -> [SDoc] -> SDoc
forall a b. (a -> b) -> a -> b
$ SDoc -> [SDoc] -> [SDoc]
punctuate SDoc
comma ([SDoc] -> [SDoc]) -> [SDoc] -> [SDoc]
forall a b. (a -> b) -> a -> b
$
     [ String -> SDoc
text "Lam ="    SDoc -> SDoc -> SDoc
<+> Maybe Int -> SDoc
forall a. Outputable a => a -> SDoc
ppr (FloatOutSwitches -> Maybe Int
floatOutLambdas FloatOutSwitches
sw)
     , String -> SDoc
text "Consts =" SDoc -> SDoc -> SDoc
<+> Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr (FloatOutSwitches -> Bool
floatOutConstants FloatOutSwitches
sw)
     , String -> SDoc
text "OverSatApps ="   SDoc -> SDoc -> SDoc
<+> Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr (FloatOutSwitches -> Bool
floatOutOverSatApps FloatOutSwitches
sw) ])

-- The core-to-core pass ordering is derived from the DynFlags:
runWhen :: Bool -> CoreToDo -> CoreToDo
runWhen :: Bool -> CoreToDo -> CoreToDo
runWhen True  do_this :: CoreToDo
do_this = CoreToDo
do_this
runWhen False _       = CoreToDo
CoreDoNothing

runMaybe :: Maybe a -> (a -> CoreToDo) -> CoreToDo
runMaybe :: Maybe a -> (a -> CoreToDo) -> CoreToDo
runMaybe (Just x :: a
x) f :: a -> CoreToDo
f = a -> CoreToDo
f a
x
runMaybe Nothing  _ = CoreToDo
CoreDoNothing

{-

************************************************************************
*                                                                      *
             Types for Plugins
*                                                                      *
************************************************************************
-}

-- | A description of the plugin pass itself
type CorePluginPass = ModGuts -> CoreM ModGuts

bindsOnlyPass :: (CoreProgram -> CoreM CoreProgram) -> ModGuts -> CoreM ModGuts
bindsOnlyPass :: (CoreProgram -> CoreM CoreProgram) -> ModGuts -> CoreM ModGuts
bindsOnlyPass pass :: CoreProgram -> CoreM CoreProgram
pass guts :: ModGuts
guts
  = do { CoreProgram
binds' <- CoreProgram -> CoreM CoreProgram
pass (ModGuts -> CoreProgram
mg_binds ModGuts
guts)
       ; ModGuts -> CoreM ModGuts
forall (m :: * -> *) a. Monad m => a -> m a
return (ModGuts
guts { mg_binds :: CoreProgram
mg_binds = CoreProgram
binds' }) }

{-
************************************************************************
*                                                                      *
             Counting and logging
*                                                                      *
************************************************************************
-}

getVerboseSimplStats :: (Bool -> SDoc) -> SDoc
getVerboseSimplStats :: (Bool -> SDoc) -> SDoc
getVerboseSimplStats = (Bool -> SDoc) -> SDoc
getPprDebug          -- For now, anyway

zeroSimplCount     :: DynFlags -> SimplCount
isZeroSimplCount   :: SimplCount -> Bool
hasDetailedCounts  :: SimplCount -> Bool
pprSimplCount      :: SimplCount -> SDoc
doSimplTick        :: DynFlags -> Tick -> SimplCount -> SimplCount
doFreeSimplTick    ::             Tick -> SimplCount -> SimplCount
plusSimplCount     :: SimplCount -> SimplCount -> SimplCount

data SimplCount
   = VerySimplCount !Int        -- Used when don't want detailed stats

   | SimplCount {
        SimplCount -> Int
ticks   :: !Int,        -- Total ticks
        SimplCount -> TickCounts
details :: !TickCounts, -- How many of each type

        SimplCount -> Int
n_log   :: !Int,        -- N
        SimplCount -> [Tick]
log1    :: [Tick],      -- Last N events; <= opt_HistorySize,
                                --   most recent first
        SimplCount -> [Tick]
log2    :: [Tick]       -- Last opt_HistorySize events before that
                                -- Having log1, log2 lets us accumulate the
                                -- recent history reasonably efficiently
     }

type TickCounts = Map Tick Int

simplCountN :: SimplCount -> Int
simplCountN :: SimplCount -> Int
simplCountN (VerySimplCount n :: Int
n)         = Int
n
simplCountN (SimplCount { ticks :: SimplCount -> Int
ticks = Int
n }) = Int
n

zeroSimplCount :: DynFlags -> SimplCount
zeroSimplCount dflags :: DynFlags
dflags
                -- This is where we decide whether to do
                -- the VerySimpl version or the full-stats version
  | DumpFlag -> DynFlags -> Bool
dopt DumpFlag
Opt_D_dump_simpl_stats DynFlags
dflags
  = $WSimplCount :: Int -> TickCounts -> Int -> [Tick] -> [Tick] -> SimplCount
SimplCount {ticks :: Int
ticks = 0, details :: TickCounts
details = TickCounts
forall k a. Map k a
Map.empty,
                n_log :: Int
n_log = 0, log1 :: [Tick]
log1 = [], log2 :: [Tick]
log2 = []}
  | Bool
otherwise
  = Int -> SimplCount
VerySimplCount 0

isZeroSimplCount :: SimplCount -> Bool
isZeroSimplCount (VerySimplCount n :: Int
n)         = Int
nInt -> Int -> Bool
forall a. Eq a => a -> a -> Bool
==0
isZeroSimplCount (SimplCount { ticks :: SimplCount -> Int
ticks = Int
n }) = Int
nInt -> Int -> Bool
forall a. Eq a => a -> a -> Bool
==0

hasDetailedCounts :: SimplCount -> Bool
hasDetailedCounts (VerySimplCount {}) = Bool
False
hasDetailedCounts (SimplCount {})     = Bool
True

doFreeSimplTick :: Tick -> SimplCount -> SimplCount
doFreeSimplTick tick :: Tick
tick sc :: SimplCount
sc@SimplCount { details :: SimplCount -> TickCounts
details = TickCounts
dts }
  = SimplCount
sc { details :: TickCounts
details = TickCounts
dts TickCounts -> Tick -> TickCounts
`addTick` Tick
tick }
doFreeSimplTick _ sc :: SimplCount
sc = SimplCount
sc

doSimplTick :: DynFlags -> Tick -> SimplCount -> SimplCount
doSimplTick dflags :: DynFlags
dflags tick :: Tick
tick
    sc :: SimplCount
sc@(SimplCount { ticks :: SimplCount -> Int
ticks = Int
tks, details :: SimplCount -> TickCounts
details = TickCounts
dts, n_log :: SimplCount -> Int
n_log = Int
nl, log1 :: SimplCount -> [Tick]
log1 = [Tick]
l1 })
  | Int
nl Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= DynFlags -> Int
historySize DynFlags
dflags = SimplCount
sc1 { n_log :: Int
n_log = 1, log1 :: [Tick]
log1 = [Tick
tick], log2 :: [Tick]
log2 = [Tick]
l1 }
  | Bool
otherwise                = SimplCount
sc1 { n_log :: Int
n_log = Int
nlInt -> Int -> Int
forall a. Num a => a -> a -> a
+1, log1 :: [Tick]
log1 = Tick
tick Tick -> [Tick] -> [Tick]
forall a. a -> [a] -> [a]
: [Tick]
l1 }
  where
    sc1 :: SimplCount
sc1 = SimplCount
sc { ticks :: Int
ticks = Int
tksInt -> Int -> Int
forall a. Num a => a -> a -> a
+1, details :: TickCounts
details = TickCounts
dts TickCounts -> Tick -> TickCounts
`addTick` Tick
tick }

doSimplTick _ _ (VerySimplCount n :: Int
n) = Int -> SimplCount
VerySimplCount (Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
+1)


addTick :: TickCounts -> Tick -> TickCounts
addTick :: TickCounts -> Tick -> TickCounts
addTick fm :: TickCounts
fm tick :: Tick
tick = (Int -> Int -> Int) -> Tick -> Int -> TickCounts -> TickCounts
forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
MapStrict.insertWith Int -> Int -> Int
forall a. Num a => a -> a -> a
(+) Tick
tick 1 TickCounts
fm

plusSimplCount :: SimplCount -> SimplCount -> SimplCount
plusSimplCount sc1 :: SimplCount
sc1@(SimplCount { ticks :: SimplCount -> Int
ticks = Int
tks1, details :: SimplCount -> TickCounts
details = TickCounts
dts1 })
               sc2 :: SimplCount
sc2@(SimplCount { ticks :: SimplCount -> Int
ticks = Int
tks2, details :: SimplCount -> TickCounts
details = TickCounts
dts2 })
  = SimplCount
log_base { ticks :: Int
ticks = Int
tks1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
tks2
             , details :: TickCounts
details = (Int -> Int -> Int) -> TickCounts -> TickCounts -> TickCounts
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
MapStrict.unionWith Int -> Int -> Int
forall a. Num a => a -> a -> a
(+) TickCounts
dts1 TickCounts
dts2 }
  where
        -- A hackish way of getting recent log info
    log_base :: SimplCount
log_base | [Tick] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (SimplCount -> [Tick]
log1 SimplCount
sc2) = SimplCount
sc1    -- Nothing at all in sc2
             | [Tick] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (SimplCount -> [Tick]
log2 SimplCount
sc2) = SimplCount
sc2 { log2 :: [Tick]
log2 = SimplCount -> [Tick]
log1 SimplCount
sc1 }
             | Bool
otherwise       = SimplCount
sc2

plusSimplCount (VerySimplCount n :: Int
n) (VerySimplCount m :: Int
m) = Int -> SimplCount
VerySimplCount (Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
+Int
m)
plusSimplCount _                  _                  = String -> SimplCount
forall a. String -> a
panic "plusSimplCount"
       -- We use one or the other consistently

pprSimplCount :: SimplCount -> SDoc
pprSimplCount (VerySimplCount n :: Int
n) = String -> SDoc
text "Total ticks:" SDoc -> SDoc -> SDoc
<+> Int -> SDoc
int Int
n
pprSimplCount (SimplCount { ticks :: SimplCount -> Int
ticks = Int
tks, details :: SimplCount -> TickCounts
details = TickCounts
dts, log1 :: SimplCount -> [Tick]
log1 = [Tick]
l1, log2 :: SimplCount -> [Tick]
log2 = [Tick]
l2 })
  = [SDoc] -> SDoc
vcat [String -> SDoc
text "Total ticks:    " SDoc -> SDoc -> SDoc
<+> Int -> SDoc
int Int
tks,
          SDoc
blankLine,
          TickCounts -> SDoc
pprTickCounts TickCounts
dts,
          (Bool -> SDoc) -> SDoc
getVerboseSimplStats ((Bool -> SDoc) -> SDoc) -> (Bool -> SDoc) -> SDoc
forall a b. (a -> b) -> a -> b
$ \dbg :: Bool
dbg -> if Bool
dbg
          then
                [SDoc] -> SDoc
vcat [SDoc
blankLine,
                      String -> SDoc
text "Log (most recent first)",
                      Int -> SDoc -> SDoc
nest 4 ([SDoc] -> SDoc
vcat ((Tick -> SDoc) -> [Tick] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map Tick -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Tick]
l1) SDoc -> SDoc -> SDoc
$$ [SDoc] -> SDoc
vcat ((Tick -> SDoc) -> [Tick] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map Tick -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Tick]
l2))]
          else SDoc
Outputable.empty
    ]

{- Note [Which transformations are innocuous]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
At one point (Jun 18) I wondered if some transformations (ticks)
might be  "innocuous", in the sense that they do not unlock a later
transformation that does not occur in the same pass.  If so, we could
refrain from bumping the overall tick-count for such innocuous
transformations, and perhaps terminate the simplifier one pass
earlier.

BUt alas I found that virtually nothing was innocuous!  This Note
just records what I learned, in case anyone wants to try again.

These transformations are not innocuous:

*** NB: I think these ones could be made innocuous
          EtaExpansion
          LetFloatFromLet

LetFloatFromLet
    x = K (let z = e2 in Just z)
  prepareRhs transforms to
    x2 = let z=e2 in Just z
    x  = K xs
  And now more let-floating can happen in the
  next pass, on x2

PreInlineUnconditionally
  Example in spectral/cichelli/Auxil
     hinsert = ...let lo = e in
                  let j = ...lo... in
                  case x of
                    False -> ()
                    True -> case lo of I# lo' ->
                              ...j...
  When we PreInlineUnconditionally j, lo's occ-info changes to once,
  so it can be PreInlineUnconditionally in the next pass, and a
  cascade of further things can happen.

PostInlineUnconditionally
  let x = e in
  let y = ...x.. in
  case .. of { A -> ...x...y...
               B -> ...x...y... }
  Current postinlineUnconditinaly will inline y, and then x; sigh.

  But PostInlineUnconditionally might also unlock subsequent
  transformations for the same reason as PreInlineUnconditionally,
  so it's probably not innocuous anyway.

KnownBranch, BetaReduction:
  May drop chunks of code, and thereby enable PreInlineUnconditionally
  for some let-binding which now occurs once

EtaExpansion:
  Example in imaginary/digits-of-e1
    fail = \void. e          where e :: IO ()
  --> etaExpandRhs
    fail = \void. (\s. (e |> g) s) |> sym g      where g :: IO () ~ S -> (S,())
  --> Next iteration of simplify
    fail1 = \void. \s. (e |> g) s
    fail = fail1 |> Void#->sym g
  And now inline 'fail'

CaseMerge:
  case x of y {
    DEFAULT -> case y of z { pi -> ei }
    alts2 }
  ---> CaseMerge
    case x of { pi -> let z = y in ei
              ; alts2 }
  The "let z=y" case-binder-swap gets dealt with in the next pass
-}

pprTickCounts :: Map Tick Int -> SDoc
pprTickCounts :: TickCounts -> SDoc
pprTickCounts counts :: TickCounts
counts
  = [SDoc] -> SDoc
vcat (([(Tick, Int)] -> SDoc) -> [[(Tick, Int)]] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map [(Tick, Int)] -> SDoc
pprTickGroup [[(Tick, Int)]]
groups)
  where
    groups :: [[(Tick,Int)]]    -- Each group shares a comon tag
                                -- toList returns common tags adjacent
    groups :: [[(Tick, Int)]]
groups = ((Tick, Int) -> (Tick, Int) -> Bool)
-> [(Tick, Int)] -> [[(Tick, Int)]]
forall a. (a -> a -> Bool) -> [a] -> [[a]]
groupBy (Tick, Int) -> (Tick, Int) -> Bool
forall b b. (Tick, b) -> (Tick, b) -> Bool
same_tag (TickCounts -> [(Tick, Int)]
forall k a. Map k a -> [(k, a)]
Map.toList TickCounts
counts)
    same_tag :: (Tick, b) -> (Tick, b) -> Bool
same_tag (tick1 :: Tick
tick1,_) (tick2 :: Tick
tick2,_) = Tick -> Int
tickToTag Tick
tick1 Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Tick -> Int
tickToTag Tick
tick2

pprTickGroup :: [(Tick, Int)] -> SDoc
pprTickGroup :: [(Tick, Int)] -> SDoc
pprTickGroup group :: [(Tick, Int)]
group@((tick1 :: Tick
tick1,_):_)
  = SDoc -> Int -> SDoc -> SDoc
hang (Int -> SDoc
int ([Int] -> Int
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Int
n | (_,n :: Int
n) <- [(Tick, Int)]
group]) SDoc -> SDoc -> SDoc
<+> String -> SDoc
text (Tick -> String
tickString Tick
tick1))
       2 ([SDoc] -> SDoc
vcat [ Int -> SDoc
int Int
n SDoc -> SDoc -> SDoc
<+> Tick -> SDoc
pprTickCts Tick
tick
                                    -- flip as we want largest first
               | (tick :: Tick
tick,n :: Int
n) <- ((Tick, Int) -> (Tick, Int) -> Ordering)
-> [(Tick, Int)] -> [(Tick, Int)]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy (((Tick, Int) -> (Tick, Int) -> Ordering)
-> (Tick, Int) -> (Tick, Int) -> Ordering
forall a b c. (a -> b -> c) -> b -> a -> c
flip (((Tick, Int) -> Int) -> (Tick, Int) -> (Tick, Int) -> Ordering
forall a b. Ord a => (b -> a) -> b -> b -> Ordering
comparing (Tick, Int) -> Int
forall a b. (a, b) -> b
snd)) [(Tick, Int)]
group])
pprTickGroup [] = String -> SDoc
forall a. String -> a
panic "pprTickGroup"

data Tick  -- See Note [Which transformations are innocuous]
  = PreInlineUnconditionally    Id
  | PostInlineUnconditionally   Id

  | UnfoldingDone               Id
  | RuleFired                   FastString      -- Rule name

  | LetFloatFromLet
  | EtaExpansion                Id      -- LHS binder
  | EtaReduction                Id      -- Binder on outer lambda
  | BetaReduction               Id      -- Lambda binder


  | CaseOfCase                  Id      -- Bndr on *inner* case
  | KnownBranch                 Id      -- Case binder
  | CaseMerge                   Id      -- Binder on outer case
  | AltMerge                    Id      -- Case binder
  | CaseElim                    Id      -- Case binder
  | CaseIdentity                Id      -- Case binder
  | FillInCaseDefault           Id      -- Case binder

  | SimplifierDone              -- Ticked at each iteration of the simplifier

instance Outputable Tick where
  ppr :: Tick -> SDoc
ppr tick :: Tick
tick = String -> SDoc
text (Tick -> String
tickString Tick
tick) SDoc -> SDoc -> SDoc
<+> Tick -> SDoc
pprTickCts Tick
tick

instance Eq Tick where
  a :: Tick
a == :: Tick -> Tick -> Bool
== b :: Tick
b = case Tick
a Tick -> Tick -> Ordering
`cmpTick` Tick
b of
           EQ -> Bool
True
           _ -> Bool
False

instance Ord Tick where
  compare :: Tick -> Tick -> Ordering
compare = Tick -> Tick -> Ordering
cmpTick

tickToTag :: Tick -> Int
tickToTag :: Tick -> Int
tickToTag (PreInlineUnconditionally _)  = 0
tickToTag (PostInlineUnconditionally _) = 1
tickToTag (UnfoldingDone _)             = 2
tickToTag (RuleFired _)                 = 3
tickToTag LetFloatFromLet               = 4
tickToTag (EtaExpansion _)              = 5
tickToTag (EtaReduction _)              = 6
tickToTag (BetaReduction _)             = 7
tickToTag (CaseOfCase _)                = 8
tickToTag (KnownBranch _)               = 9
tickToTag (CaseMerge _)                 = 10
tickToTag (CaseElim _)                  = 11
tickToTag (CaseIdentity _)              = 12
tickToTag (FillInCaseDefault _)         = 13
tickToTag SimplifierDone                = 16
tickToTag (AltMerge _)                  = 17

tickString :: Tick -> String
tickString :: Tick -> String
tickString (PreInlineUnconditionally _) = "PreInlineUnconditionally"
tickString (PostInlineUnconditionally _)= "PostInlineUnconditionally"
tickString (UnfoldingDone _)            = "UnfoldingDone"
tickString (RuleFired _)                = "RuleFired"
tickString LetFloatFromLet              = "LetFloatFromLet"
tickString (EtaExpansion _)             = "EtaExpansion"
tickString (EtaReduction _)             = "EtaReduction"
tickString (BetaReduction _)            = "BetaReduction"
tickString (CaseOfCase _)               = "CaseOfCase"
tickString (KnownBranch _)              = "KnownBranch"
tickString (CaseMerge _)                = "CaseMerge"
tickString (AltMerge _)                 = "AltMerge"
tickString (CaseElim _)                 = "CaseElim"
tickString (CaseIdentity _)             = "CaseIdentity"
tickString (FillInCaseDefault _)        = "FillInCaseDefault"
tickString SimplifierDone               = "SimplifierDone"

pprTickCts :: Tick -> SDoc
pprTickCts :: Tick -> SDoc
pprTickCts (PreInlineUnconditionally v :: Id
v) = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
v
pprTickCts (PostInlineUnconditionally v :: Id
v)= Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
v
pprTickCts (UnfoldingDone v :: Id
v)            = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
v
pprTickCts (RuleFired v :: FastString
v)                = FastString -> SDoc
forall a. Outputable a => a -> SDoc
ppr FastString
v
pprTickCts LetFloatFromLet              = SDoc
Outputable.empty
pprTickCts (EtaExpansion v :: Id
v)             = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
v
pprTickCts (EtaReduction v :: Id
v)             = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
v
pprTickCts (BetaReduction v :: Id
v)            = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
v
pprTickCts (CaseOfCase v :: Id
v)               = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
v
pprTickCts (KnownBranch v :: Id
v)              = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
v
pprTickCts (CaseMerge v :: Id
v)                = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
v
pprTickCts (AltMerge v :: Id
v)                 = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
v
pprTickCts (CaseElim v :: Id
v)                 = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
v
pprTickCts (CaseIdentity v :: Id
v)             = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
v
pprTickCts (FillInCaseDefault v :: Id
v)        = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
v
pprTickCts _                            = SDoc
Outputable.empty

cmpTick :: Tick -> Tick -> Ordering
cmpTick :: Tick -> Tick -> Ordering
cmpTick a :: Tick
a b :: Tick
b = case (Tick -> Int
tickToTag Tick
a Int -> Int -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Tick -> Int
tickToTag Tick
b) of
                GT -> Ordering
GT
                EQ -> Tick -> Tick -> Ordering
cmpEqTick Tick
a Tick
b
                LT -> Ordering
LT

cmpEqTick :: Tick -> Tick -> Ordering
cmpEqTick :: Tick -> Tick -> Ordering
cmpEqTick (PreInlineUnconditionally a :: Id
a)  (PreInlineUnconditionally b :: Id
b)    = Id
a Id -> Id -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Id
b
cmpEqTick (PostInlineUnconditionally a :: Id
a) (PostInlineUnconditionally b :: Id
b)   = Id
a Id -> Id -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Id
b
cmpEqTick (UnfoldingDone a :: Id
a)             (UnfoldingDone b :: Id
b)               = Id
a Id -> Id -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Id
b
cmpEqTick (RuleFired a :: FastString
a)                 (RuleFired b :: FastString
b)                   = FastString
a FastString -> FastString -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` FastString
b
cmpEqTick (EtaExpansion a :: Id
a)              (EtaExpansion b :: Id
b)                = Id
a Id -> Id -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Id
b
cmpEqTick (EtaReduction a :: Id
a)              (EtaReduction b :: Id
b)                = Id
a Id -> Id -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Id
b
cmpEqTick (BetaReduction a :: Id
a)             (BetaReduction b :: Id
b)               = Id
a Id -> Id -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Id
b
cmpEqTick (CaseOfCase a :: Id
a)                (CaseOfCase b :: Id
b)                  = Id
a Id -> Id -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Id
b
cmpEqTick (KnownBranch a :: Id
a)               (KnownBranch b :: Id
b)                 = Id
a Id -> Id -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Id
b
cmpEqTick (CaseMerge a :: Id
a)                 (CaseMerge b :: Id
b)                   = Id
a Id -> Id -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Id
b
cmpEqTick (AltMerge a :: Id
a)                  (AltMerge b :: Id
b)                    = Id
a Id -> Id -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Id
b
cmpEqTick (CaseElim a :: Id
a)                  (CaseElim b :: Id
b)                    = Id
a Id -> Id -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Id
b
cmpEqTick (CaseIdentity a :: Id
a)              (CaseIdentity b :: Id
b)                = Id
a Id -> Id -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Id
b
cmpEqTick (FillInCaseDefault a :: Id
a)         (FillInCaseDefault b :: Id
b)           = Id
a Id -> Id -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Id
b
cmpEqTick _                             _                               = Ordering
EQ

{-
************************************************************************
*                                                                      *
             Monad and carried data structure definitions
*                                                                      *
************************************************************************
-}

newtype CoreState = CoreState {
        CoreState -> UniqSupply
cs_uniq_supply :: UniqSupply
}

data CoreReader = CoreReader {
        CoreReader -> HscEnv
cr_hsc_env             :: HscEnv,
        CoreReader -> RuleBase
cr_rule_base           :: RuleBase,
        CoreReader -> Module
cr_module              :: Module,
        CoreReader -> PrintUnqualified
cr_print_unqual        :: PrintUnqualified,
        CoreReader -> SrcSpan
cr_loc                 :: SrcSpan,   -- Use this for log/error messages so they
                                             -- are at least tagged with the right source file
        CoreReader -> ModuleSet
cr_visible_orphan_mods :: !ModuleSet
}

-- Note: CoreWriter used to be defined with data, rather than newtype.  If it
-- is defined that way again, the cw_simpl_count field, at least, must be
-- strict to avoid a space leak (Trac #7702).
newtype CoreWriter = CoreWriter {
        CoreWriter -> SimplCount
cw_simpl_count :: SimplCount
}

emptyWriter :: DynFlags -> CoreWriter
emptyWriter :: DynFlags -> CoreWriter
emptyWriter dflags :: DynFlags
dflags = CoreWriter :: SimplCount -> CoreWriter
CoreWriter {
        cw_simpl_count :: SimplCount
cw_simpl_count = DynFlags -> SimplCount
zeroSimplCount DynFlags
dflags
    }

plusWriter :: CoreWriter -> CoreWriter -> CoreWriter
plusWriter :: CoreWriter -> CoreWriter -> CoreWriter
plusWriter w1 :: CoreWriter
w1 w2 :: CoreWriter
w2 = CoreWriter :: SimplCount -> CoreWriter
CoreWriter {
        cw_simpl_count :: SimplCount
cw_simpl_count = (CoreWriter -> SimplCount
cw_simpl_count CoreWriter
w1) SimplCount -> SimplCount -> SimplCount
`plusSimplCount` (CoreWriter -> SimplCount
cw_simpl_count CoreWriter
w2)
    }

type CoreIOEnv = IOEnv CoreReader

-- | The monad used by Core-to-Core passes to access common state, register simplification
-- statistics and so on
newtype CoreM a = CoreM { CoreM a -> CoreState -> CoreIOEnv (a, CoreState, CoreWriter)
unCoreM :: CoreState -> CoreIOEnv (a, CoreState, CoreWriter) }

instance Functor CoreM where
    fmap :: (a -> b) -> CoreM a -> CoreM b
fmap = (a -> b) -> CoreM a -> CoreM b
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM

instance Monad CoreM where
    mx :: CoreM a
mx >>= :: CoreM a -> (a -> CoreM b) -> CoreM b
>>= f :: a -> CoreM b
f = (CoreState -> CoreIOEnv (b, CoreState, CoreWriter)) -> CoreM b
forall a.
(CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
CoreM ((CoreState -> CoreIOEnv (b, CoreState, CoreWriter)) -> CoreM b)
-> (CoreState -> CoreIOEnv (b, CoreState, CoreWriter)) -> CoreM b
forall a b. (a -> b) -> a -> b
$ \s :: CoreState
s -> do
            (x :: a
x, s' :: CoreState
s', w1 :: CoreWriter
w1) <- CoreM a -> CoreState -> CoreIOEnv (a, CoreState, CoreWriter)
forall a.
CoreM a -> CoreState -> CoreIOEnv (a, CoreState, CoreWriter)
unCoreM CoreM a
mx CoreState
s
            (y :: b
y, s'' :: CoreState
s'', w2 :: CoreWriter
w2) <- CoreM b -> CoreState -> CoreIOEnv (b, CoreState, CoreWriter)
forall a.
CoreM a -> CoreState -> CoreIOEnv (a, CoreState, CoreWriter)
unCoreM (a -> CoreM b
f a
x) CoreState
s'
            let w :: CoreWriter
w = CoreWriter
w1 CoreWriter -> CoreWriter -> CoreWriter
`plusWriter` CoreWriter
w2
            (b, CoreState, CoreWriter) -> CoreIOEnv (b, CoreState, CoreWriter)
forall (m :: * -> *) a. Monad m => a -> m a
return ((b, CoreState, CoreWriter)
 -> CoreIOEnv (b, CoreState, CoreWriter))
-> (b, CoreState, CoreWriter)
-> CoreIOEnv (b, CoreState, CoreWriter)
forall a b. (a -> b) -> a -> b
$ CoreWriter
-> (b, CoreState, CoreWriter) -> (b, CoreState, CoreWriter)
forall a b. a -> b -> b
seq CoreWriter
w (b
y, CoreState
s'', CoreWriter
w)
            -- forcing w before building the tuple avoids a space leak
            -- (Trac #7702)

instance Applicative CoreM where
    pure :: a -> CoreM a
pure x :: a
x = (CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
forall a.
(CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
CoreM ((CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a)
-> (CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
forall a b. (a -> b) -> a -> b
$ \s :: CoreState
s -> CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
forall a. CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
nop CoreState
s a
x
    <*> :: CoreM (a -> b) -> CoreM a -> CoreM b
(<*>) = CoreM (a -> b) -> CoreM a -> CoreM b
forall (m :: * -> *) a b. Monad m => m (a -> b) -> m a -> m b
ap
    m :: CoreM a
m *> :: CoreM a -> CoreM b -> CoreM b
*> k :: CoreM b
k = CoreM a
m CoreM a -> (a -> CoreM b) -> CoreM b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \_ -> CoreM b
k

instance Alternative CoreM where
    empty :: CoreM a
empty   = (CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
forall a.
(CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
CoreM (CoreIOEnv (a, CoreState, CoreWriter)
-> CoreState -> CoreIOEnv (a, CoreState, CoreWriter)
forall a b. a -> b -> a
const CoreIOEnv (a, CoreState, CoreWriter)
forall (f :: * -> *) a. Alternative f => f a
Control.Applicative.empty)
    m :: CoreM a
m <|> :: CoreM a -> CoreM a -> CoreM a
<|> n :: CoreM a
n = (CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
forall a.
(CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
CoreM (\rs :: CoreState
rs -> CoreM a -> CoreState -> CoreIOEnv (a, CoreState, CoreWriter)
forall a.
CoreM a -> CoreState -> CoreIOEnv (a, CoreState, CoreWriter)
unCoreM CoreM a
m CoreState
rs CoreIOEnv (a, CoreState, CoreWriter)
-> CoreIOEnv (a, CoreState, CoreWriter)
-> CoreIOEnv (a, CoreState, CoreWriter)
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> CoreM a -> CoreState -> CoreIOEnv (a, CoreState, CoreWriter)
forall a.
CoreM a -> CoreState -> CoreIOEnv (a, CoreState, CoreWriter)
unCoreM CoreM a
n CoreState
rs)

instance MonadPlus CoreM

instance MonadUnique CoreM where
    getUniqueSupplyM :: CoreM UniqSupply
getUniqueSupplyM = do
        UniqSupply
us <- (CoreState -> UniqSupply) -> CoreM UniqSupply
forall a. (CoreState -> a) -> CoreM a
getS CoreState -> UniqSupply
cs_uniq_supply
        let (us1 :: UniqSupply
us1, us2 :: UniqSupply
us2) = UniqSupply -> (UniqSupply, UniqSupply)
splitUniqSupply UniqSupply
us
        (CoreState -> CoreState) -> CoreM ()
modifyS (\s :: CoreState
s -> CoreState
s { cs_uniq_supply :: UniqSupply
cs_uniq_supply = UniqSupply
us2 })
        UniqSupply -> CoreM UniqSupply
forall (m :: * -> *) a. Monad m => a -> m a
return UniqSupply
us1

    getUniqueM :: CoreM Unique
getUniqueM = do
        UniqSupply
us <- (CoreState -> UniqSupply) -> CoreM UniqSupply
forall a. (CoreState -> a) -> CoreM a
getS CoreState -> UniqSupply
cs_uniq_supply
        let (u :: Unique
u,us' :: UniqSupply
us') = UniqSupply -> (Unique, UniqSupply)
takeUniqFromSupply UniqSupply
us
        (CoreState -> CoreState) -> CoreM ()
modifyS (\s :: CoreState
s -> CoreState
s { cs_uniq_supply :: UniqSupply
cs_uniq_supply = UniqSupply
us' })
        Unique -> CoreM Unique
forall (m :: * -> *) a. Monad m => a -> m a
return Unique
u

runCoreM :: HscEnv
         -> RuleBase
         -> UniqSupply
         -> Module
         -> ModuleSet
         -> PrintUnqualified
         -> SrcSpan
         -> CoreM a
         -> IO (a, SimplCount)
runCoreM :: HscEnv
-> RuleBase
-> UniqSupply
-> Module
-> ModuleSet
-> PrintUnqualified
-> SrcSpan
-> CoreM a
-> IO (a, SimplCount)
runCoreM hsc_env :: HscEnv
hsc_env rule_base :: RuleBase
rule_base us :: UniqSupply
us mod :: Module
mod orph_imps :: ModuleSet
orph_imps print_unqual :: PrintUnqualified
print_unqual loc :: SrcSpan
loc m :: CoreM a
m
  = ((a, CoreState, CoreWriter) -> (a, SimplCount))
-> IO (a, CoreState, CoreWriter) -> IO (a, SimplCount)
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM (a, CoreState, CoreWriter) -> (a, SimplCount)
forall a. (a, CoreState, CoreWriter) -> (a, SimplCount)
extract (IO (a, CoreState, CoreWriter) -> IO (a, SimplCount))
-> IO (a, CoreState, CoreWriter) -> IO (a, SimplCount)
forall a b. (a -> b) -> a -> b
$ CoreReader
-> IOEnv CoreReader (a, CoreState, CoreWriter)
-> IO (a, CoreState, CoreWriter)
forall env a. env -> IOEnv env a -> IO a
runIOEnv CoreReader
reader (IOEnv CoreReader (a, CoreState, CoreWriter)
 -> IO (a, CoreState, CoreWriter))
-> IOEnv CoreReader (a, CoreState, CoreWriter)
-> IO (a, CoreState, CoreWriter)
forall a b. (a -> b) -> a -> b
$ CoreM a -> CoreState -> IOEnv CoreReader (a, CoreState, CoreWriter)
forall a.
CoreM a -> CoreState -> CoreIOEnv (a, CoreState, CoreWriter)
unCoreM CoreM a
m CoreState
state
  where
    reader :: CoreReader
reader = $WCoreReader :: HscEnv
-> RuleBase
-> Module
-> PrintUnqualified
-> SrcSpan
-> ModuleSet
-> CoreReader
CoreReader {
            cr_hsc_env :: HscEnv
cr_hsc_env = HscEnv
hsc_env,
            cr_rule_base :: RuleBase
cr_rule_base = RuleBase
rule_base,
            cr_module :: Module
cr_module = Module
mod,
            cr_visible_orphan_mods :: ModuleSet
cr_visible_orphan_mods = ModuleSet
orph_imps,
            cr_print_unqual :: PrintUnqualified
cr_print_unqual = PrintUnqualified
print_unqual,
            cr_loc :: SrcSpan
cr_loc = SrcSpan
loc
        }
    state :: CoreState
state = CoreState :: UniqSupply -> CoreState
CoreState {
            cs_uniq_supply :: UniqSupply
cs_uniq_supply = UniqSupply
us
        }

    extract :: (a, CoreState, CoreWriter) -> (a, SimplCount)
    extract :: (a, CoreState, CoreWriter) -> (a, SimplCount)
extract (value :: a
value, _, writer :: CoreWriter
writer) = (a
value, CoreWriter -> SimplCount
cw_simpl_count CoreWriter
writer)

{-
************************************************************************
*                                                                      *
             Core combinators, not exported
*                                                                      *
************************************************************************
-}

nop :: CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
nop :: CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
nop s :: CoreState
s x :: a
x = do
    CoreReader
r <- IOEnv CoreReader CoreReader
forall env. IOEnv env env
getEnv
    (a, CoreState, CoreWriter) -> CoreIOEnv (a, CoreState, CoreWriter)
forall (m :: * -> *) a. Monad m => a -> m a
return (a
x, CoreState
s, DynFlags -> CoreWriter
emptyWriter (DynFlags -> CoreWriter) -> DynFlags -> CoreWriter
forall a b. (a -> b) -> a -> b
$ (HscEnv -> DynFlags
hsc_dflags (HscEnv -> DynFlags)
-> (CoreReader -> HscEnv) -> CoreReader -> DynFlags
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CoreReader -> HscEnv
cr_hsc_env) CoreReader
r)

read :: (CoreReader -> a) -> CoreM a
read :: (CoreReader -> a) -> CoreM a
read f :: CoreReader -> a
f = (CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
forall a.
(CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
CoreM (\s :: CoreState
s -> IOEnv CoreReader CoreReader
forall env. IOEnv env env
getEnv IOEnv CoreReader CoreReader
-> (CoreReader -> CoreIOEnv (a, CoreState, CoreWriter))
-> CoreIOEnv (a, CoreState, CoreWriter)
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (\r :: CoreReader
r -> CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
forall a. CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
nop CoreState
s (CoreReader -> a
f CoreReader
r)))

getS :: (CoreState -> a) -> CoreM a
getS :: (CoreState -> a) -> CoreM a
getS f :: CoreState -> a
f = (CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
forall a.
(CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
CoreM (\s :: CoreState
s -> CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
forall a. CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
nop CoreState
s (CoreState -> a
f CoreState
s))

modifyS :: (CoreState -> CoreState) -> CoreM ()
modifyS :: (CoreState -> CoreState) -> CoreM ()
modifyS f :: CoreState -> CoreState
f = (CoreState -> CoreIOEnv ((), CoreState, CoreWriter)) -> CoreM ()
forall a.
(CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
CoreM (\s :: CoreState
s -> CoreState -> () -> CoreIOEnv ((), CoreState, CoreWriter)
forall a. CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
nop (CoreState -> CoreState
f CoreState
s) ())

write :: CoreWriter -> CoreM ()
write :: CoreWriter -> CoreM ()
write w :: CoreWriter
w = (CoreState -> CoreIOEnv ((), CoreState, CoreWriter)) -> CoreM ()
forall a.
(CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
CoreM (\s :: CoreState
s -> ((), CoreState, CoreWriter)
-> CoreIOEnv ((), CoreState, CoreWriter)
forall (m :: * -> *) a. Monad m => a -> m a
return ((), CoreState
s, CoreWriter
w))

-- \subsection{Lifting IO into the monad}

-- | Lift an 'IOEnv' operation into 'CoreM'
liftIOEnv :: CoreIOEnv a -> CoreM a
liftIOEnv :: CoreIOEnv a -> CoreM a
liftIOEnv mx :: CoreIOEnv a
mx = (CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
forall a.
(CoreState -> CoreIOEnv (a, CoreState, CoreWriter)) -> CoreM a
CoreM (\s :: CoreState
s -> CoreIOEnv a
mx CoreIOEnv a
-> (a -> CoreIOEnv (a, CoreState, CoreWriter))
-> CoreIOEnv (a, CoreState, CoreWriter)
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (\x :: a
x -> CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
forall a. CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
nop CoreState
s a
x))

instance MonadIO CoreM where
    liftIO :: IO a -> CoreM a
liftIO = CoreIOEnv a -> CoreM a
forall a. CoreIOEnv a -> CoreM a
liftIOEnv (CoreIOEnv a -> CoreM a)
-> (IO a -> CoreIOEnv a) -> IO a -> CoreM a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IO a -> CoreIOEnv a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
IOEnv.liftIO

-- | Lift an 'IO' operation into 'CoreM' while consuming its 'SimplCount'
liftIOWithCount :: IO (SimplCount, a) -> CoreM a
liftIOWithCount :: IO (SimplCount, a) -> CoreM a
liftIOWithCount what :: IO (SimplCount, a)
what = IO (SimplCount, a) -> CoreM (SimplCount, a)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO IO (SimplCount, a)
what CoreM (SimplCount, a) -> ((SimplCount, a) -> CoreM a) -> CoreM a
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (\(count :: SimplCount
count, x :: a
x) -> SimplCount -> CoreM ()
addSimplCount SimplCount
count CoreM () -> CoreM a -> CoreM a
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> a -> CoreM a
forall (m :: * -> *) a. Monad m => a -> m a
return a
x)

{-
************************************************************************
*                                                                      *
             Reader, writer and state accessors
*                                                                      *
************************************************************************
-}

getHscEnv :: CoreM HscEnv
getHscEnv :: CoreM HscEnv
getHscEnv = (CoreReader -> HscEnv) -> CoreM HscEnv
forall a. (CoreReader -> a) -> CoreM a
read CoreReader -> HscEnv
cr_hsc_env

getRuleBase :: CoreM RuleBase
getRuleBase :: CoreM RuleBase
getRuleBase = (CoreReader -> RuleBase) -> CoreM RuleBase
forall a. (CoreReader -> a) -> CoreM a
read CoreReader -> RuleBase
cr_rule_base

getVisibleOrphanMods :: CoreM ModuleSet
getVisibleOrphanMods :: CoreM ModuleSet
getVisibleOrphanMods = (CoreReader -> ModuleSet) -> CoreM ModuleSet
forall a. (CoreReader -> a) -> CoreM a
read CoreReader -> ModuleSet
cr_visible_orphan_mods

getPrintUnqualified :: CoreM PrintUnqualified
getPrintUnqualified :: CoreM PrintUnqualified
getPrintUnqualified = (CoreReader -> PrintUnqualified) -> CoreM PrintUnqualified
forall a. (CoreReader -> a) -> CoreM a
read CoreReader -> PrintUnqualified
cr_print_unqual

getSrcSpanM :: CoreM SrcSpan
getSrcSpanM :: CoreM SrcSpan
getSrcSpanM = (CoreReader -> SrcSpan) -> CoreM SrcSpan
forall a. (CoreReader -> a) -> CoreM a
read CoreReader -> SrcSpan
cr_loc

addSimplCount :: SimplCount -> CoreM ()
addSimplCount :: SimplCount -> CoreM ()
addSimplCount count :: SimplCount
count = CoreWriter -> CoreM ()
write (CoreWriter :: SimplCount -> CoreWriter
CoreWriter { cw_simpl_count :: SimplCount
cw_simpl_count = SimplCount
count })

-- Convenience accessors for useful fields of HscEnv

instance HasDynFlags CoreM where
    getDynFlags :: CoreM DynFlags
getDynFlags = (HscEnv -> DynFlags) -> CoreM HscEnv -> CoreM DynFlags
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap HscEnv -> DynFlags
hsc_dflags CoreM HscEnv
getHscEnv

instance HasModule CoreM where
    getModule :: CoreM Module
getModule = (CoreReader -> Module) -> CoreM Module
forall a. (CoreReader -> a) -> CoreM a
read CoreReader -> Module
cr_module

-- | The original name cache is the current mapping from 'Module' and
-- 'OccName' to a compiler-wide unique 'Name'
getOrigNameCache :: CoreM OrigNameCache
getOrigNameCache :: CoreM OrigNameCache
getOrigNameCache = do
    IORef NameCache
nameCacheRef <- (HscEnv -> IORef NameCache)
-> CoreM HscEnv -> CoreM (IORef NameCache)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap HscEnv -> IORef NameCache
hsc_NC CoreM HscEnv
getHscEnv
    IO OrigNameCache -> CoreM OrigNameCache
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO OrigNameCache -> CoreM OrigNameCache)
-> IO OrigNameCache -> CoreM OrigNameCache
forall a b. (a -> b) -> a -> b
$ (NameCache -> OrigNameCache) -> IO NameCache -> IO OrigNameCache
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap NameCache -> OrigNameCache
nsNames (IO NameCache -> IO OrigNameCache)
-> IO NameCache -> IO OrigNameCache
forall a b. (a -> b) -> a -> b
$ IORef NameCache -> IO NameCache
forall a. IORef a -> IO a
readIORef IORef NameCache
nameCacheRef

getPackageFamInstEnv :: CoreM PackageFamInstEnv
getPackageFamInstEnv :: CoreM PackageFamInstEnv
getPackageFamInstEnv = do
    HscEnv
hsc_env <- CoreM HscEnv
getHscEnv
    ExternalPackageState
eps <- IO ExternalPackageState -> CoreM ExternalPackageState
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO ExternalPackageState -> CoreM ExternalPackageState)
-> IO ExternalPackageState -> CoreM ExternalPackageState
forall a b. (a -> b) -> a -> b
$ HscEnv -> IO ExternalPackageState
hscEPS HscEnv
hsc_env
    PackageFamInstEnv -> CoreM PackageFamInstEnv
forall (m :: * -> *) a. Monad m => a -> m a
return (PackageFamInstEnv -> CoreM PackageFamInstEnv)
-> PackageFamInstEnv -> CoreM PackageFamInstEnv
forall a b. (a -> b) -> a -> b
$ ExternalPackageState -> PackageFamInstEnv
eps_fam_inst_env ExternalPackageState
eps

{-# DEPRECATED reinitializeGlobals "It is not necessary to call reinitializeGlobals. Since GHC 8.2, this function is a no-op and will be removed in GHC 8.4" #-}
reinitializeGlobals :: CoreM ()
reinitializeGlobals :: CoreM ()
reinitializeGlobals = () -> CoreM ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

{-
************************************************************************
*                                                                      *
             Dealing with annotations
*                                                                      *
************************************************************************
-}

-- | Get all annotations of a given type. This happens lazily, that is
-- no deserialization will take place until the [a] is actually demanded and
-- the [a] can also be empty (the UniqFM is not filtered).
--
-- This should be done once at the start of a Core-to-Core pass that uses
-- annotations.
--
-- See Note [Annotations]
getAnnotations :: Typeable a => ([Word8] -> a) -> ModGuts -> CoreM (UniqFM [a])
getAnnotations :: ([Word8] -> a) -> ModGuts -> CoreM (UniqFM [a])
getAnnotations deserialize :: [Word8] -> a
deserialize guts :: ModGuts
guts = do
     HscEnv
hsc_env <- CoreM HscEnv
getHscEnv
     AnnEnv
ann_env <- IO AnnEnv -> CoreM AnnEnv
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO AnnEnv -> CoreM AnnEnv) -> IO AnnEnv -> CoreM AnnEnv
forall a b. (a -> b) -> a -> b
$ HscEnv -> Maybe ModGuts -> IO AnnEnv
prepareAnnotations HscEnv
hsc_env (ModGuts -> Maybe ModGuts
forall a. a -> Maybe a
Just ModGuts
guts)
     UniqFM [a] -> CoreM (UniqFM [a])
forall (m :: * -> *) a. Monad m => a -> m a
return (([Word8] -> a) -> AnnEnv -> UniqFM [a]
forall a. Typeable a => ([Word8] -> a) -> AnnEnv -> UniqFM [a]
deserializeAnns [Word8] -> a
deserialize AnnEnv
ann_env)

-- | Get at most one annotation of a given type per Unique.
getFirstAnnotations :: Typeable a => ([Word8] -> a) -> ModGuts -> CoreM (UniqFM a)
getFirstAnnotations :: ([Word8] -> a) -> ModGuts -> CoreM (UniqFM a)
getFirstAnnotations deserialize :: [Word8] -> a
deserialize guts :: ModGuts
guts
  = (UniqFM [a] -> UniqFM a) -> CoreM (UniqFM [a]) -> CoreM (UniqFM a)
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM (([a] -> a) -> UniqFM [a] -> UniqFM a
forall elt1 elt2. (elt1 -> elt2) -> UniqFM elt1 -> UniqFM elt2
mapUFM [a] -> a
forall a. [a] -> a
head (UniqFM [a] -> UniqFM a)
-> (UniqFM [a] -> UniqFM [a]) -> UniqFM [a] -> UniqFM a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([a] -> Bool) -> UniqFM [a] -> UniqFM [a]
forall elt. (elt -> Bool) -> UniqFM elt -> UniqFM elt
filterUFM (Bool -> Bool
not (Bool -> Bool) -> ([a] -> Bool) -> [a] -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null))
  (CoreM (UniqFM [a]) -> CoreM (UniqFM a))
-> CoreM (UniqFM [a]) -> CoreM (UniqFM a)
forall a b. (a -> b) -> a -> b
$ ([Word8] -> a) -> ModGuts -> CoreM (UniqFM [a])
forall a.
Typeable a =>
([Word8] -> a) -> ModGuts -> CoreM (UniqFM [a])
getAnnotations [Word8] -> a
deserialize ModGuts
guts

{-
Note [Annotations]
~~~~~~~~~~~~~~~~~~
A Core-to-Core pass that wants to make use of annotations calls
getAnnotations or getFirstAnnotations at the beginning to obtain a UniqFM with
annotations of a specific type. This produces all annotations from interface
files read so far. However, annotations from interface files read during the
pass will not be visible until getAnnotations is called again. This is similar
to how rules work and probably isn't too bad.

The current implementation could be optimised a bit: when looking up
annotations for a thing from the HomePackageTable, we could search directly in
the module where the thing is defined rather than building one UniqFM which
contains all annotations we know of. This would work because annotations can
only be given to things defined in the same module. However, since we would
only want to deserialise every annotation once, we would have to build a cache
for every module in the HTP. In the end, it's probably not worth it as long as
we aren't using annotations heavily.

************************************************************************
*                                                                      *
                Direct screen output
*                                                                      *
************************************************************************
-}

msg :: Severity -> SDoc -> CoreM ()
msg :: Severity -> SDoc -> CoreM ()
msg sev :: Severity
sev doc :: SDoc
doc
  = do { DynFlags
dflags <- CoreM DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       ; SrcSpan
loc    <- CoreM SrcSpan
getSrcSpanM
       ; PrintUnqualified
unqual <- CoreM PrintUnqualified
getPrintUnqualified
       ; let sty :: PprStyle
sty = case Severity
sev of
                     SevError   -> PprStyle
err_sty
                     SevWarning -> PprStyle
err_sty
                     SevDump    -> PprStyle
dump_sty
                     _          -> PprStyle
user_sty
             err_sty :: PprStyle
err_sty  = DynFlags -> PrintUnqualified -> PprStyle
mkErrStyle DynFlags
dflags PrintUnqualified
unqual
             user_sty :: PprStyle
user_sty = DynFlags -> PrintUnqualified -> Depth -> PprStyle
mkUserStyle DynFlags
dflags PrintUnqualified
unqual Depth
AllTheWay
             dump_sty :: PprStyle
dump_sty = DynFlags -> PrintUnqualified -> PprStyle
mkDumpStyle DynFlags
dflags PrintUnqualified
unqual
       ; IO () -> CoreM ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> CoreM ()) -> IO () -> CoreM ()
forall a b. (a -> b) -> a -> b
$ DynFlags
-> WarnReason -> Severity -> SrcSpan -> PprStyle -> SDoc -> IO ()
putLogMsg DynFlags
dflags WarnReason
NoReason Severity
sev SrcSpan
loc PprStyle
sty SDoc
doc }

-- | Output a String message to the screen
putMsgS :: String -> CoreM ()
putMsgS :: String -> CoreM ()
putMsgS = SDoc -> CoreM ()
putMsg (SDoc -> CoreM ()) -> (String -> SDoc) -> String -> CoreM ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> SDoc
text

-- | Output a message to the screen
putMsg :: SDoc -> CoreM ()
putMsg :: SDoc -> CoreM ()
putMsg = Severity -> SDoc -> CoreM ()
msg Severity
SevInfo

-- | Output an error to the screen. Does not cause the compiler to die.
errorMsgS :: String -> CoreM ()
errorMsgS :: String -> CoreM ()
errorMsgS = SDoc -> CoreM ()
errorMsg (SDoc -> CoreM ()) -> (String -> SDoc) -> String -> CoreM ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> SDoc
text

-- | Output an error to the screen. Does not cause the compiler to die.
errorMsg :: SDoc -> CoreM ()
errorMsg :: SDoc -> CoreM ()
errorMsg = Severity -> SDoc -> CoreM ()
msg Severity
SevError

warnMsg :: SDoc -> CoreM ()
warnMsg :: SDoc -> CoreM ()
warnMsg = Severity -> SDoc -> CoreM ()
msg Severity
SevWarning

-- | Output a fatal error to the screen. Does not cause the compiler to die.
fatalErrorMsgS :: String -> CoreM ()
fatalErrorMsgS :: String -> CoreM ()
fatalErrorMsgS = SDoc -> CoreM ()
fatalErrorMsg (SDoc -> CoreM ()) -> (String -> SDoc) -> String -> CoreM ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> SDoc
text

-- | Output a fatal error to the screen. Does not cause the compiler to die.
fatalErrorMsg :: SDoc -> CoreM ()
fatalErrorMsg :: SDoc -> CoreM ()
fatalErrorMsg = Severity -> SDoc -> CoreM ()
msg Severity
SevFatal

-- | Output a string debugging message at verbosity level of @-v@ or higher
debugTraceMsgS :: String -> CoreM ()
debugTraceMsgS :: String -> CoreM ()
debugTraceMsgS = SDoc -> CoreM ()
debugTraceMsg (SDoc -> CoreM ()) -> (String -> SDoc) -> String -> CoreM ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> SDoc
text

-- | Outputs a debugging message at verbosity level of @-v@ or higher
debugTraceMsg :: SDoc -> CoreM ()
debugTraceMsg :: SDoc -> CoreM ()
debugTraceMsg = Severity -> SDoc -> CoreM ()
msg Severity
SevDump

-- | Show some labelled 'SDoc' if a particular flag is set or at a verbosity level of @-v -ddump-most@ or higher
dumpIfSet_dyn :: DumpFlag -> String -> SDoc -> CoreM ()
dumpIfSet_dyn :: DumpFlag -> String -> SDoc -> CoreM ()
dumpIfSet_dyn flag :: DumpFlag
flag str :: String
str doc :: SDoc
doc
  = do { DynFlags
dflags <- CoreM DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       ; PrintUnqualified
unqual <- CoreM PrintUnqualified
getPrintUnqualified
       ; Bool -> CoreM () -> CoreM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (DumpFlag -> DynFlags -> Bool
dopt DumpFlag
flag DynFlags
dflags) (CoreM () -> CoreM ()) -> CoreM () -> CoreM ()
forall a b. (a -> b) -> a -> b
$ IO () -> CoreM ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> CoreM ()) -> IO () -> CoreM ()
forall a b. (a -> b) -> a -> b
$
         DynFlags -> PrintUnqualified -> DumpFlag -> String -> SDoc -> IO ()
Err.dumpSDoc DynFlags
dflags PrintUnqualified
unqual DumpFlag
flag String
str SDoc
doc }