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 )
17 import Id ( Id, idType, isDataConId_maybe )
18 import OrdList ( OrdList, consOL, snocOL, appOL, unitOL,
19 nilOL, toOL, concatOL, fromOL )
20 import FiniteMap ( FiniteMap, addListToFM, listToFM, filterFM,
21 addToFM, lookupFM, fmToList, emptyFM, plusFM )
23 import PprCore ( pprCoreExpr, pprCoreAlt )
24 import Literal ( Literal(..) )
25 import PrimRep ( PrimRep(..) )
26 import CoreFVs ( freeVars )
27 import Type ( typePrimRep )
28 import DataCon ( DataCon, dataConTag, fIRST_TAG, dataConTyCon,
30 import TyCon ( TyCon, tyConFamilySize, isDataTyCon, tyConDataCons )
31 import Class ( Class, classTyCon )
32 import Util ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem, global )
33 import Var ( isTyVar )
34 import VarSet ( VarSet, varSetElems )
35 import PrimRep ( getPrimRepSize, isFollowableRep )
36 import Constants ( wORD_SIZE )
37 import CmdLineOpts ( DynFlags, DynFlag(..) )
38 import ErrUtils ( showPass, dumpIfSet_dyn )
39 import ClosureInfo ( mkVirtHeapOffsets )
40 import Module ( ModuleName, moduleName )
42 import List ( intersperse )
43 import Monad ( foldM )
45 import MArray ( MArray(..), IOArray, IOUArray, HasBounds(..), freeze,
46 mapArray, castSTUArray,
47 newFloatArray, writeFloatArray,
48 newDoubleArray, writeDoubleArray,
49 newIntArray, writeIntArray,
50 newAddrArray, writeAddrArray )
51 import Foreign ( Storable(..), Word8, Word16, Word32, Ptr(..),
52 malloc, castPtr, plusPtr )
53 import Addr ( Word, Addr, addrToInt, nullAddr )
54 import Bits ( Bits(..), shiftR )
56 import PrelGHC ( BCO#, newBCO#, unsafeCoerce#, ByteArray#, Array# )
57 import IOExts ( IORef, readIORef, writeIORef, fixIO )
59 import PrelArr ( Array(..) )
60 import PrelIOBase ( IO(..) )
64 %************************************************************************
66 \subsection{Functions visible from outside this module.}
68 %************************************************************************
72 byteCodeGen :: DynFlags
75 -> IO ([UnlinkedBCO], ItblEnv)
76 byteCodeGen dflags binds local_tycons local_classes
77 = do showPass dflags "ByteCodeGen"
78 let tycs = local_tycons ++ map classTyCon local_classes
79 itblenv <- mkITbls tycs
81 let flatBinds = concatMap getBind binds
82 getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
83 getBind (Rec binds) = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
84 final_state = runBc (BcM_State [] 0)
85 (mapBc schemeR flatBinds `thenBc_` returnBc ())
86 (BcM_State proto_bcos final_ctr) = final_state
88 dumpIfSet_dyn dflags Opt_D_dump_BCOs
89 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
91 bcos <- mapM assembleBCO proto_bcos
93 return (bcos, itblenv)
96 -- Returns: (the root BCO for this expression,
97 -- a list of auxilary BCOs resulting from compiling closures)
98 coreExprToBCOs :: DynFlags
100 -> IO UnlinkedBCOExpr
101 coreExprToBCOs dflags expr
102 = do showPass dflags "ByteCodeGen"
103 let invented_id = panic "invented_id" :: Id
104 (BcM_State all_proto_bcos final_ctr)
105 = runBc (BcM_State [] 0)
106 (schemeR (invented_id, freeVars expr))
107 dumpIfSet_dyn dflags Opt_D_dump_InterpSyn
108 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr all_proto_bcos)))
110 let invented_name = getName invented_id
112 = case filter ((== invented_name).nameOfProtoBCO) all_proto_bcos of
113 [root_bco] -> root_bco
115 = filter ((/= invented_name).nameOfProtoBCO) all_proto_bcos
117 auxiliary_bcos <- mapM assembleBCO auxiliary_proto_bcos
118 root_bco <- assembleBCO root_proto_bco
120 return (root_bco, auxiliary_bcos)
127 Int (IOUArray Int Word16) -- insns
128 Int (IOUArray Int Word) -- literals
129 Int (IOArray Int Name) -- ptrs
130 Int (IOArray Int Name) -- itbl refs
132 nameOfUnlinkedBCO (UnlinkedBCO nm _ _ _ _ _ _ _ _) = nm
134 -- When translating expressions, we need to distinguish the root
135 -- BCO for the expression
136 type UnlinkedBCOExpr = (UnlinkedBCO, [UnlinkedBCO])
138 instance Outputable UnlinkedBCO where
139 ppr (UnlinkedBCO nm n_insns insns n_lits lits n_ptrs ptrs n_itbls itbls)
140 = sep [text "BCO", ppr nm, text "with",
141 int n_insns, text "insns",
142 int n_lits, text "lits",
143 int n_ptrs, text "ptrs",
144 int n_itbls, text "itbls"]
147 -- these need a proper home
148 type ItblEnv = FiniteMap Name (Ptr StgInfoTable)
149 type ClosureEnv = FiniteMap Name HValue
150 data HValue = HValue -- dummy type, actually a pointer to some Real Code.
152 -- remove all entries for a given set of modules from the environment
153 filterNameMap :: [ModuleName] -> FiniteMap Name a -> FiniteMap Name a
154 filterNameMap mods env
155 = filterFM (\n _ -> moduleName (nameModule n) `notElem` mods) env
158 %************************************************************************
160 \subsection{Bytecodes, and Outputery.}
162 %************************************************************************
166 type LocalLabel = Int
168 data UnboxedLit = UnboxedI Int | UnboxedF Float | UnboxedD Double
171 -- Messing with the stack
173 -- Push locals (existing bits of the stack)
174 | PUSH_L Int{-offset-}
175 | PUSH_LL Int Int{-2 offsets-}
176 | PUSH_LLL Int Int Int{-3 offsets-}
179 -- Push an alt continuation
180 | PUSH_AS Name PrimRep -- push alts and BCO_ptr_ret_info
181 -- PrimRep so we know which itbl
183 | PUSH_UBX Literal Int
184 -- push this int/float/double, NO TAG, on the stack
185 -- Int is # of items in literal pool to push
186 | PUSH_TAG Int -- push this tag on the stack
188 | SLIDE Int{-this many-} Int{-down by this much-}
189 -- To do with the heap
190 | ALLOC Int -- make an AP_UPD with this many payload words, zeroed
191 | MKAP Int{-ptr to AP_UPD is this far down stack-} Int{-# words-}
192 | UNPACK Int -- unpack N ptr words from t.o.s Constr
193 | UPK_TAG Int Int Int
194 -- unpack N non-ptr words from offset M in constructor
195 -- K words down the stack
197 -- after assembly, the DataCon is an index into the
199 -- For doing case trees
201 | TESTLT_I Int LocalLabel
202 | TESTEQ_I Int LocalLabel
203 | TESTLT_F Float LocalLabel
204 | TESTEQ_F Float LocalLabel
205 | TESTLT_D Double LocalLabel
206 | TESTEQ_D Double LocalLabel
207 | TESTLT_P Int LocalLabel
208 | TESTEQ_P Int LocalLabel
210 -- To Infinity And Beyond
212 | RETURN -- unboxed value on TOS. Use tag to find underlying ret itbl
213 -- and return as per that.
216 instance Outputable BCInstr where
217 ppr (ARGCHECK n) = text "ARGCHECK" <+> int n
218 ppr (PUSH_L offset) = text "PUSH_L " <+> int offset
219 ppr (PUSH_LL o1 o2) = text "PUSH_LL " <+> int o1 <+> int o2
220 ppr (PUSH_LLL o1 o2 o3) = text "PUSH_LLL" <+> int o1 <+> int o2 <+> int o3
221 ppr (PUSH_G nm) = text "PUSH_G " <+> ppr nm
222 ppr (PUSH_AS nm pk) = text "PUSH_AS " <+> ppr nm <+> ppr pk
223 ppr (SLIDE n d) = text "SLIDE " <+> int n <+> int d
224 ppr (ALLOC sz) = text "ALLOC " <+> int sz
225 ppr (MKAP offset sz) = text "MKAP " <+> int offset <+> int sz
226 ppr (UNPACK sz) = text "UNPACK " <+> int sz
227 ppr (PACK dcon sz) = text "PACK " <+> ppr dcon <+> ppr sz
228 ppr (LABEL lab) = text "__" <> int lab <> colon
229 ppr (TESTLT_I i lab) = text "TESTLT_I" <+> int i <+> text "__" <> int lab
230 ppr (TESTEQ_I i lab) = text "TESTEQ_I" <+> int i <+> text "__" <> int lab
231 ppr (TESTLT_F f lab) = text "TESTLT_F" <+> float f <+> text "__" <> int lab
232 ppr (TESTEQ_F f lab) = text "TESTEQ_F" <+> float f <+> text "__" <> int lab
233 ppr (TESTLT_D d lab) = text "TESTLT_D" <+> double d <+> text "__" <> int lab
234 ppr (TESTEQ_D d lab) = text "TESTEQ_D" <+> double d <+> text "__" <> int lab
235 ppr (TESTLT_P i lab) = text "TESTLT_P" <+> int i <+> text "__" <> int lab
236 ppr (TESTEQ_P i lab) = text "TESTEQ_P" <+> int i <+> text "__" <> int lab
237 ppr CASEFAIL = text "CASEFAIL"
238 ppr ENTER = text "ENTER"
239 ppr RETURN = text "RETURN"
241 pprAltCode discrs_n_codes
242 = vcat (map f discrs_n_codes)
243 where f (discr, code) = ppr discr <> colon <+> vcat (map ppr (fromOL code))
245 instance Outputable a => Outputable (ProtoBCO a) where
246 ppr (ProtoBCO name instrs origin)
247 = (text "ProtoBCO" <+> ppr name <> colon)
248 $$ nest 6 (vcat (map ppr instrs))
250 Left alts -> vcat (map (pprCoreAlt.deAnnAlt) alts)
251 Right rhs -> pprCoreExpr (deAnnotate rhs)
254 %************************************************************************
256 \subsection{Compilation schema for the bytecode generator.}
258 %************************************************************************
262 type BCInstrList = OrdList BCInstr
265 = ProtoBCO a -- name, in some sense
267 -- what the BCO came from
268 (Either [AnnAlt Id VarSet]
271 nameOfProtoBCO (ProtoBCO nm insns origin) = nm
274 type Sequel = Int -- back off to this depth before ENTER
276 -- Maps Ids to the offset from the stack _base_ so we don't have
277 -- to mess with it after each push/pop.
278 type BCEnv = FiniteMap Id Int -- To find vars on the stack
281 -- Create a BCO and do a spot of peephole optimisation on the insns
283 mkProtoBCO nm instrs_ordlist origin
284 = ProtoBCO nm (peep (fromOL instrs_ordlist)) origin
286 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
287 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
288 peep (PUSH_L off1 : PUSH_L off2 : rest)
289 = PUSH_LL off1 off2 : peep rest
296 -- Compile code for the right hand side of a let binding.
297 -- Park the resulting BCO in the monad. Also requires the
298 -- variable to which this value was bound, so as to give the
299 -- resulting BCO a name.
300 schemeR :: (Id, AnnExpr Id VarSet) -> BcM ()
301 schemeR (nm, rhs) = schemeR_wrk rhs nm (collect [] rhs)
303 collect xs (_, AnnLam x e)
304 = collect (if isTyVar x then xs else (x:xs)) e
305 collect xs not_lambda
306 = (reverse xs, not_lambda)
308 schemeR_wrk original_body nm (args, body)
309 = let fvs = filter (not.isTyVar) (varSetElems (fst original_body))
310 all_args = fvs ++ reverse args
311 szsw_args = map taggedIdSizeW all_args
312 szw_args = sum szsw_args
313 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
314 argcheck = if null args then nilOL else unitOL (ARGCHECK szw_args)
316 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
317 emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) (Right original_body))
319 -- Let szsw be the sizes in words of some items pushed onto the stack,
320 -- which has initial depth d'. Return the values which the stack environment
321 -- should map these items to.
322 mkStackOffsets :: Int -> [Int] -> [Int]
323 mkStackOffsets original_depth szsw
324 = map (subtract 1) (tail (scanl (+) original_depth szsw))
326 -- Compile code to apply the given expression to the remaining args
327 -- on the stack, returning a HNF.
328 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
330 -- Delegate tail-calls to schemeT.
331 schemeE d s p e@(fvs, AnnApp f a)
332 = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnApp f a))
333 schemeE d s p e@(fvs, AnnVar v)
334 | isFollowableRep (typePrimRep (idType v))
335 = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnVar v))
337 = -- returning an unboxed value. Heave it on the stack, SLIDE, and RETURN.
338 let (push, szw) = pushAtom True d p (AnnVar v)
339 in returnBc (push -- value onto stack
340 `snocOL` SLIDE szw (d-s) -- clear to sequel
341 `snocOL` RETURN) -- go
343 schemeE d s p (fvs, AnnLit literal)
344 = let (push, szw) = pushAtom True d p (AnnLit literal)
345 in returnBc (push -- value onto stack
346 `snocOL` SLIDE szw (d-s) -- clear to sequel
347 `snocOL` RETURN) -- go
349 schemeE d s p (fvs, AnnLet binds b)
350 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
351 AnnRec xs_n_rhss -> unzip xs_n_rhss
353 fvss = map (filter (not.isTyVar).varSetElems.fst) rhss
354 sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
356 -- This p', d' defn is safe because all the items being pushed
357 -- are ptrs, so all have size 1. d' and p' reflect the stack
358 -- after the closures have been allocated in the heap (but not
359 -- filled in), and pointers to them parked on the stack.
360 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
363 infos = zipE4 fvss sizes xs [n, n-1 .. 1]
364 zipE = zipEqual "schemeE"
365 zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
367 -- ToDo: don't build thunks for things with no free variables
368 buildThunk dd ([], size, id, off)
369 = PUSH_G (getName id)
370 `consOL` unitOL (MKAP (off+size-1) size)
371 buildThunk dd ((fv:fvs), size, id, off)
372 = case pushAtom True dd p' (AnnVar fv) of
373 (push_code, pushed_szw)
375 buildThunk (dd+pushed_szw) (fvs, size, id, off)
377 thunkCode = concatOL (map (buildThunk d') infos)
378 allocCode = toOL (map ALLOC sizes)
380 schemeE d' s p' b `thenBc` \ bodyCode ->
381 mapBc schemeR (zip xs rhss) `thenBc_`
382 returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
385 schemeE d s p (fvs, AnnCase scrut bndr alts)
387 -- Top of stack is the return itbl, as usual.
388 -- underneath it is the pointer to the alt_code BCO.
389 -- When an alt is entered, it assumes the returned value is
390 -- on top of the itbl.
393 -- Env and depth in which to compile the alts, not including
394 -- any vars bound by the alts themselves
395 d' = d + ret_frame_sizeW + taggedIdSizeW bndr
396 p' = addToFM p bndr (d' - 1)
398 scrut_primrep = typePrimRep (idType bndr)
400 = case scrut_primrep of
401 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
403 other -> pprPanic "ByteCodeGen.schemeE" (ppr other)
405 -- given an alt, return a discr and code for it.
406 codeAlt alt@(discr, binds_f, rhs)
408 = let binds_r = reverse binds_f
409 binds_r_szsw = map untaggedIdSizeW binds_r
410 binds_szw = sum binds_r_szsw
412 p' (zip binds_r (mkStackOffsets d' binds_r_szsw))
414 unpack_code = mkUnpackCode 0 0 (map (typePrimRep.idType) binds_f)
415 in schemeE d'' s p'' rhs `thenBc` \ rhs_code ->
416 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
418 = ASSERT(null binds_f)
419 schemeE d' s p' rhs `thenBc` \ rhs_code ->
420 returnBc (my_discr alt, rhs_code)
422 my_discr (DEFAULT, binds, rhs) = NoDiscr
423 my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc)
424 my_discr (LitAlt l, binds, rhs)
425 = case l of MachInt i -> DiscrI (fromInteger i)
426 MachFloat r -> DiscrF (fromRational r)
427 MachDouble r -> DiscrD (fromRational r)
430 | not isAlgCase = Nothing
432 = case [dc | (DataAlt dc, _, _) <- alts] of
434 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
437 mapBc codeAlt alts `thenBc` \ alt_stuff ->
438 mkMultiBranch maybe_ncons alt_stuff `thenBc` \ alt_final ->
440 alt_bco_name = getName bndr
441 alt_bco = mkProtoBCO alt_bco_name alt_final (Left alts)
443 schemeE (d + ret_frame_sizeW)
444 (d + ret_frame_sizeW) p scrut `thenBc` \ scrut_code ->
446 emitBc alt_bco `thenBc_`
447 returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
450 schemeE d s p (fvs, AnnNote note body)
454 = pprPanic "ByteCodeGen.schemeE: unhandled case"
455 (pprCoreExpr (deAnnotate other))
458 -- Compile code to do a tail call. Doesn't need to be monadic.
459 schemeT :: Bool -- do tagging?
460 -> Int -- Stack depth
461 -> Sequel -- Sequel depth
462 -> Int -- # arg words so far
463 -> BCEnv -- stack env
467 schemeT enTag d s narg_words p (_, AnnApp f a)
469 AnnType _ -> schemeT enTag d s narg_words p f
471 -> let (push, arg_words) = pushAtom enTag d p (snd a)
473 `appOL` schemeT enTag (d+arg_words) s (narg_words+arg_words) p f
475 schemeT enTag d s narg_words p (_, AnnVar f)
476 | Just con <- isDataConId_maybe f
477 = ASSERT(enTag == False)
478 PACK con narg_words `consOL` (mkSLIDE 1 (d-s-1) `snocOL` ENTER)
480 = ASSERT(enTag == True)
481 let (push, arg_words) = pushAtom True d p (AnnVar f)
483 `appOL` mkSLIDE (narg_words+arg_words) (d - s - narg_words)
487 = if d == 0 then nilOL else unitOL (SLIDE n d)
489 should_args_be_tagged (_, AnnVar v)
490 = case isDataConId_maybe v of
491 Just dcon -> False; Nothing -> True
492 should_args_be_tagged (_, AnnApp f a)
493 = should_args_be_tagged f
494 should_args_be_tagged (_, other)
495 = panic "should_args_be_tagged: tail call to non-con, non-var"
498 -- Make code to unpack a constructor onto the stack, adding
499 -- tags for the unboxed bits. Takes the PrimReps of the constructor's
500 -- arguments, and a travelling offset along both the constructor
501 -- (off_h) and the stack (off_s).
502 mkUnpackCode :: Int -> Int -> [PrimRep] -> BCInstrList
503 mkUnpackCode off_h off_s [] = nilOL
504 mkUnpackCode off_h off_s (r:rs)
506 = let (rs_ptr, rs_nptr) = span isFollowableRep (r:rs)
507 ptrs_szw = sum (map untaggedSizeW rs_ptr)
508 in ASSERT(ptrs_szw == length rs_ptr)
512 `consOL` mkUnpackCode (off_h + ptrs_szw) (off_s + ptrs_szw) rs_nptr
517 DoubleRep -> approved
519 approved = UPK_TAG usizeW off_h off_s `consOL` theRest
520 theRest = mkUnpackCode (off_h + usizeW) (off_s + tsizeW) rs
521 usizeW = untaggedSizeW r
522 tsizeW = taggedSizeW r
524 -- Push an atom onto the stack, returning suitable code & number of
525 -- stack words used. Pushes it either tagged or untagged, since
526 -- pushAtom is used to set up the stack prior to copying into the
527 -- heap for both APs (requiring tags) and constructors (which don't).
529 -- NB this means NO GC between pushing atoms for a constructor and
530 -- copying them into the heap. It probably also means that
531 -- tail calls MUST be of the form atom{atom ... atom} since if the
532 -- expression head was allowed to be arbitrary, there could be GC
533 -- in between pushing the arg atoms and completing the head.
534 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
535 -- isn't a problem; but only if arbitrary graph construction for the
536 -- head doesn't leave this BCO, since GC might happen at the start of
537 -- each BCO (we consult doYouWantToGC there).
539 -- Blargh. JRS 001206
541 -- NB (further) that the env p must map each variable to the highest-
542 -- numbered stack slot for it. For example, if the stack has depth 4
543 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
544 -- the tag in stack[5], the stack will have depth 6, and p must map v to
545 -- 5 and not to 4. Stack locations are numbered from zero, so a depth
546 -- 6 stack has valid words 0 .. 5.
548 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
549 pushAtom tagged d p (AnnVar v)
550 = let str = "\npushAtom " ++ showSDocDebug (ppr v) ++ ", depth = " ++ show d
552 showSDocDebug (nest 4 (vcat (map ppr (fmToList p))))
554 showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
555 ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
556 str' = if str == str then str else str
559 = case lookupBCEnv_maybe p v of
560 Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), sz_t)
561 Nothing -> ASSERT(sz_t == 1) (unitOL (PUSH_G nm), sz_t)
564 sz_t = taggedIdSizeW v
565 sz_u = untaggedIdSizeW v
566 nwords = if tagged then sz_t else sz_u
571 pushAtom True d p (AnnLit lit)
572 = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
573 in (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
575 pushAtom False d p (AnnLit lit)
577 MachInt i -> code IntRep
578 MachFloat r -> code FloatRep
579 MachDouble r -> code DoubleRep
582 = let size_host_words = untaggedSizeW rep
583 in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
585 pushAtom tagged d p (AnnApp f (_, AnnType _))
586 = pushAtom tagged d p (snd f)
588 pushAtom tagged d p other
589 = pprPanic "ByteCodeGen.pushAtom"
590 (pprCoreExpr (deAnnotate (undefined, other)))
593 -- Given a bunch of alts code and their discrs, do the donkey work
594 -- of making a multiway branch using a switch tree.
595 -- What a load of hassle!
596 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
597 -- a hint; generates better code
598 -- Nothing is always safe
599 -> [(Discr, BCInstrList)]
601 mkMultiBranch maybe_ncons raw_ways
602 = let d_way = filter (isNoDiscr.fst) raw_ways
603 notd_ways = naturalMergeSortLe
604 (\w1 w2 -> leAlt (fst w1) (fst w2))
605 (filter (not.isNoDiscr.fst) raw_ways)
607 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
608 mkTree [] range_lo range_hi = returnBc the_default
610 mkTree [val] range_lo range_hi
611 | range_lo `eqAlt` range_hi
614 = getLabelBc `thenBc` \ label_neq ->
615 returnBc (mkTestEQ (fst val) label_neq
617 `appOL` unitOL (LABEL label_neq)
618 `appOL` the_default))
620 mkTree vals range_lo range_hi
621 = let n = length vals `div` 2
622 vals_lo = take n vals
623 vals_hi = drop n vals
624 v_mid = fst (head vals_hi)
626 getLabelBc `thenBc` \ label_geq ->
627 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
628 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
629 returnBc (mkTestLT v_mid label_geq
631 `appOL` unitOL (LABEL label_geq)
635 = case d_way of [] -> unitOL CASEFAIL
638 -- None of these will be needed if there are no non-default alts
639 (mkTestLT, mkTestEQ, init_lo, init_hi)
641 = panic "mkMultiBranch: awesome foursome"
643 = case fst (head notd_ways) of {
644 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
645 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
648 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
649 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
652 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
653 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
656 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
657 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
662 (algMinBound, algMaxBound)
663 = case maybe_ncons of
664 Just n -> (fIRST_TAG, fIRST_TAG + n - 1)
665 Nothing -> (minBound, maxBound)
667 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
668 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
669 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
670 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
671 NoDiscr `eqAlt` NoDiscr = True
674 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
675 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
676 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
677 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
678 NoDiscr `leAlt` NoDiscr = True
681 isNoDiscr NoDiscr = True
684 dec (DiscrI i) = DiscrI (i-1)
685 dec (DiscrP i) = DiscrP (i-1)
686 dec other = other -- not really right, but if you
687 -- do cases on floating values, you'll get what you deserve
689 -- same snotty comment applies to the following
697 mkTree notd_ways init_lo init_hi
701 %************************************************************************
703 \subsection{Supporting junk for the compilation schemes}
705 %************************************************************************
709 -- Describes case alts
717 instance Outputable Discr where
718 ppr (DiscrI i) = int i
719 ppr (DiscrF f) = text (show f)
720 ppr (DiscrD d) = text (show d)
721 ppr (DiscrP i) = int i
722 ppr NoDiscr = text "DEF"
725 -- Find things in the BCEnv (the what's-on-the-stack-env)
726 -- See comment preceding pushAtom for precise meaning of env contents
727 lookupBCEnv :: BCEnv -> Id -> Int
729 = case lookupFM env nm of
730 Nothing -> pprPanic "lookupBCEnv"
731 (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
734 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
735 lookupBCEnv_maybe = lookupFM
738 -- When I push one of these on the stack, how much does Sp move by?
739 taggedSizeW :: PrimRep -> Int
741 | isFollowableRep pr = 1
742 | otherwise = 1{-the tag-} + getPrimRepSize pr
745 -- The plain size of something, without tag.
746 untaggedSizeW :: PrimRep -> Int
748 | isFollowableRep pr = 1
749 | otherwise = getPrimRepSize pr
752 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
753 taggedIdSizeW = taggedSizeW . typePrimRep . idType
754 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
758 %************************************************************************
760 \subsection{The bytecode generator's monad}
762 %************************************************************************
766 = BcM_State { bcos :: [ProtoBCO Name], -- accumulates completed BCOs
767 nextlabel :: Int } -- for generating local labels
769 type BcM result = BcM_State -> (result, BcM_State)
771 mkBcM_State :: [ProtoBCO Name] -> Int -> BcM_State
772 mkBcM_State = BcM_State
774 runBc :: BcM_State -> BcM () -> BcM_State
775 runBc init_st m = case m init_st of { (r,st) -> st }
777 thenBc :: BcM a -> (a -> BcM b) -> BcM b
779 = case expr st of { (result, st') -> cont result st' }
781 thenBc_ :: BcM a -> BcM b -> BcM b
783 = case expr st of { (result, st') -> cont st' }
785 returnBc :: a -> BcM a
786 returnBc result st = (result, st)
788 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
789 mapBc f [] = returnBc []
791 = f x `thenBc` \ r ->
792 mapBc f xs `thenBc` \ rs ->
795 emitBc :: ProtoBCO Name -> BcM ()
797 = ((), st{bcos = bco : bcos st})
799 getLabelBc :: BcM Int
801 = (nextlabel st, st{nextlabel = 1 + nextlabel st})
805 %************************************************************************
807 \subsection{The bytecode assembler}
809 %************************************************************************
811 The object format for bytecodes is: 16 bits for the opcode, and 16 for
812 each field -- so the code can be considered a sequence of 16-bit ints.
813 Each field denotes either a stack offset or number of items on the
814 stack (eg SLIDE), and index into the pointer table (eg PUSH_G), an
815 index into the literal table (eg PUSH_I/D/L), or a bytecode address in
819 -- Top level assembler fn.
820 assembleBCO :: ProtoBCO Name -> IO UnlinkedBCO
822 assembleBCO (ProtoBCO nm instrs origin)
824 -- pass 1: collect up the offsets of the local labels
825 label_env = mkLabelEnv emptyFM 0 instrs
827 mkLabelEnv env i_offset [] = env
828 mkLabelEnv env i_offset (i:is)
830 = case i of LABEL n -> addToFM env n i_offset ; _ -> env
831 in mkLabelEnv new_env (i_offset + instrSizeB i) is
834 = case lookupFM label_env lab of
835 Just bco_offset -> bco_offset
836 Nothing -> pprPanic "assembleBCO.findLabel" (int lab)
843 do insns <- newXIOUArray init_n_insns :: IO (XIOUArray Word16)
844 lits <- newXIOUArray init_n_lits :: IO (XIOUArray Word)
845 ptrs <- newXIOArray init_n_ptrs -- :: IO (XIOArray Name)
846 itbls <- newXIOArray init_n_itbls -- :: IO (XIOArray Name)
848 -- pass 2: generate the instruction, ptr and nonptr bits
849 let init_asm_state = (insns,lits,ptrs,itbls)
850 final_asm_state <- mkBits findLabel init_asm_state instrs
852 -- unwrap the expandable arrays
853 let final_insns = stuffXIOU insns
854 final_lits = stuffXIOU lits
855 final_ptrs = stuffXIO ptrs
856 final_itbls = stuffXIO itbls
858 return (UnlinkedBCO nm
859 (usedXIOU insns) final_insns
860 (usedXIOU lits) final_lits
861 (usedXIO ptrs) final_ptrs
862 (usedXIO itbls) final_itbls)
865 -- instrs nonptrs ptrs itbls
866 type AsmState = (XIOUArray Word16, XIOUArray Word, XIOArray Name, XIOArray Name)
869 -- This is where all the action is (pass 2 of the assembler)
870 mkBits :: (Int -> Int) -- label finder
872 -> [BCInstr] -- instructions (in)
875 mkBits findLabel st proto_insns
876 = foldM doInstr st proto_insns
878 doInstr :: AsmState -> BCInstr -> IO AsmState
881 ARGCHECK n -> instr2 st i_ARGCHECK n
882 PUSH_L o1 -> instr2 st i_PUSH_L o1
883 PUSH_LL o1 o2 -> instr3 st i_PUSH_LL o1 o2
884 PUSH_LLL o1 o2 o3 -> instr4 st i_PUSH_LLL o1 o2 o3
885 PUSH_G nm -> do (p, st2) <- ptr st nm
886 instr2 st2 i_PUSH_G p
887 PUSH_AS nm pk -> do (p, st2) <- ptr st nm
888 (np, st3) <- ret_itbl st2 pk
889 instr3 st3 i_PUSH_AS p np
890 PUSH_UBX lit nw32s -> do (np, st2) <- literal st lit
891 instr3 st2 i_PUSH_UBX np nw32s
892 PUSH_TAG tag -> instr2 st i_PUSH_TAG tag
893 SLIDE n by -> instr3 st i_SLIDE n by
894 ALLOC n -> instr2 st i_ALLOC n
895 MKAP off sz -> instr3 st i_MKAP off sz
896 UNPACK n -> instr2 st i_UNPACK n
897 UPK_TAG n m k -> instr4 st i_UPK_TAG n m k
898 PACK dcon sz -> do (itbl_no,st2) <- itbl st dcon
899 instr3 st2 i_PACK itbl_no sz
900 LABEL lab -> return st
901 TESTLT_I i l -> do (np, st2) <- int st i
902 instr3 st2 i_TESTLT_I np (findLabel l)
903 TESTEQ_I i l -> do (np, st2) <- int st i
904 instr3 st2 i_TESTEQ_I np (findLabel l)
905 TESTLT_F f l -> do (np, st2) <- float st f
906 instr3 st2 i_TESTLT_F np (findLabel l)
907 TESTEQ_F f l -> do (np, st2) <- float st f
908 instr3 st2 i_TESTEQ_F np (findLabel l)
909 TESTLT_D d l -> do (np, st2) <- double st d
910 instr3 st2 i_TESTLT_D np (findLabel l)
911 TESTEQ_D d l -> do (np, st2) <- double st d
912 instr3 st2 i_TESTEQ_D np (findLabel l)
913 TESTLT_P i l -> do (np, st2) <- int st i
914 instr3 st2 i_TESTLT_P np (findLabel l)
915 TESTEQ_P i l -> do (np, st2) <- int st i
916 instr3 st2 i_TESTEQ_P np (findLabel l)
917 CASEFAIL -> instr1 st i_CASEFAIL
918 ENTER -> instr1 st i_ENTER
919 RETURN -> instr1 st i_RETURN
924 instr1 (st_i0,st_l0,st_p0,st_I0) i1
925 = do st_i1 <- addToXIOUArray st_i0 (i2s i1)
926 return (st_i1,st_l0,st_p0,st_I0)
928 instr2 (st_i0,st_l0,st_p0,st_I0) i1 i2
929 = do st_i1 <- addToXIOUArray st_i0 (i2s i1)
930 st_i2 <- addToXIOUArray st_i1 (i2s i2)
931 return (st_i2,st_l0,st_p0,st_I0)
933 instr3 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3
934 = do st_i1 <- addToXIOUArray st_i0 (i2s i1)
935 st_i2 <- addToXIOUArray st_i1 (i2s i2)
936 st_i3 <- addToXIOUArray st_i2 (i2s i3)
937 return (st_i3,st_l0,st_p0,st_I0)
939 instr4 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3 i4
940 = do st_i1 <- addToXIOUArray st_i0 (i2s i1)
941 st_i2 <- addToXIOUArray st_i1 (i2s i2)
942 st_i3 <- addToXIOUArray st_i2 (i2s i3)
943 st_i4 <- addToXIOUArray st_i3 (i2s i4)
944 return (st_i4,st_l0,st_p0,st_I0)
946 float (st_i0,st_l0,st_p0,st_I0) f
947 = do let w32s = mkLitF f
948 st_l1 <- addListToXIOUArray st_l0 w32s
949 return (usedXIOU st_l0, (st_i0,st_l1,st_p0,st_I0))
951 double (st_i0,st_l0,st_p0,st_I0) d
952 = do let w32s = mkLitD d
953 st_l1 <- addListToXIOUArray st_l0 w32s
954 return (usedXIOU st_l0, (st_i0,st_l1,st_p0,st_I0))
956 int (st_i0,st_l0,st_p0,st_I0) i
957 = do let w32s = mkLitI i
958 st_l1 <- addListToXIOUArray st_l0 w32s
959 return (usedXIOU st_l0, (st_i0,st_l1,st_p0,st_I0))
961 addr (st_i0,st_l0,st_p0,st_I0) a
962 = do let w32s = mkLitA a
963 st_l1 <- addListToXIOUArray st_l0 w32s
964 return (usedXIOU st_l0, (st_i0,st_l1,st_p0,st_I0))
966 ptr (st_i0,st_l0,st_p0,st_I0) p
967 = do st_p1 <- addToXIOArray st_p0 p
968 return (usedXIO st_p0, (st_i0,st_l0,st_p1,st_I0))
970 itbl (st_i0,st_l0,st_p0,st_I0) dcon
971 = do st_I1 <- addToXIOArray st_I0 (getName dcon)
972 return (usedXIO st_I0, (st_i0,st_l0,st_p0,st_I1))
974 literal st (MachInt j) = int st (fromIntegral j)
975 literal st (MachFloat r) = float st (fromRational r)
976 literal st (MachDouble r) = double st (fromRational r)
979 = addr st ret_itbl_addr
983 IntRep -> stg_ctoi_ret_R1_info
984 FloatRep -> stg_ctoi_ret_F1_info
985 DoubleRep -> stg_ctoi_ret_D1_info
987 stg_ctoi_ret_F1_info = nullAddr
988 stg_ctoi_ret_D1_info = nullAddr
990 foreign label "stg_ctoi_ret_R1_info" stg_ctoi_ret_R1_info :: Addr
991 --foreign label "stg_ctoi_ret_F1_info" stg_ctoi_ret_F1_info :: Addr
992 --foreign label "stg_ctoi_ret_D1_info" stg_ctoi_ret_D1_info :: Addr
994 -- The size in bytes of an instruction.
995 instrSizeB :: BCInstr -> Int
1022 -- Make lists of host-sized words for literals, so that when the
1023 -- words are placed in memory at increasing addresses, the
1024 -- bit pattern is correct for the host's word size and endianness.
1025 mkLitI :: Int -> [Word]
1026 mkLitF :: Float -> [Word]
1027 mkLitD :: Double -> [Word]
1028 mkLitA :: Addr -> [Word]
1032 arr <- newFloatArray ((0::Int),0)
1033 writeFloatArray arr 0 f
1034 f_arr <- castSTUArray arr
1035 w0 <- readWordArray f_arr 0
1042 arr <- newDoubleArray ((0::Int),0)
1043 writeDoubleArray arr 0 d
1044 d_arr <- castSTUArray arr
1045 w0 <- readWordArray d_arr 0
1046 w1 <- readWordArray d_arr 1
1051 arr <- newDoubleArray ((0::Int),0)
1052 writeDoubleArray arr 0 d
1053 d_arr <- castSTUArray arr
1054 w0 <- readWordArray d_arr 0
1060 arr <- newIntArray ((0::Int),0)
1061 writeIntArray arr 0 i
1062 i_arr <- castSTUArray arr
1063 w0 <- readWordArray i_arr 0
1069 arr <- newAddrArray ((0::Int),0)
1070 writeAddrArray arr 0 a
1071 a_arr <- castSTUArray arr
1072 w0 <- readWordArray a_arr 0
1077 -- Zero-based expandable arrays
1079 = XIOUArray { usedXIOU :: Int, stuffXIOU :: (IOUArray Int ele) }
1081 = XIOArray { usedXIO :: Int , stuffXIO :: (IOArray Int ele) }
1084 = do arr <- newArray (0, size-1)
1085 return (XIOUArray 0 arr)
1087 addListToXIOUArray xarr []
1089 addListToXIOUArray xarr (x:xs)
1090 = addToXIOUArray xarr x >>= \ xarr' -> addListToXIOUArray xarr' xs
1093 addToXIOUArray :: MArray IOUArray a IO
1094 => XIOUArray a -> a -> IO (XIOUArray a)
1095 addToXIOUArray (XIOUArray n_arr arr) x
1096 = case bounds arr of
1097 (lo, hi) -> ASSERT(lo == 0)
1099 then do new_arr <- newArray (0, 2*hi-1)
1101 addToXIOUArray (XIOUArray n_arr new_arr) x
1102 else do writeArray arr n_arr x
1103 return (XIOUArray (n_arr+1) arr)
1105 copy :: MArray IOUArray a IO
1106 => Int -> IOUArray Int a -> IOUArray Int a -> IO ()
1109 | otherwise = do nx <- readArray src n
1116 = do arr <- newArray (0, size-1)
1117 return (XIOArray 0 arr)
1119 addToXIOArray :: XIOArray a -> a -> IO (XIOArray a)
1120 addToXIOArray (XIOArray n_arr arr) x
1121 = case bounds arr of
1122 (lo, hi) -> ASSERT(lo == 0)
1124 then do new_arr <- newArray (0, 2*hi-1)
1126 addToXIOArray (XIOArray n_arr new_arr) x
1127 else do writeArray arr n_arr x
1128 return (XIOArray (n_arr+1) arr)
1130 copy :: Int -> IOArray Int a -> IOArray Int a -> IO ()
1133 | otherwise = do nx <- readArray src n
1139 %************************************************************************
1141 \subsection{Linking interpretables into something we can run}
1143 %************************************************************************
1149 = UnlinkedBCO Int (IOUArray Int Word16) -- #insns insns
1150 Int (IOUArray Int Word32) -- #literals literals
1151 Int (IOArray Int Name) -- #ptrs ptrs
1152 Int (IOArray Int Name) -- #itblrefs itblrefs
1154 data BCO# = BCO# ByteArray# -- instrs :: array Word16#
1155 ByteArray# -- literals :: array Word32#
1156 PtrArray# -- ptrs :: Array HValue
1157 ByteArray# -- itbls :: Array Addr#
1160 data LinkedBCO = LinkedBCO BCO#
1164 GLOBAL_VAR(v_cafTable, [], [HValue])
1166 addCAF :: HValue -> IO ()
1167 addCAF x = do xs <- readIORef v_cafTable; writeIORef v_cafTable (x:xs)
1169 bcosToHValue :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr -> IO HValue
1170 bcosToHValue ie ce (root_bco, other_bcos)
1171 = do linked_expr <- linkIExpr ie ce (root_bco, other_bcos)
1175 linkIModules :: ItblEnv -- incoming global itbl env; returned updated
1176 -> ClosureEnv -- incoming global closure env; returned updated
1177 -> [([UnlinkedBCO], ItblEnv)]
1178 -> IO ([HValue], ItblEnv, ClosureEnv)
1179 linkIModules gie gce mods = do
1180 let (bcoss, ies) = unzip mods
1182 top_level_binders = map nameOfUnlinkedBCO bcos
1183 final_gie = foldr plusFM gie ies
1185 (new_bcos, new_gce) <-
1186 fixIO (\ ~(new_bcos, new_gce) -> do
1187 new_bcos <- linkBCOs final_gie new_gce bcos
1188 let new_gce = addListToFM gce (zip top_level_binders new_bcos)
1189 return (new_bcos, new_gce))
1191 return (new_bcos, final_gie, new_gce)
1194 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
1195 -> IO HValue -- IO BCO# really
1196 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
1197 = do let aux_ul_binders = map nameOfUnlinkedBCO aux_ul_bcos
1200 (\ ~(aux_bcos, new_ce)
1201 -> do new_bcos <- linkBCOs ie new_ce aux_ul_bcos
1202 let new_ce = addListToFM ce (zip aux_ul_binders new_bcos)
1203 return (new_bcos, new_ce)
1206 <- linkBCOs ie aux_ce [root_ul_bco]
1210 linkBCOs :: ItblEnv -> ClosureEnv -> [UnlinkedBCO]
1211 -> IO [HValue] -- IO [BCO#] really
1212 linkBCOs ie ce binds = mapM (linkBCO ie ce) binds
1214 linkBCO ie ce (UnlinkedBCO nm
1215 n_insns insns n_literals literals
1216 n_ptrs ptrs n_itbls itbls)
1217 = do linked_ptrs <- mapArray (lookupCE ce) ptrs
1218 linked_itbls <- mapArray (lookupIE ie) itbls
1220 ptrs_froz <- freeze linked_ptrs
1221 let ptrs_parr = case ptrs_froz of Array lo hi parr -> parr
1223 insns_froz <- freeze insns
1224 let insns_barr = case insns_froz of UArray lo hi barr -> barr
1226 literals_froz <- freeze literals
1227 let literals_barr = case literals_froz of UArray lo hi barr -> barr
1229 itbls_froz <- freeze linked_itbls
1230 let itbls_barr = case itbls_froz of UArray lo hi barr -> barr
1232 BCO bco# <- newBCO insns_barr literals_barr ptrs_parr itbls_barr
1234 return (unsafeCoerce# bco#)
1238 newBCO :: ByteArray# -> ByteArray# -> Array# a -> ByteArray# -> IO BCO
1239 newBCO a b c d = IO (\s -> case newBCO# a b c d s of (# s1, bco #) -> (# s1, BCO bco #))
1242 lookupCE :: ClosureEnv -> Name -> HValue
1244 = case lookupFM ce nm of
1245 Just aa -> unsafeCoerce# aa
1246 Nothing -> pprPanic "ByteCodeGen.lookupCE" (ppr nm)
1248 lookupIE :: ItblEnv -> Name -> Addr
1250 = case lookupFM ie nm of
1252 Nothing -> pprPanic "ByteCodeGen.lookupIE" (ppr nm)
1258 case lookupFM ie con of
1259 Just (Ptr addr) -> return addr
1261 -- try looking up in the object files.
1262 m <- lookupSymbol (nameToCLabel con "con_info")
1264 Just addr -> return addr
1265 Nothing -> pprPanic "linkIExpr" (ppr con)
1267 -- nullary constructors don't have normal _con_info tables.
1268 lookupNullaryCon ie con =
1269 case lookupFM ie con of
1270 Just (Ptr addr) -> return (ConApp addr)
1272 -- try looking up in the object files.
1273 m <- lookupSymbol (nameToCLabel con "closure")
1275 Just (A# addr) -> return (Native (unsafeCoerce# addr))
1276 Nothing -> pprPanic "lookupNullaryCon" (ppr con)
1279 lookupNative ce var =
1280 unsafeInterleaveIO (do
1281 case lookupFM ce var of
1282 Just e -> return (Native e)
1284 -- try looking up in the object files.
1285 let lbl = (nameToCLabel var "closure")
1286 m <- lookupSymbol lbl
1289 -> do addCAF (unsafeCoerce# addr)
1290 return (Native (unsafeCoerce# addr))
1291 Nothing -> pprPanic "linkIExpr" (ppr var)
1294 -- some VarI/VarP refer to top-level interpreted functions; we change
1295 -- them into Natives here.
1297 unsafeInterleaveIO (
1298 case lookupFM ce (getName v) of
1299 Nothing -> return (f v)
1300 Just e -> return (Native e)
1303 -- HACK!!! ToDo: cleaner
1304 nameToCLabel :: Name -> String{-suffix-} -> String
1305 nameToCLabel n suffix =
1306 _UNPK_(moduleNameFS (rdrNameModule rn))
1307 ++ '_':occNameString(rdrNameOcc rn) ++ '_':suffix
1308 where rn = toRdrName n
1312 %************************************************************************
1314 \subsection{Manufacturing of info tables for DataCons}
1316 %************************************************************************
1320 #if __GLASGOW_HASKELL__ <= 408
1323 type ItblPtr = Ptr StgInfoTable
1326 -- Make info tables for the data decls in this module
1327 mkITbls :: [TyCon] -> IO ItblEnv
1328 mkITbls [] = return emptyFM
1329 mkITbls (tc:tcs) = do itbls <- mkITbl tc
1330 itbls2 <- mkITbls tcs
1331 return (itbls `plusFM` itbls2)
1333 mkITbl :: TyCon -> IO ItblEnv
1335 -- | trace ("TYCON: " ++ showSDoc (ppr tc)) False
1337 | not (isDataTyCon tc)
1339 | n == length dcs -- paranoia; this is an assertion.
1340 = make_constr_itbls dcs
1342 dcs = tyConDataCons tc
1343 n = tyConFamilySize tc
1346 cONSTR = 1 -- as defined in ghc/includes/ClosureTypes.h
1348 -- Assumes constructors are numbered from zero, not one
1349 make_constr_itbls :: [DataCon] -> IO ItblEnv
1350 make_constr_itbls cons
1352 = do is <- mapM mk_vecret_itbl (zip cons [0..])
1353 return (listToFM is)
1355 = do is <- mapM mk_dirret_itbl (zip cons [0..])
1356 return (listToFM is)
1358 mk_vecret_itbl (dcon, conNo)
1359 = mk_itbl dcon conNo (vecret_entry conNo)
1360 mk_dirret_itbl (dcon, conNo)
1361 = mk_itbl dcon conNo stg_interp_constr_entry
1363 mk_itbl :: DataCon -> Int -> Addr -> IO (Name,ItblPtr)
1364 mk_itbl dcon conNo entry_addr
1365 = let (tot_wds, ptr_wds, _)
1366 = mkVirtHeapOffsets typePrimRep (dataConRepArgTys dcon)
1368 nptrs = tot_wds - ptr_wds
1369 itbl = StgInfoTable {
1370 ptrs = fromIntegral ptrs, nptrs = fromIntegral nptrs,
1371 tipe = fromIntegral cONSTR,
1372 srtlen = fromIntegral conNo,
1373 code0 = fromIntegral code0, code1 = fromIntegral code1,
1374 code2 = fromIntegral code2, code3 = fromIntegral code3,
1375 code4 = fromIntegral code4, code5 = fromIntegral code5,
1376 code6 = fromIntegral code6, code7 = fromIntegral code7
1378 -- Make a piece of code to jump to "entry_label".
1379 -- This is the only arch-dependent bit.
1380 -- On x86, if entry_label has an address 0xWWXXYYZZ,
1381 -- emit movl $0xWWXXYYZZ,%eax ; jmp *%eax
1383 -- B8 ZZ YY XX WW FF E0
1384 (code0,code1,code2,code3,code4,code5,code6,code7)
1385 = (0xB8, byte 0 entry_addr_w, byte 1 entry_addr_w,
1386 byte 2 entry_addr_w, byte 3 entry_addr_w,
1390 entry_addr_w :: Word32
1391 entry_addr_w = fromIntegral (addrToInt entry_addr)
1394 --putStrLn ("SIZE of itbl is " ++ show (sizeOf itbl))
1395 --putStrLn ("# ptrs of itbl is " ++ show ptrs)
1396 --putStrLn ("# nptrs of itbl is " ++ show nptrs)
1398 return (getName dcon, addr `plusPtr` 8)
1401 byte :: Int -> Word32 -> Word32
1402 byte 0 w = w .&. 0xFF
1403 byte 1 w = (w `shiftR` 8) .&. 0xFF
1404 byte 2 w = (w `shiftR` 16) .&. 0xFF
1405 byte 3 w = (w `shiftR` 24) .&. 0xFF
1408 vecret_entry 0 = stg_interp_constr1_entry
1409 vecret_entry 1 = stg_interp_constr2_entry
1410 vecret_entry 2 = stg_interp_constr3_entry
1411 vecret_entry 3 = stg_interp_constr4_entry
1412 vecret_entry 4 = stg_interp_constr5_entry
1413 vecret_entry 5 = stg_interp_constr6_entry
1414 vecret_entry 6 = stg_interp_constr7_entry
1415 vecret_entry 7 = stg_interp_constr8_entry
1417 -- entry point for direct returns for created constr itbls
1418 foreign label "stg_interp_constr_entry" stg_interp_constr_entry :: Addr
1419 -- and the 8 vectored ones
1420 foreign label "stg_interp_constr1_entry" stg_interp_constr1_entry :: Addr
1421 foreign label "stg_interp_constr2_entry" stg_interp_constr2_entry :: Addr
1422 foreign label "stg_interp_constr3_entry" stg_interp_constr3_entry :: Addr
1423 foreign label "stg_interp_constr4_entry" stg_interp_constr4_entry :: Addr
1424 foreign label "stg_interp_constr5_entry" stg_interp_constr5_entry :: Addr
1425 foreign label "stg_interp_constr6_entry" stg_interp_constr6_entry :: Addr
1426 foreign label "stg_interp_constr7_entry" stg_interp_constr7_entry :: Addr
1427 foreign label "stg_interp_constr8_entry" stg_interp_constr8_entry :: Addr
1431 data Constructor = Constructor Int{-ptrs-} Int{-nptrs-}
1434 -- Ultra-minimalist version specially for constructors
1435 data StgInfoTable = StgInfoTable {
1440 code0, code1, code2, code3, code4, code5, code6, code7 :: Word8
1444 instance Storable StgInfoTable where
1447 = (sum . map (\f -> f itbl))
1448 [fieldSz ptrs, fieldSz nptrs, fieldSz srtlen, fieldSz tipe,
1449 fieldSz code0, fieldSz code1, fieldSz code2, fieldSz code3,
1450 fieldSz code4, fieldSz code5, fieldSz code6, fieldSz code7]
1453 = (sum . map (\f -> f itbl))
1454 [fieldAl ptrs, fieldAl nptrs, fieldAl srtlen, fieldAl tipe,
1455 fieldAl code0, fieldAl code1, fieldAl code2, fieldAl code3,
1456 fieldAl code4, fieldAl code5, fieldAl code6, fieldAl code7]
1459 = do a1 <- store (ptrs itbl) (castPtr a0)
1460 a2 <- store (nptrs itbl) a1
1461 a3 <- store (tipe itbl) a2
1462 a4 <- store (srtlen itbl) a3
1463 a5 <- store (code0 itbl) a4
1464 a6 <- store (code1 itbl) a5
1465 a7 <- store (code2 itbl) a6
1466 a8 <- store (code3 itbl) a7
1467 a9 <- store (code4 itbl) a8
1468 aA <- store (code5 itbl) a9
1469 aB <- store (code6 itbl) aA
1470 aC <- store (code7 itbl) aB
1474 = do (a1,ptrs) <- load (castPtr a0)
1475 (a2,nptrs) <- load a1
1476 (a3,tipe) <- load a2
1477 (a4,srtlen) <- load a3
1478 (a5,code0) <- load a4
1479 (a6,code1) <- load a5
1480 (a7,code2) <- load a6
1481 (a8,code3) <- load a7
1482 (a9,code4) <- load a8
1483 (aA,code5) <- load a9
1484 (aB,code6) <- load aA
1485 (aC,code7) <- load aB
1486 return StgInfoTable { ptrs = ptrs, nptrs = nptrs,
1487 srtlen = srtlen, tipe = tipe,
1488 code0 = code0, code1 = code1, code2 = code2,
1489 code3 = code3, code4 = code4, code5 = code5,
1490 code6 = code6, code7 = code7 }
1492 fieldSz :: (Storable a, Storable b) => (a -> b) -> a -> Int
1493 fieldSz sel x = sizeOf (sel x)
1495 fieldAl :: (Storable a, Storable b) => (a -> b) -> a -> Int
1496 fieldAl sel x = alignment (sel x)
1498 store :: Storable a => a -> Ptr a -> IO (Ptr b)
1499 store x addr = do poke addr x
1500 return (castPtr (addr `plusPtr` sizeOf x))
1502 load :: Storable a => Ptr a -> IO (Ptr b, a)
1503 load addr = do x <- peek addr
1504 return (castPtr (addr `plusPtr` sizeOf x), x)
1508 %************************************************************************
1510 \subsection{Connect to actual values for bytecode opcodes}
1512 %************************************************************************
1516 #include "Bytecodes.h"
1518 i_ARGCHECK = (bci_ARGCHECK :: Int)
1519 i_PUSH_L = (bci_PUSH_L :: Int)
1520 i_PUSH_LL = (bci_PUSH_LL :: Int)
1521 i_PUSH_LLL = (bci_PUSH_LLL :: Int)
1522 i_PUSH_G = (bci_PUSH_G :: Int)
1523 i_PUSH_AS = (bci_PUSH_AS :: Int)
1524 i_PUSH_UBX = (bci_PUSH_UBX :: Int)
1525 i_PUSH_TAG = (bci_PUSH_TAG :: Int)
1526 i_SLIDE = (bci_SLIDE :: Int)
1527 i_ALLOC = (bci_ALLOC :: Int)
1528 i_MKAP = (bci_MKAP :: Int)
1529 i_UNPACK = (bci_UNPACK :: Int)
1530 i_UPK_TAG = (bci_UPK_TAG :: Int)
1531 i_PACK = (bci_PACK :: Int)
1532 i_LABEL = (bci_LABEL :: Int)
1533 i_TESTLT_I = (bci_TESTLT_I :: Int)
1534 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
1535 i_TESTLT_F = (bci_TESTLT_F :: Int)
1536 i_TESTEQ_F = (bci_TESTEQ_F :: Int)
1537 i_TESTLT_D = (bci_TESTLT_D :: Int)
1538 i_TESTEQ_D = (bci_TESTEQ_D :: Int)
1539 i_TESTLT_P = (bci_TESTLT_P :: Int)
1540 i_TESTEQ_P = (bci_TESTEQ_P :: Int)
1541 i_CASEFAIL = (bci_CASEFAIL :: Int)
1542 i_ENTER = (bci_ENTER :: Int)
1543 i_RETURN = (bci_RETURN :: Int)