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, hscKcType
20 , hscCompileOneShot -- :: Compiler HscStatus
21 , hscCompileBatch -- :: Compiler (HscStatus, ModIface, ModDetails)
22 , hscCompileNothing -- :: Compiler (HscStatus, ModIface, ModDetails)
23 , hscCompileInteractive -- :: Compiler (InteractiveStatus, ModIface, ModDetails)
25 , InteractiveStatus, HscStatus
37 import CodeOutput ( outputForeignStubs )
38 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
39 import Linker ( HValue, linkExpr )
40 import CoreTidy ( tidyExpr )
41 import CorePrep ( corePrepExpr )
42 import Desugar ( deSugarExpr )
43 import SimplCore ( simplifyExpr )
44 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnType )
46 import PrelNames ( iNTERACTIVE )
47 import {- Kind parts of -} Type ( Kind )
48 import CoreLint ( lintUnfolding )
49 import DsMeta ( templateHaskellNames )
50 import SrcLoc ( SrcSpan, noSrcLoc, interactiveSrcLoc, srcLocSpan, noSrcSpan )
52 import VarEnv ( emptyTidyEnv )
56 import Module ( emptyModuleEnv, ModLocation(..), Module )
60 import SrcLoc ( Located(..) )
64 import SrcLoc ( mkSrcLoc )
65 import TcRnDriver ( tcRnModule )
66 import TcIface ( typecheckIface )
67 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
68 import IfaceEnv ( initNameCache )
69 import LoadIface ( ifaceStats, initExternalPackageState )
70 import PrelInfo ( wiredInThings, basicKnownKeyNames )
72 import Desugar ( deSugar )
73 import SimplCore ( core2core )
75 import CorePrep ( corePrepPgm )
76 import CoreToStg ( coreToStg )
77 import qualified StgCmm ( codeGen )
80 import TyCon ( TyCon, isDataTyCon )
81 import Name ( Name, NamedThing(..) )
82 import SimplStg ( stg2stg )
83 import CodeGen ( codeGen )
85 import PprCmm ( pprCmms )
86 import CmmParse ( parseCmmFile )
87 import CmmBuildInfoTables
91 import OptimizationFuel ( initOptFuelState )
95 import CodeOutput ( codeOutput )
96 import NameEnv ( emptyNameEnv )
97 import Fingerprint ( Fingerprint )
101 import UniqSupply ( mkSplitUniqSupply )
104 import HscStats ( ppSourceStats )
106 import MkExternalCore ( emitExternalCore )
108 import LazyUniqFM ( emptyUFM )
109 import UniqSupply ( initUs_ )
110 import Bag ( unitBag )
118 #include "HsVersions.h"
121 %************************************************************************
125 %************************************************************************
128 newHscEnv :: GhcApiCallbacks -> DynFlags -> IO HscEnv
129 newHscEnv callbacks dflags
130 = do { eps_var <- newIORef initExternalPackageState
131 ; us <- mkSplitUniqSupply 'r'
132 ; nc_var <- newIORef (initNameCache us knownKeyNames)
133 ; fc_var <- newIORef emptyUFM
134 ; mlc_var <- newIORef emptyModuleEnv
135 ; optFuel <- initOptFuelState
136 ; return (HscEnv { hsc_dflags = dflags,
137 hsc_callbacks = callbacks,
140 hsc_IC = emptyInteractiveContext,
141 hsc_HPT = emptyHomePackageTable,
146 hsc_OptFuel = optFuel,
147 hsc_type_env_var = Nothing,
148 hsc_global_rdr_env = emptyGlobalRdrEnv,
149 hsc_global_type_env = emptyNameEnv } ) }
152 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
153 -- where templateHaskellNames are defined
154 knownKeyNames = map getName wiredInThings
155 ++ basicKnownKeyNames
157 ++ templateHaskellNames
163 -- | parse a file, returning the abstract syntax
164 hscParse :: GhcMonad m =>
166 -> m (Located (HsModule RdrName))
167 hscParse mod_summary = do
168 hsc_env <- getSession
169 let dflags = hsc_dflags hsc_env
170 src_filename = ms_hspp_file mod_summary
171 maybe_src_buf = ms_hspp_buf mod_summary
172 -------------------------- Parser ----------------
173 liftIO $ showPass dflags "Parser"
174 {-# SCC "Parser" #-} do
176 -- sometimes we already have the buffer in memory, perhaps
177 -- because we needed to parse the imports out of it, or get the
179 buf <- case maybe_src_buf of
181 Nothing -> liftIO $ hGetStringBuffer src_filename
183 let loc = mkSrcLoc (mkFastString src_filename) 1 0
185 case unP parseModule (mkPState buf loc dflags) of
187 throwOneError (mkPlainErrMsg span err)
189 POk pst rdr_module -> do
190 let ms@(warns,errs) = getMessages pst
192 if errorsFound dflags ms then
193 liftIO $ throwIO $ mkSrcErr errs
195 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
196 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
197 (ppSourceStats False rdr_module) ;
199 -- ToDo: free the string buffer later.
201 -- | Rename and typecheck a module
202 hscTypecheck :: GhcMonad m =>
203 ModSummary -> Located (HsModule RdrName)
205 hscTypecheck mod_summary rdr_module = do
206 hsc_env <- getSession
207 r <- {-# SCC "Typecheck-Rename" #-}
208 ioMsgMaybe $ tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
211 -- XXX: should this really be a Maybe X? Check under which circumstances this
212 -- can become a Nothing and decide whether this should instead throw an
213 -- exception/signal an error.
215 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
216 Maybe (HsDoc Name), HaddockModInfo Name))
218 -- | Rename and typecheck a module, additionally returning the renamed syntax
219 hscTypecheckRename ::
221 ModSummary -> Located (HsModule RdrName)
222 -> m (TcGblEnv, RenamedStuff)
223 hscTypecheckRename mod_summary rdr_module = do
224 hsc_env <- getSession
226 <- {-# SCC "Typecheck-Rename" #-}
227 ioMsgMaybe $ tcRnModule hsc_env (ms_hsc_src mod_summary) True rdr_module
229 let rn_info = do decl <- tcg_rn_decls tc_result
230 imports <- tcg_rn_imports tc_result
231 let exports = tcg_rn_exports tc_result
232 let doc = tcg_doc tc_result
233 let hmi = tcg_hmi tc_result
234 return (decl,imports,exports,doc,hmi)
236 return (tc_result, rn_info)
238 -- | Convert a typechecked module to Core
239 hscDesugar :: GhcMonad m => ModSummary -> TcGblEnv -> m ModGuts
240 hscDesugar mod_summary tc_result =
241 withSession $ \hsc_env ->
242 ioMsgMaybe $ deSugar hsc_env (ms_location mod_summary) tc_result
244 -- | Make a 'ModIface' from the results of typechecking. Used when
245 -- not optimising, and the interface doesn't need to contain any
246 -- unfoldings or other cross-module optimisation info.
247 -- ToDo: the old interface is only needed to get the version numbers,
248 -- we should use fingerprint versions instead.
249 makeSimpleIface :: GhcMonad m =>
250 Maybe ModIface -> TcGblEnv -> ModDetails
252 makeSimpleIface maybe_old_iface tc_result details =
253 withSession $ \hsc_env ->
254 ioMsgMaybe $ mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) details tc_result
256 -- | Make a 'ModDetails' from the results of typechecking. Used when
257 -- typechecking only, as opposed to full compilation.
258 makeSimpleDetails :: GhcMonad m => TcGblEnv -> m ModDetails
259 makeSimpleDetails tc_result =
260 withSession $ \hsc_env -> liftIO $ mkBootModDetailsTc hsc_env tc_result
263 %************************************************************************
265 The main compiler pipeline
267 %************************************************************************
269 --------------------------------
270 The compilation proper
271 --------------------------------
274 It's the task of the compilation proper to compile Haskell, hs-boot and
275 core files to either byte-code, hard-code (C, asm, Java, ect) or to
276 nothing at all (the module is still parsed and type-checked. This
277 feature is mostly used by IDE's and the likes).
278 Compilation can happen in either 'one-shot', 'batch', 'nothing',
279 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
280 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
282 The modes are kept separate because of their different types and meanings.
283 In 'one-shot' mode, we're only compiling a single file and can therefore
284 discard the new ModIface and ModDetails. This is also the reason it only
285 targets hard-code; compiling to byte-code or nothing doesn't make sense
286 when we discard the result.
287 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
288 and ModDetails. 'Batch' mode doesn't target byte-code since that require
289 us to return the newly compiled byte-code.
290 'Nothing' mode has exactly the same type as 'batch' mode but they're still
291 kept separate. This is because compiling to nothing is fairly special: We
292 don't output any interface files, we don't run the simplifier and we don't
294 'Interactive' mode is similar to 'batch' mode except that we return the
295 compiled byte-code together with the ModIface and ModDetails.
297 Trying to compile a hs-boot file to byte-code will result in a run-time
298 error. This is the only thing that isn't caught by the type-system.
302 -- Status of a compilation to hard-code or nothing.
306 Bool -- Has stub files. This is a hack. We can't compile C files here
307 -- since it's done in DriverPipeline. For now we just return True
308 -- if we want the caller to compile them for us.
311 -- This is a bit ugly. Since we use a typeclass below and would like to avoid
312 -- functional dependencies, we have to parameterise the typeclass over the
313 -- result type. Therefore we need to artificially distinguish some types. We
314 -- do this by adding type tags which will simply be ignored by the caller.
315 type HscStatus = HscStatus' ()
316 type InteractiveStatus = HscStatus' (CompiledByteCode, ModBreaks)
318 type OneShotResult = HscStatus
319 type BatchResult = (HscStatus, ModIface, ModDetails)
320 type NothingResult = (HscStatus, ModIface, ModDetails)
321 type InteractiveResult = (InteractiveStatus, ModIface, ModDetails)
323 -- FIXME: The old interface and module index are only using in 'batch' and
324 -- 'interactive' mode. They should be removed from 'oneshot' mode.
325 type Compiler result = GhcMonad m =>
328 -> Bool -- True <=> source unchanged
329 -> Maybe ModIface -- Old interface, if available
330 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
335 -- | The main interface.
336 hscCompile :: GhcMonad m =>
337 HscEnv -> ModSummary -> Bool
338 -> Maybe ModIface -> Maybe (Int, Int)
341 -- | Called when no recompilation is necessary.
342 hscNoRecomp :: GhcMonad m =>
345 -- | Called to recompile the module.
346 hscRecompile :: GhcMonad m =>
347 ModSummary -> Maybe Fingerprint -> m a,
349 -- | Code generation for Boot modules.
350 hscGenBootOutput :: GhcMonad m =>
351 TcGblEnv -> ModSummary -> Maybe Fingerprint -> m a,
353 -- | Code generation for normal modules.
354 hscGenOutput :: GhcMonad m =>
355 ModGuts -> ModSummary -> Maybe Fingerprint -> m a
358 genericHscCompile :: GhcMonad m =>
360 -> (Maybe (Int,Int) -> Bool -> ModSummary -> m ())
361 -> HscEnv -> ModSummary -> Bool
362 -> Maybe ModIface -> Maybe (Int, Int)
364 genericHscCompile compiler hscMessage
365 hsc_env mod_summary source_unchanged
366 mb_old_iface0 mb_mod_index =
367 withTempSession (\_ -> hsc_env) $ do
368 (recomp_reqd, mb_checked_iface)
369 <- {-# SCC "checkOldIface" #-}
370 liftIO $ checkOldIface hsc_env mod_summary
371 source_unchanged mb_old_iface0
372 -- save the interface that comes back from checkOldIface.
373 -- In one-shot mode we don't have the old iface until this
374 -- point, when checkOldIface reads it from the disk.
375 let mb_old_hash = fmap mi_iface_hash mb_checked_iface
376 case mb_checked_iface of
377 Just iface | not recomp_reqd
378 -> do hscMessage mb_mod_index False mod_summary
379 hscNoRecomp compiler iface
381 -> do hscMessage mb_mod_index True mod_summary
382 hscRecompile compiler mod_summary mb_old_hash
384 genericHscRecompile :: GhcMonad m =>
386 -> ModSummary -> Maybe Fingerprint
388 genericHscRecompile compiler mod_summary mb_old_hash
389 | ExtCoreFile <- ms_hsc_src mod_summary =
390 panic "GHC does not currently support reading External Core files"
392 tc_result <- hscFileFrontEnd mod_summary
393 case ms_hsc_src mod_summary of
395 hscGenBootOutput compiler tc_result mod_summary mb_old_hash
397 guts <- hscDesugar mod_summary tc_result
398 hscGenOutput compiler guts mod_summary mb_old_hash
400 --------------------------------------------------------------
402 --------------------------------------------------------------
404 hscOneShotCompiler :: HsCompiler OneShotResult
408 hscCompile = \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
413 mod = ms_mod mod_summary
414 hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
416 genericHscCompile hscOneShotCompiler
417 oneShotMsg hsc_env' mod_summary src_changed
418 mb_old_iface mb_i_of_n
420 , hscNoRecomp = \_old_iface -> do
421 withSession (liftIO . dumpIfaceStats)
424 , hscRecompile = genericHscRecompile hscOneShotCompiler
426 , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
427 (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface
428 hscWriteIface iface changed mod_summary
429 return (HscRecomp False ())
431 , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
432 guts <- hscSimplify guts0
433 (iface, changed, _details, cgguts)
434 <- hscNormalIface guts mb_old_iface
435 hscWriteIface iface changed mod_summary
436 hasStub <- hscGenHardCode cgguts mod_summary
437 return (HscRecomp hasStub ())
440 -- Compile Haskell, boot and extCore in OneShot mode.
441 hscCompileOneShot :: Compiler OneShotResult
442 hscCompileOneShot = hscCompile hscOneShotCompiler
444 --------------------------------------------------------------
446 hscBatchCompiler :: HsCompiler BatchResult
450 hscCompile = genericHscCompile hscBatchCompiler batchMsg
452 , hscNoRecomp = \iface -> do
453 details <- genModDetails iface
454 return (HscNoRecomp, iface, details)
456 , hscRecompile = genericHscRecompile hscBatchCompiler
458 , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
459 (iface, changed, details)
460 <- hscSimpleIface tc_result mb_old_iface
461 hscWriteIface iface changed mod_summary
462 return (HscRecomp False (), iface, details)
464 , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
465 guts <- hscSimplify guts0
466 (iface, changed, details, cgguts)
467 <- hscNormalIface guts mb_old_iface
468 hscWriteIface iface changed mod_summary
469 hasStub <- hscGenHardCode cgguts mod_summary
470 return (HscRecomp hasStub (), iface, details)
473 -- Compile Haskell, boot and extCore in batch mode.
474 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
475 hscCompileBatch = hscCompile hscBatchCompiler
477 --------------------------------------------------------------
479 hscInteractiveCompiler :: HsCompiler InteractiveResult
480 hscInteractiveCompiler =
482 hscCompile = genericHscCompile hscInteractiveCompiler batchMsg
484 , hscNoRecomp = \iface -> do
485 details <- genModDetails iface
486 return (HscNoRecomp, iface, details)
488 , hscRecompile = genericHscRecompile hscInteractiveCompiler
490 , hscGenBootOutput = \_ _ _ -> panic "hscCompileInteractive: HsBootFile"
492 , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
493 guts <- hscSimplify guts0
494 (iface, _changed, details, cgguts)
495 <- hscNormalIface guts mb_old_iface
496 hscInteractive (iface, details, cgguts) mod_summary
499 -- Compile Haskell, extCore to bytecode.
500 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
501 hscCompileInteractive = hscCompile hscInteractiveCompiler
503 --------------------------------------------------------------
505 hscNothingCompiler :: HsCompiler NothingResult
508 hscCompile = genericHscCompile hscNothingCompiler batchMsg
510 , hscNoRecomp = \iface -> do
511 details <- genModDetails iface
512 return (HscNoRecomp, iface, details)
514 , hscRecompile = \mod_summary mb_old_hash ->
515 case ms_hsc_src mod_summary of
517 panic "hscCompileNothing: cannot do external core"
519 tc_result <- hscFileFrontEnd mod_summary
520 hscGenBootOutput hscNothingCompiler tc_result mod_summary mb_old_hash
522 , hscGenBootOutput = \tc_result _mod_summary mb_old_iface -> do
523 (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
524 return (HscRecomp False (), iface, details)
526 , hscGenOutput = \_ _ _ ->
527 panic "hscCompileNothing: hscGenOutput should not be called"
529 -- Type-check Haskell and .hs-boot only (no external core)
530 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
531 hscCompileNothing = hscCompile hscNothingCompiler
533 --------------------------------------------------------------
535 --------------------------------------------------------------
537 genModDetails :: GhcMonad m => ModIface -> m ModDetails
538 genModDetails old_iface =
539 withSession $ \hsc_env -> liftIO $ do
540 new_details <- {-# SCC "tcRnIface" #-}
541 initIfaceCheck hsc_env $
542 typecheckIface old_iface
543 dumpIfaceStats hsc_env
546 --------------------------------------------------------------
547 -- Progress displayers.
548 --------------------------------------------------------------
550 oneShotMsg :: GhcMonad m => Maybe (Int,Int) -> Bool -> ModSummary -> m ()
551 oneShotMsg _mb_mod_index recomp _mod_summary
552 = do hsc_env <- getSession
556 else compilationProgressMsg (hsc_dflags hsc_env) $
557 "compilation IS NOT required"
559 batchMsg :: GhcMonad m => Maybe (Int,Int) -> Bool -> ModSummary -> m ()
560 batchMsg mb_mod_index recomp mod_summary
561 = do hsc_env <- getSession
562 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
563 (showModuleIndex mb_mod_index ++
564 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
567 then showMsg "Compiling "
568 else if verbosity (hsc_dflags hsc_env) >= 2
569 then showMsg "Skipping "
572 --------------------------------------------------------------
574 --------------------------------------------------------------
575 hscFileFrontEnd :: GhcMonad m => ModSummary -> m TcGblEnv
576 hscFileFrontEnd mod_summary =
577 do rdr_module <- hscParse mod_summary
578 hscTypecheck mod_summary rdr_module
580 --------------------------------------------------------------
582 --------------------------------------------------------------
584 hscSimplify :: GhcMonad m => ModGuts -> m ModGuts
585 hscSimplify ds_result
586 = do hsc_env <- getSession
587 simpl_result <- {-# SCC "Core2Core" #-}
588 liftIO $ core2core hsc_env ds_result
591 --------------------------------------------------------------
592 -- Interface generators
593 --------------------------------------------------------------
595 hscSimpleIface :: GhcMonad m =>
598 -> m (ModIface, Bool, ModDetails)
599 hscSimpleIface tc_result mb_old_iface
600 = do hsc_env <- getSession
601 details <- liftIO $ mkBootModDetailsTc hsc_env tc_result
602 (new_iface, no_change)
603 <- {-# SCC "MkFinalIface" #-}
604 ioMsgMaybe $ mkIfaceTc hsc_env mb_old_iface details tc_result
605 -- And the answer is ...
606 liftIO $ dumpIfaceStats hsc_env
607 return (new_iface, no_change, details)
609 hscNormalIface :: GhcMonad m =>
612 -> m (ModIface, Bool, ModDetails, CgGuts)
613 hscNormalIface simpl_result mb_old_iface
614 = do hsc_env <- getSession
616 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
617 liftIO $ tidyProgram hsc_env simpl_result
619 -- BUILD THE NEW ModIface and ModDetails
620 -- and emit external core if necessary
621 -- This has to happen *after* code gen so that the back-end
622 -- info has been set. Not yet clear if it matters waiting
623 -- until after code output
624 (new_iface, no_change)
625 <- {-# SCC "MkFinalIface" #-}
626 ioMsgMaybe $ mkIface hsc_env mb_old_iface
628 -- Emit external core
629 -- This should definitely be here and not after CorePrep,
630 -- because CorePrep produces unqualified constructor wrapper declarations,
631 -- so its output isn't valid External Core (without some preprocessing).
632 liftIO $ emitExternalCore (hsc_dflags hsc_env) cg_guts
633 liftIO $ dumpIfaceStats hsc_env
635 -- Return the prepared code.
636 return (new_iface, no_change, details, cg_guts)
638 --------------------------------------------------------------
639 -- BackEnd combinators
640 --------------------------------------------------------------
642 hscWriteIface :: GhcMonad m =>
646 hscWriteIface iface no_change mod_summary
647 = do hsc_env <- getSession
648 let dflags = hsc_dflags hsc_env
651 $ writeIfaceFile dflags (ms_location mod_summary) iface
653 -- | Compile to hard-code.
654 hscGenHardCode :: GhcMonad m =>
656 -> m Bool -- ^ @True@ <=> stub.c exists
657 hscGenHardCode cgguts mod_summary
658 = withSession $ \hsc_env -> liftIO $ do
659 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
660 -- From now on, we just use the bits we need.
661 cg_module = this_mod,
662 cg_binds = core_binds,
664 cg_dir_imps = dir_imps,
665 cg_foreign = foreign_stubs,
666 cg_dep_pkgs = dependencies,
667 cg_hpc_info = hpc_info } = cgguts
668 dflags = hsc_dflags hsc_env
669 location = ms_location mod_summary
670 data_tycons = filter isDataTyCon tycons
671 -- cg_tycons includes newtypes, for the benefit of External Core,
672 -- but we don't generate any code for newtypes
675 -- PREPARE FOR CODE GENERATION
676 -- Do saturation and convert to A-normal form
677 prepd_binds <- {-# SCC "CorePrep" #-}
678 corePrepPgm dflags core_binds data_tycons ;
679 ----------------- Convert to STG ------------------
680 (stg_binds, cost_centre_info)
681 <- {-# SCC "CoreToStg" #-}
682 myCoreToStg dflags this_mod prepd_binds
684 ------------------ Code generation ------------------
685 cmms <- if dopt Opt_TryNewCodeGen (hsc_dflags hsc_env)
686 then do cmms <- tryNewCodeGen hsc_env this_mod data_tycons
687 dir_imps cost_centre_info
690 else {-# SCC "CodeGen" #-}
691 codeGen dflags this_mod data_tycons
692 dir_imps cost_centre_info
695 --- Optionally run experimental Cmm transformations ---
696 cmms <- optionallyConvertAndOrCPS hsc_env cmms
697 -- unless certain dflags are on, the identity function
698 ------------------ Code output -----------------------
699 rawcmms <- cmmToRawCmm cmms
700 (_stub_h_exists, stub_c_exists)
701 <- codeOutput dflags this_mod location foreign_stubs
705 hscInteractive :: GhcMonad m =>
706 (ModIface, ModDetails, CgGuts)
708 -> m (InteractiveStatus, ModIface, ModDetails)
710 hscInteractive (iface, details, cgguts) mod_summary
711 = do hsc_env <- getSession
713 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
714 -- From now on, we just use the bits we need.
715 cg_module = this_mod,
716 cg_binds = core_binds,
718 cg_foreign = foreign_stubs,
719 cg_modBreaks = mod_breaks } = cgguts
720 dflags = hsc_dflags hsc_env
721 location = ms_location mod_summary
722 data_tycons = filter isDataTyCon tycons
723 -- cg_tycons includes newtypes, for the benefit of External Core,
724 -- but we don't generate any code for newtypes
727 -- PREPARE FOR CODE GENERATION
728 -- Do saturation and convert to A-normal form
729 prepd_binds <- {-# SCC "CorePrep" #-}
730 corePrepPgm dflags core_binds data_tycons ;
731 ----------------- Generate byte code ------------------
732 comp_bc <- byteCodeGen dflags prepd_binds data_tycons mod_breaks
733 ------------------ Create f-x-dynamic C-side stuff ---
734 (_istub_h_exists, istub_c_exists)
735 <- outputForeignStubs dflags this_mod location foreign_stubs
736 return (HscRecomp istub_c_exists (comp_bc, mod_breaks), iface, details)
738 hscInteractive _ _ = panic "GHC not compiled with interpreter"
741 ------------------------------
743 hscCmmFile :: GhcMonad m => HscEnv -> FilePath -> m ()
744 hscCmmFile hsc_env filename = do
745 dflags <- return $ hsc_dflags hsc_env
747 parseCmmFile dflags filename
748 cmms <- liftIO $ optionallyConvertAndOrCPS hsc_env [cmm]
749 rawCmms <- liftIO $ cmmToRawCmm cmms
750 liftIO $ codeOutput dflags no_mod no_loc NoStubs [] rawCmms
753 no_mod = panic "hscCmmFile: no_mod"
754 no_loc = ModLocation{ ml_hs_file = Just filename,
755 ml_hi_file = panic "hscCmmFile: no hi file",
756 ml_obj_file = panic "hscCmmFile: no obj file" }
758 -------------------- Stuff for new code gen ---------------------
760 tryNewCodeGen :: HscEnv -> Module -> [TyCon] -> [Module]
762 -> [(StgBinding,[(Id,[Id])])]
765 tryNewCodeGen hsc_env this_mod data_tycons imported_mods
766 cost_centre_info stg_binds hpc_info
767 | not (dopt Opt_TryNewCodeGen (hsc_dflags hsc_env))
770 = do { let dflags = hsc_dflags hsc_env
771 ; prog <- StgCmm.codeGen dflags this_mod data_tycons imported_mods
772 cost_centre_info stg_binds hpc_info
773 ; dumpIfSet_dyn dflags Opt_D_dump_cmmz "Cmm produced by new codegen"
776 ; prog <- return $ map (runTx $ runCmmOpts cmmCfgOptsZ) prog
777 -- Control flow optimisation
779 -- Note: Have to thread the module's SRT through all the procedures
780 -- because we greedily build it as we go.
781 ; us <- mkSplitUniqSupply 'S'
782 ; let topSRT = initUs_ us emptySRT
783 ; (topSRT, prog) <- foldM (protoCmmCPSZ hsc_env) (topSRT, []) prog
784 -- The main CPS conversion
786 ; prog <- return $ map (runTx $ runCmmOpts cmmCfgOptsZ) (srtToData topSRT : prog)
787 -- Control flow optimisation, again
789 ; dumpIfSet_dyn dflags Opt_D_dump_cmmz "Output Cmm" (pprCmms prog)
791 ; let prog' = map cmmOfZgraph prog
792 ; dumpIfSet_dyn dflags Opt_D_dump_cmmz "Raw Cmm" (ppr prog')
796 optionallyConvertAndOrCPS :: HscEnv -> [Cmm] -> IO [Cmm]
797 optionallyConvertAndOrCPS hsc_env cmms =
798 do let dflags = hsc_dflags hsc_env
799 -------- Optionally convert to and from zipper ------
800 cmms <- if dopt Opt_ConvertToZipCfgAndBack dflags
801 then mapM (testCmmConversion hsc_env) cmms
803 --------- Optionally convert to CPS (MDA) -----------
804 cmms <- if not (dopt Opt_ConvertToZipCfgAndBack dflags) &&
805 dopt Opt_RunCPS dflags
806 then cmmCPS dflags cmms
811 testCmmConversion :: HscEnv -> Cmm -> IO Cmm
812 testCmmConversion hsc_env cmm =
813 do let dflags = hsc_dflags hsc_env
814 showPass dflags "CmmToCmm"
815 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- pre-conversion" (ppr cmm)
816 --continuationC <- cmmCPS dflags abstractC >>= cmmToRawCmm
817 us <- mkSplitUniqSupply 'C'
818 let cfopts = runTx $ runCmmOpts cmmCfgOptsZ
819 let cvtm = do g <- cmmToZgraph cmm
821 let zgraph = initUs_ us cvtm
822 us <- mkSplitUniqSupply 'S'
823 let topSRT = initUs_ us emptySRT
824 (_, [cps_zgraph]) <- protoCmmCPSZ hsc_env (topSRT, []) zgraph
825 let chosen_graph = if dopt Opt_RunCPSZ dflags then cps_zgraph else zgraph
826 dumpIfSet_dyn dflags Opt_D_dump_cmmz "C-- Zipper Graph" (ppr chosen_graph)
827 showPass dflags "Convert from Z back to Cmm"
828 let cvt = cmmOfZgraph $ cfopts $ chosen_graph
829 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- post-conversion" (ppr cvt)
831 -- return cmm -- don't use the conversion
833 myCoreToStg :: DynFlags -> Module -> [CoreBind]
834 -> IO ( [(StgBinding,[(Id,[Id])])] -- output program
835 , CollectedCCs) -- cost centre info (declared and used)
837 myCoreToStg dflags this_mod prepd_binds
839 stg_binds <- {-# SCC "Core2Stg" #-}
840 coreToStg (thisPackage dflags) prepd_binds
842 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
843 stg2stg dflags this_mod stg_binds
845 return (stg_binds2, cost_centre_info)
849 %************************************************************************
851 \subsection{Compiling a do-statement}
853 %************************************************************************
855 When the UnlinkedBCOExpr is linked you get an HValue of type
857 When you run it you get a list of HValues that should be
858 the same length as the list of names; add them to the ClosureEnv.
860 A naked expression returns a singleton Name [it].
862 What you type The IO [HValue] that hscStmt returns
863 ------------- ------------------------------------
864 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
867 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
870 expr (of IO type) ==> expr >>= \ v -> return [v]
871 [NB: result not printed] bindings: [it]
874 expr (of non-IO type,
875 result showable) ==> let v = expr in print v >> return [v]
878 expr (of non-IO type,
879 result not showable) ==> error
883 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
886 -> String -- The statement
887 -> m (Maybe ([Id], HValue))
888 -- ^ 'Nothing' <==> empty statement (or comment only), but no parse error
889 hscStmt hsc_env stmt = do
890 maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
892 Nothing -> return Nothing
893 Just parsed_stmt -> do -- The real stuff
895 -- Rename and typecheck it
896 let icontext = hsc_IC hsc_env
897 (ids, tc_expr) <- ioMsgMaybe $ tcRnStmt hsc_env icontext parsed_stmt
899 let rdr_env = ic_rn_gbl_env icontext
900 type_env = mkTypeEnv (map AnId (ic_tmp_ids icontext))
901 ds_expr <- ioMsgMaybe $
902 deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
904 -- Then desugar, code gen, and link it
905 let src_span = srcLocSpan interactiveSrcLoc
906 hval <- liftIO $ compileExpr hsc_env src_span ds_expr
908 return $ Just (ids, hval)
911 hscTcExpr -- Typecheck an expression (but don't run it)
914 -> String -- The expression
917 hscTcExpr hsc_env expr = do
918 maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
919 let icontext = hsc_IC hsc_env
921 Just (L _ (ExprStmt expr _ _)) -> do
922 ty <- ioMsgMaybe $ tcRnExpr hsc_env icontext expr
924 _ -> do throw $ mkSrcErr $ unitBag $ mkPlainErrMsg
926 (text "not an expression:" <+> quotes (text expr))
928 -- | Find the kind of a type
932 -> String -- ^ The type
935 hscKcType hsc_env str = do
936 ty <- hscParseType (hsc_dflags hsc_env) str
937 let icontext = hsc_IC hsc_env
938 ioMsgMaybe $ tcRnType hsc_env icontext ty
945 hscParseStmt :: GhcMonad m => DynFlags -> String -> m (Maybe (LStmt RdrName))
946 hscParseStmt = hscParseThing parseStmt
948 hscParseType :: GhcMonad m => DynFlags -> String -> m (LHsType RdrName)
949 hscParseType = hscParseThing parseType
952 hscParseIdentifier :: GhcMonad m => DynFlags -> String -> m (Located RdrName)
953 hscParseIdentifier = hscParseThing parseIdentifier
955 hscParseThing :: (Outputable thing, GhcMonad m)
957 -> DynFlags -> String
959 -- Nothing => Parse error (message already printed)
961 hscParseThing parser dflags str
962 = (liftIO $ showPass dflags "Parser") >>
963 {-# SCC "Parser" #-} do
965 buf <- liftIO $ stringToStringBuffer str
967 let loc = mkSrcLoc (fsLit "<interactive>") 1 0
969 case unP parser (mkPState buf loc dflags) of
971 PFailed span err -> do
972 let msg = mkPlainErrMsg span err
973 throw (mkSrcErr (unitBag msg))
977 let ms@(warns, errs) = getMessages pst
979 when (errorsFound dflags ms) $ -- handle -Werror
980 throw (mkSrcErr errs)
982 --ToDo: can't free the string buffer until we've finished this
983 -- compilation sweep and all the identifiers have gone away.
984 liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing)
988 %************************************************************************
990 Desugar, simplify, convert to bytecode, and link an expression
992 %************************************************************************
996 compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
998 compileExpr hsc_env srcspan ds_expr
999 = do { let { dflags = hsc_dflags hsc_env ;
1000 lint_on = dopt Opt_DoCoreLinting dflags }
1003 ; simpl_expr <- simplifyExpr dflags ds_expr
1005 -- Tidy it (temporary, until coreSat does cloning)
1006 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
1008 -- Prepare for codegen
1009 ; prepd_expr <- corePrepExpr dflags tidy_expr
1011 -- Lint if necessary
1012 -- ToDo: improve SrcLoc
1014 let ictxt = hsc_IC hsc_env
1015 tyvars = varSetElems (ic_tyvars ictxt)
1017 case lintUnfolding noSrcLoc tyvars prepd_expr of
1018 Just err -> pprPanic "compileExpr" err
1019 Nothing -> return ()
1024 ; bcos <- coreExprToBCOs dflags prepd_expr
1027 ; hval <- linkExpr hsc_env srcspan bcos
1035 %************************************************************************
1037 Statistics on reading interfaces
1039 %************************************************************************
1042 dumpIfaceStats :: HscEnv -> IO ()
1043 dumpIfaceStats hsc_env
1044 = do { eps <- readIORef (hsc_EPS hsc_env)
1045 ; dumpIfSet (dump_if_trace || dump_rn_stats)
1046 "Interface statistics"
1049 dflags = hsc_dflags hsc_env
1050 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
1051 dump_if_trace = dopt Opt_D_dump_if_trace dflags
1054 %************************************************************************
1056 Progress Messages: Module i of n
1058 %************************************************************************
1061 showModuleIndex :: Maybe (Int, Int) -> String
1062 showModuleIndex Nothing = ""
1063 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1067 padded = replicate (length n_str - length i_str) ' ' ++ i_str