[project @ 2001-02-05 17:29:41 by sewardj]
[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                      linkIModules, linkIExpr
11                    ) where
12
13 #include "HsVersions.h"
14
15 import Outputable
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 )
23 import CoreSyn
24 import PprCore          ( pprCoreExpr )
25 import Literal          ( Literal(..), literalPrimRep )
26 import PrimRep          ( PrimRep(..) )
27 import PrimOp           ( PrimOp(..)  )
28 import CoreFVs          ( freeVars )
29 import Type             ( typePrimRep )
30 import DataCon          ( dataConTag, fIRST_TAG, dataConTyCon, dataConWrapId )
31 import TyCon            ( TyCon, tyConFamilySize )
32 import Class            ( Class, classTyCon )
33 import Util             ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem )
34 import Var              ( isTyVar )
35 import VarSet           ( VarSet, varSetElems )
36 import PrimRep          ( getPrimRepSize, isFollowableRep )
37 import CmdLineOpts      ( DynFlags, DynFlag(..) )
38 import ErrUtils         ( showPass, dumpIfSet_dyn )
39 import Unique           ( mkPseudoUnique3 )
40 import FastString       ( FastString(..) )
41 import PprType          ( pprType )
42 import ByteCodeInstr    ( BCInstr(..), ProtoBCO(..), nameOfProtoBCO )
43 import ByteCodeItbls    ( ItblEnv, mkITbls )
44 import ByteCodeLink     ( UnlinkedBCO, UnlinkedBCOExpr, assembleBCO,
45                           ClosureEnv, HValue, linkSomeBCOs, filterNameMap )
46
47 import List             ( intersperse, sortBy )
48 import Foreign          ( Ptr(..), mallocBytes )
49 import Addr             ( Addr(..), addrToInt, writeCharOffAddr )
50 import CTypes           ( CInt )
51
52 import PrelBase         ( Int(..) )
53 import PrelGHC          ( ByteArray# )
54 import IOExts           ( unsafePerformIO )
55 import PrelIOBase       ( IO(..) )
56
57 \end{code}
58
59 %************************************************************************
60 %*                                                                      *
61 \subsection{Functions visible from outside this module.}
62 %*                                                                      *
63 %************************************************************************
64
65 \begin{code}
66
67 byteCodeGen :: DynFlags
68             -> [CoreBind] 
69             -> [TyCon] -> [Class]
70             -> IO ([UnlinkedBCO], ItblEnv)
71 byteCodeGen dflags binds local_tycons local_classes
72    = do showPass dflags "ByteCodeGen"
73         let tycs = local_tycons ++ map classTyCon local_classes
74         itblenv <- mkITbls tycs
75
76         let flatBinds = concatMap getBind binds
77             getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
78             getBind (Rec binds)       = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
79             final_state = runBc (BcM_State [] 0) 
80                                 (mapBc (schemeR True) flatBinds
81                                         `thenBc_` returnBc ())
82             (BcM_State proto_bcos final_ctr) = final_state
83
84         dumpIfSet_dyn dflags Opt_D_dump_BCOs
85            "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
86
87         bcos <- mapM assembleBCO proto_bcos
88
89         return (bcos, itblenv)
90         
91
92 -- Returns: (the root BCO for this expression, 
93 --           a list of auxilary BCOs resulting from compiling closures)
94 coreExprToBCOs :: DynFlags
95                -> CoreExpr
96                -> IO UnlinkedBCOExpr
97 coreExprToBCOs dflags expr
98  = do showPass dflags "ByteCodeGen"
99
100       -- create a totally bogus name for the top-level BCO; this
101       -- should be harmless, since it's never used for anything
102       let invented_name = mkSysLocalName (mkPseudoUnique3 0) SLIT("Expr-Top-Level")
103       let invented_id   = mkVanillaId invented_name (panic "invented_id's type")
104
105       let (BcM_State all_proto_bcos final_ctr) 
106              = runBc (BcM_State [] 0) 
107                      (schemeR True (invented_id, freeVars expr))
108       dumpIfSet_dyn dflags Opt_D_dump_BCOs
109          "Proto-bcos" (vcat (intersperse (char ' ') (map ppr all_proto_bcos)))
110
111       let root_proto_bco 
112              = case filter ((== invented_name).nameOfProtoBCO) all_proto_bcos of
113                   [root_bco] -> root_bco
114           auxiliary_proto_bcos
115              = filter ((/= invented_name).nameOfProtoBCO) all_proto_bcos
116
117       auxiliary_bcos <- mapM assembleBCO auxiliary_proto_bcos
118       root_bco <- assembleBCO root_proto_bco
119
120       return (root_bco, auxiliary_bcos)
121
122
123 -- Linking stuff
124 linkIModules :: ItblEnv    -- incoming global itbl env; returned updated
125              -> ClosureEnv -- incoming global closure env; returned updated
126              -> [([UnlinkedBCO], ItblEnv)]
127              -> IO ([HValue], ItblEnv, ClosureEnv)
128 linkIModules gie gce mods 
129    = do let (bcoss, ies) = unzip mods
130             bcos = concat bcoss
131             final_gie = foldr plusFM gie ies
132         (final_gce, linked_bcos) <- linkSomeBCOs final_gie gce bcos
133         return (linked_bcos, final_gie, final_gce)
134
135
136 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
137           -> IO HValue    -- IO BCO# really
138 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
139    = do (aux_ce, _) <- linkSomeBCOs ie ce aux_ul_bcos
140         (_, [root_bco]) <- linkSomeBCOs ie aux_ce [root_ul_bco]
141         return root_bco
142 \end{code}
143
144 %************************************************************************
145 %*                                                                      *
146 \subsection{Compilation schema for the bytecode generator.}
147 %*                                                                      *
148 %************************************************************************
149
150 \begin{code}
151
152 type BCInstrList = OrdList BCInstr
153
154 type Sequel = Int       -- back off to this depth before ENTER
155
156 -- Maps Ids to the offset from the stack _base_ so we don't have
157 -- to mess with it after each push/pop.
158 type BCEnv = FiniteMap Id Int   -- To find vars on the stack
159
160 ppBCEnv :: BCEnv -> SDoc
161 ppBCEnv p
162    = text "begin-env"
163      $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
164      $$ text "end-env"
165      where
166         pp_one (var, offset) = int offset <> colon <+> ppr var
167         cmp_snd x y = compare (snd x) (snd y)
168
169 -- Create a BCO and do a spot of peephole optimisation on the insns
170 -- at the same time.
171 mkProtoBCO nm instrs_ordlist origin
172    = ProtoBCO nm (peep (fromOL instrs_ordlist)) origin
173      where
174         peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
175            = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
176         peep (PUSH_L off1 : PUSH_L off2 : rest)
177            = PUSH_LL off1 (off2-1) : peep rest
178         peep (i:rest)
179            = i : peep rest
180         peep []
181            = []
182
183
184 -- Compile code for the right hand side of a let binding.
185 -- Park the resulting BCO in the monad.  Also requires the
186 -- variable to which this value was bound, so as to give the
187 -- resulting BCO a name.  Bool indicates top-levelness.
188
189 schemeR :: Bool -> (Id, AnnExpr Id VarSet) -> BcM ()
190 schemeR is_top (nm, rhs) 
191 {-
192    | trace (showSDoc (
193               (char ' '
194                $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
195                $$ pprCoreExpr (deAnnotate rhs)
196                $$ char ' '
197               ))) False
198    = undefined
199 -}
200    | otherwise
201    = schemeR_wrk is_top rhs nm (collect [] rhs)
202
203
204 collect xs (_, AnnNote note e)
205    = collect xs e
206 collect xs (_, AnnLam x e) 
207    = collect (if isTyVar x then xs else (x:xs)) e
208 collect xs not_lambda
209    = (reverse xs, not_lambda)
210
211 schemeR_wrk is_top original_body nm (args, body)
212    | Just dcon <- maybe_toplevel_null_con_rhs
213    = --trace ("nullary constructor! " ++ showSDocDebug (ppr nm)) (
214      emitBc (mkProtoBCO (getName nm) (toOL [PACK dcon 0, ENTER])
215                                      (Right original_body))
216      --)
217
218    | otherwise
219    = let fvs       = filter (not.isTyVar) (varSetElems (fst original_body))
220          all_args  = reverse args ++ fvs
221          szsw_args = map taggedIdSizeW all_args
222          szw_args  = sum szsw_args
223          p_init    = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
224          argcheck  = unitOL (ARGCHECK szw_args)
225      in
226      schemeE szw_args 0 p_init body             `thenBc` \ body_code ->
227      emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) 
228                                      (Right original_body))
229
230      where
231         maybe_toplevel_null_con_rhs
232            | is_top && null args
233            = case snd body of
234                 AnnVar v_wrk 
235                    -> case isDataConId_maybe v_wrk of
236                          Nothing -> Nothing
237                          Just dc_wrk |  nm == dataConWrapId dc_wrk
238                                      -> Just dc_wrk
239                                      |  otherwise 
240                                      -> Nothing
241                 other -> Nothing
242            | otherwise
243            = Nothing
244
245 -- Let szsw be the sizes in words of some items pushed onto the stack,
246 -- which has initial depth d'.  Return the values which the stack environment
247 -- should map these items to.
248 mkStackOffsets :: Int -> [Int] -> [Int]
249 mkStackOffsets original_depth szsw
250    = map (subtract 1) (tail (scanl (+) original_depth szsw))
251
252 -- Compile code to apply the given expression to the remaining args
253 -- on the stack, returning a HNF.
254 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
255
256 -- Delegate tail-calls to schemeT.
257 schemeE d s p e@(fvs, AnnApp f a) 
258    = returnBc (schemeT d s p (fvs, AnnApp f a))
259 schemeE d s p e@(fvs, AnnVar v)
260    | isFollowableRep v_rep
261    = returnBc (schemeT d s p (fvs, AnnVar v))
262
263    | otherwise
264    = -- returning an unboxed value.  Heave it on the stack, SLIDE, and RETURN.
265      let (push, szw) = pushAtom True d p (AnnVar v)
266      in  returnBc (push                         -- value onto stack
267                    `appOL`  mkSLIDE szw (d-s)   -- clear to sequel
268                    `snocOL` RETURN v_rep)       -- go
269    where
270       v_rep = typePrimRep (idType v)
271
272 schemeE d s p (fvs, AnnLit literal)
273    = let (push, szw) = pushAtom True d p (AnnLit literal)
274          l_rep = literalPrimRep literal
275      in  returnBc (push                         -- value onto stack
276                    `appOL`  mkSLIDE szw (d-s)   -- clear to sequel
277                    `snocOL` RETURN l_rep)       -- go
278
279 schemeE d s p (fvs, AnnLet binds b)
280    = let (xs,rhss) = case binds of AnnNonRec x rhs  -> ([x],[rhs])
281                                    AnnRec xs_n_rhss -> unzip xs_n_rhss
282          n     = length xs
283          fvss  = map (filter (not.isTyVar).varSetElems.fst) rhss
284
285          -- Sizes of tagged free vars, + 1 for the fn
286          sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
287
288          -- This p', d' defn is safe because all the items being pushed
289          -- are ptrs, so all have size 1.  d' and p' reflect the stack
290          -- after the closures have been allocated in the heap (but not
291          -- filled in), and pointers to them parked on the stack.
292          p'    = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
293          d'    = d + n
294
295          infos = zipE4 fvss sizes xs [n, n-1 .. 1]
296          zipE  = zipEqual "schemeE"
297          zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
298
299          -- ToDo: don't build thunks for things with no free variables
300          buildThunk dd ([], size, id, off)
301             = PUSH_G (Left (getName id))
302               `consOL` unitOL (MKAP (off+size-1) size)
303          buildThunk dd ((fv:fvs), size, id, off)
304             = case pushAtom True dd p' (AnnVar fv) of
305                  (push_code, pushed_szw)
306                     -> push_code `appOL`
307                        buildThunk (dd+pushed_szw) (fvs, size, id, off)
308
309          thunkCode = concatOL (map (buildThunk d') infos)
310          allocCode = toOL (map ALLOC sizes)
311      in
312      schemeE d' s p' b                                  `thenBc`  \ bodyCode ->
313      mapBc (schemeR False) (zip xs rhss)                `thenBc_`
314      returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
315
316
317 schemeE d s p (fvs, AnnCase scrut bndr alts)
318    = let
319         -- Top of stack is the return itbl, as usual.
320         -- underneath it is the pointer to the alt_code BCO.
321         -- When an alt is entered, it assumes the returned value is
322         -- on top of the itbl.
323         ret_frame_sizeW = 2
324
325         -- Env and depth in which to compile the alts, not including
326         -- any vars bound by the alts themselves
327         d' = d + ret_frame_sizeW + taggedIdSizeW bndr
328         p' = addToFM p bndr (d' - 1)
329
330         scrut_primrep = typePrimRep (idType bndr)
331         isAlgCase
332            = case scrut_primrep of
333                 CharRep -> False ; AddrRep -> False ; WordRep -> False
334                 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
335                 PtrRep -> True
336                 other  -> pprPanic "ByteCodeGen.schemeE" (ppr other)
337
338         -- given an alt, return a discr and code for it.
339         codeAlt alt@(discr, binds_f, rhs)
340            | isAlgCase 
341            = let (unpack_code, d_after_unpack, p_after_unpack)
342                     = mkUnpackCode binds_f d' p'
343              in  schemeE d_after_unpack s p_after_unpack rhs
344                                         `thenBc` \ rhs_code -> 
345                  returnBc (my_discr alt, unpack_code `appOL` rhs_code)
346            | otherwise 
347            = ASSERT(null binds_f) 
348              schemeE d' s p' rhs        `thenBc` \ rhs_code ->
349              returnBc (my_discr alt, rhs_code)
350
351         my_discr (DEFAULT, binds, rhs)  = NoDiscr
352         my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc - fIRST_TAG)
353         my_discr (LitAlt l, binds, rhs)
354            = case l of MachInt i     -> DiscrI (fromInteger i)
355                        MachFloat r   -> DiscrF (fromRational r)
356                        MachDouble r  -> DiscrD (fromRational r)
357                        MachChar i    -> DiscrI i
358                        _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
359
360         maybe_ncons 
361            | not isAlgCase = Nothing
362            | otherwise 
363            = case [dc | (DataAlt dc, _, _) <- alts] of
364                 []     -> Nothing
365                 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
366
367      in 
368      mapBc codeAlt alts                                 `thenBc` \ alt_stuff ->
369      mkMultiBranch maybe_ncons alt_stuff                `thenBc` \ alt_final ->
370      let 
371          alt_final_ac = ARGCHECK (taggedIdSizeW bndr) `consOL` alt_final
372          alt_bco_name = getName bndr
373          alt_bco      = mkProtoBCO alt_bco_name alt_final_ac (Left alts)
374      in
375      schemeE (d + ret_frame_sizeW) 
376              (d + ret_frame_sizeW) p scrut              `thenBc` \ scrut_code ->
377
378      emitBc alt_bco                                     `thenBc_`
379      returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
380
381
382 schemeE d s p (fvs, AnnNote note body)
383    = schemeE d s p body
384
385 schemeE d s p other
386    = pprPanic "ByteCodeGen.schemeE: unhandled case" 
387                (pprCoreExpr (deAnnotate other))
388
389
390 -- Compile code to do a tail call.  Three cases:
391 --
392 -- 1.  A nullary constructor.  Push its closure on the stack 
393 --     and SLIDE and RETURN.
394 --
395 -- 2.  Application of a non-nullary constructor, by defn saturated.
396 --     Split the args into ptrs and non-ptrs, and push the nonptrs, 
397 --     then the ptrs, and then do PACK and RETURN.
398 --
399 -- 3.  Otherwise, it must be a function call.  Push the args
400 --     right to left, SLIDE and ENTER.
401
402 schemeT :: Int          -- Stack depth
403         -> Sequel       -- Sequel depth
404         -> BCEnv        -- stack env
405         -> AnnExpr Id VarSet 
406         -> BCInstrList
407
408 schemeT d s p app
409 --   | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
410 --   = panic "schemeT ?!?!"
411
412    -- Handle case 1
413    | is_con_call && null args_r_to_l
414    = (PUSH_G (Left (getName con)) `consOL` mkSLIDE 1 (d-s))
415      `snocOL` ENTER
416
417    -- Cases 2 and 3
418    | otherwise
419    = code
420
421      where
422          -- Extract the args (R->L) and fn
423          (args_r_to_l_raw, fn) = chomp app
424          chomp expr
425             = case snd expr of
426                  AnnVar v    -> ([], v)
427                  AnnApp f a  -> case chomp f of (az, f) -> (snd a:az, f)
428                  AnnNote n e -> chomp e
429                  other       -> pprPanic "schemeT" 
430                                    (ppr (deAnnotate (panic "schemeT.chomp", other)))
431          
432          args_r_to_l = filter (not.isTypeAtom) args_r_to_l_raw
433          isTypeAtom (AnnType _) = True
434          isTypeAtom _           = False
435
436          -- decide if this is a constructor call, and rearrange
437          -- args appropriately.
438          maybe_dcon  = isDataConId_maybe fn
439          is_con_call = case maybe_dcon of Nothing -> False; Just _ -> True
440          (Just con)  = maybe_dcon
441
442          args_final_r_to_l
443             | not is_con_call
444             = args_r_to_l
445             | otherwise
446             = filter (not.isPtr) args_r_to_l ++ filter isPtr args_r_to_l
447               where isPtr = isFollowableRep . atomRep
448
449          -- make code to push the args and then do the SLIDE-ENTER thing
450          code = do_pushery d args_final_r_to_l
451
452          tag_when_push = not is_con_call
453          narg_words    = sum (map (get_arg_szw . atomRep) args_r_to_l)
454          get_arg_szw   = if tag_when_push then taggedSizeW else untaggedSizeW
455
456          do_pushery d (arg:args)
457             = let (push, arg_words) = pushAtom tag_when_push d p arg
458               in  push `appOL` do_pushery (d+arg_words) args
459          do_pushery d []
460             = case maybe_dcon of
461                  Just con -> PACK con narg_words `consOL` (
462                              mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
463                  Nothing
464                     -> let (push, arg_words) = pushAtom True d p (AnnVar fn)
465                        in  push 
466                            `appOL` mkSLIDE (narg_words+arg_words) 
467                                            (d - s - narg_words)
468                            `snocOL` ENTER
469
470 mkSLIDE n d 
471    = if d == 0 then nilOL else unitOL (SLIDE n d)
472
473 atomRep (AnnVar v)    = typePrimRep (idType v)
474 atomRep (AnnLit l)    = literalPrimRep l
475 atomRep (AnnNote n b) = atomRep (snd b)
476 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
477 atomRep (AnnLam x e) | isTyVar x = atomRep (snd e)
478 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
479
480
481 -- Make code to unpack the top-of-stack constructor onto the stack, 
482 -- adding tags for the unboxed bits.  Takes the PrimReps of the 
483 -- constructor's arguments.  off_h and off_s are travelling offsets
484 -- along the constructor and the stack.
485 --
486 -- Supposing a constructor in the heap has layout
487 --
488 --      Itbl p_1 ... p_i np_1 ... np_j
489 --
490 -- then we add to the stack, shown growing down, the following:
491 --
492 --    (previous stack)
493 --         p_i
494 --         ...
495 --         p_1
496 --         np_j
497 --         tag_for(np_j)
498 --         ..
499 --         np_1
500 --         tag_for(np_1)
501 --
502 -- so that in the common case (ptrs only) a single UNPACK instr can
503 -- copy all the payload of the constr onto the stack with no further ado.
504
505 mkUnpackCode :: [Id]    -- constr args
506              -> Int     -- depth before unpack
507              -> BCEnv   -- env before unpack
508              -> (BCInstrList, Int, BCEnv)
509 mkUnpackCode vars d p
510    = --trace ("mkUnpackCode: " ++ showSDocDebug (ppr vars)
511      --       ++ " --> " ++ show d' ++ "\n" ++ showSDocDebug (ppBCEnv p')
512      --       ++ "\n") (
513      (code_p `appOL` code_np, d', p')
514      --)
515      where
516         -- vars with reps
517         vreps = [(var, typePrimRep (idType var)) | var <- vars]
518
519         -- ptrs and nonptrs, forward
520         vreps_p  = filter (isFollowableRep.snd) vreps
521         vreps_np = filter (not.isFollowableRep.snd) vreps
522
523         -- the order in which we will augment the environment
524         vreps_env = reverse vreps_p ++ reverse vreps_np
525
526         -- new env and depth
527         vreps_env_tszsw = map (taggedSizeW.snd) vreps_env
528         p' = addListToFM p (zip (map fst vreps_env) 
529                                 (mkStackOffsets d vreps_env_tszsw))
530         d' = d + sum vreps_env_tszsw
531
532         -- code to unpack the ptrs
533         ptrs_szw = sum (map (untaggedSizeW.snd) vreps_p)
534         code_p | null vreps_p = nilOL
535                | otherwise    = unitOL (UNPACK ptrs_szw)
536
537         -- code to unpack the nonptrs
538         vreps_env_uszw = sum (map (untaggedSizeW.snd) vreps_env)
539         code_np = do_nptrs vreps_env_uszw ptrs_szw (reverse (map snd vreps_np))
540         do_nptrs off_h off_s [] = nilOL
541         do_nptrs off_h off_s (npr:nprs)
542            = case npr of
543                 IntRep -> approved ; FloatRep -> approved
544                 DoubleRep -> approved ; AddrRep -> approved
545                 CharRep -> approved
546                 _ -> pprPanic "ByteCodeGen.mkUnpackCode" (ppr npr)
547              where
548                 approved = UPK_TAG usizeW (off_h-usizeW) off_s   `consOL` theRest
549                 theRest  = do_nptrs (off_h-usizeW) (off_s + tsizeW) nprs
550                 usizeW   = untaggedSizeW npr
551                 tsizeW   = taggedSizeW npr
552
553
554 -- Push an atom onto the stack, returning suitable code & number of
555 -- stack words used.  Pushes it either tagged or untagged, since 
556 -- pushAtom is used to set up the stack prior to copying into the
557 -- heap for both APs (requiring tags) and constructors (which don't).
558 --
559 -- NB this means NO GC between pushing atoms for a constructor and
560 -- copying them into the heap.  It probably also means that 
561 -- tail calls MUST be of the form atom{atom ... atom} since if the
562 -- expression head was allowed to be arbitrary, there could be GC
563 -- in between pushing the arg atoms and completing the head.
564 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
565 -- isn't a problem; but only if arbitrary graph construction for the
566 -- head doesn't leave this BCO, since GC might happen at the start of
567 -- each BCO (we consult doYouWantToGC there).
568 --
569 -- Blargh.  JRS 001206
570 --
571 -- NB (further) that the env p must map each variable to the highest-
572 -- numbered stack slot for it.  For example, if the stack has depth 4 
573 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
574 -- the tag in stack[5], the stack will have depth 6, and p must map v to
575 -- 5 and not to 4.  Stack locations are numbered from zero, so a depth
576 -- 6 stack has valid words 0 .. 5.
577
578 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
579 pushAtom tagged d p (AnnVar v)
580
581    | idPrimRep v == VoidRep
582    = ASSERT(tagged)
583      (unitOL (PUSH_TAG 0), 1)
584
585    | Just primop <- isPrimOpId_maybe v
586    = case primop of
587         CCallOp _ -> panic "pushAtom: byte code generator can't handle CCalls"
588         other     -> (unitOL (PUSH_G (Right primop)), 1)
589
590    | otherwise
591    = let str = "\npushAtom " ++ showSDocDebug (ppr v) 
592                ++ " :: " ++ showSDocDebug (pprType (idType v))
593                ++ ", depth = " ++ show d
594                ++ ", tagged = " ++ show tagged ++ ", env =\n" ++ 
595                showSDocDebug (ppBCEnv p)
596                ++ " --> words: " ++ show (snd result) ++ "\n" ++
597                showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
598                ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
599                   where
600                      cmp_snd x y = compare (snd x) (snd y)
601          str' = if str == str then str else str
602
603          result
604             = case lookupBCEnv_maybe p v of
605                  Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), nwords)
606                  Nothing  -> ASSERT(sz_t == 1) (unitOL (PUSH_G (Left nm)), nwords)
607
608          nm = case isDataConId_maybe v of
609                  Just c  -> getName c
610                  Nothing -> getName v
611
612          sz_t   = taggedIdSizeW v
613          sz_u   = untaggedIdSizeW v
614          nwords = if tagged then sz_t else sz_u
615      in
616          --trace str'
617          result
618
619 pushAtom True d p (AnnLit lit)
620    = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
621      in  (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
622
623 pushAtom False d p (AnnLit lit)
624    = case lit of
625         MachWord w   -> code WordRep
626         MachInt i    -> code IntRep
627         MachFloat r  -> code FloatRep
628         MachDouble r -> code DoubleRep
629         MachChar c   -> code CharRep
630         MachStr s    -> pushStr s
631      where
632         code rep
633            = let size_host_words = untaggedSizeW rep
634              in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
635
636         pushStr s 
637            = let mallocvilleAddr
638                     = case s of
639                          CharStr s i -> A# s
640
641                          FastString _ l ba -> 
642                             -- sigh, a string in the heap is no good to us.
643                             -- We need a static C pointer, since the type of 
644                             -- a string literal is Addr#.  So, copy the string 
645                             -- into C land and introduce a memory leak 
646                             -- at the same time.
647                             let n = I# l
648                             -- CAREFUL!  Chars are 32 bits in ghc 4.09+
649                             in  unsafePerformIO (
650                                    do (Ptr a#) <- mallocBytes (n+1)
651                                       strncpy (Ptr a#) ba (fromIntegral n)
652                                       writeCharOffAddr (A# a#) n '\0'
653                                       return (A# a#)
654                                    )
655                          _ -> panic "StgInterp.lit2expr: unhandled string constant type"
656
657                  addrLit 
658                     = MachInt (toInteger (addrToInt mallocvilleAddr))
659              in
660                 -- Get the addr on the stack, untaggedly
661                 (unitOL (PUSH_UBX addrLit 1), 1)
662
663
664
665
666
667 pushAtom tagged d p (AnnApp f (_, AnnType _))
668    = pushAtom tagged d p (snd f)
669
670 pushAtom tagged d p (AnnNote note e)
671    = pushAtom tagged d p (snd e)
672
673 pushAtom tagged d p (AnnLam x e) 
674    | isTyVar x 
675    = pushAtom tagged d p (snd e)
676
677 pushAtom tagged d p other
678    = pprPanic "ByteCodeGen.pushAtom" 
679               (pprCoreExpr (deAnnotate (undefined, other)))
680
681 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
682
683
684 -- Given a bunch of alts code and their discrs, do the donkey work
685 -- of making a multiway branch using a switch tree.
686 -- What a load of hassle!
687 mkMultiBranch :: Maybe Int      -- # datacons in tycon, if alg alt
688                                 -- a hint; generates better code
689                                 -- Nothing is always safe
690               -> [(Discr, BCInstrList)] 
691               -> BcM BCInstrList
692 mkMultiBranch maybe_ncons raw_ways
693    = let d_way     = filter (isNoDiscr.fst) raw_ways
694          notd_ways = naturalMergeSortLe 
695                         (\w1 w2 -> leAlt (fst w1) (fst w2))
696                         (filter (not.isNoDiscr.fst) raw_ways)
697
698          mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
699          mkTree [] range_lo range_hi = returnBc the_default
700
701          mkTree [val] range_lo range_hi
702             | range_lo `eqAlt` range_hi 
703             = returnBc (snd val)
704             | otherwise
705             = getLabelBc                                `thenBc` \ label_neq ->
706               returnBc (mkTestEQ (fst val) label_neq 
707                         `consOL` (snd val
708                         `appOL`   unitOL (LABEL label_neq)
709                         `appOL`   the_default))
710
711          mkTree vals range_lo range_hi
712             = let n = length vals `div` 2
713                   vals_lo = take n vals
714                   vals_hi = drop n vals
715                   v_mid = fst (head vals_hi)
716               in
717               getLabelBc                                `thenBc` \ label_geq ->
718               mkTree vals_lo range_lo (dec v_mid)       `thenBc` \ code_lo ->
719               mkTree vals_hi v_mid range_hi             `thenBc` \ code_hi ->
720               returnBc (mkTestLT v_mid label_geq
721                         `consOL` (code_lo
722                         `appOL`   unitOL (LABEL label_geq)
723                         `appOL`   code_hi))
724  
725          the_default 
726             = case d_way of [] -> unitOL CASEFAIL
727                             [(_, def)] -> def
728
729          -- None of these will be needed if there are no non-default alts
730          (mkTestLT, mkTestEQ, init_lo, init_hi)
731             | null notd_ways
732             = panic "mkMultiBranch: awesome foursome"
733             | otherwise
734             = case fst (head notd_ways) of {
735               DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
736                             \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
737                             DiscrI minBound,
738                             DiscrI maxBound );
739               DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
740                             \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
741                             DiscrF minF,
742                             DiscrF maxF );
743               DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
744                             \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
745                             DiscrD minD,
746                             DiscrD maxD );
747               DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
748                             \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
749                             DiscrP algMinBound,
750                             DiscrP algMaxBound )
751               }
752
753          (algMinBound, algMaxBound)
754             = case maybe_ncons of
755                  Just n  -> (0, n - 1)
756                  Nothing -> (minBound, maxBound)
757
758          (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
759          (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
760          (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
761          (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
762          NoDiscr     `eqAlt` NoDiscr     = True
763          _           `eqAlt` _           = False
764
765          (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
766          (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
767          (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
768          (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
769          NoDiscr     `leAlt` NoDiscr     = True
770          _           `leAlt` _           = False
771
772          isNoDiscr NoDiscr = True
773          isNoDiscr _       = False
774
775          dec (DiscrI i) = DiscrI (i-1)
776          dec (DiscrP i) = DiscrP (i-1)
777          dec other      = other         -- not really right, but if you
778                 -- do cases on floating values, you'll get what you deserve
779
780          -- same snotty comment applies to the following
781          minF, maxF :: Float
782          minD, maxD :: Double
783          minF = -1.0e37
784          maxF =  1.0e37
785          minD = -1.0e308
786          maxD =  1.0e308
787      in
788          mkTree notd_ways init_lo init_hi
789
790 \end{code}
791
792 %************************************************************************
793 %*                                                                      *
794 \subsection{Supporting junk for the compilation schemes}
795 %*                                                                      *
796 %************************************************************************
797
798 \begin{code}
799
800 -- Describes case alts
801 data Discr 
802    = DiscrI Int
803    | DiscrF Float
804    | DiscrD Double
805    | DiscrP Int
806    | NoDiscr
807
808 instance Outputable Discr where
809    ppr (DiscrI i) = int i
810    ppr (DiscrF f) = text (show f)
811    ppr (DiscrD d) = text (show d)
812    ppr (DiscrP i) = int i
813    ppr NoDiscr    = text "DEF"
814
815
816 -- Find things in the BCEnv (the what's-on-the-stack-env)
817 -- See comment preceding pushAtom for precise meaning of env contents
818 --lookupBCEnv :: BCEnv -> Id -> Int
819 --lookupBCEnv env nm
820 --   = case lookupFM env nm of
821 --        Nothing -> pprPanic "lookupBCEnv" 
822 --                            (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
823 --        Just xx -> xx
824
825 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
826 lookupBCEnv_maybe = lookupFM
827
828
829 -- When I push one of these on the stack, how much does Sp move by?
830 taggedSizeW :: PrimRep -> Int
831 taggedSizeW pr
832    | isFollowableRep pr = 1
833    | otherwise          = 1{-the tag-} + getPrimRepSize pr
834
835
836 -- The plain size of something, without tag.
837 untaggedSizeW :: PrimRep -> Int
838 untaggedSizeW pr
839    | isFollowableRep pr = 1
840    | otherwise          = getPrimRepSize pr
841
842
843 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
844 taggedIdSizeW   = taggedSizeW   . typePrimRep . idType
845 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
846
847 \end{code}
848
849 %************************************************************************
850 %*                                                                      *
851 \subsection{The bytecode generator's monad}
852 %*                                                                      *
853 %************************************************************************
854
855 \begin{code}
856 data BcM_State 
857    = BcM_State { bcos      :: [ProtoBCO Name],  -- accumulates completed BCOs
858                  nextlabel :: Int }             -- for generating local labels
859
860 type BcM result = BcM_State -> (result, BcM_State)
861
862 runBc :: BcM_State -> BcM () -> BcM_State
863 runBc init_st m = case m init_st of { (r,st) -> st }
864
865 thenBc :: BcM a -> (a -> BcM b) -> BcM b
866 thenBc expr cont st
867   = case expr st of { (result, st') -> cont result st' }
868
869 thenBc_ :: BcM a -> BcM b -> BcM b
870 thenBc_ expr cont st
871   = case expr st of { (result, st') -> cont st' }
872
873 returnBc :: a -> BcM a
874 returnBc result st = (result, st)
875
876 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
877 mapBc f []     = returnBc []
878 mapBc f (x:xs)
879   = f x          `thenBc` \ r  ->
880     mapBc f xs   `thenBc` \ rs ->
881     returnBc (r:rs)
882
883 emitBc :: ProtoBCO Name -> BcM ()
884 emitBc bco st
885    = ((), st{bcos = bco : bcos st})
886
887 getLabelBc :: BcM Int
888 getLabelBc st
889    = (nextlabel st, st{nextlabel = 1 + nextlabel st})
890
891 \end{code}