[project @ 2001-03-08 12:07:38 by simonpj]
[ghc-hetmet.git] / ghc / compiler / ghci / ByteCodeGen.lhs
1 %
2 % (c) The University of Glasgow 2000
3 %
4 \section[ByteCodeGen]{Generate bytecode from Core}
5
6 \begin{code}
7 module ByteCodeGen ( UnlinkedBCO, UnlinkedBCOExpr, ItblEnv, ClosureEnv, HValue,
8                      filterNameMap,
9                      byteCodeGen, coreExprToBCOs
10                    ) where
11
12 #include "HsVersions.h"
13
14 import Outputable
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 )
22 import CoreSyn
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 )
48
49 import List             ( intersperse, sortBy )
50 import Foreign          ( Ptr(..), mallocBytes )
51 import Addr             ( Addr(..), addrToInt, writeCharOffAddr )
52 import CTypes           ( CInt )
53 import Exception        ( throwDyn )
54
55 import PrelBase         ( Int(..) )
56 import PrelGHC          ( ByteArray# )
57 import IOExts           ( unsafePerformIO )
58 import PrelIOBase       ( IO(..) )
59
60 \end{code}
61
62 %************************************************************************
63 %*                                                                      *
64 \subsection{Functions visible from outside this module.}
65 %*                                                                      *
66 %************************************************************************
67
68 \begin{code}
69
70 byteCodeGen :: DynFlags
71             -> [CoreBind] 
72             -> [TyCon] -> [Class]
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
78
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
86
87         dumpIfSet_dyn dflags Opt_D_dump_BCOs
88            "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
89
90         bcos <- mapM assembleBCO proto_bcos
91
92         return (bcos, itblenv)
93         
94
95 -- Returns: (the root BCO for this expression, 
96 --           a list of auxilary BCOs resulting from compiling closures)
97 coreExprToBCOs :: DynFlags
98                -> CoreExpr
99                -> IO UnlinkedBCOExpr
100 coreExprToBCOs dflags expr
101  = do showPass dflags "ByteCodeGen"
102
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
108
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)))
114
115       let root_proto_bco 
116              = case filter ((== invented_name).nameOfProtoBCO) all_proto_bcos of
117                   [root_bco] -> root_bco
118           auxiliary_proto_bcos
119              = filter ((/= invented_name).nameOfProtoBCO) all_proto_bcos
120
121       auxiliary_bcos <- mapM assembleBCO auxiliary_proto_bcos
122       root_bco <- assembleBCO root_proto_bco
123
124       return (root_bco, auxiliary_bcos)
125 \end{code}
126
127 %************************************************************************
128 %*                                                                      *
129 \subsection{Compilation schema for the bytecode generator.}
130 %*                                                                      *
131 %************************************************************************
132
133 \begin{code}
134
135 type BCInstrList = OrdList BCInstr
136
137 type Sequel = Int       -- back off to this depth before ENTER
138
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
142
143 ppBCEnv :: BCEnv -> SDoc
144 ppBCEnv p
145    = text "begin-env"
146      $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
147      $$ text "end-env"
148      where
149         pp_one (var, offset) = int offset <> colon <+> ppr var
150         cmp_snd x y = compare (snd x) (snd y)
151
152 -- Create a BCO and do a spot of peephole optimisation on the insns
153 -- at the same time.
154 mkProtoBCO nm instrs_ordlist origin
155    = ProtoBCO nm maybe_with_stack_check origin
156      where
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" 
167                       (int stack_overest)
168            | stack_overest >= iNTERP_STACK_CHECK_THRESH
169            = (STKCHECK stack_overest) : peep_d
170            | otherwise
171            = peep_d     -- the supposedly common case
172              
173         stack_overest = sum (map bciStackUse peep_d)
174                         + 10 {- just to be really really sure -}
175
176
177         -- Merge local pushes
178         peep_d = peep (fromOL instrs_ordlist)
179
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
184         peep (i:rest)
185            = i : peep rest
186         peep []
187            = []
188
189
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.
194
195 schemeR :: Bool -> (Id, AnnExpr Id VarSet) -> BcM ()
196 schemeR is_top (nm, rhs) 
197 {-
198    | trace (showSDoc (
199               (char ' '
200                $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
201                $$ pprCoreExpr (deAnnotate rhs)
202                $$ char ' '
203               ))) False
204    = undefined
205 -}
206    | otherwise
207    = schemeR_wrk is_top rhs nm (collect [] rhs)
208
209
210 collect xs (_, AnnNote note e)
211    = collect xs 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)
216
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))
222      --)
223
224    | otherwise
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)
231      in
232      schemeE szw_args 0 p_init body             `thenBc` \ body_code ->
233      emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) 
234                                      (Right original_body))
235
236      where
237         maybe_toplevel_null_con_rhs
238            | is_top && null args
239            = case snd body of
240                 AnnVar v_wrk 
241                    -> case isDataConId_maybe v_wrk of
242                          Nothing -> Nothing
243                          Just dc_wrk |  nm == dataConWrapId dc_wrk
244                                      -> Just dc_wrk
245                                      |  otherwise 
246                                      -> Nothing
247                 other -> Nothing
248            | otherwise
249            = Nothing
250
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))
257
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
261
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))
268
269    | otherwise
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
275    where
276       v_rep = typePrimRep (idType v)
277
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
284
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
288          n     = length xs
289          fvss  = map (filter (not.isTyVar).varSetElems.fst) rhss
290
291          -- Sizes of tagged free vars, + 1 for the fn
292          sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
293
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)))
299          d'    = d + n
300
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))
304
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)
312                     -> push_code `appOL`
313                        buildThunk (dd+pushed_szw) (fvs, size, id, off)
314
315          thunkCode = concatOL (map (buildThunk d') infos)
316          allocCode = toOL (map ALLOC sizes)
317      in
318      schemeE d' s p' b                                  `thenBc`  \ bodyCode ->
319      mapBc (schemeR False) (zip xs rhss)                `thenBc_`
320      returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
321
322
323 schemeE d s p (fvs, AnnCase scrut bndr alts)
324    = let
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.
329         ret_frame_sizeW = 2
330
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)
335
336         scrut_primrep = typePrimRep (idType bndr)
337         isAlgCase
338            = case scrut_primrep of
339                 CharRep -> False ; AddrRep -> False ; WordRep -> False
340                 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
341                 VoidRep -> False ;
342                 PtrRep -> True
343                 other  -> pprPanic "ByteCodeGen.schemeE" (ppr other)
344
345         -- given an alt, return a discr and code for it.
346         codeAlt alt@(discr, binds_f, rhs)
347            | isAlgCase 
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)
353            | otherwise 
354            = ASSERT(null binds_f) 
355              schemeE d' s p' rhs        `thenBc` \ rhs_code ->
356              returnBc (my_discr alt, rhs_code)
357
358         my_discr (DEFAULT, binds, rhs) = NoDiscr
359         my_discr (DataAlt dc, binds, rhs) 
360            | isUnboxedTupleCon dc
361            = unboxedTupleException
362            | otherwise
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)
370
371         maybe_ncons 
372            | not isAlgCase = Nothing
373            | otherwise 
374            = case [dc | (DataAlt dc, _, _) <- alts] of
375                 []     -> Nothing
376                 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
377
378      in 
379      mapBc codeAlt alts                                 `thenBc` \ alt_stuff ->
380      mkMultiBranch maybe_ncons alt_stuff                `thenBc` \ alt_final ->
381      let 
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)
385      in
386      schemeE (d + ret_frame_sizeW) 
387              (d + ret_frame_sizeW) p scrut              `thenBc` \ scrut_code ->
388
389      emitBc alt_bco                                     `thenBc_`
390      returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
391
392
393 schemeE d s p (fvs, AnnNote note body)
394    = schemeE d s p body
395
396 schemeE d s p other
397    = pprPanic "ByteCodeGen.schemeE: unhandled case" 
398                (pprCoreExpr (deAnnotate other))
399
400
401 -- Compile code to do a tail call.  Three cases:
402 --
403 -- 1.  A nullary constructor.  Push its closure on the stack 
404 --     and SLIDE and RETURN.
405 --
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.
409 --
410 -- 3.  Otherwise, it must be a function call.  Push the args
411 --     right to left, SLIDE and ENTER.
412
413 schemeT :: Int          -- Stack depth
414         -> Sequel       -- Sequel depth
415         -> BCEnv        -- stack env
416         -> AnnExpr Id VarSet 
417         -> BCInstrList
418
419 schemeT d s p app
420 --   | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
421 --   = panic "schemeT ?!?!"
422
423    -- Handle case 1
424    | is_con_call && null args_r_to_l
425    = (PUSH_G (Left (getName con)) `consOL` mkSLIDE 1 (d-s))
426      `snocOL` ENTER
427
428    -- Cases 2 and 3
429    | otherwise
430    = if   is_con_call && isUnboxedTupleCon con
431      then unboxedTupleException
432      else code
433
434      where
435          -- Extract the args (R->L) and fn
436          (args_r_to_l_raw, fn) = chomp app
437          chomp expr
438             = case snd expr of
439                  AnnVar v    -> ([], v)
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)))
444          
445          args_r_to_l = filter (not.isTypeAtom) args_r_to_l_raw
446          isTypeAtom (AnnType _) = True
447          isTypeAtom _           = False
448
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
454
455          args_final_r_to_l
456             | not is_con_call
457             = args_r_to_l
458             | otherwise
459             = filter (not.isPtr) args_r_to_l ++ filter isPtr args_r_to_l
460               where isPtr = isFollowableRep . atomRep
461
462          -- make code to push the args and then do the SLIDE-ENTER thing
463          code = do_pushery d args_final_r_to_l
464
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
468
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
472          do_pushery d []
473             = case maybe_dcon of
474                  Just con -> PACK con narg_words `consOL` (
475                              mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
476                  Nothing
477                     -> let (push, arg_words) = pushAtom True d p (AnnVar fn)
478                        in  push 
479                            `appOL` mkSLIDE (narg_words+arg_words) 
480                                            (d - s - narg_words)
481                            `snocOL` ENTER
482
483 mkSLIDE n d 
484    = if d == 0 then nilOL else unitOL (SLIDE n d)
485
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)))
492
493
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.
498 --
499 -- Supposing a constructor in the heap has layout
500 --
501 --      Itbl p_1 ... p_i np_1 ... np_j
502 --
503 -- then we add to the stack, shown growing down, the following:
504 --
505 --    (previous stack)
506 --         p_i
507 --         ...
508 --         p_1
509 --         np_j
510 --         tag_for(np_j)
511 --         ..
512 --         np_1
513 --         tag_for(np_1)
514 --
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.
517
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')
525      --       ++ "\n") (
526      (code_p `appOL` code_np, d', p')
527      --)
528      where
529         -- vars with reps
530         vreps = [(var, typePrimRep (idType var)) | var <- vars]
531
532         -- ptrs and nonptrs, forward
533         vreps_p  = filter (isFollowableRep.snd) vreps
534         vreps_np = filter (not.isFollowableRep.snd) vreps
535
536         -- the order in which we will augment the environment
537         vreps_env = reverse vreps_p ++ reverse vreps_np
538
539         -- new env and depth
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
544
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)
549
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)
555            = case npr of
556                 IntRep -> approved ; FloatRep -> approved
557                 DoubleRep -> approved ; AddrRep -> approved
558                 CharRep -> approved
559                 _ -> pprPanic "ByteCodeGen.mkUnpackCode" (ppr npr)
560              where
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
565
566
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).
571 --
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).
581 --
582 -- Blargh.  JRS 001206
583 --
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.
590
591 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
592 pushAtom tagged d p (AnnVar v)
593
594    | idPrimRep v == VoidRep
595    = ASSERT(tagged)
596      (unitOL (PUSH_TAG 0), 1)
597
598    | Just primop <- isPrimOpId_maybe v
599    = case primop of
600         CCallOp _ -> panic "pushAtom: byte code generator can't handle CCalls"
601         other     -> (unitOL (PUSH_G (Right primop)), 1)
602
603    | otherwise
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)
612                   where
613                      cmp_snd x y = compare (snd x) (snd y)
614          str' = if str == str then str else str
615
616          result
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)
620
621          nm = case isDataConId_maybe v of
622                  Just c  -> getName c
623                  Nothing -> getName v
624
625          sz_t   = taggedIdSizeW v
626          sz_u   = untaggedIdSizeW v
627          nwords = if tagged then sz_t else sz_u
628      in
629          --trace str'
630          result
631
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)
635
636 pushAtom False d p (AnnLit lit)
637    = case lit of
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
644      where
645         code rep
646            = let size_host_words = untaggedSizeW rep
647              in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
648
649         pushStr s 
650            = let mallocvilleAddr
651                     = case s of
652                          CharStr s i -> A# s
653
654                          FastString _ l ba -> 
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 
659                             -- at the same time.
660                             let n = I# l
661                             -- CAREFUL!  Chars are 32 bits in ghc 4.09+
662                             in  unsafePerformIO (
663                                    do (Ptr a#) <- mallocBytes (n+1)
664                                       strncpy (Ptr a#) ba (fromIntegral n)
665                                       writeCharOffAddr (A# a#) n '\0'
666                                       return (A# a#)
667                                    )
668                          _ -> panic "StgInterp.lit2expr: unhandled string constant type"
669
670                  addrLit 
671                     = MachInt (toInteger (addrToInt mallocvilleAddr))
672              in
673                 -- Get the addr on the stack, untaggedly
674                 (unitOL (PUSH_UBX addrLit 1), 1)
675
676
677
678
679
680 pushAtom tagged d p (AnnApp f (_, AnnType _))
681    = pushAtom tagged d p (snd f)
682
683 pushAtom tagged d p (AnnNote note e)
684    = pushAtom tagged d p (snd e)
685
686 pushAtom tagged d p (AnnLam x e) 
687    | isTyVar x 
688    = pushAtom tagged d p (snd e)
689
690 pushAtom tagged d p other
691    = pprPanic "ByteCodeGen.pushAtom" 
692               (pprCoreExpr (deAnnotate (undefined, other)))
693
694 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
695
696
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)] 
704               -> BcM 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)
710
711          mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
712          mkTree [] range_lo range_hi = returnBc the_default
713
714          mkTree [val] range_lo range_hi
715             | range_lo `eqAlt` range_hi 
716             = returnBc (snd val)
717             | otherwise
718             = getLabelBc                                `thenBc` \ label_neq ->
719               returnBc (mkTestEQ (fst val) label_neq 
720                         `consOL` (snd val
721                         `appOL`   unitOL (LABEL label_neq)
722                         `appOL`   the_default))
723
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)
729               in
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
734                         `consOL` (code_lo
735                         `appOL`   unitOL (LABEL label_geq)
736                         `appOL`   code_hi))
737  
738          the_default 
739             = case d_way of [] -> unitOL CASEFAIL
740                             [(_, def)] -> def
741
742          -- None of these will be needed if there are no non-default alts
743          (mkTestLT, mkTestEQ, init_lo, init_hi)
744             | null notd_ways
745             = panic "mkMultiBranch: awesome foursome"
746             | otherwise
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,
750                             DiscrI minBound,
751                             DiscrI maxBound );
752               DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
753                             \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
754                             DiscrF minF,
755                             DiscrF maxF );
756               DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
757                             \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
758                             DiscrD minD,
759                             DiscrD maxD );
760               DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
761                             \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
762                             DiscrP algMinBound,
763                             DiscrP algMaxBound )
764               }
765
766          (algMinBound, algMaxBound)
767             = case maybe_ncons of
768                  Just n  -> (0, n - 1)
769                  Nothing -> (minBound, maxBound)
770
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
776          _           `eqAlt` _           = False
777
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
783          _           `leAlt` _           = False
784
785          isNoDiscr NoDiscr = True
786          isNoDiscr _       = False
787
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
792
793          -- same snotty comment applies to the following
794          minF, maxF :: Float
795          minD, maxD :: Double
796          minF = -1.0e37
797          maxF =  1.0e37
798          minD = -1.0e308
799          maxD =  1.0e308
800      in
801          mkTree notd_ways init_lo init_hi
802
803 \end{code}
804
805 %************************************************************************
806 %*                                                                      *
807 \subsection{Supporting junk for the compilation schemes}
808 %*                                                                      *
809 %************************************************************************
810
811 \begin{code}
812
813 -- Describes case alts
814 data Discr 
815    = DiscrI Int
816    | DiscrF Float
817    | DiscrD Double
818    | DiscrP Int
819    | NoDiscr
820
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"
827
828
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
832 --lookupBCEnv env nm
833 --   = case lookupFM env nm of
834 --        Nothing -> pprPanic "lookupBCEnv" 
835 --                            (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
836 --        Just xx -> xx
837
838 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
839 lookupBCEnv_maybe = lookupFM
840
841
842 -- When I push one of these on the stack, how much does Sp move by?
843 taggedSizeW :: PrimRep -> Int
844 taggedSizeW pr
845    | isFollowableRep pr = 1
846    | otherwise          = 1{-the tag-} + getPrimRepSize pr
847
848
849 -- The plain size of something, without tag.
850 untaggedSizeW :: PrimRep -> Int
851 untaggedSizeW pr
852    | isFollowableRep pr = 1
853    | otherwise          = getPrimRepSize pr
854
855
856 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
857 taggedIdSizeW   = taggedSizeW   . typePrimRep . idType
858 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
859
860 unboxedTupleException :: a
861 unboxedTupleException 
862    = throwDyn (Panic "bytecode generator can't handle unboxed tuples")
863
864 \end{code}
865
866 %************************************************************************
867 %*                                                                      *
868 \subsection{The bytecode generator's monad}
869 %*                                                                      *
870 %************************************************************************
871
872 \begin{code}
873 data BcM_State 
874    = BcM_State { bcos      :: [ProtoBCO Name],  -- accumulates completed BCOs
875                  nextlabel :: Int }             -- for generating local labels
876
877 type BcM result = BcM_State -> (result, BcM_State)
878
879 runBc :: BcM_State -> BcM () -> BcM_State
880 runBc init_st m = case m init_st of { (r,st) -> st }
881
882 thenBc :: BcM a -> (a -> BcM b) -> BcM b
883 thenBc expr cont st
884   = case expr st of { (result, st') -> cont result st' }
885
886 thenBc_ :: BcM a -> BcM b -> BcM b
887 thenBc_ expr cont st
888   = case expr st of { (result, st') -> cont st' }
889
890 returnBc :: a -> BcM a
891 returnBc result st = (result, st)
892
893 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
894 mapBc f []     = returnBc []
895 mapBc f (x:xs)
896   = f x          `thenBc` \ r  ->
897     mapBc f xs   `thenBc` \ rs ->
898     returnBc (r:rs)
899
900 emitBc :: ProtoBCO Name -> BcM ()
901 emitBc bco st
902    = ((), st{bcos = bco : bcos st})
903
904 getLabelBc :: BcM Int
905 getLabelBc st
906    = (nextlabel st, st{nextlabel = 1 + nextlabel st})
907
908 \end{code}