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 )
45 import FastString ( FastString(..) )
48 import List ( intersperse )
49 import Monad ( foldM )
51 import MArray ( castSTUArray,
52 newFloatArray, writeFloatArray,
53 newDoubleArray, writeDoubleArray,
54 newIntArray, writeIntArray,
55 newAddrArray, writeAddrArray )
56 import Foreign ( Storable(..), Word8, Word16, Word32, Ptr(..),
57 malloc, castPtr, plusPtr, mallocBytes )
58 import Addr ( Word, addrToInt, nullAddr, writeCharOffAddr )
59 import Bits ( Bits(..), shiftR )
60 import CTypes ( CInt )
62 import PrelBase ( Int(..) )
63 import PrelAddr ( Addr(..) )
64 import PrelGHC ( BCO#, newBCO#, unsafeCoerce#,
65 ByteArray#, Array#, addrToHValue# )
66 import IOExts ( IORef, fixIO, unsafePerformIO )
68 import PrelArr ( Array(..) )
69 import PrelIOBase ( IO(..) )
73 %************************************************************************
75 \subsection{Functions visible from outside this module.}
77 %************************************************************************
81 byteCodeGen :: DynFlags
84 -> IO ([UnlinkedBCO], ItblEnv)
85 byteCodeGen dflags binds local_tycons local_classes
86 = do showPass dflags "ByteCodeGen"
87 let tycs = local_tycons ++ map classTyCon local_classes
88 itblenv <- mkITbls tycs
90 let flatBinds = concatMap getBind binds
91 getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
92 getBind (Rec binds) = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
93 final_state = runBc (BcM_State [] 0)
94 (mapBc schemeR flatBinds `thenBc_` returnBc ())
95 (BcM_State proto_bcos final_ctr) = final_state
97 dumpIfSet_dyn dflags Opt_D_dump_BCOs
98 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
100 bcos <- mapM assembleBCO proto_bcos
102 return (bcos, itblenv)
105 -- Returns: (the root BCO for this expression,
106 -- a list of auxilary BCOs resulting from compiling closures)
107 coreExprToBCOs :: DynFlags
109 -> IO UnlinkedBCOExpr
110 coreExprToBCOs dflags expr
111 = do showPass dflags "ByteCodeGen"
113 -- create a totally bogus name for the top-level BCO; this
114 -- should be harmless, since it's never used for anything
115 let invented_name = mkSysLocalName (mkPseudoUnique3 0) SLIT("Expr-Top-Level")
116 let invented_id = mkVanillaId invented_name (panic "invented_id's type")
118 let (BcM_State all_proto_bcos final_ctr)
119 = runBc (BcM_State [] 0)
120 (schemeR (invented_id, freeVars expr))
121 dumpIfSet_dyn dflags Opt_D_dump_BCOs
122 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr all_proto_bcos)))
125 = case filter ((== invented_name).nameOfProtoBCO) all_proto_bcos of
126 [root_bco] -> root_bco
128 = filter ((/= invented_name).nameOfProtoBCO) all_proto_bcos
130 auxiliary_bcos <- mapM assembleBCO auxiliary_proto_bcos
131 root_bco <- assembleBCO root_proto_bco
133 return (root_bco, auxiliary_bcos)
137 linkIModules :: ItblEnv -- incoming global itbl env; returned updated
138 -> ClosureEnv -- incoming global closure env; returned updated
139 -> [([UnlinkedBCO], ItblEnv)]
140 -> IO ([HValue], ItblEnv, ClosureEnv)
141 linkIModules gie gce mods
142 = do let (bcoss, ies) = unzip mods
144 final_gie = foldr plusFM gie ies
145 (final_gce, linked_bcos) <- linkSomeBCOs final_gie gce bcos
146 return (linked_bcos, final_gie, final_gce)
149 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
150 -> IO HValue -- IO BCO# really
151 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
152 = do (aux_ce, _) <- linkSomeBCOs ie ce aux_ul_bcos
153 (_, [root_bco]) <- linkSomeBCOs ie aux_ce [root_ul_bco]
156 -- Link a bunch of BCOs and return them + updated closure env.
157 linkSomeBCOs :: ItblEnv -> ClosureEnv -> [UnlinkedBCO]
158 -> IO (ClosureEnv, [HValue])
159 linkSomeBCOs ie ce_in ul_bcos
160 = do let nms = map nameOfUnlinkedBCO ul_bcos
162 ( \ hvs -> let ce_out = addListToFM ce_in (zipLazily nms hvs)
163 in mapM (linkBCO ie ce_out) ul_bcos )
164 let ce_out = addListToFM ce_in (zip nms hvals)
165 return (ce_out, hvals)
167 -- A lazier zip, in which no demand is propagated to the second
168 -- list unless some demand is propagated to the snd of one of the
169 -- result list elems.
171 zipLazily (x:xs) ys = (x, head ys) : zipLazily xs (tail ys)
176 (SizedSeq Word16) -- insns
177 (SizedSeq Word) -- literals
178 (SizedSeq Name) -- ptrs
179 (SizedSeq Name) -- itbl refs
181 nameOfUnlinkedBCO (UnlinkedBCO nm _ _ _ _) = nm
183 -- When translating expressions, we need to distinguish the root
184 -- BCO for the expression
185 type UnlinkedBCOExpr = (UnlinkedBCO, [UnlinkedBCO])
187 instance Outputable UnlinkedBCO where
188 ppr (UnlinkedBCO nm insns lits ptrs itbls)
189 = sep [text "BCO", ppr nm, text "with",
190 int (sizeSS insns), text "insns",
191 int (sizeSS lits), text "lits",
192 int (sizeSS ptrs), text "ptrs",
193 int (sizeSS itbls), text "itbls"]
196 -- these need a proper home
197 type ItblEnv = FiniteMap Name (Ptr StgInfoTable)
198 type ClosureEnv = FiniteMap Name HValue
199 data HValue = HValue -- dummy type, actually a pointer to some Real Code.
201 -- remove all entries for a given set of modules from the environment
202 filterNameMap :: [ModuleName] -> FiniteMap Name a -> FiniteMap Name a
203 filterNameMap mods env
204 = filterFM (\n _ -> moduleName (nameModule n) `notElem` mods) env
207 %************************************************************************
209 \subsection{Bytecodes, and Outputery.}
211 %************************************************************************
215 type LocalLabel = Int
218 -- Messing with the stack
220 -- Push locals (existing bits of the stack)
221 | PUSH_L Int{-offset-}
222 | PUSH_LL Int Int{-2 offsets-}
223 | PUSH_LLL Int Int Int{-3 offsets-}
226 -- Push an alt continuation
227 | PUSH_AS Name PrimRep -- push alts and BCO_ptr_ret_info
228 -- PrimRep so we know which itbl
230 | PUSH_UBX Literal Int
231 -- push this int/float/double, NO TAG, on the stack
232 -- Int is # of words to copy from literal pool
233 | PUSH_TAG Int -- push this tag on the stack
235 | SLIDE Int{-this many-} Int{-down by this much-}
236 -- To do with the heap
237 | ALLOC Int -- make an AP_UPD with this many payload words, zeroed
238 | MKAP Int{-ptr to AP_UPD is this far down stack-} Int{-# words-}
239 | UNPACK Int -- unpack N ptr words from t.o.s Constr
240 | UPK_TAG Int Int Int
241 -- unpack N non-ptr words from offset M in constructor
242 -- K words down the stack
244 -- after assembly, the DataCon is an index into the
246 -- For doing case trees
248 | TESTLT_I Int LocalLabel
249 | TESTEQ_I Int LocalLabel
250 | TESTLT_F Float LocalLabel
251 | TESTEQ_F Float LocalLabel
252 | TESTLT_D Double LocalLabel
253 | TESTEQ_D Double LocalLabel
255 -- The Int value is a constructor number and therefore
256 -- stored in the insn stream rather than as an offset into
258 | TESTLT_P Int LocalLabel
259 | TESTEQ_P Int LocalLabel
262 -- To Infinity And Beyond
265 -- unboxed value on TOS. Use tag to find underlying ret itbl
266 -- and return as per that.
269 instance Outputable BCInstr where
270 ppr (ARGCHECK n) = text "ARGCHECK" <+> int n
271 ppr (PUSH_L offset) = text "PUSH_L " <+> int offset
272 ppr (PUSH_LL o1 o2) = text "PUSH_LL " <+> int o1 <+> int o2
273 ppr (PUSH_LLL o1 o2 o3) = text "PUSH_LLL" <+> int o1 <+> int o2 <+> int o3
274 ppr (PUSH_G nm) = text "PUSH_G " <+> ppr nm
275 ppr (PUSH_AS nm pk) = text "PUSH_AS " <+> ppr nm <+> ppr pk
276 ppr (PUSH_UBX lit nw) = text "PUSH_UBX" <+> parens (int nw) <+> ppr lit
277 ppr (PUSH_TAG n) = text "PUSH_TAG" <+> int n
278 ppr (SLIDE n d) = text "SLIDE " <+> int n <+> int d
279 ppr (ALLOC sz) = text "ALLOC " <+> int sz
280 ppr (MKAP offset sz) = text "MKAP " <+> int sz <+> text "words,"
281 <+> int offset <+> text "stkoff"
282 ppr (UNPACK sz) = text "UNPACK " <+> int sz
283 ppr (UPK_TAG n m k) = text "UPK_TAG " <+> int n <> text "words"
284 <+> int m <> text "conoff"
285 <+> int k <> text "stkoff"
286 ppr (PACK dcon sz) = text "PACK " <+> ppr dcon <+> ppr sz
287 ppr (LABEL lab) = text "__" <> int lab <> colon
288 ppr (TESTLT_I i lab) = text "TESTLT_I" <+> int i <+> text "__" <> int lab
289 ppr (TESTEQ_I i lab) = text "TESTEQ_I" <+> int i <+> text "__" <> int lab
290 ppr (TESTLT_F f lab) = text "TESTLT_F" <+> float f <+> text "__" <> int lab
291 ppr (TESTEQ_F f lab) = text "TESTEQ_F" <+> float f <+> text "__" <> int lab
292 ppr (TESTLT_D d lab) = text "TESTLT_D" <+> double d <+> text "__" <> int lab
293 ppr (TESTEQ_D d lab) = text "TESTEQ_D" <+> double d <+> text "__" <> int lab
294 ppr (TESTLT_P i lab) = text "TESTLT_P" <+> int i <+> text "__" <> int lab
295 ppr (TESTEQ_P i lab) = text "TESTEQ_P" <+> int i <+> text "__" <> int lab
296 ppr CASEFAIL = text "CASEFAIL"
297 ppr ENTER = text "ENTER"
298 ppr (RETURN pk) = text "RETURN " <+> ppr pk
300 instance Outputable a => Outputable (ProtoBCO a) where
301 ppr (ProtoBCO name instrs origin)
302 = (text "ProtoBCO" <+> ppr name <> colon)
303 $$ nest 6 (vcat (map ppr instrs))
305 Left alts -> vcat (map (pprCoreAlt.deAnnAlt) alts)
306 Right rhs -> pprCoreExpr (deAnnotate rhs)
309 %************************************************************************
311 \subsection{Compilation schema for the bytecode generator.}
313 %************************************************************************
317 type BCInstrList = OrdList BCInstr
320 = ProtoBCO a -- name, in some sense
322 -- what the BCO came from
323 (Either [AnnAlt Id VarSet]
326 nameOfProtoBCO (ProtoBCO nm insns origin) = nm
329 type Sequel = Int -- back off to this depth before ENTER
331 -- Maps Ids to the offset from the stack _base_ so we don't have
332 -- to mess with it after each push/pop.
333 type BCEnv = FiniteMap Id Int -- To find vars on the stack
336 -- Create a BCO and do a spot of peephole optimisation on the insns
338 mkProtoBCO nm instrs_ordlist origin
339 = ProtoBCO nm (id {-peep-} (fromOL instrs_ordlist)) origin
341 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
342 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
343 peep (PUSH_L off1 : PUSH_L off2 : rest)
344 = PUSH_LL off1 off2 : peep rest
351 -- Compile code for the right hand side of a let binding.
352 -- Park the resulting BCO in the monad. Also requires the
353 -- variable to which this value was bound, so as to give the
354 -- resulting BCO a name.
355 schemeR :: (Id, AnnExpr Id VarSet) -> BcM ()
360 $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
361 $$ pprCoreExpr (deAnnotate rhs)
367 = schemeR_wrk rhs nm (collect [] rhs)
370 collect xs (_, AnnLam x e)
371 = collect (if isTyVar x then xs else (x:xs)) e
372 collect xs not_lambda
373 = (reverse xs, not_lambda)
375 schemeR_wrk original_body nm (args, body)
376 = let fvs = filter (not.isTyVar) (varSetElems (fst original_body))
377 all_args = fvs ++ reverse args
378 szsw_args = map taggedIdSizeW all_args
379 szw_args = sum szsw_args
380 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
381 argcheck = {-if null args then nilOL else-} unitOL (ARGCHECK szw_args)
383 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
384 emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) (Right original_body))
386 -- Let szsw be the sizes in words of some items pushed onto the stack,
387 -- which has initial depth d'. Return the values which the stack environment
388 -- should map these items to.
389 mkStackOffsets :: Int -> [Int] -> [Int]
390 mkStackOffsets original_depth szsw
391 = map (subtract 1) (tail (scanl (+) original_depth szsw))
393 -- Compile code to apply the given expression to the remaining args
394 -- on the stack, returning a HNF.
395 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
397 -- Delegate tail-calls to schemeT.
398 schemeE d s p e@(fvs, AnnApp f a)
399 = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnApp f a))
400 schemeE d s p e@(fvs, AnnVar v)
401 | isFollowableRep v_rep
402 = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnVar v))
404 = -- returning an unboxed value. Heave it on the stack, SLIDE, and RETURN.
405 let (push, szw) = pushAtom True d p (AnnVar v)
406 in returnBc (push -- value onto stack
407 `snocOL` SLIDE szw (d-s) -- clear to sequel
408 `snocOL` RETURN v_rep) -- go
410 v_rep = typePrimRep (idType v)
412 schemeE d s p (fvs, AnnLit literal)
413 = let (push, szw) = pushAtom True d p (AnnLit literal)
414 l_rep = literalPrimRep literal
415 in returnBc (push -- value onto stack
416 `snocOL` SLIDE szw (d-s) -- clear to sequel
417 `snocOL` RETURN l_rep) -- go
419 schemeE d s p (fvs, AnnLet binds b)
420 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
421 AnnRec xs_n_rhss -> unzip xs_n_rhss
423 fvss = map (filter (not.isTyVar).varSetElems.fst) rhss
425 -- Sizes of tagged free vars, + 1 for the fn
426 sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
428 -- This p', d' defn is safe because all the items being pushed
429 -- are ptrs, so all have size 1. d' and p' reflect the stack
430 -- after the closures have been allocated in the heap (but not
431 -- filled in), and pointers to them parked on the stack.
432 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
435 infos = zipE4 fvss sizes xs [n, n-1 .. 1]
436 zipE = zipEqual "schemeE"
437 zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
439 -- ToDo: don't build thunks for things with no free variables
440 buildThunk dd ([], size, id, off)
441 = PUSH_G (getName id)
442 `consOL` unitOL (MKAP (off+size-1) size)
443 buildThunk dd ((fv:fvs), size, id, off)
444 = case pushAtom True dd p' (AnnVar fv) of
445 (push_code, pushed_szw)
447 buildThunk (dd+pushed_szw) (fvs, size, id, off)
449 thunkCode = concatOL (map (buildThunk d') infos)
450 allocCode = toOL (map ALLOC sizes)
452 schemeE d' s p' b `thenBc` \ bodyCode ->
453 mapBc schemeR (zip xs rhss) `thenBc_`
454 returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
457 schemeE d s p (fvs, AnnCase scrut bndr alts)
459 -- Top of stack is the return itbl, as usual.
460 -- underneath it is the pointer to the alt_code BCO.
461 -- When an alt is entered, it assumes the returned value is
462 -- on top of the itbl.
465 -- Env and depth in which to compile the alts, not including
466 -- any vars bound by the alts themselves
467 d' = d + ret_frame_sizeW + taggedIdSizeW bndr
468 p' = addToFM p bndr (d' - 1)
470 scrut_primrep = typePrimRep (idType bndr)
472 = case scrut_primrep of
473 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
475 other -> pprPanic "ByteCodeGen.schemeE" (ppr other)
477 -- given an alt, return a discr and code for it.
478 codeAlt alt@(discr, binds_f, rhs)
480 = let binds_r = reverse binds_f
481 binds_r_szsw = map untaggedIdSizeW binds_r
482 binds_szw = sum binds_r_szsw
484 p' (zip binds_r (mkStackOffsets d' binds_r_szsw))
486 unpack_code = mkUnpackCode 0 0 (map (typePrimRep.idType) binds_f)
487 in schemeE d'' s p'' rhs `thenBc` \ rhs_code ->
488 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
490 = ASSERT(null binds_f)
491 schemeE d' s p' rhs `thenBc` \ rhs_code ->
492 returnBc (my_discr alt, rhs_code)
494 my_discr (DEFAULT, binds, rhs) = NoDiscr
495 my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc - fIRST_TAG)
496 my_discr (LitAlt l, binds, rhs)
497 = case l of MachInt i -> DiscrI (fromInteger i)
498 MachFloat r -> DiscrF (fromRational r)
499 MachDouble r -> DiscrD (fromRational r)
502 | not isAlgCase = Nothing
504 = case [dc | (DataAlt dc, _, _) <- alts] of
506 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
509 mapBc codeAlt alts `thenBc` \ alt_stuff ->
510 mkMultiBranch maybe_ncons alt_stuff `thenBc` \ alt_final ->
512 alt_final_ac = ARGCHECK (taggedIdSizeW bndr) `consOL` alt_final
513 alt_bco_name = getName bndr
514 alt_bco = mkProtoBCO alt_bco_name alt_final_ac (Left alts)
516 schemeE (d + ret_frame_sizeW)
517 (d + ret_frame_sizeW) p scrut `thenBc` \ scrut_code ->
519 emitBc alt_bco `thenBc_`
520 returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
523 schemeE d s p (fvs, AnnNote note body)
527 = pprPanic "ByteCodeGen.schemeE: unhandled case"
528 (pprCoreExpr (deAnnotate other))
531 -- Compile code to do a tail call. Doesn't need to be monadic.
532 schemeT :: Bool -- do tagging?
533 -> Int -- Stack depth
534 -> Sequel -- Sequel depth
535 -> Int -- # arg words so far
536 -> BCEnv -- stack env
540 schemeT enTag d s narg_words p (_, AnnApp f a)
542 AnnType _ -> schemeT enTag d s narg_words p f
544 -> let (push, arg_words) = pushAtom enTag d p (snd a)
546 `appOL` schemeT enTag (d+arg_words) s (narg_words+arg_words) p f
548 schemeT enTag d s narg_words p (_, AnnVar f)
549 | Just con <- isDataConId_maybe f
550 = ASSERT(enTag == False)
551 --trace ("schemeT: d = " ++ show d ++ ", s = " ++ show s ++ ", naw = " ++ show narg_words) (
552 PACK con narg_words `consOL` (mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
555 = ASSERT(enTag == True)
556 let (push, arg_words) = pushAtom True d p (AnnVar f)
558 `appOL` mkSLIDE (narg_words+arg_words) (d - s - narg_words)
562 = if d == 0 then nilOL else unitOL (SLIDE n d)
564 should_args_be_tagged (_, AnnVar v)
565 = case isDataConId_maybe v of
566 Just dcon -> False; Nothing -> True
567 should_args_be_tagged (_, AnnApp f a)
568 = should_args_be_tagged f
569 should_args_be_tagged (_, other)
570 = panic "should_args_be_tagged: tail call to non-con, non-var"
573 -- Make code to unpack a constructor onto the stack, adding
574 -- tags for the unboxed bits. Takes the PrimReps of the constructor's
575 -- arguments, and a travelling offset along both the constructor
576 -- (off_h) and the stack (off_s).
577 mkUnpackCode :: Int -> Int -> [PrimRep] -> BCInstrList
578 mkUnpackCode off_h off_s [] = nilOL
579 mkUnpackCode off_h off_s (r:rs)
581 = let (rs_ptr, rs_nptr) = span isFollowableRep (r:rs)
582 ptrs_szw = sum (map untaggedSizeW rs_ptr)
583 in ASSERT(ptrs_szw == length rs_ptr)
587 `consOL` mkUnpackCode (off_h + ptrs_szw) (off_s + ptrs_szw) rs_nptr
592 DoubleRep -> approved
594 approved = UPK_TAG usizeW off_h off_s `consOL` theRest
595 theRest = mkUnpackCode (off_h + usizeW) (off_s + tsizeW) rs
596 usizeW = untaggedSizeW r
597 tsizeW = taggedSizeW r
599 -- Push an atom onto the stack, returning suitable code & number of
600 -- stack words used. Pushes it either tagged or untagged, since
601 -- pushAtom is used to set up the stack prior to copying into the
602 -- heap for both APs (requiring tags) and constructors (which don't).
604 -- NB this means NO GC between pushing atoms for a constructor and
605 -- copying them into the heap. It probably also means that
606 -- tail calls MUST be of the form atom{atom ... atom} since if the
607 -- expression head was allowed to be arbitrary, there could be GC
608 -- in between pushing the arg atoms and completing the head.
609 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
610 -- isn't a problem; but only if arbitrary graph construction for the
611 -- head doesn't leave this BCO, since GC might happen at the start of
612 -- each BCO (we consult doYouWantToGC there).
614 -- Blargh. JRS 001206
616 -- NB (further) that the env p must map each variable to the highest-
617 -- numbered stack slot for it. For example, if the stack has depth 4
618 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
619 -- the tag in stack[5], the stack will have depth 6, and p must map v to
620 -- 5 and not to 4. Stack locations are numbered from zero, so a depth
621 -- 6 stack has valid words 0 .. 5.
623 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
624 pushAtom tagged d p (AnnVar v)
625 = let str = "\npushAtom " ++ showSDocDebug (ppr v) ++ ", depth = " ++ show d
627 showSDocDebug (nest 4 (vcat (map ppr (fmToList p))))
629 showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
630 ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
631 str' = if str == str then str else str
634 = case lookupBCEnv_maybe p v of
635 Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), sz_t)
636 Nothing -> ASSERT(sz_t == 1) (unitOL (PUSH_G nm), sz_t)
638 nm = case isDataConId_maybe v of
642 sz_t = taggedIdSizeW v
643 sz_u = untaggedIdSizeW v
644 nwords = if tagged then sz_t else sz_u
649 pushAtom True d p (AnnLit lit)
650 = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
651 in (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
653 pushAtom False d p (AnnLit lit)
655 MachInt i -> code IntRep
656 MachFloat r -> code FloatRep
657 MachDouble r -> code DoubleRep
658 MachChar c -> code CharRep
659 MachStr s -> pushStr s
662 = let size_host_words = untaggedSizeW rep
663 in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
666 = let mallocvilleAddr
671 -- sigh, a string in the heap is no good to us.
672 -- We need a static C pointer, since the type of
673 -- a string literal is Addr#. So, copy the string
674 -- into C land and introduce a memory leak
677 -- CAREFUL! Chars are 32 bits in ghc 4.09+
679 do a@(Ptr addr) <- mallocBytes (n+1)
680 strncpy a ba (fromIntegral n)
681 writeCharOffAddr addr n '\0'
684 _ -> panic "StgInterp.lit2expr: unhandled string constant type"
687 = MachInt (toInteger (addrToInt mallocvilleAddr))
689 -- Get the addr on the stack, untaggedly
690 (unitOL (PUSH_UBX addrLit 1), 1)
696 pushAtom tagged d p (AnnApp f (_, AnnType _))
697 = pushAtom tagged d p (snd f)
699 pushAtom tagged d p other
700 = pprPanic "ByteCodeGen.pushAtom"
701 (pprCoreExpr (deAnnotate (undefined, other)))
703 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
706 -- Given a bunch of alts code and their discrs, do the donkey work
707 -- of making a multiway branch using a switch tree.
708 -- What a load of hassle!
709 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
710 -- a hint; generates better code
711 -- Nothing is always safe
712 -> [(Discr, BCInstrList)]
714 mkMultiBranch maybe_ncons raw_ways
715 = let d_way = filter (isNoDiscr.fst) raw_ways
716 notd_ways = naturalMergeSortLe
717 (\w1 w2 -> leAlt (fst w1) (fst w2))
718 (filter (not.isNoDiscr.fst) raw_ways)
720 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
721 mkTree [] range_lo range_hi = returnBc the_default
723 mkTree [val] range_lo range_hi
724 | range_lo `eqAlt` range_hi
727 = getLabelBc `thenBc` \ label_neq ->
728 returnBc (mkTestEQ (fst val) label_neq
730 `appOL` unitOL (LABEL label_neq)
731 `appOL` the_default))
733 mkTree vals range_lo range_hi
734 = let n = length vals `div` 2
735 vals_lo = take n vals
736 vals_hi = drop n vals
737 v_mid = fst (head vals_hi)
739 getLabelBc `thenBc` \ label_geq ->
740 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
741 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
742 returnBc (mkTestLT v_mid label_geq
744 `appOL` unitOL (LABEL label_geq)
748 = case d_way of [] -> unitOL CASEFAIL
751 -- None of these will be needed if there are no non-default alts
752 (mkTestLT, mkTestEQ, init_lo, init_hi)
754 = panic "mkMultiBranch: awesome foursome"
756 = case fst (head notd_ways) of {
757 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
758 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
761 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
762 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
765 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
766 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
769 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
770 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
775 (algMinBound, algMaxBound)
776 = case maybe_ncons of
778 Nothing -> (minBound, maxBound)
780 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
781 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
782 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
783 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
784 NoDiscr `eqAlt` NoDiscr = True
787 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
788 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
789 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
790 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
791 NoDiscr `leAlt` NoDiscr = True
794 isNoDiscr NoDiscr = True
797 dec (DiscrI i) = DiscrI (i-1)
798 dec (DiscrP i) = DiscrP (i-1)
799 dec other = other -- not really right, but if you
800 -- do cases on floating values, you'll get what you deserve
802 -- same snotty comment applies to the following
810 mkTree notd_ways init_lo init_hi
814 %************************************************************************
816 \subsection{Supporting junk for the compilation schemes}
818 %************************************************************************
822 -- Describes case alts
830 instance Outputable Discr where
831 ppr (DiscrI i) = int i
832 ppr (DiscrF f) = text (show f)
833 ppr (DiscrD d) = text (show d)
834 ppr (DiscrP i) = int i
835 ppr NoDiscr = text "DEF"
838 -- Find things in the BCEnv (the what's-on-the-stack-env)
839 -- See comment preceding pushAtom for precise meaning of env contents
840 --lookupBCEnv :: BCEnv -> Id -> Int
842 -- = case lookupFM env nm of
843 -- Nothing -> pprPanic "lookupBCEnv"
844 -- (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
847 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
848 lookupBCEnv_maybe = lookupFM
851 -- When I push one of these on the stack, how much does Sp move by?
852 taggedSizeW :: PrimRep -> Int
854 | isFollowableRep pr = 1
855 | otherwise = 1{-the tag-} + getPrimRepSize pr
858 -- The plain size of something, without tag.
859 untaggedSizeW :: PrimRep -> Int
861 | isFollowableRep pr = 1
862 | otherwise = getPrimRepSize pr
865 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
866 taggedIdSizeW = taggedSizeW . typePrimRep . idType
867 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
871 %************************************************************************
873 \subsection{The bytecode generator's monad}
875 %************************************************************************
879 = BcM_State { bcos :: [ProtoBCO Name], -- accumulates completed BCOs
880 nextlabel :: Int } -- for generating local labels
882 type BcM result = BcM_State -> (result, BcM_State)
884 runBc :: BcM_State -> BcM () -> BcM_State
885 runBc init_st m = case m init_st of { (r,st) -> st }
887 thenBc :: BcM a -> (a -> BcM b) -> BcM b
889 = case expr st of { (result, st') -> cont result st' }
891 thenBc_ :: BcM a -> BcM b -> BcM b
893 = case expr st of { (result, st') -> cont st' }
895 returnBc :: a -> BcM a
896 returnBc result st = (result, st)
898 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
899 mapBc f [] = returnBc []
901 = f x `thenBc` \ r ->
902 mapBc f xs `thenBc` \ rs ->
905 emitBc :: ProtoBCO Name -> BcM ()
907 = ((), st{bcos = bco : bcos st})
909 getLabelBc :: BcM Int
911 = (nextlabel st, st{nextlabel = 1 + nextlabel st})
915 %************************************************************************
917 \subsection{The bytecode assembler}
919 %************************************************************************
921 The object format for bytecodes is: 16 bits for the opcode, and 16 for
922 each field -- so the code can be considered a sequence of 16-bit ints.
923 Each field denotes either a stack offset or number of items on the
924 stack (eg SLIDE), and index into the pointer table (eg PUSH_G), an
925 index into the literal table (eg PUSH_I/D/L), or a bytecode address in
929 -- Top level assembler fn.
930 assembleBCO :: ProtoBCO Name -> IO UnlinkedBCO
932 assembleBCO (ProtoBCO nm instrs origin)
934 -- pass 1: collect up the offsets of the local labels.
935 -- Remember that the first insn starts at offset 1 since offset 0
936 -- (eventually) will hold the total # of insns.
937 label_env = mkLabelEnv emptyFM 1 instrs
939 mkLabelEnv env i_offset [] = env
940 mkLabelEnv env i_offset (i:is)
942 = case i of LABEL n -> addToFM env n i_offset ; _ -> env
943 in mkLabelEnv new_env (i_offset + instrSize16s i) is
946 = case lookupFM label_env lab of
947 Just bco_offset -> bco_offset
948 Nothing -> pprPanic "assembleBCO.findLabel" (int lab)
950 do -- pass 2: generate the instruction, ptr and nonptr bits
951 insns <- return emptySS :: IO (SizedSeq Word16)
952 lits <- return emptySS :: IO (SizedSeq Word)
953 ptrs <- return emptySS :: IO (SizedSeq Name)
954 itbls <- return emptySS :: IO (SizedSeq Name)
955 let init_asm_state = (insns,lits,ptrs,itbls)
956 (final_insns, final_lits, final_ptrs, final_itbls)
957 <- mkBits findLabel init_asm_state instrs
959 return (UnlinkedBCO nm final_insns final_lits final_ptrs final_itbls)
961 -- instrs nonptrs ptrs itbls
962 type AsmState = (SizedSeq Word16, SizedSeq Word, SizedSeq Name, SizedSeq Name)
964 data SizedSeq a = SizedSeq !Int [a]
965 emptySS = SizedSeq 0 []
966 addToSS (SizedSeq n r_xs) x = return (SizedSeq (n+1) (x:r_xs))
967 addListToSS (SizedSeq n r_xs) xs
968 = return (SizedSeq (n + length xs) (reverse xs ++ r_xs))
969 sizeSS (SizedSeq n r_xs) = n
970 listFromSS (SizedSeq n r_xs) = return (reverse r_xs)
973 -- This is where all the action is (pass 2 of the assembler)
974 mkBits :: (Int -> Int) -- label finder
976 -> [BCInstr] -- instructions (in)
979 mkBits findLabel st proto_insns
980 = foldM doInstr st proto_insns
982 doInstr :: AsmState -> BCInstr -> IO AsmState
985 ARGCHECK n -> instr2 st i_ARGCHECK n
986 PUSH_L o1 -> instr2 st i_PUSH_L o1
987 PUSH_LL o1 o2 -> instr3 st i_PUSH_LL o1 o2
988 PUSH_LLL o1 o2 o3 -> instr4 st i_PUSH_LLL o1 o2 o3
989 PUSH_G nm -> do (p, st2) <- ptr st nm
990 instr2 st2 i_PUSH_G p
991 PUSH_AS nm pk -> do (p, st2) <- ptr st nm
992 (np, st3) <- ctoi_itbl st2 pk
993 instr3 st3 i_PUSH_AS p np
994 PUSH_UBX lit nws -> do (np, st2) <- literal st lit
995 instr3 st2 i_PUSH_UBX np nws
996 PUSH_TAG tag -> instr2 st i_PUSH_TAG tag
997 SLIDE n by -> instr3 st i_SLIDE n by
998 ALLOC n -> instr2 st i_ALLOC n
999 MKAP off sz -> instr3 st i_MKAP off sz
1000 UNPACK n -> instr2 st i_UNPACK n
1001 UPK_TAG n m k -> instr4 st i_UPK_TAG n m k
1002 PACK dcon sz -> do (itbl_no,st2) <- itbl st dcon
1003 instr3 st2 i_PACK itbl_no sz
1004 LABEL lab -> return st
1005 TESTLT_I i l -> do (np, st2) <- int st i
1006 instr3 st2 i_TESTLT_I np (findLabel l)
1007 TESTEQ_I i l -> do (np, st2) <- int st i
1008 instr3 st2 i_TESTEQ_I np (findLabel l)
1009 TESTLT_F f l -> do (np, st2) <- float st f
1010 instr3 st2 i_TESTLT_F np (findLabel l)
1011 TESTEQ_F f l -> do (np, st2) <- float st f
1012 instr3 st2 i_TESTEQ_F np (findLabel l)
1013 TESTLT_D d l -> do (np, st2) <- double st d
1014 instr3 st2 i_TESTLT_D np (findLabel l)
1015 TESTEQ_D d l -> do (np, st2) <- double st d
1016 instr3 st2 i_TESTEQ_D np (findLabel l)
1017 TESTLT_P i l -> instr3 st i_TESTLT_P i (findLabel l)
1018 TESTEQ_P i l -> instr3 st i_TESTEQ_P i (findLabel l)
1019 CASEFAIL -> instr1 st i_CASEFAIL
1020 ENTER -> instr1 st i_ENTER
1021 RETURN rep -> do (itbl_no,st2) <- itoc_itbl st rep
1022 instr2 st2 i_RETURN itbl_no
1024 i2s :: Int -> Word16
1027 instr1 (st_i0,st_l0,st_p0,st_I0) i1
1028 = do st_i1 <- addToSS st_i0 (i2s i1)
1029 return (st_i1,st_l0,st_p0,st_I0)
1031 instr2 (st_i0,st_l0,st_p0,st_I0) i1 i2
1032 = do st_i1 <- addToSS st_i0 (i2s i1)
1033 st_i2 <- addToSS st_i1 (i2s i2)
1034 return (st_i2,st_l0,st_p0,st_I0)
1036 instr3 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3
1037 = do st_i1 <- addToSS st_i0 (i2s i1)
1038 st_i2 <- addToSS st_i1 (i2s i2)
1039 st_i3 <- addToSS st_i2 (i2s i3)
1040 return (st_i3,st_l0,st_p0,st_I0)
1042 instr4 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3 i4
1043 = do st_i1 <- addToSS st_i0 (i2s i1)
1044 st_i2 <- addToSS st_i1 (i2s i2)
1045 st_i3 <- addToSS st_i2 (i2s i3)
1046 st_i4 <- addToSS st_i3 (i2s i4)
1047 return (st_i4,st_l0,st_p0,st_I0)
1049 float (st_i0,st_l0,st_p0,st_I0) f
1050 = do let ws = mkLitF f
1051 st_l1 <- addListToSS st_l0 ws
1052 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1054 double (st_i0,st_l0,st_p0,st_I0) d
1055 = do let ws = mkLitD d
1056 st_l1 <- addListToSS st_l0 ws
1057 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1059 int (st_i0,st_l0,st_p0,st_I0) i
1060 = do let ws = mkLitI i
1061 st_l1 <- addListToSS st_l0 ws
1062 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1064 addr (st_i0,st_l0,st_p0,st_I0) a
1065 = do let ws = mkLitA a
1066 st_l1 <- addListToSS st_l0 ws
1067 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1069 ptr (st_i0,st_l0,st_p0,st_I0) p
1070 = do st_p1 <- addToSS st_p0 p
1071 return (sizeSS st_p0, (st_i0,st_l0,st_p1,st_I0))
1073 itbl (st_i0,st_l0,st_p0,st_I0) dcon
1074 = do st_I1 <- addToSS st_I0 (getName dcon)
1075 return (sizeSS st_I0, (st_i0,st_l0,st_p0,st_I1))
1077 literal st (MachInt j) = int st (fromIntegral j)
1078 literal st (MachFloat r) = float st (fromRational r)
1079 literal st (MachDouble r) = double st (fromRational r)
1080 literal st (MachChar c) = int st c
1083 = addr st ret_itbl_addr
1085 ret_itbl_addr = case pk of
1086 PtrRep -> stg_ctoi_ret_R1_info
1087 IntRep -> stg_ctoi_ret_R1_info
1088 FloatRep -> stg_ctoi_ret_F1_info
1089 DoubleRep -> stg_ctoi_ret_D1_info
1090 _ -> pprPanic "mkBits.ctoi_itbl" (ppr pk)
1092 stg_ctoi_ret_F1_info = nullAddr
1093 stg_ctoi_ret_D1_info = nullAddr
1096 = addr st ret_itbl_addr
1098 ret_itbl_addr = case pk of
1099 IntRep -> stg_gc_unbx_r1_info
1100 FloatRep -> stg_gc_f1_info
1101 DoubleRep -> stg_gc_d1_info
1103 foreign label "stg_ctoi_ret_R1_info" stg_ctoi_ret_R1_info :: Addr
1104 --foreign label "stg_ctoi_ret_F1_info" stg_ctoi_ret_F1_info :: Addr
1105 --foreign label "stg_ctoi_ret_D1_info" stg_ctoi_ret_D1_info :: Addr
1107 foreign label "stg_gc_unbx_r1_info" stg_gc_unbx_r1_info :: Addr
1108 foreign label "stg_gc_f1_info" stg_gc_f1_info :: Addr
1109 foreign label "stg_gc_d1_info" stg_gc_d1_info :: Addr
1111 -- The size in 16-bit entities of an instruction.
1112 instrSize16s :: BCInstr -> Int
1143 -- Make lists of host-sized words for literals, so that when the
1144 -- words are placed in memory at increasing addresses, the
1145 -- bit pattern is correct for the host's word size and endianness.
1146 mkLitI :: Int -> [Word]
1147 mkLitF :: Float -> [Word]
1148 mkLitD :: Double -> [Word]
1149 mkLitA :: Addr -> [Word]
1153 arr <- newFloatArray ((0::Int),0)
1154 writeFloatArray arr 0 f
1155 f_arr <- castSTUArray arr
1156 w0 <- readWordArray f_arr 0
1163 arr <- newDoubleArray ((0::Int),0)
1164 writeDoubleArray arr 0 d
1165 d_arr <- castSTUArray arr
1166 w0 <- readWordArray d_arr 0
1167 w1 <- readWordArray d_arr 1
1172 arr <- newDoubleArray ((0::Int),0)
1173 writeDoubleArray arr 0 d
1174 d_arr <- castSTUArray arr
1175 w0 <- readWordArray d_arr 0
1181 arr <- newIntArray ((0::Int),0)
1182 writeIntArray arr 0 i
1183 i_arr <- castSTUArray arr
1184 w0 <- readWordArray i_arr 0
1190 arr <- newAddrArray ((0::Int),0)
1191 writeAddrArray arr 0 a
1192 a_arr <- castSTUArray arr
1193 w0 <- readWordArray a_arr 0
1199 %************************************************************************
1201 \subsection{Linking interpretables into something we can run}
1203 %************************************************************************
1208 data BCO# = BCO# ByteArray# -- instrs :: array Word16#
1209 ByteArray# -- literals :: array Word32#
1210 PtrArray# -- ptrs :: Array HValue
1211 ByteArray# -- itbls :: Array Addr#
1214 GLOBAL_VAR(v_cafTable, [], [HValue])
1216 --addCAF :: HValue -> IO ()
1217 --addCAF x = do xs <- readIORef v_cafTable; writeIORef v_cafTable (x:xs)
1219 --bcosToHValue :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr -> IO HValue
1220 --bcosToHValue ie ce (root_bco, other_bcos)
1221 -- = do linked_expr <- linkIExpr ie ce (root_bco, other_bcos)
1222 -- return linked_expr
1224 linkBCO ie ce (UnlinkedBCO nm insnsSS literalsSS ptrsSS itblsSS)
1225 = do insns <- listFromSS insnsSS
1226 literals <- listFromSS literalsSS
1227 ptrs <- listFromSS ptrsSS
1228 itbls <- listFromSS itblsSS
1230 linked_ptrs <- mapM (lookupCE ce) ptrs
1231 linked_itbls <- mapM (lookupIE ie) itbls
1233 let n_insns = sizeSS insnsSS
1234 n_literals = sizeSS literalsSS
1235 n_ptrs = sizeSS ptrsSS
1236 n_itbls = sizeSS itblsSS
1238 let ptrs_arr = array (0, n_ptrs-1) (indexify linked_ptrs)
1240 ptrs_parr = case ptrs_arr of Array lo hi parr -> parr
1242 itbls_arr = array (0, n_itbls-1) (indexify linked_itbls)
1244 itbls_barr = case itbls_arr of UArray lo hi barr -> barr
1246 insns_arr | n_insns > 65535
1247 = panic "linkBCO: >= 64k insns in BCO"
1249 = array (0, n_insns)
1250 (indexify (fromIntegral n_insns:insns))
1251 :: UArray Int Word16
1252 insns_barr = case insns_arr of UArray lo hi barr -> barr
1254 literals_arr = array (0, n_literals-1) (indexify literals)
1256 literals_barr = case literals_arr of UArray lo hi barr -> barr
1258 indexify :: [a] -> [(Int, a)]
1259 indexify xs = zip [0..] xs
1261 BCO bco# <- newBCO insns_barr literals_barr ptrs_parr itbls_barr
1263 return (unsafeCoerce# bco#)
1268 newBCO :: ByteArray# -> ByteArray# -> Array# a -> ByteArray# -> IO BCO
1270 = IO (\s -> case newBCO# a b c d s of (# s1, bco #) -> (# s1, BCO bco #))
1273 lookupCE :: ClosureEnv -> Name -> IO HValue
1275 = case lookupFM ce nm of
1276 Just aa -> return aa
1278 -> do m <- lookupSymbol (nameToCLabel nm "closure")
1280 Just (A# addr) -> case addrToHValue# addr of
1281 (# hval #) -> return hval
1282 Nothing -> pprPanic "ByteCodeGen.lookupCE" (ppr nm)
1284 lookupIE :: ItblEnv -> Name -> IO Addr
1286 = case lookupFM ie con_nm of
1287 Just (Ptr a) -> return a
1289 -> do -- try looking up in the object files.
1290 m <- lookupSymbol (nameToCLabel con_nm "con_info")
1292 Just addr -> return addr
1294 -> do -- perhaps a nullary constructor?
1295 n <- lookupSymbol (nameToCLabel con_nm "static_info")
1297 Just addr -> return addr
1298 Nothing -> pprPanic "ByteCodeGen.lookupIE" (ppr con_nm)
1300 -- HACK!!! ToDo: cleaner
1301 nameToCLabel :: Name -> String{-suffix-} -> String
1302 nameToCLabel n suffix
1303 = _UNPK_(moduleNameFS (rdrNameModule rn))
1304 ++ '_':occNameString(rdrNameOcc rn) ++ '_':suffix
1305 where rn = toRdrName n
1309 %************************************************************************
1311 \subsection{Manufacturing of info tables for DataCons}
1313 %************************************************************************
1317 #if __GLASGOW_HASKELL__ <= 408
1320 type ItblPtr = Ptr StgInfoTable
1323 -- Make info tables for the data decls in this module
1324 mkITbls :: [TyCon] -> IO ItblEnv
1325 mkITbls [] = return emptyFM
1326 mkITbls (tc:tcs) = do itbls <- mkITbl tc
1327 itbls2 <- mkITbls tcs
1328 return (itbls `plusFM` itbls2)
1330 mkITbl :: TyCon -> IO ItblEnv
1332 | not (isDataTyCon tc)
1334 | n == length dcs -- paranoia; this is an assertion.
1335 = make_constr_itbls dcs
1337 dcs = tyConDataCons tc
1338 n = tyConFamilySize tc
1341 cONSTR = 1 -- as defined in ghc/includes/ClosureTypes.h
1343 -- Assumes constructors are numbered from zero, not one
1344 make_constr_itbls :: [DataCon] -> IO ItblEnv
1345 make_constr_itbls cons
1347 = do is <- mapM mk_vecret_itbl (zip cons [0..])
1348 return (listToFM is)
1350 = do is <- mapM mk_dirret_itbl (zip cons [0..])
1351 return (listToFM is)
1353 mk_vecret_itbl (dcon, conNo)
1354 = mk_itbl dcon conNo (vecret_entry conNo)
1355 mk_dirret_itbl (dcon, conNo)
1356 = mk_itbl dcon conNo stg_interp_constr_entry
1358 mk_itbl :: DataCon -> Int -> Addr -> IO (Name,ItblPtr)
1359 mk_itbl dcon conNo entry_addr
1360 = let (tot_wds, ptr_wds, _)
1361 = mkVirtHeapOffsets typePrimRep (dataConRepArgTys dcon)
1363 nptrs = tot_wds - ptr_wds
1364 itbl = StgInfoTable {
1365 ptrs = fromIntegral ptrs, nptrs = fromIntegral nptrs,
1366 tipe = fromIntegral cONSTR,
1367 srtlen = fromIntegral conNo,
1368 code0 = fromIntegral code0, code1 = fromIntegral code1,
1369 code2 = fromIntegral code2, code3 = fromIntegral code3,
1370 code4 = fromIntegral code4, code5 = fromIntegral code5,
1371 code6 = fromIntegral code6, code7 = fromIntegral code7
1373 -- Make a piece of code to jump to "entry_label".
1374 -- This is the only arch-dependent bit.
1375 -- On x86, if entry_label has an address 0xWWXXYYZZ,
1376 -- emit movl $0xWWXXYYZZ,%eax ; jmp *%eax
1378 -- B8 ZZ YY XX WW FF E0
1379 (code0,code1,code2,code3,code4,code5,code6,code7)
1380 = (0xB8, byte 0 entry_addr_w, byte 1 entry_addr_w,
1381 byte 2 entry_addr_w, byte 3 entry_addr_w,
1385 entry_addr_w :: Word32
1386 entry_addr_w = fromIntegral (addrToInt entry_addr)
1389 --putStrLn ("SIZE of itbl is " ++ show (sizeOf itbl))
1390 --putStrLn ("# ptrs of itbl is " ++ show ptrs)
1391 --putStrLn ("# nptrs of itbl is " ++ show nptrs)
1393 return (getName dcon, addr `plusPtr` 8)
1396 byte :: Int -> Word32 -> Word32
1397 byte 0 w = w .&. 0xFF
1398 byte 1 w = (w `shiftR` 8) .&. 0xFF
1399 byte 2 w = (w `shiftR` 16) .&. 0xFF
1400 byte 3 w = (w `shiftR` 24) .&. 0xFF
1403 vecret_entry 0 = stg_interp_constr1_entry
1404 vecret_entry 1 = stg_interp_constr2_entry
1405 vecret_entry 2 = stg_interp_constr3_entry
1406 vecret_entry 3 = stg_interp_constr4_entry
1407 vecret_entry 4 = stg_interp_constr5_entry
1408 vecret_entry 5 = stg_interp_constr6_entry
1409 vecret_entry 6 = stg_interp_constr7_entry
1410 vecret_entry 7 = stg_interp_constr8_entry
1412 -- entry point for direct returns for created constr itbls
1413 foreign label "stg_interp_constr_entry" stg_interp_constr_entry :: Addr
1414 -- and the 8 vectored ones
1415 foreign label "stg_interp_constr1_entry" stg_interp_constr1_entry :: Addr
1416 foreign label "stg_interp_constr2_entry" stg_interp_constr2_entry :: Addr
1417 foreign label "stg_interp_constr3_entry" stg_interp_constr3_entry :: Addr
1418 foreign label "stg_interp_constr4_entry" stg_interp_constr4_entry :: Addr
1419 foreign label "stg_interp_constr5_entry" stg_interp_constr5_entry :: Addr
1420 foreign label "stg_interp_constr6_entry" stg_interp_constr6_entry :: Addr
1421 foreign label "stg_interp_constr7_entry" stg_interp_constr7_entry :: Addr
1422 foreign label "stg_interp_constr8_entry" stg_interp_constr8_entry :: Addr
1428 -- Ultra-minimalist version specially for constructors
1429 data StgInfoTable = StgInfoTable {
1434 code0, code1, code2, code3, code4, code5, code6, code7 :: Word8
1438 instance Storable StgInfoTable where
1441 = (sum . map (\f -> f itbl))
1442 [fieldSz ptrs, fieldSz nptrs, fieldSz srtlen, fieldSz tipe,
1443 fieldSz code0, fieldSz code1, fieldSz code2, fieldSz code3,
1444 fieldSz code4, fieldSz code5, fieldSz code6, fieldSz code7]
1447 = (sum . map (\f -> f itbl))
1448 [fieldAl ptrs, fieldAl nptrs, fieldAl srtlen, fieldAl tipe,
1449 fieldAl code0, fieldAl code1, fieldAl code2, fieldAl code3,
1450 fieldAl code4, fieldAl code5, fieldAl code6, fieldAl code7]
1453 = do a1 <- store (ptrs itbl) (castPtr a0)
1454 a2 <- store (nptrs itbl) a1
1455 a3 <- store (tipe itbl) a2
1456 a4 <- store (srtlen itbl) a3
1457 a5 <- store (code0 itbl) a4
1458 a6 <- store (code1 itbl) a5
1459 a7 <- store (code2 itbl) a6
1460 a8 <- store (code3 itbl) a7
1461 a9 <- store (code4 itbl) a8
1462 aA <- store (code5 itbl) a9
1463 aB <- store (code6 itbl) aA
1464 aC <- store (code7 itbl) aB
1468 = do (a1,ptrs) <- load (castPtr a0)
1469 (a2,nptrs) <- load a1
1470 (a3,tipe) <- load a2
1471 (a4,srtlen) <- load a3
1472 (a5,code0) <- load a4
1473 (a6,code1) <- load a5
1474 (a7,code2) <- load a6
1475 (a8,code3) <- load a7
1476 (a9,code4) <- load a8
1477 (aA,code5) <- load a9
1478 (aB,code6) <- load aA
1479 (aC,code7) <- load aB
1480 return StgInfoTable { ptrs = ptrs, nptrs = nptrs,
1481 srtlen = srtlen, tipe = tipe,
1482 code0 = code0, code1 = code1, code2 = code2,
1483 code3 = code3, code4 = code4, code5 = code5,
1484 code6 = code6, code7 = code7 }
1486 fieldSz :: (Storable a, Storable b) => (a -> b) -> a -> Int
1487 fieldSz sel x = sizeOf (sel x)
1489 fieldAl :: (Storable a, Storable b) => (a -> b) -> a -> Int
1490 fieldAl sel x = alignment (sel x)
1492 store :: Storable a => a -> Ptr a -> IO (Ptr b)
1493 store x addr = do poke addr x
1494 return (castPtr (addr `plusPtr` sizeOf x))
1496 load :: Storable a => Ptr a -> IO (Ptr b, a)
1497 load addr = do x <- peek addr
1498 return (castPtr (addr `plusPtr` sizeOf x), x)
1502 %************************************************************************
1504 \subsection{Connect to actual values for bytecode opcodes}
1506 %************************************************************************
1510 #include "Bytecodes.h"
1512 i_ARGCHECK = (bci_ARGCHECK :: Int)
1513 i_PUSH_L = (bci_PUSH_L :: Int)
1514 i_PUSH_LL = (bci_PUSH_LL :: Int)
1515 i_PUSH_LLL = (bci_PUSH_LLL :: Int)
1516 i_PUSH_G = (bci_PUSH_G :: Int)
1517 i_PUSH_AS = (bci_PUSH_AS :: Int)
1518 i_PUSH_UBX = (bci_PUSH_UBX :: Int)
1519 i_PUSH_TAG = (bci_PUSH_TAG :: Int)
1520 i_SLIDE = (bci_SLIDE :: Int)
1521 i_ALLOC = (bci_ALLOC :: Int)
1522 i_MKAP = (bci_MKAP :: Int)
1523 i_UNPACK = (bci_UNPACK :: Int)
1524 i_UPK_TAG = (bci_UPK_TAG :: Int)
1525 i_PACK = (bci_PACK :: Int)
1526 i_TESTLT_I = (bci_TESTLT_I :: Int)
1527 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
1528 i_TESTLT_F = (bci_TESTLT_F :: Int)
1529 i_TESTEQ_F = (bci_TESTEQ_F :: Int)
1530 i_TESTLT_D = (bci_TESTLT_D :: Int)
1531 i_TESTEQ_D = (bci_TESTEQ_D :: Int)
1532 i_TESTLT_P = (bci_TESTLT_P :: Int)
1533 i_TESTEQ_P = (bci_TESTEQ_P :: Int)
1534 i_CASEFAIL = (bci_CASEFAIL :: Int)
1535 i_ENTER = (bci_ENTER :: Int)
1536 i_RETURN = (bci_RETURN :: Int)