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 SrcLoc ( noSrcLoc )
21 import Rename ( renameStmt )
22 import RdrName ( mkUnqual )
23 import RdrHsSyn ( RdrNameStmt )
24 import OccName ( dataName )
26 import Id ( Id, idName, setGlobalIdDetails )
27 import IdInfo ( GlobalIdDetails(VanillaGlobal) )
28 import HscTypes ( InteractiveContext(..) )
29 import PrelNames ( iNTERACTIVE )
30 import StringBuffer ( stringToStringBuffer )
31 import FastString ( mkFastString )
37 import IdInfo ( CafInfo(..), CgInfoEnv, CgInfo(..) )
38 import StringBuffer ( hGetStringBuffer, freeStringBuffer )
40 import Lex ( PState(..), ParseResult(..) )
41 import SrcLoc ( mkSrcLoc )
42 import Finder ( findModule )
43 import Rename ( checkOldIface, renameModule, closeIfaceDecls )
44 import Rules ( emptyRuleBase )
45 import PrelInfo ( wiredInThingEnv, wiredInThings )
46 import PrelNames ( knownKeyNames )
47 import MkIface ( mkFinalIface )
49 import InstEnv ( emptyInstEnv )
52 import CoreUtils ( coreBindsSize )
53 import CoreTidy ( tidyCorePgm )
54 import CorePrep ( corePrepPgm )
56 import CoreToStg ( coreToStg )
57 import SimplStg ( stg2stg )
58 import CodeGen ( codeGen )
59 import CodeOutput ( codeOutput )
61 import Module ( ModuleName, moduleName, mkHomeModule,
64 import ErrUtils ( dumpIfSet_dyn, showPass, printError )
65 import Util ( unJust )
66 import UniqSupply ( mkSplitUniqSupply )
68 import Bag ( emptyBag )
71 import HscStats ( ppSourceStats )
73 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
74 import OccName ( OccName )
75 import Name ( Name, nameModule, nameOccName, getName, isGlobalName )
76 import NameEnv ( emptyNameEnv, mkNameEnv )
77 import Module ( Module )
79 import IOExts ( newIORef, readIORef, writeIORef, unsafePerformIO )
82 import Maybe ( isJust, fromJust )
85 import MkExternalCore ( emitExternalCore )
89 %************************************************************************
91 \subsection{The main compiler pipeline}
93 %************************************************************************
98 = HscFail PersistentCompilerState -- updated PCS
99 -- concluded that it wasn't necessary
100 | HscNoRecomp PersistentCompilerState -- updated PCS
101 ModDetails -- new details (HomeSymbolTable additions)
102 ModIface -- new iface (if any compilation was done)
104 | HscRecomp PersistentCompilerState -- updated PCS
105 ModDetails -- new details (HomeSymbolTable additions)
106 ModIface -- new iface (if any compilation was done)
107 Bool -- stub_h exists
108 Bool -- stub_c exists
109 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
112 -- no errors or warnings; the individual passes
113 -- (parse/rename/typecheck) print messages themselves
119 -> ModuleLocation -- location info
120 -> Bool -- True <=> source unchanged
121 -> Bool -- True <=> have an object file (for msgs only)
122 -> Maybe ModIface -- old interface, if available
123 -> HomeSymbolTable -- for home module ModDetails
125 -> PersistentCompilerState -- IN: persistent compiler state
128 hscMain ghci_mode dflags mod location source_unchanged have_object
129 maybe_old_iface hst hit pcs
131 showPass dflags ("Checking old interface for hs = "
132 ++ show (ml_hs_file location)
133 ++ ", hspp = " ++ show (ml_hspp_file location));
135 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
136 <- _scc_ "checkOldIface"
137 checkOldIface ghci_mode dflags hit hst pcs (ml_hi_file location)
138 source_unchanged maybe_old_iface;
141 return (HscFail pcs_ch)
144 let no_old_iface = not (isJust maybe_checked_iface)
145 what_next | recomp_reqd || no_old_iface = hscRecomp
146 | otherwise = hscNoRecomp
148 what_next ghci_mode dflags have_object mod location
149 maybe_checked_iface hst hit pcs_ch
153 -- we definitely expect to have the old interface available
154 hscNoRecomp ghci_mode dflags have_object
155 mod location (Just old_iface) hst hit pcs_ch
156 | ghci_mode == OneShot
158 hPutStrLn stderr "compilation IS NOT required";
159 let { bomb = panic "hscNoRecomp:OneShot" };
160 return (HscNoRecomp pcs_ch bomb bomb)
164 when (verbosity dflags >= 1) $
165 hPutStrLn stderr ("Skipping " ++
166 compMsg have_object mod location);
169 (pcs_cl, closure_errs, cl_hs_decls)
170 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
172 return (HscFail pcs_cl)
177 <- typecheckIface dflags pcs_cl hst old_iface cl_hs_decls;
179 case maybe_tc_result of {
180 Nothing -> return (HscFail pcs_cl);
181 Just (pcs_tc, new_details) ->
183 return (HscNoRecomp pcs_tc new_details old_iface)
186 compMsg use_object mod location =
187 mod_str ++ take (max 0 (16 - length mod_str)) (repeat ' ')
188 ++" ( " ++ unJust "hscRecomp" (ml_hs_file location) ++ ", "
190 then unJust "hscRecomp" (ml_obj_file location)
193 where mod_str = moduleUserString mod
196 hscRecomp ghci_mode dflags have_object
197 mod location maybe_checked_iface hst hit pcs_ch
199 -- what target are we shooting for?
200 ; let toInterp = dopt_HscLang dflags == HscInterpreted
202 ; when (verbosity dflags >= 1) $
203 hPutStrLn stderr ("Compiling " ++
204 compMsg (not toInterp) mod location);
209 ; maybe_parsed <- myParseModule dflags
210 (unJust "hscRecomp:hspp" (ml_hspp_file location))
211 ; case maybe_parsed of {
212 Nothing -> return (HscFail pcs_ch);
213 Just rdr_module -> do {
214 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
219 ; (pcs_rn, print_unqualified, maybe_rn_result)
221 renameModule dflags hit hst pcs_ch this_mod rdr_module
222 ; case maybe_rn_result of {
223 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
224 Just (is_exported, new_iface, rn_hs_decls) -> do {
226 -- In interactive mode, we don't want to discard any top-level entities at
227 -- all (eg. do not inline them away during simplification), and retain them
228 -- all in the TypeEnv so they are available from the command line.
230 -- isGlobalName separates the user-defined top-level names from those
231 -- introduced by the type checker.
232 ; let dont_discard | ghci_mode == Interactive = isGlobalName
233 | otherwise = is_exported
239 <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface
240 print_unqualified rn_hs_decls
241 ; case maybe_tc_result of {
242 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
243 Just (pcs_tc, tc_result) -> do {
248 ; (ds_details, foreign_stuff)
250 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
253 <- if ghci_mode == OneShot
254 then do init_pcs <- initPersistentCompilerState
255 init_prs <- initPersistentRenamerState
257 rules = pcs_rules pcs_tc
258 orig_tc = prsOrig (pcs_PRS pcs_tc)
259 new_prs = init_prs{ prsOrig=orig_tc }
261 orig_tc `seq` rules `seq` new_prs `seq`
262 return init_pcs{ pcs_PRS = new_prs,
271 core2core dflags pcs_middle hst dont_discard ds_details
276 ; cg_info_ref <- newIORef Nothing ;
277 ; let cg_info :: CgInfoEnv
278 cg_info = unsafePerformIO $ do {
279 maybe_cg_env <- readIORef cg_info_ref ;
281 Just env -> return env
282 Nothing -> do { printError "Urk! Looked at CgInfo too early!";
283 return emptyNameEnv } }
284 -- cg_info_ref will be filled in just after restOfCodeGeneration
285 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
287 ; (pcs_simpl, tidy_details)
289 tidyCorePgm dflags this_mod pcs_middle cg_info simpl_details
291 ; pcs_final <- if ghci_mode == OneShot then initPersistentCompilerState
292 else return pcs_simpl
294 -- alive at this point:
298 ; emitExternalCore dflags new_iface tidy_details
300 -- PREPARE FOR CODE GENERATION
302 -- Do saturation and convert to A-normal form
303 ; prepd_details <- _scc_ "CorePrep" corePrepPgm dflags tidy_details
306 -- CONVERT TO STG and COMPLETE CODE GENERATION
309 ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
311 local_tycons = typeEnvTyCons env_tc
312 local_classes = typeEnvClasses env_tc
314 imported_module_names = map ideclName (hsModuleImports rdr_module)
316 mod_name_to_Module nm
317 = do m <- findModule nm ; return (fst (fromJust m))
319 (h_code,c_code,fe_binders) = foreign_stuff
321 ; imported_modules <- mapM mod_name_to_Module imported_module_names
323 ; (stub_h_exists, stub_c_exists, maybe_bcos, final_iface )
326 ----------------- Generate byte code ------------------
327 (bcos,itbl_env) <- byteCodeGen dflags binds
328 local_tycons local_classes
330 -- Fill in the code-gen info
331 writeIORef cg_info_ref (Just emptyNameEnv)
333 ------------------ BUILD THE NEW ModIface ------------
334 final_iface <- _scc_ "MkFinalIface"
335 mkFinalIface ghci_mode dflags location
336 maybe_checked_iface new_iface tidy_details
338 return ( False, False, Just (bcos,itbl_env), final_iface )
341 ----------------- Convert to STG ------------------
342 (stg_binds, cost_centre_info, stg_back_end_info)
344 myCoreToStg dflags this_mod binds
346 -- Fill in the code-gen info for the earlier tidyCorePgm
347 writeIORef cg_info_ref (Just stg_back_end_info)
349 ------------------ BUILD THE NEW ModIface ------------
350 final_iface <- _scc_ "MkFinalIface"
351 mkFinalIface ghci_mode dflags location
352 maybe_checked_iface new_iface tidy_details
354 ------------------ Code generation ------------------
355 abstractC <- _scc_ "CodeGen"
356 codeGen dflags this_mod imported_modules
357 cost_centre_info fe_binders
358 local_tycons stg_binds
360 ------------------ Code output -----------------------
361 (stub_h_exists, stub_c_exists)
362 <- codeOutput dflags this_mod local_tycons
364 c_code h_code abstractC
366 return (stub_h_exists, stub_c_exists, Nothing, final_iface)
368 ; let final_details = tidy_details {md_binds = []}
371 -- and the answer is ...
372 ; return (HscRecomp pcs_final
375 stub_h_exists stub_c_exists
379 myParseModule dflags src_filename
380 = do -------------------------- Parser ----------------
381 showPass dflags "Parser"
384 buf <- hGetStringBuffer True{-expand tabs-} src_filename
386 let glaexts | dopt Opt_GlasgowExts dflags = 1#
389 case parseModule buf PState{ bol = 0#, atbol = 1#,
390 context = [], glasgow_exts = glaexts,
391 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
393 PFailed err -> do { hPutStrLn stderr (showSDoc err);
394 freeStringBuffer buf;
397 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
399 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
401 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
402 (ppSourceStats False rdr_module) ;
404 return (Just rdr_module)
405 -- ToDo: free the string buffer later.
409 myCoreToStg dflags this_mod tidy_binds
411 () <- coreBindsSize tidy_binds `seq` return ()
412 -- TEMP: the above call zaps some space usage allocated by the
413 -- simplifier, which for reasons I don't understand, persists
414 -- thoroughout code generation
416 stg_binds <- _scc_ "Core2Stg" coreToStg dflags tidy_binds
418 (stg_binds2, cost_centre_info)
419 <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
421 let env_rhs :: CgInfoEnv
422 env_rhs = mkNameEnv [ (idName bndr, CgInfo (stgRhsArity rhs) caf_info)
423 | (bind,_) <- stg_binds2,
425 | stgBindHasCafRefs bind = MayHaveCafRefs
426 | otherwise = NoCafRefs,
427 (bndr,rhs) <- stgBindPairs bind ]
429 return (stg_binds2, cost_centre_info, env_rhs)
431 stgBindPairs (StgNonRec _ b r) = [(b,r)]
432 stgBindPairs (StgRec _ prs) = prs
438 %************************************************************************
440 \subsection{Compiling a do-statement}
442 %************************************************************************
450 -> PersistentCompilerState -- IN: persistent compiler state
451 -> InteractiveContext -- Context for compiling
452 -> String -- The statement
453 -> Bool -- just treat it as an expression
454 -> IO ( PersistentCompilerState,
460 When the UnlinkedBCOExpr is linked you get an HValue of type
462 When you run it you get a list of HValues that should be
463 the same length as the list of names; add them to the ClosureEnv.
465 A naked expression returns a singleton Name [it].
467 What you type The IO [HValue] that hscStmt returns
468 ------------- ------------------------------------
469 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
472 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
475 expr (of IO type) ==> expr >>= \ v -> return [v]
476 [NB: result not printed] bindings: [it]
479 expr (of non-IO type,
480 result showable) ==> let v = expr in print v >> return [v]
483 expr (of non-IO type,
484 result not showable) ==> error
487 hscStmt dflags hst hit pcs0 icontext stmt just_expr
491 ic_type_env = type_env,
492 ic_module = scope_mod } = icontext
494 do { maybe_stmt <- hscParseStmt dflags stmt
496 Nothing -> return (pcs0, Nothing)
497 Just parsed_stmt -> do {
499 let { notExprStmt (ExprStmt _ _ _) = False;
503 if (just_expr && notExprStmt parsed_stmt)
504 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
505 return (pcs0, Nothing)
509 (pcs1, print_unqual, maybe_renamed_stmt)
510 <- renameStmt dflags hit hst pcs0 scope_mod
511 iNTERACTIVE rn_env parsed_stmt
513 ; case maybe_renamed_stmt of
514 Nothing -> return (pcs0, Nothing)
515 Just (bound_names, rn_stmt) -> do {
520 then case rn_stmt of { (ExprStmt e _ _, decls) ->
521 typecheckExpr dflags pcs1 hst type_env
522 print_unqual iNTERACTIVE (e,decls) }
523 else typecheckStmt dflags pcs1 hst type_env
524 print_unqual iNTERACTIVE bound_names rn_stmt
526 ; case maybe_tc_return of
527 Nothing -> return (pcs0, Nothing)
528 Just (pcs2, tc_expr, bound_ids, ty) -> do {
531 ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
534 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
536 -- Tidy it (temporary, until coreSat does cloning)
537 ; tidy_expr <- tidyCoreExpr simpl_expr
539 -- Prepare for codegen
540 ; prepd_expr <- corePrepExpr dflags tidy_expr
543 ; bcos <- coreExprToBCOs dflags prepd_expr
546 -- Make all the bound ids "global" ids, now that
547 -- they're notionally top-level bindings. This is
548 -- important: otherwise when we come to compile an expression
549 -- using these ids later, the byte code generator will consider
550 -- the occurrences to be free rather than global.
551 global_bound_ids = map globaliseId bound_ids;
552 globaliseId id = setGlobalIdDetails id VanillaGlobal
554 ; return (pcs2, Just (global_bound_ids, ty, bcos))
558 hscThing -- like hscStmt, but deals with a single identifier
562 -> PersistentCompilerState -- IN: persistent compiler state
563 -> InteractiveContext -- Context for compiling
564 -> String -- The identifier
565 -> IO ( PersistentCompilerState,
567 hscThing dflags hst hit pcs0 icontext id
571 ic_type_env = type_env,
572 ic_module = scope_mod } = icontext
573 fname = mkFastString id
574 rn = mkUnqual dataName fname -- need to guess correct namespace
575 stmt = ResultStmt (HsVar rn) noSrcLoc
577 do { (pcs, err, maybe_stmt) <- renameStmt dflags hit hst pcs0 scope_mod scope_mod rn_env stmt
579 Nothing -> return (pcs, Nothing)
580 Just (n:ns, _) -> return (pcs, lookupType hst type_env n)
583 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
584 hscParseStmt dflags str
585 = do -------------------------- Parser ----------------
586 showPass dflags "Parser"
589 buf <- stringToStringBuffer str
591 let glaexts | dopt Opt_GlasgowExts dflags = 1#
594 case parseStmt buf PState{ bol = 0#, atbol = 1#,
595 context = [], glasgow_exts = glaexts,
596 loc = mkSrcLoc SLIT("<no file>") 0 } of {
598 PFailed err -> do { hPutStrLn stderr (showSDoc err);
599 -- Not yet implemented in <4.11 freeStringBuffer buf;
602 -- no stmt: the line consisted of just space or comments
603 POk _ Nothing -> return Nothing;
605 POk _ (Just rdr_stmt) -> do {
607 --ToDo: can't free the string buffer until we've finished this
608 -- compilation sweep and all the identifiers have gone away.
609 --freeStringBuffer buf;
610 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
611 return (Just rdr_stmt)
616 %************************************************************************
618 \subsection{Initial persistent state}
620 %************************************************************************
623 initPersistentCompilerState :: IO PersistentCompilerState
624 initPersistentCompilerState
625 = do prs <- initPersistentRenamerState
627 PCS { pcs_PIT = emptyIfaceTable,
628 pcs_PTE = wiredInThingEnv,
629 pcs_insts = emptyInstEnv,
630 pcs_rules = emptyRuleBase,
635 initPersistentRenamerState :: IO PersistentRenamerState
636 = do us <- mkSplitUniqSupply 'r'
638 PRS { prsOrig = NameSupply { nsUniqs = us,
639 nsNames = initOrigNames,
641 prsDecls = (emptyNameEnv, 0),
642 prsInsts = (emptyBag, 0),
643 prsRules = (emptyBag, 0),
648 initOrigNames :: FiniteMap (ModuleName,OccName) Name
650 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
652 grab names = foldl add emptyFM names
654 = addToFM env (moduleName (nameModule name), nameOccName name) name