2 % (c) The University of Glasgow 2000
4 \section[ByteCodeGen]{Generate bytecode from Core}
7 module ByteCodeGen ( byteCodeGen, assembleBCO ) where
9 #include "HsVersions.h"
12 import Name ( Name, getName )
13 import Id ( Id, idType, isDataConId_maybe )
14 import OrdList ( OrdList, consOL, snocOL, appOL, unitOL,
15 nilOL, toOL, concatOL, fromOL )
16 import FiniteMap ( FiniteMap, addListToFM, listToFM,
17 addToFM, lookupFM, fmToList, emptyFM )
19 import PprCore ( pprCoreExpr, pprCoreAlt )
20 import Literal ( Literal(..) )
21 import PrimRep ( PrimRep(..) )
22 import CoreFVs ( freeVars )
23 import Type ( typePrimRep )
24 import DataCon ( DataCon, dataConTag, fIRST_TAG, dataConTyCon )
25 import TyCon ( tyConFamilySize )
26 import Util ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem )
27 import Var ( isTyVar )
28 import VarSet ( VarSet, varSetElems )
29 import PrimRep ( getPrimRepSize, isFollowableRep )
30 import Constants ( wORD_SIZE )
32 import Foreign ( Addr, Word16, Word32, nullAddr )
34 import MutableArray ( readWord32Array,
35 newFloatArray, writeFloatArray,
36 newDoubleArray, writeDoubleArray,
37 newIntArray, writeIntArray,
38 newAddrArray, writeAddrArray )
44 byteCodeGen :: [CoreBind] -> [ProtoBCO Name]
46 = let flatBinds = concatMap getBind binds
47 getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
48 getBind (Rec binds) = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
49 final_state = runBc (BcM_State [] 0)
50 (mapBc schemeR flatBinds `thenBc_` returnBc ())
53 BcM_State bcos final_ctr -> bcos
57 %************************************************************************
59 \subsection{Bytecodes, and Outputery.}
61 %************************************************************************
68 -- Messing with the stack
70 | PUSH_L Int{-offset-}
71 | PUSH_LL Int Int{-2 offsets-}
72 | PUSH_LLL Int Int Int{-3 offsets-}
74 | PUSH_AS Name Int -- push alts and BCO_ptr_ret_info
75 -- Int is lit pool offset for itbl
76 | PUSH_LIT Int -- push literal word from offset pool
77 | PUSH_TAG Int -- push this tag on the stack
85 | SLIDE Int{-this many-} Int{-down by this much-}
86 -- To do with the heap
87 | ALLOC Int -- make an AP_UPD with this many payload words, zeroed
88 | MKAP Int{-ptr to AP_UPD is this far down stack-} Int{-# words-}
89 | UNPACK Int -- unpack N ptr words from t.o.s Constr
90 | UNPACK_I Int -- unpack and tag an Int, from t.o.s Constr @ offset
91 | UNPACK_F Int -- unpack and tag a Float, from t.o.s Constr @ offset
92 | UNPACK_D Int -- unpack and tag a Double, from t.o.s Constr @ offset
94 -- For doing case trees
96 | TESTLT_I Int LocalLabel
97 | TESTEQ_I Int LocalLabel
98 | TESTLT_F Float LocalLabel
99 | TESTEQ_F Float LocalLabel
100 | TESTLT_D Double LocalLabel
101 | TESTEQ_D Double LocalLabel
102 | TESTLT_P Int LocalLabel
103 | TESTEQ_P Int LocalLabel
105 -- To Infinity And Beyond
107 | RETURN -- unboxed value on TOS. Use tag to find underlying ret itbl
108 -- and return as per that.
111 instance Outputable BCInstr where
112 ppr (ARGCHECK n) = text "ARGCHECK" <+> int n
113 ppr (PUSH_L offset) = text "PUSH_L " <+> int offset
114 ppr (PUSH_LL o1 o2) = text "PUSH_LL " <+> int o1 <+> int o2
115 ppr (PUSH_LLL o1 o2 o3) = text "PUSH_LLL" <+> int o1 <+> int o2 <+> int o3
116 ppr (PUSH_G nm) = text "PUSH_G " <+> ppr nm
117 ppr (PUSH_AS nm) = text "PUSH_AS " <+> ppr nm
118 ppr (PUSHT_I i) = text "PUSHT_I " <+> int i
119 ppr (SLIDE n d) = text "SLIDE " <+> int n <+> int d
120 ppr (ALLOC sz) = text "ALLOC " <+> int sz
121 ppr (MKAP offset sz) = text "MKAP " <+> int offset <+> int sz
122 ppr (UNPACK sz) = text "UNPACK " <+> int sz
123 ppr (UNPACK_I sz) = text "UNPACK_I" <+> int sz
124 ppr (UNPACK_F sz) = text "UNPACK_F" <+> int sz
125 ppr (UNPACK_D sz) = text "UNPACK_D" <+> int sz
126 ppr (PACK dcon sz) = text "PACK " <+> ppr dcon <+> ppr sz
127 ppr (LABEL lab) = text "__" <> int lab <> colon
128 ppr (TESTLT_I i lab) = text "TESTLT_I" <+> int i <+> text "__" <> int lab
129 ppr (TESTEQ_I i lab) = text "TESTEQ_I" <+> int i <+> text "__" <> int lab
130 ppr (TESTLT_F f lab) = text "TESTLT_F" <+> float f <+> text "__" <> int lab
131 ppr (TESTEQ_F f lab) = text "TESTEQ_F" <+> float f <+> text "__" <> int lab
132 ppr (TESTLT_D d lab) = text "TESTLT_D" <+> double d <+> text "__" <> int lab
133 ppr (TESTEQ_D d lab) = text "TESTEQ_D" <+> double d <+> text "__" <> int lab
134 ppr (TESTLT_P i lab) = text "TESTLT_P" <+> int i <+> text "__" <> int lab
135 ppr (TESTEQ_P i lab) = text "TESTEQ_P" <+> int i <+> text "__" <> int lab
136 ppr CASEFAIL = text "CASEFAIL"
137 ppr ENTER = text "ENTER"
138 ppr RETURN = text "RETURN"
140 pprAltCode discrs_n_codes
141 = vcat (map f discrs_n_codes)
142 where f (discr, code) = ppr discr <> colon <+> vcat (map ppr (fromOL code))
144 instance Outputable a => Outputable (ProtoBCO a) where
145 ppr (ProtoBCO name instrs origin)
146 = (text "ProtoBCO" <+> ppr name <> colon)
147 $$ nest 6 (vcat (map ppr instrs))
149 Left alts -> vcat (map (pprCoreAlt.deAnnAlt) alts)
150 Right rhs -> pprCoreExpr (deAnnotate rhs)
153 %************************************************************************
155 \subsection{Compilation schema for the bytecode generator.}
157 %************************************************************************
161 type BCInstrList = OrdList BCInstr
164 = ProtoBCO a -- name, in some sense
166 -- what the BCO came from
167 (Either [AnnAlt Id VarSet]
171 type Sequel = Int -- back off to this depth before ENTER
173 -- Maps Ids to the offset from the stack _base_ so we don't have
174 -- to mess with it after each push/pop.
175 type BCEnv = FiniteMap Id Int -- To find vars on the stack
178 -- Create a BCO and do a spot of peephole optimisation on the insns
180 mkProtoBCO nm instrs_ordlist origin
181 = ProtoBCO nm (peep (fromOL instrs_ordlist)) origin
183 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
184 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
185 peep (PUSH_L off1 : PUSH_L off2 : rest)
186 = PUSH_LL off1 off2 : peep rest
193 -- Compile code for the right hand side of a let binding.
194 -- Park the resulting BCO in the monad. Also requires the
195 -- variable to which this value was bound, so as to give the
196 -- resulting BCO a name.
197 schemeR :: (Id, AnnExpr Id VarSet) -> BcM ()
198 schemeR (nm, rhs) = schemeR_wrk rhs nm (collect [] rhs)
200 collect xs (_, AnnLam x e)
201 = collect (if isTyVar x then xs else (x:xs)) e
202 collect xs not_lambda
203 = (reverse xs, not_lambda)
205 schemeR_wrk original_body nm (args, body)
206 = let fvs = filter (not.isTyVar) (varSetElems (fst original_body))
207 all_args = fvs ++ reverse args
208 szsw_args = map taggedIdSizeW all_args
209 szw_args = sum szsw_args
210 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
211 argcheck = if null args then nilOL else unitOL (ARGCHECK szw_args)
213 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
214 emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) (Right original_body))
216 -- Let szsw be the sizes in words of some items pushed onto the stack,
217 -- which has initial depth d'. Return the values which the stack environment
218 -- should map these items to.
219 mkStackOffsets :: Int -> [Int] -> [Int]
220 mkStackOffsets original_depth szsw
221 = map (subtract 1) (tail (scanl (+) original_depth szsw))
223 -- Compile code to apply the given expression to the remaining args
224 -- on the stack, returning a HNF.
225 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
227 -- Delegate tail-calls to schemeT.
228 schemeE d s p e@(fvs, AnnApp f a)
229 = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnApp f a))
230 schemeE d s p e@(fvs, AnnVar v)
231 | isFollowableRep (typePrimRep (idType v))
232 = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnVar v))
234 = -- returning an unboxed value. Heave it on the stack, SLIDE, and RETURN.
235 let (push, szw) = pushAtom True d p (AnnVar v)
236 in returnBc (push -- value onto stack
237 `snocOL` SLIDE szw (d-s) -- clear to sequel
238 `snocOL` RETURN) -- go
240 schemeE d s p (fvs, AnnLit literal)
241 = let (push, szw) = pushAtom True d p (AnnLit literal)
242 in returnBc (push -- value onto stack
243 `snocOL` SLIDE szw (d-s) -- clear to sequel
244 `snocOL` RETURN) -- go
246 schemeE d s p (fvs, AnnLet binds b)
247 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
248 AnnRec xs_n_rhss -> unzip xs_n_rhss
250 fvss = map (filter (not.isTyVar).varSetElems.fst) rhss
251 sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
253 -- This p', d' defn is safe because all the items being pushed
254 -- are ptrs, so all have size 1. d' and p' reflect the stack
255 -- after the closures have been allocated in the heap (but not
256 -- filled in), and pointers to them parked on the stack.
257 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
260 infos = zipE4 fvss sizes xs [n, n-1 .. 1]
261 zipE = zipEqual "schemeE"
262 zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
264 -- ToDo: don't build thunks for things with no free variables
265 buildThunk dd ([], size, id, off)
266 = PUSH_G (getName id)
267 `consOL` unitOL (MKAP (off+size-1) size)
268 buildThunk dd ((fv:fvs), size, id, off)
269 = case pushAtom True dd p' (AnnVar fv) of
270 (push_code, pushed_szw)
272 buildThunk (dd+pushed_szw) (fvs, size, id, off)
274 thunkCode = concatOL (map (buildThunk d') infos)
275 allocCode = toOL (map ALLOC sizes)
277 schemeE d' s p' b `thenBc` \ bodyCode ->
278 mapBc schemeR (zip xs rhss) `thenBc_`
279 returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
282 schemeE d s p (fvs, AnnCase scrut bndr alts)
284 -- Top of stack is the return itbl, as usual.
285 -- underneath it is the pointer to the alt_code BCO.
286 -- When an alt is entered, it assumes the returned value is
287 -- on top of the itbl.
290 -- Env and depth in which to compile the alts, not including
291 -- any vars bound by the alts themselves
292 d' = d + ret_frame_sizeW + taggedIdSizeW bndr
293 p' = addToFM p bndr (d' - 1)
296 = case typePrimRep (idType bndr) of
297 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
299 other -> pprPanic "ByteCodeGen.schemeE" (ppr other)
301 -- given an alt, return a discr and code for it.
302 codeAlt alt@(discr, binds_f, rhs)
304 = let binds_r = reverse binds_f
305 binds_r_szsw = map untaggedIdSizeW binds_r
306 binds_szw = sum binds_r_szsw
308 p' (zip binds_r (mkStackOffsets d' binds_r_szsw))
310 unpack_code = mkUnpackCode 0 (map (typePrimRep.idType) binds_f)
311 in schemeE d'' s p'' rhs `thenBc` \ rhs_code ->
312 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
314 = ASSERT(null binds_f)
315 schemeE d' s p' rhs `thenBc` \ rhs_code ->
316 returnBc (my_discr alt, rhs_code)
318 my_discr (DEFAULT, binds, rhs) = NoDiscr
319 my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc)
320 my_discr (LitAlt l, binds, rhs)
321 = case l of MachInt i -> DiscrI (fromInteger i)
322 MachFloat r -> DiscrF (fromRational r)
323 MachDouble r -> DiscrD (fromRational r)
326 | not isAlgCase = Nothing
328 = case [dc | (DataAlt dc, _, _) <- alts] of
330 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
333 mapBc codeAlt alts `thenBc` \ alt_stuff ->
334 mkMultiBranch maybe_ncons alt_stuff `thenBc` \ alt_final ->
336 alt_bco_name = getName bndr
337 alt_bco = mkProtoBCO alt_bco_name alt_final (Left alts)
339 schemeE (d + ret_frame_sizeW)
340 (d + ret_frame_sizeW) p scrut `thenBc` \ scrut_code ->
342 emitBc alt_bco `thenBc_`
343 returnBc (PUSH_AS alt_bco_name `consOL` scrut_code)
346 schemeE d s p (fvs, AnnNote note body)
350 = pprPanic "ByteCodeGen.schemeE: unhandled case"
351 (pprCoreExpr (deAnnotate other))
354 -- Compile code to do a tail call. Doesn't need to be monadic.
355 schemeT :: Bool -- do tagging?
356 -> Int -- Stack depth
357 -> Sequel -- Sequel depth
358 -> Int -- # arg words so far
359 -> BCEnv -- stack env
360 -> AnnExpr Id VarSet -> BCInstrList
362 schemeT enTag d s narg_words p (_, AnnApp f a)
364 AnnType _ -> schemeT enTag d s narg_words p f
366 -> let (push, arg_words) = pushAtom enTag d p (snd a)
368 `appOL` schemeT enTag (d+arg_words) s (narg_words+arg_words) p f
370 schemeT enTag d s narg_words p (_, AnnVar f)
371 | Just con <- isDataConId_maybe f
372 = ASSERT(enTag == False)
373 PACK con narg_words `consOL` (mkSLIDE 1 (d-s-1) `snocOL` ENTER)
375 = ASSERT(enTag == True)
376 let (push, arg_words) = pushAtom True d p (AnnVar f)
378 `appOL` mkSLIDE (narg_words+arg_words) (d - s - narg_words)
382 = if d == 0 then nilOL else unitOL (SLIDE n d)
384 should_args_be_tagged (_, AnnVar v)
385 = case isDataConId_maybe v of
386 Just dcon -> False; Nothing -> True
387 should_args_be_tagged (_, AnnApp f a)
388 = should_args_be_tagged f
389 should_args_be_tagged (_, other)
390 = panic "should_args_be_tagged: tail call to non-con, non-var"
393 -- Make code to unpack a constructor onto the stack, adding
394 -- tags for the unboxed bits. Takes the PrimReps of the constructor's
395 -- arguments, and a travelling offset along the *constructor*.
396 mkUnpackCode :: Int -> [PrimRep] -> BCInstrList
397 mkUnpackCode off [] = nilOL
398 mkUnpackCode off (r:rs)
400 = let (rs_ptr, rs_nptr) = span isFollowableRep (r:rs)
401 ptrs_szw = sum (map untaggedSizeW rs_ptr)
402 in ASSERT(ptrs_szw == length rs_ptr)
403 UNPACK ptrs_szw `consOL` mkUnpackCode (off+ptrs_szw) rs_nptr
406 IntRep -> UNPACK_I off `consOL` theRest
407 FloatRep -> UNPACK_F off `consOL` theRest
408 DoubleRep -> UNPACK_D off `consOL` theRest
410 theRest = mkUnpackCode (off+untaggedSizeW r) rs
412 -- Push an atom onto the stack, returning suitable code & number of
413 -- stack words used. Pushes it either tagged or untagged, since
414 -- pushAtom is used to set up the stack prior to copying into the
415 -- heap for both APs (requiring tags) and constructors (which don't).
417 -- NB this means NO GC between pushing atoms for a constructor and
418 -- copying them into the heap. It probably also means that
419 -- tail calls MUST be of the form atom{atom ... atom} since if the
420 -- expression head was allowed to be arbitrary, there could be GC
421 -- in between pushing the arg atoms and completing the head.
422 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
423 -- isn't a problem; but only if arbitrary graph construction for the
424 -- head doesn't leave this BCO, since GC might happen at the start of
425 -- each BCO (we consult doYouWantToGC there).
427 -- Blargh. JRS 001206
429 -- NB (further) that the env p must map each variable to the highest-
430 -- numbered stack slot for it. For example, if the stack has depth 4
431 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
432 -- the tag in stack[5], the stack will have depth 6, and p must map v to
433 -- 5 and not to 4. Stack locations are numbered from zero, so a depth
434 -- 6 stack has valid words 0 .. 5.
436 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
437 pushAtom tagged d p (AnnVar v)
438 = let str = "\npushAtom " ++ showSDocDebug (ppr v) ++ ", depth = " ++ show d
440 showSDocDebug (nest 4 (vcat (map ppr (fmToList p))))
442 showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
443 ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
444 str' = if str == str then str else str
447 = case lookupBCEnv_maybe p v of
448 Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), sz_t)
449 Nothing -> ASSERT(sz_t == 1) (unitOL (PUSH_G nm), sz_t)
452 sz_t = taggedIdSizeW v
453 sz_u = untaggedIdSizeW v
454 nwords = if tagged then sz_t else sz_u
459 pushAtom True d p (AnnLit lit)
461 MachInt i -> (unitOL (PUSHT_I (fromInteger i)), taggedSizeW IntRep)
462 MachFloat r -> (unitOL (PUSHT_F (fromRational r)), taggedSizeW FloatRep)
463 MachDouble r -> (unitOL (PUSHT_D (fromRational r)), taggedSizeW DoubleRep)
465 pushAtom False d p (AnnLit lit)
467 MachInt i -> (unitOL (PUSHU_I (fromInteger i)), untaggedSizeW IntRep)
468 MachFloat r -> (unitOL (PUSHU_F (fromRational r)), untaggedSizeW FloatRep)
469 MachDouble r -> (unitOL (PUSHU_D (fromRational r)), untaggedSizeW DoubleRep)
471 pushAtom tagged d p (AnnApp f (_, AnnType _))
472 = pushAtom tagged d p (snd f)
474 pushAtom tagged d p other
475 = pprPanic "ByteCodeGen.pushAtom"
476 (pprCoreExpr (deAnnotate (undefined, other)))
479 -- Given a bunch of alts code and their discrs, do the donkey work
480 -- of making a multiway branch using a switch tree.
481 -- What a load of hassle!
482 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
483 -- a hint; generates better code
484 -- Nothing is always safe
485 -> [(Discr, BCInstrList)]
487 mkMultiBranch maybe_ncons raw_ways
488 = let d_way = filter (isNoDiscr.fst) raw_ways
489 notd_ways = naturalMergeSortLe
490 (\w1 w2 -> leAlt (fst w1) (fst w2))
491 (filter (not.isNoDiscr.fst) raw_ways)
493 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
494 mkTree [] range_lo range_hi = returnBc the_default
496 mkTree [val] range_lo range_hi
497 | range_lo `eqAlt` range_hi
500 = getLabelBc `thenBc` \ label_neq ->
501 returnBc (mkTestEQ (fst val) label_neq
503 `appOL` unitOL (LABEL label_neq)
504 `appOL` the_default))
506 mkTree vals range_lo range_hi
507 = let n = length vals `div` 2
508 vals_lo = take n vals
509 vals_hi = drop n vals
510 v_mid = fst (head vals_hi)
512 getLabelBc `thenBc` \ label_geq ->
513 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
514 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
515 returnBc (mkTestLT v_mid label_geq
517 `appOL` unitOL (LABEL label_geq)
521 = case d_way of [] -> unitOL CASEFAIL
524 -- None of these will be needed if there are no non-default alts
525 (mkTestLT, mkTestEQ, init_lo, init_hi)
527 = panic "mkMultiBranch: awesome foursome"
529 = case fst (head notd_ways) of {
530 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
531 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
534 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
535 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
538 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
539 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
542 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
543 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
548 (algMinBound, algMaxBound)
549 = case maybe_ncons of
550 Just n -> (fIRST_TAG, fIRST_TAG + n - 1)
551 Nothing -> (minBound, maxBound)
553 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
554 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
555 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
556 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
557 NoDiscr `eqAlt` NoDiscr = True
560 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
561 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
562 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
563 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
564 NoDiscr `leAlt` NoDiscr = True
567 isNoDiscr NoDiscr = True
570 dec (DiscrI i) = DiscrI (i-1)
571 dec (DiscrP i) = DiscrP (i-1)
572 dec other = other -- not really right, but if you
573 -- do cases on floating values, you'll get what you deserve
575 -- same snotty comment applies to the following
583 mkTree notd_ways init_lo init_hi
587 %************************************************************************
589 \subsection{Supporting junk for the compilation schemes}
591 %************************************************************************
595 -- Describes case alts
603 instance Outputable Discr where
604 ppr (DiscrI i) = int i
605 ppr (DiscrF f) = text (show f)
606 ppr (DiscrD d) = text (show d)
607 ppr (DiscrP i) = int i
608 ppr NoDiscr = text "DEF"
611 -- Find things in the BCEnv (the what's-on-the-stack-env)
612 -- See comment preceding pushAtom for precise meaning of env contents
613 lookupBCEnv :: BCEnv -> Id -> Int
615 = case lookupFM env nm of
616 Nothing -> pprPanic "lookupBCEnv"
617 (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
620 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
621 lookupBCEnv_maybe = lookupFM
624 -- When I push one of these on the stack, how much does Sp move by?
625 taggedSizeW :: PrimRep -> Int
627 | isFollowableRep pr = 1
628 | otherwise = 1{-the tag-} + getPrimRepSize pr
631 -- The plain size of something, without tag.
632 untaggedSizeW :: PrimRep -> Int
634 | isFollowableRep pr = 1
635 | otherwise = getPrimRepSize pr
638 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
639 taggedIdSizeW = taggedSizeW . typePrimRep . idType
640 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
644 %************************************************************************
646 \subsection{The bytecode generator's monad}
648 %************************************************************************
652 = BcM_State { bcos :: [ProtoBCO Name], -- accumulates completed BCOs
653 nextlabel :: Int } -- for generating local labels
655 type BcM result = BcM_State -> (result, BcM_State)
657 mkBcM_State :: [ProtoBCO Name] -> Int -> BcM_State
658 mkBcM_State = BcM_State
660 runBc :: BcM_State -> BcM () -> BcM_State
661 runBc init_st m = case m init_st of { (r,st) -> st }
663 thenBc :: BcM a -> (a -> BcM b) -> BcM b
665 = case expr st of { (result, st') -> cont result st' }
667 thenBc_ :: BcM a -> BcM b -> BcM b
669 = case expr st of { (result, st') -> cont st' }
671 returnBc :: a -> BcM a
672 returnBc result st = (result, st)
674 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
675 mapBc f [] = returnBc []
677 = f x `thenBc` \ r ->
678 mapBc f xs `thenBc` \ rs ->
681 emitBc :: ProtoBCO Name -> BcM ()
683 = ((), st{bcos = bco : bcos st})
685 getLabelBc :: BcM Int
687 = (nextlabel st, st{nextlabel = 1 + nextlabel st})
691 %************************************************************************
693 \subsection{The bytecode assembler}
695 %************************************************************************
697 The object format for bytecodes is: 16 bits for the opcode, and 16 for
698 each field -- so the code can be considered a sequence of 16-bit ints.
699 Each field denotes either a stack offset or number of items on the
700 stack (eg SLIDE), and index into the pointer table (eg PUSH_G), an
701 index into the literal table (eg PUSH_I/D/L), or a bytecode address in
705 -- An (almost) assembled BCO.
706 data BCO a = BCO [Word16] -- instructions
707 [Word32] -- literal pool
708 [a] -- Names or HValues
710 -- Top level assembler fn.
711 assembleBCO :: ProtoBCO Name -> BCO Name
712 assembleBCO (ProtoBCO nm instrs origin)
714 -- pass 1: collect up the offsets of the local labels
715 label_env = mkLabelEnv emptyFM 0 instrs
717 mkLabelEnv env i_offset [] = env
718 mkLabelEnv env i_offset (i:is)
720 = case i of LABEL n -> addToFM env n i_offset ; _ -> env
721 in mkLabelEnv new_env (i_offset + instrSizeB i) is
724 = case lookupFM label_env lab of
725 Just bco_offset -> bco_offset
726 Nothing -> pprPanic "assembleBCO.findLabel" (int lab)
728 -- pass 2: generate the instruction, ptr and nonptr bits
729 (insnW16s, litW32s, ptrs) = mkBits findLabel [] 0 [] 0 [] 0 instrs
731 BCO insnW16s litW32s ptrs
734 -- This is where all the action is (pass 2 of the assembler)
735 mkBits :: (Int -> Int) -- label finder
736 -> [Word16] -> Int -- reverse acc instr bits
737 -> [Word32] -> Int -- reverse acc literal bits
738 -> [Name] -> Int -- reverse acc ptrs
739 -> [BCInstr] -- insns!
740 -> ([Word16], [Word32], [Name])
742 mkBits findLabel r_is n_is r_lits n_lits r_ptrs n_ptrs []
743 = (reverse r_is, reverse r_lits, reverse r_ptrs)
744 mkBits findLabel r_is n_is r_lits n_lits r_ptrs n_ptrs (instr:instrs)
746 ARGCHECK n -> boring2 i_ARGCHECK n
747 PUSH_L off -> boring2 i_PUSH_L off
748 PUSH_LL o1 o2 -> boring3 i_PUSH_LL o1 o2
749 PUSH_LLL o1 o2 o3 -> boring4 i_PUSH_LLL o1 o2 o3
750 PUSH_G nm -> exciting2_P i_PUSH_G n_ptrs nm
751 PUSHT_I i -> exciting2_I i_PUSHT_I n_lits i
752 PUSHT_F f -> exciting2_F i_PUSHT_F n_lits f
753 PUSHT_D d -> exciting2_D i_PUSHT_D n_lits d
754 PUSHU_I i -> exciting2_I i_PUSHU_I n_lits i
755 PUSHU_F f -> exciting2_F i_PUSHU_F n_lits f
756 PUSHU_D d -> exciting2_D i_PUSHU_D n_lits d
757 SLIDE n by -> boring3 i_SLIDE n by
758 ALLOC n -> boring2 i_ALLOC n
759 MKAP off sz -> boring3 i_MKAP off sz
760 UNPACK n -> boring2 i_UNPACK n
761 PACK dcon sz -> exciting3_A i_PACK sz n_lits nullAddr {-findItbl dcon-}
763 TESTLT_I i l -> exciting3_I i_TESTLT_I n_lits (findLabel l) i
764 TESTEQ_I i l -> exciting3_I i_TESTEQ_I n_lits (findLabel l) i
765 TESTLT_F f l -> exciting3_F i_TESTLT_F n_lits (findLabel l) f
766 TESTEQ_F f l -> exciting3_F i_TESTEQ_F n_lits (findLabel l) f
767 TESTLT_D d l -> exciting3_D i_TESTLT_D n_lits (findLabel l) d
768 TESTEQ_D d l -> exciting3_D i_TESTEQ_D n_lits (findLabel l) d
769 TESTLT_P i l -> exciting3_I i_TESTLT_P n_lits (findLabel l) i
770 TESTEQ_P i l -> exciting3_I i_TESTEQ_P n_lits (findLabel l) i
771 CASEFAIL -> boring1 i_CASEFAIL
772 ENTER -> boring1 i_ENTER
773 RETURN -> boring1 i_RETURN
775 r_mkILit = reverse . mkILit
776 r_mkFLit = reverse . mkFLit
777 r_mkDLit = reverse . mkDLit
778 r_mkALit = reverse . mkALit
784 = mkBits findLabel r_is n_is r_lits n_lits r_ptrs n_ptrs instrs
786 = mkBits findLabel (mkw i1 : r_is) (n_is+1)
787 r_lits n_lits r_ptrs n_ptrs instrs
789 = mkBits findLabel (mkw i2 : mkw i1 : r_is) (n_is+2)
790 r_lits n_lits r_ptrs n_ptrs instrs
792 = mkBits findLabel (mkw i3 : mkw i2 : mkw i1 : r_is) (n_is+3)
793 r_lits n_lits r_ptrs n_ptrs instrs
795 = mkBits findLabel (mkw i4 : mkw i3 : mkw i2 : mkw i1 : r_is) (n_is+4)
796 r_lits n_lits r_ptrs n_ptrs instrs
799 = mkBits findLabel (mkw i2 : mkw i1 : r_is) (n_is+2) r_lits n_lits
800 (p:r_ptrs) (n_ptrs+1) instrs
801 exciting3_P i1 i2 i3 p
802 = mkBits findLabel (mkw i3 : mkw i2 : mkw i1 : r_is) (n_is+3) r_lits n_lits
803 (p:r_ptrs) (n_ptrs+1) instrs
806 = mkBits findLabel (mkw i2 : mkw i1 : r_is) (n_is+2)
807 (r_mkILit i ++ r_lits) (n_lits + intLitSz32s)
809 exciting3_I i1 i2 i3 i
810 = mkBits findLabel (mkw i3 : mkw i2 : mkw i1 : r_is) (n_is+3)
811 (r_mkILit i ++ r_lits) (n_lits + intLitSz32s)
815 = mkBits findLabel (mkw i2 : mkw i1 : r_is) (n_is+2)
816 (r_mkFLit f ++ r_lits) (n_lits + floatLitSz32s)
818 exciting3_F i1 i2 i3 f
819 = mkBits findLabel (mkw i3 : mkw i2 : mkw i1 : r_is) (n_is+3)
820 (r_mkFLit f ++ r_lits) (n_lits + floatLitSz32s)
824 = mkBits findLabel (mkw i2 : mkw i1 : r_is) (n_is+2)
825 (r_mkDLit d ++ r_lits) (n_lits + doubleLitSz32s)
827 exciting3_D i1 i2 i3 d
828 = mkBits findLabel (mkw i3 : mkw i2 : mkw i1 : r_is) (n_is+3)
829 (r_mkDLit d ++ r_lits) (n_lits + doubleLitSz32s)
832 exciting3_A i1 i2 i3 d
833 = mkBits findLabel (mkw i3 : mkw i2 : mkw i1 : r_is) (n_is+3)
834 (r_mkALit d ++ r_lits) (n_lits + addrLitSz32s)
838 -- The size in bytes of an instruction.
839 instrSizeB :: BCInstr -> Int
872 -- Sizes of Int, Float and Double literals, in units of 32-bitses
873 intLitSz32s, floatLitSz32s, doubleLitSz32s, addrLitSz32s :: Int
874 intLitSz32s = wORD_SIZE `div` 4
875 floatLitSz32s = 1 -- Assume IEEE floats
877 addrLitSz32s = intLitSz32s
879 -- Make lists of 32-bit words for literals, so that when the
880 -- words are placed in memory at increasing addresses, the
881 -- bit pattern is correct for the host's word size and endianness.
882 mkILit :: Int -> [Word32]
883 mkFLit :: Float -> [Word32]
884 mkDLit :: Double -> [Word32]
885 mkALit :: Addr -> [Word32]
889 arr <- newFloatArray ((0::Int),0)
890 writeFloatArray arr 0 f
891 w0 <- readWord32Array arr 0
897 arr <- newDoubleArray ((0::Int),0)
898 writeDoubleArray arr 0 d
899 w0 <- readWord32Array arr 0
900 w1 <- readWord32Array arr 1
907 arr <- newIntArray ((0::Int),0)
908 writeIntArray arr 0 i
909 w0 <- readWord32Array arr 0
914 arr <- newIntArray ((0::Int),0)
915 writeIntArray arr 0 i
916 w0 <- readWord32Array arr 0
917 w1 <- readWord32Array arr 1
924 arr <- newAddrArray ((0::Int),0)
925 writeAddrArray arr 0 a
926 w0 <- readWord32Array arr 0
931 arr <- newAddrArray ((0::Int),0)
932 writeAddrArray arr 0 a
933 w0 <- readWord32Array arr 0
934 w1 <- readWord32Array arr 1
940 #include "Bytecodes.h"
942 i_ARGCHECK = (bci_ARGCHECK :: Int)
943 i_PUSH_L = (bci_PUSH_L :: Int)
944 i_PUSH_LL = (bci_PUSH_LL :: Int)
945 i_PUSH_LLL = (bci_PUSH_LLL :: Int)
946 i_PUSH_G = (bci_PUSH_G :: Int)
947 i_PUSH_AS = (bci_PUSH_AS :: Int)
948 i_PUSHT_I = (bci_PUSHT_I :: Int)
949 i_PUSHT_F = (bci_PUSHT_F :: Int)
950 i_PUSHT_D = (bci_PUSHT_D :: Int)
951 i_PUSHU_I = (bci_PUSHU_I :: Int)
952 i_PUSHU_F = (bci_PUSHU_F :: Int)
953 i_PUSHU_D = (bci_PUSHU_D :: Int)
954 i_SLIDE = (bci_SLIDE :: Int)
955 i_ALLOC = (bci_ALLOC :: Int)
956 i_MKAP = (bci_MKAP :: Int)
957 i_UNPACK = (bci_UNPACK :: Int)
958 i_PACK = (bci_PACK :: Int)
959 i_LABEL = (bci_LABEL :: Int)
960 i_TESTLT_I = (bci_TESTLT_I :: Int)
961 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
962 i_TESTLT_F = (bci_TESTLT_F :: Int)
963 i_TESTEQ_F = (bci_TESTEQ_F :: Int)
964 i_TESTLT_D = (bci_TESTLT_D :: Int)
965 i_TESTEQ_D = (bci_TESTEQ_D :: Int)
966 i_TESTLT_P = (bci_TESTLT_P :: Int)
967 i_TESTEQ_P = (bci_TESTEQ_P :: Int)
968 i_CASEFAIL = (bci_CASEFAIL :: Int)
969 i_ENTER = (bci_ENTER :: Int)
970 i_RETURN = (bci_RETURN :: Int)