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