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