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,
31 dataConWrapId, isUnboxedTupleCon )
32 import TyCon ( TyCon, tyConFamilySize )
33 import Class ( Class, classTyCon )
34 import Util ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem )
35 import Var ( isTyVar )
36 import VarSet ( VarSet, varSetElems )
37 import PrimRep ( getPrimRepSize, isFollowableRep )
38 import CmdLineOpts ( DynFlags, DynFlag(..) )
39 import ErrUtils ( showPass, dumpIfSet_dyn )
40 import Unique ( mkPseudoUnique3 )
41 import FastString ( FastString(..) )
42 import Panic ( GhcException(..) )
43 import PprType ( pprType )
44 import ByteCodeInstr ( BCInstr(..), ProtoBCO(..), nameOfProtoBCO, bciStackUse )
45 import ByteCodeItbls ( ItblEnv, mkITbls )
46 import ByteCodeLink ( UnlinkedBCO, UnlinkedBCOExpr, assembleBCO,
47 ClosureEnv, HValue, linkSomeBCOs, filterNameMap,
48 iNTERP_STACK_CHECK_THRESH )
50 import List ( intersperse, sortBy )
51 import Foreign ( Ptr(..), mallocBytes )
52 import Addr ( Addr(..), addrToInt, writeCharOffAddr )
53 import CTypes ( CInt )
54 import Exception ( throwDyn )
56 import PrelBase ( Int(..) )
57 import PrelGHC ( ByteArray# )
58 import IOExts ( unsafePerformIO )
59 import PrelIOBase ( IO(..) )
63 %************************************************************************
65 \subsection{Functions visible from outside this module.}
67 %************************************************************************
71 byteCodeGen :: DynFlags
74 -> IO ([UnlinkedBCO], ItblEnv)
75 byteCodeGen dflags binds local_tycons local_classes
76 = do showPass dflags "ByteCodeGen"
77 let tycs = local_tycons ++ map classTyCon local_classes
78 itblenv <- mkITbls tycs
80 let flatBinds = concatMap getBind binds
81 getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
82 getBind (Rec binds) = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
83 final_state = runBc (BcM_State [] 0)
84 (mapBc (schemeR True) flatBinds
85 `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 True (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)
128 linkIModules :: ItblEnv -- incoming global itbl env; returned updated
129 -> ClosureEnv -- incoming global closure env; returned updated
130 -> [([UnlinkedBCO], ItblEnv)]
131 -> IO ([HValue], ItblEnv, ClosureEnv)
132 linkIModules gie gce mods
133 = do let (bcoss, ies) = unzip mods
135 final_gie = foldr plusFM gie ies
136 (final_gce, linked_bcos) <- linkSomeBCOs True final_gie gce bcos
137 return (linked_bcos, final_gie, final_gce)
140 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
141 -> IO HValue -- IO BCO# really
142 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
143 = do (aux_ce, _) <- linkSomeBCOs False ie ce aux_ul_bcos
144 (_, [root_bco]) <- linkSomeBCOs False ie aux_ce [root_ul_bco]
148 %************************************************************************
150 \subsection{Compilation schema for the bytecode generator.}
152 %************************************************************************
156 type BCInstrList = OrdList BCInstr
158 type Sequel = Int -- back off to this depth before ENTER
160 -- Maps Ids to the offset from the stack _base_ so we don't have
161 -- to mess with it after each push/pop.
162 type BCEnv = FiniteMap Id Int -- To find vars on the stack
164 ppBCEnv :: BCEnv -> SDoc
167 $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
170 pp_one (var, offset) = int offset <> colon <+> ppr var
171 cmp_snd x y = compare (snd x) (snd y)
173 -- Create a BCO and do a spot of peephole optimisation on the insns
175 mkProtoBCO nm instrs_ordlist origin
176 = ProtoBCO nm maybe_with_stack_check origin
178 -- Overestimate the stack usage (in words) of this BCO,
179 -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit
180 -- stack check. (The interpreter always does a stack check
181 -- for iNTERP_STACK_CHECK_THRESH words at the start of each
182 -- BCO anyway, so we only need to add an explicit on in the
183 -- (hopefully rare) cases when the (overestimated) stack use
184 -- exceeds iNTERP_STACK_CHECK_THRESH.
185 maybe_with_stack_check
186 | stack_overest >= 65535
187 = pprPanic "mkProtoBCO: stack use won't fit in 16 bits"
189 | stack_overest >= iNTERP_STACK_CHECK_THRESH
190 = (STKCHECK stack_overest) : peep_d
192 = peep_d -- the supposedly common case
194 stack_overest = sum (map bciStackUse peep_d)
195 + 10 {- just to be really really sure -}
198 -- Merge local pushes
199 peep_d = peep (fromOL instrs_ordlist)
201 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
202 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
203 peep (PUSH_L off1 : PUSH_L off2 : rest)
204 = PUSH_LL off1 (off2-1) : peep rest
211 -- Compile code for the right hand side of a let binding.
212 -- Park the resulting BCO in the monad. Also requires the
213 -- variable to which this value was bound, so as to give the
214 -- resulting BCO a name. Bool indicates top-levelness.
216 schemeR :: Bool -> (Id, AnnExpr Id VarSet) -> BcM ()
217 schemeR is_top (nm, rhs)
221 $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
222 $$ pprCoreExpr (deAnnotate rhs)
228 = schemeR_wrk is_top rhs nm (collect [] rhs)
231 collect xs (_, AnnNote note e)
233 collect xs (_, AnnLam x e)
234 = collect (if isTyVar x then xs else (x:xs)) e
235 collect xs not_lambda
236 = (reverse xs, not_lambda)
238 schemeR_wrk is_top original_body nm (args, body)
239 | Just dcon <- maybe_toplevel_null_con_rhs
240 = --trace ("nullary constructor! " ++ showSDocDebug (ppr nm)) (
241 emitBc (mkProtoBCO (getName nm) (toOL [PACK dcon 0, ENTER])
242 (Right original_body))
246 = let fvs = filter (not.isTyVar) (varSetElems (fst original_body))
247 all_args = reverse args ++ fvs
248 szsw_args = map taggedIdSizeW all_args
249 szw_args = sum szsw_args
250 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
251 argcheck = unitOL (ARGCHECK szw_args)
253 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
254 emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code)
255 (Right original_body))
258 maybe_toplevel_null_con_rhs
259 | is_top && null args
262 -> case isDataConId_maybe v_wrk of
264 Just dc_wrk | nm == dataConWrapId dc_wrk
272 -- Let szsw be the sizes in words of some items pushed onto the stack,
273 -- which has initial depth d'. Return the values which the stack environment
274 -- should map these items to.
275 mkStackOffsets :: Int -> [Int] -> [Int]
276 mkStackOffsets original_depth szsw
277 = map (subtract 1) (tail (scanl (+) original_depth szsw))
279 -- Compile code to apply the given expression to the remaining args
280 -- on the stack, returning a HNF.
281 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
283 -- Delegate tail-calls to schemeT.
284 schemeE d s p e@(fvs, AnnApp f a)
285 = returnBc (schemeT d s p (fvs, AnnApp f a))
286 schemeE d s p e@(fvs, AnnVar v)
287 | isFollowableRep v_rep
288 = returnBc (schemeT d s p (fvs, AnnVar v))
291 = -- returning an unboxed value. Heave it on the stack, SLIDE, and RETURN.
292 let (push, szw) = pushAtom True d p (AnnVar v)
293 in returnBc (push -- value onto stack
294 `appOL` mkSLIDE szw (d-s) -- clear to sequel
295 `snocOL` RETURN v_rep) -- go
297 v_rep = typePrimRep (idType v)
299 schemeE d s p (fvs, AnnLit literal)
300 = let (push, szw) = pushAtom True d p (AnnLit literal)
301 l_rep = literalPrimRep literal
302 in returnBc (push -- value onto stack
303 `appOL` mkSLIDE szw (d-s) -- clear to sequel
304 `snocOL` RETURN l_rep) -- go
306 schemeE d s p (fvs, AnnLet binds b)
307 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
308 AnnRec xs_n_rhss -> unzip xs_n_rhss
310 fvss = map (filter (not.isTyVar).varSetElems.fst) rhss
312 -- Sizes of tagged free vars, + 1 for the fn
313 sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
315 -- This p', d' defn is safe because all the items being pushed
316 -- are ptrs, so all have size 1. d' and p' reflect the stack
317 -- after the closures have been allocated in the heap (but not
318 -- filled in), and pointers to them parked on the stack.
319 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
322 infos = zipE4 fvss sizes xs [n, n-1 .. 1]
323 zipE = zipEqual "schemeE"
324 zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
326 -- ToDo: don't build thunks for things with no free variables
327 buildThunk dd ([], size, id, off)
328 = PUSH_G (Left (getName id))
329 `consOL` unitOL (MKAP (off+size-1) size)
330 buildThunk dd ((fv:fvs), size, id, off)
331 = case pushAtom True dd p' (AnnVar fv) of
332 (push_code, pushed_szw)
334 buildThunk (dd+pushed_szw) (fvs, size, id, off)
336 thunkCode = concatOL (map (buildThunk d') infos)
337 allocCode = toOL (map ALLOC sizes)
339 schemeE d' s p' b `thenBc` \ bodyCode ->
340 mapBc (schemeR False) (zip xs rhss) `thenBc_`
341 returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
344 schemeE d s p (fvs, AnnCase scrut bndr alts)
346 -- Top of stack is the return itbl, as usual.
347 -- underneath it is the pointer to the alt_code BCO.
348 -- When an alt is entered, it assumes the returned value is
349 -- on top of the itbl.
352 -- Env and depth in which to compile the alts, not including
353 -- any vars bound by the alts themselves
354 d' = d + ret_frame_sizeW + taggedIdSizeW bndr
355 p' = addToFM p bndr (d' - 1)
357 scrut_primrep = typePrimRep (idType bndr)
359 = case scrut_primrep of
360 CharRep -> False ; AddrRep -> False ; WordRep -> False
361 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
363 other -> pprPanic "ByteCodeGen.schemeE" (ppr other)
365 -- given an alt, return a discr and code for it.
366 codeAlt alt@(discr, binds_f, rhs)
368 = let (unpack_code, d_after_unpack, p_after_unpack)
369 = mkUnpackCode binds_f d' p'
370 in schemeE d_after_unpack s p_after_unpack rhs
371 `thenBc` \ rhs_code ->
372 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
374 = ASSERT(null binds_f)
375 schemeE d' s p' rhs `thenBc` \ rhs_code ->
376 returnBc (my_discr alt, rhs_code)
378 my_discr (DEFAULT, binds, rhs) = NoDiscr
379 my_discr (DataAlt dc, binds, rhs)
380 | isUnboxedTupleCon dc
381 = unboxedTupleException
383 = DiscrP (dataConTag dc - fIRST_TAG)
384 my_discr (LitAlt l, binds, rhs)
385 = case l of MachInt i -> DiscrI (fromInteger i)
386 MachFloat r -> DiscrF (fromRational r)
387 MachDouble r -> DiscrD (fromRational r)
388 MachChar i -> DiscrI i
389 _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
392 | not isAlgCase = Nothing
394 = case [dc | (DataAlt dc, _, _) <- alts] of
396 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
399 mapBc codeAlt alts `thenBc` \ alt_stuff ->
400 mkMultiBranch maybe_ncons alt_stuff `thenBc` \ alt_final ->
402 alt_final_ac = ARGCHECK (taggedIdSizeW bndr) `consOL` alt_final
403 alt_bco_name = getName bndr
404 alt_bco = mkProtoBCO alt_bco_name alt_final_ac (Left alts)
406 schemeE (d + ret_frame_sizeW)
407 (d + ret_frame_sizeW) p scrut `thenBc` \ scrut_code ->
409 emitBc alt_bco `thenBc_`
410 returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
413 schemeE d s p (fvs, AnnNote note body)
417 = pprPanic "ByteCodeGen.schemeE: unhandled case"
418 (pprCoreExpr (deAnnotate other))
421 -- Compile code to do a tail call. Three cases:
423 -- 1. A nullary constructor. Push its closure on the stack
424 -- and SLIDE and RETURN.
426 -- 2. Application of a non-nullary constructor, by defn saturated.
427 -- Split the args into ptrs and non-ptrs, and push the nonptrs,
428 -- then the ptrs, and then do PACK and RETURN.
430 -- 3. Otherwise, it must be a function call. Push the args
431 -- right to left, SLIDE and ENTER.
433 schemeT :: Int -- Stack depth
434 -> Sequel -- Sequel depth
435 -> BCEnv -- stack env
440 -- | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
441 -- = panic "schemeT ?!?!"
444 | is_con_call && null args_r_to_l
445 = (PUSH_G (Left (getName con)) `consOL` mkSLIDE 1 (d-s))
450 = if is_con_call && isUnboxedTupleCon con
451 then unboxedTupleException
455 -- Extract the args (R->L) and fn
456 (args_r_to_l_raw, fn) = chomp app
460 AnnApp f a -> case chomp f of (az, f) -> (snd a:az, f)
461 AnnNote n e -> chomp e
462 other -> pprPanic "schemeT"
463 (ppr (deAnnotate (panic "schemeT.chomp", other)))
465 args_r_to_l = filter (not.isTypeAtom) args_r_to_l_raw
466 isTypeAtom (AnnType _) = True
469 -- decide if this is a constructor call, and rearrange
470 -- args appropriately.
471 maybe_dcon = isDataConId_maybe fn
472 is_con_call = case maybe_dcon of Nothing -> False; Just _ -> True
473 (Just con) = maybe_dcon
479 = filter (not.isPtr) args_r_to_l ++ filter isPtr args_r_to_l
480 where isPtr = isFollowableRep . atomRep
482 -- make code to push the args and then do the SLIDE-ENTER thing
483 code = do_pushery d args_final_r_to_l
485 tag_when_push = not is_con_call
486 narg_words = sum (map (get_arg_szw . atomRep) args_r_to_l)
487 get_arg_szw = if tag_when_push then taggedSizeW else untaggedSizeW
489 do_pushery d (arg:args)
490 = let (push, arg_words) = pushAtom tag_when_push d p arg
491 in push `appOL` do_pushery (d+arg_words) args
494 Just con -> PACK con narg_words `consOL` (
495 mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
497 -> let (push, arg_words) = pushAtom True d p (AnnVar fn)
499 `appOL` mkSLIDE (narg_words+arg_words)
504 = if d == 0 then nilOL else unitOL (SLIDE n d)
506 atomRep (AnnVar v) = typePrimRep (idType v)
507 atomRep (AnnLit l) = literalPrimRep l
508 atomRep (AnnNote n b) = atomRep (snd b)
509 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
510 atomRep (AnnLam x e) | isTyVar x = atomRep (snd e)
511 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
514 -- Make code to unpack the top-of-stack constructor onto the stack,
515 -- adding tags for the unboxed bits. Takes the PrimReps of the
516 -- constructor's arguments. off_h and off_s are travelling offsets
517 -- along the constructor and the stack.
519 -- Supposing a constructor in the heap has layout
521 -- Itbl p_1 ... p_i np_1 ... np_j
523 -- then we add to the stack, shown growing down, the following:
535 -- so that in the common case (ptrs only) a single UNPACK instr can
536 -- copy all the payload of the constr onto the stack with no further ado.
538 mkUnpackCode :: [Id] -- constr args
539 -> Int -- depth before unpack
540 -> BCEnv -- env before unpack
541 -> (BCInstrList, Int, BCEnv)
542 mkUnpackCode vars d p
543 = --trace ("mkUnpackCode: " ++ showSDocDebug (ppr vars)
544 -- ++ " --> " ++ show d' ++ "\n" ++ showSDocDebug (ppBCEnv p')
546 (code_p `appOL` code_np, d', p')
550 vreps = [(var, typePrimRep (idType var)) | var <- vars]
552 -- ptrs and nonptrs, forward
553 vreps_p = filter (isFollowableRep.snd) vreps
554 vreps_np = filter (not.isFollowableRep.snd) vreps
556 -- the order in which we will augment the environment
557 vreps_env = reverse vreps_p ++ reverse vreps_np
560 vreps_env_tszsw = map (taggedSizeW.snd) vreps_env
561 p' = addListToFM p (zip (map fst vreps_env)
562 (mkStackOffsets d vreps_env_tszsw))
563 d' = d + sum vreps_env_tszsw
565 -- code to unpack the ptrs
566 ptrs_szw = sum (map (untaggedSizeW.snd) vreps_p)
567 code_p | null vreps_p = nilOL
568 | otherwise = unitOL (UNPACK ptrs_szw)
570 -- code to unpack the nonptrs
571 vreps_env_uszw = sum (map (untaggedSizeW.snd) vreps_env)
572 code_np = do_nptrs vreps_env_uszw ptrs_szw (reverse (map snd vreps_np))
573 do_nptrs off_h off_s [] = nilOL
574 do_nptrs off_h off_s (npr:nprs)
576 IntRep -> approved ; FloatRep -> approved
577 DoubleRep -> approved ; AddrRep -> approved
579 _ -> pprPanic "ByteCodeGen.mkUnpackCode" (ppr npr)
581 approved = UPK_TAG usizeW (off_h-usizeW) off_s `consOL` theRest
582 theRest = do_nptrs (off_h-usizeW) (off_s + tsizeW) nprs
583 usizeW = untaggedSizeW npr
584 tsizeW = taggedSizeW npr
587 -- Push an atom onto the stack, returning suitable code & number of
588 -- stack words used. Pushes it either tagged or untagged, since
589 -- pushAtom is used to set up the stack prior to copying into the
590 -- heap for both APs (requiring tags) and constructors (which don't).
592 -- NB this means NO GC between pushing atoms for a constructor and
593 -- copying them into the heap. It probably also means that
594 -- tail calls MUST be of the form atom{atom ... atom} since if the
595 -- expression head was allowed to be arbitrary, there could be GC
596 -- in between pushing the arg atoms and completing the head.
597 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
598 -- isn't a problem; but only if arbitrary graph construction for the
599 -- head doesn't leave this BCO, since GC might happen at the start of
600 -- each BCO (we consult doYouWantToGC there).
602 -- Blargh. JRS 001206
604 -- NB (further) that the env p must map each variable to the highest-
605 -- numbered stack slot for it. For example, if the stack has depth 4
606 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
607 -- the tag in stack[5], the stack will have depth 6, and p must map v to
608 -- 5 and not to 4. Stack locations are numbered from zero, so a depth
609 -- 6 stack has valid words 0 .. 5.
611 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
612 pushAtom tagged d p (AnnVar v)
614 | idPrimRep v == VoidRep
616 (unitOL (PUSH_TAG 0), 1)
618 | Just primop <- isPrimOpId_maybe v
620 CCallOp _ -> panic "pushAtom: byte code generator can't handle CCalls"
621 other -> (unitOL (PUSH_G (Right primop)), 1)
624 = let str = "\npushAtom " ++ showSDocDebug (ppr v)
625 ++ " :: " ++ showSDocDebug (pprType (idType v))
626 ++ ", depth = " ++ show d
627 ++ ", tagged = " ++ show tagged ++ ", env =\n" ++
628 showSDocDebug (ppBCEnv p)
629 ++ " --> words: " ++ show (snd result) ++ "\n" ++
630 showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
631 ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
633 cmp_snd x y = compare (snd x) (snd y)
634 str' = if str == str then str else str
637 = case lookupBCEnv_maybe p v of
638 Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), nwords)
639 Nothing -> ASSERT(sz_t == 1) (unitOL (PUSH_G (Left nm)), nwords)
641 nm = case isDataConId_maybe v of
645 sz_t = taggedIdSizeW v
646 sz_u = untaggedIdSizeW v
647 nwords = if tagged then sz_t else sz_u
652 pushAtom True d p (AnnLit lit)
653 = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
654 in (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
656 pushAtom False d p (AnnLit lit)
658 MachWord w -> code WordRep
659 MachInt i -> code IntRep
660 MachFloat r -> code FloatRep
661 MachDouble r -> code DoubleRep
662 MachChar c -> code CharRep
663 MachStr s -> pushStr s
666 = let size_host_words = untaggedSizeW rep
667 in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
670 = let mallocvilleAddr
675 -- sigh, a string in the heap is no good to us.
676 -- We need a static C pointer, since the type of
677 -- a string literal is Addr#. So, copy the string
678 -- into C land and introduce a memory leak
681 -- CAREFUL! Chars are 32 bits in ghc 4.09+
683 do (Ptr a#) <- mallocBytes (n+1)
684 strncpy (Ptr a#) ba (fromIntegral n)
685 writeCharOffAddr (A# a#) n '\0'
688 _ -> panic "StgInterp.lit2expr: unhandled string constant type"
691 = MachInt (toInteger (addrToInt mallocvilleAddr))
693 -- Get the addr on the stack, untaggedly
694 (unitOL (PUSH_UBX addrLit 1), 1)
700 pushAtom tagged d p (AnnApp f (_, AnnType _))
701 = pushAtom tagged d p (snd f)
703 pushAtom tagged d p (AnnNote note e)
704 = pushAtom tagged d p (snd e)
706 pushAtom tagged d p (AnnLam x e)
708 = pushAtom tagged d p (snd e)
710 pushAtom tagged d p other
711 = pprPanic "ByteCodeGen.pushAtom"
712 (pprCoreExpr (deAnnotate (undefined, other)))
714 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
717 -- Given a bunch of alts code and their discrs, do the donkey work
718 -- of making a multiway branch using a switch tree.
719 -- What a load of hassle!
720 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
721 -- a hint; generates better code
722 -- Nothing is always safe
723 -> [(Discr, BCInstrList)]
725 mkMultiBranch maybe_ncons raw_ways
726 = let d_way = filter (isNoDiscr.fst) raw_ways
727 notd_ways = naturalMergeSortLe
728 (\w1 w2 -> leAlt (fst w1) (fst w2))
729 (filter (not.isNoDiscr.fst) raw_ways)
731 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
732 mkTree [] range_lo range_hi = returnBc the_default
734 mkTree [val] range_lo range_hi
735 | range_lo `eqAlt` range_hi
738 = getLabelBc `thenBc` \ label_neq ->
739 returnBc (mkTestEQ (fst val) label_neq
741 `appOL` unitOL (LABEL label_neq)
742 `appOL` the_default))
744 mkTree vals range_lo range_hi
745 = let n = length vals `div` 2
746 vals_lo = take n vals
747 vals_hi = drop n vals
748 v_mid = fst (head vals_hi)
750 getLabelBc `thenBc` \ label_geq ->
751 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
752 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
753 returnBc (mkTestLT v_mid label_geq
755 `appOL` unitOL (LABEL label_geq)
759 = case d_way of [] -> unitOL CASEFAIL
762 -- None of these will be needed if there are no non-default alts
763 (mkTestLT, mkTestEQ, init_lo, init_hi)
765 = panic "mkMultiBranch: awesome foursome"
767 = case fst (head notd_ways) of {
768 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
769 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
772 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
773 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
776 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
777 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
780 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
781 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
786 (algMinBound, algMaxBound)
787 = case maybe_ncons of
789 Nothing -> (minBound, maxBound)
791 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
792 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
793 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
794 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
795 NoDiscr `eqAlt` NoDiscr = True
798 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
799 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
800 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
801 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
802 NoDiscr `leAlt` NoDiscr = True
805 isNoDiscr NoDiscr = True
808 dec (DiscrI i) = DiscrI (i-1)
809 dec (DiscrP i) = DiscrP (i-1)
810 dec other = other -- not really right, but if you
811 -- do cases on floating values, you'll get what you deserve
813 -- same snotty comment applies to the following
821 mkTree notd_ways init_lo init_hi
825 %************************************************************************
827 \subsection{Supporting junk for the compilation schemes}
829 %************************************************************************
833 -- Describes case alts
841 instance Outputable Discr where
842 ppr (DiscrI i) = int i
843 ppr (DiscrF f) = text (show f)
844 ppr (DiscrD d) = text (show d)
845 ppr (DiscrP i) = int i
846 ppr NoDiscr = text "DEF"
849 -- Find things in the BCEnv (the what's-on-the-stack-env)
850 -- See comment preceding pushAtom for precise meaning of env contents
851 --lookupBCEnv :: BCEnv -> Id -> Int
853 -- = case lookupFM env nm of
854 -- Nothing -> pprPanic "lookupBCEnv"
855 -- (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
858 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
859 lookupBCEnv_maybe = lookupFM
862 -- When I push one of these on the stack, how much does Sp move by?
863 taggedSizeW :: PrimRep -> Int
865 | isFollowableRep pr = 1
866 | otherwise = 1{-the tag-} + getPrimRepSize pr
869 -- The plain size of something, without tag.
870 untaggedSizeW :: PrimRep -> Int
872 | isFollowableRep pr = 1
873 | otherwise = getPrimRepSize pr
876 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
877 taggedIdSizeW = taggedSizeW . typePrimRep . idType
878 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
880 unboxedTupleException :: a
881 unboxedTupleException
882 = throwDyn (Panic "bytecode generator can't handle unboxed tuples")
886 %************************************************************************
888 \subsection{The bytecode generator's monad}
890 %************************************************************************
894 = BcM_State { bcos :: [ProtoBCO Name], -- accumulates completed BCOs
895 nextlabel :: Int } -- for generating local labels
897 type BcM result = BcM_State -> (result, BcM_State)
899 runBc :: BcM_State -> BcM () -> BcM_State
900 runBc init_st m = case m init_st of { (r,st) -> st }
902 thenBc :: BcM a -> (a -> BcM b) -> BcM b
904 = case expr st of { (result, st') -> cont result st' }
906 thenBc_ :: BcM a -> BcM b -> BcM b
908 = case expr st of { (result, st') -> cont st' }
910 returnBc :: a -> BcM a
911 returnBc result st = (result, st)
913 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
914 mapBc f [] = returnBc []
916 = f x `thenBc` \ r ->
917 mapBc f xs `thenBc` \ rs ->
920 emitBc :: ProtoBCO Name -> BcM ()
922 = ((), st{bcos = bco : bcos st})
924 getLabelBc :: BcM Int
926 = (nextlabel st, st{nextlabel = 1 + nextlabel st})