2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1995
4 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
7 #include "HsVersions.h"
10 #ifdef __GLASGOW_HASKELL__
21 import AbsPrel ( builtinNameInfo )
23 import AbsUniType ( isDataTyCon, TauType(..), UniType, TyVar, TyCon, Class )
24 import Bag ( emptyBag, isEmptyBag, Bag )
25 import CE ( CE(..), UniqFM )
26 import CodeGen ( codeGen )
27 import CoreToStg ( topCoreBindsToStg )
28 import Desugar ( deSugar )
29 import DsMonad ( DsMatchContext, DsMatchKind, pprDsWarnings )
30 import E ( getE_TCE, E, GVE(..) )
31 -- most of above needed by mkInterface
33 import Errors ( pprBagOfErrors, Error(..) )
35 import Errors ( pprBagOfErrors, pprPodizedWarning, Error(..) )
36 #endif {- Data Parallel Haskell -}
37 import Id ( mkInstId, Id, Inst )
38 import Maybes ( maybeToBool, Maybe(..), MaybeErr(..) )
39 import MkIface ( mkInterface )
41 import PlainCore ( CoreExpr, CoreBinding, pprPlainCoreBinding,
42 PlainCoreProgram(..), PlainCoreBinding(..)
47 import ReadPrefix2 ( rdModule )
49 import {-hide from mkdependHS-}
50 ReadPrefix ( rdModule )
52 import Rename -- renameModule ...
53 import SimplCore -- core2core
54 import SimplStg ( stg2stg )
55 --ANDY: import SimplHaskell
56 import StgSyn ( pprPlainStgBinding, StgBinding, StgRhs, CostCentre,
57 StgBinderInfo, PlainStgProgram(..), PlainStgBinding(..)
59 import TCE ( rngTCE, {- UNUSED: printTypeInfoForPop,-} TCE(..)
60 IF_ATTACK_PRAGMAS(COMMA eltsUFM)
62 import Typecheck -- typecheckModule ...
64 import Unique -- lots of UniqueSupplies, etc.
67 #if ! OMIT_NATIVE_CODEGEN
68 import AsmCodeGen ( dumpRealAsm
69 # if __GLASGOW_HASKELL__
75 #ifdef USE_SEMANTIQUE_STRANAL
76 import ProgEnv ( ProgEnv(..), TreeProgEnv(..), createProgEnv )
77 import StrAnal ( ppShowStrAnal, OAT )
80 import PodizeCore ( podizeCore , PodWarning)
81 import AbsCTopApal ( nuAbsCToApal )
82 import NextUsed ( pprTopNextUsedC, getTopLevelNexts, AbsCNextUsed,
83 TopAbsCNextUsed(..) , MagicId)
85 #endif {- Data Parallel Haskell -}
89 #ifndef __GLASGOW_HASKELL__
92 main = mainIOtoDialogue main_io
100 BSCC("rdInput") readMn stdin ESCC `thenMn` \ input_pgm ->
101 getArgsMn `thenMn` \ raw_cmd_line ->
102 classifyOpts raw_cmd_line `thenMn` \ cmd_line_info ->
104 doIt cmd_line_info input_pgm
109 doIt :: CmdLineInfo -> String -> MainIO ()
111 doIt (switch_lookup_fn, core_cmds, stg_cmds) input_pgm
113 doIt (switch_lookup_fn, core_cmds, podize_cmds, pcore_cmds, stg_cmds) input_pgm
114 #endif {- Data Parallel Haskell -}
116 -- Help functions and boring global variables (e.g., printing style)
117 -- are figured out first; the "business end" follows, in the
121 -- ****** help functions:
123 switch_is_on switch = switchIsOn switch_lookup_fn switch
125 string_switch_is_on switch
126 = maybeToBool (stringSwitchSet switch_lookup_fn switch)
129 = if switch_is_on D_show_passes
130 then \ what -> writeMn stderr ("*** "++what++":\n")
131 else \ what -> returnMn ()
133 doOutput switch io_action
135 case (stringSwitchSet switch_lookup_fn switch) of
136 Nothing -> returnMn ()
138 fopen fname "a+" `thenMn` \ file ->
139 if (file == ``NULL'') then
140 error ("doOutput: failed to open:"++fname)
142 io_action file `thenMn` \ () ->
143 fclose file `thenMn` \ status ->
146 else error ("doOutput: closed failed: "{-++show status++" "-}++fname)
149 doDump switch hdr string
151 if (switch_is_on switch)
152 then writeMn stderr hdr `thenMn_`
153 writeMn stderr ('\n': string) `thenMn_`
158 -- ****** printing styles and column width:
160 pprCols = (80 :: Int) -- could make configurable
162 (pprStyle, pprErrorsStyle)
163 = if switch_is_on PprStyle_All then
164 (PprShowAll, PprShowAll)
165 else if switch_is_on PprStyle_Debug then
167 else if switch_is_on PprStyle_User then
168 (PprForUser, PprForUser)
170 (PprDebug, PprForUser)
172 pp_show p = ppShow {-WAS:pprCols-}10000{-random-} p
174 -- non-tuple-ish bindings...
176 -- ****** possibly fiddle builtin namespaces:
178 BIND (BSCC("builtinEnv")
179 builtinNameInfo switch_is_on {-switch looker-upper-}
182 _TO_ (init_val_lookup_fn, init_tc_lookup_fn) ->
184 -- **********************************************
185 -- Welcome to the business end of the main module
186 -- of the Glorious Glasgow Haskell compiler!
187 -- **********************************************
189 doDump Verbose "Glasgow Haskell Compiler, version 0.27" "" `thenMn_`
191 doDump Verbose "Data Parallel Haskell Compiler, version 0.06 (Glasgow 0.27)" ""
193 #endif {- Data Parallel Haskell -}
196 show_pass "Read" `thenMn_`
197 #ifdef USE_NEW_READER
201 `thenMn` \ (mod_name, export_list_fns, absyn_tree) ->
203 BIND (\x -> x) _TO_ bar_foo ->
204 -- so BINDs and BENDs add up...
206 BIND BSCC("rdModule")
209 _TO_ (mod_name, export_list_fns, absyn_tree) ->
212 -- reader things used (much?) later
213 ds_mod_name = mod_name
214 if_mod_name = mod_name
215 co_mod_name = mod_name
216 st_mod_name = mod_name
217 cc_mod_name = mod_name
218 -- also: export_list_fns
220 doDump D_source_stats "\nSource Statistics:"
221 (pp_show (ppSourceStats absyn_tree)) `thenMn_`
223 doDump D_dump_rif2hs "Parsed, Haskellised:"
224 (pp_show (ppr pprStyle absyn_tree)) `thenMn_`
226 -- UniqueSupplies for later use
227 getSplitUniqSupplyMn 'r' `thenMn` \ rn_uniqs -> -- renamer
228 getSplitUniqSupplyMn 't' `thenMn` \ tc_uniqs -> -- typechecker
229 getSplitUniqSupplyMn 'd' `thenMn` \ ds_uniqs -> -- desugarer
230 getSplitUniqSupplyMn 's' `thenMn` \ sm_uniqs -> -- core-to-core simplifier
231 getSplitUniqSupplyMn 'C' `thenMn` \ c2s_uniqs -> -- core-to-stg
232 getSplitUniqSupplyMn 'T' `thenMn` \ st_uniqs -> -- stg-to-stg passes
233 getSplitUniqSupplyMn 'F' `thenMn` \ fl_uniqs -> -- absC flattener
234 getSplitUniqSupplyMn 'P' `thenMn` \ prof_uniqs -> -- profiling tidy-upper
235 getSplitUniqSupplyMn 'L' `thenMn` \ pre_ncg_uniqs -> -- native-code generator
237 ncg_uniqs = {-mkUniqueSupplyGrimily-} pre_ncg_uniqs
240 show_pass "Rename" `thenMn_`
242 renameModule switch_is_on
243 (init_val_lookup_fn, init_tc_lookup_fn)
247 _TO_ (mod4, import_names, final_name_funs, rn_errs_bag) ->
249 -- renamer things used (much?) later
250 cc_import_names = import_names
253 doDump D_dump_rn4 "Renamer-pass4:"
254 (pp_show (ppr pprStyle mod4)) `thenMn_`
256 if (not (isEmptyBag rn_errs_bag)) then
258 writeMn stderr (ppShow pprCols (pprBagOfErrors pprErrorsStyle rn_errs_bag))
259 `thenMn_` writeMn stderr "\n"
262 else -- No renaming errors, carry on with...
264 -- ******* TYPECHECKER
265 show_pass "TypeCheck" `thenMn_`
266 BIND (case BSCC("TypeChecker")
267 typecheckModule switch_is_on tc_uniqs final_name_funs mod4
274 panic "main: tickled tc_results even though there were errors"))
276 _TO_ (tc_errs_bag, tc_results) ->
279 ppr_b :: (Inst, TypecheckedExpr) -> Pretty
280 ppr_b (i,e) = ppr pprStyle (VarMonoBind (mkInstId i) e)
282 if (not (isEmptyBag tc_errs_bag)) then
283 -- Must stop *before* trying to dump tc output, because
284 -- if it fails it does not give you any useful stuff back!
285 writeMn stderr (ppShow pprCols (pprBagOfErrors pprErrorsStyle tc_errs_bag))
286 `thenMn_` writeMn stderr "\n"
289 else ( -- No typechecking errors either -- so, go for broke!
292 _TO_ (typechecked_quad@(class_binds, inst_binds, val_binds, const_binds),
293 interface_stuff@(_,_,_,_,_), -- @-pat just for strictness...
294 pragma_tycon_specs, {-UNUSED:big_env,-} this_mod_env, ddump_deriv) ->
296 -- big_tce = getE_TCE big_env
297 -- big_elts = rngTCE big_tce
299 this_mod_tce = getE_TCE this_mod_env
300 this_mod_elts = rngTCE this_mod_tce
302 local_tycons = [tc | tc <- this_mod_elts,
303 isLocallyDefined tc, -- from this module only
304 isDataTyCon tc ] -- algebraic types only
306 -- pprTrace "Envs:" (ppAboves [
307 -- ppr pprStyle if_global_ids,
308 -- ppr pprStyle if_tce,
309 -- ppr pprStyle if_ce,
310 -- ppr pprStyle this_mod_env,
311 -- ppr pprStyle big_env
314 doDump D_dump_tc "Typechecked:"
316 (ppAboves [ppr pprStyle class_binds,
317 ppr pprStyle inst_binds,
318 ppAboves (map ppr_b const_binds),
319 ppr pprStyle val_binds])) `thenMn_`
321 doDump D_dump_deriv "Derived instances:"
322 (pp_show (ddump_deriv pprStyle)) `thenMn_`
325 -- doDump D_dump_type_info "" (pp_show (printTypeInfoForPop big_tce)) `thenMn_`
327 show_pass "DeSugar" `thenMn_`
329 (desugared,ds_warnings)
331 deSugar ds_uniqs switch_lookup_fn ds_mod_name typechecked_quad
334 (if isEmptyBag ds_warnings then
337 writeMn stderr (ppShow pprCols (pprDsWarnings pprErrorsStyle ds_warnings))
338 `thenMn_` writeMn stderr "\n"
341 doDump D_dump_ds "Desugared:" (pp_show (ppAboves
342 (map (pprPlainCoreBinding pprStyle) desugared))) `thenMn_`
344 -- ******* CORE-TO-CORE SIMPLIFICATION (NB: I/O op)
345 core2core core_cmds switch_lookup_fn co_mod_name pprStyle
346 sm_uniqs local_tycons pragma_tycon_specs desugared
347 `thenMn` \ (simplified, inlinings_env,
348 SpecData _ _ _ gen_tycons all_tycon_specs _ _ _) ->
350 doDump D_dump_simpl "Simplified:" (pp_show (ppAboves
351 (map (pprPlainCoreBinding pprStyle) simplified))) `thenMn_`
354 -- doDump D_dump_core_passes_info "(Haskell) Simplified:"
355 -- (coreToHaskell simplified) `thenMn_`
358 -- ******* PODIZE (VECTORIZE) THE CORE PROGRAM
360 (warn,podized) = BSCC("PodizeCore")
361 podizeCore podize_cmds switch_is_on
362 uniqSupply_p simplified
365 (if (not (null warn))
366 then writeMn stderr "\n" `thenMn_`
367 writeMn stderr (ppShow pprCols (ppAboves
368 (map (\w -> pprPodizedWarning w pprErrorsStyle) warn))) `thenMn_`
370 else returnMn ()) `thenMn_`
372 doDump D_dump_pod "Podization:" (pp_show (ppAboves
373 (map (pprPlainCoreBinding pprStyle) podized))) `thenMn_`
375 -- ******** CORE-TO-CORE SIMPLIFICATION OF PODIZED PROGRAM
377 psimplified = BSCC("PodizeCore2Core")
378 core2core pcore_cmds switch_is_on pprStyle
382 doDump D_dump_psimpl "Par Simplified:" (pp_show (ppAboves
383 (map (pprPlainCoreBinding pprStyle) psimplified))) `thenMn_`
385 #endif {- Data Parallel Haskell -}
387 #ifdef USE_SEMANTIQUE_STRANAL
388 -- ******* SEMANTIQUE STRICTNESS ANALYSER
389 doDump D_dump_stranal_sem "Strictness:" (ppShowStrAnal simplified big_env) `thenMn_`
392 -- ******* STG-TO-STG SIMPLIFICATION
393 show_pass "Core2Stg" `thenMn_`
396 stg_binds = BSCC("Core2Stg")
397 topCoreBindsToStg c2s_uniqs simplified
400 stg_binds = BSCC("Core2Stg")
401 topCoreBindsToStg c2s_uniqs psimplified
403 #endif {- Data Parallel Haskell -}
405 show_pass "Stg2Stg" `thenMn_`
406 stg2stg stg_cmds switch_lookup_fn st_mod_name pprStyle st_uniqs stg_binds
407 `thenMn` \ (stg_binds2, cost_centre_info) ->
409 doDump D_dump_stg "STG syntax:" (pp_show (ppAboves
410 (map (pprPlainStgBinding pprStyle) stg_binds2))) `thenMn_`
412 -- ******* INTERFACE GENERATION (needs STG output)
414 mod_name = "_TestName_"
415 export_list_fns = (\ x -> False, \ x -> False)
416 inlinings_env = nullIdEnv
421 if_inst_info = emptyBag
424 show_pass "Interface" `thenMn_`
427 = BSCC("MkInterface")
428 mkInterface switch_is_on if_mod_name export_list_fns
429 inlinings_env all_tycon_specs
434 doOutput ProduceHi BSCC("PrintInterface")
436 ppAppendFile file 1000{-pprCols-} mod_interface )
439 -- ******* "ABSTRACT", THEN "FLAT", THEN *REAL* C!
440 show_pass "CodeGen" `thenMn_`
442 abstractC = BSCC("CodeGen")
443 codeGen cc_mod_name -- module name for CC labelling
445 cc_import_names -- import names for CC registering
447 gen_tycons -- type constructors generated locally
448 all_tycon_specs -- tycon specialisations
452 flat_abstractC = BSCC("FlattenAbsC")
453 flattenAbsC fl_uniqs abstractC
456 doDump D_dump_absC "Abstract C:" (dumpRealC switch_is_on abstractC) `thenMn_`
458 doDump D_dump_flatC "Flat Abstract C:" (dumpRealC switch_is_on flat_abstractC) `thenMn_`
460 -- You can have C (c_output) or assembly-language (ncg_output),
461 -- but not both. [Allowing for both gives a space leak on
462 -- flat_abstractC. WDP 94/10]
464 (flat_absC_c, flat_absC_ncg) =
465 case (string_switch_is_on ProduceC || switch_is_on D_dump_realC,
466 string_switch_is_on ProduceS || switch_is_on D_dump_asm) of
467 (True, False) -> (flat_abstractC, AbsCNop)
468 (False, True) -> (AbsCNop, flat_abstractC)
469 (False, False) -> (AbsCNop, AbsCNop)
470 (True, True) -> error "ERROR: Can't do both .hc and .s at the same time"
472 c_output_d = BSCC("PrintRealC")
473 dumpRealC switch_is_on flat_absC_c
476 #ifdef __GLASGOW_HASKELL__
477 c_output_w = BSCC("PrintRealC")
478 (\ f -> writeRealC switch_is_on f flat_absC_c)
481 c_output_w = c_output_d
484 #if OMIT_NATIVE_CODEGEN
486 = error "*** GHC not built with a native-code generator ***"
487 ncg_output_w = ncg_output_d
489 ncg_output_d = BSCC("nativeCode")
490 dumpRealAsm switch_lookup_fn flat_absC_ncg ncg_uniqs
493 #ifdef __GLASGOW_HASKELL__
494 ncg_output_w = BSCC("nativeCode")
495 (\ f -> writeRealAsm switch_lookup_fn f flat_absC_ncg ncg_uniqs)
498 ncg_output_w = ncg_output_d
502 doDump D_dump_asm "" ncg_output_d `thenMn_`
503 doOutput ProduceS ncg_output_w `thenMn_`
506 -- ********* GHC Finished !!!!
507 doDump D_dump_realC "" c_output_d `thenMn_`
508 doOutput ProduceC c_output_w `thenMn_`
511 -- ********* DPH needs native code generator, nearly finished.....
513 next_used_flatC = getTopLevelNexts flat_abstractC []
514 apal_module = nuAbsCToApal uniqSupply_L mod_name next_used_flatC
516 doDump D_dump_nextC "Next Used annotated C:" (ppShow pprCols
517 (pprTopNextUsedC next_used_flatC)) `thenMn_`
518 doOutput ProduceC ("! /* DAP assembler (APAL): */\n"++apal_module) `thenMn_`
520 #endif {- Data Parallel Haskell -}
522 {-)-} BEND ) BEND BEND BEND BEND
525 ppSourceStats (Module name exports imports fixities typedecls typesigs
526 classdecls instdecls instsigs defdecls binds
527 [{-no sigs-}] src_loc)
528 = ppAboves (map pp_val
529 [("ExportAll ", export_all), -- 1 if no export list
530 ("ExportDecls ", export_ds),
531 ("ExportModules ", export_ms),
532 ("ImportAll ", import_all),
533 ("ImportPartial ", import_partial),
534 (" PartialDecls ", partial_decls),
535 ("ImportHiding ", import_hiding),
536 (" HidingDecls ", hiding_decls),
537 ("FixityDecls ", fixity_ds),
538 ("DefaultDecls ", defalut_ds),
539 ("TypeDecls ", type_ds),
540 ("DataDecls ", data_ds),
541 ("DataConstrs ", data_constrs),
542 ("DataDerivings ", data_derivs),
543 ("ClassDecls ", class_ds),
544 ("ClassMethods ", class_method_ds),
545 ("DefaultMethods ", default_method_ds),
546 ("InstDecls ", inst_ds),
547 ("InstMethods ", inst_method_ds),
548 ("TypeSigs ", bind_tys),
549 ("ValBinds ", val_bind_ds),
550 ("FunBinds ", fn_bind_ds),
551 ("InlineMeths ", method_inlines),
552 ("InlineBinds ", bind_inlines),
553 ("SpecialisedData ", data_specs),
554 ("SpecialisedInsts ", inst_specs),
555 ("SpecialisedMeths ", method_specs),
556 ("SpecialisedBinds ", bind_specs)
559 pp_val (str, 0) = ppNil
560 pp_val (str, n) = ppBesides [ppStr str, ppInt n]
562 (export_decls, export_mods) = getRawIEStrings exports
563 type_decls = filter is_type_decl typedecls
564 data_decls = filter is_data_decl typedecls
566 export_ds = length export_decls
567 export_ms = length export_mods
568 export_all = if export_ds == 0 && export_ms == 0 then 1 else 0
570 fixity_ds = length fixities
571 defalut_ds = length defdecls
572 type_ds = length type_decls
573 data_ds = length data_decls
574 class_ds = length classdecls
575 inst_ds = length instdecls
577 (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
580 (import_all, import_partial, partial_decls, import_hiding, hiding_decls)
581 = foldr add5 (0,0,0,0,0) (map import_info imports)
582 (data_constrs, data_derivs)
583 = foldr add2 (0,0) (map data_info data_decls)
584 (class_method_ds, default_method_ds)
585 = foldr add2 (0,0) (map class_info classdecls)
586 (inst_method_ds, method_specs, method_inlines)
587 = foldr add3 (0,0,0) (map inst_info instdecls)
589 data_specs = length (filter is_data_spec_sig typesigs)
590 inst_specs = length (filter is_inst_spec_sig instsigs)
593 count_binds EmptyBinds = (0,0,0,0,0)
594 count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
595 count_binds (SingleBind b) = case count_bind b of
596 (vs,fs) -> (vs,fs,0,0,0)
597 count_binds (BindWith b sigs) = case (count_bind b, count_sigs sigs) of
598 ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
600 count_bind EmptyBind = (0,0)
601 count_bind (NonRecBind b) = count_monobinds b
602 count_bind (RecBind b) = count_monobinds b
604 count_monobinds EmptyMonoBinds = (0,0)
605 count_monobinds (AndMonoBinds b1 b2) = count_monobinds b1 `add2` count_monobinds b2
606 count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
607 count_monobinds (PatMonoBind p r _) = (0,1)
608 count_monobinds (FunMonoBind f m _) = (0,1)
610 count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
612 sig_info (Sig _ _ _ _) = (1,0,0,0)
613 sig_info (ClassOpSig _ _ _ _) = (0,1,0,0)
614 sig_info (SpecSig _ _ _ _) = (0,0,1,0)
615 sig_info (InlineSig _ _ _) = (0,0,0,1)
616 sig_info _ = (0,0,0,0)
618 import_info (ImportAll _ _) = (1,0,0,0,0)
619 import_info (ImportSome _ ds _) = (0,1,length ds,0,0)
620 import_info (ImportButHide _ ds _) = (0,0,0,1,length ds)
622 data_info (TyData _ _ _ constrs derivs _ _)
623 = (length constrs, length derivs)
625 class_info (ClassDecl _ _ _ meth_sigs def_meths _ _)
626 = case count_sigs meth_sigs of
628 (classops, addpr (count_monobinds def_meths))
630 inst_info (InstDecl _ _ _ inst_meths _ _ _ inst_sigs _ _)
631 = case count_sigs inst_sigs of
633 (addpr (count_monobinds inst_meths), ss, is)
635 is_type_decl (TySynonym _ _ _ _ _) = True
636 is_type_decl _ = False
637 is_data_decl (TyData _ _ _ _ _ _ _) = True
638 is_data_decl _ = False
639 is_data_spec_sig (SpecDataSig _ _ _) = True
640 is_data_spec_sig _ = False
641 is_inst_spec_sig (InstSpecSig _ _ _) = True
645 add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
646 add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
647 add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
648 add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)