2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
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 MkIface ( writeIface )
25 import TcModule ( TcResults(..), typecheckModule )
26 import Desugar ( deSugar )
27 import SimplCore ( core2core )
28 import OccurAnal ( occurAnalyseBinds )
29 import CoreUtils ( coreBindsSize )
30 import CoreTidy ( tidyCorePgm )
31 import CoreToStg ( topCoreBindsToStg )
32 import StgSyn ( collectFinalStgBinders )
33 import SimplStg ( stg2stg )
34 import CodeGen ( codeGen )
35 import CodeOutput ( codeOutput )
37 import Module ( ModuleName, moduleNameUserString )
39 import ErrUtils ( ghcExit, doIfSet, dumpIfSet )
40 import UniqSupply ( mkSplitUniqSupply )
43 import Char ( isSpace )
44 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
47 import IOExts ( unsafePerformIO )
48 import NativeInfo ( os, arch )
50 import StgInterp ( runStgI )
54 %************************************************************************
56 \subsection{The main compiler pipeline}
58 %************************************************************************
62 = HscOK ModDetails -- new details (HomeSymbolTable additions)
63 (Maybe ModIface) -- new iface (if any compilation was done)
64 (Maybe String) -- generated stub_h filename (in /tmp)
65 (Maybe String) -- generated stub_c filename (in /tmp)
66 (Maybe [UnlinkedIBind]) -- interpreted code, if any
67 PersistentCompilerState -- updated PCS
68 (Bag WarnMsg) -- warnings
70 | HscErrs PersistentCompilerState -- updated PCS
71 (Bag ErrMsg) -- errors
72 (Bag WarnMsg) -- warnings
76 -> ModSummary -- summary, including source filename
77 -> Maybe ModIFace -- old interface, if available
78 -> String -- file in which to put the output (.s, .hc, .java etc.)
79 -> HomeSymbolTable -- for home module ModDetails
80 -> PersistentCompilerState -- IN: persistent compiler state
83 hscMain flags core_cmds stg_cmds summary maybe_old_iface
84 output_filename mod_details pcs1 =
86 -------------------------- Reader ----------------
90 let src_filename -- name of the preprocessed source file
91 = case ms_ppsource summary of
92 Just (filename, fingerprint) -> filename
93 Nothing -> pprPanic "hscMain:summary is not of a source module"
96 buf <- hGetStringBuffer True{-expand tabs-} src_filename
98 let glaexts | opt_GlasgowExts = 1#
101 case parse buf PState{ bol = 0#, atbol = 1#,
102 context = [], glasgow_exts = glaexts,
103 loc = mkSrcLoc src_filename 1 } of {
105 PFailed err -> return (CompErrs pcs err)
107 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) ->
109 dumpIfSet (dopt_D_dump_parsed flags) "Parser" (ppr rdr_module) >>
111 dumpIfSet (dopt_D_source_stats flags) "Source Statistics"
112 (ppSourceStats False rdr_module) >>
114 -- UniqueSupplies for later use (these are the only lower case uniques)
115 mkSplitUniqSupply 'd' >>= \ ds_uniqs -> -- desugarer
116 mkSplitUniqSupply 'r' >>= \ ru_uniqs -> -- rules
117 mkSplitUniqSupply 'c' >>= \ c2s_uniqs -> -- core-to-stg
118 mkSplitUniqSupply 'u' >>= \ tidy_uniqs -> -- tidy up
119 mkSplitUniqSupply 'g' >>= \ st_uniqs -> -- stg-to-stg passes
120 mkSplitUniqSupply 'n' >>= \ ncg_uniqs -> -- native-code generator
122 -------------------------- Rename ----------------
123 show_pass "Renamer" >>
126 renameModule rn_uniqs rdr_module >>= \ maybe_rn_stuff ->
127 case maybe_rn_stuff of {
128 Nothing -> -- Hurrah! Renamer reckons that there's no need to
130 reportCompile mod_name "Compilation NOT required!" >>
133 Just (this_mod, rn_mod,
134 old_iface, new_iface,
135 rn_name_supply, fixity_env,
137 -- Oh well, we've got to recompile for real
140 -------------------------- Typechecking ----------------
141 show_pass "TypeCheck" >>
143 typecheckModule tc_uniqs rn_name_supply
144 fixity_env rn_mod >>= \ maybe_tc_stuff ->
145 case maybe_tc_stuff of {
146 Nothing -> ghcExit 1; -- Type checker failed
148 Just (tc_results@(TcResults {tc_tycons = local_tycons,
149 tc_classes = local_classes,
150 tc_insts = inst_info })) ->
153 -------------------------- Desugaring ----------------
155 deSugar this_mod ds_uniqs tc_results >>= \ (desugared, rules, h_code, c_code, fe_binders) ->
158 -------------------------- Main Core-language transformations ----------------
160 core2core core_cmds desugared rules >>= \ (simplified, orphan_rules) ->
162 -- Do the final tidy-up
163 tidyCorePgm tidy_uniqs this_mod
164 simplified orphan_rules >>= \ (tidy_binds, tidy_orphan_rules) ->
166 -- Run the occurrence analyser one last time, so that
167 -- dead binders get dead-binder info. This is exploited by
168 -- code generators to avoid spitting out redundant bindings.
169 -- The occurrence-zapping in Simplify.simplCaseBinder means
170 -- that the Simplifier nukes useful dead-var stuff especially
172 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds in
174 coreBindsSize occ_anal_tidy_binds `seq`
175 -- TEMP: the above call zaps some space usage allocated by the
176 -- simplifier, which for reasons I don't understand, persists
177 -- thoroughout code generation
181 -------------------------- Convert to STG code -------------------------------
182 show_pass "Core2Stg" >>
185 stg_binds = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
188 -------------------------- Simplify STG code -------------------------------
189 show_pass "Stg2Stg" >>
191 stg2stg stg_cmds this_mod st_uniqs stg_binds >>= \ (stg_binds2, cost_centre_info) ->
194 runStgI local_tycons local_classes
195 (map fst stg_binds2) >>= \ i_result ->
196 putStr ("\nANSWER = " ++ show i_result ++ "\n\n")
200 -------------------------- Interface file -------------------------------
201 -- Dump instance decls and type signatures into the interface file
204 final_ids = collectFinalStgBinders (map fst stg_binds2)
206 writeIface this_mod old_iface new_iface
207 local_tycons local_classes inst_info
208 final_ids occ_anal_tidy_binds tidy_orphan_rules >>
211 -------------------------- Code generation -------------------------------
212 show_pass "CodeGen" >>
214 codeGen this_mod imported_modules
217 local_tycons local_classes
218 stg_binds2 >>= \ abstractC ->
221 -------------------------- Code output -------------------------------
222 show_pass "CodeOutput" >>
224 codeOutput this_mod local_tycons local_classes
225 occ_anal_tidy_binds stg_binds2
226 c_code h_code abstractC
230 -------------------------- Final report -------------------------------
231 reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
239 -------------------------------------------------------------
240 -- ****** help functions:
243 = if opt_D_show_passes
244 then \ what -> hPutStr stderr ("*** "++what++":\n")
245 else \ what -> return ()
249 %************************************************************************
251 \subsection{Initial persistent state}
253 %************************************************************************
256 initPersistentCompilerState :: PersistentCompilerState
257 initPersistentCompilerState
258 = PCS { pcs_PST = initPackageDetails,
259 pcs_insts = emptyInstEnv,
260 pcs_rules = emptyRuleEnv,
261 pcs_PRS = initPersistentRenamerState }
263 initPackageDetails :: PackageSymbolTable
264 initPackageDetails = extendTypeEnv emptyModuleEnv wiredInThings
266 initPersistentRenamerState :: PersistentRenamerState
267 = PRS { prsOrig = Orig { origNames = initOrigNames,
268 origIParam = emptyFM },
269 prsDecls = emptyNameEnv,
274 initOrigNames :: FiniteMap (ModuleName,OccName) Name
275 initOrigNames = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
277 grab names = foldl add emptyFM names
278 add env name = addToFM env (moduleName (nameModule name), nameOccName name) name
281 %************************************************************************
283 \subsection{Statistics}
285 %************************************************************************
288 ppSourceStats short (HsModule name version exports imports decls _ src_loc)
289 = (if short then hcat else vcat)
291 [("ExportAll ", export_all), -- 1 if no export list
292 ("ExportDecls ", export_ds),
293 ("ExportModules ", export_ms),
294 ("Imports ", import_no),
295 (" ImpQual ", import_qual),
296 (" ImpAs ", import_as),
297 (" ImpAll ", import_all),
298 (" ImpPartial ", import_partial),
299 (" ImpHiding ", import_hiding),
300 ("FixityDecls ", fixity_ds),
301 ("DefaultDecls ", default_ds),
302 ("TypeDecls ", type_ds),
303 ("DataDecls ", data_ds),
304 ("NewTypeDecls ", newt_ds),
305 ("DataConstrs ", data_constrs),
306 ("DataDerivings ", data_derivs),
307 ("ClassDecls ", class_ds),
308 ("ClassMethods ", class_method_ds),
309 ("DefaultMethods ", default_method_ds),
310 ("InstDecls ", inst_ds),
311 ("InstMethods ", inst_method_ds),
312 ("TypeSigs ", bind_tys),
313 ("ValBinds ", val_bind_ds),
314 ("FunBinds ", fn_bind_ds),
315 ("InlineMeths ", method_inlines),
316 ("InlineBinds ", bind_inlines),
317 -- ("SpecialisedData ", data_specs),
318 -- ("SpecialisedInsts ", inst_specs),
319 ("SpecialisedMeths ", method_specs),
320 ("SpecialisedBinds ", bind_specs)
323 pp_val (str, 0) = empty
325 | not short = hcat [text str, int n]
326 | otherwise = hcat [text (trim str), equals, int n, semi]
328 trim ls = takeWhile (not.isSpace) (dropWhile isSpace ls)
330 fixity_ds = length [() | FixD d <- decls]
331 -- NB: this omits fixity decls on local bindings and
332 -- in class decls. ToDo
334 tycl_decls = [d | TyClD d <- decls]
335 (class_ds, data_ds, newt_ds, type_ds) = countTyClDecls tycl_decls
337 inst_decls = [d | InstD d <- decls]
338 inst_ds = length inst_decls
339 default_ds = length [() | DefD _ <- decls]
340 val_decls = [d | ValD d <- decls]
342 real_exports = case exports of { Nothing -> []; Just es -> es }
343 n_exports = length real_exports
344 export_ms = length [() | IEModuleContents _ <- real_exports]
345 export_ds = n_exports - export_ms
346 export_all = case exports of { Nothing -> 1; other -> 0 }
348 (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
349 = count_binds (foldr ThenBinds EmptyBinds val_decls)
351 (import_no, import_qual, import_as, import_all, import_partial, import_hiding)
352 = foldr add6 (0,0,0,0,0,0) (map import_info imports)
353 (data_constrs, data_derivs)
354 = foldr add2 (0,0) (map data_info tycl_decls)
355 (class_method_ds, default_method_ds)
356 = foldr add2 (0,0) (map class_info tycl_decls)
357 (inst_method_ds, method_specs, method_inlines)
358 = foldr add3 (0,0,0) (map inst_info inst_decls)
361 count_binds EmptyBinds = (0,0,0,0,0)
362 count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
363 count_binds (MonoBind b sigs _) = case (count_monobinds b, count_sigs sigs) of
364 ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
366 count_monobinds EmptyMonoBinds = (0,0)
367 count_monobinds (AndMonoBinds b1 b2) = count_monobinds b1 `add2` count_monobinds b2
368 count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
369 count_monobinds (PatMonoBind p r _) = (0,1)
370 count_monobinds (FunMonoBind f _ m _) = (0,1)
372 count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
374 sig_info (Sig _ _ _) = (1,0,0,0)
375 sig_info (ClassOpSig _ _ _ _) = (0,1,0,0)
376 sig_info (SpecSig _ _ _) = (0,0,1,0)
377 sig_info (InlineSig _ _ _) = (0,0,0,1)
378 sig_info (NoInlineSig _ _ _) = (0,0,0,1)
379 sig_info _ = (0,0,0,0)
381 import_info (ImportDecl _ _ qual as spec _)
382 = add6 (1, qual_info qual, as_info as, 0,0,0) (spec_info spec)
387 spec_info Nothing = (0,0,0,1,0,0)
388 spec_info (Just (False, _)) = (0,0,0,0,1,0)
389 spec_info (Just (True, _)) = (0,0,0,0,0,1)
391 data_info (TyData _ _ _ _ _ nconstrs derivs _ _ _ _)
392 = (nconstrs, case derivs of {Nothing -> 0; Just ds -> length ds})
393 data_info other = (0,0)
395 class_info (ClassDecl _ _ _ _ meth_sigs def_meths _ _ _ )
396 = case count_sigs meth_sigs of
398 (classops, addpr (count_monobinds def_meths))
399 class_info other = (0,0)
401 inst_info (InstDecl _ inst_meths inst_sigs _ _)
402 = case count_sigs inst_sigs of
404 (addpr (count_monobinds inst_meths), ss, is)
406 addpr :: (Int,Int) -> Int
407 add1 :: Int -> Int -> Int
408 add2 :: (Int,Int) -> (Int,Int) -> (Int, Int)
409 add3 :: (Int,Int,Int) -> (Int,Int,Int) -> (Int, Int, Int)
410 add4 :: (Int,Int,Int,Int) -> (Int,Int,Int,Int) -> (Int, Int, Int, Int)
411 add5 :: (Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int)
412 add6 :: (Int,Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int, Int)
416 add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
417 add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
418 add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
419 add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
420 add6 (x1,x2,x3,x4,x5,x6) (y1,y2,y3,y4,y5,y6) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5,x6+y6)
427 reportCompile :: ModuleName -> String -> IO ()
428 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
429 reportCompile mod_name info
430 | not opt_ReportCompile = return ()
434 sendTo sock (moduleNameUserString mod_name ++ ';': compiler_version ++
435 ';': os ++ ';':arch ++ '\n':' ':info ++ "\n") addr
436 return ()) `catch` (\ _ -> return ())
438 motherShip :: IO SockAddr
440 he <- getHostByName "laysan.dcs.gla.ac.uk"
441 case (hostAddresses he) of
442 [] -> IOERROR (userError "No address!")
443 (x:_) -> return (SockAddrInet motherShipPort x)
446 motherShipPort :: PortNumber
447 motherShipPort = mkPortNumber 12345
449 -- creates a socket capable of sending datagrams,
450 -- binding it to a port
451 -- ( 0 => have the system pick next available port no.)
452 udpSocket :: Int -> IO Socket
454 pr <- getProtocolNumber "udp"
455 s <- socket AF_INET Datagram pr
456 bindSocket s (SockAddrInet (mkPortNumber p) iNADDR_ANY)
459 reportCompile _ _ = return ()