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