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
12 #include "HsVersions.h"
15 import Name ( Name, getName, mkSysLocalName )
16 import Id ( Id, idType, isDataConId_maybe, mkVanillaId,
17 isPrimOpId_maybe, idPrimRep )
18 import OrdList ( OrdList, consOL, snocOL, appOL, unitOL,
19 nilOL, toOL, concatOL, fromOL )
20 import FiniteMap ( FiniteMap, addListToFM, listToFM,
21 addToFM, lookupFM, fmToList, plusFM )
23 import PprCore ( pprCoreExpr )
24 import Literal ( Literal(..), literalPrimRep )
25 import PrimRep ( PrimRep(..) )
26 import PrimOp ( PrimOp(..) )
27 import CoreFVs ( freeVars )
28 import Type ( typePrimRep )
29 import DataCon ( dataConTag, fIRST_TAG, dataConTyCon,
30 dataConWrapId, isUnboxedTupleCon )
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 Panic ( GhcException(..) )
42 import PprType ( pprType )
43 import ByteCodeInstr ( BCInstr(..), ProtoBCO(..), nameOfProtoBCO, bciStackUse )
44 import ByteCodeItbls ( ItblEnv, mkITbls )
45 import ByteCodeLink ( UnlinkedBCO, UnlinkedBCOExpr, assembleBCO,
46 ClosureEnv, HValue, filterNameMap,
47 iNTERP_STACK_CHECK_THRESH )
49 import List ( intersperse, sortBy )
50 import Foreign ( Ptr(..), mallocBytes )
51 import Addr ( Addr(..), addrToInt, writeCharOffAddr )
52 import CTypes ( CInt )
53 import Exception ( throwDyn )
55 import PrelBase ( Int(..) )
56 import PrelGHC ( ByteArray# )
57 import IOExts ( unsafePerformIO )
58 import PrelIOBase ( IO(..) )
62 %************************************************************************
64 \subsection{Functions visible from outside this module.}
66 %************************************************************************
70 byteCodeGen :: DynFlags
73 -> IO ([UnlinkedBCO], ItblEnv)
74 byteCodeGen dflags binds local_tycons local_classes
75 = do showPass dflags "ByteCodeGen"
76 let tycs = local_tycons ++ map classTyCon local_classes
77 itblenv <- mkITbls tycs
79 let flatBinds = concatMap getBind binds
80 getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
81 getBind (Rec binds) = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
82 final_state = runBc (BcM_State [] 0)
83 (mapBc (schemeR True) flatBinds
84 `thenBc_` returnBc ())
85 (BcM_State proto_bcos final_ctr) = final_state
87 dumpIfSet_dyn dflags Opt_D_dump_BCOs
88 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
90 bcos <- mapM assembleBCO proto_bcos
92 return (bcos, itblenv)
95 -- Returns: (the root BCO for this expression,
96 -- a list of auxilary BCOs resulting from compiling closures)
97 coreExprToBCOs :: DynFlags
100 coreExprToBCOs dflags expr
101 = do showPass dflags "ByteCodeGen"
103 -- create a totally bogus name for the top-level BCO; this
104 -- should be harmless, since it's never used for anything
105 let invented_id = mkSysLocal SLIT("Expr-Top-Level") (mkPseudoUnique3 0)
106 (panic "invented_id's type")
107 let invented_name = idName invented_id
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)
127 %************************************************************************
129 \subsection{Compilation schema for the bytecode generator.}
131 %************************************************************************
135 type BCInstrList = OrdList BCInstr
137 type Sequel = Int -- back off to this depth before ENTER
139 -- Maps Ids to the offset from the stack _base_ so we don't have
140 -- to mess with it after each push/pop.
141 type BCEnv = FiniteMap Id Int -- To find vars on the stack
143 ppBCEnv :: BCEnv -> SDoc
146 $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
149 pp_one (var, offset) = int offset <> colon <+> ppr var
150 cmp_snd x y = compare (snd x) (snd y)
152 -- Create a BCO and do a spot of peephole optimisation on the insns
154 mkProtoBCO nm instrs_ordlist origin
155 = ProtoBCO nm maybe_with_stack_check origin
157 -- Overestimate the stack usage (in words) of this BCO,
158 -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit
159 -- stack check. (The interpreter always does a stack check
160 -- for iNTERP_STACK_CHECK_THRESH words at the start of each
161 -- BCO anyway, so we only need to add an explicit on in the
162 -- (hopefully rare) cases when the (overestimated) stack use
163 -- exceeds iNTERP_STACK_CHECK_THRESH.
164 maybe_with_stack_check
165 | stack_overest >= 65535
166 = pprPanic "mkProtoBCO: stack use won't fit in 16 bits"
168 | stack_overest >= iNTERP_STACK_CHECK_THRESH
169 = (STKCHECK stack_overest) : peep_d
171 = peep_d -- the supposedly common case
173 stack_overest = sum (map bciStackUse peep_d)
174 + 10 {- just to be really really sure -}
177 -- Merge local pushes
178 peep_d = peep (fromOL instrs_ordlist)
180 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
181 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
182 peep (PUSH_L off1 : PUSH_L off2 : rest)
183 = PUSH_LL off1 (off2-1) : peep rest
190 -- Compile code for the right hand side of a let binding.
191 -- Park the resulting BCO in the monad. Also requires the
192 -- variable to which this value was bound, so as to give the
193 -- resulting BCO a name. Bool indicates top-levelness.
195 schemeR :: Bool -> (Id, AnnExpr Id VarSet) -> BcM ()
196 schemeR is_top (nm, rhs)
200 $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
201 $$ pprCoreExpr (deAnnotate rhs)
207 = schemeR_wrk is_top rhs nm (collect [] rhs)
210 collect xs (_, AnnNote note e)
212 collect xs (_, AnnLam x e)
213 = collect (if isTyVar x then xs else (x:xs)) e
214 collect xs not_lambda
215 = (reverse xs, not_lambda)
217 schemeR_wrk is_top original_body nm (args, body)
218 | Just dcon <- maybe_toplevel_null_con_rhs
219 = --trace ("nullary constructor! " ++ showSDocDebug (ppr nm)) (
220 emitBc (mkProtoBCO (getName nm) (toOL [PACK dcon 0, ENTER])
221 (Right original_body))
225 = let fvs = filter (not.isTyVar) (varSetElems (fst original_body))
226 all_args = reverse args ++ fvs
227 szsw_args = map taggedIdSizeW all_args
228 szw_args = sum szsw_args
229 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
230 argcheck = unitOL (ARGCHECK szw_args)
232 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
233 emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code)
234 (Right original_body))
237 maybe_toplevel_null_con_rhs
238 | is_top && null args
241 -> case isDataConId_maybe v_wrk of
243 Just dc_wrk | nm == dataConWrapId dc_wrk
251 -- Let szsw be the sizes in words of some items pushed onto the stack,
252 -- which has initial depth d'. Return the values which the stack environment
253 -- should map these items to.
254 mkStackOffsets :: Int -> [Int] -> [Int]
255 mkStackOffsets original_depth szsw
256 = map (subtract 1) (tail (scanl (+) original_depth szsw))
258 -- Compile code to apply the given expression to the remaining args
259 -- on the stack, returning a HNF.
260 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
262 -- Delegate tail-calls to schemeT.
263 schemeE d s p e@(fvs, AnnApp f a)
264 = returnBc (schemeT d s p (fvs, AnnApp f a))
265 schemeE d s p e@(fvs, AnnVar v)
266 | isFollowableRep v_rep
267 = returnBc (schemeT d s p (fvs, AnnVar v))
270 = -- returning an unboxed value. Heave it on the stack, SLIDE, and RETURN.
271 let (push, szw) = pushAtom True d p (AnnVar v)
272 in returnBc (push -- value onto stack
273 `appOL` mkSLIDE szw (d-s) -- clear to sequel
274 `snocOL` RETURN v_rep) -- go
276 v_rep = typePrimRep (idType v)
278 schemeE d s p (fvs, AnnLit literal)
279 = let (push, szw) = pushAtom True d p (AnnLit literal)
280 l_rep = literalPrimRep literal
281 in returnBc (push -- value onto stack
282 `appOL` mkSLIDE szw (d-s) -- clear to sequel
283 `snocOL` RETURN l_rep) -- go
285 schemeE d s p (fvs, AnnLet binds b)
286 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
287 AnnRec xs_n_rhss -> unzip xs_n_rhss
289 fvss = map (filter (not.isTyVar).varSetElems.fst) rhss
291 -- Sizes of tagged free vars, + 1 for the fn
292 sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
294 -- This p', d' defn is safe because all the items being pushed
295 -- are ptrs, so all have size 1. d' and p' reflect the stack
296 -- after the closures have been allocated in the heap (but not
297 -- filled in), and pointers to them parked on the stack.
298 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
301 infos = zipE4 fvss sizes xs [n, n-1 .. 1]
302 zipE = zipEqual "schemeE"
303 zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
305 -- ToDo: don't build thunks for things with no free variables
306 buildThunk dd ([], size, id, off)
307 = PUSH_G (Left (getName id))
308 `consOL` unitOL (MKAP (off+size-1) size)
309 buildThunk dd ((fv:fvs), size, id, off)
310 = case pushAtom True dd p' (AnnVar fv) of
311 (push_code, pushed_szw)
313 buildThunk (dd+pushed_szw) (fvs, size, id, off)
315 thunkCode = concatOL (map (buildThunk d') infos)
316 allocCode = toOL (map ALLOC sizes)
318 schemeE d' s p' b `thenBc` \ bodyCode ->
319 mapBc (schemeR False) (zip xs rhss) `thenBc_`
320 returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
323 schemeE d s p (fvs, AnnCase scrut bndr alts)
325 -- Top of stack is the return itbl, as usual.
326 -- underneath it is the pointer to the alt_code BCO.
327 -- When an alt is entered, it assumes the returned value is
328 -- on top of the itbl.
331 -- Env and depth in which to compile the alts, not including
332 -- any vars bound by the alts themselves
333 d' = d + ret_frame_sizeW + taggedIdSizeW bndr
334 p' = addToFM p bndr (d' - 1)
336 scrut_primrep = typePrimRep (idType bndr)
338 = case scrut_primrep of
339 CharRep -> False ; AddrRep -> False ; WordRep -> False
340 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
343 other -> pprPanic "ByteCodeGen.schemeE" (ppr other)
345 -- given an alt, return a discr and code for it.
346 codeAlt alt@(discr, binds_f, rhs)
348 = let (unpack_code, d_after_unpack, p_after_unpack)
349 = mkUnpackCode binds_f d' p'
350 in schemeE d_after_unpack s p_after_unpack rhs
351 `thenBc` \ rhs_code ->
352 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
354 = ASSERT(null binds_f)
355 schemeE d' s p' rhs `thenBc` \ rhs_code ->
356 returnBc (my_discr alt, rhs_code)
358 my_discr (DEFAULT, binds, rhs) = NoDiscr
359 my_discr (DataAlt dc, binds, rhs)
360 | isUnboxedTupleCon dc
361 = unboxedTupleException
363 = DiscrP (dataConTag dc - fIRST_TAG)
364 my_discr (LitAlt l, binds, rhs)
365 = case l of MachInt i -> DiscrI (fromInteger i)
366 MachFloat r -> DiscrF (fromRational r)
367 MachDouble r -> DiscrD (fromRational r)
368 MachChar i -> DiscrI i
369 _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
372 | not isAlgCase = Nothing
374 = case [dc | (DataAlt dc, _, _) <- alts] of
376 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
379 mapBc codeAlt alts `thenBc` \ alt_stuff ->
380 mkMultiBranch maybe_ncons alt_stuff `thenBc` \ alt_final ->
382 alt_final_ac = ARGCHECK (taggedIdSizeW bndr) `consOL` alt_final
383 alt_bco_name = getName bndr
384 alt_bco = mkProtoBCO alt_bco_name alt_final_ac (Left alts)
386 schemeE (d + ret_frame_sizeW)
387 (d + ret_frame_sizeW) p scrut `thenBc` \ scrut_code ->
389 emitBc alt_bco `thenBc_`
390 returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
393 schemeE d s p (fvs, AnnNote note body)
397 = pprPanic "ByteCodeGen.schemeE: unhandled case"
398 (pprCoreExpr (deAnnotate other))
401 -- Compile code to do a tail call. Three cases:
403 -- 1. A nullary constructor. Push its closure on the stack
404 -- and SLIDE and RETURN.
406 -- 2. Application of a non-nullary constructor, by defn saturated.
407 -- Split the args into ptrs and non-ptrs, and push the nonptrs,
408 -- then the ptrs, and then do PACK and RETURN.
410 -- 3. Otherwise, it must be a function call. Push the args
411 -- right to left, SLIDE and ENTER.
413 schemeT :: Int -- Stack depth
414 -> Sequel -- Sequel depth
415 -> BCEnv -- stack env
420 -- | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
421 -- = panic "schemeT ?!?!"
424 | is_con_call && null args_r_to_l
425 = (PUSH_G (Left (getName con)) `consOL` mkSLIDE 1 (d-s))
430 = if is_con_call && isUnboxedTupleCon con
431 then unboxedTupleException
435 -- Extract the args (R->L) and fn
436 (args_r_to_l_raw, fn) = chomp app
440 AnnApp f a -> case chomp f of (az, f) -> (snd a:az, f)
441 AnnNote n e -> chomp e
442 other -> pprPanic "schemeT"
443 (ppr (deAnnotate (panic "schemeT.chomp", other)))
445 args_r_to_l = filter (not.isTypeAtom) args_r_to_l_raw
446 isTypeAtom (AnnType _) = True
449 -- decide if this is a constructor call, and rearrange
450 -- args appropriately.
451 maybe_dcon = isDataConId_maybe fn
452 is_con_call = case maybe_dcon of Nothing -> False; Just _ -> True
453 (Just con) = maybe_dcon
459 = filter (not.isPtr) args_r_to_l ++ filter isPtr args_r_to_l
460 where isPtr = isFollowableRep . atomRep
462 -- make code to push the args and then do the SLIDE-ENTER thing
463 code = do_pushery d args_final_r_to_l
465 tag_when_push = not is_con_call
466 narg_words = sum (map (get_arg_szw . atomRep) args_r_to_l)
467 get_arg_szw = if tag_when_push then taggedSizeW else untaggedSizeW
469 do_pushery d (arg:args)
470 = let (push, arg_words) = pushAtom tag_when_push d p arg
471 in push `appOL` do_pushery (d+arg_words) args
474 Just con -> PACK con narg_words `consOL` (
475 mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
477 -> let (push, arg_words) = pushAtom True d p (AnnVar fn)
479 `appOL` mkSLIDE (narg_words+arg_words)
484 = if d == 0 then nilOL else unitOL (SLIDE n d)
486 atomRep (AnnVar v) = typePrimRep (idType v)
487 atomRep (AnnLit l) = literalPrimRep l
488 atomRep (AnnNote n b) = atomRep (snd b)
489 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
490 atomRep (AnnLam x e) | isTyVar x = atomRep (snd e)
491 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
494 -- Make code to unpack the top-of-stack constructor onto the stack,
495 -- adding tags for the unboxed bits. Takes the PrimReps of the
496 -- constructor's arguments. off_h and off_s are travelling offsets
497 -- along the constructor and the stack.
499 -- Supposing a constructor in the heap has layout
501 -- Itbl p_1 ... p_i np_1 ... np_j
503 -- then we add to the stack, shown growing down, the following:
515 -- so that in the common case (ptrs only) a single UNPACK instr can
516 -- copy all the payload of the constr onto the stack with no further ado.
518 mkUnpackCode :: [Id] -- constr args
519 -> Int -- depth before unpack
520 -> BCEnv -- env before unpack
521 -> (BCInstrList, Int, BCEnv)
522 mkUnpackCode vars d p
523 = --trace ("mkUnpackCode: " ++ showSDocDebug (ppr vars)
524 -- ++ " --> " ++ show d' ++ "\n" ++ showSDocDebug (ppBCEnv p')
526 (code_p `appOL` code_np, d', p')
530 vreps = [(var, typePrimRep (idType var)) | var <- vars]
532 -- ptrs and nonptrs, forward
533 vreps_p = filter (isFollowableRep.snd) vreps
534 vreps_np = filter (not.isFollowableRep.snd) vreps
536 -- the order in which we will augment the environment
537 vreps_env = reverse vreps_p ++ reverse vreps_np
540 vreps_env_tszsw = map (taggedSizeW.snd) vreps_env
541 p' = addListToFM p (zip (map fst vreps_env)
542 (mkStackOffsets d vreps_env_tszsw))
543 d' = d + sum vreps_env_tszsw
545 -- code to unpack the ptrs
546 ptrs_szw = sum (map (untaggedSizeW.snd) vreps_p)
547 code_p | null vreps_p = nilOL
548 | otherwise = unitOL (UNPACK ptrs_szw)
550 -- code to unpack the nonptrs
551 vreps_env_uszw = sum (map (untaggedSizeW.snd) vreps_env)
552 code_np = do_nptrs vreps_env_uszw ptrs_szw (reverse (map snd vreps_np))
553 do_nptrs off_h off_s [] = nilOL
554 do_nptrs off_h off_s (npr:nprs)
556 IntRep -> approved ; FloatRep -> approved
557 DoubleRep -> approved ; AddrRep -> approved
559 _ -> pprPanic "ByteCodeGen.mkUnpackCode" (ppr npr)
561 approved = UPK_TAG usizeW (off_h-usizeW) off_s `consOL` theRest
562 theRest = do_nptrs (off_h-usizeW) (off_s + tsizeW) nprs
563 usizeW = untaggedSizeW npr
564 tsizeW = taggedSizeW npr
567 -- Push an atom onto the stack, returning suitable code & number of
568 -- stack words used. Pushes it either tagged or untagged, since
569 -- pushAtom is used to set up the stack prior to copying into the
570 -- heap for both APs (requiring tags) and constructors (which don't).
572 -- NB this means NO GC between pushing atoms for a constructor and
573 -- copying them into the heap. It probably also means that
574 -- tail calls MUST be of the form atom{atom ... atom} since if the
575 -- expression head was allowed to be arbitrary, there could be GC
576 -- in between pushing the arg atoms and completing the head.
577 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
578 -- isn't a problem; but only if arbitrary graph construction for the
579 -- head doesn't leave this BCO, since GC might happen at the start of
580 -- each BCO (we consult doYouWantToGC there).
582 -- Blargh. JRS 001206
584 -- NB (further) that the env p must map each variable to the highest-
585 -- numbered stack slot for it. For example, if the stack has depth 4
586 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
587 -- the tag in stack[5], the stack will have depth 6, and p must map v to
588 -- 5 and not to 4. Stack locations are numbered from zero, so a depth
589 -- 6 stack has valid words 0 .. 5.
591 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
592 pushAtom tagged d p (AnnVar v)
594 | idPrimRep v == VoidRep
596 (unitOL (PUSH_TAG 0), 1)
598 | Just primop <- isPrimOpId_maybe v
600 CCallOp _ -> panic "pushAtom: byte code generator can't handle CCalls"
601 other -> (unitOL (PUSH_G (Right primop)), 1)
604 = let str = "\npushAtom " ++ showSDocDebug (ppr v)
605 ++ " :: " ++ showSDocDebug (pprType (idType v))
606 ++ ", depth = " ++ show d
607 ++ ", tagged = " ++ show tagged ++ ", env =\n" ++
608 showSDocDebug (ppBCEnv p)
609 ++ " --> words: " ++ show (snd result) ++ "\n" ++
610 showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
611 ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
613 cmp_snd x y = compare (snd x) (snd y)
614 str' = if str == str then str else str
617 = case lookupBCEnv_maybe p v of
618 Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), nwords)
619 Nothing -> ASSERT(sz_t == 1) (unitOL (PUSH_G (Left nm)), nwords)
621 nm = case isDataConId_maybe v of
625 sz_t = taggedIdSizeW v
626 sz_u = untaggedIdSizeW v
627 nwords = if tagged then sz_t else sz_u
632 pushAtom True d p (AnnLit lit)
633 = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
634 in (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
636 pushAtom False d p (AnnLit lit)
638 MachWord w -> code WordRep
639 MachInt i -> code IntRep
640 MachFloat r -> code FloatRep
641 MachDouble r -> code DoubleRep
642 MachChar c -> code CharRep
643 MachStr s -> pushStr s
646 = let size_host_words = untaggedSizeW rep
647 in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
650 = let mallocvilleAddr
655 -- sigh, a string in the heap is no good to us.
656 -- We need a static C pointer, since the type of
657 -- a string literal is Addr#. So, copy the string
658 -- into C land and introduce a memory leak
661 -- CAREFUL! Chars are 32 bits in ghc 4.09+
663 do (Ptr a#) <- mallocBytes (n+1)
664 strncpy (Ptr a#) ba (fromIntegral n)
665 writeCharOffAddr (A# a#) n '\0'
668 _ -> panic "StgInterp.lit2expr: unhandled string constant type"
671 = MachInt (toInteger (addrToInt mallocvilleAddr))
673 -- Get the addr on the stack, untaggedly
674 (unitOL (PUSH_UBX addrLit 1), 1)
680 pushAtom tagged d p (AnnApp f (_, AnnType _))
681 = pushAtom tagged d p (snd f)
683 pushAtom tagged d p (AnnNote note e)
684 = pushAtom tagged d p (snd e)
686 pushAtom tagged d p (AnnLam x e)
688 = pushAtom tagged d p (snd e)
690 pushAtom tagged d p other
691 = pprPanic "ByteCodeGen.pushAtom"
692 (pprCoreExpr (deAnnotate (undefined, other)))
694 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
697 -- Given a bunch of alts code and their discrs, do the donkey work
698 -- of making a multiway branch using a switch tree.
699 -- What a load of hassle!
700 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
701 -- a hint; generates better code
702 -- Nothing is always safe
703 -> [(Discr, BCInstrList)]
705 mkMultiBranch maybe_ncons raw_ways
706 = let d_way = filter (isNoDiscr.fst) raw_ways
707 notd_ways = naturalMergeSortLe
708 (\w1 w2 -> leAlt (fst w1) (fst w2))
709 (filter (not.isNoDiscr.fst) raw_ways)
711 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
712 mkTree [] range_lo range_hi = returnBc the_default
714 mkTree [val] range_lo range_hi
715 | range_lo `eqAlt` range_hi
718 = getLabelBc `thenBc` \ label_neq ->
719 returnBc (mkTestEQ (fst val) label_neq
721 `appOL` unitOL (LABEL label_neq)
722 `appOL` the_default))
724 mkTree vals range_lo range_hi
725 = let n = length vals `div` 2
726 vals_lo = take n vals
727 vals_hi = drop n vals
728 v_mid = fst (head vals_hi)
730 getLabelBc `thenBc` \ label_geq ->
731 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
732 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
733 returnBc (mkTestLT v_mid label_geq
735 `appOL` unitOL (LABEL label_geq)
739 = case d_way of [] -> unitOL CASEFAIL
742 -- None of these will be needed if there are no non-default alts
743 (mkTestLT, mkTestEQ, init_lo, init_hi)
745 = panic "mkMultiBranch: awesome foursome"
747 = case fst (head notd_ways) of {
748 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
749 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
752 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
753 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
756 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
757 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
760 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
761 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
766 (algMinBound, algMaxBound)
767 = case maybe_ncons of
769 Nothing -> (minBound, maxBound)
771 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
772 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
773 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
774 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
775 NoDiscr `eqAlt` NoDiscr = True
778 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
779 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
780 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
781 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
782 NoDiscr `leAlt` NoDiscr = True
785 isNoDiscr NoDiscr = True
788 dec (DiscrI i) = DiscrI (i-1)
789 dec (DiscrP i) = DiscrP (i-1)
790 dec other = other -- not really right, but if you
791 -- do cases on floating values, you'll get what you deserve
793 -- same snotty comment applies to the following
801 mkTree notd_ways init_lo init_hi
805 %************************************************************************
807 \subsection{Supporting junk for the compilation schemes}
809 %************************************************************************
813 -- Describes case alts
821 instance Outputable Discr where
822 ppr (DiscrI i) = int i
823 ppr (DiscrF f) = text (show f)
824 ppr (DiscrD d) = text (show d)
825 ppr (DiscrP i) = int i
826 ppr NoDiscr = text "DEF"
829 -- Find things in the BCEnv (the what's-on-the-stack-env)
830 -- See comment preceding pushAtom for precise meaning of env contents
831 --lookupBCEnv :: BCEnv -> Id -> Int
833 -- = case lookupFM env nm of
834 -- Nothing -> pprPanic "lookupBCEnv"
835 -- (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
838 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
839 lookupBCEnv_maybe = lookupFM
842 -- When I push one of these on the stack, how much does Sp move by?
843 taggedSizeW :: PrimRep -> Int
845 | isFollowableRep pr = 1
846 | otherwise = 1{-the tag-} + getPrimRepSize pr
849 -- The plain size of something, without tag.
850 untaggedSizeW :: PrimRep -> Int
852 | isFollowableRep pr = 1
853 | otherwise = getPrimRepSize pr
856 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
857 taggedIdSizeW = taggedSizeW . typePrimRep . idType
858 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
860 unboxedTupleException :: a
861 unboxedTupleException
862 = throwDyn (Panic "bytecode generator can't handle unboxed tuples")
866 %************************************************************************
868 \subsection{The bytecode generator's monad}
870 %************************************************************************
874 = BcM_State { bcos :: [ProtoBCO Name], -- accumulates completed BCOs
875 nextlabel :: Int } -- for generating local labels
877 type BcM result = BcM_State -> (result, BcM_State)
879 runBc :: BcM_State -> BcM () -> BcM_State
880 runBc init_st m = case m init_st of { (r,st) -> st }
882 thenBc :: BcM a -> (a -> BcM b) -> BcM b
884 = case expr st of { (result, st') -> cont result st' }
886 thenBc_ :: BcM a -> BcM b -> BcM b
888 = case expr st of { (result, st') -> cont st' }
890 returnBc :: a -> BcM a
891 returnBc result st = (result, st)
893 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
894 mapBc f [] = returnBc []
896 = f x `thenBc` \ r ->
897 mapBc f xs `thenBc` \ rs ->
900 emitBc :: ProtoBCO Name -> BcM ()
902 = ((), st{bcos = bco : bcos st})
904 getLabelBc :: BcM Int
906 = (nextlabel st, st{nextlabel = 1 + nextlabel st})