2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
8 This module says how things get going at the top level.
10 @codeGen@ is the interface to the outside world. The \tr{cgTop*}
11 functions drive the mangling of top-level bindings.
14 module CodeGen ( codeGen ) where
16 #include "HsVersions.h"
18 -- Kludge (??) so that CgExpr is reached via at least one non-SOURCE
19 -- import. Before, that wasn't the case, and CM therefore didn't
20 -- bother to compile it.
21 import CgExpr ( {-NOTHING!-} ) -- DO NOT DELETE THIS IMPORT
61 -> [Module] -- directly-imported modules
62 -> CollectedCCs -- (Local/global) cost-centres needing declaring/registering.
63 -> [(StgBinding,[(Id,[Id])])] -- Bindings to convert, with SRTs
67 codeGen dflags this_mod data_tycons foreign_stubs imported_mods
68 cost_centre_info stg_binds hpc_info
70 { showPass dflags "CodeGen"
71 ; let way = buildTag dflags
72 main_mod = mainModIs dflags
75 -- ; mapM_ (\x -> seq x (return ())) data_tycons
77 ; code_stuff <- initC dflags this_mod $ do
78 { cmm_binds <- mapM (getCmm . cgTopBinding dflags) stg_binds
79 ; cmm_tycons <- mapM cgTyCon data_tycons
80 ; cmm_init <- getCmm (mkModuleInit dflags way cost_centre_info
82 foreign_stubs imported_mods hpc_info)
83 ; return (cmm_binds ++ concat cmm_tycons ++ [cmm_init])
85 -- Put datatype_stuff after code_stuff, because the
86 -- datatype closure table (for enumeration types) to
87 -- (say) PrelBase_True_closure, which is defined in
90 ; dumpIfSet_dyn dflags Opt_D_dump_cmm "Cmm" (pprCmms code_stuff)
95 %************************************************************************
97 \subsection[codegen-init]{Module initialisation code}
99 %************************************************************************
101 /* -----------------------------------------------------------------------------
102 Module initialisation
104 The module initialisation code looks like this, roughly:
107 JMP_(__stginit_Foo_1_p)
110 FN(__stginit_Foo_1_p) {
114 We have one version of the init code with a module version and the
115 'way' attached to it. The version number helps to catch cases
116 where modules are not compiled in dependency order before being
117 linked: if a module has been compiled since any modules which depend on
118 it, then the latter modules will refer to a different version in their
119 init blocks and a link error will ensue.
121 The 'way' suffix helps to catch cases where modules compiled in different
122 ways are linked together (eg. profiled and non-profiled).
124 We provide a plain, unadorned, version of the module init code
125 which just jumps to the version with the label and way attached. The
126 reason for this is that when using foreign exports, the caller of
127 startupHaskell() must supply the name of the init function for the "top"
128 module in the program, and we don't want to require that this name
129 has the version and way info appended to it.
130 -------------------------------------------------------------------------- */
132 We initialise the module tree by keeping a work-stack,
134 * that grows downward
135 * Sp points to the last occupied slot
141 -> String -- the "way"
142 -> CollectedCCs -- cost centre info
144 -> Module -- name of the Main module
149 mkModuleInit dflags way cost_centre_info this_mod main_mod foreign_stubs imported_mods hpc_info
150 = do { -- Allocate the static boolean that records if this
151 -- module has been registered already
152 emitData Data [CmmDataLabel moduleRegdLabel,
153 CmmStaticLit zeroCLit]
156 hpcTable this_mod hpc_info
158 -- we emit a recursive descent module search for all modules
159 -- and *choose* to chase it in :Main, below.
160 -- In this way, Hpc enabled modules can interact seamlessly with
161 -- not Hpc enabled moduled, provided Main is compiled with Hpc.
163 ; emitSimpleProc real_init_lbl $ do
164 { ret_blk <- forkLabelledCode ret_code
166 ; init_blk <- forkLabelledCode $ do
167 { mod_init_code; stmtC (CmmBranch ret_blk) }
169 ; stmtC (CmmCondBranch (cmmNeWord (CmmLit zeroCLit) mod_reg_val)
171 ; stmtC (CmmBranch init_blk)
174 -- Make the "plain" procedure jump to the "real" init procedure
175 ; emitSimpleProc plain_init_lbl jump_to_init
177 -- When compiling the module in which the 'main' function lives,
178 -- (that is, this_mod == main_mod)
179 -- we inject an extra stg_init procedure for stg_init_ZCMain, for the
180 -- RTS to invoke. We must consult the -main-is flag in case the
181 -- user specified a different function to Main.main
183 -- Notice that the recursive descent is optional, depending on what options
186 ; whenC (this_mod == main_mod)
187 (emitSimpleProc plain_main_init_lbl rec_descent_init)
190 this_pkg = thisPackage dflags
192 plain_init_lbl = mkPlainModuleInitLabel this_pkg this_mod
193 real_init_lbl = mkModuleInitLabel this_pkg this_mod way
194 plain_main_init_lbl = mkPlainModuleInitLabel this_pkg rOOT_MAIN
196 jump_to_init = stmtC (CmmJump (mkLblExpr real_init_lbl) [])
198 mod_reg_val = CmmLoad (mkLblExpr moduleRegdLabel) wordRep
200 -- Main refers to GHC.TopHandler.runIO, so make sure we call the
201 -- init function for GHC.TopHandler.
203 | this_mod == main_mod = [gHC_TOP_HANDLER]
207 { -- Set mod_reg to 1 to record that we've been here
208 stmtC (CmmStore (mkLblExpr moduleRegdLabel) (CmmLit (mkIntCLit 1)))
210 ; whenC (opt_SccProfilingOn) $ do
211 initCostCentres cost_centre_info
214 initHpc this_mod hpc_info
216 ; mapCs (registerModuleImport this_pkg way)
217 (imported_mods++extra_imported_mods)
221 -- The return-code pops the work stack by
222 -- incrementing Sp, and then jumpd to the popped item
223 ret_code = stmtsC [ CmmAssign spReg (cmmRegOffW spReg 1)
224 , CmmJump (CmmLoad (cmmRegOffW spReg (-1)) wordRep) [] ]
227 rec_descent_init = if opt_SccProfilingOn || opt_Hpc
231 -----------------------
232 registerModuleImport :: PackageId -> String -> Module -> Code
233 registerModuleImport this_pkg way mod
236 | otherwise -- Push the init procedure onto the work stack
237 = stmtsC [ CmmAssign spReg (cmmRegOffW spReg (-1))
238 , CmmStore (CmmReg spReg) (mkLblExpr (mkModuleInitLabel this_pkg mod way)) ]
243 Cost-centre profiling: Besides the usual stuff, we must produce
244 declarations for the cost-centres defined in this module;
246 (The local cost-centres involved in this are passed into the
250 initCostCentres :: CollectedCCs -> Code
251 -- Emit the declarations, and return code to register them
252 initCostCentres (local_CCs, ___extern_CCs, singleton_CCSs)
253 | not opt_SccProfilingOn = nopC
255 = do { mapM_ emitCostCentreDecl local_CCs
256 ; mapM_ emitCostCentreStackDecl singleton_CCSs
257 ; mapM_ emitRegisterCC local_CCs
258 ; mapM_ emitRegisterCCS singleton_CCSs
262 %************************************************************************
264 \subsection[codegen-top-bindings]{Converting top-level STG bindings}
266 %************************************************************************
268 @cgTopBinding@ is only used for top-level bindings, since they need
269 to be allocated statically (not in the heap) and need to be labelled.
270 No unboxed bindings can happen at top level.
272 In the code below, the static bindings are accumulated in the
273 @MkCgState@, and transferred into the ``statics'' slot by @forkStatics@.
274 This is so that we can write the top level processing in a compositional
275 style, with the increasing static environment being plumbed as a state
279 cgTopBinding :: DynFlags -> (StgBinding,[(Id,[Id])]) -> Code
280 cgTopBinding dflags (StgNonRec id rhs, srts)
281 = do { id' <- maybeExternaliseId dflags id
282 ; mapM_ (mkSRT (thisPackage dflags) [id']) srts
283 ; (id,info) <- cgTopRhs id' rhs
284 ; addBindC id info -- Add the *un-externalised* Id to the envt,
285 -- so we find it when we look up occurrences
288 cgTopBinding dflags (StgRec pairs, srts)
289 = do { let (bndrs, rhss) = unzip pairs
290 ; bndrs' <- mapFCs (maybeExternaliseId dflags) bndrs
291 ; let pairs' = zip bndrs' rhss
292 ; mapM_ (mkSRT (thisPackage dflags) bndrs') srts
293 ; _new_binds <- fixC (\ new_binds -> do
294 { addBindsC new_binds
295 ; mapFCs ( \ (b,e) -> cgTopRhs b e ) pairs' })
298 mkSRT :: PackageId -> [Id] -> (Id,[Id]) -> Code
299 mkSRT this_pkg these (id,[]) = nopC
300 mkSRT this_pkg these (id,ids)
301 = do { ids <- mapFCs remap ids
303 ; emitRODataLits (mkSRTLabel (idName id))
304 (map (CmmLabel . mkClosureLabel this_pkg . idName) ids)
307 -- Sigh, better map all the ids against the environment in
308 -- case they've been externalised (see maybeExternaliseId below).
309 remap id = case filter (==id) these of
310 (id':_) -> returnFC id'
311 [] -> do { info <- getCgIdInfo id; return (cgIdInfoId info) }
313 -- Urgh! I tried moving the forkStatics call from the rhss of cgTopRhs
314 -- to enclose the listFCs in cgTopBinding, but that tickled the
315 -- statics "error" call in initC. I DON'T UNDERSTAND WHY!
317 cgTopRhs :: Id -> StgRhs -> FCode (Id, CgIdInfo)
318 -- The Id is passed along for setting up a binding...
319 -- It's already been externalised if necessary
321 cgTopRhs bndr (StgRhsCon cc con args)
322 = forkStatics (cgTopRhsCon bndr con args)
324 cgTopRhs bndr (StgRhsClosure cc bi fvs upd_flag srt args body)
325 = ASSERT(null fvs) -- There should be no free variables
326 setSRTLabel (mkSRTLabel (idName bndr)) $
327 forkStatics (cgTopRhsClosure bndr cc bi srt upd_flag args body)
331 %************************************************************************
333 \subsection{Stuff to support splitting}
335 %************************************************************************
337 If we're splitting the object, we need to externalise all the top-level names
338 (and then make sure we only use the externalised one in any C label we use
339 which refers to this name).
342 maybeExternaliseId :: DynFlags -> Id -> FCode Id
343 maybeExternaliseId dflags id
344 | dopt Opt_SplitObjs dflags, -- Externalise the name for -split-objs
345 isInternalName name = do { mod <- getModuleName
346 ; returnFC (setIdName id (externalise mod)) }
347 | otherwise = returnFC id
349 externalise mod = mkExternalName uniq mod new_occ loc
351 uniq = nameUnique name
352 new_occ = mkLocalOcc uniq (nameOccName name)
353 loc = nameSrcLoc name
354 -- We want to conjure up a name that can't clash with any
355 -- existing name. So we generate
357 -- where 243 is the unique.