PageRenderTime 62ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/ghc-7.0.4/compiler/main/HscMain.lhs

http://picorec.googlecode.com/
Haskell | 1103 lines | 803 code | 161 blank | 139 comment | 18 complexity | 2bcb81a409fd2674b8b0442427651743 MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause
  1. %
  2. % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
  3. %
  4. \begin{code}
  5. -- | Main driver for the compiling plain Haskell source code.
  6. --
  7. -- This module implements compilation of a Haskell-only source file. It is
  8. -- /not/ concerned with preprocessing of source files; this is handled in
  9. -- "DriverPipeline".
  10. --
  11. module HscMain
  12. ( newHscEnv, hscCmmFile
  13. , hscParseIdentifier
  14. , hscSimplify
  15. , hscNormalIface, hscWriteIface, hscGenHardCode
  16. #ifdef GHCI
  17. , hscStmt, hscTcExpr, hscImport, hscKcType
  18. , compileExpr
  19. #endif
  20. , HsCompiler(..)
  21. , hscOneShotCompiler, hscNothingCompiler
  22. , hscInteractiveCompiler, hscBatchCompiler
  23. , hscCompileOneShot -- :: Compiler HscStatus
  24. , hscCompileBatch -- :: Compiler (HscStatus, ModIface, ModDetails)
  25. , hscCompileNothing -- :: Compiler (HscStatus, ModIface, ModDetails)
  26. , hscCompileInteractive -- :: Compiler (InteractiveStatus, ModIface, ModDetails)
  27. , hscCheckRecompBackend
  28. , HscStatus' (..)
  29. , InteractiveStatus, HscStatus
  30. -- The new interface
  31. , hscParse
  32. , hscTypecheck
  33. , hscTypecheckRename
  34. , hscDesugar
  35. , makeSimpleIface
  36. , makeSimpleDetails
  37. ) where
  38. #ifdef GHCI
  39. import CodeOutput ( outputForeignStubs )
  40. import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
  41. import Linker ( HValue, linkExpr )
  42. import CoreTidy ( tidyExpr )
  43. import CorePrep ( corePrepExpr )
  44. import Desugar ( deSugarExpr )
  45. import SimplCore ( simplifyExpr )
  46. import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnType )
  47. import Type ( Type, tyVarsOfTypes )
  48. import PrelNames ( iNTERACTIVE )
  49. import {- Kind parts of -} Type ( Kind )
  50. import Id ( idType )
  51. import CoreLint ( lintUnfolding )
  52. import DsMeta ( templateHaskellNames )
  53. import SrcLoc ( SrcSpan, noSrcLoc, interactiveSrcLoc, srcLocSpan, noSrcSpan, unLoc )
  54. import VarSet
  55. import VarEnv ( emptyTidyEnv )
  56. import Panic
  57. #endif
  58. import Id ( Id )
  59. import Module ( emptyModuleEnv, ModLocation(..), Module )
  60. import RdrName
  61. import HsSyn
  62. import CoreSyn
  63. import SrcLoc ( Located(..) )
  64. import StringBuffer
  65. import Parser
  66. import Lexer
  67. import SrcLoc ( mkSrcLoc )
  68. import TcRnDriver ( tcRnModule )
  69. import TcIface ( typecheckIface )
  70. import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
  71. import IfaceEnv ( initNameCache )
  72. import LoadIface ( ifaceStats, initExternalPackageState )
  73. import PrelInfo ( wiredInThings, basicKnownKeyNames )
  74. import MkIface
  75. import Desugar ( deSugar )
  76. import SimplCore ( core2core )
  77. import TidyPgm
  78. import CorePrep ( corePrepPgm )
  79. import CoreToStg ( coreToStg )
  80. import qualified StgCmm ( codeGen )
  81. import StgSyn
  82. import CostCentre
  83. import TyCon ( TyCon, isDataTyCon )
  84. import Name ( Name, NamedThing(..) )
  85. import SimplStg ( stg2stg )
  86. import CodeGen ( codeGen )
  87. import Cmm ( Cmm )
  88. import PprCmm ( pprCmms )
  89. import CmmParse ( parseCmmFile )
  90. import CmmBuildInfoTables
  91. import CmmCPS
  92. import CmmCPSZ
  93. import CmmInfo
  94. import OptimizationFuel ( initOptFuelState )
  95. import CmmCvt
  96. import CmmTx
  97. import CmmContFlowOpt
  98. import CodeOutput ( codeOutput )
  99. import NameEnv ( emptyNameEnv )
  100. import Fingerprint ( Fingerprint )
  101. import DynFlags
  102. import ErrUtils
  103. import UniqSupply ( mkSplitUniqSupply )
  104. import Outputable
  105. import HscStats ( ppSourceStats )
  106. import HscTypes
  107. import MkExternalCore ( emitExternalCore )
  108. import FastString
  109. import UniqFM ( emptyUFM )
  110. import UniqSupply ( initUs_ )
  111. import Bag ( unitBag )
  112. import Exception
  113. -- import MonadUtils
  114. import Control.Monad
  115. -- import System.IO
  116. import Data.IORef
  117. \end{code}
  118. #include "HsVersions.h"
  119. %************************************************************************
  120. %* *
  121. Initialisation
  122. %* *
  123. %************************************************************************
  124. \begin{code}
  125. newHscEnv :: GhcApiCallbacks -> DynFlags -> IO HscEnv
  126. newHscEnv callbacks dflags
  127. = do { eps_var <- newIORef initExternalPackageState
  128. ; us <- mkSplitUniqSupply 'r'
  129. ; nc_var <- newIORef (initNameCache us knownKeyNames)
  130. ; fc_var <- newIORef emptyUFM
  131. ; mlc_var <- newIORef emptyModuleEnv
  132. ; optFuel <- initOptFuelState
  133. ; return (HscEnv { hsc_dflags = dflags,
  134. hsc_callbacks = callbacks,
  135. hsc_targets = [],
  136. hsc_mod_graph = [],
  137. hsc_IC = emptyInteractiveContext,
  138. hsc_HPT = emptyHomePackageTable,
  139. hsc_EPS = eps_var,
  140. hsc_NC = nc_var,
  141. hsc_FC = fc_var,
  142. hsc_MLC = mlc_var,
  143. hsc_OptFuel = optFuel,
  144. hsc_type_env_var = Nothing } ) }
  145. knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
  146. -- where templateHaskellNames are defined
  147. knownKeyNames = map getName wiredInThings
  148. ++ basicKnownKeyNames
  149. #ifdef GHCI
  150. ++ templateHaskellNames
  151. #endif
  152. \end{code}
  153. \begin{code}
  154. -- | parse a file, returning the abstract syntax
  155. hscParse :: GhcMonad m =>
  156. ModSummary
  157. -> m (Located (HsModule RdrName))
  158. hscParse mod_summary = do
  159. hsc_env <- getSession
  160. let dflags = hsc_dflags hsc_env
  161. src_filename = ms_hspp_file mod_summary
  162. maybe_src_buf = ms_hspp_buf mod_summary
  163. -------------------------- Parser ----------------
  164. liftIO $ showPass dflags "Parser"
  165. {-# SCC "Parser" #-} do
  166. -- sometimes we already have the buffer in memory, perhaps
  167. -- because we needed to parse the imports out of it, or get the
  168. -- module name.
  169. buf <- case maybe_src_buf of
  170. Just b -> return b
  171. Nothing -> liftIO $ hGetStringBuffer src_filename
  172. let loc = mkSrcLoc (mkFastString src_filename) 1 1
  173. case unP parseModule (mkPState dflags buf loc) of
  174. PFailed span err ->
  175. throwOneError (mkPlainErrMsg span err)
  176. POk pst rdr_module -> do
  177. let ms@(warns,errs) = getMessages pst
  178. logWarnings warns
  179. if errorsFound dflags ms then
  180. liftIO $ throwIO $ mkSrcErr errs
  181. else liftIO $ do
  182. dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
  183. dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
  184. (ppSourceStats False rdr_module) ;
  185. return rdr_module
  186. -- ToDo: free the string buffer later.
  187. -- | Rename and typecheck a module
  188. hscTypecheck :: GhcMonad m =>
  189. ModSummary -> Located (HsModule RdrName)
  190. -> m TcGblEnv
  191. hscTypecheck mod_summary rdr_module = do
  192. hsc_env <- getSession
  193. r <- {-# SCC "Typecheck-Rename" #-}
  194. ioMsgMaybe $ tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
  195. return r
  196. -- XXX: should this really be a Maybe X? Check under which circumstances this
  197. -- can become a Nothing and decide whether this should instead throw an
  198. -- exception/signal an error.
  199. type RenamedStuff =
  200. (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
  201. Maybe LHsDocString))
  202. -- | Rename and typecheck a module, additionally returning the renamed syntax
  203. hscTypecheckRename ::
  204. GhcMonad m =>
  205. ModSummary -> Located (HsModule RdrName)
  206. -> m (TcGblEnv, RenamedStuff)
  207. hscTypecheckRename mod_summary rdr_module = do
  208. hsc_env <- getSession
  209. tc_result
  210. <- {-# SCC "Typecheck-Rename" #-}
  211. ioMsgMaybe $ tcRnModule hsc_env (ms_hsc_src mod_summary) True rdr_module
  212. let -- This 'do' is in the Maybe monad!
  213. rn_info = do { decl <- tcg_rn_decls tc_result
  214. ; let imports = tcg_rn_imports tc_result
  215. exports = tcg_rn_exports tc_result
  216. doc_hdr = tcg_doc_hdr tc_result
  217. ; return (decl,imports,exports,doc_hdr) }
  218. return (tc_result, rn_info)
  219. -- | Convert a typechecked module to Core
  220. hscDesugar :: GhcMonad m => ModSummary -> TcGblEnv -> m ModGuts
  221. hscDesugar mod_summary tc_result =
  222. withSession $ \hsc_env ->
  223. ioMsgMaybe $ deSugar hsc_env (ms_location mod_summary) tc_result
  224. -- | Make a 'ModIface' from the results of typechecking. Used when
  225. -- not optimising, and the interface doesn't need to contain any
  226. -- unfoldings or other cross-module optimisation info.
  227. -- ToDo: the old interface is only needed to get the version numbers,
  228. -- we should use fingerprint versions instead.
  229. makeSimpleIface :: GhcMonad m =>
  230. Maybe ModIface -> TcGblEnv -> ModDetails
  231. -> m (ModIface,Bool)
  232. makeSimpleIface maybe_old_iface tc_result details =
  233. withSession $ \hsc_env ->
  234. ioMsgMaybe $ mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) details tc_result
  235. -- | Make a 'ModDetails' from the results of typechecking. Used when
  236. -- typechecking only, as opposed to full compilation.
  237. makeSimpleDetails :: GhcMonad m => TcGblEnv -> m ModDetails
  238. makeSimpleDetails tc_result =
  239. withSession $ \hsc_env -> liftIO $ mkBootModDetailsTc hsc_env tc_result
  240. \end{code}
  241. %************************************************************************
  242. %* *
  243. The main compiler pipeline
  244. %* *
  245. %************************************************************************
  246. --------------------------------
  247. The compilation proper
  248. --------------------------------
  249. It's the task of the compilation proper to compile Haskell, hs-boot and
  250. core files to either byte-code, hard-code (C, asm, Java, ect) or to
  251. nothing at all (the module is still parsed and type-checked. This
  252. feature is mostly used by IDE's and the likes).
  253. Compilation can happen in either 'one-shot', 'batch', 'nothing',
  254. or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
  255. targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
  256. targets byte-code.
  257. The modes are kept separate because of their different types and meanings.
  258. In 'one-shot' mode, we're only compiling a single file and can therefore
  259. discard the new ModIface and ModDetails. This is also the reason it only
  260. targets hard-code; compiling to byte-code or nothing doesn't make sense
  261. when we discard the result.
  262. 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
  263. and ModDetails. 'Batch' mode doesn't target byte-code since that require
  264. us to return the newly compiled byte-code.
  265. 'Nothing' mode has exactly the same type as 'batch' mode but they're still
  266. kept separate. This is because compiling to nothing is fairly special: We
  267. don't output any interface files, we don't run the simplifier and we don't
  268. generate any code.
  269. 'Interactive' mode is similar to 'batch' mode except that we return the
  270. compiled byte-code together with the ModIface and ModDetails.
  271. Trying to compile a hs-boot file to byte-code will result in a run-time
  272. error. This is the only thing that isn't caught by the type-system.
  273. \begin{code}
  274. -- Status of a compilation to hard-code or nothing.
  275. data HscStatus' a
  276. = HscNoRecomp
  277. | HscRecomp
  278. Bool -- Has stub files. This is a hack. We can't compile C files here
  279. -- since it's done in DriverPipeline. For now we just return True
  280. -- if we want the caller to compile them for us.
  281. a
  282. -- This is a bit ugly. Since we use a typeclass below and would like to avoid
  283. -- functional dependencies, we have to parameterise the typeclass over the
  284. -- result type. Therefore we need to artificially distinguish some types. We
  285. -- do this by adding type tags which will simply be ignored by the caller.
  286. type HscStatus = HscStatus' ()
  287. type InteractiveStatus = HscStatus' (Maybe (CompiledByteCode, ModBreaks))
  288. -- INVARIANT: result is @Nothing@ <=> input was a boot file
  289. type OneShotResult = HscStatus
  290. type BatchResult = (HscStatus, ModIface, ModDetails)
  291. type NothingResult = (HscStatus, ModIface, ModDetails)
  292. type InteractiveResult = (InteractiveStatus, ModIface, ModDetails)
  293. -- FIXME: The old interface and module index are only using in 'batch' and
  294. -- 'interactive' mode. They should be removed from 'oneshot' mode.
  295. type Compiler result = GhcMonad m =>
  296. HscEnv
  297. -> ModSummary
  298. -> Bool -- True <=> source unchanged
  299. -> Maybe ModIface -- Old interface, if available
  300. -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
  301. -> m result
  302. data HsCompiler a
  303. = HsCompiler {
  304. -- | Called when no recompilation is necessary.
  305. hscNoRecomp :: GhcMonad m =>
  306. ModIface -> m a,
  307. -- | Called to recompile the module.
  308. hscRecompile :: GhcMonad m =>
  309. ModSummary -> Maybe Fingerprint -> m a,
  310. hscBackend :: GhcMonad m =>
  311. TcGblEnv -> ModSummary -> Maybe Fingerprint -> m a,
  312. -- | Code generation for Boot modules.
  313. hscGenBootOutput :: GhcMonad m =>
  314. TcGblEnv -> ModSummary -> Maybe Fingerprint -> m a,
  315. -- | Code generation for normal modules.
  316. hscGenOutput :: GhcMonad m =>
  317. ModGuts -> ModSummary -> Maybe Fingerprint -> m a
  318. }
  319. genericHscCompile :: GhcMonad m =>
  320. HsCompiler a
  321. -> (Maybe (Int,Int) -> Bool -> ModSummary -> m ())
  322. -> HscEnv -> ModSummary -> Bool
  323. -> Maybe ModIface -> Maybe (Int, Int)
  324. -> m a
  325. genericHscCompile compiler hscMessage
  326. hsc_env mod_summary source_unchanged
  327. mb_old_iface0 mb_mod_index =
  328. withTempSession (\_ -> hsc_env) $ do
  329. (recomp_reqd, mb_checked_iface)
  330. <- {-# SCC "checkOldIface" #-}
  331. liftIO $ checkOldIface hsc_env mod_summary
  332. source_unchanged mb_old_iface0
  333. -- save the interface that comes back from checkOldIface.
  334. -- In one-shot mode we don't have the old iface until this
  335. -- point, when checkOldIface reads it from the disk.
  336. let mb_old_hash = fmap mi_iface_hash mb_checked_iface
  337. case mb_checked_iface of
  338. Just iface | not recomp_reqd
  339. -> do hscMessage mb_mod_index False mod_summary
  340. hscNoRecomp compiler iface
  341. _otherwise
  342. -> do hscMessage mb_mod_index True mod_summary
  343. hscRecompile compiler mod_summary mb_old_hash
  344. hscCheckRecompBackend :: HsCompiler a -> TcGblEnv -> Compiler a
  345. hscCheckRecompBackend compiler tc_result
  346. hsc_env mod_summary source_unchanged mb_old_iface _m_of_n =
  347. withTempSession (\_ -> hsc_env) $ do
  348. (recomp_reqd, mb_checked_iface)
  349. <- {-# SCC "checkOldIface" #-}
  350. liftIO $ checkOldIface hsc_env mod_summary
  351. source_unchanged mb_old_iface
  352. let mb_old_hash = fmap mi_iface_hash mb_checked_iface
  353. case mb_checked_iface of
  354. Just iface | not recomp_reqd
  355. -> hscNoRecomp compiler iface{ mi_globals = Just (tcg_rdr_env tc_result) }
  356. _otherwise
  357. -> hscBackend compiler tc_result mod_summary mb_old_hash
  358. genericHscRecompile :: GhcMonad m =>
  359. HsCompiler a
  360. -> ModSummary -> Maybe Fingerprint
  361. -> m a
  362. genericHscRecompile compiler mod_summary mb_old_hash
  363. | ExtCoreFile <- ms_hsc_src mod_summary =
  364. panic "GHC does not currently support reading External Core files"
  365. | otherwise = do
  366. tc_result <- hscFileFrontEnd mod_summary
  367. hscBackend compiler tc_result mod_summary mb_old_hash
  368. genericHscBackend :: GhcMonad m =>
  369. HsCompiler a
  370. -> TcGblEnv -> ModSummary -> Maybe Fingerprint
  371. -> m a
  372. genericHscBackend compiler tc_result mod_summary mb_old_hash
  373. | HsBootFile <- ms_hsc_src mod_summary =
  374. hscGenBootOutput compiler tc_result mod_summary mb_old_hash
  375. | otherwise = do
  376. guts <- hscDesugar mod_summary tc_result
  377. hscGenOutput compiler guts mod_summary mb_old_hash
  378. --------------------------------------------------------------
  379. -- Compilers
  380. --------------------------------------------------------------
  381. hscOneShotCompiler :: HsCompiler OneShotResult
  382. hscOneShotCompiler =
  383. HsCompiler {
  384. hscNoRecomp = \_old_iface -> do
  385. withSession (liftIO . dumpIfaceStats)
  386. return HscNoRecomp
  387. , hscRecompile = genericHscRecompile hscOneShotCompiler
  388. , hscBackend = \ tc_result mod_summary mb_old_hash -> do
  389. hsc_env <- getSession
  390. case hscTarget (hsc_dflags hsc_env) of
  391. HscNothing -> return (HscRecomp False ())
  392. _otherw -> genericHscBackend hscOneShotCompiler
  393. tc_result mod_summary mb_old_hash
  394. , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
  395. (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface
  396. hscWriteIface iface changed mod_summary
  397. return (HscRecomp False ())
  398. , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
  399. guts <- hscSimplify guts0
  400. (iface, changed, _details, cgguts)
  401. <- hscNormalIface guts mb_old_iface
  402. hscWriteIface iface changed mod_summary
  403. hasStub <- hscGenHardCode cgguts mod_summary
  404. return (HscRecomp hasStub ())
  405. }
  406. -- Compile Haskell, boot and extCore in OneShot mode.
  407. hscCompileOneShot :: Compiler OneShotResult
  408. hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n = do
  409. -- One-shot mode needs a knot-tying mutable variable for interface
  410. -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var.
  411. type_env_var <- liftIO $ newIORef emptyNameEnv
  412. let
  413. mod = ms_mod mod_summary
  414. hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
  415. ---
  416. genericHscCompile hscOneShotCompiler
  417. oneShotMsg hsc_env' mod_summary src_changed
  418. mb_old_iface mb_i_of_n
  419. --------------------------------------------------------------
  420. hscBatchCompiler :: HsCompiler BatchResult
  421. hscBatchCompiler =
  422. HsCompiler {
  423. hscNoRecomp = \iface -> do
  424. details <- genModDetails iface
  425. return (HscNoRecomp, iface, details)
  426. , hscRecompile = genericHscRecompile hscBatchCompiler
  427. , hscBackend = genericHscBackend hscBatchCompiler
  428. , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
  429. (iface, changed, details)
  430. <- hscSimpleIface tc_result mb_old_iface
  431. hscWriteIface iface changed mod_summary
  432. return (HscRecomp False (), iface, details)
  433. , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
  434. guts <- hscSimplify guts0
  435. (iface, changed, details, cgguts)
  436. <- hscNormalIface guts mb_old_iface
  437. hscWriteIface iface changed mod_summary
  438. hasStub <- hscGenHardCode cgguts mod_summary
  439. return (HscRecomp hasStub (), iface, details)
  440. }
  441. -- Compile Haskell, boot and extCore in batch mode.
  442. hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
  443. hscCompileBatch = genericHscCompile hscBatchCompiler batchMsg
  444. --------------------------------------------------------------
  445. hscInteractiveCompiler :: HsCompiler InteractiveResult
  446. hscInteractiveCompiler =
  447. HsCompiler {
  448. hscNoRecomp = \iface -> do
  449. details <- genModDetails iface
  450. return (HscNoRecomp, iface, details)
  451. , hscRecompile = genericHscRecompile hscInteractiveCompiler
  452. , hscBackend = genericHscBackend hscInteractiveCompiler
  453. , hscGenBootOutput = \tc_result _mod_summary mb_old_iface -> do
  454. (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
  455. return (HscRecomp False Nothing, iface, details)
  456. , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
  457. guts <- hscSimplify guts0
  458. (iface, _changed, details, cgguts)
  459. <- hscNormalIface guts mb_old_iface
  460. hscInteractive (iface, details, cgguts) mod_summary
  461. }
  462. -- Compile Haskell, extCore to bytecode.
  463. hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
  464. hscCompileInteractive = genericHscCompile hscInteractiveCompiler batchMsg
  465. --------------------------------------------------------------
  466. hscNothingCompiler :: HsCompiler NothingResult
  467. hscNothingCompiler =
  468. HsCompiler {
  469. hscNoRecomp = \iface -> do
  470. details <- genModDetails iface
  471. return (HscNoRecomp, iface, details)
  472. , hscRecompile = genericHscRecompile hscNothingCompiler
  473. , hscBackend = \tc_result _mod_summary mb_old_iface -> do
  474. (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
  475. return (HscRecomp False (), iface, details)
  476. , hscGenBootOutput = \_ _ _ ->
  477. panic "hscCompileNothing: hscGenBootOutput should not be called"
  478. , hscGenOutput = \_ _ _ ->
  479. panic "hscCompileNothing: hscGenOutput should not be called"
  480. }
  481. -- Type-check Haskell and .hs-boot only (no external core)
  482. hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
  483. hscCompileNothing = genericHscCompile hscNothingCompiler batchMsg
  484. --------------------------------------------------------------
  485. -- NoRecomp handlers
  486. --------------------------------------------------------------
  487. genModDetails :: GhcMonad m => ModIface -> m ModDetails
  488. genModDetails old_iface =
  489. withSession $ \hsc_env -> liftIO $ do
  490. new_details <- {-# SCC "tcRnIface" #-}
  491. initIfaceCheck hsc_env $
  492. typecheckIface old_iface
  493. dumpIfaceStats hsc_env
  494. return new_details
  495. --------------------------------------------------------------
  496. -- Progress displayers.
  497. --------------------------------------------------------------
  498. oneShotMsg :: GhcMonad m => Maybe (Int,Int) -> Bool -> ModSummary -> m ()
  499. oneShotMsg _mb_mod_index recomp _mod_summary
  500. = do hsc_env <- getSession
  501. liftIO $ do
  502. if recomp
  503. then return ()
  504. else compilationProgressMsg (hsc_dflags hsc_env) $
  505. "compilation IS NOT required"
  506. batchMsg :: GhcMonad m => Maybe (Int,Int) -> Bool -> ModSummary -> m ()
  507. batchMsg mb_mod_index recomp mod_summary
  508. = do hsc_env <- getSession
  509. let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
  510. (showModuleIndex mb_mod_index ++
  511. msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
  512. liftIO $ do
  513. if recomp
  514. then showMsg "Compiling "
  515. else if verbosity (hsc_dflags hsc_env) >= 2
  516. then showMsg "Skipping "
  517. else return ()
  518. --------------------------------------------------------------
  519. -- FrontEnds
  520. --------------------------------------------------------------
  521. hscFileFrontEnd :: GhcMonad m => ModSummary -> m TcGblEnv
  522. hscFileFrontEnd mod_summary =
  523. do rdr_module <- hscParse mod_summary
  524. hscTypecheck mod_summary rdr_module
  525. --------------------------------------------------------------
  526. -- Simplifiers
  527. --------------------------------------------------------------
  528. hscSimplify :: GhcMonad m => ModGuts -> m ModGuts
  529. hscSimplify ds_result
  530. = do hsc_env <- getSession
  531. simpl_result <- {-# SCC "Core2Core" #-}
  532. liftIO $ core2core hsc_env ds_result
  533. return simpl_result
  534. --------------------------------------------------------------
  535. -- Interface generators
  536. --------------------------------------------------------------
  537. hscSimpleIface :: GhcMonad m =>
  538. TcGblEnv
  539. -> Maybe Fingerprint
  540. -> m (ModIface, Bool, ModDetails)
  541. hscSimpleIface tc_result mb_old_iface
  542. = do hsc_env <- getSession
  543. details <- liftIO $ mkBootModDetailsTc hsc_env tc_result
  544. (new_iface, no_change)
  545. <- {-# SCC "MkFinalIface" #-}
  546. ioMsgMaybe $ mkIfaceTc hsc_env mb_old_iface details tc_result
  547. -- And the answer is ...
  548. liftIO $ dumpIfaceStats hsc_env
  549. return (new_iface, no_change, details)
  550. hscNormalIface :: GhcMonad m =>
  551. ModGuts
  552. -> Maybe Fingerprint
  553. -> m (ModIface, Bool, ModDetails, CgGuts)
  554. hscNormalIface simpl_result mb_old_iface
  555. = do hsc_env <- getSession
  556. (cg_guts, details) <- {-# SCC "CoreTidy" #-}
  557. liftIO $ tidyProgram hsc_env simpl_result
  558. -- BUILD THE NEW ModIface and ModDetails
  559. -- and emit external core if necessary
  560. -- This has to happen *after* code gen so that the back-end
  561. -- info has been set. Not yet clear if it matters waiting
  562. -- until after code output
  563. (new_iface, no_change)
  564. <- {-# SCC "MkFinalIface" #-}
  565. ioMsgMaybe $ mkIface hsc_env mb_old_iface
  566. details simpl_result
  567. -- Emit external core
  568. -- This should definitely be here and not after CorePrep,
  569. -- because CorePrep produces unqualified constructor wrapper declarations,
  570. -- so its output isn't valid External Core (without some preprocessing).
  571. liftIO $ emitExternalCore (hsc_dflags hsc_env) cg_guts
  572. liftIO $ dumpIfaceStats hsc_env
  573. -- Return the prepared code.
  574. return (new_iface, no_change, details, cg_guts)
  575. --------------------------------------------------------------
  576. -- BackEnd combinators
  577. --------------------------------------------------------------
  578. hscWriteIface :: GhcMonad m =>
  579. ModIface -> Bool
  580. -> ModSummary
  581. -> m ()
  582. hscWriteIface iface no_change mod_summary
  583. = do hsc_env <- getSession
  584. let dflags = hsc_dflags hsc_env
  585. liftIO $ do
  586. unless no_change
  587. $ writeIfaceFile dflags (ms_location mod_summary) iface
  588. -- | Compile to hard-code.
  589. hscGenHardCode :: GhcMonad m =>
  590. CgGuts -> ModSummary
  591. -> m Bool -- ^ @True@ <=> stub.c exists
  592. hscGenHardCode cgguts mod_summary
  593. = withSession $ \hsc_env -> liftIO $ do
  594. let CgGuts{ -- This is the last use of the ModGuts in a compilation.
  595. -- From now on, we just use the bits we need.
  596. cg_module = this_mod,
  597. cg_binds = core_binds,
  598. cg_tycons = tycons,
  599. cg_dir_imps = dir_imps,
  600. cg_foreign = foreign_stubs,
  601. cg_dep_pkgs = dependencies,
  602. cg_hpc_info = hpc_info } = cgguts
  603. dflags = hsc_dflags hsc_env
  604. location = ms_location mod_summary
  605. data_tycons = filter isDataTyCon tycons
  606. -- cg_tycons includes newtypes, for the benefit of External Core,
  607. -- but we don't generate any code for newtypes
  608. -------------------
  609. -- PREPARE FOR CODE GENERATION
  610. -- Do saturation and convert to A-normal form
  611. prepd_binds <- {-# SCC "CorePrep" #-}
  612. corePrepPgm dflags core_binds data_tycons ;
  613. ----------------- Convert to STG ------------------
  614. (stg_binds, cost_centre_info)
  615. <- {-# SCC "CoreToStg" #-}
  616. myCoreToStg dflags this_mod prepd_binds
  617. ------------------ Code generation ------------------
  618. cmms <- if dopt Opt_TryNewCodeGen (hsc_dflags hsc_env)
  619. then do cmms <- tryNewCodeGen hsc_env this_mod data_tycons
  620. dir_imps cost_centre_info
  621. stg_binds hpc_info
  622. return cmms
  623. else {-# SCC "CodeGen" #-}
  624. codeGen dflags this_mod data_tycons
  625. dir_imps cost_centre_info
  626. stg_binds hpc_info
  627. --- Optionally run experimental Cmm transformations ---
  628. -- cmms <- optionallyConvertAndOrCPS hsc_env cmms
  629. -- unless certain dflags are on, the identity function
  630. ------------------ Code output -----------------------
  631. rawcmms <- cmmToRawCmm cmms
  632. dumpIfSet_dyn dflags Opt_D_dump_cmmz "Raw Cmm" (ppr rawcmms)
  633. (_stub_h_exists, stub_c_exists)
  634. <- codeOutput dflags this_mod location foreign_stubs
  635. dependencies rawcmms
  636. return stub_c_exists
  637. hscInteractive :: GhcMonad m =>
  638. (ModIface, ModDetails, CgGuts)
  639. -> ModSummary
  640. -> m (InteractiveStatus, ModIface, ModDetails)
  641. #ifdef GHCI
  642. hscInteractive (iface, details, cgguts) mod_summary
  643. = do hsc_env <- getSession
  644. liftIO $ do
  645. let CgGuts{ -- This is the last use of the ModGuts in a compilation.
  646. -- From now on, we just use the bits we need.
  647. cg_module = this_mod,
  648. cg_binds = core_binds,
  649. cg_tycons = tycons,
  650. cg_foreign = foreign_stubs,
  651. cg_modBreaks = mod_breaks } = cgguts
  652. dflags = hsc_dflags hsc_env
  653. location = ms_location mod_summary
  654. data_tycons = filter isDataTyCon tycons
  655. -- cg_tycons includes newtypes, for the benefit of External Core,
  656. -- but we don't generate any code for newtypes
  657. -------------------
  658. -- PREPARE FOR CODE GENERATION
  659. -- Do saturation and convert to A-normal form
  660. prepd_binds <- {-# SCC "CorePrep" #-}
  661. corePrepPgm dflags core_binds data_tycons ;
  662. ----------------- Generate byte code ------------------
  663. comp_bc <- byteCodeGen dflags prepd_binds data_tycons mod_breaks
  664. ------------------ Create f-x-dynamic C-side stuff ---
  665. (_istub_h_exists, istub_c_exists)
  666. <- outputForeignStubs dflags this_mod location foreign_stubs
  667. return (HscRecomp istub_c_exists (Just (comp_bc, mod_breaks))
  668. , iface, details)
  669. #else
  670. hscInteractive _ _ = panic "GHC not compiled with interpreter"
  671. #endif
  672. ------------------------------
  673. hscCmmFile :: GhcMonad m => HscEnv -> FilePath -> m ()
  674. hscCmmFile hsc_env filename = do
  675. dflags <- return $ hsc_dflags hsc_env
  676. cmm <- ioMsgMaybe $
  677. parseCmmFile dflags filename
  678. cmms <- liftIO $ optionallyConvertAndOrCPS hsc_env [cmm]
  679. rawCmms <- liftIO $ cmmToRawCmm cmms
  680. _ <- liftIO $ codeOutput dflags no_mod no_loc NoStubs [] rawCmms
  681. return ()
  682. where
  683. no_mod = panic "hscCmmFile: no_mod"
  684. no_loc = ModLocation{ ml_hs_file = Just filename,
  685. ml_hi_file = panic "hscCmmFile: no hi file",
  686. ml_obj_file = panic "hscCmmFile: no obj file" }
  687. -------------------- Stuff for new code gen ---------------------
  688. tryNewCodeGen :: HscEnv -> Module -> [TyCon] -> [Module]
  689. -> CollectedCCs
  690. -> [(StgBinding,[(Id,[Id])])]
  691. -> HpcInfo
  692. -> IO [Cmm]
  693. tryNewCodeGen hsc_env this_mod data_tycons imported_mods
  694. cost_centre_info stg_binds hpc_info =
  695. do { let dflags = hsc_dflags hsc_env
  696. ; prog <- StgCmm.codeGen dflags this_mod data_tycons imported_mods
  697. cost_centre_info stg_binds hpc_info
  698. ; dumpIfSet_dyn dflags Opt_D_dump_cmmz "Cmm produced by new codegen"
  699. (pprCmms prog)
  700. ; prog <- return $ map (runTx $ runCmmOpts cmmCfgOptsZ) prog
  701. -- Control flow optimisation
  702. -- We are building a single SRT for the entire module, so
  703. -- we must thread it through all the procedures as we cps-convert them.
  704. ; us <- mkSplitUniqSupply 'S'
  705. ; let topSRT = initUs_ us emptySRT
  706. ; (topSRT, prog) <- foldM (protoCmmCPSZ hsc_env) (topSRT, []) prog
  707. -- The main CPS conversion
  708. ; prog <- return $ map (runTx $ runCmmOpts cmmCfgOptsZ) (srtToData topSRT : prog)
  709. -- Control flow optimisation, again
  710. ; let prog' = map cmmOfZgraph prog
  711. ; dumpIfSet_dyn dflags Opt_D_dump_cmmz "Output Cmm" (ppr prog')
  712. ; return prog' }
  713. optionallyConvertAndOrCPS :: HscEnv -> [Cmm] -> IO [Cmm]
  714. optionallyConvertAndOrCPS hsc_env cmms =
  715. do let dflags = hsc_dflags hsc_env
  716. -------- Optionally convert to and from zipper ------
  717. cmms <- if dopt Opt_ConvertToZipCfgAndBack dflags
  718. then mapM (testCmmConversion hsc_env) cmms
  719. else return cmms
  720. --------- Optionally convert to CPS (MDA) -----------
  721. cmms <- if not (dopt Opt_ConvertToZipCfgAndBack dflags) &&
  722. dopt Opt_RunCPS dflags
  723. then cmmCPS dflags cmms
  724. else return cmms
  725. return cmms
  726. testCmmConversion :: HscEnv -> Cmm -> IO Cmm
  727. testCmmConversion hsc_env cmm =
  728. do let dflags = hsc_dflags hsc_env
  729. showPass dflags "CmmToCmm"
  730. dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- pre-conversion" (ppr cmm)
  731. --continuationC <- cmmCPS dflags abstractC >>= cmmToRawCmm
  732. us <- mkSplitUniqSupply 'C'
  733. let cfopts = runTx $ runCmmOpts cmmCfgOptsZ
  734. let cvtm = do g <- cmmToZgraph cmm
  735. return $ cfopts g
  736. let zgraph = initUs_ us cvtm
  737. us <- mkSplitUniqSupply 'S'
  738. let topSRT = initUs_ us emptySRT
  739. (_, [cps_zgraph]) <- protoCmmCPSZ hsc_env (topSRT, []) zgraph
  740. let chosen_graph = if dopt Opt_RunCPSZ dflags then cps_zgraph else zgraph
  741. dumpIfSet_dyn dflags Opt_D_dump_cmmz "C-- Zipper Graph" (ppr chosen_graph)
  742. showPass dflags "Convert from Z back to Cmm"
  743. let cvt = cmmOfZgraph $ cfopts $ chosen_graph
  744. dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- post-conversion" (ppr cvt)
  745. return cvt
  746. myCoreToStg :: DynFlags -> Module -> [CoreBind]
  747. -> IO ( [(StgBinding,[(Id,[Id])])] -- output program
  748. , CollectedCCs) -- cost centre info (declared and used)
  749. myCoreToStg dflags this_mod prepd_binds
  750. = do
  751. stg_binds <- {-# SCC "Core2Stg" #-}
  752. coreToStg (thisPackage dflags) prepd_binds
  753. (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
  754. stg2stg dflags this_mod stg_binds
  755. return (stg_binds2, cost_centre_info)
  756. \end{code}
  757. %************************************************************************
  758. %* *
  759. \subsection{Compiling a do-statement}
  760. %* *
  761. %************************************************************************
  762. When the UnlinkedBCOExpr is linked you get an HValue of type
  763. IO [HValue]
  764. When you run it you get a list of HValues that should be
  765. the same length as the list of names; add them to the ClosureEnv.
  766. A naked expression returns a singleton Name [it].
  767. What you type The IO [HValue] that hscStmt returns
  768. ------------- ------------------------------------
  769. let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
  770. bindings: [x,y,...]
  771. pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
  772. bindings: [x,y,...]
  773. expr (of IO type) ==> expr >>= \ v -> return [v]
  774. [NB: result not printed] bindings: [it]
  775. expr (of non-IO type,
  776. result showable) ==> let v = expr in print v >> return [v]
  777. bindings: [it]
  778. expr (of non-IO type,
  779. result not showable) ==> error
  780. \begin{code}
  781. #ifdef GHCI
  782. hscStmt -- Compile a stmt all the way to an HValue, but don't run it
  783. :: GhcMonad m =>
  784. HscEnv
  785. -> String -- The statement
  786. -> m (Maybe ([Id], HValue))
  787. -- ^ 'Nothing' <==> empty statement (or comment only), but no parse error
  788. hscStmt hsc_env stmt = do
  789. maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
  790. case maybe_stmt of
  791. Nothing -> return Nothing
  792. Just parsed_stmt -> do -- The real stuff
  793. -- Rename and typecheck it
  794. let icontext = hsc_IC hsc_env
  795. (ids, tc_expr) <- ioMsgMaybe $ tcRnStmt hsc_env icontext parsed_stmt
  796. -- Desugar it
  797. let rdr_env = ic_rn_gbl_env icontext
  798. type_env = mkTypeEnv (map AnId (ic_tmp_ids icontext))
  799. ds_expr <- ioMsgMaybe $
  800. deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
  801. -- Then desugar, code gen, and link it
  802. let src_span = srcLocSpan interactiveSrcLoc
  803. hval <- liftIO $ compileExpr hsc_env src_span ds_expr
  804. return $ Just (ids, hval)
  805. hscImport :: GhcMonad m => HscEnv -> String -> m (ImportDecl RdrName)
  806. hscImport hsc_env str = do
  807. (L _ (HsModule{hsmodImports=is})) <- hscParseThing parseModule (hsc_dflags hsc_env) str
  808. case is of
  809. [i] -> return (unLoc i)
  810. _ -> throwOneError (mkPlainErrMsg noSrcSpan (ptext (sLit "parse error in import declaration")))
  811. hscTcExpr -- Typecheck an expression (but don't run it)
  812. :: GhcMonad m =>
  813. HscEnv
  814. -> String -- The expression
  815. -> m Type
  816. hscTcExpr hsc_env expr = do
  817. maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
  818. let icontext = hsc_IC hsc_env
  819. case maybe_stmt of
  820. Just (L _ (ExprStmt expr _ _)) -> do
  821. ty <- ioMsgMaybe $ tcRnExpr hsc_env icontext expr
  822. return ty
  823. _ -> do throw $ mkSrcErr $ unitBag $ mkPlainErrMsg
  824. noSrcSpan
  825. (text "not an expression:" <+> quotes (text expr))
  826. -- | Find the kind of a type
  827. hscKcType
  828. :: GhcMonad m =>
  829. HscEnv
  830. -> String -- ^ The type
  831. -> m Kind
  832. hscKcType hsc_env str = do
  833. ty <- hscParseType (hsc_dflags hsc_env) str
  834. let icontext = hsc_IC hsc_env
  835. ioMsgMaybe $ tcRnType hsc_env icontext ty
  836. #endif
  837. \end{code}
  838. \begin{code}
  839. #ifdef GHCI
  840. hscParseStmt :: GhcMonad m => DynFlags -> String -> m (Maybe (LStmt RdrName))
  841. hscParseStmt = hscParseThing parseStmt
  842. hscParseType :: GhcMonad m => DynFlags -> String -> m (LHsType RdrName)
  843. hscParseType = hscParseThing parseType
  844. #endif
  845. hscParseIdentifier :: GhcMonad m => DynFlags -> String -> m (Located RdrName)
  846. hscParseIdentifier = hscParseThing parseIdentifier
  847. hscParseThing :: (Outputable thing, GhcMonad m)
  848. => Lexer.P thing
  849. -> DynFlags -> String
  850. -> m thing
  851. -- Nothing => Parse error (message already printed)
  852. -- Just x => success
  853. hscParseThing parser dflags str
  854. = (liftIO $ showPass dflags "Parser") >>
  855. {-# SCC "Parser" #-} do
  856. buf <- liftIO $ stringToStringBuffer str
  857. let loc = mkSrcLoc (fsLit "<interactive>") 1 1
  858. case unP parser (mkPState dflags buf loc) of
  859. PFailed span err -> do
  860. let msg = mkPlainErrMsg span err
  861. throw (mkSrcErr (unitBag msg))
  862. POk pst thing -> do
  863. let ms@(warns, errs) = getMessages pst
  864. logWarnings warns
  865. when (errorsFound dflags ms) $ -- handle -Werror
  866. throw (mkSrcErr errs)
  867. --ToDo: can't free the string buffer until we've finished this
  868. -- compilation sweep and all the identifiers have gone away.
  869. liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing)
  870. return thing
  871. \end{code}
  872. %************************************************************************
  873. %* *
  874. Desugar, simplify, convert to bytecode, and link an expression
  875. %* *
  876. %************************************************************************
  877. \begin{code}
  878. #ifdef GHCI
  879. compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
  880. compileExpr hsc_env srcspan ds_expr
  881. | rtsIsProfiled
  882. = throwIO (InstallationError "You can't call compileExpr in a profiled compiler")
  883. -- Otherwise you get a seg-fault when you run it
  884. | otherwise
  885. = do { let { dflags = hsc_dflags hsc_env ;
  886. lint_on = dopt Opt_DoCoreLinting dflags }
  887. -- Simplify it
  888. ; simpl_expr <- simplifyExpr dflags ds_expr
  889. -- Tidy it (temporary, until coreSat does cloning)
  890. ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
  891. -- Prepare for codegen
  892. ; prepd_expr <- corePrepExpr dflags tidy_expr
  893. -- Lint if necessary
  894. -- ToDo: improve SrcLoc
  895. ; if lint_on then
  896. let ictxt = hsc_IC hsc_env
  897. tyvars = varSetElems (tyVarsOfTypes (map idType (ic_tmp_ids ictxt)))
  898. in
  899. case lintUnfolding noSrcLoc tyvars prepd_expr of
  900. Just err -> pprPanic "compileExpr" err
  901. Nothing -> return ()
  902. else
  903. return ()
  904. -- Convert to BCOs
  905. ; bcos <- coreExprToBCOs dflags prepd_expr
  906. -- link it
  907. ; hval <- linkExpr hsc_env srcspan bcos
  908. ; return hval
  909. }
  910. #endif
  911. \end{code}
  912. %************************************************************************
  913. %* *
  914. Statistics on reading interfaces
  915. %* *
  916. %************************************************************************
  917. \begin{code}
  918. dumpIfaceStats :: HscEnv -> IO ()
  919. dumpIfaceStats hsc_env
  920. = do { eps <- readIORef (hsc_EPS hsc_env)
  921. ; dumpIfSet (dump_if_trace || dump_rn_stats)
  922. "Interface statistics"
  923. (ifaceStats eps) }
  924. where
  925. dflags = hsc_dflags hsc_env
  926. dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
  927. dump_if_trace = dopt Opt_D_dump_if_trace dflags
  928. \end{code}
  929. %************************************************************************
  930. %* *
  931. Progress Messages: Module i of n
  932. %* *
  933. %************************************************************************
  934. \begin{code}
  935. showModuleIndex :: Maybe (Int, Int) -> String
  936. showModuleIndex Nothing = ""
  937. showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
  938. where
  939. n_str = show n
  940. i_str = show i
  941. padded = replicate (length n_str - length i_str) ' ' ++ i_str
  942. \end{code}