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