[project @ 2001-01-21 16:37:22 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 (id {-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 : 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 other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
478
479
480 -- Make code to unpack the top-of-stack constructor onto the stack, 
481 -- adding tags for the unboxed bits.  Takes the PrimReps of the 
482 -- constructor's arguments.  off_h and off_s are travelling offsets
483 -- along the constructor and the stack.
484 --
485 -- Supposing a constructor in the heap has layout
486 --
487 --      Itbl p_1 ... p_i np_1 ... np_j
488 --
489 -- then we add to the stack, shown growing down, the following:
490 --
491 --    (previous stack)
492 --         p_i
493 --         ...
494 --         p_1
495 --         np_j
496 --         tag_for(np_j)
497 --         ..
498 --         np_1
499 --         tag_for(np_1)
500 --
501 -- so that in the common case (ptrs only) a single UNPACK instr can
502 -- copy all the payload of the constr onto the stack with no further ado.
503
504 mkUnpackCode :: [Id]    -- constr args
505              -> Int     -- depth before unpack
506              -> BCEnv   -- env before unpack
507              -> (BCInstrList, Int, BCEnv)
508 mkUnpackCode vars d p
509    = --trace ("mkUnpackCode: " ++ showSDocDebug (ppr vars)
510      --       ++ " --> " ++ show d' ++ "\n" ++ showSDocDebug (ppBCEnv p')
511      --       ++ "\n") (
512      (code_p `appOL` code_np, d', p')
513      --)
514      where
515         -- vars with reps
516         vreps = [(var, typePrimRep (idType var)) | var <- vars]
517
518         -- ptrs and nonptrs, forward
519         vreps_p  = filter (isFollowableRep.snd) vreps
520         vreps_np = filter (not.isFollowableRep.snd) vreps
521
522         -- the order in which we will augment the environment
523         vreps_env = reverse vreps_p ++ reverse vreps_np
524
525         -- new env and depth
526         vreps_env_tszsw = map (taggedSizeW.snd) vreps_env
527         p' = addListToFM p (zip (map fst vreps_env) 
528                                 (mkStackOffsets d vreps_env_tszsw))
529         d' = d + sum vreps_env_tszsw
530
531         -- code to unpack the ptrs
532         ptrs_szw = sum (map (untaggedSizeW.snd) vreps_p)
533         code_p | null vreps_p = nilOL
534                | otherwise    = unitOL (UNPACK ptrs_szw)
535
536         -- code to unpack the nonptrs
537         vreps_env_uszw = sum (map (untaggedSizeW.snd) vreps_env)
538         code_np = do_nptrs vreps_env_uszw ptrs_szw (reverse (map snd vreps_np))
539         do_nptrs off_h off_s [] = nilOL
540         do_nptrs off_h off_s (npr:nprs)
541            = case npr of
542                 IntRep -> approved ; FloatRep -> approved
543                 DoubleRep -> approved ; AddrRep -> approved
544                 CharRep -> approved
545                 _ -> pprPanic "ByteCodeGen.mkUnpackCode" (ppr npr)
546              where
547                 approved = UPK_TAG usizeW (off_h-usizeW) off_s   `consOL` theRest
548                 theRest  = do_nptrs (off_h-usizeW) (off_s + tsizeW) nprs
549                 usizeW   = untaggedSizeW npr
550                 tsizeW   = taggedSizeW npr
551
552
553 -- Push an atom onto the stack, returning suitable code & number of
554 -- stack words used.  Pushes it either tagged or untagged, since 
555 -- pushAtom is used to set up the stack prior to copying into the
556 -- heap for both APs (requiring tags) and constructors (which don't).
557 --
558 -- NB this means NO GC between pushing atoms for a constructor and
559 -- copying them into the heap.  It probably also means that 
560 -- tail calls MUST be of the form atom{atom ... atom} since if the
561 -- expression head was allowed to be arbitrary, there could be GC
562 -- in between pushing the arg atoms and completing the head.
563 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
564 -- isn't a problem; but only if arbitrary graph construction for the
565 -- head doesn't leave this BCO, since GC might happen at the start of
566 -- each BCO (we consult doYouWantToGC there).
567 --
568 -- Blargh.  JRS 001206
569 --
570 -- NB (further) that the env p must map each variable to the highest-
571 -- numbered stack slot for it.  For example, if the stack has depth 4 
572 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
573 -- the tag in stack[5], the stack will have depth 6, and p must map v to
574 -- 5 and not to 4.  Stack locations are numbered from zero, so a depth
575 -- 6 stack has valid words 0 .. 5.
576
577 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
578 pushAtom tagged d p (AnnVar v)
579
580    | idPrimRep v == VoidRep
581    = ASSERT(tagged)
582      (unitOL (PUSH_TAG 0), 1)
583
584    | Just primop <- isPrimOpId_maybe v
585    = case primop of
586         CCallOp _ -> panic "pushAtom: byte code generator can't handle CCalls"
587         other     -> (unitOL (PUSH_G (Right primop)), 1)
588
589    | otherwise
590    = let str = "\npushAtom " ++ showSDocDebug (ppr v) 
591                ++ " :: " ++ showSDocDebug (pprType (idType v))
592                ++ ", depth = " ++ show d
593                ++ ", tagged = " ++ show tagged ++ ", env =\n" ++ 
594                showSDocDebug (ppBCEnv p)
595                ++ " --> words: " ++ show (snd result) ++ "\n" ++
596                showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
597                ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
598                   where
599                      cmp_snd x y = compare (snd x) (snd y)
600          str' = if str == str then str else str
601
602          result
603             = case lookupBCEnv_maybe p v of
604                  Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), nwords)
605                  Nothing  -> ASSERT(sz_t == 1) (unitOL (PUSH_G (Left nm)), nwords)
606
607          nm = case isDataConId_maybe v of
608                  Just c  -> getName c
609                  Nothing -> getName v
610
611          sz_t   = taggedIdSizeW v
612          sz_u   = untaggedIdSizeW v
613          nwords = if tagged then sz_t else sz_u
614      in
615          --trace str'
616          result
617
618 pushAtom True d p (AnnLit lit)
619    = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
620      in  (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
621
622 pushAtom False d p (AnnLit lit)
623    = case lit of
624         MachWord w   -> code WordRep
625         MachInt i    -> code IntRep
626         MachFloat r  -> code FloatRep
627         MachDouble r -> code DoubleRep
628         MachChar c   -> code CharRep
629         MachStr s    -> pushStr s
630      where
631         code rep
632            = let size_host_words = untaggedSizeW rep
633              in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
634
635         pushStr s 
636            = let mallocvilleAddr
637                     = case s of
638                          CharStr s i -> A# s
639
640                          FastString _ l ba -> 
641                             -- sigh, a string in the heap is no good to us.
642                             -- We need a static C pointer, since the type of 
643                             -- a string literal is Addr#.  So, copy the string 
644                             -- into C land and introduce a memory leak 
645                             -- at the same time.
646                             let n = I# l
647                             -- CAREFUL!  Chars are 32 bits in ghc 4.09+
648                             in  unsafePerformIO (
649                                    do (Ptr a#) <- mallocBytes (n+1)
650                                       strncpy (Ptr a#) ba (fromIntegral n)
651                                       writeCharOffAddr (A# a#) n '\0'
652                                       return (A# a#)
653                                    )
654                          _ -> panic "StgInterp.lit2expr: unhandled string constant type"
655
656                  addrLit 
657                     = MachInt (toInteger (addrToInt mallocvilleAddr))
658              in
659                 -- Get the addr on the stack, untaggedly
660                 (unitOL (PUSH_UBX addrLit 1), 1)
661
662
663
664
665
666 pushAtom tagged d p (AnnApp f (_, AnnType _))
667    = pushAtom tagged d p (snd f)
668
669 pushAtom tagged d p (AnnNote note e)
670    = pushAtom tagged d p (snd e)
671
672 pushAtom tagged d p other
673    = pprPanic "ByteCodeGen.pushAtom" 
674               (pprCoreExpr (deAnnotate (undefined, other)))
675
676 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
677
678
679 -- Given a bunch of alts code and their discrs, do the donkey work
680 -- of making a multiway branch using a switch tree.
681 -- What a load of hassle!
682 mkMultiBranch :: Maybe Int      -- # datacons in tycon, if alg alt
683                                 -- a hint; generates better code
684                                 -- Nothing is always safe
685               -> [(Discr, BCInstrList)] 
686               -> BcM BCInstrList
687 mkMultiBranch maybe_ncons raw_ways
688    = let d_way     = filter (isNoDiscr.fst) raw_ways
689          notd_ways = naturalMergeSortLe 
690                         (\w1 w2 -> leAlt (fst w1) (fst w2))
691                         (filter (not.isNoDiscr.fst) raw_ways)
692
693          mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
694          mkTree [] range_lo range_hi = returnBc the_default
695
696          mkTree [val] range_lo range_hi
697             | range_lo `eqAlt` range_hi 
698             = returnBc (snd val)
699             | otherwise
700             = getLabelBc                                `thenBc` \ label_neq ->
701               returnBc (mkTestEQ (fst val) label_neq 
702                         `consOL` (snd val
703                         `appOL`   unitOL (LABEL label_neq)
704                         `appOL`   the_default))
705
706          mkTree vals range_lo range_hi
707             = let n = length vals `div` 2
708                   vals_lo = take n vals
709                   vals_hi = drop n vals
710                   v_mid = fst (head vals_hi)
711               in
712               getLabelBc                                `thenBc` \ label_geq ->
713               mkTree vals_lo range_lo (dec v_mid)       `thenBc` \ code_lo ->
714               mkTree vals_hi v_mid range_hi             `thenBc` \ code_hi ->
715               returnBc (mkTestLT v_mid label_geq
716                         `consOL` (code_lo
717                         `appOL`   unitOL (LABEL label_geq)
718                         `appOL`   code_hi))
719  
720          the_default 
721             = case d_way of [] -> unitOL CASEFAIL
722                             [(_, def)] -> def
723
724          -- None of these will be needed if there are no non-default alts
725          (mkTestLT, mkTestEQ, init_lo, init_hi)
726             | null notd_ways
727             = panic "mkMultiBranch: awesome foursome"
728             | otherwise
729             = case fst (head notd_ways) of {
730               DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
731                             \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
732                             DiscrI minBound,
733                             DiscrI maxBound );
734               DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
735                             \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
736                             DiscrF minF,
737                             DiscrF maxF );
738               DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
739                             \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
740                             DiscrD minD,
741                             DiscrD maxD );
742               DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
743                             \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
744                             DiscrP algMinBound,
745                             DiscrP algMaxBound )
746               }
747
748          (algMinBound, algMaxBound)
749             = case maybe_ncons of
750                  Just n  -> (0, n - 1)
751                  Nothing -> (minBound, maxBound)
752
753          (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
754          (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
755          (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
756          (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
757          NoDiscr     `eqAlt` NoDiscr     = True
758          _           `eqAlt` _           = False
759
760          (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
761          (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
762          (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
763          (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
764          NoDiscr     `leAlt` NoDiscr     = True
765          _           `leAlt` _           = False
766
767          isNoDiscr NoDiscr = True
768          isNoDiscr _       = False
769
770          dec (DiscrI i) = DiscrI (i-1)
771          dec (DiscrP i) = DiscrP (i-1)
772          dec other      = other         -- not really right, but if you
773                 -- do cases on floating values, you'll get what you deserve
774
775          -- same snotty comment applies to the following
776          minF, maxF :: Float
777          minD, maxD :: Double
778          minF = -1.0e37
779          maxF =  1.0e37
780          minD = -1.0e308
781          maxD =  1.0e308
782      in
783          mkTree notd_ways init_lo init_hi
784
785 \end{code}
786
787 %************************************************************************
788 %*                                                                      *
789 \subsection{Supporting junk for the compilation schemes}
790 %*                                                                      *
791 %************************************************************************
792
793 \begin{code}
794
795 -- Describes case alts
796 data Discr 
797    = DiscrI Int
798    | DiscrF Float
799    | DiscrD Double
800    | DiscrP Int
801    | NoDiscr
802
803 instance Outputable Discr where
804    ppr (DiscrI i) = int i
805    ppr (DiscrF f) = text (show f)
806    ppr (DiscrD d) = text (show d)
807    ppr (DiscrP i) = int i
808    ppr NoDiscr    = text "DEF"
809
810
811 -- Find things in the BCEnv (the what's-on-the-stack-env)
812 -- See comment preceding pushAtom for precise meaning of env contents
813 --lookupBCEnv :: BCEnv -> Id -> Int
814 --lookupBCEnv env nm
815 --   = case lookupFM env nm of
816 --        Nothing -> pprPanic "lookupBCEnv" 
817 --                            (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
818 --        Just xx -> xx
819
820 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
821 lookupBCEnv_maybe = lookupFM
822
823
824 -- When I push one of these on the stack, how much does Sp move by?
825 taggedSizeW :: PrimRep -> Int
826 taggedSizeW pr
827    | isFollowableRep pr = 1
828    | otherwise          = 1{-the tag-} + getPrimRepSize pr
829
830
831 -- The plain size of something, without tag.
832 untaggedSizeW :: PrimRep -> Int
833 untaggedSizeW pr
834    | isFollowableRep pr = 1
835    | otherwise          = getPrimRepSize pr
836
837
838 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
839 taggedIdSizeW   = taggedSizeW   . typePrimRep . idType
840 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
841
842 \end{code}
843
844 %************************************************************************
845 %*                                                                      *
846 \subsection{The bytecode generator's monad}
847 %*                                                                      *
848 %************************************************************************
849
850 \begin{code}
851 data BcM_State 
852    = BcM_State { bcos      :: [ProtoBCO Name],  -- accumulates completed BCOs
853                  nextlabel :: Int }             -- for generating local labels
854
855 type BcM result = BcM_State -> (result, BcM_State)
856
857 runBc :: BcM_State -> BcM () -> BcM_State
858 runBc init_st m = case m init_st of { (r,st) -> st }
859
860 thenBc :: BcM a -> (a -> BcM b) -> BcM b
861 thenBc expr cont st
862   = case expr st of { (result, st') -> cont result st' }
863
864 thenBc_ :: BcM a -> BcM b -> BcM b
865 thenBc_ expr cont st
866   = case expr st of { (result, st') -> cont st' }
867
868 returnBc :: a -> BcM a
869 returnBc result st = (result, st)
870
871 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
872 mapBc f []     = returnBc []
873 mapBc f (x:xs)
874   = f x          `thenBc` \ r  ->
875     mapBc f xs   `thenBc` \ rs ->
876     returnBc (r:rs)
877
878 emitBc :: ProtoBCO Name -> BcM ()
879 emitBc bco st
880    = ((), st{bcos = bco : bcos st})
881
882 getLabelBc :: BcM Int
883 getLabelBc st
884    = (nextlabel st, st{nextlabel = 1 + nextlabel st})
885
886 \end{code}