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 MkIface ( writeIface )
24 import TcModule ( TcResults(..), typecheckModule )
25 import Desugar ( deSugar )
26 import SimplCore ( core2core )
27 import OccurAnal ( occurAnalyseBinds )
28 import CoreUtils ( coreBindsSize )
29 import CoreTidy ( tidyCorePgm )
30 import CoreToStg ( topCoreBindsToStg )
31 import StgSyn ( collectFinalStgBinders )
32 import SimplStg ( stg2stg )
33 import CodeGen ( codeGen )
34 import CodeOutput ( codeOutput )
36 import Module ( ModuleName, moduleNameUserString )
38 import ErrUtils ( ghcExit, doIfSet, dumpIfSet )
39 import UniqSupply ( mkSplitUniqSupply )
42 import Char ( isSpace )
43 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
46 import IOExts ( unsafePerformIO )
47 import NativeInfo ( os, arch )
49 import StgInterp ( runStgI )
53 %************************************************************************
55 \subsection{The main compiler pipeline}
57 %************************************************************************
62 -> ModSummary -- summary, including source filename
63 -> Maybe ModIFace -- old interface, if available
64 -> String -- file in which to put the output (.s, .hc, .java etc.)
65 -> HomeSymbolTable -- for home module ModDetails
66 -> PersistentCompilerState -- IN: persistent compiler state
69 hscMain flags core_cmds stg_cmds summary maybe_old_iface
70 output_filename mod_details pcs1 =
72 -------------------------- Reader ----------------
76 let src_filename -- name of the preprocessed source file
77 = case ms_ppsource summary of
78 Just (filename, fingerprint) -> filename
79 Nothing -> pprPanic "hscMain:summary is not of a source module"
82 buf <- hGetStringBuffer True{-expand tabs-} src_filename
84 let glaexts | opt_GlasgowExts = 1#
87 case parse buf PState{ bol = 0#, atbol = 1#,
88 context = [], glasgow_exts = glaexts,
89 loc = mkSrcLoc src_filename 1 } of {
91 PFailed err -> return (CompErrs pcs err)
93 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) ->
95 dumpIfSet (dopt_D_dump_parsed flags) "Parser" (ppr rdr_module) >>
97 dumpIfSet (dopt_D_source_stats flags) "Source Statistics"
98 (ppSourceStats False rdr_module) >>
100 -- UniqueSupplies for later use (these are the only lower case uniques)
101 mkSplitUniqSupply 'd' >>= \ ds_uniqs -> -- desugarer
102 mkSplitUniqSupply 'r' >>= \ ru_uniqs -> -- rules
103 mkSplitUniqSupply 'c' >>= \ c2s_uniqs -> -- core-to-stg
104 mkSplitUniqSupply 'u' >>= \ tidy_uniqs -> -- tidy up
105 mkSplitUniqSupply 'g' >>= \ st_uniqs -> -- stg-to-stg passes
106 mkSplitUniqSupply 'n' >>= \ ncg_uniqs -> -- native-code generator
108 -------------------------- Rename ----------------
109 show_pass "Renamer" >>
112 renameModule rn_uniqs rdr_module >>= \ maybe_rn_stuff ->
113 case maybe_rn_stuff of {
114 Nothing -> -- Hurrah! Renamer reckons that there's no need to
116 reportCompile mod_name "Compilation NOT required!" >>
119 Just (this_mod, rn_mod,
120 old_iface, new_iface,
121 rn_name_supply, fixity_env,
123 -- Oh well, we've got to recompile for real
126 -------------------------- Typechecking ----------------
127 show_pass "TypeCheck" >>
129 typecheckModule tc_uniqs rn_name_supply
130 fixity_env rn_mod >>= \ maybe_tc_stuff ->
131 case maybe_tc_stuff of {
132 Nothing -> ghcExit 1; -- Type checker failed
134 Just (tc_results@(TcResults {tc_tycons = local_tycons,
135 tc_classes = local_classes,
136 tc_insts = inst_info })) ->
139 -------------------------- Desugaring ----------------
141 deSugar this_mod ds_uniqs tc_results >>= \ (desugared, rules, h_code, c_code, fe_binders) ->
144 -------------------------- Main Core-language transformations ----------------
146 core2core core_cmds desugared rules >>= \ (simplified, orphan_rules) ->
148 -- Do the final tidy-up
149 tidyCorePgm tidy_uniqs this_mod
150 simplified orphan_rules >>= \ (tidy_binds, tidy_orphan_rules) ->
152 -- Run the occurrence analyser one last time, so that
153 -- dead binders get dead-binder info. This is exploited by
154 -- code generators to avoid spitting out redundant bindings.
155 -- The occurrence-zapping in Simplify.simplCaseBinder means
156 -- that the Simplifier nukes useful dead-var stuff especially
158 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds in
160 coreBindsSize occ_anal_tidy_binds `seq`
161 -- TEMP: the above call zaps some space usage allocated by the
162 -- simplifier, which for reasons I don't understand, persists
163 -- thoroughout code generation
167 -------------------------- Convert to STG code -------------------------------
168 show_pass "Core2Stg" >>
171 stg_binds = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
174 -------------------------- Simplify STG code -------------------------------
175 show_pass "Stg2Stg" >>
177 stg2stg stg_cmds this_mod st_uniqs stg_binds >>= \ (stg_binds2, cost_centre_info) ->
180 runStgI local_tycons local_classes
181 (map fst stg_binds2) >>= \ i_result ->
182 putStr ("\nANSWER = " ++ show i_result ++ "\n\n")
186 -------------------------- Interface file -------------------------------
187 -- Dump instance decls and type signatures into the interface file
190 final_ids = collectFinalStgBinders (map fst stg_binds2)
192 writeIface this_mod old_iface new_iface
193 local_tycons local_classes inst_info
194 final_ids occ_anal_tidy_binds tidy_orphan_rules >>
197 -------------------------- Code generation -------------------------------
198 show_pass "CodeGen" >>
200 codeGen this_mod imported_modules
203 local_tycons local_classes
204 stg_binds2 >>= \ abstractC ->
207 -------------------------- Code output -------------------------------
208 show_pass "CodeOutput" >>
210 codeOutput this_mod local_tycons local_classes
211 occ_anal_tidy_binds stg_binds2
212 c_code h_code abstractC
216 -------------------------- Final report -------------------------------
217 reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
225 -------------------------------------------------------------
226 -- ****** help functions:
229 = if opt_D_show_passes
230 then \ what -> hPutStr stderr ("*** "++what++":\n")
231 else \ what -> return ()
235 %************************************************************************
237 \subsection{Initial persistent state}
239 %************************************************************************
242 initPersistentCompilerState :: PersistentCompilerState
243 initPersistentCompilerState
244 = PCS { pcs_PST = initPackageDetails,
245 pcs_insts = emptyInstEnv,
246 pcs_rules = emptyRuleEnv,
247 pcs_PRS = initPersistentRenamerState }
249 initPackageDetails :: PackageSymbolTable
250 initPackageDetails = extendTypeEnv emptyModuleEnv wiredInThings
252 initPersistentRenamerState :: PersistentRenamerState
253 = PRS { prsOrig = Orig { origNames = initOrigNames,
254 origIParam = emptyFM },
255 prsDecls = emptyNameEnv,
260 initOrigNames :: FiniteMap (ModuleName,OccName) Name
261 initOrigNames = grab knownKeyNames `plusFM` grab wiredInNames
263 grab names = foldl add emptyFM names
264 add env name = addToFM env (moduleName (nameModule name), nameOccName name) name
267 %************************************************************************
269 \subsection{Statistics}
271 %************************************************************************
274 ppSourceStats short (HsModule name version exports imports decls _ src_loc)
275 = (if short then hcat else vcat)
277 [("ExportAll ", export_all), -- 1 if no export list
278 ("ExportDecls ", export_ds),
279 ("ExportModules ", export_ms),
280 ("Imports ", import_no),
281 (" ImpQual ", import_qual),
282 (" ImpAs ", import_as),
283 (" ImpAll ", import_all),
284 (" ImpPartial ", import_partial),
285 (" ImpHiding ", import_hiding),
286 ("FixityDecls ", fixity_ds),
287 ("DefaultDecls ", default_ds),
288 ("TypeDecls ", type_ds),
289 ("DataDecls ", data_ds),
290 ("NewTypeDecls ", newt_ds),
291 ("DataConstrs ", data_constrs),
292 ("DataDerivings ", data_derivs),
293 ("ClassDecls ", class_ds),
294 ("ClassMethods ", class_method_ds),
295 ("DefaultMethods ", default_method_ds),
296 ("InstDecls ", inst_ds),
297 ("InstMethods ", inst_method_ds),
298 ("TypeSigs ", bind_tys),
299 ("ValBinds ", val_bind_ds),
300 ("FunBinds ", fn_bind_ds),
301 ("InlineMeths ", method_inlines),
302 ("InlineBinds ", bind_inlines),
303 -- ("SpecialisedData ", data_specs),
304 -- ("SpecialisedInsts ", inst_specs),
305 ("SpecialisedMeths ", method_specs),
306 ("SpecialisedBinds ", bind_specs)
309 pp_val (str, 0) = empty
311 | not short = hcat [text str, int n]
312 | otherwise = hcat [text (trim str), equals, int n, semi]
314 trim ls = takeWhile (not.isSpace) (dropWhile isSpace ls)
316 fixity_ds = length [() | FixD d <- decls]
317 -- NB: this omits fixity decls on local bindings and
318 -- in class decls. ToDo
320 tycl_decls = [d | TyClD d <- decls]
321 (class_ds, data_ds, newt_ds, type_ds) = countTyClDecls tycl_decls
323 inst_decls = [d | InstD d <- decls]
324 inst_ds = length inst_decls
325 default_ds = length [() | DefD _ <- decls]
326 val_decls = [d | ValD d <- decls]
328 real_exports = case exports of { Nothing -> []; Just es -> es }
329 n_exports = length real_exports
330 export_ms = length [() | IEModuleContents _ <- real_exports]
331 export_ds = n_exports - export_ms
332 export_all = case exports of { Nothing -> 1; other -> 0 }
334 (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
335 = count_binds (foldr ThenBinds EmptyBinds val_decls)
337 (import_no, import_qual, import_as, import_all, import_partial, import_hiding)
338 = foldr add6 (0,0,0,0,0,0) (map import_info imports)
339 (data_constrs, data_derivs)
340 = foldr add2 (0,0) (map data_info tycl_decls)
341 (class_method_ds, default_method_ds)
342 = foldr add2 (0,0) (map class_info tycl_decls)
343 (inst_method_ds, method_specs, method_inlines)
344 = foldr add3 (0,0,0) (map inst_info inst_decls)
347 count_binds EmptyBinds = (0,0,0,0,0)
348 count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
349 count_binds (MonoBind b sigs _) = case (count_monobinds b, count_sigs sigs) of
350 ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
352 count_monobinds EmptyMonoBinds = (0,0)
353 count_monobinds (AndMonoBinds b1 b2) = count_monobinds b1 `add2` count_monobinds b2
354 count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
355 count_monobinds (PatMonoBind p r _) = (0,1)
356 count_monobinds (FunMonoBind f _ m _) = (0,1)
358 count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
360 sig_info (Sig _ _ _) = (1,0,0,0)
361 sig_info (ClassOpSig _ _ _ _) = (0,1,0,0)
362 sig_info (SpecSig _ _ _) = (0,0,1,0)
363 sig_info (InlineSig _ _ _) = (0,0,0,1)
364 sig_info (NoInlineSig _ _ _) = (0,0,0,1)
365 sig_info _ = (0,0,0,0)
367 import_info (ImportDecl _ _ qual as spec _)
368 = add6 (1, qual_info qual, as_info as, 0,0,0) (spec_info spec)
373 spec_info Nothing = (0,0,0,1,0,0)
374 spec_info (Just (False, _)) = (0,0,0,0,1,0)
375 spec_info (Just (True, _)) = (0,0,0,0,0,1)
377 data_info (TyData _ _ _ _ _ nconstrs derivs _ _ _ _)
378 = (nconstrs, case derivs of {Nothing -> 0; Just ds -> length ds})
379 data_info other = (0,0)
381 class_info (ClassDecl _ _ _ _ meth_sigs def_meths _ _ _ )
382 = case count_sigs meth_sigs of
384 (classops, addpr (count_monobinds def_meths))
385 class_info other = (0,0)
387 inst_info (InstDecl _ inst_meths inst_sigs _ _)
388 = case count_sigs inst_sigs of
390 (addpr (count_monobinds inst_meths), ss, is)
392 addpr :: (Int,Int) -> Int
393 add1 :: Int -> Int -> Int
394 add2 :: (Int,Int) -> (Int,Int) -> (Int, Int)
395 add3 :: (Int,Int,Int) -> (Int,Int,Int) -> (Int, Int, Int)
396 add4 :: (Int,Int,Int,Int) -> (Int,Int,Int,Int) -> (Int, Int, Int, Int)
397 add5 :: (Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int)
398 add6 :: (Int,Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int, Int)
402 add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
403 add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
404 add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
405 add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
406 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)
413 reportCompile :: ModuleName -> String -> IO ()
414 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
415 reportCompile mod_name info
416 | not opt_ReportCompile = return ()
420 sendTo sock (moduleNameUserString mod_name ++ ';': compiler_version ++
421 ';': os ++ ';':arch ++ '\n':' ':info ++ "\n") addr
422 return ()) `catch` (\ _ -> return ())
424 motherShip :: IO SockAddr
426 he <- getHostByName "laysan.dcs.gla.ac.uk"
427 case (hostAddresses he) of
428 [] -> IOERROR (userError "No address!")
429 (x:_) -> return (SockAddrInet motherShipPort x)
432 motherShipPort :: PortNumber
433 motherShipPort = mkPortNumber 12345
435 -- creates a socket capable of sending datagrams,
436 -- binding it to a port
437 -- ( 0 => have the system pick next available port no.)
438 udpSocket :: Int -> IO Socket
440 pr <- getProtocolNumber "udp"
441 s <- socket AF_INET Datagram pr
442 bindSocket s (SockAddrInet (mkPortNumber p) iNADDR_ANY)
445 reportCompile _ _ = return ()