PageRenderTime 84ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/simplCore/CoreMonad.lhs

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