2 % (c) The University of Glasgow 2000
4 \section[ByteCodeGen]{Generate bytecode from Core}
7 module ByteCodeGen ( UnlinkedBCO, UnlinkedBCOExpr, ItblEnv, ClosureEnv, HValue,
9 byteCodeGen, coreExprToBCOs,
10 linkIModules, linkIExpr
13 #include "HsVersions.h"
16 import Name ( Name, getName, nameModule, mkSysLocalName, toRdrName )
17 import RdrName ( rdrNameOcc, rdrNameModule )
18 import OccName ( occNameString )
19 import Id ( Id, idType, isDataConId_maybe, mkVanillaId )
20 import OrdList ( OrdList, consOL, snocOL, appOL, unitOL,
21 nilOL, toOL, concatOL, fromOL )
22 import FiniteMap ( FiniteMap, addListToFM, listToFM, filterFM,
23 addToFM, lookupFM, fmToList, emptyFM, plusFM )
25 import PprCore ( pprCoreExpr, pprCoreAlt )
26 import Literal ( Literal(..), literalPrimRep )
27 import PrimRep ( PrimRep(..) )
28 import CoreFVs ( freeVars )
29 import Type ( typePrimRep )
30 import DataCon ( DataCon, dataConTag, fIRST_TAG, dataConTyCon,
32 import TyCon ( TyCon, tyConFamilySize, isDataTyCon, tyConDataCons )
33 import Class ( Class, classTyCon )
34 import Util ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem, global )
35 import Var ( isTyVar )
36 import VarSet ( VarSet, varSetElems )
37 import PrimRep ( getPrimRepSize, isFollowableRep )
38 import Constants ( wORD_SIZE )
39 import CmdLineOpts ( DynFlags, DynFlag(..) )
40 import ErrUtils ( showPass, dumpIfSet_dyn )
41 import ClosureInfo ( mkVirtHeapOffsets )
42 import Module ( ModuleName, moduleName, moduleNameFS )
43 import Unique ( mkPseudoUnique3 )
44 import Linker ( lookupSymbol )
46 import List ( intersperse )
47 import Monad ( foldM )
49 import MArray ( castSTUArray,
50 newFloatArray, writeFloatArray,
51 newDoubleArray, writeDoubleArray,
52 newIntArray, writeIntArray,
53 newAddrArray, writeAddrArray )
54 import Foreign ( Storable(..), Word8, Word16, Word32, Ptr(..),
55 malloc, castPtr, plusPtr )
56 import Addr ( Word, addrToInt, nullAddr )
57 import Bits ( Bits(..), shiftR )
59 import PrelAddr ( Addr(..) )
60 import PrelGHC ( BCO#, newBCO#, unsafeCoerce#,
61 ByteArray#, Array#, addrToHValue# )
62 import IOExts ( IORef, fixIO )
64 import PrelArr ( Array(..) )
65 import PrelIOBase ( IO(..) )
69 %************************************************************************
71 \subsection{Functions visible from outside this module.}
73 %************************************************************************
77 byteCodeGen :: DynFlags
80 -> IO ([UnlinkedBCO], ItblEnv)
81 byteCodeGen dflags binds local_tycons local_classes
82 = do showPass dflags "ByteCodeGen"
83 let tycs = local_tycons ++ map classTyCon local_classes
84 itblenv <- mkITbls tycs
86 let flatBinds = concatMap getBind binds
87 getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
88 getBind (Rec binds) = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
89 final_state = runBc (BcM_State [] 0)
90 (mapBc schemeR flatBinds `thenBc_` returnBc ())
91 (BcM_State proto_bcos final_ctr) = final_state
93 dumpIfSet_dyn dflags Opt_D_dump_BCOs
94 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
96 bcos <- mapM assembleBCO proto_bcos
98 return (bcos, itblenv)
101 -- Returns: (the root BCO for this expression,
102 -- a list of auxilary BCOs resulting from compiling closures)
103 coreExprToBCOs :: DynFlags
105 -> IO UnlinkedBCOExpr
106 coreExprToBCOs dflags expr
107 = do showPass dflags "ByteCodeGen"
109 -- create a totally bogus name for the top-level BCO; this
110 -- should be harmless, since it's never used for anything
111 let invented_name = mkSysLocalName (mkPseudoUnique3 0) SLIT("Expr-Top-Level")
112 let invented_id = mkVanillaId invented_name (panic "invented_id's type")
114 let (BcM_State all_proto_bcos final_ctr)
115 = runBc (BcM_State [] 0)
116 (schemeR (invented_id, freeVars expr))
117 dumpIfSet_dyn dflags Opt_D_dump_BCOs
118 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr all_proto_bcos)))
121 = case filter ((== invented_name).nameOfProtoBCO) all_proto_bcos of
122 [root_bco] -> root_bco
124 = filter ((/= invented_name).nameOfProtoBCO) all_proto_bcos
126 auxiliary_bcos <- mapM assembleBCO auxiliary_proto_bcos
127 root_bco <- assembleBCO root_proto_bco
129 return (root_bco, auxiliary_bcos)
133 linkIModules :: ItblEnv -- incoming global itbl env; returned updated
134 -> ClosureEnv -- incoming global closure env; returned updated
135 -> [([UnlinkedBCO], ItblEnv)]
136 -> IO ([HValue], ItblEnv, ClosureEnv)
137 linkIModules gie gce mods
138 = do let (bcoss, ies) = unzip mods
140 final_gie = foldr plusFM gie ies
141 (final_gce, linked_bcos) <- linkSomeBCOs final_gie gce bcos
142 return (linked_bcos, final_gie, final_gce)
145 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
146 -> IO HValue -- IO BCO# really
147 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
148 = do (aux_ce, _) <- linkSomeBCOs ie ce aux_ul_bcos
149 (_, [root_bco]) <- linkSomeBCOs ie aux_ce [root_ul_bco]
152 -- Link a bunch of BCOs and return them + updated closure env.
153 linkSomeBCOs :: ItblEnv -> ClosureEnv -> [UnlinkedBCO]
154 -> IO (ClosureEnv, [HValue])
155 linkSomeBCOs ie ce_in ul_bcos
156 = do let nms = map nameOfUnlinkedBCO ul_bcos
158 ( \ hvs -> let ce_out = addListToFM ce_in (zipLazily nms hvs)
159 in mapM (linkBCO ie ce_out) ul_bcos )
160 let ce_out = addListToFM ce_in (zip nms hvals)
161 return (ce_out, hvals)
163 -- A lazier zip, in which no demand is propagated to the second
164 -- list unless some demand is propagated to the snd of one of the
165 -- result list elems.
167 zipLazily (x:xs) ys = (x, head ys) : zipLazily xs (tail ys)
172 (SizedSeq Word16) -- insns
173 (SizedSeq Word) -- literals
174 (SizedSeq Name) -- ptrs
175 (SizedSeq Name) -- itbl refs
177 nameOfUnlinkedBCO (UnlinkedBCO nm _ _ _ _) = nm
179 -- When translating expressions, we need to distinguish the root
180 -- BCO for the expression
181 type UnlinkedBCOExpr = (UnlinkedBCO, [UnlinkedBCO])
183 instance Outputable UnlinkedBCO where
184 ppr (UnlinkedBCO nm insns lits ptrs itbls)
185 = sep [text "BCO", ppr nm, text "with",
186 int (sizeSS insns), text "insns",
187 int (sizeSS lits), text "lits",
188 int (sizeSS ptrs), text "ptrs",
189 int (sizeSS itbls), text "itbls"]
192 -- these need a proper home
193 type ItblEnv = FiniteMap Name (Ptr StgInfoTable)
194 type ClosureEnv = FiniteMap Name HValue
195 data HValue = HValue -- dummy type, actually a pointer to some Real Code.
197 -- remove all entries for a given set of modules from the environment
198 filterNameMap :: [ModuleName] -> FiniteMap Name a -> FiniteMap Name a
199 filterNameMap mods env
200 = filterFM (\n _ -> moduleName (nameModule n) `notElem` mods) env
203 %************************************************************************
205 \subsection{Bytecodes, and Outputery.}
207 %************************************************************************
211 type LocalLabel = Int
214 -- Messing with the stack
216 -- Push locals (existing bits of the stack)
217 | PUSH_L Int{-offset-}
218 | PUSH_LL Int Int{-2 offsets-}
219 | PUSH_LLL Int Int Int{-3 offsets-}
222 -- Push an alt continuation
223 | PUSH_AS Name PrimRep -- push alts and BCO_ptr_ret_info
224 -- PrimRep so we know which itbl
226 | PUSH_UBX Literal Int
227 -- push this int/float/double, NO TAG, on the stack
228 -- Int is # of words to copy from literal pool
229 | PUSH_TAG Int -- push this tag on the stack
231 | SLIDE Int{-this many-} Int{-down by this much-}
232 -- To do with the heap
233 | ALLOC Int -- make an AP_UPD with this many payload words, zeroed
234 | MKAP Int{-ptr to AP_UPD is this far down stack-} Int{-# words-}
235 | UNPACK Int -- unpack N ptr words from t.o.s Constr
236 | UPK_TAG Int Int Int
237 -- unpack N non-ptr words from offset M in constructor
238 -- K words down the stack
240 -- after assembly, the DataCon is an index into the
242 -- For doing case trees
244 | TESTLT_I Int LocalLabel
245 | TESTEQ_I Int LocalLabel
246 | TESTLT_F Float LocalLabel
247 | TESTEQ_F Float LocalLabel
248 | TESTLT_D Double LocalLabel
249 | TESTEQ_D Double LocalLabel
251 -- The Int value is a constructor number and therefore
252 -- stored in the insn stream rather than as an offset into
254 | TESTLT_P Int LocalLabel
255 | TESTEQ_P Int LocalLabel
258 -- To Infinity And Beyond
261 -- unboxed value on TOS. Use tag to find underlying ret itbl
262 -- and return as per that.
265 instance Outputable BCInstr where
266 ppr (ARGCHECK n) = text "ARGCHECK" <+> int n
267 ppr (PUSH_L offset) = text "PUSH_L " <+> int offset
268 ppr (PUSH_LL o1 o2) = text "PUSH_LL " <+> int o1 <+> int o2
269 ppr (PUSH_LLL o1 o2 o3) = text "PUSH_LLL" <+> int o1 <+> int o2 <+> int o3
270 ppr (PUSH_G nm) = text "PUSH_G " <+> ppr nm
271 ppr (PUSH_AS nm pk) = text "PUSH_AS " <+> ppr nm <+> ppr pk
272 ppr (PUSH_UBX lit nw) = text "PUSH_UBX" <+> parens (int nw) <+> ppr lit
273 ppr (PUSH_TAG n) = text "PUSH_TAG" <+> int n
274 ppr (SLIDE n d) = text "SLIDE " <+> int n <+> int d
275 ppr (ALLOC sz) = text "ALLOC " <+> int sz
276 ppr (MKAP offset sz) = text "MKAP " <+> int sz <+> text "words,"
277 <+> int offset <+> text "stkoff"
278 ppr (UNPACK sz) = text "UNPACK " <+> int sz
279 ppr (UPK_TAG n m k) = text "UPK_TAG " <+> int n <> text "words"
280 <+> int m <> text "conoff"
281 <+> int k <> text "stkoff"
282 ppr (PACK dcon sz) = text "PACK " <+> ppr dcon <+> ppr sz
283 ppr (LABEL lab) = text "__" <> int lab <> colon
284 ppr (TESTLT_I i lab) = text "TESTLT_I" <+> int i <+> text "__" <> int lab
285 ppr (TESTEQ_I i lab) = text "TESTEQ_I" <+> int i <+> text "__" <> int lab
286 ppr (TESTLT_F f lab) = text "TESTLT_F" <+> float f <+> text "__" <> int lab
287 ppr (TESTEQ_F f lab) = text "TESTEQ_F" <+> float f <+> text "__" <> int lab
288 ppr (TESTLT_D d lab) = text "TESTLT_D" <+> double d <+> text "__" <> int lab
289 ppr (TESTEQ_D d lab) = text "TESTEQ_D" <+> double d <+> text "__" <> int lab
290 ppr (TESTLT_P i lab) = text "TESTLT_P" <+> int i <+> text "__" <> int lab
291 ppr (TESTEQ_P i lab) = text "TESTEQ_P" <+> int i <+> text "__" <> int lab
292 ppr CASEFAIL = text "CASEFAIL"
293 ppr ENTER = text "ENTER"
294 ppr (RETURN pk) = text "RETURN " <+> ppr pk
296 instance Outputable a => Outputable (ProtoBCO a) where
297 ppr (ProtoBCO name instrs origin)
298 = (text "ProtoBCO" <+> ppr name <> colon)
299 $$ nest 6 (vcat (map ppr instrs))
301 Left alts -> vcat (map (pprCoreAlt.deAnnAlt) alts)
302 Right rhs -> pprCoreExpr (deAnnotate rhs)
305 %************************************************************************
307 \subsection{Compilation schema for the bytecode generator.}
309 %************************************************************************
313 type BCInstrList = OrdList BCInstr
316 = ProtoBCO a -- name, in some sense
318 -- what the BCO came from
319 (Either [AnnAlt Id VarSet]
322 nameOfProtoBCO (ProtoBCO nm insns origin) = nm
325 type Sequel = Int -- back off to this depth before ENTER
327 -- Maps Ids to the offset from the stack _base_ so we don't have
328 -- to mess with it after each push/pop.
329 type BCEnv = FiniteMap Id Int -- To find vars on the stack
332 -- Create a BCO and do a spot of peephole optimisation on the insns
334 mkProtoBCO nm instrs_ordlist origin
335 = ProtoBCO nm (id {-peep-} (fromOL instrs_ordlist)) origin
337 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
338 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
339 peep (PUSH_L off1 : PUSH_L off2 : rest)
340 = PUSH_LL off1 off2 : peep rest
347 -- Compile code for the right hand side of a let binding.
348 -- Park the resulting BCO in the monad. Also requires the
349 -- variable to which this value was bound, so as to give the
350 -- resulting BCO a name.
351 schemeR :: (Id, AnnExpr Id VarSet) -> BcM ()
356 $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
357 $$ pprCoreExpr (deAnnotate rhs)
363 = schemeR_wrk rhs nm (collect [] rhs)
366 collect xs (_, AnnLam x e)
367 = collect (if isTyVar x then xs else (x:xs)) e
368 collect xs not_lambda
369 = (reverse xs, not_lambda)
371 schemeR_wrk original_body nm (args, body)
372 = let fvs = filter (not.isTyVar) (varSetElems (fst original_body))
373 all_args = fvs ++ reverse args
374 szsw_args = map taggedIdSizeW all_args
375 szw_args = sum szsw_args
376 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
377 argcheck = {-if null args then nilOL else-} unitOL (ARGCHECK szw_args)
379 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
380 emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) (Right original_body))
382 -- Let szsw be the sizes in words of some items pushed onto the stack,
383 -- which has initial depth d'. Return the values which the stack environment
384 -- should map these items to.
385 mkStackOffsets :: Int -> [Int] -> [Int]
386 mkStackOffsets original_depth szsw
387 = map (subtract 1) (tail (scanl (+) original_depth szsw))
389 -- Compile code to apply the given expression to the remaining args
390 -- on the stack, returning a HNF.
391 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
393 -- Delegate tail-calls to schemeT.
394 schemeE d s p e@(fvs, AnnApp f a)
395 = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnApp f a))
396 schemeE d s p e@(fvs, AnnVar v)
397 | isFollowableRep v_rep
398 = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnVar v))
400 = -- returning an unboxed value. Heave it on the stack, SLIDE, and RETURN.
401 let (push, szw) = pushAtom True d p (AnnVar v)
402 in returnBc (push -- value onto stack
403 `snocOL` SLIDE szw (d-s) -- clear to sequel
404 `snocOL` RETURN v_rep) -- go
406 v_rep = typePrimRep (idType v)
408 schemeE d s p (fvs, AnnLit literal)
409 = let (push, szw) = pushAtom True d p (AnnLit literal)
410 l_rep = literalPrimRep literal
411 in returnBc (push -- value onto stack
412 `snocOL` SLIDE szw (d-s) -- clear to sequel
413 `snocOL` RETURN l_rep) -- go
415 schemeE d s p (fvs, AnnLet binds b)
416 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
417 AnnRec xs_n_rhss -> unzip xs_n_rhss
419 fvss = map (filter (not.isTyVar).varSetElems.fst) rhss
421 -- Sizes of tagged free vars, + 1 for the fn
422 sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
424 -- This p', d' defn is safe because all the items being pushed
425 -- are ptrs, so all have size 1. d' and p' reflect the stack
426 -- after the closures have been allocated in the heap (but not
427 -- filled in), and pointers to them parked on the stack.
428 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
431 infos = zipE4 fvss sizes xs [n, n-1 .. 1]
432 zipE = zipEqual "schemeE"
433 zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
435 -- ToDo: don't build thunks for things with no free variables
436 buildThunk dd ([], size, id, off)
437 = PUSH_G (getName id)
438 `consOL` unitOL (MKAP (off+size-1) size)
439 buildThunk dd ((fv:fvs), size, id, off)
440 = case pushAtom True dd p' (AnnVar fv) of
441 (push_code, pushed_szw)
443 buildThunk (dd+pushed_szw) (fvs, size, id, off)
445 thunkCode = concatOL (map (buildThunk d') infos)
446 allocCode = toOL (map ALLOC sizes)
448 schemeE d' s p' b `thenBc` \ bodyCode ->
449 mapBc schemeR (zip xs rhss) `thenBc_`
450 returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
453 schemeE d s p (fvs, AnnCase scrut bndr alts)
455 -- Top of stack is the return itbl, as usual.
456 -- underneath it is the pointer to the alt_code BCO.
457 -- When an alt is entered, it assumes the returned value is
458 -- on top of the itbl.
461 -- Env and depth in which to compile the alts, not including
462 -- any vars bound by the alts themselves
463 d' = d + ret_frame_sizeW + taggedIdSizeW bndr
464 p' = addToFM p bndr (d' - 1)
466 scrut_primrep = typePrimRep (idType bndr)
468 = case scrut_primrep of
469 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
471 other -> pprPanic "ByteCodeGen.schemeE" (ppr other)
473 -- given an alt, return a discr and code for it.
474 codeAlt alt@(discr, binds_f, rhs)
476 = let binds_r = reverse binds_f
477 binds_r_szsw = map untaggedIdSizeW binds_r
478 binds_szw = sum binds_r_szsw
480 p' (zip binds_r (mkStackOffsets d' binds_r_szsw))
482 unpack_code = mkUnpackCode 0 0 (map (typePrimRep.idType) binds_f)
483 in schemeE d'' s p'' rhs `thenBc` \ rhs_code ->
484 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
486 = ASSERT(null binds_f)
487 schemeE d' s p' rhs `thenBc` \ rhs_code ->
488 returnBc (my_discr alt, rhs_code)
490 my_discr (DEFAULT, binds, rhs) = NoDiscr
491 my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc)
492 my_discr (LitAlt l, binds, rhs)
493 = case l of MachInt i -> DiscrI (fromInteger i)
494 MachFloat r -> DiscrF (fromRational r)
495 MachDouble r -> DiscrD (fromRational r)
498 | not isAlgCase = Nothing
500 = case [dc | (DataAlt dc, _, _) <- alts] of
502 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
505 mapBc codeAlt alts `thenBc` \ alt_stuff ->
506 mkMultiBranch maybe_ncons alt_stuff `thenBc` \ alt_final ->
508 alt_bco_name = getName bndr
509 alt_bco = mkProtoBCO alt_bco_name alt_final (Left alts)
511 schemeE (d + ret_frame_sizeW)
512 (d + ret_frame_sizeW) p scrut `thenBc` \ scrut_code ->
514 emitBc alt_bco `thenBc_`
515 returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
518 schemeE d s p (fvs, AnnNote note body)
522 = pprPanic "ByteCodeGen.schemeE: unhandled case"
523 (pprCoreExpr (deAnnotate other))
526 -- Compile code to do a tail call. Doesn't need to be monadic.
527 schemeT :: Bool -- do tagging?
528 -> Int -- Stack depth
529 -> Sequel -- Sequel depth
530 -> Int -- # arg words so far
531 -> BCEnv -- stack env
535 schemeT enTag d s narg_words p (_, AnnApp f a)
537 AnnType _ -> schemeT enTag d s narg_words p f
539 -> let (push, arg_words) = pushAtom enTag d p (snd a)
541 `appOL` schemeT enTag (d+arg_words) s (narg_words+arg_words) p f
543 schemeT enTag d s narg_words p (_, AnnVar f)
544 | Just con <- isDataConId_maybe f
545 = ASSERT(enTag == False)
546 PACK con narg_words `consOL` (mkSLIDE 1 (d-s-1) `snocOL` ENTER)
548 = ASSERT(enTag == True)
549 let (push, arg_words) = pushAtom True d p (AnnVar f)
551 `appOL` mkSLIDE (narg_words+arg_words) (d - s - narg_words)
555 = if d == 0 then nilOL else unitOL (SLIDE n d)
557 should_args_be_tagged (_, AnnVar v)
558 = case isDataConId_maybe v of
559 Just dcon -> False; Nothing -> True
560 should_args_be_tagged (_, AnnApp f a)
561 = should_args_be_tagged f
562 should_args_be_tagged (_, other)
563 = panic "should_args_be_tagged: tail call to non-con, non-var"
566 -- Make code to unpack a constructor onto the stack, adding
567 -- tags for the unboxed bits. Takes the PrimReps of the constructor's
568 -- arguments, and a travelling offset along both the constructor
569 -- (off_h) and the stack (off_s).
570 mkUnpackCode :: Int -> Int -> [PrimRep] -> BCInstrList
571 mkUnpackCode off_h off_s [] = nilOL
572 mkUnpackCode off_h off_s (r:rs)
574 = let (rs_ptr, rs_nptr) = span isFollowableRep (r:rs)
575 ptrs_szw = sum (map untaggedSizeW rs_ptr)
576 in ASSERT(ptrs_szw == length rs_ptr)
580 `consOL` mkUnpackCode (off_h + ptrs_szw) (off_s + ptrs_szw) rs_nptr
585 DoubleRep -> approved
587 approved = UPK_TAG usizeW off_h off_s `consOL` theRest
588 theRest = mkUnpackCode (off_h + usizeW) (off_s + tsizeW) rs
589 usizeW = untaggedSizeW r
590 tsizeW = taggedSizeW r
592 -- Push an atom onto the stack, returning suitable code & number of
593 -- stack words used. Pushes it either tagged or untagged, since
594 -- pushAtom is used to set up the stack prior to copying into the
595 -- heap for both APs (requiring tags) and constructors (which don't).
597 -- NB this means NO GC between pushing atoms for a constructor and
598 -- copying them into the heap. It probably also means that
599 -- tail calls MUST be of the form atom{atom ... atom} since if the
600 -- expression head was allowed to be arbitrary, there could be GC
601 -- in between pushing the arg atoms and completing the head.
602 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
603 -- isn't a problem; but only if arbitrary graph construction for the
604 -- head doesn't leave this BCO, since GC might happen at the start of
605 -- each BCO (we consult doYouWantToGC there).
607 -- Blargh. JRS 001206
609 -- NB (further) that the env p must map each variable to the highest-
610 -- numbered stack slot for it. For example, if the stack has depth 4
611 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
612 -- the tag in stack[5], the stack will have depth 6, and p must map v to
613 -- 5 and not to 4. Stack locations are numbered from zero, so a depth
614 -- 6 stack has valid words 0 .. 5.
616 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
617 pushAtom tagged d p (AnnVar v)
618 = let str = "\npushAtom " ++ showSDocDebug (ppr v) ++ ", depth = " ++ show d
620 showSDocDebug (nest 4 (vcat (map ppr (fmToList p))))
622 showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
623 ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
624 str' = if str == str then str else str
627 = case lookupBCEnv_maybe p v of
628 Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), sz_t)
629 Nothing -> ASSERT(sz_t == 1) (unitOL (PUSH_G nm), sz_t)
632 sz_t = taggedIdSizeW v
633 sz_u = untaggedIdSizeW v
634 nwords = if tagged then sz_t else sz_u
639 pushAtom True d p (AnnLit lit)
640 = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
641 in (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
643 pushAtom False d p (AnnLit lit)
645 MachInt i -> code IntRep
646 MachFloat r -> code FloatRep
647 MachDouble r -> code DoubleRep
648 MachChar c -> code CharRep
651 = let size_host_words = untaggedSizeW rep
652 in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
654 pushAtom tagged d p (AnnApp f (_, AnnType _))
655 = pushAtom tagged d p (snd f)
657 pushAtom tagged d p other
658 = pprPanic "ByteCodeGen.pushAtom"
659 (pprCoreExpr (deAnnotate (undefined, other)))
662 -- Given a bunch of alts code and their discrs, do the donkey work
663 -- of making a multiway branch using a switch tree.
664 -- What a load of hassle!
665 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
666 -- a hint; generates better code
667 -- Nothing is always safe
668 -> [(Discr, BCInstrList)]
670 mkMultiBranch maybe_ncons raw_ways
671 = let d_way = filter (isNoDiscr.fst) raw_ways
672 notd_ways = naturalMergeSortLe
673 (\w1 w2 -> leAlt (fst w1) (fst w2))
674 (filter (not.isNoDiscr.fst) raw_ways)
676 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
677 mkTree [] range_lo range_hi = returnBc the_default
679 mkTree [val] range_lo range_hi
680 | range_lo `eqAlt` range_hi
683 = getLabelBc `thenBc` \ label_neq ->
684 returnBc (mkTestEQ (fst val) label_neq
686 `appOL` unitOL (LABEL label_neq)
687 `appOL` the_default))
689 mkTree vals range_lo range_hi
690 = let n = length vals `div` 2
691 vals_lo = take n vals
692 vals_hi = drop n vals
693 v_mid = fst (head vals_hi)
695 getLabelBc `thenBc` \ label_geq ->
696 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
697 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
698 returnBc (mkTestLT v_mid label_geq
700 `appOL` unitOL (LABEL label_geq)
704 = case d_way of [] -> unitOL CASEFAIL
707 -- None of these will be needed if there are no non-default alts
708 (mkTestLT, mkTestEQ, init_lo, init_hi)
710 = panic "mkMultiBranch: awesome foursome"
712 = case fst (head notd_ways) of {
713 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
714 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
717 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
718 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
721 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
722 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
725 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
726 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
731 (algMinBound, algMaxBound)
732 = case maybe_ncons of
733 Just n -> (fIRST_TAG, fIRST_TAG + n - 1)
734 Nothing -> (minBound, maxBound)
736 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
737 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
738 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
739 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
740 NoDiscr `eqAlt` NoDiscr = True
743 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
744 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
745 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
746 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
747 NoDiscr `leAlt` NoDiscr = True
750 isNoDiscr NoDiscr = True
753 dec (DiscrI i) = DiscrI (i-1)
754 dec (DiscrP i) = DiscrP (i-1)
755 dec other = other -- not really right, but if you
756 -- do cases on floating values, you'll get what you deserve
758 -- same snotty comment applies to the following
766 mkTree notd_ways init_lo init_hi
770 %************************************************************************
772 \subsection{Supporting junk for the compilation schemes}
774 %************************************************************************
778 -- Describes case alts
786 instance Outputable Discr where
787 ppr (DiscrI i) = int i
788 ppr (DiscrF f) = text (show f)
789 ppr (DiscrD d) = text (show d)
790 ppr (DiscrP i) = int i
791 ppr NoDiscr = text "DEF"
794 -- Find things in the BCEnv (the what's-on-the-stack-env)
795 -- See comment preceding pushAtom for precise meaning of env contents
796 --lookupBCEnv :: BCEnv -> Id -> Int
798 -- = case lookupFM env nm of
799 -- Nothing -> pprPanic "lookupBCEnv"
800 -- (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
803 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
804 lookupBCEnv_maybe = lookupFM
807 -- When I push one of these on the stack, how much does Sp move by?
808 taggedSizeW :: PrimRep -> Int
810 | isFollowableRep pr = 1
811 | otherwise = 1{-the tag-} + getPrimRepSize pr
814 -- The plain size of something, without tag.
815 untaggedSizeW :: PrimRep -> Int
817 | isFollowableRep pr = 1
818 | otherwise = getPrimRepSize pr
821 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
822 taggedIdSizeW = taggedSizeW . typePrimRep . idType
823 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
827 %************************************************************************
829 \subsection{The bytecode generator's monad}
831 %************************************************************************
835 = BcM_State { bcos :: [ProtoBCO Name], -- accumulates completed BCOs
836 nextlabel :: Int } -- for generating local labels
838 type BcM result = BcM_State -> (result, BcM_State)
840 runBc :: BcM_State -> BcM () -> BcM_State
841 runBc init_st m = case m init_st of { (r,st) -> st }
843 thenBc :: BcM a -> (a -> BcM b) -> BcM b
845 = case expr st of { (result, st') -> cont result st' }
847 thenBc_ :: BcM a -> BcM b -> BcM b
849 = case expr st of { (result, st') -> cont st' }
851 returnBc :: a -> BcM a
852 returnBc result st = (result, st)
854 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
855 mapBc f [] = returnBc []
857 = f x `thenBc` \ r ->
858 mapBc f xs `thenBc` \ rs ->
861 emitBc :: ProtoBCO Name -> BcM ()
863 = ((), st{bcos = bco : bcos st})
865 getLabelBc :: BcM Int
867 = (nextlabel st, st{nextlabel = 1 + nextlabel st})
871 %************************************************************************
873 \subsection{The bytecode assembler}
875 %************************************************************************
877 The object format for bytecodes is: 16 bits for the opcode, and 16 for
878 each field -- so the code can be considered a sequence of 16-bit ints.
879 Each field denotes either a stack offset or number of items on the
880 stack (eg SLIDE), and index into the pointer table (eg PUSH_G), an
881 index into the literal table (eg PUSH_I/D/L), or a bytecode address in
885 -- Top level assembler fn.
886 assembleBCO :: ProtoBCO Name -> IO UnlinkedBCO
888 assembleBCO (ProtoBCO nm instrs origin)
890 -- pass 1: collect up the offsets of the local labels.
891 -- Remember that the first insn starts at offset 1 since offset 0
892 -- (eventually) will hold the total # of insns.
893 label_env = mkLabelEnv emptyFM 1 instrs
895 mkLabelEnv env i_offset [] = env
896 mkLabelEnv env i_offset (i:is)
898 = case i of LABEL n -> addToFM env n i_offset ; _ -> env
899 in mkLabelEnv new_env (i_offset + instrSizeB i) is
902 = case lookupFM label_env lab of
903 Just bco_offset -> bco_offset
904 Nothing -> pprPanic "assembleBCO.findLabel" (int lab)
906 do -- pass 2: generate the instruction, ptr and nonptr bits
907 insns <- return emptySS :: IO (SizedSeq Word16)
908 lits <- return emptySS :: IO (SizedSeq Word)
909 ptrs <- return emptySS :: IO (SizedSeq Name)
910 itbls <- return emptySS :: IO (SizedSeq Name)
911 let init_asm_state = (insns,lits,ptrs,itbls)
912 (final_insns, final_lits, final_ptrs, final_itbls)
913 <- mkBits findLabel init_asm_state instrs
915 return (UnlinkedBCO nm final_insns final_lits final_ptrs final_itbls)
917 -- instrs nonptrs ptrs itbls
918 type AsmState = (SizedSeq Word16, SizedSeq Word, SizedSeq Name, SizedSeq Name)
920 data SizedSeq a = SizedSeq !Int [a]
921 emptySS = SizedSeq 0 []
922 addToSS (SizedSeq n r_xs) x = return (SizedSeq (n+1) (x:r_xs))
923 addListToSS (SizedSeq n r_xs) xs
924 = return (SizedSeq (n + length xs) (reverse xs ++ r_xs))
925 sizeSS (SizedSeq n r_xs) = n
926 listFromSS (SizedSeq n r_xs) = return (reverse r_xs)
929 -- This is where all the action is (pass 2 of the assembler)
930 mkBits :: (Int -> Int) -- label finder
932 -> [BCInstr] -- instructions (in)
935 mkBits findLabel st proto_insns
936 = foldM doInstr st proto_insns
938 doInstr :: AsmState -> BCInstr -> IO AsmState
941 ARGCHECK n -> instr2 st i_ARGCHECK n
942 PUSH_L o1 -> instr2 st i_PUSH_L o1
943 PUSH_LL o1 o2 -> instr3 st i_PUSH_LL o1 o2
944 PUSH_LLL o1 o2 o3 -> instr4 st i_PUSH_LLL o1 o2 o3
945 PUSH_G nm -> do (p, st2) <- ptr st nm
946 instr2 st2 i_PUSH_G p
947 PUSH_AS nm pk -> do (p, st2) <- ptr st nm
948 (np, st3) <- ctoi_itbl st2 pk
949 instr3 st3 i_PUSH_AS p np
950 PUSH_UBX lit nws -> do (np, st2) <- literal st lit
951 instr3 st2 i_PUSH_UBX np nws
952 PUSH_TAG tag -> instr2 st i_PUSH_TAG tag
953 SLIDE n by -> instr3 st i_SLIDE n by
954 ALLOC n -> instr2 st i_ALLOC n
955 MKAP off sz -> instr3 st i_MKAP off sz
956 UNPACK n -> instr2 st i_UNPACK n
957 UPK_TAG n m k -> instr4 st i_UPK_TAG n m k
958 PACK dcon sz -> do (itbl_no,st2) <- itbl st dcon
959 instr3 st2 i_PACK itbl_no sz
960 LABEL lab -> return st
961 TESTLT_I i l -> do (np, st2) <- int st i
962 instr3 st2 i_TESTLT_I np (findLabel l)
963 TESTEQ_I i l -> do (np, st2) <- int st i
964 instr3 st2 i_TESTEQ_I np (findLabel l)
965 TESTLT_F f l -> do (np, st2) <- float st f
966 instr3 st2 i_TESTLT_F np (findLabel l)
967 TESTEQ_F f l -> do (np, st2) <- float st f
968 instr3 st2 i_TESTEQ_F np (findLabel l)
969 TESTLT_D d l -> do (np, st2) <- double st d
970 instr3 st2 i_TESTLT_D np (findLabel l)
971 TESTEQ_D d l -> do (np, st2) <- double st d
972 instr3 st2 i_TESTEQ_D np (findLabel l)
973 TESTLT_P i l -> instr3 st i_TESTLT_P i (findLabel l)
974 TESTEQ_P i l -> instr3 st i_TESTEQ_P i (findLabel l)
975 CASEFAIL -> instr1 st i_CASEFAIL
976 ENTER -> instr1 st i_ENTER
977 RETURN rep -> do (itbl_no,st2) <- itoc_itbl st rep
978 instr2 st2 i_RETURN itbl_no
983 instr1 (st_i0,st_l0,st_p0,st_I0) i1
984 = do st_i1 <- addToSS st_i0 (i2s i1)
985 return (st_i1,st_l0,st_p0,st_I0)
987 instr2 (st_i0,st_l0,st_p0,st_I0) i1 i2
988 = do st_i1 <- addToSS st_i0 (i2s i1)
989 st_i2 <- addToSS st_i1 (i2s i2)
990 return (st_i2,st_l0,st_p0,st_I0)
992 instr3 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3
993 = do st_i1 <- addToSS st_i0 (i2s i1)
994 st_i2 <- addToSS st_i1 (i2s i2)
995 st_i3 <- addToSS st_i2 (i2s i3)
996 return (st_i3,st_l0,st_p0,st_I0)
998 instr4 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3 i4
999 = do st_i1 <- addToSS st_i0 (i2s i1)
1000 st_i2 <- addToSS st_i1 (i2s i2)
1001 st_i3 <- addToSS st_i2 (i2s i3)
1002 st_i4 <- addToSS st_i3 (i2s i4)
1003 return (st_i4,st_l0,st_p0,st_I0)
1005 float (st_i0,st_l0,st_p0,st_I0) f
1006 = do let ws = mkLitF f
1007 st_l1 <- addListToSS st_l0 ws
1008 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1010 double (st_i0,st_l0,st_p0,st_I0) d
1011 = do let ws = mkLitD d
1012 st_l1 <- addListToSS st_l0 ws
1013 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1015 int (st_i0,st_l0,st_p0,st_I0) i
1016 = do let ws = mkLitI i
1017 st_l1 <- addListToSS st_l0 ws
1018 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1020 addr (st_i0,st_l0,st_p0,st_I0) a
1021 = do let ws = mkLitA a
1022 st_l1 <- addListToSS st_l0 ws
1023 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1025 ptr (st_i0,st_l0,st_p0,st_I0) p
1026 = do st_p1 <- addToSS st_p0 p
1027 return (sizeSS st_p0, (st_i0,st_l0,st_p1,st_I0))
1029 itbl (st_i0,st_l0,st_p0,st_I0) dcon
1030 = do st_I1 <- addToSS st_I0 (getName dcon)
1031 return (sizeSS st_I0, (st_i0,st_l0,st_p0,st_I1))
1033 literal st (MachInt j) = int st (fromIntegral j)
1034 literal st (MachFloat r) = float st (fromRational r)
1035 literal st (MachDouble r) = double st (fromRational r)
1036 literal st (MachChar c) = int st c
1039 = addr st ret_itbl_addr
1041 ret_itbl_addr = case pk of
1042 IntRep -> stg_ctoi_ret_R1_info
1043 FloatRep -> stg_ctoi_ret_F1_info
1044 DoubleRep -> stg_ctoi_ret_D1_info
1046 stg_ctoi_ret_F1_info = nullAddr
1047 stg_ctoi_ret_D1_info = nullAddr
1050 = addr st ret_itbl_addr
1052 ret_itbl_addr = case pk of
1053 IntRep -> stg_gc_unbx_r1_info
1054 FloatRep -> stg_gc_f1_info
1055 DoubleRep -> stg_gc_d1_info
1057 foreign label "stg_ctoi_ret_R1_info" stg_ctoi_ret_R1_info :: Addr
1058 --foreign label "stg_ctoi_ret_F1_info" stg_ctoi_ret_F1_info :: Addr
1059 --foreign label "stg_ctoi_ret_D1_info" stg_ctoi_ret_D1_info :: Addr
1061 foreign label "stg_gc_unbx_r1_info" stg_gc_unbx_r1_info :: Addr
1062 foreign label "stg_gc_f1_info" stg_gc_f1_info :: Addr
1063 foreign label "stg_gc_d1_info" stg_gc_d1_info :: Addr
1065 -- The size in bytes of an instruction.
1066 instrSizeB :: BCInstr -> Int
1097 -- Make lists of host-sized words for literals, so that when the
1098 -- words are placed in memory at increasing addresses, the
1099 -- bit pattern is correct for the host's word size and endianness.
1100 mkLitI :: Int -> [Word]
1101 mkLitF :: Float -> [Word]
1102 mkLitD :: Double -> [Word]
1103 mkLitA :: Addr -> [Word]
1107 arr <- newFloatArray ((0::Int),0)
1108 writeFloatArray arr 0 f
1109 f_arr <- castSTUArray arr
1110 w0 <- readWordArray f_arr 0
1117 arr <- newDoubleArray ((0::Int),0)
1118 writeDoubleArray arr 0 d
1119 d_arr <- castSTUArray arr
1120 w0 <- readWordArray d_arr 0
1121 w1 <- readWordArray d_arr 1
1126 arr <- newDoubleArray ((0::Int),0)
1127 writeDoubleArray arr 0 d
1128 d_arr <- castSTUArray arr
1129 w0 <- readWordArray d_arr 0
1135 arr <- newIntArray ((0::Int),0)
1136 writeIntArray arr 0 i
1137 i_arr <- castSTUArray arr
1138 w0 <- readWordArray i_arr 0
1144 arr <- newAddrArray ((0::Int),0)
1145 writeAddrArray arr 0 a
1146 a_arr <- castSTUArray arr
1147 w0 <- readWordArray a_arr 0
1153 %************************************************************************
1155 \subsection{Linking interpretables into something we can run}
1157 %************************************************************************
1162 data BCO# = BCO# ByteArray# -- instrs :: array Word16#
1163 ByteArray# -- literals :: array Word32#
1164 PtrArray# -- ptrs :: Array HValue
1165 ByteArray# -- itbls :: Array Addr#
1168 GLOBAL_VAR(v_cafTable, [], [HValue])
1170 --addCAF :: HValue -> IO ()
1171 --addCAF x = do xs <- readIORef v_cafTable; writeIORef v_cafTable (x:xs)
1173 --bcosToHValue :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr -> IO HValue
1174 --bcosToHValue ie ce (root_bco, other_bcos)
1175 -- = do linked_expr <- linkIExpr ie ce (root_bco, other_bcos)
1176 -- return linked_expr
1178 linkBCO ie ce (UnlinkedBCO nm insnsSS literalsSS ptrsSS itblsSS)
1179 = do insns <- listFromSS insnsSS
1180 literals <- listFromSS literalsSS
1181 ptrs <- listFromSS ptrsSS
1182 itbls <- listFromSS itblsSS
1184 linked_ptrs <- mapM (lookupCE ce) ptrs
1185 linked_itbls <- mapM (lookupIE ie) itbls
1187 let n_insns = sizeSS insnsSS
1188 n_literals = sizeSS literalsSS
1189 n_ptrs = sizeSS ptrsSS
1190 n_itbls = sizeSS itblsSS
1192 let ptrs_arr = array (0, n_ptrs-1) (indexify linked_ptrs)
1194 ptrs_parr = case ptrs_arr of Array lo hi parr -> parr
1196 itbls_arr = array (0, n_itbls-1) (indexify linked_itbls)
1198 itbls_barr = case itbls_arr of UArray lo hi barr -> barr
1200 insns_arr | n_insns > 65535
1201 = panic "linkBCO: >= 64k insns in BCO"
1203 = array (0, n_insns)
1204 (indexify (fromIntegral n_insns:insns))
1205 :: UArray Int Word16
1206 insns_barr = case insns_arr of UArray lo hi barr -> barr
1208 literals_arr = array (0, n_literals-1) (indexify literals)
1210 literals_barr = case literals_arr of UArray lo hi barr -> barr
1212 indexify :: [a] -> [(Int, a)]
1213 indexify xs = zip [0..] xs
1215 BCO bco# <- newBCO insns_barr literals_barr ptrs_parr itbls_barr
1217 return (unsafeCoerce# bco#)
1222 newBCO :: ByteArray# -> ByteArray# -> Array# a -> ByteArray# -> IO BCO
1224 = IO (\s -> case newBCO# a b c d s of (# s1, bco #) -> (# s1, BCO bco #))
1227 lookupCE :: ClosureEnv -> Name -> IO HValue
1229 = case lookupFM ce nm of
1230 Just aa -> return aa
1232 -> do m <- lookupSymbol (nameToCLabel nm "closure")
1234 Just (A# addr) -> case addrToHValue# addr of
1235 (# hval #) -> return hval
1236 Nothing -> pprPanic "ByteCodeGen.lookupCE" (ppr nm)
1238 lookupIE :: ItblEnv -> Name -> IO Addr
1240 = case lookupFM ie con_nm of
1241 Just (Ptr a) -> return a
1243 -> do -- try looking up in the object files.
1244 m <- lookupSymbol (nameToCLabel con_nm "con_info")
1246 Just addr -> return addr
1247 Nothing -> pprPanic "ByteCodeGen.lookupIE" (ppr con_nm)
1249 -- HACK!!! ToDo: cleaner
1250 nameToCLabel :: Name -> String{-suffix-} -> String
1251 nameToCLabel n suffix
1252 = _UNPK_(moduleNameFS (rdrNameModule rn))
1253 ++ '_':occNameString(rdrNameOcc rn) ++ '_':suffix
1254 where rn = toRdrName n
1259 case lookupFM ie con of
1260 Just (Ptr addr) -> return addr
1262 -- try looking up in the object files.
1263 m <- lookupSymbol (nameToCLabel con "con_info")
1265 Just addr -> return addr
1266 Nothing -> pprPanic "linkIExpr" (ppr con)
1268 -- nullary constructors don't have normal _con_info tables.
1269 lookupNullaryCon ie con =
1270 case lookupFM ie con of
1271 Just (Ptr addr) -> return (ConApp addr)
1273 -- try looking up in the object files.
1274 m <- lookupSymbol (nameToCLabel con "closure")
1276 Just (A# addr) -> return (Native (unsafeCoerce# addr))
1277 Nothing -> pprPanic "lookupNullaryCon" (ppr con)
1280 lookupNative ce var =
1281 unsafeInterleaveIO (do
1282 case lookupFM ce var of
1283 Just e -> return (Native e)
1285 -- try looking up in the object files.
1286 let lbl = (nameToCLabel var "closure")
1287 m <- lookupSymbol lbl
1290 -> do addCAF (unsafeCoerce# addr)
1291 return (Native (unsafeCoerce# addr))
1292 Nothing -> pprPanic "linkIExpr" (ppr var)
1295 -- some VarI/VarP refer to top-level interpreted functions; we change
1296 -- them into Natives here.
1298 unsafeInterleaveIO (
1299 case lookupFM ce (getName v) of
1300 Nothing -> return (f v)
1301 Just e -> return (Native e)
1306 %************************************************************************
1308 \subsection{Manufacturing of info tables for DataCons}
1310 %************************************************************************
1314 #if __GLASGOW_HASKELL__ <= 408
1317 type ItblPtr = Ptr StgInfoTable
1320 -- Make info tables for the data decls in this module
1321 mkITbls :: [TyCon] -> IO ItblEnv
1322 mkITbls [] = return emptyFM
1323 mkITbls (tc:tcs) = do itbls <- mkITbl tc
1324 itbls2 <- mkITbls tcs
1325 return (itbls `plusFM` itbls2)
1327 mkITbl :: TyCon -> IO ItblEnv
1329 -- | trace ("TYCON: " ++ showSDoc (ppr tc)) False
1331 | not (isDataTyCon tc)
1333 | n == length dcs -- paranoia; this is an assertion.
1334 = make_constr_itbls dcs
1336 dcs = tyConDataCons tc
1337 n = tyConFamilySize tc
1340 cONSTR = 1 -- as defined in ghc/includes/ClosureTypes.h
1342 -- Assumes constructors are numbered from zero, not one
1343 make_constr_itbls :: [DataCon] -> IO ItblEnv
1344 make_constr_itbls cons
1346 = do is <- mapM mk_vecret_itbl (zip cons [0..])
1347 return (listToFM is)
1349 = do is <- mapM mk_dirret_itbl (zip cons [0..])
1350 return (listToFM is)
1352 mk_vecret_itbl (dcon, conNo)
1353 = mk_itbl dcon conNo (vecret_entry conNo)
1354 mk_dirret_itbl (dcon, conNo)
1355 = mk_itbl dcon conNo stg_interp_constr_entry
1357 mk_itbl :: DataCon -> Int -> Addr -> IO (Name,ItblPtr)
1358 mk_itbl dcon conNo entry_addr
1359 = let (tot_wds, ptr_wds, _)
1360 = mkVirtHeapOffsets typePrimRep (dataConRepArgTys dcon)
1362 nptrs = tot_wds - ptr_wds
1363 itbl = StgInfoTable {
1364 ptrs = fromIntegral ptrs, nptrs = fromIntegral nptrs,
1365 tipe = fromIntegral cONSTR,
1366 srtlen = fromIntegral conNo,
1367 code0 = fromIntegral code0, code1 = fromIntegral code1,
1368 code2 = fromIntegral code2, code3 = fromIntegral code3,
1369 code4 = fromIntegral code4, code5 = fromIntegral code5,
1370 code6 = fromIntegral code6, code7 = fromIntegral code7
1372 -- Make a piece of code to jump to "entry_label".
1373 -- This is the only arch-dependent bit.
1374 -- On x86, if entry_label has an address 0xWWXXYYZZ,
1375 -- emit movl $0xWWXXYYZZ,%eax ; jmp *%eax
1377 -- B8 ZZ YY XX WW FF E0
1378 (code0,code1,code2,code3,code4,code5,code6,code7)
1379 = (0xB8, byte 0 entry_addr_w, byte 1 entry_addr_w,
1380 byte 2 entry_addr_w, byte 3 entry_addr_w,
1384 entry_addr_w :: Word32
1385 entry_addr_w = fromIntegral (addrToInt entry_addr)
1388 --putStrLn ("SIZE of itbl is " ++ show (sizeOf itbl))
1389 --putStrLn ("# ptrs of itbl is " ++ show ptrs)
1390 --putStrLn ("# nptrs of itbl is " ++ show nptrs)
1392 return (getName dcon, addr `plusPtr` 8)
1395 byte :: Int -> Word32 -> Word32
1396 byte 0 w = w .&. 0xFF
1397 byte 1 w = (w `shiftR` 8) .&. 0xFF
1398 byte 2 w = (w `shiftR` 16) .&. 0xFF
1399 byte 3 w = (w `shiftR` 24) .&. 0xFF
1402 vecret_entry 0 = stg_interp_constr1_entry
1403 vecret_entry 1 = stg_interp_constr2_entry
1404 vecret_entry 2 = stg_interp_constr3_entry
1405 vecret_entry 3 = stg_interp_constr4_entry
1406 vecret_entry 4 = stg_interp_constr5_entry
1407 vecret_entry 5 = stg_interp_constr6_entry
1408 vecret_entry 6 = stg_interp_constr7_entry
1409 vecret_entry 7 = stg_interp_constr8_entry
1411 -- entry point for direct returns for created constr itbls
1412 foreign label "stg_interp_constr_entry" stg_interp_constr_entry :: Addr
1413 -- and the 8 vectored ones
1414 foreign label "stg_interp_constr1_entry" stg_interp_constr1_entry :: Addr
1415 foreign label "stg_interp_constr2_entry" stg_interp_constr2_entry :: Addr
1416 foreign label "stg_interp_constr3_entry" stg_interp_constr3_entry :: Addr
1417 foreign label "stg_interp_constr4_entry" stg_interp_constr4_entry :: Addr
1418 foreign label "stg_interp_constr5_entry" stg_interp_constr5_entry :: Addr
1419 foreign label "stg_interp_constr6_entry" stg_interp_constr6_entry :: Addr
1420 foreign label "stg_interp_constr7_entry" stg_interp_constr7_entry :: Addr
1421 foreign label "stg_interp_constr8_entry" stg_interp_constr8_entry :: Addr
1427 -- Ultra-minimalist version specially for constructors
1428 data StgInfoTable = StgInfoTable {
1433 code0, code1, code2, code3, code4, code5, code6, code7 :: Word8
1437 instance Storable StgInfoTable where
1440 = (sum . map (\f -> f itbl))
1441 [fieldSz ptrs, fieldSz nptrs, fieldSz srtlen, fieldSz tipe,
1442 fieldSz code0, fieldSz code1, fieldSz code2, fieldSz code3,
1443 fieldSz code4, fieldSz code5, fieldSz code6, fieldSz code7]
1446 = (sum . map (\f -> f itbl))
1447 [fieldAl ptrs, fieldAl nptrs, fieldAl srtlen, fieldAl tipe,
1448 fieldAl code0, fieldAl code1, fieldAl code2, fieldAl code3,
1449 fieldAl code4, fieldAl code5, fieldAl code6, fieldAl code7]
1452 = do a1 <- store (ptrs itbl) (castPtr a0)
1453 a2 <- store (nptrs itbl) a1
1454 a3 <- store (tipe itbl) a2
1455 a4 <- store (srtlen itbl) a3
1456 a5 <- store (code0 itbl) a4
1457 a6 <- store (code1 itbl) a5
1458 a7 <- store (code2 itbl) a6
1459 a8 <- store (code3 itbl) a7
1460 a9 <- store (code4 itbl) a8
1461 aA <- store (code5 itbl) a9
1462 aB <- store (code6 itbl) aA
1463 aC <- store (code7 itbl) aB
1467 = do (a1,ptrs) <- load (castPtr a0)
1468 (a2,nptrs) <- load a1
1469 (a3,tipe) <- load a2
1470 (a4,srtlen) <- load a3
1471 (a5,code0) <- load a4
1472 (a6,code1) <- load a5
1473 (a7,code2) <- load a6
1474 (a8,code3) <- load a7
1475 (a9,code4) <- load a8
1476 (aA,code5) <- load a9
1477 (aB,code6) <- load aA
1478 (aC,code7) <- load aB
1479 return StgInfoTable { ptrs = ptrs, nptrs = nptrs,
1480 srtlen = srtlen, tipe = tipe,
1481 code0 = code0, code1 = code1, code2 = code2,
1482 code3 = code3, code4 = code4, code5 = code5,
1483 code6 = code6, code7 = code7 }
1485 fieldSz :: (Storable a, Storable b) => (a -> b) -> a -> Int
1486 fieldSz sel x = sizeOf (sel x)
1488 fieldAl :: (Storable a, Storable b) => (a -> b) -> a -> Int
1489 fieldAl sel x = alignment (sel x)
1491 store :: Storable a => a -> Ptr a -> IO (Ptr b)
1492 store x addr = do poke addr x
1493 return (castPtr (addr `plusPtr` sizeOf x))
1495 load :: Storable a => Ptr a -> IO (Ptr b, a)
1496 load addr = do x <- peek addr
1497 return (castPtr (addr `plusPtr` sizeOf x), x)
1501 %************************************************************************
1503 \subsection{Connect to actual values for bytecode opcodes}
1505 %************************************************************************
1509 #include "Bytecodes.h"
1511 i_ARGCHECK = (bci_ARGCHECK :: Int)
1512 i_PUSH_L = (bci_PUSH_L :: Int)
1513 i_PUSH_LL = (bci_PUSH_LL :: Int)
1514 i_PUSH_LLL = (bci_PUSH_LLL :: Int)
1515 i_PUSH_G = (bci_PUSH_G :: Int)
1516 i_PUSH_AS = (bci_PUSH_AS :: Int)
1517 i_PUSH_UBX = (bci_PUSH_UBX :: Int)
1518 i_PUSH_TAG = (bci_PUSH_TAG :: Int)
1519 i_SLIDE = (bci_SLIDE :: Int)
1520 i_ALLOC = (bci_ALLOC :: Int)
1521 i_MKAP = (bci_MKAP :: Int)
1522 i_UNPACK = (bci_UNPACK :: Int)
1523 i_UPK_TAG = (bci_UPK_TAG :: Int)
1524 i_PACK = (bci_PACK :: Int)
1525 i_TESTLT_I = (bci_TESTLT_I :: Int)
1526 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
1527 i_TESTLT_F = (bci_TESTLT_F :: Int)
1528 i_TESTEQ_F = (bci_TESTEQ_F :: Int)
1529 i_TESTLT_D = (bci_TESTLT_D :: Int)
1530 i_TESTEQ_D = (bci_TESTEQ_D :: Int)
1531 i_TESTLT_P = (bci_TESTLT_P :: Int)
1532 i_TESTEQ_P = (bci_TESTEQ_P :: Int)
1533 i_CASEFAIL = (bci_CASEFAIL :: Int)
1534 i_ENTER = (bci_ENTER :: Int)
1535 i_RETURN = (bci_RETURN :: Int)