2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
7 module Main ( main ) where
9 #include "HsVersions.h"
11 import IO ( IOMode(..), hPutStr, hClose, openFile, stderr )
13 import BasicTypes ( NewOrData(..) )
15 import ReadPrefix ( rdModule )
16 import Rename ( renameModule )
18 import MkIface -- several functions
19 import TcModule ( typecheckModule )
20 import Desugar ( deSugar )
21 import SimplCore ( core2core )
22 import CoreToStg ( topCoreBindsToStg )
23 import StgSyn ( collectFinalStgBinders, pprStgBindingsWithSRTs )
24 import SimplStg ( stg2stg )
25 import CodeGen ( codeGen )
26 #if ! OMIT_NATIVE_CODEGEN
27 import AsmCodeGen ( dumpRealAsm, writeRealAsm )
30 import Module ( Module, moduleString )
31 import AbsCSyn ( absCNop )
32 import AbsCUtils ( flattenAbsC )
34 import ErrUtils ( ghcExit, doIfSet, dumpIfSet )
35 import Maybes ( maybeToBool, MaybeErr(..) )
36 import TyCon ( isDataTyCon )
37 import Class ( classTyCon )
38 import UniqSupply ( mkSplitUniqSupply )
40 import PprAbsC ( dumpRealC, writeRealC )
41 import FiniteMap ( emptyFM )
43 import Char ( isSpace )
44 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
47 import IOExts ( unsafePerformIO )
48 import NativeInfo ( os, arch )
60 doIt :: ([CoreToDo], [StgToDo]) -> IO ()
62 doIt (core_cmds, stg_cmds)
64 (hPutStr stderr "Glasgow Haskell Compiler, version " >>
65 hPutStr stderr compiler_version >>
66 hPutStr stderr ", for Haskell 98\n") >>
71 rdModule >>= \ (mod_name, rdr_module) ->
73 dumpIfSet opt_D_dump_rdr "Reader" (ppr rdr_module) >>
75 dumpIfSet opt_D_source_stats "Source Statistics"
76 (ppSourceStats False rdr_module) >>
78 -- UniqueSupplies for later use (these are the only lower case uniques)
80 mkSplitUniqSupply 'r' >>= \ rn_uniqs -> -- renamer
82 mkSplitUniqSupply 'a' >>= \ tc_uniqs -> -- typechecker
84 mkSplitUniqSupply 'd' >>= \ ds_uniqs -> -- desugarer
86 mkSplitUniqSupply 's' >>= \ sm_uniqs -> -- core-to-core simplifier
88 mkSplitUniqSupply 'c' >>= \ c2s_uniqs -> -- core-to-stg
90 mkSplitUniqSupply 'g' >>= \ st_uniqs -> -- stg-to-stg passes
92 mkSplitUniqSupply 'f' >>= \ fl_uniqs -> -- absC flattener
94 mkSplitUniqSupply 'n' >>= \ ncg_uniqs -> -- native-code generator
97 show_pass "Renamer" >>
100 renameModule rn_uniqs rdr_module >>=
102 case maybe_rn_stuff of {
103 Nothing -> -- Hurrah! Renamer reckons that there's no need to
105 reportCompile mod_name "Compilation NOT required!" >>
108 Just (rn_mod, iface_file_stuff, rn_name_supply, imported_modules) ->
109 -- Oh well, we've got to recompile for real
112 -- Safely past renaming: we can start the interface file:
113 -- (the iface file is produced incrementally, as we have
114 -- the information that we need...; we use "iface<blah>")
115 -- "endIface" finishes the job.
116 startIface mod_name >>= \ if_handle ->
117 ifaceMain if_handle iface_file_stuff >>
120 -- ******* TYPECHECKER
121 show_pass "TypeCheck" >>
123 typecheckModule tc_uniqs rn_name_supply iface_file_stuff rn_mod
124 >>= \ maybe_tc_stuff ->
125 case maybe_tc_stuff of {
126 Nothing -> ghcExit 1; -- Type checker failed
129 local_tycons, local_classes, inst_info,
135 show_pass "DeSugar" >>
137 deSugar ds_uniqs global_env mod_name all_binds fo_decls >>= \ (desugared, h_code, c_code) ->
140 -- ******* CORE-TO-CORE SIMPLIFICATION
141 show_pass "Core2Core" >>
144 local_data_tycons = filter isDataTyCon local_tycons
146 core2core core_cmds mod_name local_classes
152 -- ******* STG-TO-STG SIMPLIFICATION
153 show_pass "Core2Stg" >>
156 stg_binds = topCoreBindsToStg c2s_uniqs simplified
159 show_pass "Stg2Stg" >>
161 stg2stg stg_cmds mod_name st_uniqs stg_binds
163 \ (stg_binds2, cost_centre_info) ->
165 dumpIfSet opt_D_dump_stg "STG syntax:"
166 (pprStgBindingsWithSRTs stg_binds2) >>
168 -- Dump instance decls and type signatures into the interface file
170 final_ids = collectFinalStgBinders (map fst stg_binds2)
173 ifaceDecls if_handle local_tycons local_classes inst_info final_ids simplified >>
174 endIface if_handle >>
175 -- We are definitely done w/ interface-file stuff at this point:
176 -- (See comments near call to "startIface".)
178 -- ******* "ABSTRACT", THEN "FLAT", THEN *REAL* C!
179 show_pass "CodeGen" >>
182 all_local_data_tycons = filter isDataTyCon (map classTyCon local_classes)
184 -- Generate info tables for the data constrs arising
185 -- from class decls as well
187 all_tycon_specs = emptyFM -- Not specialising tycons any more
189 abstractC = codeGen mod_name -- module name for CC labelling
191 imported_modules -- import names for CC registering
192 all_local_data_tycons -- type constructors generated locally
193 all_tycon_specs -- tycon specialisations
196 flat_abstractC = flattenAbsC fl_uniqs abstractC
198 dumpIfSet opt_D_dump_absC "Abstract C" (dumpRealC abstractC) >>
200 show_pass "CodeOutput" >>
202 -- You can have C (c_output) or assembly-language (ncg_output),
203 -- but not both. [Allowing for both gives a space leak on
204 -- flat_abstractC. WDP 94/10]
206 (flat_absC_c, flat_absC_ncg) =
207 case (maybeToBool opt_ProduceC || opt_D_dump_realC,
208 maybeToBool opt_ProduceS || opt_D_dump_asm) of
209 (True, False) -> (flat_abstractC, absCNop)
210 (False, True) -> (absCNop, flat_abstractC)
211 (False, False) -> (absCNop, absCNop)
212 (True, True) -> error "ERROR: Can't do both .hc and .s at the same time"
214 -- C stubs for "foreign export"ed functions.
215 stub_c_output_d = pprCode CStyle c_code
216 stub_c_output_w = showSDoc stub_c_output_d
218 -- Header file protos for "foreign export"ed functions.
219 stub_h_output_d = pprCode CStyle h_code
220 stub_h_output_w = showSDoc stub_h_output_d
222 c_output_d = dumpRealC flat_absC_c
223 c_output_w = (\ f -> writeRealC f flat_absC_c)
225 #if OMIT_NATIVE_CODEGEN
226 ncg_output_d = error "*** GHC not built with a native-code generator ***"
227 ncg_output_w = ncg_output_d
229 ncg_output_d = dumpRealAsm flat_absC_ncg ncg_uniqs
230 ncg_output_w = (\ f -> writeRealAsm f flat_absC_ncg ncg_uniqs)
234 dumpIfSet opt_D_dump_asm "Asm code" ncg_output_d >>
235 doOutput opt_ProduceS ncg_output_w >>
237 dumpIfSet opt_D_dump_foreign "Foreign export header file" stub_h_output_d >>
238 outputHStub opt_ProduceExportHStubs stub_h_output_w >>
240 dumpIfSet opt_D_dump_foreign "Foreign export stubs" stub_c_output_d >>
241 outputCStub mod_name opt_ProduceExportCStubs stub_c_output_w >>
243 dumpIfSet opt_D_dump_realC "Real C" c_output_d >>
244 doOutput opt_ProduceC c_output_w >>
246 reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
251 -------------------------------------------------------------
252 -- ****** help functions:
255 = if opt_D_show_passes
256 then \ what -> hPutStr stderr ("*** "++what++":\n")
257 else \ what -> return ()
259 doOutput switch io_action
263 openFile fname WriteMode >>= \ handle ->
267 -- don't use doOutput for dumping the f. export stubs
268 -- since it is more than likely that the stubs file will
269 -- turn out to be empty, in which case no file should be created.
270 outputCStub mod_name switch "" = return ()
271 outputCStub mod_name switch doc_str
274 Just fname -> writeFile fname ("#include \"Rts.h\"\n#include \"RtsAPI.h\"\n"++rest)
276 rest = "#include "++show (moduleString mod_name ++ "_stub.h") ++ '\n':doc_str
278 outputHStub switch "" = return ()
279 outputHStub switch doc_str
282 Just fname -> writeFile fname ("#include \"Rts.h\"\n"++doc_str)
284 ppSourceStats short (HsModule name version exports imports decls src_loc)
285 = (if short then hcat else vcat)
287 [("ExportAll ", export_all), -- 1 if no export list
288 ("ExportDecls ", export_ds),
289 ("ExportModules ", export_ms),
290 ("Imports ", import_no),
291 (" ImpQual ", import_qual),
292 (" ImpAs ", import_as),
293 (" ImpAll ", import_all),
294 (" ImpPartial ", import_partial),
295 (" ImpHiding ", import_hiding),
296 ("FixityDecls ", fixity_ds),
297 ("DefaultDecls ", default_ds),
298 ("TypeDecls ", type_ds),
299 ("DataDecls ", data_ds),
300 ("NewTypeDecls ", newt_ds),
301 ("DataConstrs ", data_constrs),
302 ("DataDerivings ", data_derivs),
303 ("ClassDecls ", class_ds),
304 ("ClassMethods ", class_method_ds),
305 ("DefaultMethods ", default_method_ds),
306 ("InstDecls ", inst_ds),
307 ("InstMethods ", inst_method_ds),
308 ("TypeSigs ", bind_tys),
309 ("ValBinds ", val_bind_ds),
310 ("FunBinds ", fn_bind_ds),
311 ("InlineMeths ", method_inlines),
312 ("InlineBinds ", bind_inlines),
313 -- ("SpecialisedData ", data_specs),
314 -- ("SpecialisedInsts ", inst_specs),
315 ("SpecialisedMeths ", method_specs),
316 ("SpecialisedBinds ", bind_specs)
319 pp_val (str, 0) = empty
321 | not short = hcat [text str, int n]
322 | otherwise = hcat [text (trim str), equals, int n, semi]
324 trim ls = takeWhile (not.isSpace) (dropWhile isSpace ls)
326 fixity_ds = length [() | FixD d <- decls]
327 -- NB: this omits fixity decls on local bindings and
328 -- in class decls. ToDo
330 tycl_decls = [d | TyClD d <- decls]
331 (class_ds, data_ds, newt_ds, type_ds) = countTyClDecls tycl_decls
333 inst_decls = [d | InstD d <- decls]
334 inst_ds = length inst_decls
335 default_ds = length [() | DefD _ <- decls]
336 val_decls = [d | ValD d <- decls]
338 real_exports = case exports of { Nothing -> []; Just es -> es }
339 n_exports = length real_exports
340 export_ms = length [() | IEModuleContents _ <- real_exports]
341 export_ds = n_exports - export_ms
342 export_all = case exports of { Nothing -> 1; other -> 0 }
344 (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
345 = count_binds (foldr ThenBinds EmptyBinds val_decls)
347 (import_no, import_qual, import_as, import_all, import_partial, import_hiding)
348 = foldr add6 (0,0,0,0,0,0) (map import_info imports)
349 (data_constrs, data_derivs)
350 = foldr add2 (0,0) (map data_info tycl_decls)
351 (class_method_ds, default_method_ds)
352 = foldr add2 (0,0) (map class_info tycl_decls)
353 (inst_method_ds, method_specs, method_inlines)
354 = foldr add3 (0,0,0) (map inst_info inst_decls)
357 count_binds EmptyBinds = (0,0,0,0,0)
358 count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
359 count_binds (MonoBind b sigs _) = case (count_monobinds b, count_sigs sigs) of
360 ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
362 count_monobinds EmptyMonoBinds = (0,0)
363 count_monobinds (AndMonoBinds b1 b2) = count_monobinds b1 `add2` count_monobinds b2
364 count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
365 count_monobinds (PatMonoBind p r _) = (0,1)
366 count_monobinds (FunMonoBind f _ m _) = (0,1)
368 count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
370 sig_info (Sig _ _ _) = (1,0,0,0)
371 sig_info (ClassOpSig _ _ _ _) = (0,1,0,0)
372 sig_info (SpecSig _ _ _ _) = (0,0,1,0)
373 sig_info (InlineSig _ _) = (0,0,0,1)
374 sig_info _ = (0,0,0,0)
376 import_info (ImportDecl _ qual as spec _)
377 = add6 (1, qual_info qual, as_info as, 0,0,0) (spec_info spec)
382 spec_info Nothing = (0,0,0,1,0,0)
383 spec_info (Just (False, _)) = (0,0,0,0,1,0)
384 spec_info (Just (True, _)) = (0,0,0,0,0,1)
386 data_info (TyData _ _ _ _ constrs derivs _ _)
387 = (length constrs, case derivs of {Nothing -> 0; Just ds -> length ds})
388 data_info other = (0,0)
390 class_info (ClassDecl _ _ _ meth_sigs def_meths _ _ _ _)
391 = case count_sigs meth_sigs of
393 (classops, addpr (count_monobinds def_meths))
394 class_info other = (0,0)
396 inst_info (InstDecl _ inst_meths inst_sigs _ _)
397 = case count_sigs inst_sigs of
399 (addpr (count_monobinds inst_meths), ss, is)
401 addpr :: (Int,Int) -> Int
402 add1 :: Int -> Int -> Int
403 add2 :: (Int,Int) -> (Int,Int) -> (Int, Int)
404 add3 :: (Int,Int,Int) -> (Int,Int,Int) -> (Int, Int, Int)
405 add4 :: (Int,Int,Int,Int) -> (Int,Int,Int,Int) -> (Int, Int, Int, Int)
406 add5 :: (Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int)
407 add6 :: (Int,Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int, Int)
411 add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
412 add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
413 add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
414 add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
415 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)
419 compiler_version :: String
421 case (show opt_HiVersion) of
423 ls@[x,y] -> "0." ++ ls
426 -- 10232353 => 10232.53
433 reportCompile :: Module -> String -> IO ()
434 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
435 reportCompile mod_name info
436 | not opt_ReportCompile = return ()
440 sendTo sock (moduleString mod_name ++ ';': compiler_version ++ ';': os ++ ';':arch ++ '\n':' ':info ++ "\n") addr
441 return ()) `catch` (\ _ -> return ())
443 motherShip :: IO SockAddr
445 he <- getHostByName "laysan.dcs.gla.ac.uk"
446 case (hostAddresses he) of
447 [] -> IOERROR (userError "No address!")
448 (x:_) -> return (SockAddrInet motherShipPort x)
451 motherShipPort :: PortNumber
452 motherShipPort = mkPortNumber 12345
454 -- creates a socket capable of sending datagrams,
455 -- binding it to a port
456 -- ( 0 => have the system pick next available port no.)
457 udpSocket :: Int -> IO Socket
459 pr <- getProtocolNumber "udp"
460 s <- socket AF_INET Datagram pr
461 bindSocket s (SockAddrInet (mkPortNumber p) iNADDR_ANY)
464 reportCompile _ _ = return ()