[project @ 2004-11-26 16:19:45 by simonmar]
[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 import DriverState      ( v_Build_tag, v_MainModIs )
23
24 -- Kludge (??) so that CgExpr is reached via at least one non-SOURCE
25 -- import.  Before, that wasn't the case, and CM therefore didn't 
26 -- bother to compile it.
27 import CgExpr           ( {-NOTHING!-} )        -- DO NOT DELETE THIS IMPORT
28 import CgProf
29 import CgMonad
30 import CgBindery        ( CgIdInfo, addBindC, addBindsC, getCgIdInfo,
31                           cgIdInfoId )
32 import CgClosure        ( cgTopRhsClosure )
33 import CgCon            ( cgTopRhsCon, cgTyCon )
34 import CgUtils          ( cmmRegOffW, emitRODataLits, cmmNeWord, emitRtsCall )
35
36 import CLabel
37 import Cmm
38 import CmmUtils         ( zeroCLit, mkIntCLit, mkLblExpr )
39 import PprCmm           ( pprCmms )
40 import MachOp           ( wordRep, MachHint(..) )
41
42 import StgSyn
43 import PrelNames        ( gHC_PRIM, rOOT_MAIN, mAIN, pREL_TOP_HANDLER )
44 import CmdLineOpts      ( DynFlags, DynFlag(..), opt_EnsureSplittableC,
45                           opt_SccProfilingOn )
46
47 import HscTypes         ( ForeignStubs(..), TypeEnv, typeEnvTyCons )
48 import CostCentre       ( CollectedCCs )
49 import Id               ( Id, idName, setIdName )
50 import Name             ( nameSrcLoc, nameOccName, nameUnique, isInternalName, mkExternalName )
51 import OccName          ( mkLocalOcc )
52 import TyCon            ( isDataTyCon )
53 import Module           ( Module, mkModule )
54 import ErrUtils         ( dumpIfSet_dyn, showPass )
55 import Panic            ( assertPanic )
56
57 #ifdef DEBUG
58 import Outputable
59 #endif
60
61 import DATA_IOREF       ( readIORef )
62 \end{code}
63
64 \begin{code}
65 codeGen :: DynFlags
66         -> Module
67         -> TypeEnv
68         -> ForeignStubs
69         -> [Module]             -- directly-imported modules
70         -> CollectedCCs         -- (Local/global) cost-centres needing declaring/registering.
71         -> [(StgBinding,[(Id,[Id])])]   -- Bindings to convert, with SRTs
72         -> IO [Cmm]             -- Output
73
74 codeGen dflags this_mod type_env foreign_stubs imported_mods 
75         cost_centre_info stg_binds
76   = do  
77   { showPass dflags "CodeGen"
78   ; way <- readIORef v_Build_tag
79   ; mb_main_mod <- readIORef v_MainModIs
80
81   ; let     tycons      = typeEnvTyCons type_env
82             data_tycons = filter isDataTyCon tycons
83
84 -- Why?
85 --   ; mapM_ (\x -> seq x (return ())) data_tycons
86
87   ; code_stuff <- initC dflags this_mod $ do 
88                 { cmm_binds  <- mapM (getCmm . cgTopBinding dflags) stg_binds
89                 ; cmm_tycons <- mapM cgTyCon data_tycons
90                 ; cmm_init   <- getCmm (mkModuleInit dflags way cost_centre_info 
91                                              this_mod mb_main_mod
92                                              foreign_stubs imported_mods)
93                 ; return (cmm_binds ++ concat cmm_tycons ++ [cmm_init]) 
94                 }
95                 -- Put datatype_stuff after code_stuff, because the
96                 -- datatype closure table (for enumeration types) to
97                 -- (say) PrelBase_True_closure, which is defined in
98                 -- code_stuff
99
100   ; dumpIfSet_dyn dflags Opt_D_dump_cmm "Cmm" (pprCmms code_stuff)
101
102   ; return code_stuff }
103 \end{code}
104
105 %************************************************************************
106 %*                                                                      *
107 \subsection[codegen-init]{Module initialisation code}
108 %*                                                                      *
109 %************************************************************************
110
111 /* -----------------------------------------------------------------------------
112    Module initialisation
113
114    The module initialisation code looks like this, roughly:
115
116         FN(__stginit_Foo) {
117           JMP_(__stginit_Foo_1_p)
118         }
119
120         FN(__stginit_Foo_1_p) {
121         ...
122         }
123
124    We have one version of the init code with a module version and the
125    'way' attached to it.  The version number helps to catch cases
126    where modules are not compiled in dependency order before being
127    linked: if a module has been compiled since any modules which depend on
128    it, then the latter modules will refer to a different version in their
129    init blocks and a link error will ensue.
130
131    The 'way' suffix helps to catch cases where modules compiled in different
132    ways are linked together (eg. profiled and non-profiled).
133
134    We provide a plain, unadorned, version of the module init code
135    which just jumps to the version with the label and way attached.  The
136    reason for this is that when using foreign exports, the caller of
137    startupHaskell() must supply the name of the init function for the "top"
138    module in the program, and we don't want to require that this name
139    has the version and way info appended to it.
140    -------------------------------------------------------------------------- */
141
142 We initialise the module tree by keeping a work-stack, 
143         * pointed to by Sp
144         * that grows downward
145         * Sp points to the last occupied slot
146
147
148 \begin{code}
149 mkModuleInit 
150         :: DynFlags
151         -> String               -- the "way"
152         -> CollectedCCs         -- cost centre info
153         -> Module
154         -> Maybe String         -- Just m ==> we have flag: -main-is Foo.baz 
155         -> ForeignStubs
156         -> [Module]
157         -> Code
158 mkModuleInit dflags way cost_centre_info this_mod mb_main_mod foreign_stubs imported_mods
159   = do  {       
160
161         -- Allocate the static boolean that records if this
162         -- module has been registered already
163         ; emitData Data [CmmDataLabel moduleRegdLabel, 
164                          CmmStaticLit zeroCLit]
165
166         ; emitSimpleProc real_init_lbl $ do
167             {   -- The return-code pops the work stack by 
168                 -- incrementing Sp, and then jumpd to the popped item
169               ret_blk <- forkLabelledCode $ stmtsC
170                         [ CmmAssign spReg (cmmRegOffW spReg 1)
171                         , CmmJump (CmmLoad (cmmRegOffW spReg (-1)) wordRep) [] ]
172
173             ; init_blk <- forkLabelledCode $ do
174                             { mod_init_code; stmtC (CmmBranch ret_blk) }
175                         
176             ; stmtC (CmmCondBranch (cmmNeWord (CmmLit zeroCLit) mod_reg_val)
177                         ret_blk)
178             ; stmtC (CmmBranch init_blk)            
179             }
180
181
182             -- Make the "plain" procedure jump to the "real" init procedure
183         ; emitSimpleProc plain_init_lbl jump_to_init
184
185         -- When compiling the module in which the 'main' function lives,
186         -- (that is, this_mod == main_mod)
187         -- we inject an extra stg_init procedure for stg_init_ZCMain, for the 
188         -- RTS to invoke.  We must consult the -main-is flag in case the
189         -- user specified a different function to Main.main
190         ; whenC (this_mod == main_mod)
191                 (emitSimpleProc plain_main_init_lbl jump_to_init)
192     }
193   where
194     plain_init_lbl = mkPlainModuleInitLabel dflags this_mod
195     real_init_lbl  = mkModuleInitLabel dflags this_mod way
196     plain_main_init_lbl = mkPlainModuleInitLabel dflags rOOT_MAIN
197
198     jump_to_init = stmtC (CmmJump (mkLblExpr real_init_lbl) [])
199
200     mod_reg_val = CmmLoad (mkLblExpr moduleRegdLabel) wordRep
201
202     main_mod = case mb_main_mod of
203                         Just mod_name -> mkModule mod_name
204                         Nothing       -> mAIN
205
206     -- Main refers to GHC.TopHandler.runIO, so make sure we call the
207     -- init function for GHC.TopHandler.
208     extra_imported_mods
209         | this_mod == main_mod = [pREL_TOP_HANDLER]
210         | otherwise            = []
211
212     mod_init_code = do
213         {       -- Set mod_reg to 1 to record that we've been here
214           stmtC (CmmStore (mkLblExpr moduleRegdLabel) (CmmLit (mkIntCLit 1)))
215
216                 -- Now do local stuff
217         ; registerForeignExports foreign_stubs
218         ; initCostCentres cost_centre_info
219         ; mapCs (registerModuleImport dflags way) 
220                 (imported_mods++extra_imported_mods)
221         } 
222
223
224 -----------------------
225 registerModuleImport :: DynFlags -> String -> Module -> Code
226 registerModuleImport dflags way mod 
227   | mod == gHC_PRIM
228   = nopC 
229   | otherwise   -- Push the init procedure onto the work stack
230   = stmtsC [ CmmAssign spReg (cmmRegOffW spReg (-1))
231            , CmmStore (CmmReg spReg) (mkLblExpr (mkModuleInitLabel dflags mod way)) ]
232
233 -----------------------
234 registerForeignExports :: ForeignStubs -> Code
235 registerForeignExports NoStubs 
236   = nopC
237 registerForeignExports (ForeignStubs _ _ _ fe_bndrs)
238   = mapM_ mk_export_register fe_bndrs
239   where
240         mk_export_register bndr
241           = emitRtsCall SLIT("getStablePtr") 
242                 [ (CmmLit (CmmLabel (mkLocalClosureLabel (idName bndr))), 
243                    PtrHint) ]
244 \end{code}
245
246
247
248 Cost-centre profiling: Besides the usual stuff, we must produce
249 declarations for the cost-centres defined in this module;
250
251 (The local cost-centres involved in this are passed into the
252 code-generator.)
253
254 \begin{code}
255 initCostCentres :: CollectedCCs -> Code
256 -- Emit the declarations, and return code to register them
257 initCostCentres (local_CCs, ___extern_CCs, singleton_CCSs)
258   | not opt_SccProfilingOn = nopC
259   | otherwise
260   = do  { mapM_ emitCostCentreDecl       local_CCs
261         ; mapM_ emitCostCentreStackDecl  singleton_CCSs
262         ; mapM_ emitRegisterCC           local_CCs
263         ; mapM_ emitRegisterCCS          singleton_CCSs
264         }
265 \end{code}
266
267 %************************************************************************
268 %*                                                                      *
269 \subsection[codegen-top-bindings]{Converting top-level STG bindings}
270 %*                                                                      *
271 %************************************************************************
272
273 @cgTopBinding@ is only used for top-level bindings, since they need
274 to be allocated statically (not in the heap) and need to be labelled.
275 No unboxed bindings can happen at top level.
276
277 In the code below, the static bindings are accumulated in the
278 @MkCgState@, and transferred into the ``statics'' slot by @forkStatics@.
279 This is so that we can write the top level processing in a compositional
280 style, with the increasing static environment being plumbed as a state
281 variable.
282
283 \begin{code}
284 cgTopBinding :: DynFlags -> (StgBinding,[(Id,[Id])]) -> Code
285 cgTopBinding dflags (StgNonRec id rhs, srts)
286   = do  { id' <- maybeExternaliseId id
287         ; mapM_ (mkSRT dflags [id']) srts
288         ; (id,info) <- cgTopRhs id' rhs
289         ; addBindC id info      -- Add the *un-externalised* Id to the envt,
290                                 -- so we find it when we look up occurrences
291         }
292
293 cgTopBinding dflags (StgRec pairs, srts)
294   = do  { let (bndrs, rhss) = unzip pairs
295         ; bndrs' <- mapFCs maybeExternaliseId bndrs
296         ; let pairs' = zip bndrs' rhss
297         ; mapM_ (mkSRT dflags bndrs')  srts
298         ; new_binds <- fixC (\ new_binds -> do 
299                 { addBindsC new_binds
300                 ; mapFCs ( \ (b,e) -> cgTopRhs b e ) pairs' })
301         ; nopC }
302
303 mkSRT :: DynFlags -> [Id] -> (Id,[Id]) -> Code
304 mkSRT dflags these (id,[])  = nopC
305 mkSRT dflags these (id,ids)
306   = do  { ids <- mapFCs remap ids
307         ; id  <- remap id
308         ; emitRODataLits (mkSRTLabel (idName id)) 
309                        (map (CmmLabel . mkClosureLabel dflags . idName) ids)
310         }
311   where
312         -- Sigh, better map all the ids against the environment in 
313         -- case they've been externalised (see maybeExternaliseId below).
314     remap id = case filter (==id) these of
315                 (id':_) -> returnFC id'
316                 [] -> do { info <- getCgIdInfo id; return (cgIdInfoId info) }
317
318 -- Urgh!  I tried moving the forkStatics call from the rhss of cgTopRhs
319 -- to enclose the listFCs in cgTopBinding, but that tickled the
320 -- statics "error" call in initC.  I DON'T UNDERSTAND WHY!
321
322 cgTopRhs :: Id -> StgRhs -> FCode (Id, CgIdInfo)
323         -- The Id is passed along for setting up a binding...
324         -- It's already been externalised if necessary
325
326 cgTopRhs bndr (StgRhsCon cc con args)
327   = forkStatics (cgTopRhsCon bndr con args)
328
329 cgTopRhs bndr (StgRhsClosure cc bi fvs upd_flag srt args body)
330   = ASSERT(null fvs)    -- There should be no free variables
331     setSRTLabel (mkSRTLabel (idName bndr)) $ 
332     forkStatics (cgTopRhsClosure bndr cc bi srt upd_flag args body)
333 \end{code}
334
335
336 %************************************************************************
337 %*                                                                      *
338 \subsection{Stuff to support splitting}
339 %*                                                                      *
340 %************************************************************************
341
342 If we're splitting the object, we need to externalise all the top-level names
343 (and then make sure we only use the externalised one in any C label we use
344 which refers to this name).
345
346 \begin{code}
347 maybeExternaliseId :: Id -> FCode Id
348 maybeExternaliseId id
349   | opt_EnsureSplittableC,      -- Externalise the name for -split-objs
350     isInternalName name = do { mod <- moduleName
351                              ; returnFC (setIdName id (externalise mod)) }
352   | otherwise           = returnFC id
353   where
354     externalise mod = mkExternalName uniq mod new_occ Nothing loc
355     name    = idName id
356     uniq    = nameUnique name
357     new_occ = mkLocalOcc uniq (nameOccName name)
358     loc     = nameSrcLoc name
359         -- We want to conjure up a name that can't clash with any
360         -- existing name.  So we generate
361         --      Mod_$L243foo
362         -- where 243 is the unique.
363 \end{code}