2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
8 module HscMain ( HscResult(..), hscMain,
12 initPersistentCompilerState ) where
14 #include "HsVersions.h"
17 import ByteCodeGen ( byteCodeGen )
18 import CoreTidy ( tidyCoreExpr )
19 import CorePrep ( corePrepExpr )
20 import Rename ( renameStmt )
21 import RdrHsSyn ( RdrNameStmt )
23 import Id ( Id, idName, setGlobalIdDetails )
24 import IdInfo ( GlobalIdDetails(VanillaGlobal) )
25 import HscTypes ( InteractiveContext(..) )
26 import PrelNames ( iNTERACTIVE )
27 import StringBuffer ( stringToStringBuffer )
33 import IdInfo ( CafInfo(..), CgInfoEnv, CgInfo(..) )
34 import StringBuffer ( hGetStringBuffer, freeStringBuffer )
36 import Lex ( PState(..), ParseResult(..) )
37 import SrcLoc ( mkSrcLoc )
38 import Finder ( findModule )
39 import Rename ( checkOldIface, renameModule, closeIfaceDecls )
40 import Rules ( emptyRuleBase )
41 import PrelInfo ( wiredInThingEnv, wiredInThings )
42 import PrelNames ( vanillaSyntaxMap, knownKeyNames )
43 import MkIface ( mkFinalIface )
45 import InstEnv ( emptyInstEnv )
48 import CoreUtils ( coreBindsSize )
49 import CoreTidy ( tidyCorePgm )
50 import CorePrep ( corePrepPgm )
52 import CoreToStg ( coreToStg )
53 import SimplStg ( stg2stg )
54 import CodeGen ( codeGen )
55 import CodeOutput ( codeOutput )
57 import Module ( ModuleName, moduleName, mkHomeModule,
60 import ErrUtils ( dumpIfSet_dyn, showPass, printError )
61 import Util ( unJust )
62 import UniqSupply ( mkSplitUniqSupply )
64 import Bag ( emptyBag )
67 import CmStaticInfo ( GhciMode(..) )
68 import HscStats ( ppSourceStats )
70 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
71 import OccName ( OccName )
72 import Name ( Name, nameModule, nameOccName, getName, isGlobalName )
73 import NameEnv ( emptyNameEnv, mkNameEnv )
74 import Module ( Module )
76 import IOExts ( newIORef, readIORef, writeIORef, unsafePerformIO )
79 import Maybe ( isJust, fromJust )
82 import MkExternalCore ( emitExternalCore )
86 %************************************************************************
88 \subsection{The main compiler pipeline}
90 %************************************************************************
95 = HscFail PersistentCompilerState -- updated PCS
96 -- concluded that it wasn't necessary
97 | HscNoRecomp PersistentCompilerState -- updated PCS
98 ModDetails -- new details (HomeSymbolTable additions)
99 ModIface -- new iface (if any compilation was done)
101 | HscRecomp PersistentCompilerState -- updated PCS
102 ModDetails -- new details (HomeSymbolTable additions)
103 ModIface -- new iface (if any compilation was done)
104 Bool -- stub_h exists
105 Bool -- stub_c exists
106 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
109 -- no errors or warnings; the individual passes
110 -- (parse/rename/typecheck) print messages themselves
116 -> ModuleLocation -- location info
117 -> Bool -- True <=> source unchanged
118 -> Bool -- True <=> have an object file (for msgs only)
119 -> Maybe ModIface -- old interface, if available
120 -> HomeSymbolTable -- for home module ModDetails
122 -> PersistentCompilerState -- IN: persistent compiler state
125 hscMain ghci_mode dflags mod location source_unchanged have_object
126 maybe_old_iface hst hit pcs
128 showPass dflags ("Checking old interface for hs = "
129 ++ show (ml_hs_file location)
130 ++ ", hspp = " ++ show (ml_hspp_file location));
132 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
133 <- _scc_ "checkOldIface"
134 checkOldIface ghci_mode dflags hit hst pcs (ml_hi_file location)
135 source_unchanged maybe_old_iface;
138 return (HscFail pcs_ch)
141 let no_old_iface = not (isJust maybe_checked_iface)
142 what_next | recomp_reqd || no_old_iface = hscRecomp
143 | otherwise = hscNoRecomp
145 what_next ghci_mode dflags have_object mod location
146 maybe_checked_iface hst hit pcs_ch
150 -- we definitely expect to have the old interface available
151 hscNoRecomp ghci_mode dflags have_object
152 mod location (Just old_iface) hst hit pcs_ch
153 | ghci_mode == OneShot
155 hPutStrLn stderr "compilation IS NOT required";
156 let { bomb = panic "hscNoRecomp:OneShot" };
157 return (HscNoRecomp pcs_ch bomb bomb)
161 when (verbosity dflags >= 1) $
162 hPutStrLn stderr ("Skipping " ++
163 compMsg have_object mod location);
166 (pcs_cl, closure_errs, cl_hs_decls)
167 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
169 return (HscFail pcs_cl)
174 <- typecheckIface dflags pcs_cl hst old_iface (vanillaSyntaxMap, cl_hs_decls);
176 case maybe_tc_result of {
177 Nothing -> return (HscFail pcs_cl);
178 Just (pcs_tc, new_details) ->
180 return (HscNoRecomp pcs_tc new_details old_iface)
183 compMsg use_object mod location =
184 mod_str ++ take (max 0 (16 - length mod_str)) (repeat ' ')
185 ++" ( " ++ unJust "hscRecomp" (ml_hs_file location) ++ ", "
187 then unJust "hscRecomp" (ml_obj_file location)
190 where mod_str = moduleUserString mod
193 hscRecomp ghci_mode dflags have_object
194 mod location maybe_checked_iface hst hit pcs_ch
196 -- what target are we shooting for?
197 ; let toInterp = dopt_HscLang dflags == HscInterpreted
199 ; when (verbosity dflags >= 1) $
200 hPutStrLn stderr ("Compiling " ++
201 compMsg (not toInterp) mod location);
206 ; maybe_parsed <- myParseModule dflags
207 (unJust "hscRecomp:hspp" (ml_hspp_file location))
208 ; case maybe_parsed of {
209 Nothing -> return (HscFail pcs_ch);
210 Just rdr_module -> do {
211 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
216 ; (pcs_rn, print_unqualified, maybe_rn_result)
218 renameModule dflags hit hst pcs_ch this_mod rdr_module
219 ; case maybe_rn_result of {
220 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
221 Just (is_exported, new_iface, rn_hs_decls) -> do {
223 -- In interactive mode, we don't want to discard any top-level entities at
224 -- all (eg. do not inline them away during simplification), and retain them
225 -- all in the TypeEnv so they are available from the command line.
227 -- isGlobalName separates the user-defined top-level names from those
228 -- introduced by the type checker.
229 ; let dont_discard | ghci_mode == Interactive = isGlobalName
230 | otherwise = is_exported
236 <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface
237 print_unqualified rn_hs_decls
238 ; case maybe_tc_result of {
239 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
240 Just (pcs_tc, tc_result) -> do {
245 ; (ds_details, foreign_stuff)
247 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
250 <- if ghci_mode == OneShot
251 then do init_pcs <- initPersistentCompilerState
252 init_prs <- initPersistentRenamerState
254 rules = pcs_rules pcs_tc
255 orig_tc = prsOrig (pcs_PRS pcs_tc)
256 new_prs = init_prs{ prsOrig=orig_tc }
258 orig_tc `seq` rules `seq` new_prs `seq`
259 return init_pcs{ pcs_PRS = new_prs,
268 core2core dflags pcs_middle hst dont_discard ds_details
273 ; cg_info_ref <- newIORef Nothing ;
274 ; let cg_info :: CgInfoEnv
275 cg_info = unsafePerformIO $ do {
276 maybe_cg_env <- readIORef cg_info_ref ;
278 Just env -> return env
279 Nothing -> do { printError "Urk! Looked at CgInfo too early!";
280 return emptyNameEnv } }
281 -- cg_info_ref will be filled in just after restOfCodeGeneration
282 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
284 ; (pcs_simpl, tidy_details)
286 tidyCorePgm dflags this_mod pcs_middle cg_info simpl_details
288 ; pcs_final <- if ghci_mode == OneShot then initPersistentCompilerState
289 else return pcs_simpl
291 -- alive at this point:
295 ; emitExternalCore dflags new_iface tidy_details
297 -- PREPARE FOR CODE GENERATION
299 -- Do saturation and convert to A-normal form
300 ; prepd_details <- _scc_ "CorePrep" corePrepPgm dflags tidy_details
303 -- CONVERT TO STG and COMPLETE CODE GENERATION
306 ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
308 local_tycons = typeEnvTyCons env_tc
309 local_classes = typeEnvClasses env_tc
311 imported_module_names = map ideclName (hsModuleImports rdr_module)
313 mod_name_to_Module nm
314 = do m <- findModule nm ; return (fst (fromJust m))
316 (h_code,c_code,fe_binders) = foreign_stuff
318 ; imported_modules <- mapM mod_name_to_Module imported_module_names
320 ; (stub_h_exists, stub_c_exists, maybe_bcos, final_iface )
323 ----------------- Generate byte code ------------------
324 (bcos,itbl_env) <- byteCodeGen dflags binds
325 local_tycons local_classes
327 -- Fill in the code-gen info
328 writeIORef cg_info_ref (Just emptyNameEnv)
330 ------------------ BUILD THE NEW ModIface ------------
331 final_iface <- _scc_ "MkFinalIface"
332 mkFinalIface ghci_mode dflags location
333 maybe_checked_iface new_iface tidy_details
335 return ( False, False, Just (bcos,itbl_env), final_iface )
338 ----------------- Convert to STG ------------------
339 (stg_binds, cost_centre_info, stg_back_end_info)
341 myCoreToStg dflags this_mod binds
343 -- Fill in the code-gen info for the earlier tidyCorePgm
344 writeIORef cg_info_ref (Just stg_back_end_info)
346 ------------------ BUILD THE NEW ModIface ------------
347 final_iface <- _scc_ "MkFinalIface"
348 mkFinalIface ghci_mode dflags location
349 maybe_checked_iface new_iface tidy_details
351 ------------------ Code generation ------------------
352 abstractC <- _scc_ "CodeGen"
353 codeGen dflags this_mod imported_modules
354 cost_centre_info fe_binders
355 local_tycons stg_binds
357 ------------------ Code output -----------------------
358 (stub_h_exists, stub_c_exists)
359 <- codeOutput dflags this_mod local_tycons
361 c_code h_code abstractC
363 return (stub_h_exists, stub_c_exists, Nothing, final_iface)
365 ; let final_details = tidy_details {md_binds = []}
368 -- and the answer is ...
369 ; return (HscRecomp pcs_final
372 stub_h_exists stub_c_exists
376 myParseModule dflags src_filename
377 = do -------------------------- Parser ----------------
378 showPass dflags "Parser"
381 buf <- hGetStringBuffer True{-expand tabs-} src_filename
383 let glaexts | dopt Opt_GlasgowExts dflags = 1#
386 case parseModule buf PState{ bol = 0#, atbol = 1#,
387 context = [], glasgow_exts = glaexts,
388 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
390 PFailed err -> do { hPutStrLn stderr (showSDoc err);
391 freeStringBuffer buf;
394 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
396 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
398 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
399 (ppSourceStats False rdr_module) ;
401 return (Just rdr_module)
402 -- ToDo: free the string buffer later.
406 myCoreToStg dflags this_mod tidy_binds
408 () <- coreBindsSize tidy_binds `seq` return ()
409 -- TEMP: the above call zaps some space usage allocated by the
410 -- simplifier, which for reasons I don't understand, persists
411 -- thoroughout code generation
413 stg_binds <- _scc_ "Core2Stg" coreToStg dflags tidy_binds
415 (stg_binds2, cost_centre_info)
416 <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
418 let env_rhs :: CgInfoEnv
419 env_rhs = mkNameEnv [ (idName bndr, CgInfo (stgRhsArity rhs) caf_info)
420 | (bind,_) <- stg_binds2,
422 | stgBindHasCafRefs bind = MayHaveCafRefs
423 | otherwise = NoCafRefs,
424 (bndr,rhs) <- stgBindPairs bind ]
426 return (stg_binds2, cost_centre_info, env_rhs)
428 stgBindPairs (StgNonRec _ b r) = [(b,r)]
429 stgBindPairs (StgRec _ prs) = prs
435 %************************************************************************
437 \subsection{Compiling a do-statement}
439 %************************************************************************
447 -> PersistentCompilerState -- IN: persistent compiler state
448 -> InteractiveContext -- Context for compiling
449 -> String -- The statement
450 -> Bool -- just treat it as an expression
451 -> IO ( PersistentCompilerState,
457 When the UnlinkedBCOExpr is linked you get an HValue of type
459 When you run it you get a list of HValues that should be
460 the same length as the list of names; add them to the ClosureEnv.
462 A naked expression returns a singleton Name [it].
464 What you type The IO [HValue] that hscStmt returns
465 ------------- ------------------------------------
466 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
469 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
472 expr (of IO type) ==> expr >>= \ v -> return [v]
473 [NB: result not printed] bindings: [it]
476 expr (of non-IO type,
477 result showable) ==> let v = expr in print v >> return [v]
480 expr (of non-IO type,
481 result not showable) ==> error
484 hscStmt dflags hst hit pcs0 icontext stmt just_expr
488 ic_type_env = type_env,
489 ic_module = scope_mod } = icontext
491 do { maybe_stmt <- hscParseStmt dflags stmt
493 Nothing -> return (pcs0, Nothing)
494 Just parsed_stmt -> do {
496 let { notExprStmt (ExprStmt _ _) = False;
500 if (just_expr && notExprStmt parsed_stmt)
501 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
502 return (pcs0, Nothing)
506 (pcs1, print_unqual, maybe_renamed_stmt)
507 <- renameStmt dflags hit hst pcs0 scope_mod
508 iNTERACTIVE rn_env parsed_stmt
510 ; case maybe_renamed_stmt of
511 Nothing -> return (pcs0, Nothing)
512 Just (bound_names, rn_stmt) -> do {
517 then case rn_stmt of { (syn, ExprStmt e _, decls) ->
518 typecheckExpr dflags pcs1 hst type_env
519 print_unqual iNTERACTIVE (syn,e,decls) }
520 else typecheckStmt dflags pcs1 hst type_env
521 print_unqual iNTERACTIVE bound_names rn_stmt
523 ; case maybe_tc_return of
524 Nothing -> return (pcs0, Nothing)
525 Just (pcs2, tc_expr, bound_ids, ty) -> do {
528 ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
531 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
533 -- Tidy it (temporary, until coreSat does cloning)
534 ; tidy_expr <- tidyCoreExpr simpl_expr
536 -- Prepare for codegen
537 ; prepd_expr <- corePrepExpr dflags tidy_expr
540 ; bcos <- coreExprToBCOs dflags prepd_expr
543 -- Make all the bound ids "global" ids, now that
544 -- they're notionally top-level bindings. This is
545 -- important: otherwise when we come to compile an expression
546 -- using these ids later, the byte code generator will consider
547 -- the occurrences to be free rather than global.
548 global_bound_ids = map globaliseId bound_ids;
549 globaliseId id = setGlobalIdDetails id VanillaGlobal
551 ; return (pcs2, Just (global_bound_ids, ty, bcos))
555 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
556 hscParseStmt dflags str
557 = do -------------------------- Parser ----------------
558 showPass dflags "Parser"
561 buf <- stringToStringBuffer str
563 let glaexts | dopt Opt_GlasgowExts dflags = 1#
566 case parseStmt buf PState{ bol = 0#, atbol = 1#,
567 context = [], glasgow_exts = glaexts,
568 loc = mkSrcLoc SLIT("<no file>") 0 } of {
570 PFailed err -> do { hPutStrLn stderr (showSDoc err);
571 -- Not yet implemented in <4.11 freeStringBuffer buf;
574 -- no stmt: the line consisted of just space or comments
575 POk _ Nothing -> return Nothing;
577 POk _ (Just rdr_stmt) -> do {
579 --ToDo: can't free the string buffer until we've finished this
580 -- compilation sweep and all the identifiers have gone away.
581 --freeStringBuffer buf;
582 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
583 return (Just rdr_stmt)
588 %************************************************************************
590 \subsection{Initial persistent state}
592 %************************************************************************
595 initPersistentCompilerState :: IO PersistentCompilerState
596 initPersistentCompilerState
597 = do prs <- initPersistentRenamerState
599 PCS { pcs_PIT = emptyIfaceTable,
600 pcs_PTE = wiredInThingEnv,
601 pcs_insts = emptyInstEnv,
602 pcs_rules = emptyRuleBase,
607 initPersistentRenamerState :: IO PersistentRenamerState
608 = do us <- mkSplitUniqSupply 'r'
610 PRS { prsOrig = NameSupply { nsUniqs = us,
611 nsNames = initOrigNames,
613 prsDecls = (emptyNameEnv, 0),
614 prsInsts = (emptyBag, 0),
615 prsRules = (emptyBag, 0),
620 initOrigNames :: FiniteMap (ModuleName,OccName) Name
622 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
624 grab names = foldl add emptyFM names
626 = addToFM env (moduleName (nameModule name), nameOccName name) name