PageRenderTime 56ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/simplCore/CoreMonad.lhs

http://github.com/ghc/ghc
Haskell | 1136 lines | 829 code | 191 blank | 116 comment | 14 complexity | cc4340f618d6bb19b33ac3f48e54dabd MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, GPL-3.0
  1. %
  2. % (c) The AQUA Project, Glasgow University, 1993-1998
  3. %
  4. \section[CoreMonad]{The core pipeline monad}
  5. \begin{code}
  6. {-# OPTIONS -fno-warn-tabs #-}
  7. -- The above warning supression flag is a temporary kludge.
  8. -- While working on this module you are encouraged to remove it and
  9. -- detab the module (please do the detabbing in a separate patch). See
  10. -- http://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
  11. -- for details
  12. {-# LANGUAGE UndecidableInstances #-}
  13. module CoreMonad (
  14. -- * Configuration of the core-to-core passes
  15. CoreToDo(..), runWhen, runMaybe,
  16. SimplifierMode(..),
  17. FloatOutSwitches(..),
  18. dumpSimplPhase, pprPassDetails,
  19. -- * Plugins
  20. PluginPass, Plugin(..), CommandLineOption,
  21. defaultPlugin, bindsOnlyPass,
  22. -- * Counting
  23. SimplCount, doSimplTick, doFreeSimplTick, simplCountN,
  24. pprSimplCount, plusSimplCount, zeroSimplCount,
  25. isZeroSimplCount, hasDetailedCounts, Tick(..),
  26. -- * The monad
  27. CoreM, runCoreM,
  28. -- ** Reading from the monad
  29. getHscEnv, getRuleBase, getModule,
  30. getDynFlags, getOrigNameCache,
  31. -- ** Writing to the monad
  32. addSimplCount,
  33. -- ** Lifting into the monad
  34. liftIO, liftIOWithCount,
  35. liftIO1, liftIO2, liftIO3, liftIO4,
  36. -- ** Global initialization
  37. reinitializeGlobals,
  38. -- ** Dealing with annotations
  39. getAnnotations, getFirstAnnotations,
  40. -- ** Debug output
  41. showPass, endPass, dumpPassResult, lintPassResult,
  42. lintInteractiveExpr, dumpIfSet,
  43. -- ** Screen output
  44. putMsg, putMsgS, errorMsg, errorMsgS,
  45. fatalErrorMsg, fatalErrorMsgS,
  46. debugTraceMsg, debugTraceMsgS,
  47. dumpIfSet_dyn,
  48. #ifdef GHCI
  49. -- * Getting 'Name's
  50. thNameToGhcName
  51. #endif
  52. ) where
  53. #ifdef GHCI
  54. import Name( Name )
  55. #endif
  56. import CoreSyn
  57. import PprCore
  58. import CoreUtils
  59. import CoreLint ( lintCoreBindings, lintExpr )
  60. import HscTypes
  61. import Module
  62. import DynFlags
  63. import StaticFlags
  64. import Rules ( RuleBase )
  65. import BasicTypes ( CompilerPhase(..) )
  66. import Annotations
  67. import IOEnv hiding ( liftIO, failM, failWithM )
  68. import qualified IOEnv ( liftIO )
  69. import TcEnv ( tcLookupGlobal )
  70. import TcRnMonad ( initTcForLookup )
  71. import Var
  72. import VarSet
  73. import Outputable
  74. import FastString
  75. import qualified ErrUtils as Err
  76. import Bag
  77. import Maybes
  78. import SrcLoc
  79. import UniqSupply
  80. import UniqFM ( UniqFM, mapUFM, filterUFM )
  81. import MonadUtils
  82. import Util ( split )
  83. import ListSetOps ( runs )
  84. import Data.List
  85. import Data.Ord
  86. import Data.Dynamic
  87. import Data.IORef
  88. import Data.Map (Map)
  89. import qualified Data.Map as Map
  90. import Data.Word
  91. import qualified Control.Applicative as A
  92. import Control.Monad
  93. import Prelude hiding ( read )
  94. #ifdef GHCI
  95. import Control.Concurrent.MVar (MVar)
  96. import Linker ( PersistentLinkerState, saveLinkerGlobals, restoreLinkerGlobals )
  97. import {-# SOURCE #-} TcSplice ( lookupThName_maybe )
  98. import qualified Language.Haskell.TH as TH
  99. #else
  100. saveLinkerGlobals :: IO ()
  101. saveLinkerGlobals = return ()
  102. restoreLinkerGlobals :: () -> IO ()
  103. restoreLinkerGlobals () = return ()
  104. #endif
  105. \end{code}
  106. %************************************************************************
  107. %* *
  108. Debug output
  109. %* *
  110. %************************************************************************
  111. These functions are not CoreM monad stuff, but they probably ought to
  112. be, and it makes a conveneint place. place for them. They print out
  113. stuff before and after core passes, and do Core Lint when necessary.
  114. \begin{code}
  115. showPass :: DynFlags -> CoreToDo -> IO ()
  116. showPass dflags pass = Err.showPass dflags (showPpr dflags pass)
  117. endPass :: HscEnv -> CoreToDo -> CoreProgram -> [CoreRule] -> IO ()
  118. endPass hsc_env pass binds rules
  119. = do { dumpPassResult dflags mb_flag (ppr pass) (pprPassDetails pass) binds rules
  120. ; lintPassResult hsc_env pass binds }
  121. where
  122. dflags = hsc_dflags hsc_env
  123. mb_flag = case coreDumpFlag pass of
  124. Just flag | dopt flag dflags -> Just flag
  125. | dopt Opt_D_verbose_core2core dflags -> Just flag
  126. _ -> Nothing
  127. dumpIfSet :: DynFlags -> Bool -> CoreToDo -> SDoc -> SDoc -> IO ()
  128. dumpIfSet dflags dump_me pass extra_info doc
  129. = Err.dumpIfSet dflags dump_me (showSDoc dflags (ppr pass <+> extra_info)) doc
  130. dumpPassResult :: DynFlags
  131. -> Maybe DumpFlag -- Just df => show details in a file whose
  132. -- name is specified by df
  133. -> SDoc -- Header
  134. -> SDoc -- Extra info to appear after header
  135. -> CoreProgram -> [CoreRule]
  136. -> IO ()
  137. dumpPassResult dflags mb_flag hdr extra_info binds rules
  138. | Just flag <- mb_flag
  139. = Err.dumpSDoc dflags flag (showSDoc dflags hdr) dump_doc
  140. | otherwise
  141. = Err.debugTraceMsg dflags 2 size_doc
  142. -- Report result size
  143. -- This has the side effect of forcing the intermediate to be evaluated
  144. where
  145. size_doc = sep [text "Result size of" <+> hdr, nest 2 (equals <+> ppr (coreBindsStats binds))]
  146. dump_doc = vcat [ nest 2 extra_info
  147. , size_doc
  148. , blankLine
  149. , pprCoreBindings binds
  150. , ppUnless (null rules) pp_rules ]
  151. pp_rules = vcat [ blankLine
  152. , ptext (sLit "------ Local rules for imported ids --------")
  153. , pprRules rules ]
  154. lintPassResult :: HscEnv -> CoreToDo -> CoreProgram -> IO ()
  155. lintPassResult hsc_env pass binds
  156. | not (gopt Opt_DoCoreLinting dflags)
  157. = return ()
  158. | otherwise
  159. = do { let (warns, errs) = lintCoreBindings (interactiveInScope hsc_env) binds
  160. ; Err.showPass dflags ("Core Linted result of " ++ showPpr dflags pass)
  161. ; displayLintResults dflags pass warns errs binds }
  162. where
  163. dflags = hsc_dflags hsc_env
  164. displayLintResults :: DynFlags -> CoreToDo
  165. -> Bag Err.MsgDoc -> Bag Err.MsgDoc -> CoreProgram
  166. -> IO ()
  167. displayLintResults dflags pass warns errs binds
  168. | not (isEmptyBag errs)
  169. = do { log_action dflags dflags Err.SevDump noSrcSpan defaultDumpStyle
  170. (vcat [ lint_banner "errors" (ppr pass), Err.pprMessageBag errs
  171. , ptext (sLit "*** Offending Program ***")
  172. , pprCoreBindings binds
  173. , ptext (sLit "*** End of Offense ***") ])
  174. ; Err.ghcExit dflags 1 }
  175. | not (isEmptyBag warns)
  176. , not (case pass of { CoreDesugar -> True; _ -> False })
  177. -- Suppress warnings after desugaring pass because some
  178. -- are legitimate. Notably, the desugarer generates instance
  179. -- methods with INLINE pragmas that form a mutually recursive
  180. -- group. Only afer a round of simplification are they unravelled.
  181. , not opt_NoDebugOutput
  182. , showLintWarnings pass
  183. = log_action dflags dflags Err.SevDump noSrcSpan defaultDumpStyle
  184. (lint_banner "warnings" (ppr pass) $$ Err.pprMessageBag warns)
  185. | otherwise = return ()
  186. where
  187. lint_banner :: String -> SDoc -> SDoc
  188. lint_banner string pass = ptext (sLit "*** Core Lint") <+> text string
  189. <+> ptext (sLit ": in result of") <+> pass
  190. <+> ptext (sLit "***")
  191. showLintWarnings :: CoreToDo -> Bool
  192. -- Disable Lint warnings on the first simplifier pass, because
  193. -- there may be some INLINE knots still tied, which is tiresomely noisy
  194. showLintWarnings (CoreDoSimplify _ (SimplMode { sm_phase = InitialPhase })) = False
  195. showLintWarnings _ = True
  196. lintInteractiveExpr :: String -> HscEnv -> CoreExpr -> IO ()
  197. lintInteractiveExpr what hsc_env expr
  198. | not (gopt Opt_DoCoreLinting dflags)
  199. = return ()
  200. | Just err <- lintExpr (interactiveInScope hsc_env) expr
  201. = do { display_lint_err err
  202. ; Err.ghcExit dflags 1 }
  203. | otherwise
  204. = return ()
  205. where
  206. dflags = hsc_dflags hsc_env
  207. display_lint_err err
  208. = do { log_action dflags dflags Err.SevDump noSrcSpan defaultDumpStyle
  209. (vcat [ lint_banner "errors" (text what)
  210. , err
  211. , ptext (sLit "*** Offending Program ***")
  212. , pprCoreExpr expr
  213. , ptext (sLit "*** End of Offense ***") ])
  214. ; Err.ghcExit dflags 1 }
  215. interactiveInScope :: HscEnv -> [Var]
  216. -- In GHCi we may lint expressions, or bindings arising from 'deriving'
  217. -- clauses, that mention variables bound in the interactive context.
  218. -- These are Local things (see Note [Interactively-bound Ids in GHCi] in TcRnDriver).
  219. -- So we have to tell Lint about them, lest it reports them as out of scope.
  220. --
  221. -- We do this by find local-named things that may appear free in interactive
  222. -- context. This function is pretty revolting and quite possibly not quite right.
  223. -- When we are not in GHCi, the interactive context (hsc_IC hsc_env) is empty
  224. -- so this is a (cheap) no-op.
  225. --
  226. -- See Trac #8215 for an example
  227. interactiveInScope hsc_env
  228. = tyvars ++ vars
  229. where
  230. ictxt = hsc_IC hsc_env
  231. te = mkTypeEnvWithImplicits (ic_tythings ictxt ++ map AnId (ic_sys_vars ictxt))
  232. vars = typeEnvIds te
  233. tyvars = varSetElems $ tyThingsTyVars $ typeEnvElts $ te
  234. -- Why the type variables? How can the top level envt have free tyvars?
  235. -- I think it's because of the GHCi debugger, which can bind variables
  236. -- f :: [t] -> [t]
  237. -- where t is a RuntimeUnk (see TcType)
  238. \end{code}
  239. %************************************************************************
  240. %* *
  241. The CoreToDo type and related types
  242. Abstraction of core-to-core passes to run.
  243. %* *
  244. %************************************************************************
  245. \begin{code}
  246. data CoreToDo -- These are diff core-to-core passes,
  247. -- which may be invoked in any order,
  248. -- as many times as you like.
  249. = CoreDoSimplify -- The core-to-core simplifier.
  250. Int -- Max iterations
  251. SimplifierMode
  252. | CoreDoPluginPass String PluginPass
  253. | CoreDoFloatInwards
  254. | CoreDoFloatOutwards FloatOutSwitches
  255. | CoreLiberateCase
  256. | CoreDoPrintCore
  257. | CoreDoStaticArgs
  258. | CoreDoStrictness
  259. | CoreDoWorkerWrapper
  260. | CoreDoSpecialising
  261. | CoreDoSpecConstr
  262. | CoreCSE
  263. | CoreDoRuleCheck CompilerPhase String -- Check for non-application of rules
  264. -- matching this string
  265. | CoreDoVectorisation
  266. | CoreDoNothing -- Useful when building up
  267. | CoreDoPasses [CoreToDo] -- lists of these things
  268. | CoreDesugar -- Right after desugaring, no simple optimisation yet!
  269. | CoreDesugarOpt -- CoreDesugarXXX: Not strictly a core-to-core pass, but produces
  270. -- Core output, and hence useful to pass to endPass
  271. | CoreTidy
  272. | CorePrep
  273. \end{code}
  274. \begin{code}
  275. coreDumpFlag :: CoreToDo -> Maybe DumpFlag
  276. coreDumpFlag (CoreDoSimplify {}) = Just Opt_D_dump_simpl_phases
  277. coreDumpFlag (CoreDoPluginPass {}) = Just Opt_D_dump_core_pipeline
  278. coreDumpFlag CoreDoFloatInwards = Just Opt_D_verbose_core2core
  279. coreDumpFlag (CoreDoFloatOutwards {}) = Just Opt_D_verbose_core2core
  280. coreDumpFlag CoreLiberateCase = Just Opt_D_verbose_core2core
  281. coreDumpFlag CoreDoStaticArgs = Just Opt_D_verbose_core2core
  282. coreDumpFlag CoreDoStrictness = Just Opt_D_dump_stranal
  283. coreDumpFlag CoreDoWorkerWrapper = Just Opt_D_dump_worker_wrapper
  284. coreDumpFlag CoreDoSpecialising = Just Opt_D_dump_spec
  285. coreDumpFlag CoreDoSpecConstr = Just Opt_D_dump_spec
  286. coreDumpFlag CoreCSE = Just Opt_D_dump_cse
  287. coreDumpFlag CoreDoVectorisation = Just Opt_D_dump_vect
  288. coreDumpFlag CoreDesugar = Just Opt_D_dump_ds
  289. coreDumpFlag CoreDesugarOpt = Just Opt_D_dump_ds
  290. coreDumpFlag CoreTidy = Just Opt_D_dump_simpl
  291. coreDumpFlag CorePrep = Just Opt_D_dump_prep
  292. coreDumpFlag CoreDoPrintCore = Nothing
  293. coreDumpFlag (CoreDoRuleCheck {}) = Nothing
  294. coreDumpFlag CoreDoNothing = Nothing
  295. coreDumpFlag (CoreDoPasses {}) = Nothing
  296. instance Outputable CoreToDo where
  297. ppr (CoreDoSimplify _ _) = ptext (sLit "Simplifier")
  298. ppr (CoreDoPluginPass s _) = ptext (sLit "Core plugin: ") <+> text s
  299. ppr CoreDoFloatInwards = ptext (sLit "Float inwards")
  300. ppr (CoreDoFloatOutwards f) = ptext (sLit "Float out") <> parens (ppr f)
  301. ppr CoreLiberateCase = ptext (sLit "Liberate case")
  302. ppr CoreDoStaticArgs = ptext (sLit "Static argument")
  303. ppr CoreDoStrictness = ptext (sLit "Demand analysis")
  304. ppr CoreDoWorkerWrapper = ptext (sLit "Worker Wrapper binds")
  305. ppr CoreDoSpecialising = ptext (sLit "Specialise")
  306. ppr CoreDoSpecConstr = ptext (sLit "SpecConstr")
  307. ppr CoreCSE = ptext (sLit "Common sub-expression")
  308. ppr CoreDoVectorisation = ptext (sLit "Vectorisation")
  309. ppr CoreDesugar = ptext (sLit "Desugar (before optimization)")
  310. ppr CoreDesugarOpt = ptext (sLit "Desugar (after optimization)")
  311. ppr CoreTidy = ptext (sLit "Tidy Core")
  312. ppr CorePrep = ptext (sLit "CorePrep")
  313. ppr CoreDoPrintCore = ptext (sLit "Print core")
  314. ppr (CoreDoRuleCheck {}) = ptext (sLit "Rule check")
  315. ppr CoreDoNothing = ptext (sLit "CoreDoNothing")
  316. ppr (CoreDoPasses {}) = ptext (sLit "CoreDoPasses")
  317. pprPassDetails :: CoreToDo -> SDoc
  318. pprPassDetails (CoreDoSimplify n md) = vcat [ ptext (sLit "Max iterations =") <+> int n
  319. , ppr md ]
  320. pprPassDetails _ = empty
  321. \end{code}
  322. \begin{code}
  323. data SimplifierMode -- See comments in SimplMonad
  324. = SimplMode
  325. { sm_names :: [String] -- Name(s) of the phase
  326. , sm_phase :: CompilerPhase
  327. , sm_rules :: Bool -- Whether RULES are enabled
  328. , sm_inline :: Bool -- Whether inlining is enabled
  329. , sm_case_case :: Bool -- Whether case-of-case is enabled
  330. , sm_eta_expand :: Bool -- Whether eta-expansion is enabled
  331. }
  332. instance Outputable SimplifierMode where
  333. ppr (SimplMode { sm_phase = p, sm_names = ss
  334. , sm_rules = r, sm_inline = i
  335. , sm_eta_expand = eta, sm_case_case = cc })
  336. = ptext (sLit "SimplMode") <+> braces (
  337. sep [ ptext (sLit "Phase =") <+> ppr p <+>
  338. brackets (text (concat $ intersperse "," ss)) <> comma
  339. , pp_flag i (sLit "inline") <> comma
  340. , pp_flag r (sLit "rules") <> comma
  341. , pp_flag eta (sLit "eta-expand") <> comma
  342. , pp_flag cc (sLit "case-of-case") ])
  343. where
  344. pp_flag f s = ppUnless f (ptext (sLit "no")) <+> ptext s
  345. \end{code}
  346. \begin{code}
  347. data FloatOutSwitches = FloatOutSwitches {
  348. floatOutLambdas :: Maybe Int, -- ^ Just n <=> float lambdas to top level, if
  349. -- doing so will abstract over n or fewer
  350. -- value variables
  351. -- Nothing <=> float all lambdas to top level,
  352. -- regardless of how many free variables
  353. -- Just 0 is the vanilla case: float a lambda
  354. -- iff it has no free vars
  355. floatOutConstants :: Bool, -- ^ True <=> float constants to top level,
  356. -- even if they do not escape a lambda
  357. floatOutPartialApplications :: Bool -- ^ True <=> float out partial applications
  358. -- based on arity information.
  359. }
  360. instance Outputable FloatOutSwitches where
  361. ppr = pprFloatOutSwitches
  362. pprFloatOutSwitches :: FloatOutSwitches -> SDoc
  363. pprFloatOutSwitches sw
  364. = ptext (sLit "FOS") <+> (braces $
  365. sep $ punctuate comma $
  366. [ ptext (sLit "Lam =") <+> ppr (floatOutLambdas sw)
  367. , ptext (sLit "Consts =") <+> ppr (floatOutConstants sw)
  368. , ptext (sLit "PAPs =") <+> ppr (floatOutPartialApplications sw) ])
  369. -- The core-to-core pass ordering is derived from the DynFlags:
  370. runWhen :: Bool -> CoreToDo -> CoreToDo
  371. runWhen True do_this = do_this
  372. runWhen False _ = CoreDoNothing
  373. runMaybe :: Maybe a -> (a -> CoreToDo) -> CoreToDo
  374. runMaybe (Just x) f = f x
  375. runMaybe Nothing _ = CoreDoNothing
  376. dumpSimplPhase :: DynFlags -> SimplifierMode -> Bool
  377. dumpSimplPhase dflags mode
  378. | Just spec_string <- shouldDumpSimplPhase dflags
  379. = match_spec spec_string
  380. | otherwise
  381. = dopt Opt_D_verbose_core2core dflags
  382. where
  383. match_spec :: String -> Bool
  384. match_spec spec_string
  385. = or $ map (and . map match . split ':')
  386. $ split ',' spec_string
  387. match :: String -> Bool
  388. match "" = True
  389. match s = case reads s of
  390. [(n,"")] -> phase_num n
  391. _ -> phase_name s
  392. phase_num :: Int -> Bool
  393. phase_num n = case sm_phase mode of
  394. Phase k -> n == k
  395. _ -> False
  396. phase_name :: String -> Bool
  397. phase_name s = s `elem` sm_names mode
  398. \end{code}
  399. Note [RULEs enabled in SimplGently]
  400. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  401. RULES are enabled when doing "gentle" simplification. Two reasons:
  402. * We really want the class-op cancellation to happen:
  403. op (df d1 d2) --> $cop3 d1 d2
  404. because this breaks the mutual recursion between 'op' and 'df'
  405. * I wanted the RULE
  406. lift String ===> ...
  407. to work in Template Haskell when simplifying
  408. splices, so we get simpler code for literal strings
  409. But watch out: list fusion can prevent floating. So use phase control
  410. to switch off those rules until after floating.
  411. %************************************************************************
  412. %* *
  413. Types for Plugins
  414. %* *
  415. %************************************************************************
  416. \begin{code}
  417. -- | Command line options gathered from the -PModule.Name:stuff syntax are given to you as this type
  418. type CommandLineOption = String
  419. -- | 'Plugin' is the core compiler plugin data type. Try to avoid
  420. -- constructing one of these directly, and just modify some fields of
  421. -- 'defaultPlugin' instead: this is to try and preserve source-code
  422. -- compatability when we add fields to this.
  423. --
  424. -- Nonetheless, this API is preliminary and highly likely to change in the future.
  425. data Plugin = Plugin {
  426. installCoreToDos :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
  427. -- ^ Modify the Core pipeline that will be used for compilation.
  428. -- This is called as the Core pipeline is built for every module
  429. -- being compiled, and plugins get the opportunity to modify
  430. -- the pipeline in a nondeterministic order.
  431. }
  432. -- | Default plugin: does nothing at all! For compatability reasons you should base all your
  433. -- plugin definitions on this default value.
  434. defaultPlugin :: Plugin
  435. defaultPlugin = Plugin {
  436. installCoreToDos = const return
  437. }
  438. -- | A description of the plugin pass itself
  439. type PluginPass = ModGuts -> CoreM ModGuts
  440. bindsOnlyPass :: (CoreProgram -> CoreM CoreProgram) -> ModGuts -> CoreM ModGuts
  441. bindsOnlyPass pass guts
  442. = do { binds' <- pass (mg_binds guts)
  443. ; return (guts { mg_binds = binds' }) }
  444. \end{code}
  445. %************************************************************************
  446. %* *
  447. Counting and logging
  448. %* *
  449. %************************************************************************
  450. \begin{code}
  451. verboseSimplStats :: Bool
  452. verboseSimplStats = opt_PprStyle_Debug -- For now, anyway
  453. zeroSimplCount :: DynFlags -> SimplCount
  454. isZeroSimplCount :: SimplCount -> Bool
  455. hasDetailedCounts :: SimplCount -> Bool
  456. pprSimplCount :: SimplCount -> SDoc
  457. doSimplTick :: DynFlags -> Tick -> SimplCount -> SimplCount
  458. doFreeSimplTick :: Tick -> SimplCount -> SimplCount
  459. plusSimplCount :: SimplCount -> SimplCount -> SimplCount
  460. \end{code}
  461. \begin{code}
  462. data SimplCount
  463. = VerySimplCount !Int -- Used when don't want detailed stats
  464. | SimplCount {
  465. ticks :: !Int, -- Total ticks
  466. details :: !TickCounts, -- How many of each type
  467. n_log :: !Int, -- N
  468. log1 :: [Tick], -- Last N events; <= opt_HistorySize,
  469. -- most recent first
  470. log2 :: [Tick] -- Last opt_HistorySize events before that
  471. -- Having log1, log2 lets us accumulate the
  472. -- recent history reasonably efficiently
  473. }
  474. type TickCounts = Map Tick Int
  475. simplCountN :: SimplCount -> Int
  476. simplCountN (VerySimplCount n) = n
  477. simplCountN (SimplCount { ticks = n }) = n
  478. zeroSimplCount dflags
  479. -- This is where we decide whether to do
  480. -- the VerySimpl version or the full-stats version
  481. | dopt Opt_D_dump_simpl_stats dflags
  482. = SimplCount {ticks = 0, details = Map.empty,
  483. n_log = 0, log1 = [], log2 = []}
  484. | otherwise
  485. = VerySimplCount 0
  486. isZeroSimplCount (VerySimplCount n) = n==0
  487. isZeroSimplCount (SimplCount { ticks = n }) = n==0
  488. hasDetailedCounts (VerySimplCount {}) = False
  489. hasDetailedCounts (SimplCount {}) = True
  490. doFreeSimplTick tick sc@SimplCount { details = dts }
  491. = sc { details = dts `addTick` tick }
  492. doFreeSimplTick _ sc = sc
  493. doSimplTick dflags tick
  494. sc@(SimplCount { ticks = tks, details = dts, n_log = nl, log1 = l1 })
  495. | nl >= historySize dflags = sc1 { n_log = 1, log1 = [tick], log2 = l1 }
  496. | otherwise = sc1 { n_log = nl+1, log1 = tick : l1 }
  497. where
  498. sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
  499. doSimplTick _ _ (VerySimplCount n) = VerySimplCount (n+1)
  500. -- Don't use Map.unionWith because that's lazy, and we want to
  501. -- be pretty strict here!
  502. addTick :: TickCounts -> Tick -> TickCounts
  503. addTick fm tick = case Map.lookup tick fm of
  504. Nothing -> Map.insert tick 1 fm
  505. Just n -> n1 `seq` Map.insert tick n1 fm
  506. where
  507. n1 = n+1
  508. plusSimplCount sc1@(SimplCount { ticks = tks1, details = dts1 })
  509. sc2@(SimplCount { ticks = tks2, details = dts2 })
  510. = log_base { ticks = tks1 + tks2, details = Map.unionWith (+) dts1 dts2 }
  511. where
  512. -- A hackish way of getting recent log info
  513. log_base | null (log1 sc2) = sc1 -- Nothing at all in sc2
  514. | null (log2 sc2) = sc2 { log2 = log1 sc1 }
  515. | otherwise = sc2
  516. plusSimplCount (VerySimplCount n) (VerySimplCount m) = VerySimplCount (n+m)
  517. plusSimplCount _ _ = panic "plusSimplCount"
  518. -- We use one or the other consistently
  519. pprSimplCount (VerySimplCount n) = ptext (sLit "Total ticks:") <+> int n
  520. pprSimplCount (SimplCount { ticks = tks, details = dts, log1 = l1, log2 = l2 })
  521. = vcat [ptext (sLit "Total ticks: ") <+> int tks,
  522. blankLine,
  523. pprTickCounts dts,
  524. if verboseSimplStats then
  525. vcat [blankLine,
  526. ptext (sLit "Log (most recent first)"),
  527. nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
  528. else empty
  529. ]
  530. pprTickCounts :: Map Tick Int -> SDoc
  531. pprTickCounts counts
  532. = vcat (map pprTickGroup groups)
  533. where
  534. groups :: [[(Tick,Int)]] -- Each group shares a comon tag
  535. -- toList returns common tags adjacent
  536. groups = runs same_tag (Map.toList counts)
  537. same_tag (tick1,_) (tick2,_) = tickToTag tick1 == tickToTag tick2
  538. pprTickGroup :: [(Tick, Int)] -> SDoc
  539. pprTickGroup group@((tick1,_):_)
  540. = hang (int (sum [n | (_,n) <- group]) <+> text (tickString tick1))
  541. 2 (vcat [ int n <+> pprTickCts tick
  542. -- flip as we want largest first
  543. | (tick,n) <- sortBy (flip (comparing snd)) group])
  544. pprTickGroup [] = panic "pprTickGroup"
  545. \end{code}
  546. \begin{code}
  547. data Tick
  548. = PreInlineUnconditionally Id
  549. | PostInlineUnconditionally Id
  550. | UnfoldingDone Id
  551. | RuleFired FastString -- Rule name
  552. | LetFloatFromLet
  553. | EtaExpansion Id -- LHS binder
  554. | EtaReduction Id -- Binder on outer lambda
  555. | BetaReduction Id -- Lambda binder
  556. | CaseOfCase Id -- Bndr on *inner* case
  557. | KnownBranch Id -- Case binder
  558. | CaseMerge Id -- Binder on outer case
  559. | AltMerge Id -- Case binder
  560. | CaseElim Id -- Case binder
  561. | CaseIdentity Id -- Case binder
  562. | FillInCaseDefault Id -- Case binder
  563. | BottomFound
  564. | SimplifierDone -- Ticked at each iteration of the simplifier
  565. instance Outputable Tick where
  566. ppr tick = text (tickString tick) <+> pprTickCts tick
  567. instance Eq Tick where
  568. a == b = case a `cmpTick` b of
  569. EQ -> True
  570. _ -> False
  571. instance Ord Tick where
  572. compare = cmpTick
  573. tickToTag :: Tick -> Int
  574. tickToTag (PreInlineUnconditionally _) = 0
  575. tickToTag (PostInlineUnconditionally _) = 1
  576. tickToTag (UnfoldingDone _) = 2
  577. tickToTag (RuleFired _) = 3
  578. tickToTag LetFloatFromLet = 4
  579. tickToTag (EtaExpansion _) = 5
  580. tickToTag (EtaReduction _) = 6
  581. tickToTag (BetaReduction _) = 7
  582. tickToTag (CaseOfCase _) = 8
  583. tickToTag (KnownBranch _) = 9
  584. tickToTag (CaseMerge _) = 10
  585. tickToTag (CaseElim _) = 11
  586. tickToTag (CaseIdentity _) = 12
  587. tickToTag (FillInCaseDefault _) = 13
  588. tickToTag BottomFound = 14
  589. tickToTag SimplifierDone = 16
  590. tickToTag (AltMerge _) = 17
  591. tickString :: Tick -> String
  592. tickString (PreInlineUnconditionally _) = "PreInlineUnconditionally"
  593. tickString (PostInlineUnconditionally _)= "PostInlineUnconditionally"
  594. tickString (UnfoldingDone _) = "UnfoldingDone"
  595. tickString (RuleFired _) = "RuleFired"
  596. tickString LetFloatFromLet = "LetFloatFromLet"
  597. tickString (EtaExpansion _) = "EtaExpansion"
  598. tickString (EtaReduction _) = "EtaReduction"
  599. tickString (BetaReduction _) = "BetaReduction"
  600. tickString (CaseOfCase _) = "CaseOfCase"
  601. tickString (KnownBranch _) = "KnownBranch"
  602. tickString (CaseMerge _) = "CaseMerge"
  603. tickString (AltMerge _) = "AltMerge"
  604. tickString (CaseElim _) = "CaseElim"
  605. tickString (CaseIdentity _) = "CaseIdentity"
  606. tickString (FillInCaseDefault _) = "FillInCaseDefault"
  607. tickString BottomFound = "BottomFound"
  608. tickString SimplifierDone = "SimplifierDone"
  609. pprTickCts :: Tick -> SDoc
  610. pprTickCts (PreInlineUnconditionally v) = ppr v
  611. pprTickCts (PostInlineUnconditionally v)= ppr v
  612. pprTickCts (UnfoldingDone v) = ppr v
  613. pprTickCts (RuleFired v) = ppr v
  614. pprTickCts LetFloatFromLet = empty
  615. pprTickCts (EtaExpansion v) = ppr v
  616. pprTickCts (EtaReduction v) = ppr v
  617. pprTickCts (BetaReduction v) = ppr v
  618. pprTickCts (CaseOfCase v) = ppr v
  619. pprTickCts (KnownBranch v) = ppr v
  620. pprTickCts (CaseMerge v) = ppr v
  621. pprTickCts (AltMerge v) = ppr v
  622. pprTickCts (CaseElim v) = ppr v
  623. pprTickCts (CaseIdentity v) = ppr v
  624. pprTickCts (FillInCaseDefault v) = ppr v
  625. pprTickCts _ = empty
  626. cmpTick :: Tick -> Tick -> Ordering
  627. cmpTick a b = case (tickToTag a `compare` tickToTag b) of
  628. GT -> GT
  629. EQ -> cmpEqTick a b
  630. LT -> LT
  631. cmpEqTick :: Tick -> Tick -> Ordering
  632. cmpEqTick (PreInlineUnconditionally a) (PreInlineUnconditionally b) = a `compare` b
  633. cmpEqTick (PostInlineUnconditionally a) (PostInlineUnconditionally b) = a `compare` b
  634. cmpEqTick (UnfoldingDone a) (UnfoldingDone b) = a `compare` b
  635. cmpEqTick (RuleFired a) (RuleFired b) = a `compare` b
  636. cmpEqTick (EtaExpansion a) (EtaExpansion b) = a `compare` b
  637. cmpEqTick (EtaReduction a) (EtaReduction b) = a `compare` b
  638. cmpEqTick (BetaReduction a) (BetaReduction b) = a `compare` b
  639. cmpEqTick (CaseOfCase a) (CaseOfCase b) = a `compare` b
  640. cmpEqTick (KnownBranch a) (KnownBranch b) = a `compare` b
  641. cmpEqTick (CaseMerge a) (CaseMerge b) = a `compare` b
  642. cmpEqTick (AltMerge a) (AltMerge b) = a `compare` b
  643. cmpEqTick (CaseElim a) (CaseElim b) = a `compare` b
  644. cmpEqTick (CaseIdentity a) (CaseIdentity b) = a `compare` b
  645. cmpEqTick (FillInCaseDefault a) (FillInCaseDefault b) = a `compare` b
  646. cmpEqTick _ _ = EQ
  647. \end{code}
  648. %************************************************************************
  649. %* *
  650. Monad and carried data structure definitions
  651. %* *
  652. %************************************************************************
  653. \begin{code}
  654. newtype CoreState = CoreState {
  655. cs_uniq_supply :: UniqSupply
  656. }
  657. data CoreReader = CoreReader {
  658. cr_hsc_env :: HscEnv,
  659. cr_rule_base :: RuleBase,
  660. cr_module :: Module,
  661. #ifdef GHCI
  662. cr_globals :: (MVar PersistentLinkerState, Bool)
  663. #else
  664. cr_globals :: ()
  665. #endif
  666. }
  667. data CoreWriter = CoreWriter {
  668. cw_simpl_count :: !SimplCount
  669. -- Making this strict fixes a nasty space leak
  670. -- See Trac #7702
  671. }
  672. emptyWriter :: DynFlags -> CoreWriter
  673. emptyWriter dflags = CoreWriter {
  674. cw_simpl_count = zeroSimplCount dflags
  675. }
  676. plusWriter :: CoreWriter -> CoreWriter -> CoreWriter
  677. plusWriter w1 w2 = CoreWriter {
  678. cw_simpl_count = (cw_simpl_count w1) `plusSimplCount` (cw_simpl_count w2)
  679. }
  680. type CoreIOEnv = IOEnv CoreReader
  681. -- | The monad used by Core-to-Core passes to access common state, register simplification
  682. -- statistics and so on
  683. newtype CoreM a = CoreM { unCoreM :: CoreState -> CoreIOEnv (a, CoreState, CoreWriter) }
  684. instance Functor CoreM where
  685. fmap f ma = do
  686. a <- ma
  687. return (f a)
  688. instance Monad CoreM where
  689. return x = CoreM (\s -> nop s x)
  690. mx >>= f = CoreM $ \s -> do
  691. (x, s', w1) <- unCoreM mx s
  692. (y, s'', w2) <- unCoreM (f x) s'
  693. let w = w1 `plusWriter` w2 -- forcing w before returning avoids a space leak (Trac #7702)
  694. return $ seq w (y, s'', w)
  695. instance A.Applicative CoreM where
  696. pure = return
  697. (<*>) = ap
  698. instance MonadPlus IO => A.Alternative CoreM where
  699. empty = mzero
  700. (<|>) = mplus
  701. -- For use if the user has imported Control.Monad.Error from MTL
  702. -- Requires UndecidableInstances
  703. instance MonadPlus IO => MonadPlus CoreM where
  704. mzero = CoreM (const mzero)
  705. m `mplus` n = CoreM (\rs -> unCoreM m rs `mplus` unCoreM n rs)
  706. instance MonadUnique CoreM where
  707. getUniqueSupplyM = do
  708. us <- getS cs_uniq_supply
  709. let (us1, us2) = splitUniqSupply us
  710. modifyS (\s -> s { cs_uniq_supply = us2 })
  711. return us1
  712. getUniqueM = do
  713. us <- getS cs_uniq_supply
  714. let (u,us') = takeUniqFromSupply us
  715. modifyS (\s -> s { cs_uniq_supply = us' })
  716. return u
  717. runCoreM :: HscEnv
  718. -> RuleBase
  719. -> UniqSupply
  720. -> Module
  721. -> CoreM a
  722. -> IO (a, SimplCount)
  723. runCoreM hsc_env rule_base us mod m = do
  724. glbls <- saveLinkerGlobals
  725. liftM extract $ runIOEnv (reader glbls) $ unCoreM m state
  726. where
  727. reader glbls = CoreReader {
  728. cr_hsc_env = hsc_env,
  729. cr_rule_base = rule_base,
  730. cr_module = mod,
  731. cr_globals = glbls
  732. }
  733. state = CoreState {
  734. cs_uniq_supply = us
  735. }
  736. extract :: (a, CoreState, CoreWriter) -> (a, SimplCount)
  737. extract (value, _, writer) = (value, cw_simpl_count writer)
  738. \end{code}
  739. %************************************************************************
  740. %* *
  741. Core combinators, not exported
  742. %* *
  743. %************************************************************************
  744. \begin{code}
  745. nop :: CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
  746. nop s x = do
  747. r <- getEnv
  748. return (x, s, emptyWriter $ (hsc_dflags . cr_hsc_env) r)
  749. read :: (CoreReader -> a) -> CoreM a
  750. read f = CoreM (\s -> getEnv >>= (\r -> nop s (f r)))
  751. getS :: (CoreState -> a) -> CoreM a
  752. getS f = CoreM (\s -> nop s (f s))
  753. modifyS :: (CoreState -> CoreState) -> CoreM ()
  754. modifyS f = CoreM (\s -> nop (f s) ())
  755. write :: CoreWriter -> CoreM ()
  756. write w = CoreM (\s -> return ((), s, w))
  757. \end{code}
  758. \subsection{Lifting IO into the monad}
  759. \begin{code}
  760. -- | Lift an 'IOEnv' operation into 'CoreM'
  761. liftIOEnv :: CoreIOEnv a -> CoreM a
  762. liftIOEnv mx = CoreM (\s -> mx >>= (\x -> nop s x))
  763. instance MonadIO CoreM where
  764. liftIO = liftIOEnv . IOEnv.liftIO
  765. -- | Lift an 'IO' operation into 'CoreM' while consuming its 'SimplCount'
  766. liftIOWithCount :: IO (SimplCount, a) -> CoreM a
  767. liftIOWithCount what = liftIO what >>= (\(count, x) -> addSimplCount count >> return x)
  768. \end{code}
  769. %************************************************************************
  770. %* *
  771. Reader, writer and state accessors
  772. %* *
  773. %************************************************************************
  774. \begin{code}
  775. getHscEnv :: CoreM HscEnv
  776. getHscEnv = read cr_hsc_env
  777. getRuleBase :: CoreM RuleBase
  778. getRuleBase = read cr_rule_base
  779. addSimplCount :: SimplCount -> CoreM ()
  780. addSimplCount count = write (CoreWriter { cw_simpl_count = count })
  781. -- Convenience accessors for useful fields of HscEnv
  782. instance HasDynFlags CoreM where
  783. getDynFlags = fmap hsc_dflags getHscEnv
  784. instance HasModule CoreM where
  785. getModule = read cr_module
  786. -- | The original name cache is the current mapping from 'Module' and
  787. -- 'OccName' to a compiler-wide unique 'Name'
  788. getOrigNameCache :: CoreM OrigNameCache
  789. getOrigNameCache = do
  790. nameCacheRef <- fmap hsc_NC getHscEnv
  791. liftIO $ fmap nsNames $ readIORef nameCacheRef
  792. \end{code}
  793. %************************************************************************
  794. %* *
  795. Initializing globals
  796. %* *
  797. %************************************************************************
  798. This is a rather annoying function. When a plugin is loaded, it currently
  799. gets linked against a *newly loaded* copy of the GHC package. This would
  800. not be a problem, except that the new copy has its own mutable state
  801. that is not shared with that state that has already been initialized by
  802. the original GHC package.
  803. (NB This mechanism is sufficient for granting plugins read-only access to
  804. globals that are guaranteed to be initialized before the plugin is loaded. If
  805. any further synchronization is necessary, I would suggest using the more
  806. sophisticated mechanism involving GHC.Conc.Sync.sharedCAF and rts/Globals.c to
  807. share a single instance of the global variable among the compiler and the
  808. plugins. Perhaps we should migrate all global variables to use that mechanism,
  809. for robustness... -- NSF July 2013)
  810. This leads to loaded plugins calling GHC code which pokes the static flags,
  811. and then dying with a panic because the static flags *it* sees are uninitialized.
  812. There are two possible solutions:
  813. 1. Export the symbols from the GHC executable from the GHC library and link
  814. against this existing copy rather than a new copy of the GHC library
  815. 2. Carefully ensure that the global state in the two copies of the GHC
  816. library matches
  817. I tried 1. and it *almost* works (and speeds up plugin load times!) except
  818. on Windows. On Windows the GHC library tends to export more than 65536 symbols
  819. (see #5292) which overflows the limit of what we can export from the EXE and
  820. causes breakage.
  821. (Note that if the GHC exeecutable was dynamically linked this wouldn't be a problem,
  822. because we could share the GHC library it links to.)
  823. We are going to try 2. instead. Unfortunately, this means that every plugin
  824. will have to say `reinitializeGlobals` before it does anything, but never mind.
  825. I've threaded the cr_globals through CoreM rather than giving them as an
  826. argument to the plugin function so that we can turn this function into
  827. (return ()) without breaking any plugins when we eventually get 1. working.
  828. \begin{code}
  829. reinitializeGlobals :: CoreM ()
  830. reinitializeGlobals = do
  831. linker_globals <- read cr_globals
  832. hsc_env <- getHscEnv
  833. let dflags = hsc_dflags hsc_env
  834. liftIO $ restoreLinkerGlobals linker_globals
  835. liftIO $ setUnsafeGlobalDynFlags dflags
  836. \end{code}
  837. %************************************************************************
  838. %* *
  839. Dealing with annotations
  840. %* *
  841. %************************************************************************
  842. \begin{code}
  843. -- | Get all annotations of a given type. This happens lazily, that is
  844. -- no deserialization will take place until the [a] is actually demanded and
  845. -- the [a] can also be empty (the UniqFM is not filtered).
  846. --
  847. -- This should be done once at the start of a Core-to-Core pass that uses
  848. -- annotations.
  849. --
  850. -- See Note [Annotations]
  851. getAnnotations :: Typeable a => ([Word8] -> a) -> ModGuts -> CoreM (UniqFM [a])
  852. getAnnotations deserialize guts = do
  853. hsc_env <- getHscEnv
  854. ann_env <- liftIO $ prepareAnnotations hsc_env (Just guts)
  855. return (deserializeAnns deserialize ann_env)
  856. -- | Get at most one annotation of a given type per Unique.
  857. getFirstAnnotations :: Typeable a => ([Word8] -> a) -> ModGuts -> CoreM (UniqFM a)
  858. getFirstAnnotations deserialize guts
  859. = liftM (mapUFM head . filterUFM (not . null))
  860. $ getAnnotations deserialize guts
  861. \end{code}
  862. Note [Annotations]
  863. ~~~~~~~~~~~~~~~~~~
  864. A Core-to-Core pass that wants to make use of annotations calls
  865. getAnnotations or getFirstAnnotations at the beginning to obtain a UniqFM with
  866. annotations of a specific type. This produces all annotations from interface
  867. files read so far. However, annotations from interface files read during the
  868. pass will not be visible until getAnnotations is called again. This is similar
  869. to how rules work and probably isn't too bad.
  870. The current implementation could be optimised a bit: when looking up
  871. annotations for a thing from the HomePackageTable, we could search directly in
  872. the module where the thing is defined rather than building one UniqFM which
  873. contains all annotations we know of. This would work because annotations can
  874. only be given to things defined in the same module. However, since we would
  875. only want to deserialise every annotation once, we would have to build a cache
  876. for every module in the HTP. In the end, it's probably not worth it as long as
  877. we aren't using annotations heavily.
  878. %************************************************************************
  879. %* *
  880. Direct screen output
  881. %* *
  882. %************************************************************************
  883. \begin{code}
  884. msg :: (DynFlags -> SDoc -> IO ()) -> SDoc -> CoreM ()
  885. msg how doc = do
  886. dflags <- getDynFlags
  887. liftIO $ how dflags doc
  888. -- | Output a String message to the screen
  889. putMsgS :: String -> CoreM ()
  890. putMsgS = putMsg . text
  891. -- | Output a message to the screen
  892. putMsg :: SDoc -> CoreM ()
  893. putMsg = msg Err.putMsg
  894. -- | Output a string error to the screen
  895. errorMsgS :: String -> CoreM ()
  896. errorMsgS = errorMsg . text
  897. -- | Output an error to the screen
  898. errorMsg :: SDoc -> CoreM ()
  899. errorMsg = msg Err.errorMsg
  900. -- | Output a fatal string error to the screen. Note this does not by itself cause the compiler to die
  901. fatalErrorMsgS :: String -> CoreM ()
  902. fatalErrorMsgS = fatalErrorMsg . text
  903. -- | Output a fatal error to the screen. Note this does not by itself cause the compiler to die
  904. fatalErrorMsg :: SDoc -> CoreM ()
  905. fatalErrorMsg = msg Err.fatalErrorMsg
  906. -- | Output a string debugging message at verbosity level of @-v@ or higher
  907. debugTraceMsgS :: String -> CoreM ()
  908. debugTraceMsgS = debugTraceMsg . text
  909. -- | Outputs a debugging message at verbosity level of @-v@ or higher
  910. debugTraceMsg :: SDoc -> CoreM ()
  911. debugTraceMsg = msg (flip Err.debugTraceMsg 3)
  912. -- | Show some labelled 'SDoc' if a particular flag is set or at a verbosity level of @-v -ddump-most@ or higher
  913. dumpIfSet_dyn :: DumpFlag -> String -> SDoc -> CoreM ()
  914. dumpIfSet_dyn flag str = msg (\dflags -> Err.dumpIfSet_dyn dflags flag str)
  915. \end{code}
  916. %************************************************************************
  917. %* *
  918. Finding TyThings
  919. %* *
  920. %************************************************************************
  921. \begin{code}
  922. instance MonadThings CoreM where
  923. lookupThing name = do
  924. hsc_env <- getHscEnv
  925. liftIO $ initTcForLookup hsc_env (tcLookupGlobal name)
  926. \end{code}
  927. %************************************************************************
  928. %* *
  929. Template Haskell interoperability
  930. %* *
  931. %************************************************************************
  932. \begin{code}
  933. #ifdef GHCI
  934. -- | Attempt to convert a Template Haskell name to one that GHC can
  935. -- understand. Original TH names such as those you get when you use
  936. -- the @'foo@ syntax will be translated to their equivalent GHC name
  937. -- exactly. Qualified or unqualifed TH names will be dynamically bound
  938. -- to names in the module being compiled, if possible. Exact TH names
  939. -- will be bound to the name they represent, exactly.
  940. thNameToGhcName :: TH.Name -> CoreM (Maybe Name)
  941. thNameToGhcName th_name = do
  942. hsc_env <- getHscEnv
  943. liftIO $ initTcForLookup hsc_env (lookupThName_maybe th_name)
  944. #endif
  945. \end{code}