2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 -- | Main driver for the compiling plain Haskell source code.
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
12 ( newHscEnv, hscCmmFile
15 , hscNormalIface, hscWriteIface, hscGenHardCode
17 , hscStmt, hscTcExpr, hscImport, hscKcType
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
29 , InteractiveStatus, HscStatus
41 import CodeOutput ( outputForeignStubs )
42 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
43 import Linker ( HValue, linkExpr )
44 import CoreTidy ( tidyExpr )
45 import CorePrep ( corePrepExpr )
46 import Desugar ( deSugarExpr )
47 import SimplCore ( simplifyExpr )
48 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnType )
50 import PrelNames ( iNTERACTIVE )
51 import {- Kind parts of -} Type ( Kind )
52 import CoreLint ( lintUnfolding )
53 import DsMeta ( templateHaskellNames )
54 import SrcLoc ( SrcSpan, noSrcLoc, interactiveSrcLoc, srcLocSpan, noSrcSpan, unLoc )
56 import VarEnv ( emptyTidyEnv )
61 import Module ( emptyModuleEnv, ModLocation(..), Module )
65 import SrcLoc ( Located(..) )
69 import SrcLoc ( mkSrcLoc )
70 import TcRnDriver ( tcRnModule )
71 import TcIface ( typecheckIface )
72 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
73 import IfaceEnv ( initNameCache )
74 import LoadIface ( ifaceStats, initExternalPackageState )
75 import PrelInfo ( wiredInThings, basicKnownKeyNames )
77 import Desugar ( deSugar )
78 import SimplCore ( core2core )
80 import CorePrep ( corePrepPgm )
81 import CoreToStg ( coreToStg )
82 import qualified StgCmm ( codeGen )
85 import TyCon ( TyCon, isDataTyCon )
86 import Name ( Name, NamedThing(..) )
87 import SimplStg ( stg2stg )
88 import CodeGen ( codeGen )
90 import PprCmm ( pprCmms )
91 import CmmParse ( parseCmmFile )
92 import CmmBuildInfoTables
96 import OptimizationFuel ( initOptFuelState )
100 import CodeOutput ( codeOutput )
101 import NameEnv ( emptyNameEnv )
102 import Fingerprint ( Fingerprint )
106 import UniqSupply ( mkSplitUniqSupply )
109 import HscStats ( ppSourceStats )
111 import MkExternalCore ( emitExternalCore )
113 import UniqFM ( emptyUFM )
114 import UniqSupply ( initUs_ )
115 import Bag ( unitBag )
123 #include "HsVersions.h"
126 %************************************************************************
130 %************************************************************************
133 newHscEnv :: GhcApiCallbacks -> DynFlags -> IO HscEnv
134 newHscEnv callbacks dflags
135 = do { eps_var <- newIORef initExternalPackageState
136 ; us <- mkSplitUniqSupply 'r'
137 ; nc_var <- newIORef (initNameCache us knownKeyNames)
138 ; fc_var <- newIORef emptyUFM
139 ; mlc_var <- newIORef emptyModuleEnv
140 ; optFuel <- initOptFuelState
141 ; return (HscEnv { hsc_dflags = dflags,
142 hsc_callbacks = callbacks,
145 hsc_IC = emptyInteractiveContext,
146 hsc_HPT = emptyHomePackageTable,
151 hsc_OptFuel = optFuel,
152 hsc_type_env_var = Nothing } ) }
155 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
156 -- where templateHaskellNames are defined
157 knownKeyNames = map getName wiredInThings
158 ++ basicKnownKeyNames
160 ++ templateHaskellNames
166 -- | parse a file, returning the abstract syntax
167 hscParse :: GhcMonad m =>
169 -> m (Located (HsModule RdrName))
170 hscParse mod_summary = do
171 hsc_env <- getSession
172 let dflags = hsc_dflags hsc_env
173 src_filename = ms_hspp_file mod_summary
174 maybe_src_buf = ms_hspp_buf mod_summary
175 -------------------------- Parser ----------------
176 liftIO $ showPass dflags "Parser"
177 {-# SCC "Parser" #-} do
179 -- sometimes we already have the buffer in memory, perhaps
180 -- because we needed to parse the imports out of it, or get the
182 buf <- case maybe_src_buf of
184 Nothing -> liftIO $ hGetStringBuffer src_filename
186 let loc = mkSrcLoc (mkFastString src_filename) 1 1
188 case unP parseModule (mkPState dflags buf loc) of
190 throwOneError (mkPlainErrMsg span err)
192 POk pst rdr_module -> do
193 let ms@(warns,errs) = getMessages pst
195 if errorsFound dflags ms then
196 liftIO $ throwIO $ mkSrcErr errs
198 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
199 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
200 (ppSourceStats False rdr_module) ;
202 -- ToDo: free the string buffer later.
204 -- | Rename and typecheck a module
205 hscTypecheck :: GhcMonad m =>
206 ModSummary -> Located (HsModule RdrName)
208 hscTypecheck mod_summary rdr_module = do
209 hsc_env <- getSession
210 r <- {-# SCC "Typecheck-Rename" #-}
211 ioMsgMaybe $ tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
214 -- XXX: should this really be a Maybe X? Check under which circumstances this
215 -- can become a Nothing and decide whether this should instead throw an
216 -- exception/signal an error.
218 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
221 -- | Rename and typecheck a module, additionally returning the renamed syntax
222 hscTypecheckRename ::
224 ModSummary -> Located (HsModule RdrName)
225 -> m (TcGblEnv, RenamedStuff)
226 hscTypecheckRename mod_summary rdr_module = do
227 hsc_env <- getSession
229 <- {-# SCC "Typecheck-Rename" #-}
230 ioMsgMaybe $ tcRnModule hsc_env (ms_hsc_src mod_summary) True rdr_module
232 let -- This 'do' is in the Maybe monad!
233 rn_info = do { decl <- tcg_rn_decls tc_result
234 ; let imports = tcg_rn_imports tc_result
235 exports = tcg_rn_exports tc_result
236 doc_hdr = tcg_doc_hdr tc_result
237 ; return (decl,imports,exports,doc_hdr) }
239 return (tc_result, rn_info)
241 -- | Convert a typechecked module to Core
242 hscDesugar :: GhcMonad m => ModSummary -> TcGblEnv -> m ModGuts
243 hscDesugar mod_summary tc_result =
244 withSession $ \hsc_env ->
245 ioMsgMaybe $ deSugar hsc_env (ms_location mod_summary) tc_result
247 -- | Make a 'ModIface' from the results of typechecking. Used when
248 -- not optimising, and the interface doesn't need to contain any
249 -- unfoldings or other cross-module optimisation info.
250 -- ToDo: the old interface is only needed to get the version numbers,
251 -- we should use fingerprint versions instead.
252 makeSimpleIface :: GhcMonad m =>
253 Maybe ModIface -> TcGblEnv -> ModDetails
255 makeSimpleIface maybe_old_iface tc_result details =
256 withSession $ \hsc_env ->
257 ioMsgMaybe $ mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) details tc_result
259 -- | Make a 'ModDetails' from the results of typechecking. Used when
260 -- typechecking only, as opposed to full compilation.
261 makeSimpleDetails :: GhcMonad m => TcGblEnv -> m ModDetails
262 makeSimpleDetails tc_result =
263 withSession $ \hsc_env -> liftIO $ mkBootModDetailsTc hsc_env tc_result
266 %************************************************************************
268 The main compiler pipeline
270 %************************************************************************
272 --------------------------------
273 The compilation proper
274 --------------------------------
277 It's the task of the compilation proper to compile Haskell, hs-boot and
278 core files to either byte-code, hard-code (C, asm, Java, ect) or to
279 nothing at all (the module is still parsed and type-checked. This
280 feature is mostly used by IDE's and the likes).
281 Compilation can happen in either 'one-shot', 'batch', 'nothing',
282 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
283 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
285 The modes are kept separate because of their different types and meanings.
286 In 'one-shot' mode, we're only compiling a single file and can therefore
287 discard the new ModIface and ModDetails. This is also the reason it only
288 targets hard-code; compiling to byte-code or nothing doesn't make sense
289 when we discard the result.
290 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
291 and ModDetails. 'Batch' mode doesn't target byte-code since that require
292 us to return the newly compiled byte-code.
293 'Nothing' mode has exactly the same type as 'batch' mode but they're still
294 kept separate. This is because compiling to nothing is fairly special: We
295 don't output any interface files, we don't run the simplifier and we don't
297 'Interactive' mode is similar to 'batch' mode except that we return the
298 compiled byte-code together with the ModIface and ModDetails.
300 Trying to compile a hs-boot file to byte-code will result in a run-time
301 error. This is the only thing that isn't caught by the type-system.
305 -- Status of a compilation to hard-code or nothing.
309 Bool -- Has stub files. This is a hack. We can't compile C files here
310 -- since it's done in DriverPipeline. For now we just return True
311 -- if we want the caller to compile them for us.
314 -- This is a bit ugly. Since we use a typeclass below and would like to avoid
315 -- functional dependencies, we have to parameterise the typeclass over the
316 -- result type. Therefore we need to artificially distinguish some types. We
317 -- do this by adding type tags which will simply be ignored by the caller.
318 type HscStatus = HscStatus' ()
319 type InteractiveStatus = HscStatus' (Maybe (CompiledByteCode, ModBreaks))
320 -- INVARIANT: result is @Nothing@ <=> input was a boot file
322 type OneShotResult = HscStatus
323 type BatchResult = (HscStatus, ModIface, ModDetails)
324 type NothingResult = (HscStatus, ModIface, ModDetails)
325 type InteractiveResult = (InteractiveStatus, ModIface, ModDetails)
327 -- FIXME: The old interface and module index are only using in 'batch' and
328 -- 'interactive' mode. They should be removed from 'oneshot' mode.
329 type Compiler result = GhcMonad m =>
332 -> Bool -- True <=> source unchanged
333 -> Maybe ModIface -- Old interface, if available
334 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
339 -- | Called when no recompilation is necessary.
340 hscNoRecomp :: GhcMonad m =>
343 -- | Called to recompile the module.
344 hscRecompile :: GhcMonad m =>
345 ModSummary -> Maybe Fingerprint -> m a,
347 hscBackend :: GhcMonad m =>
348 TcGblEnv -> ModSummary -> Maybe Fingerprint -> m a,
350 -- | Code generation for Boot modules.
351 hscGenBootOutput :: GhcMonad m =>
352 TcGblEnv -> ModSummary -> Maybe Fingerprint -> m a,
354 -- | Code generation for normal modules.
355 hscGenOutput :: GhcMonad m =>
356 ModGuts -> ModSummary -> Maybe Fingerprint -> m a
359 genericHscCompile :: GhcMonad m =>
361 -> (Maybe (Int,Int) -> Bool -> ModSummary -> m ())
362 -> HscEnv -> ModSummary -> Bool
363 -> Maybe ModIface -> Maybe (Int, Int)
365 genericHscCompile compiler hscMessage
366 hsc_env mod_summary source_unchanged
367 mb_old_iface0 mb_mod_index =
368 withTempSession (\_ -> hsc_env) $ do
369 (recomp_reqd, mb_checked_iface)
370 <- {-# SCC "checkOldIface" #-}
371 liftIO $ checkOldIface hsc_env mod_summary
372 source_unchanged mb_old_iface0
373 -- save the interface that comes back from checkOldIface.
374 -- In one-shot mode we don't have the old iface until this
375 -- point, when checkOldIface reads it from the disk.
376 let mb_old_hash = fmap mi_iface_hash mb_checked_iface
377 case mb_checked_iface of
378 Just iface | not recomp_reqd
379 -> do hscMessage mb_mod_index False mod_summary
380 hscNoRecomp compiler iface
382 -> do hscMessage mb_mod_index True mod_summary
383 hscRecompile compiler mod_summary mb_old_hash
385 hscCheckRecompBackend :: HsCompiler a -> TcGblEnv -> Compiler a
386 hscCheckRecompBackend compiler tc_result
387 hsc_env mod_summary source_unchanged mb_old_iface _m_of_n =
388 withTempSession (\_ -> hsc_env) $ do
389 (recomp_reqd, mb_checked_iface)
390 <- {-# SCC "checkOldIface" #-}
391 liftIO $ checkOldIface hsc_env mod_summary
392 source_unchanged mb_old_iface
394 let mb_old_hash = fmap mi_iface_hash mb_checked_iface
395 case mb_checked_iface of
396 Just iface | not recomp_reqd
397 -> hscNoRecomp compiler iface{ mi_globals = Just (tcg_rdr_env tc_result) }
399 -> hscBackend compiler tc_result mod_summary mb_old_hash
401 genericHscRecompile :: GhcMonad m =>
403 -> ModSummary -> Maybe Fingerprint
405 genericHscRecompile compiler mod_summary mb_old_hash
406 | ExtCoreFile <- ms_hsc_src mod_summary =
407 panic "GHC does not currently support reading External Core files"
409 tc_result <- hscFileFrontEnd mod_summary
410 hscBackend compiler tc_result mod_summary mb_old_hash
412 genericHscBackend :: GhcMonad m =>
414 -> TcGblEnv -> ModSummary -> Maybe Fingerprint
416 genericHscBackend compiler tc_result mod_summary mb_old_hash
417 | HsBootFile <- ms_hsc_src mod_summary =
418 hscGenBootOutput compiler tc_result mod_summary mb_old_hash
420 guts <- hscDesugar mod_summary tc_result
421 hscGenOutput compiler guts mod_summary mb_old_hash
423 --------------------------------------------------------------
425 --------------------------------------------------------------
427 hscOneShotCompiler :: HsCompiler OneShotResult
431 hscNoRecomp = \_old_iface -> do
432 withSession (liftIO . dumpIfaceStats)
435 , hscRecompile = genericHscRecompile hscOneShotCompiler
437 , hscBackend = \ tc_result mod_summary mb_old_hash -> do
438 hsc_env <- getSession
439 case hscTarget (hsc_dflags hsc_env) of
440 HscNothing -> return (HscRecomp False ())
441 _otherw -> genericHscBackend hscOneShotCompiler
442 tc_result mod_summary mb_old_hash
444 , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
445 (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface
446 hscWriteIface iface changed mod_summary
447 return (HscRecomp False ())
449 , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
450 guts <- hscSimplify guts0
451 (iface, changed, _details, cgguts)
452 <- hscNormalIface guts mb_old_iface
453 hscWriteIface iface changed mod_summary
454 hasStub <- hscGenHardCode cgguts mod_summary
455 return (HscRecomp hasStub ())
458 -- Compile Haskell, boot and extCore in OneShot mode.
459 hscCompileOneShot :: Compiler OneShotResult
460 hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n = do
461 -- One-shot mode needs a knot-tying mutable variable for interface
462 -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var.
463 type_env_var <- liftIO $ newIORef emptyNameEnv
465 mod = ms_mod mod_summary
466 hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
468 genericHscCompile hscOneShotCompiler
469 oneShotMsg hsc_env' mod_summary src_changed
470 mb_old_iface mb_i_of_n
473 --------------------------------------------------------------
475 hscBatchCompiler :: HsCompiler BatchResult
479 hscNoRecomp = \iface -> do
480 details <- genModDetails iface
481 return (HscNoRecomp, iface, details)
483 , hscRecompile = genericHscRecompile hscBatchCompiler
485 , hscBackend = genericHscBackend hscBatchCompiler
487 , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
488 (iface, changed, details)
489 <- hscSimpleIface tc_result mb_old_iface
490 hscWriteIface iface changed mod_summary
491 return (HscRecomp False (), iface, details)
493 , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
494 guts <- hscSimplify guts0
495 (iface, changed, details, cgguts)
496 <- hscNormalIface guts mb_old_iface
497 hscWriteIface iface changed mod_summary
498 hasStub <- hscGenHardCode cgguts mod_summary
499 return (HscRecomp hasStub (), iface, details)
502 -- Compile Haskell, boot and extCore in batch mode.
503 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
504 hscCompileBatch = genericHscCompile hscBatchCompiler batchMsg
506 --------------------------------------------------------------
508 hscInteractiveCompiler :: HsCompiler InteractiveResult
509 hscInteractiveCompiler =
511 hscNoRecomp = \iface -> do
512 details <- genModDetails iface
513 return (HscNoRecomp, iface, details)
515 , hscRecompile = genericHscRecompile hscInteractiveCompiler
517 , hscBackend = genericHscBackend hscInteractiveCompiler
519 , hscGenBootOutput = \tc_result _mod_summary mb_old_iface -> do
520 (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
521 return (HscRecomp False Nothing, iface, details)
523 , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
524 guts <- hscSimplify guts0
525 (iface, _changed, details, cgguts)
526 <- hscNormalIface guts mb_old_iface
527 hscInteractive (iface, details, cgguts) mod_summary
530 -- Compile Haskell, extCore to bytecode.
531 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
532 hscCompileInteractive = genericHscCompile hscInteractiveCompiler batchMsg
534 --------------------------------------------------------------
536 hscNothingCompiler :: HsCompiler NothingResult
539 hscNoRecomp = \iface -> do
540 details <- genModDetails iface
541 return (HscNoRecomp, iface, details)
543 , hscRecompile = genericHscRecompile hscNothingCompiler
545 , hscBackend = \tc_result _mod_summary mb_old_iface -> do
546 (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
547 return (HscRecomp False (), iface, details)
549 , hscGenBootOutput = \_ _ _ ->
550 panic "hscCompileNothing: hscGenBootOutput should not be called"
552 , hscGenOutput = \_ _ _ ->
553 panic "hscCompileNothing: hscGenOutput should not be called"
556 -- Type-check Haskell and .hs-boot only (no external core)
557 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
558 hscCompileNothing = genericHscCompile hscNothingCompiler batchMsg
560 --------------------------------------------------------------
562 --------------------------------------------------------------
564 genModDetails :: GhcMonad m => ModIface -> m ModDetails
565 genModDetails old_iface =
566 withSession $ \hsc_env -> liftIO $ do
567 new_details <- {-# SCC "tcRnIface" #-}
568 initIfaceCheck hsc_env $
569 typecheckIface old_iface
570 dumpIfaceStats hsc_env
573 --------------------------------------------------------------
574 -- Progress displayers.
575 --------------------------------------------------------------
577 oneShotMsg :: GhcMonad m => Maybe (Int,Int) -> Bool -> ModSummary -> m ()
578 oneShotMsg _mb_mod_index recomp _mod_summary
579 = do hsc_env <- getSession
583 else compilationProgressMsg (hsc_dflags hsc_env) $
584 "compilation IS NOT required"
586 batchMsg :: GhcMonad m => Maybe (Int,Int) -> Bool -> ModSummary -> m ()
587 batchMsg mb_mod_index recomp mod_summary
588 = do hsc_env <- getSession
589 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
590 (showModuleIndex mb_mod_index ++
591 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
594 then showMsg "Compiling "
595 else if verbosity (hsc_dflags hsc_env) >= 2
596 then showMsg "Skipping "
599 --------------------------------------------------------------
601 --------------------------------------------------------------
602 hscFileFrontEnd :: GhcMonad m => ModSummary -> m TcGblEnv
603 hscFileFrontEnd mod_summary =
604 do rdr_module <- hscParse mod_summary
605 hscTypecheck mod_summary rdr_module
607 --------------------------------------------------------------
609 --------------------------------------------------------------
611 hscSimplify :: GhcMonad m => ModGuts -> m ModGuts
612 hscSimplify ds_result
613 = do hsc_env <- getSession
614 simpl_result <- {-# SCC "Core2Core" #-}
615 liftIO $ core2core hsc_env ds_result
618 --------------------------------------------------------------
619 -- Interface generators
620 --------------------------------------------------------------
622 hscSimpleIface :: GhcMonad m =>
625 -> m (ModIface, Bool, ModDetails)
626 hscSimpleIface tc_result mb_old_iface
627 = do hsc_env <- getSession
628 details <- liftIO $ mkBootModDetailsTc hsc_env tc_result
629 (new_iface, no_change)
630 <- {-# SCC "MkFinalIface" #-}
631 ioMsgMaybe $ mkIfaceTc hsc_env mb_old_iface details tc_result
632 -- And the answer is ...
633 liftIO $ dumpIfaceStats hsc_env
634 return (new_iface, no_change, details)
636 hscNormalIface :: GhcMonad m =>
639 -> m (ModIface, Bool, ModDetails, CgGuts)
640 hscNormalIface simpl_result mb_old_iface
641 = do hsc_env <- getSession
643 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
644 liftIO $ tidyProgram hsc_env simpl_result
646 -- BUILD THE NEW ModIface and ModDetails
647 -- and emit external core if necessary
648 -- This has to happen *after* code gen so that the back-end
649 -- info has been set. Not yet clear if it matters waiting
650 -- until after code output
651 (new_iface, no_change)
652 <- {-# SCC "MkFinalIface" #-}
653 ioMsgMaybe $ mkIface hsc_env mb_old_iface
655 -- Emit external core
656 -- This should definitely be here and not after CorePrep,
657 -- because CorePrep produces unqualified constructor wrapper declarations,
658 -- so its output isn't valid External Core (without some preprocessing).
659 liftIO $ emitExternalCore (hsc_dflags hsc_env) cg_guts
660 liftIO $ dumpIfaceStats hsc_env
662 -- Return the prepared code.
663 return (new_iface, no_change, details, cg_guts)
665 --------------------------------------------------------------
666 -- BackEnd combinators
667 --------------------------------------------------------------
669 hscWriteIface :: GhcMonad m =>
673 hscWriteIface iface no_change mod_summary
674 = do hsc_env <- getSession
675 let dflags = hsc_dflags hsc_env
678 $ writeIfaceFile dflags (ms_location mod_summary) iface
680 -- | Compile to hard-code.
681 hscGenHardCode :: GhcMonad m =>
683 -> m Bool -- ^ @True@ <=> stub.c exists
684 hscGenHardCode cgguts mod_summary
685 = withSession $ \hsc_env -> liftIO $ do
686 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
687 -- From now on, we just use the bits we need.
688 cg_module = this_mod,
689 cg_binds = core_binds,
691 cg_dir_imps = dir_imps,
692 cg_foreign = foreign_stubs,
693 cg_dep_pkgs = dependencies,
694 cg_hpc_info = hpc_info } = cgguts
695 dflags = hsc_dflags hsc_env
696 location = ms_location mod_summary
697 data_tycons = filter isDataTyCon tycons
698 -- cg_tycons includes newtypes, for the benefit of External Core,
699 -- but we don't generate any code for newtypes
702 -- PREPARE FOR CODE GENERATION
703 -- Do saturation and convert to A-normal form
704 prepd_binds <- {-# SCC "CorePrep" #-}
705 corePrepPgm dflags core_binds data_tycons ;
706 ----------------- Convert to STG ------------------
707 (stg_binds, cost_centre_info)
708 <- {-# SCC "CoreToStg" #-}
709 myCoreToStg dflags this_mod prepd_binds
711 ------------------ Code generation ------------------
712 cmms <- if dopt Opt_TryNewCodeGen (hsc_dflags hsc_env)
713 then do cmms <- tryNewCodeGen hsc_env this_mod data_tycons
714 dir_imps cost_centre_info
717 else {-# SCC "CodeGen" #-}
718 codeGen dflags this_mod data_tycons
719 dir_imps cost_centre_info
722 --- Optionally run experimental Cmm transformations ---
723 -- cmms <- optionallyConvertAndOrCPS hsc_env cmms
724 -- unless certain dflags are on, the identity function
725 ------------------ Code output -----------------------
726 rawcmms <- cmmToRawCmm cmms
727 dumpIfSet_dyn dflags Opt_D_dump_cmmz "Raw Cmm" (ppr rawcmms)
728 (_stub_h_exists, stub_c_exists)
729 <- codeOutput dflags this_mod location foreign_stubs
733 hscInteractive :: GhcMonad m =>
734 (ModIface, ModDetails, CgGuts)
736 -> m (InteractiveStatus, ModIface, ModDetails)
738 hscInteractive (iface, details, cgguts) mod_summary
739 = do hsc_env <- getSession
741 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
742 -- From now on, we just use the bits we need.
743 cg_module = this_mod,
744 cg_binds = core_binds,
746 cg_foreign = foreign_stubs,
747 cg_modBreaks = mod_breaks } = cgguts
748 dflags = hsc_dflags hsc_env
749 location = ms_location mod_summary
750 data_tycons = filter isDataTyCon tycons
751 -- cg_tycons includes newtypes, for the benefit of External Core,
752 -- but we don't generate any code for newtypes
755 -- PREPARE FOR CODE GENERATION
756 -- Do saturation and convert to A-normal form
757 prepd_binds <- {-# SCC "CorePrep" #-}
758 corePrepPgm dflags core_binds data_tycons ;
759 ----------------- Generate byte code ------------------
760 comp_bc <- byteCodeGen dflags prepd_binds data_tycons mod_breaks
761 ------------------ Create f-x-dynamic C-side stuff ---
762 (_istub_h_exists, istub_c_exists)
763 <- outputForeignStubs dflags this_mod location foreign_stubs
764 return (HscRecomp istub_c_exists (Just (comp_bc, mod_breaks))
767 hscInteractive _ _ = panic "GHC not compiled with interpreter"
770 ------------------------------
772 hscCmmFile :: GhcMonad m => HscEnv -> FilePath -> m ()
773 hscCmmFile hsc_env filename = do
774 dflags <- return $ hsc_dflags hsc_env
776 parseCmmFile dflags filename
777 cmms <- liftIO $ optionallyConvertAndOrCPS hsc_env [cmm]
778 rawCmms <- liftIO $ cmmToRawCmm cmms
779 _ <- liftIO $ codeOutput dflags no_mod no_loc NoStubs [] rawCmms
782 no_mod = panic "hscCmmFile: no_mod"
783 no_loc = ModLocation{ ml_hs_file = Just filename,
784 ml_hi_file = panic "hscCmmFile: no hi file",
785 ml_obj_file = panic "hscCmmFile: no obj file" }
787 -------------------- Stuff for new code gen ---------------------
789 tryNewCodeGen :: HscEnv -> Module -> [TyCon] -> [Module]
791 -> [(StgBinding,[(Id,[Id])])]
794 tryNewCodeGen hsc_env this_mod data_tycons imported_mods
795 cost_centre_info stg_binds hpc_info =
796 do { let dflags = hsc_dflags hsc_env
797 ; prog <- StgCmm.codeGen dflags this_mod data_tycons imported_mods
798 cost_centre_info stg_binds hpc_info
799 ; dumpIfSet_dyn dflags Opt_D_dump_cmmz "Cmm produced by new codegen"
802 ; prog <- return $ map (runTx $ runCmmOpts cmmCfgOptsZ) prog
803 -- Control flow optimisation
805 -- We are building a single SRT for the entire module, so
806 -- we must thread it through all the procedures as we cps-convert them.
807 ; us <- mkSplitUniqSupply 'S'
808 ; let topSRT = initUs_ us emptySRT
809 ; (topSRT, prog) <- foldM (protoCmmCPSZ hsc_env) (topSRT, []) prog
810 -- The main CPS conversion
812 ; prog <- return $ map (runTx $ runCmmOpts cmmCfgOptsZ) (srtToData topSRT : prog)
813 -- Control flow optimisation, again
815 ; let prog' = map cmmOfZgraph prog
816 ; dumpIfSet_dyn dflags Opt_D_dump_cmmz "Output Cmm" (ppr prog')
820 optionallyConvertAndOrCPS :: HscEnv -> [Cmm] -> IO [Cmm]
821 optionallyConvertAndOrCPS hsc_env cmms =
822 do let dflags = hsc_dflags hsc_env
823 -------- Optionally convert to and from zipper ------
824 cmms <- if dopt Opt_ConvertToZipCfgAndBack dflags
825 then mapM (testCmmConversion hsc_env) cmms
827 --------- Optionally convert to CPS (MDA) -----------
828 cmms <- if not (dopt Opt_ConvertToZipCfgAndBack dflags) &&
829 dopt Opt_RunCPS dflags
830 then cmmCPS dflags cmms
835 testCmmConversion :: HscEnv -> Cmm -> IO Cmm
836 testCmmConversion hsc_env cmm =
837 do let dflags = hsc_dflags hsc_env
838 showPass dflags "CmmToCmm"
839 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- pre-conversion" (ppr cmm)
840 --continuationC <- cmmCPS dflags abstractC >>= cmmToRawCmm
841 us <- mkSplitUniqSupply 'C'
842 let cfopts = runTx $ runCmmOpts cmmCfgOptsZ
843 let cvtm = do g <- cmmToZgraph cmm
845 let zgraph = initUs_ us cvtm
846 us <- mkSplitUniqSupply 'S'
847 let topSRT = initUs_ us emptySRT
848 (_, [cps_zgraph]) <- protoCmmCPSZ hsc_env (topSRT, []) zgraph
849 let chosen_graph = if dopt Opt_RunCPSZ dflags then cps_zgraph else zgraph
850 dumpIfSet_dyn dflags Opt_D_dump_cmmz "C-- Zipper Graph" (ppr chosen_graph)
851 showPass dflags "Convert from Z back to Cmm"
852 let cvt = cmmOfZgraph $ cfopts $ chosen_graph
853 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- post-conversion" (ppr cvt)
856 myCoreToStg :: DynFlags -> Module -> [CoreBind]
857 -> IO ( [(StgBinding,[(Id,[Id])])] -- output program
858 , CollectedCCs) -- cost centre info (declared and used)
860 myCoreToStg dflags this_mod prepd_binds
862 stg_binds <- {-# SCC "Core2Stg" #-}
863 coreToStg (thisPackage dflags) prepd_binds
865 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
866 stg2stg dflags this_mod stg_binds
868 return (stg_binds2, cost_centre_info)
872 %************************************************************************
874 \subsection{Compiling a do-statement}
876 %************************************************************************
878 When the UnlinkedBCOExpr is linked you get an HValue of type
880 When you run it you get a list of HValues that should be
881 the same length as the list of names; add them to the ClosureEnv.
883 A naked expression returns a singleton Name [it].
885 What you type The IO [HValue] that hscStmt returns
886 ------------- ------------------------------------
887 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
890 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
893 expr (of IO type) ==> expr >>= \ v -> return [v]
894 [NB: result not printed] bindings: [it]
897 expr (of non-IO type,
898 result showable) ==> let v = expr in print v >> return [v]
901 expr (of non-IO type,
902 result not showable) ==> error
906 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
909 -> String -- The statement
910 -> m (Maybe ([Id], HValue))
911 -- ^ 'Nothing' <==> empty statement (or comment only), but no parse error
912 hscStmt hsc_env stmt = do
913 maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
915 Nothing -> return Nothing
916 Just parsed_stmt -> do -- The real stuff
918 -- Rename and typecheck it
919 let icontext = hsc_IC hsc_env
920 (ids, tc_expr) <- ioMsgMaybe $ tcRnStmt hsc_env icontext parsed_stmt
922 let rdr_env = ic_rn_gbl_env icontext
923 type_env = mkTypeEnv (map AnId (ic_tmp_ids icontext))
924 ds_expr <- ioMsgMaybe $
925 deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
927 -- Then desugar, code gen, and link it
928 let src_span = srcLocSpan interactiveSrcLoc
929 hval <- liftIO $ compileExpr hsc_env src_span ds_expr
931 return $ Just (ids, hval)
933 hscImport :: GhcMonad m => HscEnv -> String -> m (ImportDecl RdrName)
934 hscImport hsc_env str = do
935 (L _ (HsModule{hsmodImports=is})) <- hscParseThing parseModule (hsc_dflags hsc_env) str
937 [i] -> return (unLoc i)
938 _ -> throwOneError (mkPlainErrMsg noSrcSpan (ptext (sLit "parse error in import declaration")))
940 hscTcExpr -- Typecheck an expression (but don't run it)
943 -> String -- The expression
946 hscTcExpr hsc_env expr = do
947 maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
948 let icontext = hsc_IC hsc_env
950 Just (L _ (ExprStmt expr _ _)) -> do
951 ty <- ioMsgMaybe $ tcRnExpr hsc_env icontext expr
953 _ -> do throw $ mkSrcErr $ unitBag $ mkPlainErrMsg
955 (text "not an expression:" <+> quotes (text expr))
957 -- | Find the kind of a type
961 -> String -- ^ The type
964 hscKcType hsc_env str = do
965 ty <- hscParseType (hsc_dflags hsc_env) str
966 let icontext = hsc_IC hsc_env
967 ioMsgMaybe $ tcRnType hsc_env icontext ty
974 hscParseStmt :: GhcMonad m => DynFlags -> String -> m (Maybe (LStmt RdrName))
975 hscParseStmt = hscParseThing parseStmt
977 hscParseType :: GhcMonad m => DynFlags -> String -> m (LHsType RdrName)
978 hscParseType = hscParseThing parseType
981 hscParseIdentifier :: GhcMonad m => DynFlags -> String -> m (Located RdrName)
982 hscParseIdentifier = hscParseThing parseIdentifier
984 hscParseThing :: (Outputable thing, GhcMonad m)
986 -> DynFlags -> String
988 -- Nothing => Parse error (message already printed)
990 hscParseThing parser dflags str
991 = (liftIO $ showPass dflags "Parser") >>
992 {-# SCC "Parser" #-} do
994 buf <- liftIO $ stringToStringBuffer str
996 let loc = mkSrcLoc (fsLit "<interactive>") 1 1
998 case unP parser (mkPState dflags buf loc) of
1000 PFailed span err -> do
1001 let msg = mkPlainErrMsg span err
1002 throw (mkSrcErr (unitBag msg))
1006 let ms@(warns, errs) = getMessages pst
1008 when (errorsFound dflags ms) $ -- handle -Werror
1009 throw (mkSrcErr errs)
1011 --ToDo: can't free the string buffer until we've finished this
1012 -- compilation sweep and all the identifiers have gone away.
1013 liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing)
1017 %************************************************************************
1019 Desugar, simplify, convert to bytecode, and link an expression
1021 %************************************************************************
1025 compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
1027 compileExpr hsc_env srcspan ds_expr
1029 = throwIO (InstallationError "You can't call compileExpr in a profiled compiler")
1030 -- Otherwise you get a seg-fault when you run it
1033 = do { let { dflags = hsc_dflags hsc_env ;
1034 lint_on = dopt Opt_DoCoreLinting dflags }
1037 ; simpl_expr <- simplifyExpr dflags ds_expr
1039 -- Tidy it (temporary, until coreSat does cloning)
1040 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
1042 -- Prepare for codegen
1043 ; prepd_expr <- corePrepExpr dflags tidy_expr
1045 -- Lint if necessary
1046 -- ToDo: improve SrcLoc
1048 let ictxt = hsc_IC hsc_env
1049 tyvars = varSetElems (ic_tyvars ictxt)
1051 case lintUnfolding noSrcLoc tyvars prepd_expr of
1052 Just err -> pprPanic "compileExpr" err
1053 Nothing -> return ()
1058 ; bcos <- coreExprToBCOs dflags prepd_expr
1061 ; hval <- linkExpr hsc_env srcspan bcos
1069 %************************************************************************
1071 Statistics on reading interfaces
1073 %************************************************************************
1076 dumpIfaceStats :: HscEnv -> IO ()
1077 dumpIfaceStats hsc_env
1078 = do { eps <- readIORef (hsc_EPS hsc_env)
1079 ; dumpIfSet (dump_if_trace || dump_rn_stats)
1080 "Interface statistics"
1083 dflags = hsc_dflags hsc_env
1084 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
1085 dump_if_trace = dopt Opt_D_dump_if_trace dflags
1088 %************************************************************************
1090 Progress Messages: Module i of n
1092 %************************************************************************
1095 showModuleIndex :: Maybe (Int, Int) -> String
1096 showModuleIndex Nothing = ""
1097 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1101 padded = replicate (length n_str - length i_str) ' ' ++ i_str