2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
4 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
7 module HscMain ( hscMain ) where
9 #include "HsVersions.h"
11 import IO ( hPutStr, stderr )
14 import RdrHsSyn ( RdrNameHsModule )
15 import FastString ( unpackFS )
16 import StringBuffer ( hGetStringBuffer )
17 import Parser ( parse )
18 import Lex ( PState(..), ParseResult(..) )
19 import SrcLoc ( mkSrcLoc )
21 import Rename ( renameModule )
23 import PrelInfo ( wiredInThings )
24 import PrelRules ( builtinRules )
25 import MkIface ( writeIface )
26 import TcModule ( TcResults(..), typecheckModule )
27 import Desugar ( deSugar )
28 import SimplCore ( core2core )
29 import OccurAnal ( occurAnalyseBinds )
30 import CoreUtils ( coreBindsSize )
31 import CoreTidy ( tidyCorePgm )
32 import CoreToStg ( topCoreBindsToStg )
33 import StgSyn ( collectFinalStgBinders )
34 import SimplStg ( stg2stg )
35 import CodeGen ( codeGen )
36 import CodeOutput ( codeOutput )
38 import Module ( ModuleName, moduleNameUserString )
40 import ErrUtils ( ghcExit, doIfSet, dumpIfSet )
41 import UniqSupply ( mkSplitUniqSupply )
44 import Char ( isSpace )
45 import StgInterp ( runStgI )
46 import HscStats ( ppSourceStats )
50 %************************************************************************
52 \subsection{The main compiler pipeline}
54 %************************************************************************
58 = HscOK ModDetails -- new details (HomeSymbolTable additions)
59 (Maybe ModIface) -- new iface (if any compilation was done)
60 (Maybe String) -- generated stub_h filename (in /tmp)
61 (Maybe String) -- generated stub_c filename (in /tmp)
62 (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
63 PersistentCompilerState -- updated PCS
65 | HscFail PersistentCompilerState -- updated PCS
66 -- no errors or warnings; the individual passes
67 -- (parse/rename/typecheck) print messages themselves
71 -> ModSummary -- summary, including source filename
72 -> Maybe ModIFace -- old interface, if available
73 -> String -- file in which to put the output (.s, .hc, .java etc.)
74 -> HomeSymbolTable -- for home module ModDetails
75 -> PersistentCompilerState -- IN: persistent compiler state
78 hscMain dflags core_cmds stg_cmds summary maybe_old_iface
79 output_filename mod_details pcs1
81 source_unchanged :: Bool -- extracted from summary?
83 (pcs2, check_errs, (recomp_reqd, maybe_checked_iface))
84 <- checkOldIface dflags finder hit hst pcs1 mod source_unchanged
87 -- test check_errs and give up if a problem happened
88 what_next = if recomp_reqd then hscRecomp else hscNoRecomp
91 what_next dflags core_cmds stg_cmds summary hit hst
92 pcs2 maybe_checked_iface
94 hscNoRecomp = panic "hscNoRecomp"
96 hscRecomp dflags core_cmds stg_cmds summary hit hst pcs maybe_old_iface
98 -- what target are we shooting for?
99 let toInterp = dopt_HscLang dflags == HscInterpreted;
102 maybe_parsed <- myParseModule dflags summary;
103 case maybe_parsed of {
104 Nothing -> return (HscFail pcs);
105 Just rdr_module -> do {
108 (pcs_rn, maybe_rn_result)
109 <- renameModule dflags finder hit hst pcs mod rdr_module;
110 case maybe_rn_result of {
111 Nothing -> return (HscFail pcs_rn);
112 Just (new_iface, rn_hs_decls) -> do {
116 <- typecheckModule dflags mod pcs_rn hst hit pit rn_hs_decls;
117 case maybe_tc_result of {
118 Nothing -> return (HscFail pcs_rn);
119 Just tc_result -> do {
121 let pcs_tc = tc_pcs tc_result
122 let env_tc = tc_env tc_result
123 let binds_tc = tc_binds tc_result
124 let local_tycons = tc_tycons tc_result
125 let local_classes = tc_classes tc_result
127 -- DESUGAR, SIMPLIFY, TIDY-CORE
128 -- We grab the the unfoldings at this point.
129 (tidy_binds, orphan_rules, fe_binders, h_code, c_code) -- return modDetails?
130 <- dsThenSimplThenTidy dflags mod tc_result rule_base ds_uniqs
133 (stg_binds, cost_centre_info, top_level_ids)
134 <- myCoreToStg c2s_uniqs st_uniqs this_mod tidy_binds
136 -- cook up a new ModDetails now we (finally) have all the bits
137 let new_details = completeModDetails tc_env tidy_binds top_level_ids orphan_rules
139 -- and possibly create a new ModIface
140 let maybe_final_iface = completeIface maybe_old_iface new_iface new_details
142 -- do the rest of code generation/emission
143 (maybe_ibinds, maybe_stub_h_filename, maybe_stub_c_filename)
144 <- restOfCodeGeneration toInterp
145 this_mod imported_modules cost_centre_info
146 fe_binders local_tycons local_classes stg_binds
148 -- and the answer is ...
149 return (HscOK new_details maybe_final_iface
150 maybe_stub_h_filename maybe_stub_c_filename
155 myParseModule dflags summary
156 = do -------------------------- Reader ----------------
160 let src_filename -- name of the preprocessed source file
161 = case ms_ppsource summary of
162 Just (filename, fingerprint) -> filename
163 Nothing -> pprPanic "myParseModule:summary is not of a source module"
166 buf <- hGetStringBuffer True{-expand tabs-} src_filename
168 let glaexts | dopt Opt_GlasgowExts dflags = 1#
171 case parse buf PState{ bol = 0#, atbol = 1#,
172 context = [], glasgow_exts = glaexts,
173 loc = mkSrcLoc src_filename 1 } of {
175 PFailed err -> do hPutStrLn stderr (showSDoc err)
177 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) ->
179 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module)
180 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
181 (ppSourceStats False rdr_module)
183 return (Just rdr_module)
186 restOfCodeGeneration toInterp this_mod imported_modules cost_centre_info
187 fe_binders local_tycons local_classes stg_binds
189 = return (Nothing, Nothing, stgToInterpSyn stg_binds local_tycons local_classes)
192 = do -------------------------- Code generation -------------------------------
195 abstractC <- codeGen this_mod imported_modules
196 cost_centre_info fe_binders
197 local_tycons local_classes stg_binds
199 -------------------------- Code output -------------------------------
200 show_pass "CodeOutput"
201 -- _scc_ "CodeOutput"
202 (maybe_stub_h_name, maybe_stub_c_name)
203 <- codeOutput this_mod local_tycons local_classes
204 occ_anal_tidy_binds stg_binds2
205 c_code h_code abstractC ncg_uniqs
207 return (maybe_stub_h_name, maybe_stub_c_name, [{-UnlinkedIBind-}])
210 dsThenSimplThenTidy dflags mod tc_result rule_base ds_uniqs
211 = do -------------------------- Desugaring ----------------
213 (desugared, rules, h_code, c_code, fe_binders)
214 <- deSugar this_mod ds_uniqs tc_results
216 -------------------------- Main Core-language transformations ----------------
218 (simplified, orphan_rules) <- core2core core_cmds desugared rules
220 -- Do the final tidy-up
221 (tidy_binds, tidy_orphan_rules)
222 <- tidyCorePgm this_mod simplified orphan_rules
224 return (tidy_binds, tidy_orphan_rules, fe_binders, h_code, c_code)
228 myCoreToStg c2s_uniqs st_uniqs this_mod tidy_binds
229 = do let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
231 () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
232 -- TEMP: the above call zaps some space usage allocated by the
233 -- simplifier, which for reasons I don't understand, persists
234 -- thoroughout code generation
238 let stg_binds = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
242 (stg_binds2, cost_centre_info) <- stg2stg stg_cmds this_mod st_uniqs stg_binds
243 let final_ids = collectFinalStgBinders (map fst stg_binds2)
245 return (stg_binds2, cost_centre_info, final_ids)
249 -------------------------- Reader ----------------
250 show_pass "Parser" >>
253 let src_filename -- name of the preprocessed source file
254 = case ms_ppsource summary of
255 Just (filename, fingerprint) -> filename
256 Nothing -> pprPanic "hscMain:summary is not of a source module"
259 buf <- hGetStringBuffer True{-expand tabs-} src_filename
261 let glaexts | dopt Opt_GlasgowExts dflags = 1#
264 case parse buf PState{ bol = 0#, atbol = 1#,
265 context = [], glasgow_exts = glaexts,
266 loc = mkSrcLoc src_filename 1 } of {
268 PFailed err -> return (HscErrs pcs (unitBag err) emptyBag)
270 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) ->
272 dumpIfSet (dopt_D_dump_parsed flags) "Parser" (ppr rdr_module) >>
274 dumpIfSet (dopt_D_source_stats flags) "Source Statistics"
275 (ppSourceStats False rdr_module) >>
277 -- UniqueSupplies for later use (these are the only lower case uniques)
278 mkSplitUniqSupply 'd' >>= \ ds_uniqs -> -- desugarer
279 mkSplitUniqSupply 'r' >>= \ ru_uniqs -> -- rules
280 mkSplitUniqSupply 'c' >>= \ c2s_uniqs -> -- core-to-stg
281 mkSplitUniqSupply 'g' >>= \ st_uniqs -> -- stg-to-stg passes
282 mkSplitUniqSupply 'n' >>= \ ncg_uniqs -> -- native-code generator
284 -------------------------- Rename ----------------
285 show_pass "Renamer" >>
288 renameModule dflags finder pcs hst rdr_module
289 >>= \ (pcs_rn, maybe_rn_stuff) ->
290 case maybe_rn_stuff of {
291 Nothing -> -- Hurrah! Renamer reckons that there's no need to
293 reportCompile mod_name "Compilation NOT required!" >>
296 Just (this_mod, rn_mod,
297 old_iface, new_iface,
298 rn_name_supply, fixity_env,
300 -- Oh well, we've got to recompile for real
303 -------------------------- Typechecking ----------------
304 show_pass "TypeCheck" >>
306 typecheckModule dflags mod pcs hst hit pit rn_mod
307 -- tc_uniqs rn_name_supply
309 >>= \ maybe_tc_stuff ->
310 case maybe_tc_stuff of {
311 Nothing -> ghcExit 1; -- Type checker failed
313 Just (tc_results@(TcResults {tc_tycons = local_tycons,
314 tc_classes = local_classes,
315 tc_insts = inst_info })) ->
318 -------------------------- Desugaring ----------------
320 deSugar this_mod ds_uniqs tc_results >>= \ (desugared, rules, h_code, c_code, fe_binders) ->
323 -------------------------- Main Core-language transformations ----------------
325 core2core core_cmds desugared rules >>= \ (simplified, orphan_rules) ->
327 -- Do the final tidy-up
329 simplified orphan_rules >>= \ (tidy_binds, tidy_orphan_rules) ->
331 -- Run the occurrence analyser one last time, so that
332 -- dead binders get dead-binder info. This is exploited by
333 -- code generators to avoid spitting out redundant bindings.
334 -- The occurrence-zapping in Simplify.simplCaseBinder means
335 -- that the Simplifier nukes useful dead-var stuff especially
337 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds in
339 coreBindsSize occ_anal_tidy_binds `seq`
340 -- TEMP: the above call zaps some space usage allocated by the
341 -- simplifier, which for reasons I don't understand, persists
342 -- thoroughout code generation
346 -------------------------- Convert to STG code -------------------------------
347 show_pass "Core2Stg" >>
350 stg_binds = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
353 -------------------------- Simplify STG code -------------------------------
354 show_pass "Stg2Stg" >>
356 stg2stg stg_cmds this_mod st_uniqs stg_binds >>= \ (stg_binds2, cost_centre_info) ->
359 runStgI local_tycons local_classes
360 (map fst stg_binds2) >>= \ i_result ->
361 putStr ("\nANSWER = " ++ show i_result ++ "\n\n")
365 -------------------------- Interface file -------------------------------
366 -- Dump instance decls and type signatures into the interface file
369 final_ids = collectFinalStgBinders (map fst stg_binds2)
371 writeIface this_mod old_iface new_iface
372 local_tycons local_classes inst_info
373 final_ids occ_anal_tidy_binds tidy_orphan_rules >>
376 -------------------------- Code generation -------------------------------
377 show_pass "CodeGen" >>
379 codeGen this_mod imported_modules
382 local_tycons local_classes
383 stg_binds2 >>= \ abstractC ->
386 -------------------------- Code output -------------------------------
387 show_pass "CodeOutput" >>
389 codeOutput this_mod local_tycons local_classes
390 occ_anal_tidy_binds stg_binds2
391 c_code h_code abstractC
395 -------------------------- Final report -------------------------------
396 reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
404 -------------------------------------------------------------
405 -- ****** help functions:
408 = if opt_D_show_passes
409 then \ what -> hPutStr stderr ("*** "++what++":\n")
410 else \ what -> return ()
416 %************************************************************************
418 \subsection{Initial persistent state}
420 %************************************************************************
423 initPersistentCompilerState :: IO PersistentCompilerState
424 initPersistentCompilerState
426 = do prs <- initPersistentRenamerState
428 PCS { pcs_PST = initPackageDetails,
429 pcs_insts = emptyInstEnv,
430 pcs_rules = emptyRuleEnv,
431 pcs_PRS = initPersistentRenamerState
435 = PCS { pcs_PST = initPackageDetails,
436 pcs_insts = emptyInstEnv,
437 pcs_rules = initRules,
438 pcs_PRS = initPersistentRenamerState }
441 initPackageDetails :: PackageSymbolTable
442 initPackageDetails = extendTypeEnv emptyModuleEnv wiredInThings
444 initPersistentRenamerState :: IO PersistentRenamerState
445 = do ns <- mkSplitUniqSupply 'r'
447 PRS { prsOrig = Orig { origNames = initOrigNames,
448 origIParam = emptyFM },
449 prsDecls = emptyNameEnv,
456 initOrigNames :: FiniteMap (ModuleName,OccName) Name
457 initOrigNames = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
459 grab names = foldl add emptyFM names
460 add env name = addToFM env (moduleName (nameModule name), nameOccName name) name
464 initRules = foldl add emptyVarEnv builtinRules
466 add env (name,rule) = extendNameEnv_C add1 env name [rule]
467 add1 rules _ = rule : rules
473 writeIface this_mod old_iface new_iface
474 local_tycons local_classes inst_info
475 final_ids tidy_binds tidy_orphan_rules
477 if isNothing opt_HiDir && isNothing opt_HiFile
478 then return () -- not producing any .hi file
482 hi_suf = case opt_HiSuf of { Nothing -> "hi"; Just suf -> suf }
483 filename = case opt_HiFile of {
487 Just dir -> dir ++ '/':moduleUserString this_mod
489 Nothing -> panic "writeIface"
493 do maybe_final_iface <- checkIface old_iface full_new_iface
494 case maybe_final_iface of {
495 Nothing -> when opt_D_dump_rn_trace $
496 putStrLn "Interface file unchanged" ; -- No need to update .hi file
500 do let mod_vers_unchanged = case old_iface of
501 Just iface -> pi_vers iface == pi_vers final_iface
503 when (mod_vers_unchanged && opt_D_dump_rn_trace) $
504 putStrLn "Module version unchanged, but usages differ; hence need new hi file"
506 if_hdl <- openFile filename WriteMode
507 printForIface if_hdl (pprIface final_iface)
511 full_new_iface = completeIface new_iface local_tycons local_classes
512 inst_info final_ids tidy_binds
517 %************************************************************************
519 \subsection{Printing the interface}
521 %************************************************************************
524 pprIface (ParsedIface { pi_mod = mod, pi_vers = mod_vers, pi_orphan = orphan,
525 pi_usages = usages, pi_exports = exports,
526 pi_fixity = (fix_vers, fixities),
527 pi_insts = insts, pi_decls = decls,
528 pi_rules = (rule_vers, rules), pi_deprecs = deprecs })
529 = vcat [ ptext SLIT("__interface")
530 <+> doubleQuotes (ptext opt_InPackage)
531 <+> ppr mod <+> ppr mod_vers <+> pp_sub_vers
532 <+> (if orphan then char '!' else empty)
533 <+> int opt_HiVersion
534 <+> ptext SLIT("where")
535 , vcat (map pprExport exports)
536 , vcat (map pprUsage usages)
537 , pprFixities fixities
538 , vcat [ppr i <+> semi | i <- insts]
539 , vcat [ppr_vers v <+> ppr d <> semi | (v,d) <- decls]
544 ppr_vers v | v == initialVersion = empty
547 | fix_vers == initialVersion && rule_vers == initialVersion = empty
548 | otherwise = brackets (ppr fix_vers <+> ppr rule_vers)
551 When printing export lists, we print like this:
553 AvailTC C [C, x, y] C(x,y)
554 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
557 pprExport :: ExportItem -> SDoc
558 pprExport (mod, items)
559 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map upp_avail items) ] <> semi
561 upp_avail :: RdrAvailInfo -> SDoc
562 upp_avail (Avail name) = pprOccName name
563 upp_avail (AvailTC name []) = empty
564 upp_avail (AvailTC name ns) = hcat [pprOccName name, bang, upp_export ns']
566 bang | name `elem` ns = empty
567 | otherwise = char '|'
568 ns' = filter (/= name) ns
570 upp_export [] = empty
571 upp_export names = braces (hsep (map pprOccName names))
576 pprUsage :: ImportVersion OccName -> SDoc
577 pprUsage (m, has_orphans, is_boot, whats_imported)
578 = hsep [ptext SLIT("import"), pprModuleName m,
580 upp_import_versions whats_imported
583 pp_orphan | has_orphans = char '!'
585 pp_boot | is_boot = char '@'
588 -- Importing the whole module is indicated by an empty list
589 upp_import_versions NothingAtAll = empty
590 upp_import_versions (Everything v) = dcolon <+> int v
591 upp_import_versions (Specifically vm vf vr nvs)
592 = dcolon <+> int vm <+> int vf <+> int vr <+> hsep [ ppr n <+> int v | (n,v) <- nvs ]
597 pprFixities [] = empty
598 pprFixities fixes = hsep (map ppr fixes) <> semi
601 pprRules rules = hsep [ptext SLIT("{-## __R"), hsep (map ppr rules), ptext SLIT("##-}")]
603 pprDeprecs [] = empty
604 pprDeprecs deps = hsep [ ptext SLIT("{-## __D"), guts, ptext SLIT("##-}")]
606 guts = hsep [ ppr ie <+> doubleQuotes (ppr txt) <> semi
607 | Deprecation ie txt _ <- deps ]