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, mkSysLocalName )
17 import Id ( Id, idType, isDataConId_maybe, mkVanillaId,
18 isPrimOpId_maybe, idPrimRep )
19 import OrdList ( OrdList, consOL, snocOL, appOL, unitOL,
20 nilOL, toOL, concatOL, fromOL )
21 import FiniteMap ( FiniteMap, addListToFM, listToFM,
22 addToFM, lookupFM, fmToList, plusFM )
24 import PprCore ( pprCoreExpr )
25 import Literal ( Literal(..), literalPrimRep )
26 import PrimRep ( PrimRep(..) )
27 import PrimOp ( PrimOp(..) )
28 import CoreFVs ( freeVars )
29 import Type ( typePrimRep )
30 import DataCon ( dataConTag, fIRST_TAG, dataConTyCon, dataConWrapId )
31 import TyCon ( TyCon, tyConFamilySize )
32 import Class ( Class, classTyCon )
33 import Util ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem )
34 import Var ( isTyVar )
35 import VarSet ( VarSet, varSetElems )
36 import PrimRep ( getPrimRepSize, isFollowableRep )
37 import CmdLineOpts ( DynFlags, DynFlag(..) )
38 import ErrUtils ( showPass, dumpIfSet_dyn )
39 import Unique ( mkPseudoUnique3 )
40 import FastString ( FastString(..) )
41 import PprType ( pprType )
42 import ByteCodeInstr ( BCInstr(..), ProtoBCO(..), nameOfProtoBCO )
43 import ByteCodeItbls ( ItblEnv, mkITbls )
44 import ByteCodeLink ( UnlinkedBCO, UnlinkedBCOExpr, assembleBCO,
45 ClosureEnv, HValue, linkSomeBCOs, filterNameMap )
47 import List ( intersperse, sortBy )
48 import Foreign ( Ptr(..), mallocBytes )
49 import Addr ( Addr(..), addrToInt, writeCharOffAddr )
50 import CTypes ( CInt )
52 import PrelBase ( Int(..) )
53 import PrelGHC ( ByteArray# )
54 import IOExts ( unsafePerformIO )
55 import PrelIOBase ( IO(..) )
59 %************************************************************************
61 \subsection{Functions visible from outside this module.}
63 %************************************************************************
67 byteCodeGen :: DynFlags
70 -> IO ([UnlinkedBCO], ItblEnv)
71 byteCodeGen dflags binds local_tycons local_classes
72 = do showPass dflags "ByteCodeGen"
73 let tycs = local_tycons ++ map classTyCon local_classes
74 itblenv <- mkITbls tycs
76 let flatBinds = concatMap getBind binds
77 getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
78 getBind (Rec binds) = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
79 final_state = runBc (BcM_State [] 0)
80 (mapBc (schemeR True) flatBinds
81 `thenBc_` returnBc ())
82 (BcM_State proto_bcos final_ctr) = final_state
84 dumpIfSet_dyn dflags Opt_D_dump_BCOs
85 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
87 bcos <- mapM assembleBCO proto_bcos
89 return (bcos, itblenv)
92 -- Returns: (the root BCO for this expression,
93 -- a list of auxilary BCOs resulting from compiling closures)
94 coreExprToBCOs :: DynFlags
97 coreExprToBCOs dflags expr
98 = do showPass dflags "ByteCodeGen"
100 -- create a totally bogus name for the top-level BCO; this
101 -- should be harmless, since it's never used for anything
102 let invented_name = mkSysLocalName (mkPseudoUnique3 0) SLIT("Expr-Top-Level")
103 let invented_id = mkVanillaId invented_name (panic "invented_id's type")
105 let (BcM_State all_proto_bcos final_ctr)
106 = runBc (BcM_State [] 0)
107 (schemeR True (invented_id, freeVars expr))
108 dumpIfSet_dyn dflags Opt_D_dump_BCOs
109 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr all_proto_bcos)))
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)
124 linkIModules :: ItblEnv -- incoming global itbl env; returned updated
125 -> ClosureEnv -- incoming global closure env; returned updated
126 -> [([UnlinkedBCO], ItblEnv)]
127 -> IO ([HValue], ItblEnv, ClosureEnv)
128 linkIModules gie gce mods
129 = do let (bcoss, ies) = unzip mods
131 final_gie = foldr plusFM gie ies
132 (final_gce, linked_bcos) <- linkSomeBCOs final_gie gce bcos
133 return (linked_bcos, final_gie, final_gce)
136 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
137 -> IO HValue -- IO BCO# really
138 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
139 = do (aux_ce, _) <- linkSomeBCOs ie ce aux_ul_bcos
140 (_, [root_bco]) <- linkSomeBCOs ie aux_ce [root_ul_bco]
144 %************************************************************************
146 \subsection{Compilation schema for the bytecode generator.}
148 %************************************************************************
152 type BCInstrList = OrdList BCInstr
154 type Sequel = Int -- back off to this depth before ENTER
156 -- Maps Ids to the offset from the stack _base_ so we don't have
157 -- to mess with it after each push/pop.
158 type BCEnv = FiniteMap Id Int -- To find vars on the stack
160 ppBCEnv :: BCEnv -> SDoc
163 $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
166 pp_one (var, offset) = int offset <> colon <+> ppr var
167 cmp_snd x y = compare (snd x) (snd y)
169 -- Create a BCO and do a spot of peephole optimisation on the insns
171 mkProtoBCO nm instrs_ordlist origin
172 = ProtoBCO nm (id {-peep-} (fromOL instrs_ordlist)) origin
174 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
175 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
176 peep (PUSH_L off1 : PUSH_L off2 : rest)
177 = PUSH_LL off1 off2 : peep rest
184 -- Compile code for the right hand side of a let binding.
185 -- Park the resulting BCO in the monad. Also requires the
186 -- variable to which this value was bound, so as to give the
187 -- resulting BCO a name. Bool indicates top-levelness.
189 schemeR :: Bool -> (Id, AnnExpr Id VarSet) -> BcM ()
190 schemeR is_top (nm, rhs)
194 $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
195 $$ pprCoreExpr (deAnnotate rhs)
201 = schemeR_wrk is_top rhs nm (collect [] rhs)
204 collect xs (_, AnnNote note e)
206 collect xs (_, AnnLam x e)
207 = collect (if isTyVar x then xs else (x:xs)) e
208 collect xs not_lambda
209 = (reverse xs, not_lambda)
211 schemeR_wrk is_top original_body nm (args, body)
212 | Just dcon <- maybe_toplevel_null_con_rhs
213 = --trace ("nullary constructor! " ++ showSDocDebug (ppr nm)) (
214 emitBc (mkProtoBCO (getName nm) (toOL [PACK dcon 0, ENTER])
215 (Right original_body))
219 = let fvs = filter (not.isTyVar) (varSetElems (fst original_body))
220 all_args = reverse args ++ fvs
221 szsw_args = map taggedIdSizeW all_args
222 szw_args = sum szsw_args
223 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
224 argcheck = unitOL (ARGCHECK szw_args)
226 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
227 emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code)
228 (Right original_body))
231 maybe_toplevel_null_con_rhs
232 | is_top && null args
235 -> case isDataConId_maybe v_wrk of
237 Just dc_wrk | nm == dataConWrapId dc_wrk
245 -- Let szsw be the sizes in words of some items pushed onto the stack,
246 -- which has initial depth d'. Return the values which the stack environment
247 -- should map these items to.
248 mkStackOffsets :: Int -> [Int] -> [Int]
249 mkStackOffsets original_depth szsw
250 = map (subtract 1) (tail (scanl (+) original_depth szsw))
252 -- Compile code to apply the given expression to the remaining args
253 -- on the stack, returning a HNF.
254 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
256 -- Delegate tail-calls to schemeT.
257 schemeE d s p e@(fvs, AnnApp f a)
258 = returnBc (schemeT d s p (fvs, AnnApp f a))
259 schemeE d s p e@(fvs, AnnVar v)
260 | isFollowableRep v_rep
261 = returnBc (schemeT d s p (fvs, AnnVar v))
264 = -- returning an unboxed value. Heave it on the stack, SLIDE, and RETURN.
265 let (push, szw) = pushAtom True d p (AnnVar v)
266 in returnBc (push -- value onto stack
267 `appOL` mkSLIDE szw (d-s) -- clear to sequel
268 `snocOL` RETURN v_rep) -- go
270 v_rep = typePrimRep (idType v)
272 schemeE d s p (fvs, AnnLit literal)
273 = let (push, szw) = pushAtom True d p (AnnLit literal)
274 l_rep = literalPrimRep literal
275 in returnBc (push -- value onto stack
276 `appOL` mkSLIDE szw (d-s) -- clear to sequel
277 `snocOL` RETURN l_rep) -- go
279 schemeE d s p (fvs, AnnLet binds b)
280 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
281 AnnRec xs_n_rhss -> unzip xs_n_rhss
283 fvss = map (filter (not.isTyVar).varSetElems.fst) rhss
285 -- Sizes of tagged free vars, + 1 for the fn
286 sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
288 -- This p', d' defn is safe because all the items being pushed
289 -- are ptrs, so all have size 1. d' and p' reflect the stack
290 -- after the closures have been allocated in the heap (but not
291 -- filled in), and pointers to them parked on the stack.
292 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
295 infos = zipE4 fvss sizes xs [n, n-1 .. 1]
296 zipE = zipEqual "schemeE"
297 zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
299 -- ToDo: don't build thunks for things with no free variables
300 buildThunk dd ([], size, id, off)
301 = PUSH_G (Left (getName id))
302 `consOL` unitOL (MKAP (off+size-1) size)
303 buildThunk dd ((fv:fvs), size, id, off)
304 = case pushAtom True dd p' (AnnVar fv) of
305 (push_code, pushed_szw)
307 buildThunk (dd+pushed_szw) (fvs, size, id, off)
309 thunkCode = concatOL (map (buildThunk d') infos)
310 allocCode = toOL (map ALLOC sizes)
312 schemeE d' s p' b `thenBc` \ bodyCode ->
313 mapBc (schemeR False) (zip xs rhss) `thenBc_`
314 returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
317 schemeE d s p (fvs, AnnCase scrut bndr alts)
319 -- Top of stack is the return itbl, as usual.
320 -- underneath it is the pointer to the alt_code BCO.
321 -- When an alt is entered, it assumes the returned value is
322 -- on top of the itbl.
325 -- Env and depth in which to compile the alts, not including
326 -- any vars bound by the alts themselves
327 d' = d + ret_frame_sizeW + taggedIdSizeW bndr
328 p' = addToFM p bndr (d' - 1)
330 scrut_primrep = typePrimRep (idType bndr)
332 = case scrut_primrep of
333 CharRep -> False ; AddrRep -> False ; WordRep -> False
334 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
336 other -> pprPanic "ByteCodeGen.schemeE" (ppr other)
338 -- given an alt, return a discr and code for it.
339 codeAlt alt@(discr, binds_f, rhs)
341 = let (unpack_code, d_after_unpack, p_after_unpack)
342 = mkUnpackCode binds_f d' p'
343 in schemeE d_after_unpack s p_after_unpack rhs
344 `thenBc` \ rhs_code ->
345 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
347 = ASSERT(null binds_f)
348 schemeE d' s p' rhs `thenBc` \ rhs_code ->
349 returnBc (my_discr alt, rhs_code)
351 my_discr (DEFAULT, binds, rhs) = NoDiscr
352 my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc - fIRST_TAG)
353 my_discr (LitAlt l, binds, rhs)
354 = case l of MachInt i -> DiscrI (fromInteger i)
355 MachFloat r -> DiscrF (fromRational r)
356 MachDouble r -> DiscrD (fromRational r)
357 MachChar i -> DiscrI i
358 _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
361 | not isAlgCase = Nothing
363 = case [dc | (DataAlt dc, _, _) <- alts] of
365 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
368 mapBc codeAlt alts `thenBc` \ alt_stuff ->
369 mkMultiBranch maybe_ncons alt_stuff `thenBc` \ alt_final ->
371 alt_final_ac = ARGCHECK (taggedIdSizeW bndr) `consOL` alt_final
372 alt_bco_name = getName bndr
373 alt_bco = mkProtoBCO alt_bco_name alt_final_ac (Left alts)
375 schemeE (d + ret_frame_sizeW)
376 (d + ret_frame_sizeW) p scrut `thenBc` \ scrut_code ->
378 emitBc alt_bco `thenBc_`
379 returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
382 schemeE d s p (fvs, AnnNote note body)
386 = pprPanic "ByteCodeGen.schemeE: unhandled case"
387 (pprCoreExpr (deAnnotate other))
390 -- Compile code to do a tail call. Three cases:
392 -- 1. A nullary constructor. Push its closure on the stack
393 -- and SLIDE and RETURN.
395 -- 2. Application of a non-nullary constructor, by defn saturated.
396 -- Split the args into ptrs and non-ptrs, and push the nonptrs,
397 -- then the ptrs, and then do PACK and RETURN.
399 -- 3. Otherwise, it must be a function call. Push the args
400 -- right to left, SLIDE and ENTER.
402 schemeT :: Int -- Stack depth
403 -> Sequel -- Sequel depth
404 -> BCEnv -- stack env
409 -- | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
410 -- = panic "schemeT ?!?!"
413 | is_con_call && null args_r_to_l
414 = (PUSH_G (Left (getName con)) `consOL` mkSLIDE 1 (d-s))
422 -- Extract the args (R->L) and fn
423 (args_r_to_l_raw, fn) = chomp app
427 AnnApp f a -> case chomp f of (az, f) -> (snd a:az, f)
428 AnnNote n e -> chomp e
429 other -> pprPanic "schemeT"
430 (ppr (deAnnotate (panic "schemeT.chomp", other)))
432 args_r_to_l = filter (not.isTypeAtom) args_r_to_l_raw
433 isTypeAtom (AnnType _) = True
436 -- decide if this is a constructor call, and rearrange
437 -- args appropriately.
438 maybe_dcon = isDataConId_maybe fn
439 is_con_call = case maybe_dcon of Nothing -> False; Just _ -> True
440 (Just con) = maybe_dcon
446 = filter (not.isPtr) args_r_to_l ++ filter isPtr args_r_to_l
447 where isPtr = isFollowableRep . atomRep
449 -- make code to push the args and then do the SLIDE-ENTER thing
450 code = do_pushery d args_final_r_to_l
452 tag_when_push = not is_con_call
453 narg_words = sum (map (get_arg_szw . atomRep) args_r_to_l)
454 get_arg_szw = if tag_when_push then taggedSizeW else untaggedSizeW
456 do_pushery d (arg:args)
457 = let (push, arg_words) = pushAtom tag_when_push d p arg
458 in push `appOL` do_pushery (d+arg_words) args
461 Just con -> PACK con narg_words `consOL` (
462 mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
464 -> let (push, arg_words) = pushAtom True d p (AnnVar fn)
466 `appOL` mkSLIDE (narg_words+arg_words)
471 = if d == 0 then nilOL else unitOL (SLIDE n d)
473 atomRep (AnnVar v) = typePrimRep (idType v)
474 atomRep (AnnLit l) = literalPrimRep l
475 atomRep (AnnNote n b) = atomRep (snd b)
476 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
477 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
480 -- Make code to unpack the top-of-stack constructor onto the stack,
481 -- adding tags for the unboxed bits. Takes the PrimReps of the
482 -- constructor's arguments. off_h and off_s are travelling offsets
483 -- along the constructor and the stack.
485 -- Supposing a constructor in the heap has layout
487 -- Itbl p_1 ... p_i np_1 ... np_j
489 -- then we add to the stack, shown growing down, the following:
501 -- so that in the common case (ptrs only) a single UNPACK instr can
502 -- copy all the payload of the constr onto the stack with no further ado.
504 mkUnpackCode :: [Id] -- constr args
505 -> Int -- depth before unpack
506 -> BCEnv -- env before unpack
507 -> (BCInstrList, Int, BCEnv)
508 mkUnpackCode vars d p
509 = --trace ("mkUnpackCode: " ++ showSDocDebug (ppr vars)
510 -- ++ " --> " ++ show d' ++ "\n" ++ showSDocDebug (ppBCEnv p')
512 (code_p `appOL` code_np, d', p')
516 vreps = [(var, typePrimRep (idType var)) | var <- vars]
518 -- ptrs and nonptrs, forward
519 vreps_p = filter (isFollowableRep.snd) vreps
520 vreps_np = filter (not.isFollowableRep.snd) vreps
522 -- the order in which we will augment the environment
523 vreps_env = reverse vreps_p ++ reverse vreps_np
526 vreps_env_tszsw = map (taggedSizeW.snd) vreps_env
527 p' = addListToFM p (zip (map fst vreps_env)
528 (mkStackOffsets d vreps_env_tszsw))
529 d' = d + sum vreps_env_tszsw
531 -- code to unpack the ptrs
532 ptrs_szw = sum (map (untaggedSizeW.snd) vreps_p)
533 code_p | null vreps_p = nilOL
534 | otherwise = unitOL (UNPACK ptrs_szw)
536 -- code to unpack the nonptrs
537 vreps_env_uszw = sum (map (untaggedSizeW.snd) vreps_env)
538 code_np = do_nptrs vreps_env_uszw ptrs_szw (reverse (map snd vreps_np))
539 do_nptrs off_h off_s [] = nilOL
540 do_nptrs off_h off_s (npr:nprs)
542 IntRep -> approved ; FloatRep -> approved
543 DoubleRep -> approved ; AddrRep -> approved
545 _ -> pprPanic "ByteCodeGen.mkUnpackCode" (ppr npr)
547 approved = UPK_TAG usizeW (off_h-usizeW) off_s `consOL` theRest
548 theRest = do_nptrs (off_h-usizeW) (off_s + tsizeW) nprs
549 usizeW = untaggedSizeW npr
550 tsizeW = taggedSizeW npr
553 -- Push an atom onto the stack, returning suitable code & number of
554 -- stack words used. Pushes it either tagged or untagged, since
555 -- pushAtom is used to set up the stack prior to copying into the
556 -- heap for both APs (requiring tags) and constructors (which don't).
558 -- NB this means NO GC between pushing atoms for a constructor and
559 -- copying them into the heap. It probably also means that
560 -- tail calls MUST be of the form atom{atom ... atom} since if the
561 -- expression head was allowed to be arbitrary, there could be GC
562 -- in between pushing the arg atoms and completing the head.
563 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
564 -- isn't a problem; but only if arbitrary graph construction for the
565 -- head doesn't leave this BCO, since GC might happen at the start of
566 -- each BCO (we consult doYouWantToGC there).
568 -- Blargh. JRS 001206
570 -- NB (further) that the env p must map each variable to the highest-
571 -- numbered stack slot for it. For example, if the stack has depth 4
572 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
573 -- the tag in stack[5], the stack will have depth 6, and p must map v to
574 -- 5 and not to 4. Stack locations are numbered from zero, so a depth
575 -- 6 stack has valid words 0 .. 5.
577 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
578 pushAtom tagged d p (AnnVar v)
580 | idPrimRep v == VoidRep
582 (unitOL (PUSH_TAG 0), 1)
584 | Just primop <- isPrimOpId_maybe v
586 CCallOp _ -> panic "pushAtom: byte code generator can't handle CCalls"
587 other -> (unitOL (PUSH_G (Right primop)), 1)
590 = let str = "\npushAtom " ++ showSDocDebug (ppr v)
591 ++ " :: " ++ showSDocDebug (pprType (idType v))
592 ++ ", depth = " ++ show d
593 ++ ", tagged = " ++ show tagged ++ ", env =\n" ++
594 showSDocDebug (ppBCEnv p)
595 ++ " --> words: " ++ show (snd result) ++ "\n" ++
596 showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
597 ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
599 cmp_snd x y = compare (snd x) (snd y)
600 str' = if str == str then str else str
603 = case lookupBCEnv_maybe p v of
604 Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), nwords)
605 Nothing -> ASSERT(sz_t == 1) (unitOL (PUSH_G (Left nm)), nwords)
607 nm = case isDataConId_maybe v of
611 sz_t = taggedIdSizeW v
612 sz_u = untaggedIdSizeW v
613 nwords = if tagged then sz_t else sz_u
618 pushAtom True d p (AnnLit lit)
619 = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
620 in (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
622 pushAtom False d p (AnnLit lit)
624 MachWord w -> code WordRep
625 MachInt i -> code IntRep
626 MachFloat r -> code FloatRep
627 MachDouble r -> code DoubleRep
628 MachChar c -> code CharRep
629 MachStr s -> pushStr s
632 = let size_host_words = untaggedSizeW rep
633 in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
636 = let mallocvilleAddr
641 -- sigh, a string in the heap is no good to us.
642 -- We need a static C pointer, since the type of
643 -- a string literal is Addr#. So, copy the string
644 -- into C land and introduce a memory leak
647 -- CAREFUL! Chars are 32 bits in ghc 4.09+
649 do (Ptr a#) <- mallocBytes (n+1)
650 strncpy (Ptr a#) ba (fromIntegral n)
651 writeCharOffAddr (A# a#) n '\0'
654 _ -> panic "StgInterp.lit2expr: unhandled string constant type"
657 = MachInt (toInteger (addrToInt mallocvilleAddr))
659 -- Get the addr on the stack, untaggedly
660 (unitOL (PUSH_UBX addrLit 1), 1)
666 pushAtom tagged d p (AnnApp f (_, AnnType _))
667 = pushAtom tagged d p (snd f)
669 pushAtom tagged d p (AnnNote note e)
670 = pushAtom tagged d p (snd e)
672 pushAtom tagged d p other
673 = pprPanic "ByteCodeGen.pushAtom"
674 (pprCoreExpr (deAnnotate (undefined, other)))
676 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
679 -- Given a bunch of alts code and their discrs, do the donkey work
680 -- of making a multiway branch using a switch tree.
681 -- What a load of hassle!
682 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
683 -- a hint; generates better code
684 -- Nothing is always safe
685 -> [(Discr, BCInstrList)]
687 mkMultiBranch maybe_ncons raw_ways
688 = let d_way = filter (isNoDiscr.fst) raw_ways
689 notd_ways = naturalMergeSortLe
690 (\w1 w2 -> leAlt (fst w1) (fst w2))
691 (filter (not.isNoDiscr.fst) raw_ways)
693 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
694 mkTree [] range_lo range_hi = returnBc the_default
696 mkTree [val] range_lo range_hi
697 | range_lo `eqAlt` range_hi
700 = getLabelBc `thenBc` \ label_neq ->
701 returnBc (mkTestEQ (fst val) label_neq
703 `appOL` unitOL (LABEL label_neq)
704 `appOL` the_default))
706 mkTree vals range_lo range_hi
707 = let n = length vals `div` 2
708 vals_lo = take n vals
709 vals_hi = drop n vals
710 v_mid = fst (head vals_hi)
712 getLabelBc `thenBc` \ label_geq ->
713 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
714 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
715 returnBc (mkTestLT v_mid label_geq
717 `appOL` unitOL (LABEL label_geq)
721 = case d_way of [] -> unitOL CASEFAIL
724 -- None of these will be needed if there are no non-default alts
725 (mkTestLT, mkTestEQ, init_lo, init_hi)
727 = panic "mkMultiBranch: awesome foursome"
729 = case fst (head notd_ways) of {
730 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
731 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
734 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
735 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
738 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
739 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
742 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
743 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
748 (algMinBound, algMaxBound)
749 = case maybe_ncons of
751 Nothing -> (minBound, maxBound)
753 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
754 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
755 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
756 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
757 NoDiscr `eqAlt` NoDiscr = True
760 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
761 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
762 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
763 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
764 NoDiscr `leAlt` NoDiscr = True
767 isNoDiscr NoDiscr = True
770 dec (DiscrI i) = DiscrI (i-1)
771 dec (DiscrP i) = DiscrP (i-1)
772 dec other = other -- not really right, but if you
773 -- do cases on floating values, you'll get what you deserve
775 -- same snotty comment applies to the following
783 mkTree notd_ways init_lo init_hi
787 %************************************************************************
789 \subsection{Supporting junk for the compilation schemes}
791 %************************************************************************
795 -- Describes case alts
803 instance Outputable Discr where
804 ppr (DiscrI i) = int i
805 ppr (DiscrF f) = text (show f)
806 ppr (DiscrD d) = text (show d)
807 ppr (DiscrP i) = int i
808 ppr NoDiscr = text "DEF"
811 -- Find things in the BCEnv (the what's-on-the-stack-env)
812 -- See comment preceding pushAtom for precise meaning of env contents
813 --lookupBCEnv :: BCEnv -> Id -> Int
815 -- = case lookupFM env nm of
816 -- Nothing -> pprPanic "lookupBCEnv"
817 -- (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
820 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
821 lookupBCEnv_maybe = lookupFM
824 -- When I push one of these on the stack, how much does Sp move by?
825 taggedSizeW :: PrimRep -> Int
827 | isFollowableRep pr = 1
828 | otherwise = 1{-the tag-} + getPrimRepSize pr
831 -- The plain size of something, without tag.
832 untaggedSizeW :: PrimRep -> Int
834 | isFollowableRep pr = 1
835 | otherwise = getPrimRepSize pr
838 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
839 taggedIdSizeW = taggedSizeW . typePrimRep . idType
840 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
844 %************************************************************************
846 \subsection{The bytecode generator's monad}
848 %************************************************************************
852 = BcM_State { bcos :: [ProtoBCO Name], -- accumulates completed BCOs
853 nextlabel :: Int } -- for generating local labels
855 type BcM result = BcM_State -> (result, BcM_State)
857 runBc :: BcM_State -> BcM () -> BcM_State
858 runBc init_st m = case m init_st of { (r,st) -> st }
860 thenBc :: BcM a -> (a -> BcM b) -> BcM b
862 = case expr st of { (result, st') -> cont result st' }
864 thenBc_ :: BcM a -> BcM b -> BcM b
866 = case expr st of { (result, st') -> cont st' }
868 returnBc :: a -> BcM a
869 returnBc result st = (result, st)
871 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
872 mapBc f [] = returnBc []
874 = f x `thenBc` \ r ->
875 mapBc f xs `thenBc` \ rs ->
878 emitBc :: ProtoBCO Name -> BcM ()
880 = ((), st{bcos = bco : bcos st})
882 getLabelBc :: BcM Int
884 = (nextlabel st, st{nextlabel = 1 + nextlabel st})