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 )
17 import Id ( Id, idType, isDataConId_maybe, mkVanillaId )
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 )
41 import Unique ( mkPseudoUnique3 )
43 import List ( intersperse )
44 import Monad ( foldM )
46 import MArray ( 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, 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"
104 -- create a totally bogus name for the top-level BCO; this
105 -- should be harmless, since it's never used for anything
106 let invented_name = mkSysLocalName (mkPseudoUnique3 0) SLIT("Expr-Top-Level")
107 let invented_id = mkVanillaId invented_name (panic "invented_id's type")
109 let (BcM_State all_proto_bcos final_ctr)
110 = runBc (BcM_State [] 0)
111 (schemeR (invented_id, freeVars expr))
112 dumpIfSet_dyn dflags Opt_D_dump_BCOs
113 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr all_proto_bcos)))
116 = case filter ((== invented_name).nameOfProtoBCO) all_proto_bcos of
117 [root_bco] -> root_bco
119 = filter ((/= invented_name).nameOfProtoBCO) all_proto_bcos
121 auxiliary_bcos <- mapM assembleBCO auxiliary_proto_bcos
122 root_bco <- assembleBCO root_proto_bco
124 return (root_bco, auxiliary_bcos)
130 (SizedSeq Word16) -- insns
131 (SizedSeq Word) -- literals
132 (SizedSeq Name) -- ptrs
133 (SizedSeq Name) -- itbl refs
135 nameOfUnlinkedBCO (UnlinkedBCO nm _ _ _ _) = nm
137 -- When translating expressions, we need to distinguish the root
138 -- BCO for the expression
139 type UnlinkedBCOExpr = (UnlinkedBCO, [UnlinkedBCO])
141 instance Outputable UnlinkedBCO where
142 ppr (UnlinkedBCO nm insns lits ptrs itbls)
143 = sep [text "BCO", ppr nm, text "with",
144 int (sizeSS insns), text "insns",
145 int (sizeSS lits), text "lits",
146 int (sizeSS ptrs), text "ptrs",
147 int (sizeSS itbls), text "itbls"]
150 -- these need a proper home
151 type ItblEnv = FiniteMap Name (Ptr StgInfoTable)
152 type ClosureEnv = FiniteMap Name HValue
153 data HValue = HValue -- dummy type, actually a pointer to some Real Code.
155 -- remove all entries for a given set of modules from the environment
156 filterNameMap :: [ModuleName] -> FiniteMap Name a -> FiniteMap Name a
157 filterNameMap mods env
158 = filterFM (\n _ -> moduleName (nameModule n) `notElem` mods) env
161 %************************************************************************
163 \subsection{Bytecodes, and Outputery.}
165 %************************************************************************
169 type LocalLabel = Int
172 -- Messing with the stack
174 -- Push locals (existing bits of the stack)
175 | PUSH_L Int{-offset-}
176 | PUSH_LL Int Int{-2 offsets-}
177 | PUSH_LLL Int Int Int{-3 offsets-}
180 -- Push an alt continuation
181 | PUSH_AS Name PrimRep -- push alts and BCO_ptr_ret_info
182 -- PrimRep so we know which itbl
184 | PUSH_UBX Literal Int
185 -- push this int/float/double, NO TAG, on the stack
186 -- Int is # of words to copy from literal pool
187 | PUSH_TAG Int -- push this tag on the stack
189 | SLIDE Int{-this many-} Int{-down by this much-}
190 -- To do with the heap
191 | ALLOC Int -- make an AP_UPD with this many payload words, zeroed
192 | MKAP Int{-ptr to AP_UPD is this far down stack-} Int{-# words-}
193 | UNPACK Int -- unpack N ptr words from t.o.s Constr
194 | UPK_TAG Int Int Int
195 -- unpack N non-ptr words from offset M in constructor
196 -- K words down the stack
198 -- after assembly, the DataCon is an index into the
200 -- For doing case trees
202 | TESTLT_I Int LocalLabel
203 | TESTEQ_I Int LocalLabel
204 | TESTLT_F Float LocalLabel
205 | TESTEQ_F Float LocalLabel
206 | TESTLT_D Double LocalLabel
207 | TESTEQ_D Double LocalLabel
208 | TESTLT_P Int LocalLabel
209 | TESTEQ_P Int LocalLabel
211 -- To Infinity And Beyond
213 | RETURN -- unboxed value on TOS. Use tag to find underlying ret itbl
214 -- and return as per that.
217 instance Outputable BCInstr where
218 ppr (ARGCHECK n) = text "ARGCHECK" <+> int n
219 ppr (PUSH_L offset) = text "PUSH_L " <+> int offset
220 ppr (PUSH_LL o1 o2) = text "PUSH_LL " <+> int o1 <+> int o2
221 ppr (PUSH_LLL o1 o2 o3) = text "PUSH_LLL" <+> int o1 <+> int o2 <+> int o3
222 ppr (PUSH_G nm) = text "PUSH_G " <+> ppr nm
223 ppr (PUSH_AS nm pk) = text "PUSH_AS " <+> ppr nm <+> ppr pk
224 ppr (PUSH_UBX lit nw) = text "PUSH_UBX" <+> parens (int nw) <+> ppr lit
225 ppr (PUSH_TAG n) = text "PUSH_TAG" <+> int n
226 ppr (SLIDE n d) = text "SLIDE " <+> int n <+> int d
227 ppr (ALLOC sz) = text "ALLOC " <+> int sz
228 ppr (MKAP offset sz) = text "MKAP " <+> int offset <+> int sz
229 ppr (UNPACK sz) = text "UNPACK " <+> int sz
230 ppr (UPK_TAG n m k) = text "UPK_TAG " <+> int n <> text "words"
231 <+> int m <> text "conoff"
232 <+> int k <> text "stkoff"
233 ppr (PACK dcon sz) = text "PACK " <+> ppr dcon <+> ppr sz
234 ppr (LABEL lab) = text "__" <> int lab <> colon
235 ppr (TESTLT_I i lab) = text "TESTLT_I" <+> int i <+> text "__" <> int lab
236 ppr (TESTEQ_I i lab) = text "TESTEQ_I" <+> int i <+> text "__" <> int lab
237 ppr (TESTLT_F f lab) = text "TESTLT_F" <+> float f <+> text "__" <> int lab
238 ppr (TESTEQ_F f lab) = text "TESTEQ_F" <+> float f <+> text "__" <> int lab
239 ppr (TESTLT_D d lab) = text "TESTLT_D" <+> double d <+> text "__" <> int lab
240 ppr (TESTEQ_D d lab) = text "TESTEQ_D" <+> double d <+> text "__" <> int lab
241 ppr (TESTLT_P i lab) = text "TESTLT_P" <+> int i <+> text "__" <> int lab
242 ppr (TESTEQ_P i lab) = text "TESTEQ_P" <+> int i <+> text "__" <> int lab
243 ppr CASEFAIL = text "CASEFAIL"
244 ppr ENTER = text "ENTER"
245 ppr RETURN = text "RETURN"
247 instance Outputable a => Outputable (ProtoBCO a) where
248 ppr (ProtoBCO name instrs origin)
249 = (text "ProtoBCO" <+> ppr name <> colon)
250 $$ nest 6 (vcat (map ppr instrs))
252 Left alts -> vcat (map (pprCoreAlt.deAnnAlt) alts)
253 Right rhs -> pprCoreExpr (deAnnotate rhs)
256 %************************************************************************
258 \subsection{Compilation schema for the bytecode generator.}
260 %************************************************************************
264 type BCInstrList = OrdList BCInstr
267 = ProtoBCO a -- name, in some sense
269 -- what the BCO came from
270 (Either [AnnAlt Id VarSet]
273 nameOfProtoBCO (ProtoBCO nm insns origin) = nm
276 type Sequel = Int -- back off to this depth before ENTER
278 -- Maps Ids to the offset from the stack _base_ so we don't have
279 -- to mess with it after each push/pop.
280 type BCEnv = FiniteMap Id Int -- To find vars on the stack
283 -- Create a BCO and do a spot of peephole optimisation on the insns
285 mkProtoBCO nm instrs_ordlist origin
286 = ProtoBCO nm (peep (fromOL instrs_ordlist)) origin
288 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
289 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
290 peep (PUSH_L off1 : PUSH_L off2 : rest)
291 = PUSH_LL off1 off2 : peep rest
298 -- Compile code for the right hand side of a let binding.
299 -- Park the resulting BCO in the monad. Also requires the
300 -- variable to which this value was bound, so as to give the
301 -- resulting BCO a name.
302 schemeR :: (Id, AnnExpr Id VarSet) -> BcM ()
303 schemeR (nm, rhs) = schemeR_wrk rhs nm (collect [] rhs)
305 collect xs (_, AnnLam x e)
306 = collect (if isTyVar x then xs else (x:xs)) e
307 collect xs not_lambda
308 = (reverse xs, not_lambda)
310 schemeR_wrk original_body nm (args, body)
311 = let fvs = filter (not.isTyVar) (varSetElems (fst original_body))
312 all_args = fvs ++ reverse args
313 szsw_args = map taggedIdSizeW all_args
314 szw_args = sum szsw_args
315 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
316 argcheck = if null args then nilOL else unitOL (ARGCHECK szw_args)
318 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
319 emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) (Right original_body))
321 -- Let szsw be the sizes in words of some items pushed onto the stack,
322 -- which has initial depth d'. Return the values which the stack environment
323 -- should map these items to.
324 mkStackOffsets :: Int -> [Int] -> [Int]
325 mkStackOffsets original_depth szsw
326 = map (subtract 1) (tail (scanl (+) original_depth szsw))
328 -- Compile code to apply the given expression to the remaining args
329 -- on the stack, returning a HNF.
330 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
332 -- Delegate tail-calls to schemeT.
333 schemeE d s p e@(fvs, AnnApp f a)
334 = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnApp f a))
335 schemeE d s p e@(fvs, AnnVar v)
336 | isFollowableRep (typePrimRep (idType v))
337 = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnVar v))
339 = -- returning an unboxed value. Heave it on the stack, SLIDE, and RETURN.
340 let (push, szw) = pushAtom True d p (AnnVar v)
341 in returnBc (push -- value onto stack
342 `snocOL` SLIDE szw (d-s) -- clear to sequel
343 `snocOL` RETURN) -- go
345 schemeE d s p (fvs, AnnLit literal)
346 = let (push, szw) = pushAtom True d p (AnnLit literal)
347 in returnBc (push -- value onto stack
348 `snocOL` SLIDE szw (d-s) -- clear to sequel
349 `snocOL` RETURN) -- go
351 schemeE d s p (fvs, AnnLet binds b)
352 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
353 AnnRec xs_n_rhss -> unzip xs_n_rhss
355 fvss = map (filter (not.isTyVar).varSetElems.fst) rhss
356 sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
358 -- This p', d' defn is safe because all the items being pushed
359 -- are ptrs, so all have size 1. d' and p' reflect the stack
360 -- after the closures have been allocated in the heap (but not
361 -- filled in), and pointers to them parked on the stack.
362 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
365 infos = zipE4 fvss sizes xs [n, n-1 .. 1]
366 zipE = zipEqual "schemeE"
367 zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
369 -- ToDo: don't build thunks for things with no free variables
370 buildThunk dd ([], size, id, off)
371 = PUSH_G (getName id)
372 `consOL` unitOL (MKAP (off+size-1) size)
373 buildThunk dd ((fv:fvs), size, id, off)
374 = case pushAtom True dd p' (AnnVar fv) of
375 (push_code, pushed_szw)
377 buildThunk (dd+pushed_szw) (fvs, size, id, off)
379 thunkCode = concatOL (map (buildThunk d') infos)
380 allocCode = toOL (map ALLOC sizes)
382 schemeE d' s p' b `thenBc` \ bodyCode ->
383 mapBc schemeR (zip xs rhss) `thenBc_`
384 returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
387 schemeE d s p (fvs, AnnCase scrut bndr alts)
389 -- Top of stack is the return itbl, as usual.
390 -- underneath it is the pointer to the alt_code BCO.
391 -- When an alt is entered, it assumes the returned value is
392 -- on top of the itbl.
395 -- Env and depth in which to compile the alts, not including
396 -- any vars bound by the alts themselves
397 d' = d + ret_frame_sizeW + taggedIdSizeW bndr
398 p' = addToFM p bndr (d' - 1)
400 scrut_primrep = typePrimRep (idType bndr)
402 = case scrut_primrep of
403 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
405 other -> pprPanic "ByteCodeGen.schemeE" (ppr other)
407 -- given an alt, return a discr and code for it.
408 codeAlt alt@(discr, binds_f, rhs)
410 = let binds_r = reverse binds_f
411 binds_r_szsw = map untaggedIdSizeW binds_r
412 binds_szw = sum binds_r_szsw
414 p' (zip binds_r (mkStackOffsets d' binds_r_szsw))
416 unpack_code = mkUnpackCode 0 0 (map (typePrimRep.idType) binds_f)
417 in schemeE d'' s p'' rhs `thenBc` \ rhs_code ->
418 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
420 = ASSERT(null binds_f)
421 schemeE d' s p' rhs `thenBc` \ rhs_code ->
422 returnBc (my_discr alt, rhs_code)
424 my_discr (DEFAULT, binds, rhs) = NoDiscr
425 my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc)
426 my_discr (LitAlt l, binds, rhs)
427 = case l of MachInt i -> DiscrI (fromInteger i)
428 MachFloat r -> DiscrF (fromRational r)
429 MachDouble r -> DiscrD (fromRational r)
432 | not isAlgCase = Nothing
434 = case [dc | (DataAlt dc, _, _) <- alts] of
436 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
439 mapBc codeAlt alts `thenBc` \ alt_stuff ->
440 mkMultiBranch maybe_ncons alt_stuff `thenBc` \ alt_final ->
442 alt_bco_name = getName bndr
443 alt_bco = mkProtoBCO alt_bco_name alt_final (Left alts)
445 schemeE (d + ret_frame_sizeW)
446 (d + ret_frame_sizeW) p scrut `thenBc` \ scrut_code ->
448 emitBc alt_bco `thenBc_`
449 returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
452 schemeE d s p (fvs, AnnNote note body)
456 = pprPanic "ByteCodeGen.schemeE: unhandled case"
457 (pprCoreExpr (deAnnotate other))
460 -- Compile code to do a tail call. Doesn't need to be monadic.
461 schemeT :: Bool -- do tagging?
462 -> Int -- Stack depth
463 -> Sequel -- Sequel depth
464 -> Int -- # arg words so far
465 -> BCEnv -- stack env
469 schemeT enTag d s narg_words p (_, AnnApp f a)
471 AnnType _ -> schemeT enTag d s narg_words p f
473 -> let (push, arg_words) = pushAtom enTag d p (snd a)
475 `appOL` schemeT enTag (d+arg_words) s (narg_words+arg_words) p f
477 schemeT enTag d s narg_words p (_, AnnVar f)
478 | Just con <- isDataConId_maybe f
479 = ASSERT(enTag == False)
480 PACK con narg_words `consOL` (mkSLIDE 1 (d-s-1) `snocOL` ENTER)
482 = ASSERT(enTag == True)
483 let (push, arg_words) = pushAtom True d p (AnnVar f)
485 `appOL` mkSLIDE (narg_words+arg_words) (d - s - narg_words)
489 = if d == 0 then nilOL else unitOL (SLIDE n d)
491 should_args_be_tagged (_, AnnVar v)
492 = case isDataConId_maybe v of
493 Just dcon -> False; Nothing -> True
494 should_args_be_tagged (_, AnnApp f a)
495 = should_args_be_tagged f
496 should_args_be_tagged (_, other)
497 = panic "should_args_be_tagged: tail call to non-con, non-var"
500 -- Make code to unpack a constructor onto the stack, adding
501 -- tags for the unboxed bits. Takes the PrimReps of the constructor's
502 -- arguments, and a travelling offset along both the constructor
503 -- (off_h) and the stack (off_s).
504 mkUnpackCode :: Int -> Int -> [PrimRep] -> BCInstrList
505 mkUnpackCode off_h off_s [] = nilOL
506 mkUnpackCode off_h off_s (r:rs)
508 = let (rs_ptr, rs_nptr) = span isFollowableRep (r:rs)
509 ptrs_szw = sum (map untaggedSizeW rs_ptr)
510 in ASSERT(ptrs_szw == length rs_ptr)
514 `consOL` mkUnpackCode (off_h + ptrs_szw) (off_s + ptrs_szw) rs_nptr
519 DoubleRep -> approved
521 approved = UPK_TAG usizeW off_h off_s `consOL` theRest
522 theRest = mkUnpackCode (off_h + usizeW) (off_s + tsizeW) rs
523 usizeW = untaggedSizeW r
524 tsizeW = taggedSizeW r
526 -- Push an atom onto the stack, returning suitable code & number of
527 -- stack words used. Pushes it either tagged or untagged, since
528 -- pushAtom is used to set up the stack prior to copying into the
529 -- heap for both APs (requiring tags) and constructors (which don't).
531 -- NB this means NO GC between pushing atoms for a constructor and
532 -- copying them into the heap. It probably also means that
533 -- tail calls MUST be of the form atom{atom ... atom} since if the
534 -- expression head was allowed to be arbitrary, there could be GC
535 -- in between pushing the arg atoms and completing the head.
536 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
537 -- isn't a problem; but only if arbitrary graph construction for the
538 -- head doesn't leave this BCO, since GC might happen at the start of
539 -- each BCO (we consult doYouWantToGC there).
541 -- Blargh. JRS 001206
543 -- NB (further) that the env p must map each variable to the highest-
544 -- numbered stack slot for it. For example, if the stack has depth 4
545 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
546 -- the tag in stack[5], the stack will have depth 6, and p must map v to
547 -- 5 and not to 4. Stack locations are numbered from zero, so a depth
548 -- 6 stack has valid words 0 .. 5.
550 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
551 pushAtom tagged d p (AnnVar v)
552 = let str = "\npushAtom " ++ showSDocDebug (ppr v) ++ ", depth = " ++ show d
554 showSDocDebug (nest 4 (vcat (map ppr (fmToList p))))
556 showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
557 ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
558 str' = if str == str then str else str
561 = case lookupBCEnv_maybe p v of
562 Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), sz_t)
563 Nothing -> ASSERT(sz_t == 1) (unitOL (PUSH_G nm), sz_t)
566 sz_t = taggedIdSizeW v
567 sz_u = untaggedIdSizeW v
568 nwords = if tagged then sz_t else sz_u
573 pushAtom True d p (AnnLit lit)
574 = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
575 in (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
577 pushAtom False d p (AnnLit lit)
579 MachInt i -> code IntRep
580 MachFloat r -> code FloatRep
581 MachDouble r -> code DoubleRep
584 = let size_host_words = untaggedSizeW rep
585 in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
587 pushAtom tagged d p (AnnApp f (_, AnnType _))
588 = pushAtom tagged d p (snd f)
590 pushAtom tagged d p other
591 = pprPanic "ByteCodeGen.pushAtom"
592 (pprCoreExpr (deAnnotate (undefined, other)))
595 -- Given a bunch of alts code and their discrs, do the donkey work
596 -- of making a multiway branch using a switch tree.
597 -- What a load of hassle!
598 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
599 -- a hint; generates better code
600 -- Nothing is always safe
601 -> [(Discr, BCInstrList)]
603 mkMultiBranch maybe_ncons raw_ways
604 = let d_way = filter (isNoDiscr.fst) raw_ways
605 notd_ways = naturalMergeSortLe
606 (\w1 w2 -> leAlt (fst w1) (fst w2))
607 (filter (not.isNoDiscr.fst) raw_ways)
609 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
610 mkTree [] range_lo range_hi = returnBc the_default
612 mkTree [val] range_lo range_hi
613 | range_lo `eqAlt` range_hi
616 = getLabelBc `thenBc` \ label_neq ->
617 returnBc (mkTestEQ (fst val) label_neq
619 `appOL` unitOL (LABEL label_neq)
620 `appOL` the_default))
622 mkTree vals range_lo range_hi
623 = let n = length vals `div` 2
624 vals_lo = take n vals
625 vals_hi = drop n vals
626 v_mid = fst (head vals_hi)
628 getLabelBc `thenBc` \ label_geq ->
629 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
630 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
631 returnBc (mkTestLT v_mid label_geq
633 `appOL` unitOL (LABEL label_geq)
637 = case d_way of [] -> unitOL CASEFAIL
640 -- None of these will be needed if there are no non-default alts
641 (mkTestLT, mkTestEQ, init_lo, init_hi)
643 = panic "mkMultiBranch: awesome foursome"
645 = case fst (head notd_ways) of {
646 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
647 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
650 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
651 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
654 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
655 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
658 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
659 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
664 (algMinBound, algMaxBound)
665 = case maybe_ncons of
666 Just n -> (fIRST_TAG, fIRST_TAG + n - 1)
667 Nothing -> (minBound, maxBound)
669 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
670 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
671 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
672 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
673 NoDiscr `eqAlt` NoDiscr = True
676 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
677 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
678 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
679 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
680 NoDiscr `leAlt` NoDiscr = True
683 isNoDiscr NoDiscr = True
686 dec (DiscrI i) = DiscrI (i-1)
687 dec (DiscrP i) = DiscrP (i-1)
688 dec other = other -- not really right, but if you
689 -- do cases on floating values, you'll get what you deserve
691 -- same snotty comment applies to the following
699 mkTree notd_ways init_lo init_hi
703 %************************************************************************
705 \subsection{Supporting junk for the compilation schemes}
707 %************************************************************************
711 -- Describes case alts
719 instance Outputable Discr where
720 ppr (DiscrI i) = int i
721 ppr (DiscrF f) = text (show f)
722 ppr (DiscrD d) = text (show d)
723 ppr (DiscrP i) = int i
724 ppr NoDiscr = text "DEF"
727 -- Find things in the BCEnv (the what's-on-the-stack-env)
728 -- See comment preceding pushAtom for precise meaning of env contents
729 --lookupBCEnv :: BCEnv -> Id -> Int
731 -- = case lookupFM env nm of
732 -- Nothing -> pprPanic "lookupBCEnv"
733 -- (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
736 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
737 lookupBCEnv_maybe = lookupFM
740 -- When I push one of these on the stack, how much does Sp move by?
741 taggedSizeW :: PrimRep -> Int
743 | isFollowableRep pr = 1
744 | otherwise = 1{-the tag-} + getPrimRepSize pr
747 -- The plain size of something, without tag.
748 untaggedSizeW :: PrimRep -> Int
750 | isFollowableRep pr = 1
751 | otherwise = getPrimRepSize pr
754 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
755 taggedIdSizeW = taggedSizeW . typePrimRep . idType
756 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
760 %************************************************************************
762 \subsection{The bytecode generator's monad}
764 %************************************************************************
768 = BcM_State { bcos :: [ProtoBCO Name], -- accumulates completed BCOs
769 nextlabel :: Int } -- for generating local labels
771 type BcM result = BcM_State -> (result, BcM_State)
773 runBc :: BcM_State -> BcM () -> BcM_State
774 runBc init_st m = case m init_st of { (r,st) -> st }
776 thenBc :: BcM a -> (a -> BcM b) -> BcM b
778 = case expr st of { (result, st') -> cont result st' }
780 thenBc_ :: BcM a -> BcM b -> BcM b
782 = case expr st of { (result, st') -> cont st' }
784 returnBc :: a -> BcM a
785 returnBc result st = (result, st)
787 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
788 mapBc f [] = returnBc []
790 = f x `thenBc` \ r ->
791 mapBc f xs `thenBc` \ rs ->
794 emitBc :: ProtoBCO Name -> BcM ()
796 = ((), st{bcos = bco : bcos st})
798 getLabelBc :: BcM Int
800 = (nextlabel st, st{nextlabel = 1 + nextlabel st})
804 %************************************************************************
806 \subsection{The bytecode assembler}
808 %************************************************************************
810 The object format for bytecodes is: 16 bits for the opcode, and 16 for
811 each field -- so the code can be considered a sequence of 16-bit ints.
812 Each field denotes either a stack offset or number of items on the
813 stack (eg SLIDE), and index into the pointer table (eg PUSH_G), an
814 index into the literal table (eg PUSH_I/D/L), or a bytecode address in
818 -- Top level assembler fn.
819 assembleBCO :: ProtoBCO Name -> IO UnlinkedBCO
821 assembleBCO (ProtoBCO nm instrs origin)
823 -- pass 1: collect up the offsets of the local labels
824 label_env = mkLabelEnv emptyFM 0 instrs
826 mkLabelEnv env i_offset [] = env
827 mkLabelEnv env i_offset (i:is)
829 = case i of LABEL n -> addToFM env n i_offset ; _ -> env
830 in mkLabelEnv new_env (i_offset + instrSizeB i) is
833 = case lookupFM label_env lab of
834 Just bco_offset -> bco_offset
835 Nothing -> pprPanic "assembleBCO.findLabel" (int lab)
837 do -- pass 2: generate the instruction, ptr and nonptr bits
838 insns <- return emptySS :: IO (SizedSeq Word16)
839 lits <- return emptySS :: IO (SizedSeq Word)
840 ptrs <- return emptySS :: IO (SizedSeq Name)
841 itbls <- return emptySS :: IO (SizedSeq Name)
842 let init_asm_state = (insns,lits,ptrs,itbls)
843 (final_insns, final_lits, final_ptrs, final_itbls)
844 <- mkBits findLabel init_asm_state instrs
846 return (UnlinkedBCO nm final_insns final_lits final_ptrs final_itbls)
848 -- instrs nonptrs ptrs itbls
849 type AsmState = (SizedSeq Word16, SizedSeq Word, SizedSeq Name, SizedSeq Name)
851 data SizedSeq a = SizedSeq !Int [a]
852 emptySS = SizedSeq 0 []
853 addToSS (SizedSeq n r_xs) x = return (SizedSeq (n+1) (x:r_xs))
854 addListToSS (SizedSeq n r_xs) xs
855 = return (SizedSeq (n + length xs) (reverse xs ++ r_xs))
856 sizeSS (SizedSeq n r_xs) = n
857 listFromSS (SizedSeq n r_xs) = return (reverse r_xs)
860 -- This is where all the action is (pass 2 of the assembler)
861 mkBits :: (Int -> Int) -- label finder
863 -> [BCInstr] -- instructions (in)
866 mkBits findLabel st proto_insns
867 = foldM doInstr st proto_insns
869 doInstr :: AsmState -> BCInstr -> IO AsmState
872 ARGCHECK n -> instr2 st i_ARGCHECK n
873 PUSH_L o1 -> instr2 st i_PUSH_L o1
874 PUSH_LL o1 o2 -> instr3 st i_PUSH_LL o1 o2
875 PUSH_LLL o1 o2 o3 -> instr4 st i_PUSH_LLL o1 o2 o3
876 PUSH_G nm -> do (p, st2) <- ptr st nm
877 instr2 st2 i_PUSH_G p
878 PUSH_AS nm pk -> do (p, st2) <- ptr st nm
879 (np, st3) <- ret_itbl st2 pk
880 instr3 st3 i_PUSH_AS p np
881 PUSH_UBX lit nws -> do (np, st2) <- literal st lit
882 instr3 st2 i_PUSH_UBX np nws
883 PUSH_TAG tag -> instr2 st i_PUSH_TAG tag
884 SLIDE n by -> instr3 st i_SLIDE n by
885 ALLOC n -> instr2 st i_ALLOC n
886 MKAP off sz -> instr3 st i_MKAP off sz
887 UNPACK n -> instr2 st i_UNPACK n
888 UPK_TAG n m k -> instr4 st i_UPK_TAG n m k
889 PACK dcon sz -> do (itbl_no,st2) <- itbl st dcon
890 instr3 st2 i_PACK itbl_no sz
891 LABEL lab -> return st
892 TESTLT_I i l -> do (np, st2) <- int st i
893 instr3 st2 i_TESTLT_I np (findLabel l)
894 TESTEQ_I i l -> do (np, st2) <- int st i
895 instr3 st2 i_TESTEQ_I np (findLabel l)
896 TESTLT_F f l -> do (np, st2) <- float st f
897 instr3 st2 i_TESTLT_F np (findLabel l)
898 TESTEQ_F f l -> do (np, st2) <- float st f
899 instr3 st2 i_TESTEQ_F np (findLabel l)
900 TESTLT_D d l -> do (np, st2) <- double st d
901 instr3 st2 i_TESTLT_D np (findLabel l)
902 TESTEQ_D d l -> do (np, st2) <- double st d
903 instr3 st2 i_TESTEQ_D np (findLabel l)
904 TESTLT_P i l -> do (np, st2) <- int st i
905 instr3 st2 i_TESTLT_P np (findLabel l)
906 TESTEQ_P i l -> do (np, st2) <- int st i
907 instr3 st2 i_TESTEQ_P np (findLabel l)
908 CASEFAIL -> instr1 st i_CASEFAIL
909 ENTER -> instr1 st i_ENTER
910 RETURN -> instr1 st i_RETURN
915 instr1 (st_i0,st_l0,st_p0,st_I0) i1
916 = do st_i1 <- addToSS st_i0 (i2s i1)
917 return (st_i1,st_l0,st_p0,st_I0)
919 instr2 (st_i0,st_l0,st_p0,st_I0) i1 i2
920 = do st_i1 <- addToSS st_i0 (i2s i1)
921 st_i2 <- addToSS st_i1 (i2s i2)
922 return (st_i2,st_l0,st_p0,st_I0)
924 instr3 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3
925 = do st_i1 <- addToSS st_i0 (i2s i1)
926 st_i2 <- addToSS st_i1 (i2s i2)
927 st_i3 <- addToSS st_i2 (i2s i3)
928 return (st_i3,st_l0,st_p0,st_I0)
930 instr4 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3 i4
931 = do st_i1 <- addToSS st_i0 (i2s i1)
932 st_i2 <- addToSS st_i1 (i2s i2)
933 st_i3 <- addToSS st_i2 (i2s i3)
934 st_i4 <- addToSS st_i3 (i2s i4)
935 return (st_i4,st_l0,st_p0,st_I0)
937 float (st_i0,st_l0,st_p0,st_I0) f
938 = do let ws = mkLitF f
939 st_l1 <- addListToSS st_l0 ws
940 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
942 double (st_i0,st_l0,st_p0,st_I0) d
943 = do let ws = mkLitD d
944 st_l1 <- addListToSS st_l0 ws
945 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
947 int (st_i0,st_l0,st_p0,st_I0) i
948 = do let ws = mkLitI i
949 st_l1 <- addListToSS st_l0 ws
950 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
952 addr (st_i0,st_l0,st_p0,st_I0) a
953 = do let ws = mkLitA a
954 st_l1 <- addListToSS st_l0 ws
955 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
957 ptr (st_i0,st_l0,st_p0,st_I0) p
958 = do st_p1 <- addToSS st_p0 p
959 return (sizeSS st_p0, (st_i0,st_l0,st_p1,st_I0))
961 itbl (st_i0,st_l0,st_p0,st_I0) dcon
962 = do st_I1 <- addToSS st_I0 (getName dcon)
963 return (sizeSS st_I0, (st_i0,st_l0,st_p0,st_I1))
965 literal st (MachInt j) = int st (fromIntegral j)
966 literal st (MachFloat r) = float st (fromRational r)
967 literal st (MachDouble r) = double st (fromRational r)
970 = addr st ret_itbl_addr
974 IntRep -> stg_ctoi_ret_R1_info
975 FloatRep -> stg_ctoi_ret_F1_info
976 DoubleRep -> stg_ctoi_ret_D1_info
978 stg_ctoi_ret_F1_info = nullAddr
979 stg_ctoi_ret_D1_info = nullAddr
981 foreign label "stg_ctoi_ret_R1_info" stg_ctoi_ret_R1_info :: Addr
982 --foreign label "stg_ctoi_ret_F1_info" stg_ctoi_ret_F1_info :: Addr
983 --foreign label "stg_ctoi_ret_D1_info" stg_ctoi_ret_D1_info :: Addr
985 -- The size in bytes of an instruction.
986 instrSizeB :: BCInstr -> Int
1017 -- Make lists of host-sized words for literals, so that when the
1018 -- words are placed in memory at increasing addresses, the
1019 -- bit pattern is correct for the host's word size and endianness.
1020 mkLitI :: Int -> [Word]
1021 mkLitF :: Float -> [Word]
1022 mkLitD :: Double -> [Word]
1023 mkLitA :: Addr -> [Word]
1027 arr <- newFloatArray ((0::Int),0)
1028 writeFloatArray arr 0 f
1029 f_arr <- castSTUArray arr
1030 w0 <- readWordArray f_arr 0
1037 arr <- newDoubleArray ((0::Int),0)
1038 writeDoubleArray arr 0 d
1039 d_arr <- castSTUArray arr
1040 w0 <- readWordArray d_arr 0
1041 w1 <- readWordArray d_arr 1
1046 arr <- newDoubleArray ((0::Int),0)
1047 writeDoubleArray arr 0 d
1048 d_arr <- castSTUArray arr
1049 w0 <- readWordArray d_arr 0
1055 arr <- newIntArray ((0::Int),0)
1056 writeIntArray arr 0 i
1057 i_arr <- castSTUArray arr
1058 w0 <- readWordArray i_arr 0
1064 arr <- newAddrArray ((0::Int),0)
1065 writeAddrArray arr 0 a
1066 a_arr <- castSTUArray arr
1067 w0 <- readWordArray a_arr 0
1073 %************************************************************************
1075 \subsection{Linking interpretables into something we can run}
1077 %************************************************************************
1083 = UnlinkedBCO Int (IOUArray Int Word16) -- #insns insns
1084 Int (IOUArray Int Word32) -- #literals literals
1085 Int (IOArray Int Name) -- #ptrs ptrs
1086 Int (IOArray Int Name) -- #itblrefs itblrefs
1088 data BCO# = BCO# ByteArray# -- instrs :: array Word16#
1089 ByteArray# -- literals :: array Word32#
1090 PtrArray# -- ptrs :: Array HValue
1091 ByteArray# -- itbls :: Array Addr#
1094 GLOBAL_VAR(v_cafTable, [], [HValue])
1096 --addCAF :: HValue -> IO ()
1097 --addCAF x = do xs <- readIORef v_cafTable; writeIORef v_cafTable (x:xs)
1099 --bcosToHValue :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr -> IO HValue
1100 --bcosToHValue ie ce (root_bco, other_bcos)
1101 -- = do linked_expr <- linkIExpr ie ce (root_bco, other_bcos)
1102 -- return linked_expr
1105 linkIModules :: ItblEnv -- incoming global itbl env; returned updated
1106 -> ClosureEnv -- incoming global closure env; returned updated
1107 -> [([UnlinkedBCO], ItblEnv)]
1108 -> IO ([HValue], ItblEnv, ClosureEnv)
1109 linkIModules gie gce mods = do
1110 let (bcoss, ies) = unzip mods
1112 top_level_binders = map nameOfUnlinkedBCO bcos
1113 final_gie = foldr plusFM gie ies
1115 (new_bcos, new_gce) <-
1116 fixIO (\ ~(new_bcos, new_gce) -> do
1117 new_bcos <- linkBCOs final_gie new_gce bcos
1118 let new_gce = addListToFM gce (zip top_level_binders new_bcos)
1119 return (new_bcos, new_gce))
1121 return (new_bcos, final_gie, new_gce)
1124 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
1125 -> IO HValue -- IO BCO# really
1126 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
1127 = do let aux_ul_binders = map nameOfUnlinkedBCO aux_ul_bcos
1130 (\ ~(aux_bcos, new_ce)
1131 -> do new_bcos <- linkBCOs ie new_ce aux_ul_bcos
1132 let new_ce = addListToFM ce (zip aux_ul_binders new_bcos)
1133 return (new_bcos, new_ce)
1136 <- linkBCOs ie aux_ce [root_ul_bco]
1140 linkBCOs :: ItblEnv -> ClosureEnv -> [UnlinkedBCO]
1141 -> IO [HValue] -- IO [BCO#] really
1142 linkBCOs ie ce binds = mapM (linkBCO ie ce) binds
1144 linkBCO ie ce (UnlinkedBCO nm insnsSS literalsSS ptrsSS itblsSS)
1145 = do insns <- listFromSS insnsSS
1146 literals <- listFromSS literalsSS
1147 ptrs <- listFromSS ptrsSS
1148 itbls <- listFromSS itblsSS
1150 let linked_ptrs = map (lookupCE ce) ptrs
1151 linked_itbls = map (lookupIE ie) itbls
1153 let n_insns = sizeSS insnsSS
1154 n_literals = sizeSS literalsSS
1155 n_ptrs = sizeSS ptrsSS
1156 n_itbls = sizeSS itblsSS
1158 let ptrs_arr = array (0, n_ptrs-1) (indexify linked_ptrs)
1160 ptrs_parr = case ptrs_arr of Array lo hi parr -> parr
1162 itbls_arr = array (0, n_itbls-1) (indexify linked_itbls)
1164 itbls_barr = case itbls_arr of UArray lo hi barr -> barr
1166 insns_arr = array (0, n_insns-1) (indexify insns)
1167 :: UArray Int Word16
1168 insns_barr = case insns_arr of UArray lo hi barr -> barr
1170 literals_arr = array (0, n_literals-1) (indexify literals)
1172 literals_barr = case literals_arr of UArray lo hi barr -> barr
1174 indexify :: [a] -> [(Int, a)]
1175 indexify xs = zip [0..] xs
1177 BCO bco# <- newBCO insns_barr literals_barr ptrs_parr itbls_barr
1179 return (unsafeCoerce# bco#)
1184 newBCO :: ByteArray# -> ByteArray# -> Array# a -> ByteArray# -> IO BCO
1186 = IO (\s -> case newBCO# a b c d s of (# s1, bco #) -> (# s1, BCO bco #))
1189 lookupCE :: ClosureEnv -> Name -> HValue
1191 = case lookupFM ce nm of
1192 Just aa -> unsafeCoerce# aa
1193 Nothing -> pprPanic "ByteCodeGen.lookupCE" (ppr nm)
1195 lookupIE :: ItblEnv -> Name -> Addr
1197 = case lookupFM ie nm of
1199 Nothing -> pprPanic "ByteCodeGen.lookupIE" (ppr nm)
1205 case lookupFM ie con of
1206 Just (Ptr addr) -> return addr
1208 -- try looking up in the object files.
1209 m <- lookupSymbol (nameToCLabel con "con_info")
1211 Just addr -> return addr
1212 Nothing -> pprPanic "linkIExpr" (ppr con)
1214 -- nullary constructors don't have normal _con_info tables.
1215 lookupNullaryCon ie con =
1216 case lookupFM ie con of
1217 Just (Ptr addr) -> return (ConApp addr)
1219 -- try looking up in the object files.
1220 m <- lookupSymbol (nameToCLabel con "closure")
1222 Just (A# addr) -> return (Native (unsafeCoerce# addr))
1223 Nothing -> pprPanic "lookupNullaryCon" (ppr con)
1226 lookupNative ce var =
1227 unsafeInterleaveIO (do
1228 case lookupFM ce var of
1229 Just e -> return (Native e)
1231 -- try looking up in the object files.
1232 let lbl = (nameToCLabel var "closure")
1233 m <- lookupSymbol lbl
1236 -> do addCAF (unsafeCoerce# addr)
1237 return (Native (unsafeCoerce# addr))
1238 Nothing -> pprPanic "linkIExpr" (ppr var)
1241 -- some VarI/VarP refer to top-level interpreted functions; we change
1242 -- them into Natives here.
1244 unsafeInterleaveIO (
1245 case lookupFM ce (getName v) of
1246 Nothing -> return (f v)
1247 Just e -> return (Native e)
1250 -- HACK!!! ToDo: cleaner
1251 nameToCLabel :: Name -> String{-suffix-} -> String
1252 nameToCLabel n suffix =
1253 _UNPK_(moduleNameFS (rdrNameModule rn))
1254 ++ '_':occNameString(rdrNameOcc rn) ++ '_':suffix
1255 where rn = toRdrName n
1259 %************************************************************************
1261 \subsection{Manufacturing of info tables for DataCons}
1263 %************************************************************************
1267 #if __GLASGOW_HASKELL__ <= 408
1270 type ItblPtr = Ptr StgInfoTable
1273 -- Make info tables for the data decls in this module
1274 mkITbls :: [TyCon] -> IO ItblEnv
1275 mkITbls [] = return emptyFM
1276 mkITbls (tc:tcs) = do itbls <- mkITbl tc
1277 itbls2 <- mkITbls tcs
1278 return (itbls `plusFM` itbls2)
1280 mkITbl :: TyCon -> IO ItblEnv
1282 -- | trace ("TYCON: " ++ showSDoc (ppr tc)) False
1284 | not (isDataTyCon tc)
1286 | n == length dcs -- paranoia; this is an assertion.
1287 = make_constr_itbls dcs
1289 dcs = tyConDataCons tc
1290 n = tyConFamilySize tc
1293 cONSTR = 1 -- as defined in ghc/includes/ClosureTypes.h
1295 -- Assumes constructors are numbered from zero, not one
1296 make_constr_itbls :: [DataCon] -> IO ItblEnv
1297 make_constr_itbls cons
1299 = do is <- mapM mk_vecret_itbl (zip cons [0..])
1300 return (listToFM is)
1302 = do is <- mapM mk_dirret_itbl (zip cons [0..])
1303 return (listToFM is)
1305 mk_vecret_itbl (dcon, conNo)
1306 = mk_itbl dcon conNo (vecret_entry conNo)
1307 mk_dirret_itbl (dcon, conNo)
1308 = mk_itbl dcon conNo stg_interp_constr_entry
1310 mk_itbl :: DataCon -> Int -> Addr -> IO (Name,ItblPtr)
1311 mk_itbl dcon conNo entry_addr
1312 = let (tot_wds, ptr_wds, _)
1313 = mkVirtHeapOffsets typePrimRep (dataConRepArgTys dcon)
1315 nptrs = tot_wds - ptr_wds
1316 itbl = StgInfoTable {
1317 ptrs = fromIntegral ptrs, nptrs = fromIntegral nptrs,
1318 tipe = fromIntegral cONSTR,
1319 srtlen = fromIntegral conNo,
1320 code0 = fromIntegral code0, code1 = fromIntegral code1,
1321 code2 = fromIntegral code2, code3 = fromIntegral code3,
1322 code4 = fromIntegral code4, code5 = fromIntegral code5,
1323 code6 = fromIntegral code6, code7 = fromIntegral code7
1325 -- Make a piece of code to jump to "entry_label".
1326 -- This is the only arch-dependent bit.
1327 -- On x86, if entry_label has an address 0xWWXXYYZZ,
1328 -- emit movl $0xWWXXYYZZ,%eax ; jmp *%eax
1330 -- B8 ZZ YY XX WW FF E0
1331 (code0,code1,code2,code3,code4,code5,code6,code7)
1332 = (0xB8, byte 0 entry_addr_w, byte 1 entry_addr_w,
1333 byte 2 entry_addr_w, byte 3 entry_addr_w,
1337 entry_addr_w :: Word32
1338 entry_addr_w = fromIntegral (addrToInt entry_addr)
1341 --putStrLn ("SIZE of itbl is " ++ show (sizeOf itbl))
1342 --putStrLn ("# ptrs of itbl is " ++ show ptrs)
1343 --putStrLn ("# nptrs of itbl is " ++ show nptrs)
1345 return (getName dcon, addr `plusPtr` 8)
1348 byte :: Int -> Word32 -> Word32
1349 byte 0 w = w .&. 0xFF
1350 byte 1 w = (w `shiftR` 8) .&. 0xFF
1351 byte 2 w = (w `shiftR` 16) .&. 0xFF
1352 byte 3 w = (w `shiftR` 24) .&. 0xFF
1355 vecret_entry 0 = stg_interp_constr1_entry
1356 vecret_entry 1 = stg_interp_constr2_entry
1357 vecret_entry 2 = stg_interp_constr3_entry
1358 vecret_entry 3 = stg_interp_constr4_entry
1359 vecret_entry 4 = stg_interp_constr5_entry
1360 vecret_entry 5 = stg_interp_constr6_entry
1361 vecret_entry 6 = stg_interp_constr7_entry
1362 vecret_entry 7 = stg_interp_constr8_entry
1364 -- entry point for direct returns for created constr itbls
1365 foreign label "stg_interp_constr_entry" stg_interp_constr_entry :: Addr
1366 -- and the 8 vectored ones
1367 foreign label "stg_interp_constr1_entry" stg_interp_constr1_entry :: Addr
1368 foreign label "stg_interp_constr2_entry" stg_interp_constr2_entry :: Addr
1369 foreign label "stg_interp_constr3_entry" stg_interp_constr3_entry :: Addr
1370 foreign label "stg_interp_constr4_entry" stg_interp_constr4_entry :: Addr
1371 foreign label "stg_interp_constr5_entry" stg_interp_constr5_entry :: Addr
1372 foreign label "stg_interp_constr6_entry" stg_interp_constr6_entry :: Addr
1373 foreign label "stg_interp_constr7_entry" stg_interp_constr7_entry :: Addr
1374 foreign label "stg_interp_constr8_entry" stg_interp_constr8_entry :: Addr
1380 -- Ultra-minimalist version specially for constructors
1381 data StgInfoTable = StgInfoTable {
1386 code0, code1, code2, code3, code4, code5, code6, code7 :: Word8
1390 instance Storable StgInfoTable where
1393 = (sum . map (\f -> f itbl))
1394 [fieldSz ptrs, fieldSz nptrs, fieldSz srtlen, fieldSz tipe,
1395 fieldSz code0, fieldSz code1, fieldSz code2, fieldSz code3,
1396 fieldSz code4, fieldSz code5, fieldSz code6, fieldSz code7]
1399 = (sum . map (\f -> f itbl))
1400 [fieldAl ptrs, fieldAl nptrs, fieldAl srtlen, fieldAl tipe,
1401 fieldAl code0, fieldAl code1, fieldAl code2, fieldAl code3,
1402 fieldAl code4, fieldAl code5, fieldAl code6, fieldAl code7]
1405 = do a1 <- store (ptrs itbl) (castPtr a0)
1406 a2 <- store (nptrs itbl) a1
1407 a3 <- store (tipe itbl) a2
1408 a4 <- store (srtlen itbl) a3
1409 a5 <- store (code0 itbl) a4
1410 a6 <- store (code1 itbl) a5
1411 a7 <- store (code2 itbl) a6
1412 a8 <- store (code3 itbl) a7
1413 a9 <- store (code4 itbl) a8
1414 aA <- store (code5 itbl) a9
1415 aB <- store (code6 itbl) aA
1416 aC <- store (code7 itbl) aB
1420 = do (a1,ptrs) <- load (castPtr a0)
1421 (a2,nptrs) <- load a1
1422 (a3,tipe) <- load a2
1423 (a4,srtlen) <- load a3
1424 (a5,code0) <- load a4
1425 (a6,code1) <- load a5
1426 (a7,code2) <- load a6
1427 (a8,code3) <- load a7
1428 (a9,code4) <- load a8
1429 (aA,code5) <- load a9
1430 (aB,code6) <- load aA
1431 (aC,code7) <- load aB
1432 return StgInfoTable { ptrs = ptrs, nptrs = nptrs,
1433 srtlen = srtlen, tipe = tipe,
1434 code0 = code0, code1 = code1, code2 = code2,
1435 code3 = code3, code4 = code4, code5 = code5,
1436 code6 = code6, code7 = code7 }
1438 fieldSz :: (Storable a, Storable b) => (a -> b) -> a -> Int
1439 fieldSz sel x = sizeOf (sel x)
1441 fieldAl :: (Storable a, Storable b) => (a -> b) -> a -> Int
1442 fieldAl sel x = alignment (sel x)
1444 store :: Storable a => a -> Ptr a -> IO (Ptr b)
1445 store x addr = do poke addr x
1446 return (castPtr (addr `plusPtr` sizeOf x))
1448 load :: Storable a => Ptr a -> IO (Ptr b, a)
1449 load addr = do x <- peek addr
1450 return (castPtr (addr `plusPtr` sizeOf x), x)
1454 %************************************************************************
1456 \subsection{Connect to actual values for bytecode opcodes}
1458 %************************************************************************
1462 #include "Bytecodes.h"
1464 i_ARGCHECK = (bci_ARGCHECK :: Int)
1465 i_PUSH_L = (bci_PUSH_L :: Int)
1466 i_PUSH_LL = (bci_PUSH_LL :: Int)
1467 i_PUSH_LLL = (bci_PUSH_LLL :: Int)
1468 i_PUSH_G = (bci_PUSH_G :: Int)
1469 i_PUSH_AS = (bci_PUSH_AS :: Int)
1470 i_PUSH_UBX = (bci_PUSH_UBX :: Int)
1471 i_PUSH_TAG = (bci_PUSH_TAG :: Int)
1472 i_SLIDE = (bci_SLIDE :: Int)
1473 i_ALLOC = (bci_ALLOC :: Int)
1474 i_MKAP = (bci_MKAP :: Int)
1475 i_UNPACK = (bci_UNPACK :: Int)
1476 i_UPK_TAG = (bci_UPK_TAG :: Int)
1477 i_PACK = (bci_PACK :: Int)
1478 i_LABEL = (bci_LABEL :: Int)
1479 i_TESTLT_I = (bci_TESTLT_I :: Int)
1480 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
1481 i_TESTLT_F = (bci_TESTLT_F :: Int)
1482 i_TESTEQ_F = (bci_TESTEQ_F :: Int)
1483 i_TESTLT_D = (bci_TESTLT_D :: Int)
1484 i_TESTEQ_D = (bci_TESTEQ_D :: Int)
1485 i_TESTLT_P = (bci_TESTLT_P :: Int)
1486 i_TESTEQ_P = (bci_TESTEQ_P :: Int)
1487 i_CASEFAIL = (bci_CASEFAIL :: Int)
1488 i_ENTER = (bci_ENTER :: Int)
1489 i_RETURN = (bci_RETURN :: Int)