2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
9 HscResult(..), hscMain, initPersistentCompilerState
11 , hscStmt, hscTcExpr, hscThing,
16 #include "HsVersions.h"
19 import TcHsSyn ( TypecheckedHsExpr )
20 import CodeOutput ( outputForeignStubs )
21 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
22 import Linker ( HValue, linkExpr )
23 import TidyPgm ( tidyCoreExpr )
24 import CorePrep ( corePrepExpr )
25 import Flattening ( flattenExpr )
26 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnThing )
27 import RdrHsSyn ( RdrNameStmt )
29 import PrelNames ( iNTERACTIVE )
30 import StringBuffer ( stringToStringBuffer )
36 import RdrName ( nameRdrName )
38 import IdInfo ( CafInfo(..), CgInfoEnv, CgInfo(..) )
39 import StringBuffer ( hGetStringBuffer, freeStringBuffer )
41 import Lex ( ParseResult(..), ExtFlags(..), mkPState )
42 import SrcLoc ( mkSrcLoc )
43 import TcRnDriver ( checkOldIface, tcRnModule, tcRnExtCore, tcRnIface )
44 import RnEnv ( extendOrigNameCache )
45 import Rules ( emptyRuleBase )
46 import PrelInfo ( wiredInThingEnv, wiredInThings, knownKeyNames )
47 import PrelRules ( builtinRules )
48 import MkIface ( mkIface )
49 import InstEnv ( emptyInstEnv )
51 import Flattening ( flatten )
53 import CoreUtils ( coreBindsSize )
54 import TidyPgm ( tidyCorePgm )
55 import CorePrep ( corePrepPgm )
57 import CoreToStg ( coreToStg )
58 import SimplStg ( stg2stg )
59 import CodeGen ( codeGen )
60 import CodeOutput ( codeOutput )
62 import Module ( emptyModuleEnv )
64 import DriverPhases ( isExtCore_file )
65 import ErrUtils ( dumpIfSet_dyn, showPass, printError )
66 import UniqSupply ( mkSplitUniqSupply )
68 import Bag ( consBag, emptyBag )
70 import HscStats ( ppSourceStats )
72 import MkExternalCore ( emitExternalCore )
74 import ParserCoreUtils
75 import FiniteMap ( emptyFM )
76 import Name ( nameModule, getName )
77 import NameEnv ( emptyNameEnv, mkNameEnv )
78 import NameSet ( emptyNameSet )
79 import Module ( Module, ModLocation(..), showModMsg )
81 import Maybes ( expectJust )
83 import DATA_IOREF ( newIORef, readIORef, writeIORef )
84 import UNSAFE_IO ( unsafePerformIO )
87 import Maybe ( isJust, fromJust )
92 %************************************************************************
94 \subsection{The main compiler pipeline}
96 %************************************************************************
100 -- compilation failed
101 = HscFail PersistentCompilerState -- updated PCS
102 -- concluded that it wasn't necessary
103 | HscNoRecomp PersistentCompilerState -- updated PCS
104 ModDetails -- new details (HomeSymbolTable additions)
105 ModIface -- new iface (if any compilation was done)
107 | HscRecomp PersistentCompilerState -- updated PCS
108 ModDetails -- new details (HomeSymbolTable additions)
109 ModIface -- new iface (if any compilation was done)
110 Bool -- stub_h exists
111 Bool -- stub_c exists
112 (Maybe CompiledByteCode)
114 -- no errors or warnings; the individual passes
115 -- (parse/rename/typecheck) print messages themselves
119 -> PersistentCompilerState -- IN: persistent compiler state
121 -> ModLocation -- location info
122 -> Bool -- True <=> source unchanged
123 -> Bool -- True <=> have an object file (for msgs only)
124 -> Maybe ModIface -- old interface, if available
127 hscMain hsc_env pcs mod location
128 source_unchanged have_object maybe_old_iface
130 (pcs_ch, maybe_chk_result) <- _scc_ "checkOldIface"
131 checkOldIface hsc_env pcs mod
132 (ml_hi_file location)
133 source_unchanged maybe_old_iface;
134 case maybe_chk_result of {
135 Nothing -> return (HscFail pcs_ch) ;
136 Just (recomp_reqd, maybe_checked_iface) -> do {
138 let no_old_iface = not (isJust maybe_checked_iface)
139 what_next | recomp_reqd || no_old_iface = hscRecomp
140 | otherwise = hscNoRecomp
142 ; what_next hsc_env pcs_ch have_object
143 mod location maybe_checked_iface
147 -- hscNoRecomp definitely expects to have the old interface available
148 hscNoRecomp hsc_env pcs_ch have_object
149 mod location (Just old_iface)
150 | hsc_mode hsc_env == OneShot
152 when (verbosity (hsc_dflags hsc_env) > 0) $
153 hPutStrLn stderr "compilation IS NOT required";
154 let { bomb = panic "hscNoRecomp:OneShot" };
155 return (HscNoRecomp pcs_ch bomb bomb)
159 when (verbosity (hsc_dflags hsc_env) >= 1) $
160 hPutStrLn stderr ("Skipping " ++
161 showModMsg have_object mod location);
164 (pcs_tc, maybe_tc_result) <- tcRnIface hsc_env pcs_ch old_iface ;
166 case maybe_tc_result of {
167 Nothing -> return (HscFail pcs_tc);
170 return (HscNoRecomp pcs_tc new_details old_iface)
173 hscRecomp hsc_env pcs_ch have_object
174 mod location maybe_checked_iface
176 -- what target are we shooting for?
177 ; let one_shot = hsc_mode hsc_env == OneShot
178 ; let dflags = hsc_dflags hsc_env
179 ; let toInterp = dopt_HscLang dflags == HscInterpreted
180 ; let toCore = isJust (ml_hs_file location) &&
181 isExtCore_file (fromJust (ml_hs_file location))
183 ; when (not one_shot && verbosity dflags >= 1) $
184 hPutStrLn stderr ("Compiling " ++
185 showModMsg (not toInterp) mod location);
187 ; front_res <- if toCore then
188 hscCoreFrontEnd hsc_env pcs_ch location
190 hscFrontEnd hsc_env pcs_ch location
193 Left flure -> return flure;
194 Right (pcs_tc, ds_result) -> do {
198 -- ; seqList imported_modules (return ())
203 ; flat_result <- _scc_ "Flattening"
204 flatten hsc_env pcs_tc ds_result
206 ; let pcs_middle = pcs_tc
208 {- Again, omit this because it loses the usage info
209 which is needed in mkIface. Maybe we should compute
213 <- _scc_ "pcs_middle"
215 do init_pcs <- initPersistentCompilerState
216 init_prs <- initPersistentRenamerState
218 rules = pcs_rules pcs_tc
219 orig_tc = prsOrig (pcs_PRS pcs_tc)
220 new_prs = init_prs{ prsOrig=orig_tc }
222 orig_tc `seq` rules `seq` new_prs `seq`
223 return init_pcs{ pcs_PRS = new_prs,
228 -- Should we remove bits of flat_result at this point?
229 -- ; flat_result <- case flat_result of
230 -- ModResult { md_binds = binds } ->
231 -- return ModDetails { md_binds = binds,
233 -- md_types = emptyTypeEnv,
236 -- alive at this point:
243 ; simpl_result <- _scc_ "Core2Core"
244 core2core hsc_env pcs_middle flat_result
249 ; cg_info_ref <- newIORef Nothing ;
250 ; let cg_info :: CgInfoEnv
251 cg_info = unsafePerformIO $ do {
252 maybe_cg_env <- readIORef cg_info_ref ;
254 Just env -> return env
255 Nothing -> do { printError "Urk! Looked at CgInfo too early!";
256 return emptyNameEnv } }
257 -- cg_info_ref will be filled in just after restOfCodeGeneration
258 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
260 ; (pcs_simpl, tidy_result)
262 tidyCorePgm dflags pcs_middle cg_info simpl_result
264 -- Space-saving ploy doesn't work so well now
265 -- because mkIface needs the populated PIT to
266 -- generate usage info. Maybe we should re-visit this.
267 -- ; pcs_final <- if one_shot then initPersistentCompilerState
268 -- else return pcs_simpl
269 ; let pcs_final = pcs_simpl
271 -- Alive at this point:
272 -- tidy_result, pcs_final
275 -- PREPARE FOR CODE GENERATION
276 -- Do saturation and convert to A-normal form
277 ; prepd_result <- _scc_ "CorePrep"
278 corePrepPgm dflags tidy_result
281 -- CONVERT TO STG and COMPLETE CODE GENERATION
282 ; (stub_h_exists, stub_c_exists, maybe_bcos)
283 <- hscBackEnd dflags cg_info_ref prepd_result
286 -- BUILD THE NEW ModIface and ModDetails
287 -- and emit external core if necessary
288 -- This has to happen *after* code gen so that the back-end
289 -- info has been set. Not yet clear if it matters waiting
290 -- until after code output
291 ; final_iface <- _scc_ "MkFinalIface"
292 mkIface hsc_env location
293 maybe_checked_iface tidy_result
294 ; let final_details = ModDetails { md_types = mg_types tidy_result,
295 md_insts = mg_insts tidy_result,
296 md_rules = mg_rules tidy_result }
297 ; emitExternalCore dflags tidy_result
299 -- and the answer is ...
300 ; return (HscRecomp pcs_final
303 stub_h_exists stub_c_exists
307 hscCoreFrontEnd hsc_env pcs_ch location = do {
311 ; inp <- readFile (expectJust "hscCoreFrontEnd:hspp" (ml_hspp_file location))
312 ; case parseCore inp 1 of
313 FailP s -> hPutStrLn stderr s >> return (Left (HscFail pcs_ch));
314 OkP rdr_module -> do {
317 -- RENAME and TYPECHECK
319 ; (pcs_tc, maybe_tc_result) <- _scc_ "TypeCheck"
320 tcRnExtCore hsc_env pcs_ch rdr_module
321 ; case maybe_tc_result of {
322 Nothing -> return (Left (HscFail pcs_tc));
323 Just mod_guts -> return (Right (pcs_tc, mod_guts))
324 -- No desugaring to do!
328 hscFrontEnd hsc_env pcs_ch location = do {
332 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env)
333 (expectJust "hscFrontEnd:hspp" (ml_hspp_file location))
335 ; case maybe_parsed of {
336 Nothing -> return (Left (HscFail pcs_ch));
337 Just rdr_module -> do {
340 -- RENAME and TYPECHECK
342 ; (pcs_tc, maybe_tc_result) <- _scc_ "Typecheck and Rename"
343 tcRnModule hsc_env pcs_ch rdr_module
344 ; case maybe_tc_result of {
345 Nothing -> return (Left (HscFail pcs_ch));
346 Just tc_result -> do {
351 ; ds_result <- _scc_ "DeSugar"
352 deSugar hsc_env pcs_tc tc_result
353 ; return (Right (pcs_tc, ds_result))
357 hscBackEnd dflags cg_info_ref prepd_result
358 = case dopt_HscLang dflags of
359 HscNothing -> return (False, False, Nothing)
363 do ----------------- Generate byte code ------------------
364 comp_bc <- byteCodeGen dflags prepd_result
366 -- Fill in the code-gen info
367 writeIORef cg_info_ref (Just emptyNameEnv)
369 ------------------ Create f-x-dynamic C-side stuff ---
370 (istub_h_exists, istub_c_exists)
371 <- outputForeignStubs dflags (mg_foreign prepd_result)
373 return ( istub_h_exists, istub_c_exists,
376 panic "GHC not compiled with interpreter"
381 ----------------- Convert to STG ------------------
382 (stg_binds, cost_centre_info, stg_back_end_info)
384 myCoreToStg dflags prepd_result
386 -- Fill in the code-gen info for the earlier tidyCorePgm
387 writeIORef cg_info_ref (Just stg_back_end_info)
389 ------------------ Code generation ------------------
390 abstractC <- _scc_ "CodeGen"
391 codeGen dflags prepd_result
392 cost_centre_info stg_binds
394 ------------------ Code output -----------------------
395 (stub_h_exists, stub_c_exists)
396 <- codeOutput dflags prepd_result abstractC
398 return (stub_h_exists, stub_c_exists, Nothing)
401 myParseModule dflags src_filename
402 = do -------------------------- Parser ----------------
403 showPass dflags "Parser"
405 buf <- hGetStringBuffer src_filename
407 let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
408 ffiEF = dopt Opt_FFI dflags,
409 withEF = dopt Opt_With dflags,
410 parrEF = dopt Opt_PArr dflags}
411 loc = mkSrcLoc (mkFastString src_filename) 1
413 case parseModule buf (mkPState loc exts) of {
415 PFailed err -> do { hPutStrLn stderr (showSDoc err);
416 freeStringBuffer buf;
419 POk _ rdr_module -> do {
421 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
423 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
424 (ppSourceStats False rdr_module) ;
426 return (Just rdr_module)
427 -- ToDo: free the string buffer later.
431 myCoreToStg dflags (ModGuts {mg_module = this_mod, mg_binds = tidy_binds})
433 () <- coreBindsSize tidy_binds `seq` return ()
434 -- TEMP: the above call zaps some space usage allocated by the
435 -- simplifier, which for reasons I don't understand, persists
436 -- thoroughout code generation -- JRS
438 -- This is still necessary. -- SDM (10 Dec 2001)
440 stg_binds <- _scc_ "Core2Stg"
441 coreToStg dflags tidy_binds
443 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
444 stg2stg dflags this_mod stg_binds
446 let env_rhs :: CgInfoEnv
447 env_rhs = mkNameEnv [ caf_info `seq` (idName bndr, CgInfo caf_info)
448 | (bind,_) <- stg_binds2,
450 | stgBindHasCafRefs bind = MayHaveCafRefs
451 | otherwise = NoCafRefs,
452 bndr <- stgBinders bind ]
454 return (stg_binds2, cost_centre_info, env_rhs)
458 %************************************************************************
460 \subsection{Compiling a do-statement}
462 %************************************************************************
464 When the UnlinkedBCOExpr is linked you get an HValue of type
466 When you run it you get a list of HValues that should be
467 the same length as the list of names; add them to the ClosureEnv.
469 A naked expression returns a singleton Name [it].
471 What you type The IO [HValue] that hscStmt returns
472 ------------- ------------------------------------
473 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
476 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
479 expr (of IO type) ==> expr >>= \ v -> return [v]
480 [NB: result not printed] bindings: [it]
483 expr (of non-IO type,
484 result showable) ==> let v = expr in print v >> return [v]
487 expr (of non-IO type,
488 result not showable) ==> error
492 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
494 -> PersistentCompilerState -- IN: persistent compiler state
495 -> InteractiveContext -- Context for compiling
496 -> String -- The statement
497 -> IO ( PersistentCompilerState,
498 Maybe (InteractiveContext, [Name], HValue) )
500 hscStmt hsc_env pcs icontext stmt
501 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
502 ; case maybe_stmt of {
503 Nothing -> return (pcs, Nothing) ;
504 Just parsed_stmt -> do {
506 -- Rename and typecheck it
507 (pcs1, maybe_tc_result)
508 <- tcRnStmt hsc_env pcs icontext parsed_stmt
510 ; case maybe_tc_result of {
511 Nothing -> return (pcs1, Nothing) ;
512 Just (new_ic, bound_names, tc_expr) -> do {
514 -- Then desugar, code gen, and link it
515 ; hval <- compileExpr hsc_env pcs1 iNTERACTIVE
516 (ic_rn_gbl_env new_ic)
520 ; return (pcs1, Just (new_ic, bound_names, hval))
523 hscTcExpr -- Typecheck an expression (but don't run it)
525 -> PersistentCompilerState -- IN: persistent compiler state
526 -> InteractiveContext -- Context for compiling
527 -> String -- The expression
528 -> IO (PersistentCompilerState, Maybe Type)
530 hscTcExpr hsc_env pcs icontext expr
531 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
532 ; case maybe_stmt of {
533 Just (ExprStmt expr _ _)
534 -> tcRnExpr hsc_env pcs icontext expr ;
535 Just other -> do { hPutStrLn stderr ("not an expression: `" ++ expr ++ "'") ;
536 return (pcs, Nothing) } ;
537 Nothing -> return (pcs, Nothing) } }
541 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
542 hscParseStmt dflags str
543 = do showPass dflags "Parser"
546 buf <- stringToStringBuffer str
548 let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
549 ffiEF = dopt Opt_FFI dflags,
550 withEF = dopt Opt_With dflags,
551 parrEF = dopt Opt_PArr dflags}
552 loc = mkSrcLoc FSLIT("<interactive>") 1
554 case parseStmt buf (mkPState loc exts) of {
556 PFailed err -> do { hPutStrLn stderr (showSDoc err);
557 -- Not yet implemented in <4.11 freeStringBuffer buf;
560 -- no stmt: the line consisted of just space or comments
561 POk _ Nothing -> return Nothing;
563 POk _ (Just rdr_stmt) -> do {
565 --ToDo: can't free the string buffer until we've finished this
566 -- compilation sweep and all the identifiers have gone away.
567 --freeStringBuffer buf;
568 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
569 return (Just rdr_stmt)
574 %************************************************************************
576 \subsection{Getting information about an identifer}
578 %************************************************************************
582 hscThing -- like hscStmt, but deals with a single identifier
584 -> PersistentCompilerState -- IN: persistent compiler state
585 -> InteractiveContext -- Context for compiling
586 -> String -- The identifier
587 -> IO ( PersistentCompilerState,
590 hscThing hsc_env pcs0 ic str
591 = do let dflags = hsc_dflags hsc_env
593 maybe_rdr_name <- myParseIdentifier dflags str
594 case maybe_rdr_name of {
595 Nothing -> return (pcs0, []);
598 (pcs1, maybe_tc_result) <-
599 tcRnThing hsc_env pcs0 ic rdr_name
601 case maybe_tc_result of {
602 Nothing -> return (pcs1, []) ;
603 Just things -> return (pcs1, things)
606 myParseIdentifier dflags str
607 = do buf <- stringToStringBuffer str
609 let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
610 ffiEF = dopt Opt_FFI dflags,
611 withEF = dopt Opt_With dflags,
612 parrEF = dopt Opt_PArr dflags}
613 loc = mkSrcLoc FSLIT("<interactive>") 1
615 case parseIdentifier buf (mkPState loc exts) of
617 PFailed err -> do { hPutStrLn stderr (showSDoc err);
618 freeStringBuffer buf;
621 POk _ rdr_name -> do { --should, but can't: freeStringBuffer buf;
622 return (Just rdr_name) }
626 %************************************************************************
628 Desugar, simplify, convert to bytecode, and link an expression
630 %************************************************************************
634 compileExpr :: HscEnv
635 -> PersistentCompilerState
636 -> Module -> GlobalRdrEnv -> TypeEnv
640 compileExpr hsc_env pcs this_mod rdr_env type_env tc_expr
641 = do { let dflags = hsc_dflags hsc_env
644 ; ds_expr <- deSugarExpr hsc_env pcs this_mod rdr_env type_env tc_expr
647 ; flat_expr <- flattenExpr hsc_env pcs ds_expr
650 ; simpl_expr <- simplifyExpr dflags flat_expr
652 -- Tidy it (temporary, until coreSat does cloning)
653 ; tidy_expr <- tidyCoreExpr simpl_expr
655 -- Prepare for codegen
656 ; prepd_expr <- corePrepExpr dflags tidy_expr
659 ; bcos <- coreExprToBCOs dflags prepd_expr
662 ; hval <- linkExpr hsc_env pcs bcos
670 %************************************************************************
672 \subsection{Initial persistent state}
674 %************************************************************************
677 initPersistentCompilerState :: IO PersistentCompilerState
678 initPersistentCompilerState
679 = do nc <- initNameCache
681 PCS { pcs_EPS = initExternalPackageState,
684 initNameCache :: IO NameCache
685 = do us <- mkSplitUniqSupply 'r'
686 return (NameCache { nsUniqs = us,
687 nsNames = initOrigNames,
690 initExternalPackageState :: ExternalPackageState
691 initExternalPackageState
693 eps_decls = (emptyNameEnv, 0),
694 eps_insts = (emptyBag, 0),
695 eps_inst_gates = emptyNameSet,
696 eps_rules = foldr add_rule (emptyBag, 0) builtinRules,
698 eps_PIT = emptyPackageIfaceTable,
699 eps_PTE = wiredInThingEnv,
700 eps_inst_env = emptyInstEnv,
701 eps_rule_base = emptyRuleBase }
704 add_rule (name,rule) (rules, n_slurped)
705 = (gated_decl `consBag` rules, n_slurped)
707 gated_decl = (gate_fn, (mod, IfaceRuleOut rdr_name rule))
708 mod = nameModule name
709 rdr_name = nameRdrName name
710 gate_fn vis_fn = vis_fn name -- Load the rule whenever name is visible
712 initOrigNames :: OrigNameCache
714 = insert knownKeyNames $
715 insert (map getName wiredInThings) $
718 insert names env = foldl extendOrigNameCache env names