PageRenderTime 28ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/simplCore/CoreMonad.hs

http://github.com/ghc/ghc
Haskell | 906 lines | 542 code | 130 blank | 234 comment | 4 complexity | 236e131ddcb3bbcda1bb5c6a61882a63 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, GPL-3.0
  1. {-
  2. (c) The AQUA Project, Glasgow University, 1993-1998
  3. \section[CoreMonad]{The core pipeline monad}
  4. -}
  5. {-# LANGUAGE CPP #-}
  6. module CoreMonad (
  7. -- * Configuration of the core-to-core passes
  8. CoreToDo(..), runWhen, runMaybe,
  9. SimplifierMode(..),
  10. FloatOutSwitches(..),
  11. pprPassDetails,
  12. -- * Plugins
  13. PluginPass, bindsOnlyPass,
  14. -- * Counting
  15. SimplCount, doSimplTick, doFreeSimplTick, simplCountN,
  16. pprSimplCount, plusSimplCount, zeroSimplCount,
  17. isZeroSimplCount, hasDetailedCounts, Tick(..),
  18. -- * The monad
  19. CoreM, runCoreM,
  20. -- ** Reading from the monad
  21. getHscEnv, getRuleBase, getModule,
  22. getDynFlags, getOrigNameCache, getPackageFamInstEnv,
  23. getVisibleOrphanMods,
  24. getPrintUnqualified, getSrcSpanM,
  25. -- ** Writing to the monad
  26. addSimplCount,
  27. -- ** Lifting into the monad
  28. liftIO, liftIOWithCount,
  29. liftIO1, liftIO2, liftIO3, liftIO4,
  30. -- ** Global initialization
  31. reinitializeGlobals,
  32. -- ** Dealing with annotations
  33. getAnnotations, getFirstAnnotations,
  34. -- ** Screen output
  35. putMsg, putMsgS, errorMsg, errorMsgS, warnMsg,
  36. fatalErrorMsg, fatalErrorMsgS,
  37. debugTraceMsg, debugTraceMsgS,
  38. dumpIfSet_dyn,
  39. #ifdef GHCI
  40. -- * Getting 'Name's
  41. thNameToGhcName
  42. #endif
  43. ) where
  44. #ifdef GHCI
  45. import Name( Name )
  46. import TcRnMonad ( initTcForLookup )
  47. #endif
  48. import CoreSyn
  49. import HscTypes
  50. import Module
  51. import DynFlags
  52. import StaticFlags
  53. import BasicTypes ( CompilerPhase(..) )
  54. import Annotations
  55. import IOEnv hiding ( liftIO, failM, failWithM )
  56. import qualified IOEnv ( liftIO )
  57. import TcEnv ( lookupGlobal )
  58. import Var
  59. import Outputable
  60. import FastString
  61. import qualified ErrUtils as Err
  62. import ErrUtils( Severity(..) )
  63. import Maybes
  64. import UniqSupply
  65. import UniqFM ( UniqFM, mapUFM, filterUFM )
  66. import MonadUtils
  67. import SrcLoc
  68. import ListSetOps ( runs )
  69. import Data.List
  70. import Data.Ord
  71. import Data.Dynamic
  72. import Data.IORef
  73. import Data.Map (Map)
  74. import qualified Data.Map as Map
  75. import Data.Word
  76. import Control.Monad
  77. import Control.Applicative ( Alternative(..) )
  78. import Prelude hiding ( read )
  79. #ifdef GHCI
  80. import Control.Concurrent.MVar (MVar)
  81. import Linker ( PersistentLinkerState, saveLinkerGlobals, restoreLinkerGlobals )
  82. import {-# SOURCE #-} TcSplice ( lookupThName_maybe )
  83. import qualified Language.Haskell.TH as TH
  84. #else
  85. saveLinkerGlobals :: IO ()
  86. saveLinkerGlobals = return ()
  87. restoreLinkerGlobals :: () -> IO ()
  88. restoreLinkerGlobals () = return ()
  89. #endif
  90. {-
  91. ************************************************************************
  92. * *
  93. The CoreToDo type and related types
  94. Abstraction of core-to-core passes to run.
  95. * *
  96. ************************************************************************
  97. -}
  98. data CoreToDo -- These are diff core-to-core passes,
  99. -- which may be invoked in any order,
  100. -- as many times as you like.
  101. = CoreDoSimplify -- The core-to-core simplifier.
  102. Int -- Max iterations
  103. SimplifierMode
  104. | CoreDoPluginPass String PluginPass
  105. | CoreDoFloatInwards
  106. | CoreDoFloatOutwards FloatOutSwitches
  107. | CoreLiberateCase
  108. | CoreDoPrintCore
  109. | CoreDoStaticArgs
  110. | CoreDoCallArity
  111. | CoreDoStrictness
  112. | CoreDoWorkerWrapper
  113. | CoreDoSpecialising
  114. | CoreDoSpecConstr
  115. | CoreCSE
  116. | CoreDoRuleCheck CompilerPhase String -- Check for non-application of rules
  117. -- matching this string
  118. | CoreDoVectorisation
  119. | CoreDoNothing -- Useful when building up
  120. | CoreDoPasses [CoreToDo] -- lists of these things
  121. | CoreDesugar -- Right after desugaring, no simple optimisation yet!
  122. | CoreDesugarOpt -- CoreDesugarXXX: Not strictly a core-to-core pass, but produces
  123. -- Core output, and hence useful to pass to endPass
  124. | CoreTidy
  125. | CorePrep
  126. instance Outputable CoreToDo where
  127. ppr (CoreDoSimplify _ _) = text "Simplifier"
  128. ppr (CoreDoPluginPass s _) = text "Core plugin: " <+> text s
  129. ppr CoreDoFloatInwards = text "Float inwards"
  130. ppr (CoreDoFloatOutwards f) = text "Float out" <> parens (ppr f)
  131. ppr CoreLiberateCase = text "Liberate case"
  132. ppr CoreDoStaticArgs = text "Static argument"
  133. ppr CoreDoCallArity = text "Called arity analysis"
  134. ppr CoreDoStrictness = text "Demand analysis"
  135. ppr CoreDoWorkerWrapper = text "Worker Wrapper binds"
  136. ppr CoreDoSpecialising = text "Specialise"
  137. ppr CoreDoSpecConstr = text "SpecConstr"
  138. ppr CoreCSE = text "Common sub-expression"
  139. ppr CoreDoVectorisation = text "Vectorisation"
  140. ppr CoreDesugar = text "Desugar (before optimization)"
  141. ppr CoreDesugarOpt = text "Desugar (after optimization)"
  142. ppr CoreTidy = text "Tidy Core"
  143. ppr CorePrep = text "CorePrep"
  144. ppr CoreDoPrintCore = text "Print core"
  145. ppr (CoreDoRuleCheck {}) = text "Rule check"
  146. ppr CoreDoNothing = text "CoreDoNothing"
  147. ppr (CoreDoPasses passes) = text "CoreDoPasses" <+> ppr passes
  148. pprPassDetails :: CoreToDo -> SDoc
  149. pprPassDetails (CoreDoSimplify n md) = vcat [ text "Max iterations =" <+> int n
  150. , ppr md ]
  151. pprPassDetails _ = Outputable.empty
  152. data SimplifierMode -- See comments in SimplMonad
  153. = SimplMode
  154. { sm_names :: [String] -- Name(s) of the phase
  155. , sm_phase :: CompilerPhase
  156. , sm_rules :: Bool -- Whether RULES are enabled
  157. , sm_inline :: Bool -- Whether inlining is enabled
  158. , sm_case_case :: Bool -- Whether case-of-case is enabled
  159. , sm_eta_expand :: Bool -- Whether eta-expansion is enabled
  160. }
  161. instance Outputable SimplifierMode where
  162. ppr (SimplMode { sm_phase = p, sm_names = ss
  163. , sm_rules = r, sm_inline = i
  164. , sm_eta_expand = eta, sm_case_case = cc })
  165. = text "SimplMode" <+> braces (
  166. sep [ text "Phase =" <+> ppr p <+>
  167. brackets (text (concat $ intersperse "," ss)) <> comma
  168. , pp_flag i (sLit "inline") <> comma
  169. , pp_flag r (sLit "rules") <> comma
  170. , pp_flag eta (sLit "eta-expand") <> comma
  171. , pp_flag cc (sLit "case-of-case") ])
  172. where
  173. pp_flag f s = ppUnless f (text "no") <+> ptext s
  174. data FloatOutSwitches = FloatOutSwitches {
  175. floatOutLambdas :: Maybe Int, -- ^ Just n <=> float lambdas to top level, if
  176. -- doing so will abstract over n or fewer
  177. -- value variables
  178. -- Nothing <=> float all lambdas to top level,
  179. -- regardless of how many free variables
  180. -- Just 0 is the vanilla case: float a lambda
  181. -- iff it has no free vars
  182. floatOutConstants :: Bool, -- ^ True <=> float constants to top level,
  183. -- even if they do not escape a lambda
  184. floatOutOverSatApps :: Bool,
  185. -- ^ True <=> float out over-saturated applications
  186. -- based on arity information.
  187. -- See Note [Floating over-saturated applications]
  188. -- in SetLevels
  189. floatToTopLevelOnly :: Bool -- ^ Allow floating to the top level only.
  190. }
  191. instance Outputable FloatOutSwitches where
  192. ppr = pprFloatOutSwitches
  193. pprFloatOutSwitches :: FloatOutSwitches -> SDoc
  194. pprFloatOutSwitches sw
  195. = text "FOS" <+> (braces $
  196. sep $ punctuate comma $
  197. [ text "Lam =" <+> ppr (floatOutLambdas sw)
  198. , text "Consts =" <+> ppr (floatOutConstants sw)
  199. , text "OverSatApps =" <+> ppr (floatOutOverSatApps sw) ])
  200. -- The core-to-core pass ordering is derived from the DynFlags:
  201. runWhen :: Bool -> CoreToDo -> CoreToDo
  202. runWhen True do_this = do_this
  203. runWhen False _ = CoreDoNothing
  204. runMaybe :: Maybe a -> (a -> CoreToDo) -> CoreToDo
  205. runMaybe (Just x) f = f x
  206. runMaybe Nothing _ = CoreDoNothing
  207. {-
  208. Note [RULEs enabled in SimplGently]
  209. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  210. RULES are enabled when doing "gentle" simplification. Two reasons:
  211. * We really want the class-op cancellation to happen:
  212. op (df d1 d2) --> $cop3 d1 d2
  213. because this breaks the mutual recursion between 'op' and 'df'
  214. * I wanted the RULE
  215. lift String ===> ...
  216. to work in Template Haskell when simplifying
  217. splices, so we get simpler code for literal strings
  218. But watch out: list fusion can prevent floating. So use phase control
  219. to switch off those rules until after floating.
  220. ************************************************************************
  221. * *
  222. Types for Plugins
  223. * *
  224. ************************************************************************
  225. -}
  226. -- | A description of the plugin pass itself
  227. type PluginPass = ModGuts -> CoreM ModGuts
  228. bindsOnlyPass :: (CoreProgram -> CoreM CoreProgram) -> ModGuts -> CoreM ModGuts
  229. bindsOnlyPass pass guts
  230. = do { binds' <- pass (mg_binds guts)
  231. ; return (guts { mg_binds = binds' }) }
  232. {-
  233. ************************************************************************
  234. * *
  235. Counting and logging
  236. * *
  237. ************************************************************************
  238. -}
  239. verboseSimplStats :: Bool
  240. verboseSimplStats = opt_PprStyle_Debug -- For now, anyway
  241. zeroSimplCount :: DynFlags -> SimplCount
  242. isZeroSimplCount :: SimplCount -> Bool
  243. hasDetailedCounts :: SimplCount -> Bool
  244. pprSimplCount :: SimplCount -> SDoc
  245. doSimplTick :: DynFlags -> Tick -> SimplCount -> SimplCount
  246. doFreeSimplTick :: Tick -> SimplCount -> SimplCount
  247. plusSimplCount :: SimplCount -> SimplCount -> SimplCount
  248. data SimplCount
  249. = VerySimplCount !Int -- Used when don't want detailed stats
  250. | SimplCount {
  251. ticks :: !Int, -- Total ticks
  252. details :: !TickCounts, -- How many of each type
  253. n_log :: !Int, -- N
  254. log1 :: [Tick], -- Last N events; <= opt_HistorySize,
  255. -- most recent first
  256. log2 :: [Tick] -- Last opt_HistorySize events before that
  257. -- Having log1, log2 lets us accumulate the
  258. -- recent history reasonably efficiently
  259. }
  260. type TickCounts = Map Tick Int
  261. simplCountN :: SimplCount -> Int
  262. simplCountN (VerySimplCount n) = n
  263. simplCountN (SimplCount { ticks = n }) = n
  264. zeroSimplCount dflags
  265. -- This is where we decide whether to do
  266. -- the VerySimpl version or the full-stats version
  267. | dopt Opt_D_dump_simpl_stats dflags
  268. = SimplCount {ticks = 0, details = Map.empty,
  269. n_log = 0, log1 = [], log2 = []}
  270. | otherwise
  271. = VerySimplCount 0
  272. isZeroSimplCount (VerySimplCount n) = n==0
  273. isZeroSimplCount (SimplCount { ticks = n }) = n==0
  274. hasDetailedCounts (VerySimplCount {}) = False
  275. hasDetailedCounts (SimplCount {}) = True
  276. doFreeSimplTick tick sc@SimplCount { details = dts }
  277. = sc { details = dts `addTick` tick }
  278. doFreeSimplTick _ sc = sc
  279. doSimplTick dflags tick
  280. sc@(SimplCount { ticks = tks, details = dts, n_log = nl, log1 = l1 })
  281. | nl >= historySize dflags = sc1 { n_log = 1, log1 = [tick], log2 = l1 }
  282. | otherwise = sc1 { n_log = nl+1, log1 = tick : l1 }
  283. where
  284. sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
  285. doSimplTick _ _ (VerySimplCount n) = VerySimplCount (n+1)
  286. -- Don't use Map.unionWith because that's lazy, and we want to
  287. -- be pretty strict here!
  288. addTick :: TickCounts -> Tick -> TickCounts
  289. addTick fm tick = case Map.lookup tick fm of
  290. Nothing -> Map.insert tick 1 fm
  291. Just n -> n1 `seq` Map.insert tick n1 fm
  292. where
  293. n1 = n+1
  294. plusSimplCount sc1@(SimplCount { ticks = tks1, details = dts1 })
  295. sc2@(SimplCount { ticks = tks2, details = dts2 })
  296. = log_base { ticks = tks1 + tks2, details = Map.unionWith (+) dts1 dts2 }
  297. where
  298. -- A hackish way of getting recent log info
  299. log_base | null (log1 sc2) = sc1 -- Nothing at all in sc2
  300. | null (log2 sc2) = sc2 { log2 = log1 sc1 }
  301. | otherwise = sc2
  302. plusSimplCount (VerySimplCount n) (VerySimplCount m) = VerySimplCount (n+m)
  303. plusSimplCount _ _ = panic "plusSimplCount"
  304. -- We use one or the other consistently
  305. pprSimplCount (VerySimplCount n) = text "Total ticks:" <+> int n
  306. pprSimplCount (SimplCount { ticks = tks, details = dts, log1 = l1, log2 = l2 })
  307. = vcat [text "Total ticks: " <+> int tks,
  308. blankLine,
  309. pprTickCounts dts,
  310. if verboseSimplStats then
  311. vcat [blankLine,
  312. text "Log (most recent first)",
  313. nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
  314. else Outputable.empty
  315. ]
  316. pprTickCounts :: Map Tick Int -> SDoc
  317. pprTickCounts counts
  318. = vcat (map pprTickGroup groups)
  319. where
  320. groups :: [[(Tick,Int)]] -- Each group shares a comon tag
  321. -- toList returns common tags adjacent
  322. groups = runs same_tag (Map.toList counts)
  323. same_tag (tick1,_) (tick2,_) = tickToTag tick1 == tickToTag tick2
  324. pprTickGroup :: [(Tick, Int)] -> SDoc
  325. pprTickGroup group@((tick1,_):_)
  326. = hang (int (sum [n | (_,n) <- group]) <+> text (tickString tick1))
  327. 2 (vcat [ int n <+> pprTickCts tick
  328. -- flip as we want largest first
  329. | (tick,n) <- sortBy (flip (comparing snd)) group])
  330. pprTickGroup [] = panic "pprTickGroup"
  331. data Tick
  332. = PreInlineUnconditionally Id
  333. | PostInlineUnconditionally Id
  334. | UnfoldingDone Id
  335. | RuleFired FastString -- Rule name
  336. | LetFloatFromLet
  337. | EtaExpansion Id -- LHS binder
  338. | EtaReduction Id -- Binder on outer lambda
  339. | BetaReduction Id -- Lambda binder
  340. | CaseOfCase Id -- Bndr on *inner* case
  341. | KnownBranch Id -- Case binder
  342. | CaseMerge Id -- Binder on outer case
  343. | AltMerge Id -- Case binder
  344. | CaseElim Id -- Case binder
  345. | CaseIdentity Id -- Case binder
  346. | FillInCaseDefault Id -- Case binder
  347. | BottomFound
  348. | SimplifierDone -- Ticked at each iteration of the simplifier
  349. instance Outputable Tick where
  350. ppr tick = text (tickString tick) <+> pprTickCts tick
  351. instance Eq Tick where
  352. a == b = case a `cmpTick` b of
  353. EQ -> True
  354. _ -> False
  355. instance Ord Tick where
  356. compare = cmpTick
  357. tickToTag :: Tick -> Int
  358. tickToTag (PreInlineUnconditionally _) = 0
  359. tickToTag (PostInlineUnconditionally _) = 1
  360. tickToTag (UnfoldingDone _) = 2
  361. tickToTag (RuleFired _) = 3
  362. tickToTag LetFloatFromLet = 4
  363. tickToTag (EtaExpansion _) = 5
  364. tickToTag (EtaReduction _) = 6
  365. tickToTag (BetaReduction _) = 7
  366. tickToTag (CaseOfCase _) = 8
  367. tickToTag (KnownBranch _) = 9
  368. tickToTag (CaseMerge _) = 10
  369. tickToTag (CaseElim _) = 11
  370. tickToTag (CaseIdentity _) = 12
  371. tickToTag (FillInCaseDefault _) = 13
  372. tickToTag BottomFound = 14
  373. tickToTag SimplifierDone = 16
  374. tickToTag (AltMerge _) = 17
  375. tickString :: Tick -> String
  376. tickString (PreInlineUnconditionally _) = "PreInlineUnconditionally"
  377. tickString (PostInlineUnconditionally _)= "PostInlineUnconditionally"
  378. tickString (UnfoldingDone _) = "UnfoldingDone"
  379. tickString (RuleFired _) = "RuleFired"
  380. tickString LetFloatFromLet = "LetFloatFromLet"
  381. tickString (EtaExpansion _) = "EtaExpansion"
  382. tickString (EtaReduction _) = "EtaReduction"
  383. tickString (BetaReduction _) = "BetaReduction"
  384. tickString (CaseOfCase _) = "CaseOfCase"
  385. tickString (KnownBranch _) = "KnownBranch"
  386. tickString (CaseMerge _) = "CaseMerge"
  387. tickString (AltMerge _) = "AltMerge"
  388. tickString (CaseElim _) = "CaseElim"
  389. tickString (CaseIdentity _) = "CaseIdentity"
  390. tickString (FillInCaseDefault _) = "FillInCaseDefault"
  391. tickString BottomFound = "BottomFound"
  392. tickString SimplifierDone = "SimplifierDone"
  393. pprTickCts :: Tick -> SDoc
  394. pprTickCts (PreInlineUnconditionally v) = ppr v
  395. pprTickCts (PostInlineUnconditionally v)= ppr v
  396. pprTickCts (UnfoldingDone v) = ppr v
  397. pprTickCts (RuleFired v) = ppr v
  398. pprTickCts LetFloatFromLet = Outputable.empty
  399. pprTickCts (EtaExpansion v) = ppr v
  400. pprTickCts (EtaReduction v) = ppr v
  401. pprTickCts (BetaReduction v) = ppr v
  402. pprTickCts (CaseOfCase v) = ppr v
  403. pprTickCts (KnownBranch v) = ppr v
  404. pprTickCts (CaseMerge v) = ppr v
  405. pprTickCts (AltMerge v) = ppr v
  406. pprTickCts (CaseElim v) = ppr v
  407. pprTickCts (CaseIdentity v) = ppr v
  408. pprTickCts (FillInCaseDefault v) = ppr v
  409. pprTickCts _ = Outputable.empty
  410. cmpTick :: Tick -> Tick -> Ordering
  411. cmpTick a b = case (tickToTag a `compare` tickToTag b) of
  412. GT -> GT
  413. EQ -> cmpEqTick a b
  414. LT -> LT
  415. cmpEqTick :: Tick -> Tick -> Ordering
  416. cmpEqTick (PreInlineUnconditionally a) (PreInlineUnconditionally b) = a `compare` b
  417. cmpEqTick (PostInlineUnconditionally a) (PostInlineUnconditionally b) = a `compare` b
  418. cmpEqTick (UnfoldingDone a) (UnfoldingDone b) = a `compare` b
  419. cmpEqTick (RuleFired a) (RuleFired b) = a `compare` b
  420. cmpEqTick (EtaExpansion a) (EtaExpansion b) = a `compare` b
  421. cmpEqTick (EtaReduction a) (EtaReduction b) = a `compare` b
  422. cmpEqTick (BetaReduction a) (BetaReduction b) = a `compare` b
  423. cmpEqTick (CaseOfCase a) (CaseOfCase b) = a `compare` b
  424. cmpEqTick (KnownBranch a) (KnownBranch b) = a `compare` b
  425. cmpEqTick (CaseMerge a) (CaseMerge b) = a `compare` b
  426. cmpEqTick (AltMerge a) (AltMerge b) = a `compare` b
  427. cmpEqTick (CaseElim a) (CaseElim b) = a `compare` b
  428. cmpEqTick (CaseIdentity a) (CaseIdentity b) = a `compare` b
  429. cmpEqTick (FillInCaseDefault a) (FillInCaseDefault b) = a `compare` b
  430. cmpEqTick _ _ = EQ
  431. {-
  432. ************************************************************************
  433. * *
  434. Monad and carried data structure definitions
  435. * *
  436. ************************************************************************
  437. -}
  438. newtype CoreState = CoreState {
  439. cs_uniq_supply :: UniqSupply
  440. }
  441. data CoreReader = CoreReader {
  442. cr_hsc_env :: HscEnv,
  443. cr_rule_base :: RuleBase,
  444. cr_module :: Module,
  445. cr_print_unqual :: PrintUnqualified,
  446. cr_loc :: SrcSpan, -- Use this for log/error messages so they
  447. -- are at least tagged with the right source file
  448. cr_visible_orphan_mods :: !ModuleSet,
  449. #ifdef GHCI
  450. cr_globals :: (MVar PersistentLinkerState, Bool)
  451. #else
  452. cr_globals :: ()
  453. #endif
  454. }
  455. -- Note: CoreWriter used to be defined with data, rather than newtype. If it
  456. -- is defined that way again, the cw_simpl_count field, at least, must be
  457. -- strict to avoid a space leak (Trac #7702).
  458. newtype CoreWriter = CoreWriter {
  459. cw_simpl_count :: SimplCount
  460. }
  461. emptyWriter :: DynFlags -> CoreWriter
  462. emptyWriter dflags = CoreWriter {
  463. cw_simpl_count = zeroSimplCount dflags
  464. }
  465. plusWriter :: CoreWriter -> CoreWriter -> CoreWriter
  466. plusWriter w1 w2 = CoreWriter {
  467. cw_simpl_count = (cw_simpl_count w1) `plusSimplCount` (cw_simpl_count w2)
  468. }
  469. type CoreIOEnv = IOEnv CoreReader
  470. -- | The monad used by Core-to-Core passes to access common state, register simplification
  471. -- statistics and so on
  472. newtype CoreM a = CoreM { unCoreM :: CoreState -> CoreIOEnv (a, CoreState, CoreWriter) }
  473. instance Functor CoreM where
  474. fmap = liftM
  475. instance Monad CoreM where
  476. mx >>= f = CoreM $ \s -> do
  477. (x, s', w1) <- unCoreM mx s
  478. (y, s'', w2) <- unCoreM (f x) s'
  479. let w = w1 `plusWriter` w2
  480. return $ seq w (y, s'', w)
  481. -- forcing w before building the tuple avoids a space leak
  482. -- (Trac #7702)
  483. instance Applicative CoreM where
  484. pure x = CoreM $ \s -> nop s x
  485. (<*>) = ap
  486. m *> k = m >>= \_ -> k
  487. instance Alternative CoreM where
  488. empty = CoreM (const Control.Applicative.empty)
  489. m <|> n = CoreM (\rs -> unCoreM m rs <|> unCoreM n rs)
  490. instance MonadPlus CoreM
  491. instance MonadUnique CoreM where
  492. getUniqueSupplyM = do
  493. us <- getS cs_uniq_supply
  494. let (us1, us2) = splitUniqSupply us
  495. modifyS (\s -> s { cs_uniq_supply = us2 })
  496. return us1
  497. getUniqueM = do
  498. us <- getS cs_uniq_supply
  499. let (u,us') = takeUniqFromSupply us
  500. modifyS (\s -> s { cs_uniq_supply = us' })
  501. return u
  502. runCoreM :: HscEnv
  503. -> RuleBase
  504. -> UniqSupply
  505. -> Module
  506. -> ModuleSet
  507. -> PrintUnqualified
  508. -> SrcSpan
  509. -> CoreM a
  510. -> IO (a, SimplCount)
  511. runCoreM hsc_env rule_base us mod orph_imps print_unqual loc m
  512. = do { glbls <- saveLinkerGlobals
  513. ; liftM extract $ runIOEnv (reader glbls) $ unCoreM m state }
  514. where
  515. reader glbls = CoreReader {
  516. cr_hsc_env = hsc_env,
  517. cr_rule_base = rule_base,
  518. cr_module = mod,
  519. cr_visible_orphan_mods = orph_imps,
  520. cr_globals = glbls,
  521. cr_print_unqual = print_unqual,
  522. cr_loc = loc
  523. }
  524. state = CoreState {
  525. cs_uniq_supply = us
  526. }
  527. extract :: (a, CoreState, CoreWriter) -> (a, SimplCount)
  528. extract (value, _, writer) = (value, cw_simpl_count writer)
  529. {-
  530. ************************************************************************
  531. * *
  532. Core combinators, not exported
  533. * *
  534. ************************************************************************
  535. -}
  536. nop :: CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
  537. nop s x = do
  538. r <- getEnv
  539. return (x, s, emptyWriter $ (hsc_dflags . cr_hsc_env) r)
  540. read :: (CoreReader -> a) -> CoreM a
  541. read f = CoreM (\s -> getEnv >>= (\r -> nop s (f r)))
  542. getS :: (CoreState -> a) -> CoreM a
  543. getS f = CoreM (\s -> nop s (f s))
  544. modifyS :: (CoreState -> CoreState) -> CoreM ()
  545. modifyS f = CoreM (\s -> nop (f s) ())
  546. write :: CoreWriter -> CoreM ()
  547. write w = CoreM (\s -> return ((), s, w))
  548. -- \subsection{Lifting IO into the monad}
  549. -- | Lift an 'IOEnv' operation into 'CoreM'
  550. liftIOEnv :: CoreIOEnv a -> CoreM a
  551. liftIOEnv mx = CoreM (\s -> mx >>= (\x -> nop s x))
  552. instance MonadIO CoreM where
  553. liftIO = liftIOEnv . IOEnv.liftIO
  554. -- | Lift an 'IO' operation into 'CoreM' while consuming its 'SimplCount'
  555. liftIOWithCount :: IO (SimplCount, a) -> CoreM a
  556. liftIOWithCount what = liftIO what >>= (\(count, x) -> addSimplCount count >> return x)
  557. {-
  558. ************************************************************************
  559. * *
  560. Reader, writer and state accessors
  561. * *
  562. ************************************************************************
  563. -}
  564. getHscEnv :: CoreM HscEnv
  565. getHscEnv = read cr_hsc_env
  566. getRuleBase :: CoreM RuleBase
  567. getRuleBase = read cr_rule_base
  568. getVisibleOrphanMods :: CoreM ModuleSet
  569. getVisibleOrphanMods = read cr_visible_orphan_mods
  570. getPrintUnqualified :: CoreM PrintUnqualified
  571. getPrintUnqualified = read cr_print_unqual
  572. getSrcSpanM :: CoreM SrcSpan
  573. getSrcSpanM = read cr_loc
  574. addSimplCount :: SimplCount -> CoreM ()
  575. addSimplCount count = write (CoreWriter { cw_simpl_count = count })
  576. -- Convenience accessors for useful fields of HscEnv
  577. instance HasDynFlags CoreM where
  578. getDynFlags = fmap hsc_dflags getHscEnv
  579. instance HasModule CoreM where
  580. getModule = read cr_module
  581. -- | The original name cache is the current mapping from 'Module' and
  582. -- 'OccName' to a compiler-wide unique 'Name'
  583. getOrigNameCache :: CoreM OrigNameCache
  584. getOrigNameCache = do
  585. nameCacheRef <- fmap hsc_NC getHscEnv
  586. liftIO $ fmap nsNames $ readIORef nameCacheRef
  587. getPackageFamInstEnv :: CoreM PackageFamInstEnv
  588. getPackageFamInstEnv = do
  589. hsc_env <- getHscEnv
  590. eps <- liftIO $ hscEPS hsc_env
  591. return $ eps_fam_inst_env eps
  592. {-
  593. ************************************************************************
  594. * *
  595. Initializing globals
  596. * *
  597. ************************************************************************
  598. This is a rather annoying function. When a plugin is loaded, it currently
  599. gets linked against a *newly loaded* copy of the GHC package. This would
  600. not be a problem, except that the new copy has its own mutable state
  601. that is not shared with that state that has already been initialized by
  602. the original GHC package.
  603. (NB This mechanism is sufficient for granting plugins read-only access to
  604. globals that are guaranteed to be initialized before the plugin is loaded. If
  605. any further synchronization is necessary, I would suggest using the more
  606. sophisticated mechanism involving GHC.Conc.Sync.sharedCAF and rts/Globals.c to
  607. share a single instance of the global variable among the compiler and the
  608. plugins. Perhaps we should migrate all global variables to use that mechanism,
  609. for robustness... -- NSF July 2013)
  610. This leads to loaded plugins calling GHC code which pokes the static flags,
  611. and then dying with a panic because the static flags *it* sees are uninitialized.
  612. There are two possible solutions:
  613. 1. Export the symbols from the GHC executable from the GHC library and link
  614. against this existing copy rather than a new copy of the GHC library
  615. 2. Carefully ensure that the global state in the two copies of the GHC
  616. library matches
  617. I tried 1. and it *almost* works (and speeds up plugin load times!) except
  618. on Windows. On Windows the GHC library tends to export more than 65536 symbols
  619. (see #5292) which overflows the limit of what we can export from the EXE and
  620. causes breakage.
  621. (Note that if the GHC executable was dynamically linked this wouldn't be a
  622. problem, because we could share the GHC library it links to.)
  623. We are going to try 2. instead. Unfortunately, this means that every plugin
  624. will have to say `reinitializeGlobals` before it does anything, but never mind.
  625. I've threaded the cr_globals through CoreM rather than giving them as an
  626. argument to the plugin function so that we can turn this function into
  627. (return ()) without breaking any plugins when we eventually get 1. working.
  628. -}
  629. reinitializeGlobals :: CoreM ()
  630. reinitializeGlobals = do
  631. linker_globals <- read cr_globals
  632. hsc_env <- getHscEnv
  633. let dflags = hsc_dflags hsc_env
  634. liftIO $ restoreLinkerGlobals linker_globals
  635. liftIO $ setUnsafeGlobalDynFlags dflags
  636. {-
  637. ************************************************************************
  638. * *
  639. Dealing with annotations
  640. * *
  641. ************************************************************************
  642. -}
  643. -- | Get all annotations of a given type. This happens lazily, that is
  644. -- no deserialization will take place until the [a] is actually demanded and
  645. -- the [a] can also be empty (the UniqFM is not filtered).
  646. --
  647. -- This should be done once at the start of a Core-to-Core pass that uses
  648. -- annotations.
  649. --
  650. -- See Note [Annotations]
  651. getAnnotations :: Typeable a => ([Word8] -> a) -> ModGuts -> CoreM (UniqFM [a])
  652. getAnnotations deserialize guts = do
  653. hsc_env <- getHscEnv
  654. ann_env <- liftIO $ prepareAnnotations hsc_env (Just guts)
  655. return (deserializeAnns deserialize ann_env)
  656. -- | Get at most one annotation of a given type per Unique.
  657. getFirstAnnotations :: Typeable a => ([Word8] -> a) -> ModGuts -> CoreM (UniqFM a)
  658. getFirstAnnotations deserialize guts
  659. = liftM (mapUFM head . filterUFM (not . null))
  660. $ getAnnotations deserialize guts
  661. {-
  662. Note [Annotations]
  663. ~~~~~~~~~~~~~~~~~~
  664. A Core-to-Core pass that wants to make use of annotations calls
  665. getAnnotations or getFirstAnnotations at the beginning to obtain a UniqFM with
  666. annotations of a specific type. This produces all annotations from interface
  667. files read so far. However, annotations from interface files read during the
  668. pass will not be visible until getAnnotations is called again. This is similar
  669. to how rules work and probably isn't too bad.
  670. The current implementation could be optimised a bit: when looking up
  671. annotations for a thing from the HomePackageTable, we could search directly in
  672. the module where the thing is defined rather than building one UniqFM which
  673. contains all annotations we know of. This would work because annotations can
  674. only be given to things defined in the same module. However, since we would
  675. only want to deserialise every annotation once, we would have to build a cache
  676. for every module in the HTP. In the end, it's probably not worth it as long as
  677. we aren't using annotations heavily.
  678. ************************************************************************
  679. * *
  680. Direct screen output
  681. * *
  682. ************************************************************************
  683. -}
  684. msg :: Severity -> SDoc -> CoreM ()
  685. msg sev doc
  686. = do { dflags <- getDynFlags
  687. ; loc <- getSrcSpanM
  688. ; unqual <- getPrintUnqualified
  689. ; let sty = case sev of
  690. SevError -> err_sty
  691. SevWarning -> err_sty
  692. SevDump -> dump_sty
  693. _ -> user_sty
  694. err_sty = mkErrStyle dflags unqual
  695. user_sty = mkUserStyle unqual AllTheWay
  696. dump_sty = mkDumpStyle unqual
  697. ; liftIO $
  698. (log_action dflags) dflags NoReason sev loc sty doc }
  699. -- | Output a String message to the screen
  700. putMsgS :: String -> CoreM ()
  701. putMsgS = putMsg . text
  702. -- | Output a message to the screen
  703. putMsg :: SDoc -> CoreM ()
  704. putMsg = msg SevInfo
  705. -- | Output an error to the screen. Does not cause the compiler to die.
  706. errorMsgS :: String -> CoreM ()
  707. errorMsgS = errorMsg . text
  708. -- | Output an error to the screen. Does not cause the compiler to die.
  709. errorMsg :: SDoc -> CoreM ()
  710. errorMsg = msg SevError
  711. warnMsg :: SDoc -> CoreM ()
  712. warnMsg = msg SevWarning
  713. -- | Output a fatal error to the screen. Does not cause the compiler to die.
  714. fatalErrorMsgS :: String -> CoreM ()
  715. fatalErrorMsgS = fatalErrorMsg . text
  716. -- | Output a fatal error to the screen. Does not cause the compiler to die.
  717. fatalErrorMsg :: SDoc -> CoreM ()
  718. fatalErrorMsg = msg SevFatal
  719. -- | Output a string debugging message at verbosity level of @-v@ or higher
  720. debugTraceMsgS :: String -> CoreM ()
  721. debugTraceMsgS = debugTraceMsg . text
  722. -- | Outputs a debugging message at verbosity level of @-v@ or higher
  723. debugTraceMsg :: SDoc -> CoreM ()
  724. debugTraceMsg = msg SevDump
  725. -- | Show some labelled 'SDoc' if a particular flag is set or at a verbosity level of @-v -ddump-most@ or higher
  726. dumpIfSet_dyn :: DumpFlag -> String -> SDoc -> CoreM ()
  727. dumpIfSet_dyn flag str doc
  728. = do { dflags <- getDynFlags
  729. ; unqual <- getPrintUnqualified
  730. ; when (dopt flag dflags) $ liftIO $
  731. Err.dumpSDoc dflags unqual flag str doc }
  732. {-
  733. ************************************************************************
  734. * *
  735. Finding TyThings
  736. * *
  737. ************************************************************************
  738. -}
  739. instance MonadThings CoreM where
  740. lookupThing name = do { hsc_env <- getHscEnv
  741. ; liftIO $ lookupGlobal hsc_env name }
  742. {-
  743. ************************************************************************
  744. * *
  745. Template Haskell interoperability
  746. * *
  747. ************************************************************************
  748. -}
  749. #ifdef GHCI
  750. -- | Attempt to convert a Template Haskell name to one that GHC can
  751. -- understand. Original TH names such as those you get when you use
  752. -- the @'foo@ syntax will be translated to their equivalent GHC name
  753. -- exactly. Qualified or unqualifed TH names will be dynamically bound
  754. -- to names in the module being compiled, if possible. Exact TH names
  755. -- will be bound to the name they represent, exactly.
  756. thNameToGhcName :: TH.Name -> CoreM (Maybe Name)
  757. thNameToGhcName th_name = do
  758. hsc_env <- getHscEnv
  759. liftIO $ initTcForLookup hsc_env (lookupThName_maybe th_name)
  760. #endif