[project @ 2002-09-13 15:02:25 by simonpj]
[ghc-hetmet.git] / ghc / compiler / codeGen / CodeGen.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[CodeGen]{@CodeGen@: main module of the code generator}
5
6 This module says how things get going at the top level.
7
8 @codeGen@ is the interface to the outside world.  The \tr{cgTop*}
9 functions drive the mangling of top-level bindings.
10
11 %************************************************************************
12 %*                                                                      *
13 \subsection[codeGen-outside-interface]{The code generator's offering to the world}
14 %*                                                                      *
15 %************************************************************************
16
17 \begin{code}
18 module CodeGen ( codeGen ) where
19
20 #include "HsVersions.h"
21
22 -- Kludge (??) so that CgExpr is reached via at least one non-SOURCE
23 -- import.  Before, that wasn't the case, and CM therefore didn't 
24 -- bother to compile it.
25 import CgExpr           ( {-NOTHING!-} )        -- DO NOT DELETE THIS IMPORT
26
27 import DriverState      ( v_Build_tag )
28 import StgSyn
29 import CgMonad
30 import AbsCSyn
31 import PrelNames        ( gHC_PRIM )
32 import CLabel           ( CLabel, mkSRTLabel, mkClosureLabel, 
33                           mkPlainModuleInitLabel, mkModuleInitLabel )
34 import PprAbsC          ( dumpRealC )
35 import AbsCUtils        ( mkAbstractCs, flattenAbsC )
36 import CgBindery        ( CgIdInfo, addBindC, addBindsC, getCAddrModeAndInfo )
37 import CgClosure        ( cgTopRhsClosure )
38 import CgCon            ( cgTopRhsCon )
39 import CgConTbls        ( genStaticConBits )
40 import ClosureInfo      ( mkClosureLFInfo )
41 import CmdLineOpts      ( DynFlags, DynFlag(..),
42                           opt_SccProfilingOn, opt_EnsureSplittableC )
43 import HscTypes         ( ModGuts(..), ModGuts, ForeignStubs(..),
44                           typeEnvTyCons )
45 import CostCentre       ( CollectedCCs )
46 import Id               ( Id, idName, setIdName )
47 import Name             ( nameSrcLoc, nameOccName, nameUnique, isInternalName, mkExternalName )
48 import OccName          ( mkLocalOcc )
49 import PrimRep          ( PrimRep(..) )
50 import TyCon            ( isDataTyCon )
51 import BasicTypes       ( TopLevelFlag(..) )
52 import UniqSupply       ( mkSplitUniqSupply )
53 import ErrUtils         ( dumpIfSet_dyn, showPass )
54 import Panic            ( assertPanic )
55
56 #ifdef DEBUG
57 import Outputable
58 #endif
59
60 import DATA_IOREF       ( readIORef )
61 \end{code}
62
63 \begin{code}
64 codeGen :: DynFlags
65         -> ModGuts
66         -> CollectedCCs         -- (Local/global) cost-centres needing declaring/registering.
67         -> [(StgBinding,[Id])]  -- Bindings to convert, with SRTs
68         -> IO AbstractC         -- Output
69
70 codeGen dflags 
71         mod_impl@(ModGuts { mg_module = mod_name, mg_types = type_env })
72         cost_centre_info stg_binds
73   = do  
74         showPass dflags "CodeGen"
75         fl_uniqs <- mkSplitUniqSupply 'f'
76         way <- readIORef v_Build_tag
77
78         let
79             tycons         = typeEnvTyCons type_env
80             data_tycons    = filter isDataTyCon tycons
81             cinfo          = MkCompInfo mod_name
82
83             datatype_stuff = genStaticConBits cinfo data_tycons
84             code_stuff     = initC cinfo (mapCs cgTopBinding stg_binds)
85             init_stuff     = mkModuleInit way cost_centre_info mod_impl
86
87             abstractC = mkAbstractCs [ maybeSplitCode,
88                                        init_stuff, 
89                                        code_stuff,
90                                        datatype_stuff]
91                 -- Put datatype_stuff after code_stuff, because the
92                 -- datatype closure table (for enumeration types) to
93                 -- (say) PrelBase_True_closure, which is defined in
94                 -- code_stuff
95
96         dumpIfSet_dyn dflags Opt_D_dump_absC "Abstract C" (dumpRealC abstractC)
97
98         return $! flattenAbsC fl_uniqs abstractC
99 \end{code}
100
101 %************************************************************************
102 %*                                                                      *
103 \subsection[codegen-init]{Module initialisation code}
104 %*                                                                      *
105 %************************************************************************
106
107 \begin{code}
108 mkModuleInit 
109         :: String               -- the "way"
110         -> CollectedCCs         -- cost centre info
111         -> ModGuts
112         -> AbstractC
113 mkModuleInit way cost_centre_info
114              (ModGuts { mg_module  = mod,
115                         mg_foreign = ForeignStubs _ _ _ fe_binders,
116                         mg_dir_imps = imported_modules })
117   = let
118         register_fes = 
119            map (\f -> CMacroStmt REGISTER_FOREIGN_EXPORT [f]) fe_labels
120
121         fe_labels = 
122            map (\f -> CLbl (mkClosureLabel (idName f)) PtrRep) fe_binders
123
124         (cc_decls, cc_regs) = mkCostCentreStuff cost_centre_info
125
126         -- we don't want/need to init GHC.Prim, so filter it out
127         mk_import_register mod
128             | mod == gHC_PRIM = AbsCNop
129             | otherwise       = CMacroStmt REGISTER_IMPORT [
130                                    CLbl (mkModuleInitLabel mod way) AddrRep
131                                 ]
132
133         register_imports = map mk_import_register imported_modules
134     in
135     mkAbstractCs [
136         cc_decls,
137         CModuleInitBlock (mkPlainModuleInitLabel mod)
138                          (mkModuleInitLabel mod way)
139                          (mkAbstractCs (register_fes ++
140                                         cc_regs :
141                                         register_imports))
142     ]
143 \end{code}
144
145 Cost-centre profiling: Besides the usual stuff, we must produce
146 declarations for the cost-centres defined in this module;
147
148 (The local cost-centres involved in this are passed into the
149 code-generator.)
150
151 \begin{code}
152 mkCostCentreStuff (local_CCs, extern_CCs, singleton_CCSs)
153   | not opt_SccProfilingOn = (AbsCNop, AbsCNop)
154   | otherwise = 
155         ( mkAbstractCs (
156                 map (CCostCentreDecl True)   local_CCs ++
157                 map (CCostCentreDecl False)  extern_CCs ++
158                 map CCostCentreStackDecl     singleton_CCSs),
159           mkAbstractCs (mkCcRegister local_CCs singleton_CCSs)
160         )
161   where
162     mkCcRegister ccs cc_stacks
163       = let
164             register_ccs       = mkAbstractCs (map mk_register ccs)
165             register_cc_stacks = mkAbstractCs (map mk_register_ccs cc_stacks)
166         in
167         [ register_ccs, register_cc_stacks ]
168       where
169         mk_register cc
170           = CCallProfCCMacro FSLIT("REGISTER_CC") [mkCCostCentre cc]
171
172         mk_register_ccs ccs
173           = CCallProfCCMacro FSLIT("REGISTER_CCS") [mkCCostCentreStack ccs]
174 \end{code}
175
176 %************************************************************************
177 %*                                                                      *
178 \subsection[codegen-top-bindings]{Converting top-level STG bindings}
179 %*                                                                      *
180 %************************************************************************
181
182 @cgTopBinding@ is only used for top-level bindings, since they need
183 to be allocated statically (not in the heap) and need to be labelled.
184 No unboxed bindings can happen at top level.
185
186 In the code below, the static bindings are accumulated in the
187 @MkCgState@, and transferred into the ``statics'' slot by @forkStatics@.
188 This is so that we can write the top level processing in a compositional
189 style, with the increasing static environment being plumbed as a state
190 variable.
191
192 \begin{code}
193 cgTopBinding :: (StgBinding,[Id]) -> Code
194 cgTopBinding (StgNonRec srt_info id rhs, srt)
195   = absC maybeSplitCode         `thenC`
196     maybeExternaliseId id               `thenFC` \ id' ->
197     let
198         srt_label = mkSRTLabel (idName id')
199     in
200     mkSRT srt_label srt []      `thenC`
201     setSRTLabel srt_label (
202     cgTopRhs id' rhs srt_info   `thenFC` \ (id, info) ->
203     addBindC id info    -- Add the un-externalised Id to the envt, so we
204                         -- find it when we look up occurrences
205     )
206
207 cgTopBinding (StgRec srt_info pairs, srt)
208   = absC maybeSplitCode                 `thenC`
209     let
210         (bndrs, rhss) = unzip pairs
211     in
212     mapFCs maybeExternaliseId bndrs     `thenFC` \ bndrs'@(id:_) ->
213     let
214         srt_label = mkSRTLabel (idName id)
215         pairs'    = zip bndrs' rhss
216     in
217     mkSRT srt_label srt bndrs'          `thenC`
218     setSRTLabel srt_label (
219        fixC (\ new_binds -> 
220                 addBindsC new_binds             `thenC`
221                 mapFCs ( \ (b,e) -> cgTopRhs b e srt_info ) pairs'
222        )  `thenFC` \ new_binds -> nopC
223     )
224
225 mkSRT :: CLabel -> [Id] -> [Id] -> Code
226 mkSRT lbl []  these = nopC
227 mkSRT lbl ids these
228   = mapFCs remap ids `thenFC` \ ids ->
229     absC (CSRT lbl (map (mkClosureLabel . idName) ids))
230   where
231         -- sigh, better map all the ids against the environment in case they've
232         -- been externalised (see maybeExternaliseId below).
233     remap id = case filter (==id) these of
234                 [] ->  getCAddrModeAndInfo id 
235                                 `thenFC` \ (id, _, _) -> returnFC id
236                 (id':_) -> returnFC id'
237
238 -- Urgh!  I tried moving the forkStatics call from the rhss of cgTopRhs
239 -- to enclose the listFCs in cgTopBinding, but that tickled the
240 -- statics "error" call in initC.  I DON'T UNDERSTAND WHY!
241
242 cgTopRhs :: Id -> StgRhs -> SRT -> FCode (Id, CgIdInfo)
243         -- The Id is passed along for setting up a binding...
244         -- It's already been externalised if necessary
245
246 cgTopRhs bndr (StgRhsCon cc con args) srt
247   = forkStatics (cgTopRhsCon bndr con args srt)
248
249 cgTopRhs bndr (StgRhsClosure cc bi fvs upd_flag args body) srt
250   = ASSERT(null fvs)    -- There should be no free variables
251     let 
252         lf_info = mkClosureLFInfo bndr TopLevel [{-no fvs-}] upd_flag args
253     in
254     forkStatics (cgTopRhsClosure bndr cc bi srt args body lf_info)
255 \end{code}
256
257
258 %************************************************************************
259 %*                                                                      *
260 \subsection{Stuff to support splitting}
261 %*                                                                      *
262 %************************************************************************
263
264 If we're splitting the object, we need to externalise all the top-level names
265 (and then make sure we only use the externalised one in any C label we use
266 which refers to this name).
267
268 \begin{code}
269 maybeExternaliseId :: Id -> FCode Id
270 maybeExternaliseId id
271   | opt_EnsureSplittableC,      -- Externalise the name for -split-objs
272     isInternalName name
273   = moduleName                           `thenFC` \ mod ->
274     returnFC (setIdName id (mkExternalName uniq mod new_occ (nameSrcLoc name)))
275   | otherwise           
276   = returnFC id
277   where
278     name       = idName id
279     uniq       = nameUnique name
280     new_occ    = mkLocalOcc uniq (nameOccName name)
281         -- We want to conjure up a name that can't clash with any
282         -- existing name.  So we generate
283         --      Mod_$L243foo
284         -- where 243 is the unique.
285
286 maybeSplitCode
287   | opt_EnsureSplittableC = CSplitMarker 
288   | otherwise             = AbsCNop
289 \end{code}