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