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_name = mkSysLocalName (mkPseudoUnique3 0) SLIT("Expr-Top-Level")
106 let invented_id = mkVanillaId invented_name (panic "invented_id's type")
108 let (BcM_State all_proto_bcos final_ctr)
109 = runBc (BcM_State [] 0)
110 (schemeR True (invented_id, freeVars expr))
111 dumpIfSet_dyn dflags Opt_D_dump_BCOs
112 "Proto-bcos" (vcat (intersperse (char ' ') (map ppr all_proto_bcos)))
115 = case filter ((== invented_name).nameOfProtoBCO) all_proto_bcos of
116 [root_bco] -> root_bco
118 = filter ((/= invented_name).nameOfProtoBCO) all_proto_bcos
120 auxiliary_bcos <- mapM assembleBCO auxiliary_proto_bcos
121 root_bco <- assembleBCO root_proto_bco
123 return (root_bco, auxiliary_bcos)
126 %************************************************************************
128 \subsection{Compilation schema for the bytecode generator.}
130 %************************************************************************
134 type BCInstrList = OrdList BCInstr
136 type Sequel = Int -- back off to this depth before ENTER
138 -- Maps Ids to the offset from the stack _base_ so we don't have
139 -- to mess with it after each push/pop.
140 type BCEnv = FiniteMap Id Int -- To find vars on the stack
142 ppBCEnv :: BCEnv -> SDoc
145 $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
148 pp_one (var, offset) = int offset <> colon <+> ppr var
149 cmp_snd x y = compare (snd x) (snd y)
151 -- Create a BCO and do a spot of peephole optimisation on the insns
153 mkProtoBCO nm instrs_ordlist origin
154 = ProtoBCO nm maybe_with_stack_check origin
156 -- Overestimate the stack usage (in words) of this BCO,
157 -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit
158 -- stack check. (The interpreter always does a stack check
159 -- for iNTERP_STACK_CHECK_THRESH words at the start of each
160 -- BCO anyway, so we only need to add an explicit on in the
161 -- (hopefully rare) cases when the (overestimated) stack use
162 -- exceeds iNTERP_STACK_CHECK_THRESH.
163 maybe_with_stack_check
164 | stack_overest >= 65535
165 = pprPanic "mkProtoBCO: stack use won't fit in 16 bits"
167 | stack_overest >= iNTERP_STACK_CHECK_THRESH
168 = (STKCHECK stack_overest) : peep_d
170 = peep_d -- the supposedly common case
172 stack_overest = sum (map bciStackUse peep_d)
173 + 10 {- just to be really really sure -}
176 -- Merge local pushes
177 peep_d = peep (fromOL instrs_ordlist)
179 peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
180 = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
181 peep (PUSH_L off1 : PUSH_L off2 : rest)
182 = PUSH_LL off1 (off2-1) : peep rest
189 -- Compile code for the right hand side of a let binding.
190 -- Park the resulting BCO in the monad. Also requires the
191 -- variable to which this value was bound, so as to give the
192 -- resulting BCO a name. Bool indicates top-levelness.
194 schemeR :: Bool -> (Id, AnnExpr Id VarSet) -> BcM ()
195 schemeR is_top (nm, rhs)
199 $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
200 $$ pprCoreExpr (deAnnotate rhs)
206 = schemeR_wrk is_top rhs nm (collect [] rhs)
209 collect xs (_, AnnNote note e)
211 collect xs (_, AnnLam x e)
212 = collect (if isTyVar x then xs else (x:xs)) e
213 collect xs not_lambda
214 = (reverse xs, not_lambda)
216 schemeR_wrk is_top original_body nm (args, body)
217 | Just dcon <- maybe_toplevel_null_con_rhs
218 = --trace ("nullary constructor! " ++ showSDocDebug (ppr nm)) (
219 emitBc (mkProtoBCO (getName nm) (toOL [PACK dcon 0, ENTER])
220 (Right original_body))
224 = let fvs = filter (not.isTyVar) (varSetElems (fst original_body))
225 all_args = reverse args ++ fvs
226 szsw_args = map taggedIdSizeW all_args
227 szw_args = sum szsw_args
228 p_init = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
229 argcheck = unitOL (ARGCHECK szw_args)
231 schemeE szw_args 0 p_init body `thenBc` \ body_code ->
232 emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code)
233 (Right original_body))
236 maybe_toplevel_null_con_rhs
237 | is_top && null args
240 -> case isDataConId_maybe v_wrk of
242 Just dc_wrk | nm == dataConWrapId dc_wrk
250 -- Let szsw be the sizes in words of some items pushed onto the stack,
251 -- which has initial depth d'. Return the values which the stack environment
252 -- should map these items to.
253 mkStackOffsets :: Int -> [Int] -> [Int]
254 mkStackOffsets original_depth szsw
255 = map (subtract 1) (tail (scanl (+) original_depth szsw))
257 -- Compile code to apply the given expression to the remaining args
258 -- on the stack, returning a HNF.
259 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
261 -- Delegate tail-calls to schemeT.
262 schemeE d s p e@(fvs, AnnApp f a)
263 = returnBc (schemeT d s p (fvs, AnnApp f a))
264 schemeE d s p e@(fvs, AnnVar v)
265 | isFollowableRep v_rep
266 = returnBc (schemeT d s p (fvs, AnnVar v))
269 = -- returning an unboxed value. Heave it on the stack, SLIDE, and RETURN.
270 let (push, szw) = pushAtom True d p (AnnVar v)
271 in returnBc (push -- value onto stack
272 `appOL` mkSLIDE szw (d-s) -- clear to sequel
273 `snocOL` RETURN v_rep) -- go
275 v_rep = typePrimRep (idType v)
277 schemeE d s p (fvs, AnnLit literal)
278 = let (push, szw) = pushAtom True d p (AnnLit literal)
279 l_rep = literalPrimRep literal
280 in returnBc (push -- value onto stack
281 `appOL` mkSLIDE szw (d-s) -- clear to sequel
282 `snocOL` RETURN l_rep) -- go
284 schemeE d s p (fvs, AnnLet binds b)
285 = let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
286 AnnRec xs_n_rhss -> unzip xs_n_rhss
288 fvss = map (filter (not.isTyVar).varSetElems.fst) rhss
290 -- Sizes of tagged free vars, + 1 for the fn
291 sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
293 -- This p', d' defn is safe because all the items being pushed
294 -- are ptrs, so all have size 1. d' and p' reflect the stack
295 -- after the closures have been allocated in the heap (but not
296 -- filled in), and pointers to them parked on the stack.
297 p' = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
300 infos = zipE4 fvss sizes xs [n, n-1 .. 1]
301 zipE = zipEqual "schemeE"
302 zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
304 -- ToDo: don't build thunks for things with no free variables
305 buildThunk dd ([], size, id, off)
306 = PUSH_G (Left (getName id))
307 `consOL` unitOL (MKAP (off+size-1) size)
308 buildThunk dd ((fv:fvs), size, id, off)
309 = case pushAtom True dd p' (AnnVar fv) of
310 (push_code, pushed_szw)
312 buildThunk (dd+pushed_szw) (fvs, size, id, off)
314 thunkCode = concatOL (map (buildThunk d') infos)
315 allocCode = toOL (map ALLOC sizes)
317 schemeE d' s p' b `thenBc` \ bodyCode ->
318 mapBc (schemeR False) (zip xs rhss) `thenBc_`
319 returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
322 schemeE d s p (fvs, AnnCase scrut bndr alts)
324 -- Top of stack is the return itbl, as usual.
325 -- underneath it is the pointer to the alt_code BCO.
326 -- When an alt is entered, it assumes the returned value is
327 -- on top of the itbl.
330 -- Env and depth in which to compile the alts, not including
331 -- any vars bound by the alts themselves
332 d' = d + ret_frame_sizeW + taggedIdSizeW bndr
333 p' = addToFM p bndr (d' - 1)
335 scrut_primrep = typePrimRep (idType bndr)
337 = case scrut_primrep of
338 CharRep -> False ; AddrRep -> False ; WordRep -> False
339 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
342 other -> pprPanic "ByteCodeGen.schemeE" (ppr other)
344 -- given an alt, return a discr and code for it.
345 codeAlt alt@(discr, binds_f, rhs)
347 = let (unpack_code, d_after_unpack, p_after_unpack)
348 = mkUnpackCode binds_f d' p'
349 in schemeE d_after_unpack s p_after_unpack rhs
350 `thenBc` \ rhs_code ->
351 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
353 = ASSERT(null binds_f)
354 schemeE d' s p' rhs `thenBc` \ rhs_code ->
355 returnBc (my_discr alt, rhs_code)
357 my_discr (DEFAULT, binds, rhs) = NoDiscr
358 my_discr (DataAlt dc, binds, rhs)
359 | isUnboxedTupleCon dc
360 = unboxedTupleException
362 = DiscrP (dataConTag dc - fIRST_TAG)
363 my_discr (LitAlt l, binds, rhs)
364 = case l of MachInt i -> DiscrI (fromInteger i)
365 MachFloat r -> DiscrF (fromRational r)
366 MachDouble r -> DiscrD (fromRational r)
367 MachChar i -> DiscrI i
368 _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
371 | not isAlgCase = Nothing
373 = case [dc | (DataAlt dc, _, _) <- alts] of
375 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
378 mapBc codeAlt alts `thenBc` \ alt_stuff ->
379 mkMultiBranch maybe_ncons alt_stuff `thenBc` \ alt_final ->
381 alt_final_ac = ARGCHECK (taggedIdSizeW bndr) `consOL` alt_final
382 alt_bco_name = getName bndr
383 alt_bco = mkProtoBCO alt_bco_name alt_final_ac (Left alts)
385 schemeE (d + ret_frame_sizeW)
386 (d + ret_frame_sizeW) p scrut `thenBc` \ scrut_code ->
388 emitBc alt_bco `thenBc_`
389 returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
392 schemeE d s p (fvs, AnnNote note body)
396 = pprPanic "ByteCodeGen.schemeE: unhandled case"
397 (pprCoreExpr (deAnnotate other))
400 -- Compile code to do a tail call. Three cases:
402 -- 1. A nullary constructor. Push its closure on the stack
403 -- and SLIDE and RETURN.
405 -- 2. Application of a non-nullary constructor, by defn saturated.
406 -- Split the args into ptrs and non-ptrs, and push the nonptrs,
407 -- then the ptrs, and then do PACK and RETURN.
409 -- 3. Otherwise, it must be a function call. Push the args
410 -- right to left, SLIDE and ENTER.
412 schemeT :: Int -- Stack depth
413 -> Sequel -- Sequel depth
414 -> BCEnv -- stack env
419 -- | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
420 -- = panic "schemeT ?!?!"
423 | is_con_call && null args_r_to_l
424 = (PUSH_G (Left (getName con)) `consOL` mkSLIDE 1 (d-s))
429 = if is_con_call && isUnboxedTupleCon con
430 then unboxedTupleException
434 -- Extract the args (R->L) and fn
435 (args_r_to_l_raw, fn) = chomp app
439 AnnApp f a -> case chomp f of (az, f) -> (snd a:az, f)
440 AnnNote n e -> chomp e
441 other -> pprPanic "schemeT"
442 (ppr (deAnnotate (panic "schemeT.chomp", other)))
444 args_r_to_l = filter (not.isTypeAtom) args_r_to_l_raw
445 isTypeAtom (AnnType _) = True
448 -- decide if this is a constructor call, and rearrange
449 -- args appropriately.
450 maybe_dcon = isDataConId_maybe fn
451 is_con_call = case maybe_dcon of Nothing -> False; Just _ -> True
452 (Just con) = maybe_dcon
458 = filter (not.isPtr) args_r_to_l ++ filter isPtr args_r_to_l
459 where isPtr = isFollowableRep . atomRep
461 -- make code to push the args and then do the SLIDE-ENTER thing
462 code = do_pushery d args_final_r_to_l
464 tag_when_push = not is_con_call
465 narg_words = sum (map (get_arg_szw . atomRep) args_r_to_l)
466 get_arg_szw = if tag_when_push then taggedSizeW else untaggedSizeW
468 do_pushery d (arg:args)
469 = let (push, arg_words) = pushAtom tag_when_push d p arg
470 in push `appOL` do_pushery (d+arg_words) args
473 Just con -> PACK con narg_words `consOL` (
474 mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
476 -> let (push, arg_words) = pushAtom True d p (AnnVar fn)
478 `appOL` mkSLIDE (narg_words+arg_words)
483 = if d == 0 then nilOL else unitOL (SLIDE n d)
485 atomRep (AnnVar v) = typePrimRep (idType v)
486 atomRep (AnnLit l) = literalPrimRep l
487 atomRep (AnnNote n b) = atomRep (snd b)
488 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
489 atomRep (AnnLam x e) | isTyVar x = atomRep (snd e)
490 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
493 -- Make code to unpack the top-of-stack constructor onto the stack,
494 -- adding tags for the unboxed bits. Takes the PrimReps of the
495 -- constructor's arguments. off_h and off_s are travelling offsets
496 -- along the constructor and the stack.
498 -- Supposing a constructor in the heap has layout
500 -- Itbl p_1 ... p_i np_1 ... np_j
502 -- then we add to the stack, shown growing down, the following:
514 -- so that in the common case (ptrs only) a single UNPACK instr can
515 -- copy all the payload of the constr onto the stack with no further ado.
517 mkUnpackCode :: [Id] -- constr args
518 -> Int -- depth before unpack
519 -> BCEnv -- env before unpack
520 -> (BCInstrList, Int, BCEnv)
521 mkUnpackCode vars d p
522 = --trace ("mkUnpackCode: " ++ showSDocDebug (ppr vars)
523 -- ++ " --> " ++ show d' ++ "\n" ++ showSDocDebug (ppBCEnv p')
525 (code_p `appOL` code_np, d', p')
529 vreps = [(var, typePrimRep (idType var)) | var <- vars]
531 -- ptrs and nonptrs, forward
532 vreps_p = filter (isFollowableRep.snd) vreps
533 vreps_np = filter (not.isFollowableRep.snd) vreps
535 -- the order in which we will augment the environment
536 vreps_env = reverse vreps_p ++ reverse vreps_np
539 vreps_env_tszsw = map (taggedSizeW.snd) vreps_env
540 p' = addListToFM p (zip (map fst vreps_env)
541 (mkStackOffsets d vreps_env_tszsw))
542 d' = d + sum vreps_env_tszsw
544 -- code to unpack the ptrs
545 ptrs_szw = sum (map (untaggedSizeW.snd) vreps_p)
546 code_p | null vreps_p = nilOL
547 | otherwise = unitOL (UNPACK ptrs_szw)
549 -- code to unpack the nonptrs
550 vreps_env_uszw = sum (map (untaggedSizeW.snd) vreps_env)
551 code_np = do_nptrs vreps_env_uszw ptrs_szw (reverse (map snd vreps_np))
552 do_nptrs off_h off_s [] = nilOL
553 do_nptrs off_h off_s (npr:nprs)
555 IntRep -> approved ; FloatRep -> approved
556 DoubleRep -> approved ; AddrRep -> approved
558 _ -> pprPanic "ByteCodeGen.mkUnpackCode" (ppr npr)
560 approved = UPK_TAG usizeW (off_h-usizeW) off_s `consOL` theRest
561 theRest = do_nptrs (off_h-usizeW) (off_s + tsizeW) nprs
562 usizeW = untaggedSizeW npr
563 tsizeW = taggedSizeW npr
566 -- Push an atom onto the stack, returning suitable code & number of
567 -- stack words used. Pushes it either tagged or untagged, since
568 -- pushAtom is used to set up the stack prior to copying into the
569 -- heap for both APs (requiring tags) and constructors (which don't).
571 -- NB this means NO GC between pushing atoms for a constructor and
572 -- copying them into the heap. It probably also means that
573 -- tail calls MUST be of the form atom{atom ... atom} since if the
574 -- expression head was allowed to be arbitrary, there could be GC
575 -- in between pushing the arg atoms and completing the head.
576 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
577 -- isn't a problem; but only if arbitrary graph construction for the
578 -- head doesn't leave this BCO, since GC might happen at the start of
579 -- each BCO (we consult doYouWantToGC there).
581 -- Blargh. JRS 001206
583 -- NB (further) that the env p must map each variable to the highest-
584 -- numbered stack slot for it. For example, if the stack has depth 4
585 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
586 -- the tag in stack[5], the stack will have depth 6, and p must map v to
587 -- 5 and not to 4. Stack locations are numbered from zero, so a depth
588 -- 6 stack has valid words 0 .. 5.
590 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
591 pushAtom tagged d p (AnnVar v)
593 | idPrimRep v == VoidRep
595 (unitOL (PUSH_TAG 0), 1)
597 | Just primop <- isPrimOpId_maybe v
599 CCallOp _ -> panic "pushAtom: byte code generator can't handle CCalls"
600 other -> (unitOL (PUSH_G (Right primop)), 1)
603 = let str = "\npushAtom " ++ showSDocDebug (ppr v)
604 ++ " :: " ++ showSDocDebug (pprType (idType v))
605 ++ ", depth = " ++ show d
606 ++ ", tagged = " ++ show tagged ++ ", env =\n" ++
607 showSDocDebug (ppBCEnv p)
608 ++ " --> words: " ++ show (snd result) ++ "\n" ++
609 showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
610 ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
612 cmp_snd x y = compare (snd x) (snd y)
613 str' = if str == str then str else str
616 = case lookupBCEnv_maybe p v of
617 Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), nwords)
618 Nothing -> ASSERT(sz_t == 1) (unitOL (PUSH_G (Left nm)), nwords)
620 nm = case isDataConId_maybe v of
624 sz_t = taggedIdSizeW v
625 sz_u = untaggedIdSizeW v
626 nwords = if tagged then sz_t else sz_u
631 pushAtom True d p (AnnLit lit)
632 = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
633 in (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
635 pushAtom False d p (AnnLit lit)
637 MachWord w -> code WordRep
638 MachInt i -> code IntRep
639 MachFloat r -> code FloatRep
640 MachDouble r -> code DoubleRep
641 MachChar c -> code CharRep
642 MachStr s -> pushStr s
645 = let size_host_words = untaggedSizeW rep
646 in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
649 = let mallocvilleAddr
654 -- sigh, a string in the heap is no good to us.
655 -- We need a static C pointer, since the type of
656 -- a string literal is Addr#. So, copy the string
657 -- into C land and introduce a memory leak
660 -- CAREFUL! Chars are 32 bits in ghc 4.09+
662 do (Ptr a#) <- mallocBytes (n+1)
663 strncpy (Ptr a#) ba (fromIntegral n)
664 writeCharOffAddr (A# a#) n '\0'
667 _ -> panic "StgInterp.lit2expr: unhandled string constant type"
670 = MachInt (toInteger (addrToInt mallocvilleAddr))
672 -- Get the addr on the stack, untaggedly
673 (unitOL (PUSH_UBX addrLit 1), 1)
679 pushAtom tagged d p (AnnApp f (_, AnnType _))
680 = pushAtom tagged d p (snd f)
682 pushAtom tagged d p (AnnNote note e)
683 = pushAtom tagged d p (snd e)
685 pushAtom tagged d p (AnnLam x e)
687 = pushAtom tagged d p (snd e)
689 pushAtom tagged d p other
690 = pprPanic "ByteCodeGen.pushAtom"
691 (pprCoreExpr (deAnnotate (undefined, other)))
693 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
696 -- Given a bunch of alts code and their discrs, do the donkey work
697 -- of making a multiway branch using a switch tree.
698 -- What a load of hassle!
699 mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
700 -- a hint; generates better code
701 -- Nothing is always safe
702 -> [(Discr, BCInstrList)]
704 mkMultiBranch maybe_ncons raw_ways
705 = let d_way = filter (isNoDiscr.fst) raw_ways
706 notd_ways = naturalMergeSortLe
707 (\w1 w2 -> leAlt (fst w1) (fst w2))
708 (filter (not.isNoDiscr.fst) raw_ways)
710 mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
711 mkTree [] range_lo range_hi = returnBc the_default
713 mkTree [val] range_lo range_hi
714 | range_lo `eqAlt` range_hi
717 = getLabelBc `thenBc` \ label_neq ->
718 returnBc (mkTestEQ (fst val) label_neq
720 `appOL` unitOL (LABEL label_neq)
721 `appOL` the_default))
723 mkTree vals range_lo range_hi
724 = let n = length vals `div` 2
725 vals_lo = take n vals
726 vals_hi = drop n vals
727 v_mid = fst (head vals_hi)
729 getLabelBc `thenBc` \ label_geq ->
730 mkTree vals_lo range_lo (dec v_mid) `thenBc` \ code_lo ->
731 mkTree vals_hi v_mid range_hi `thenBc` \ code_hi ->
732 returnBc (mkTestLT v_mid label_geq
734 `appOL` unitOL (LABEL label_geq)
738 = case d_way of [] -> unitOL CASEFAIL
741 -- None of these will be needed if there are no non-default alts
742 (mkTestLT, mkTestEQ, init_lo, init_hi)
744 = panic "mkMultiBranch: awesome foursome"
746 = case fst (head notd_ways) of {
747 DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
748 \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
751 DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
752 \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
755 DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
756 \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
759 DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
760 \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
765 (algMinBound, algMaxBound)
766 = case maybe_ncons of
768 Nothing -> (minBound, maxBound)
770 (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
771 (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
772 (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
773 (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
774 NoDiscr `eqAlt` NoDiscr = True
777 (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
778 (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
779 (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
780 (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
781 NoDiscr `leAlt` NoDiscr = True
784 isNoDiscr NoDiscr = True
787 dec (DiscrI i) = DiscrI (i-1)
788 dec (DiscrP i) = DiscrP (i-1)
789 dec other = other -- not really right, but if you
790 -- do cases on floating values, you'll get what you deserve
792 -- same snotty comment applies to the following
800 mkTree notd_ways init_lo init_hi
804 %************************************************************************
806 \subsection{Supporting junk for the compilation schemes}
808 %************************************************************************
812 -- Describes case alts
820 instance Outputable Discr where
821 ppr (DiscrI i) = int i
822 ppr (DiscrF f) = text (show f)
823 ppr (DiscrD d) = text (show d)
824 ppr (DiscrP i) = int i
825 ppr NoDiscr = text "DEF"
828 -- Find things in the BCEnv (the what's-on-the-stack-env)
829 -- See comment preceding pushAtom for precise meaning of env contents
830 --lookupBCEnv :: BCEnv -> Id -> Int
832 -- = case lookupFM env nm of
833 -- Nothing -> pprPanic "lookupBCEnv"
834 -- (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
837 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
838 lookupBCEnv_maybe = lookupFM
841 -- When I push one of these on the stack, how much does Sp move by?
842 taggedSizeW :: PrimRep -> Int
844 | isFollowableRep pr = 1
845 | otherwise = 1{-the tag-} + getPrimRepSize pr
848 -- The plain size of something, without tag.
849 untaggedSizeW :: PrimRep -> Int
851 | isFollowableRep pr = 1
852 | otherwise = getPrimRepSize pr
855 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
856 taggedIdSizeW = taggedSizeW . typePrimRep . idType
857 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
859 unboxedTupleException :: a
860 unboxedTupleException
861 = throwDyn (Panic "bytecode generator can't handle unboxed tuples")
865 %************************************************************************
867 \subsection{The bytecode generator's monad}
869 %************************************************************************
873 = BcM_State { bcos :: [ProtoBCO Name], -- accumulates completed BCOs
874 nextlabel :: Int } -- for generating local labels
876 type BcM result = BcM_State -> (result, BcM_State)
878 runBc :: BcM_State -> BcM () -> BcM_State
879 runBc init_st m = case m init_st of { (r,st) -> st }
881 thenBc :: BcM a -> (a -> BcM b) -> BcM b
883 = case expr st of { (result, st') -> cont result st' }
885 thenBc_ :: BcM a -> BcM b -> BcM b
887 = case expr st of { (result, st') -> cont st' }
889 returnBc :: a -> BcM a
890 returnBc result st = (result, st)
892 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
893 mapBc f [] = returnBc []
895 = f x `thenBc` \ r ->
896 mapBc f xs `thenBc` \ rs ->
899 emitBc :: ProtoBCO Name -> BcM ()
901 = ((), st{bcos = bco : bcos st})
903 getLabelBc :: BcM Int
905 = (nextlabel st, st{nextlabel = 1 + nextlabel st})