[project @ 2001-10-25 05:07:32 by sof]
[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, isFCallId_maybe )
18 import ForeignCall      ( ForeignCall(..), CCallTarget(..), CCallSpec(..) )
19 import OrdList          ( OrdList, consOL, snocOL, appOL, unitOL, 
20                           nilOL, toOL, concatOL, fromOL )
21 import FiniteMap        ( FiniteMap, addListToFM, listToFM,
22                           addToFM, lookupFM, fmToList )
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, splitTyConApp_maybe, isTyVarTy )
30 import DataCon          ( dataConTag, fIRST_TAG, dataConTyCon, 
31                           dataConWrapId, isUnboxedTupleCon )
32 import TyCon            ( TyCon(..), tyConFamilySize, isDataTyCon, tyConDataCons,
33                           isFunTyCon, isUnboxedTupleTyCon )
34 import Class            ( Class, classTyCon )
35 import Type             ( Type, repType, splitRepFunTys )
36 import Util             ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem,
37                           isSingleton, lengthIs )
38 import Var              ( isTyVar )
39 import VarSet           ( VarSet, varSetElems )
40 import PrimRep          ( isFollowableRep )
41 import CmdLineOpts      ( DynFlags, DynFlag(..) )
42 import ErrUtils         ( showPass, dumpIfSet_dyn )
43 import Unique           ( mkPseudoUnique3 )
44 import FastString       ( FastString(..) )
45 import Panic            ( GhcException(..) )
46 import PprType          ( pprType )
47 import SMRep            ( arrWordsHdrSize, arrPtrsHdrSize )
48 import Constants        ( wORD_SIZE )
49 import ByteCodeInstr    ( BCInstr(..), ProtoBCO(..), nameOfProtoBCO, bciStackUse )
50 import ByteCodeItbls    ( ItblEnv, mkITbls )
51 import ByteCodeLink     ( UnlinkedBCO, UnlinkedBCOExpr, assembleBCO,
52                           ClosureEnv, HValue, filterNameMap, linkFail,
53                           iNTERP_STACK_CHECK_THRESH )
54 import ByteCodeFFI      ( taggedSizeW, untaggedSizeW, mkMarshalCode, moan64 )
55 import Linker           ( lookupSymbol )
56
57 import List             ( intersperse, sortBy, zip4 )
58 import Foreign          ( Ptr(..), mallocBytes )
59 import Addr             ( Addr(..), writeCharOffAddr )
60 import CTypes           ( CInt )
61 import Exception        ( throwDyn )
62
63 import PrelBase         ( Int(..) )
64 import PrelGHC          ( ByteArray# )
65 import PrelIOBase       ( IO(..) )
66 import Monad            ( when )
67
68 \end{code}
69
70 %************************************************************************
71 %*                                                                      *
72 \subsection{Functions visible from outside this module.}
73 %*                                                                      *
74 %************************************************************************
75
76 \begin{code}
77
78 byteCodeGen :: DynFlags
79             -> [CoreBind] 
80             -> [TyCon] -> [Class]
81             -> IO ([UnlinkedBCO], ItblEnv)
82 byteCodeGen dflags binds local_tycons local_classes
83    = do showPass dflags "ByteCodeGen"
84         let tycs = local_tycons ++ map classTyCon local_classes
85         itblenv <- mkITbls tycs
86
87         let flatBinds = concatMap getBind binds
88             getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
89             getBind (Rec binds)       = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
90
91         (BcM_State proto_bcos final_ctr mallocd, ())
92            <- runBc (BcM_State [] 0 []) 
93                     (mapBc (schemeR True) flatBinds `thenBc_` returnBc ())
94
95         when (not (null mallocd))
96              (panic "ByteCodeGen.byteCodeGen: missing final emitBc?")
97
98         dumpIfSet_dyn dflags Opt_D_dump_BCOs
99            "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
100
101         bcos <- mapM assembleBCO proto_bcos
102
103         return (bcos, itblenv)
104         
105
106 -- Returns: (the root BCO for this expression, 
107 --           a list of auxilary BCOs resulting from compiling closures)
108 coreExprToBCOs :: DynFlags
109                -> CoreExpr
110                -> IO UnlinkedBCOExpr
111 coreExprToBCOs dflags expr
112  = do showPass dflags "ByteCodeGen"
113
114       -- create a totally bogus name for the top-level BCO; this
115       -- should be harmless, since it's never used for anything
116       let invented_id   = mkSysLocal SLIT("Expr-Top-Level") (mkPseudoUnique3 0) 
117                                      (panic "invented_id's type")
118       let invented_name = idName invented_id
119
120       (BcM_State all_proto_bcos final_ctr mallocd, ()) 
121          <- runBc (BcM_State [] 0 []) 
122                   (schemeR True (invented_id, freeVars expr))
123
124       when (not (null mallocd))
125            (panic "ByteCodeGen.coreExprToBCOs: missing final emitBc?")
126
127       dumpIfSet_dyn dflags Opt_D_dump_BCOs
128          "Proto-bcos" (vcat (intersperse (char ' ') (map ppr all_proto_bcos)))
129
130       let root_proto_bco 
131              = case filter ((== invented_name).nameOfProtoBCO) all_proto_bcos of
132                   [root_bco] -> root_bco
133           auxiliary_proto_bcos
134              = filter ((/= invented_name).nameOfProtoBCO) all_proto_bcos
135
136       auxiliary_bcos <- mapM assembleBCO auxiliary_proto_bcos
137       root_bco <- assembleBCO root_proto_bco
138
139       return (root_bco, auxiliary_bcos)
140 \end{code}
141
142 %************************************************************************
143 %*                                                                      *
144 \subsection{Compilation schema for the bytecode generator.}
145 %*                                                                      *
146 %************************************************************************
147
148 \begin{code}
149
150 type BCInstrList = OrdList BCInstr
151
152 type Sequel = Int       -- back off to this depth before ENTER
153
154 -- Maps Ids to the offset from the stack _base_ so we don't have
155 -- to mess with it after each push/pop.
156 type BCEnv = FiniteMap Id Int   -- To find vars on the stack
157
158 ppBCEnv :: BCEnv -> SDoc
159 ppBCEnv p
160    = text "begin-env"
161      $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
162      $$ text "end-env"
163      where
164         pp_one (var, offset) = int offset <> colon <+> ppr var
165         cmp_snd x y = compare (snd x) (snd y)
166
167 -- Create a BCO and do a spot of peephole optimisation on the insns
168 -- at the same time.
169 mkProtoBCO nm instrs_ordlist origin mallocd_blocks
170    = ProtoBCO nm maybe_with_stack_check origin mallocd_blocks
171      where
172         -- Overestimate the stack usage (in words) of this BCO,
173         -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit
174         -- stack check.  (The interpreter always does a stack check
175         -- for iNTERP_STACK_CHECK_THRESH words at the start of each
176         -- BCO anyway, so we only need to add an explicit on in the
177         -- (hopefully rare) cases when the (overestimated) stack use
178         -- exceeds iNTERP_STACK_CHECK_THRESH.
179         maybe_with_stack_check
180            | stack_overest >= 65535
181            = pprPanic "mkProtoBCO: stack use won't fit in 16 bits" 
182                       (int stack_overest)
183            | stack_overest >= iNTERP_STACK_CHECK_THRESH
184            = (STKCHECK stack_overest) : peep_d
185            | otherwise
186            = peep_d     -- the supposedly common case
187              
188         stack_overest = sum (map bciStackUse peep_d)
189                         + 10 {- just to be really really sure -}
190
191
192         -- Merge local pushes
193         peep_d = peep (fromOL instrs_ordlist)
194
195         peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
196            = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
197         peep (PUSH_L off1 : PUSH_L off2 : rest)
198            = PUSH_LL off1 (off2-1) : peep rest
199         peep (i:rest)
200            = i : peep rest
201         peep []
202            = []
203
204
205 -- Compile code for the right hand side of a let binding.
206 -- Park the resulting BCO in the monad.  Also requires the
207 -- variable to which this value was bound, so as to give the
208 -- resulting BCO a name.  Bool indicates top-levelness.
209
210 schemeR :: Bool -> (Id, AnnExpr Id VarSet) -> BcM ()
211 schemeR is_top (nm, rhs) 
212 {-
213    | trace (showSDoc (
214               (char ' '
215                $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
216                $$ pprCoreExpr (deAnnotate rhs)
217                $$ char ' '
218               ))) False
219    = undefined
220 -}
221    | otherwise
222    = schemeR_wrk is_top rhs nm (collect [] rhs)
223
224
225 collect xs (_, AnnNote note e)
226    = collect xs e
227 collect xs (_, AnnLam x e) 
228    = collect (if isTyVar x then xs else (x:xs)) e
229 collect xs not_lambda
230    = (reverse xs, not_lambda)
231
232 schemeR_wrk is_top original_body nm (args, body)
233    | Just dcon <- maybe_toplevel_null_con_rhs
234    = --trace ("nullary constructor! " ++ showSDocDebug (ppr nm)) (
235      emitBc (mkProtoBCO (getName nm) (toOL [PACK dcon 0, ENTER])
236                                      (Right original_body))
237      --)
238
239    | otherwise
240    = let fvs       = filter (not.isTyVar) (varSetElems (fst original_body))
241          all_args  = reverse args ++ fvs
242          szsw_args = map taggedIdSizeW all_args
243          szw_args  = sum szsw_args
244          p_init    = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
245          argcheck  = unitOL (ARGCHECK szw_args)
246      in
247      schemeE szw_args 0 p_init body             `thenBc` \ body_code ->
248      emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) 
249                                      (Right original_body))
250
251      where
252         maybe_toplevel_null_con_rhs
253            | is_top && null args
254            = case nukeTyArgs (snd body) of
255                 AnnVar v_wrk 
256                    -> case isDataConId_maybe v_wrk of
257                          Nothing -> Nothing
258                          Just dc_wrk |  nm == dataConWrapId dc_wrk
259                                      -> Just dc_wrk
260                                      |  otherwise 
261                                      -> Nothing
262                 other -> Nothing
263            | otherwise
264            = Nothing
265
266         nukeTyArgs (AnnApp f (_, AnnType _)) = nukeTyArgs (snd f)
267         nukeTyArgs other                     = other
268
269
270 -- Let szsw be the sizes in words of some items pushed onto the stack,
271 -- which has initial depth d'.  Return the values which the stack environment
272 -- should map these items to.
273 mkStackOffsets :: Int -> [Int] -> [Int]
274 mkStackOffsets original_depth szsw
275    = map (subtract 1) (tail (scanl (+) original_depth szsw))
276
277 -- Compile code to apply the given expression to the remaining args
278 -- on the stack, returning a HNF.
279 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
280
281 -- Delegate tail-calls to schemeT.
282 schemeE d s p e@(fvs, AnnApp f a) 
283    = schemeT d s p (fvs, AnnApp f a)
284
285 schemeE d s p e@(fvs, AnnVar v)
286    | isFollowableRep v_rep
287    =  -- Ptr-ish thing; push it in the normal way
288      schemeT d s p (fvs, AnnVar v)
289
290    | otherwise
291    = -- returning an unboxed value.  Heave it on the stack, SLIDE, and RETURN.
292      pushAtom True d p (AnnVar v)       `thenBc` \ (push, szw) ->
293      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    = pushAtom True d p (AnnLit literal) `thenBc` \ (push, szw) ->
301      let 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             = returnBc (PUSH_G (Left (getName id))
329                         `consOL` unitOL (MKAP (off+size-1) size))
330          buildThunk dd ((fv:fvs), size, id, off)
331             = pushAtom True dd p' (AnnVar fv) 
332                                         `thenBc` \ (push_code, pushed_szw) ->
333               buildThunk (dd+pushed_szw) (fvs, size, id, off)
334                                         `thenBc` \ more_push_code ->
335               returnBc (push_code `appOL` more_push_code)
336
337          genThunkCode = mapBc (buildThunk d') infos     `thenBc` \ tcodes ->
338                         returnBc (concatOL tcodes)
339
340          allocCode = toOL (map ALLOC sizes)
341      in
342      schemeE d' s p' b                                  `thenBc`  \ bodyCode ->
343      mapBc (schemeR False) (zip xs rhss)                `thenBc_`
344      genThunkCode                                       `thenBc` \ thunkCode ->
345      returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
346
347
348
349
350
351 schemeE d s p (fvs_case, AnnCase (fvs_scrut, scrut) bndr 
352                                  [(DEFAULT, [], (fvs_rhs, rhs))])
353
354    | let isFunType var_type 
355             = case splitTyConApp_maybe var_type of
356                  Just (tycon,_) | isFunTyCon tycon -> True
357                  _ -> False
358          ty_bndr = repType (idType bndr)
359      in isFunType ty_bndr || isTyVarTy ty_bndr
360
361    -- Nasty hack; treat
362    --     case scrut::suspect of bndr { DEFAULT -> rhs }
363    --     as 
364    --     let bndr = scrut in rhs
365    --     when suspect is polymorphic or arrowtyped
366    -- So the required strictness properties are not observed.
367    -- At some point, must fix this properly.
368    = let new_expr
369             = (fvs_case, 
370                AnnLet 
371                   (AnnNonRec bndr (fvs_scrut, scrut)) (fvs_rhs, rhs)
372               )
373
374      in  trace ("WARNING: ignoring polymorphic case in interpreted mode.\n" ++
375                 "   Possibly due to strict polymorphic/functional constructor args.\n" ++
376                 "   Your program may leak space unexpectedly.\n")
377          (schemeE d s p new_expr)
378
379
380
381 {- Convert case .... of (# VoidRep'd-thing, a #) -> ...
382       as
383    case .... of a -> ...
384    Use  a  as the name of the binder too.
385
386    Also    case .... of (# a #) -> ...
387       to
388    case .... of a -> ...
389 -}
390 schemeE d s p (fvs, AnnCase scrut bndr [(DataAlt dc, [bind1, bind2], rhs)])
391    | isUnboxedTupleCon dc && VoidRep == typePrimRep (idType bind1)
392    = --trace "automagic mashing of case alts (# VoidRep, a #)" (
393      schemeE d s p (fvs, AnnCase scrut bind2 [(DEFAULT, [bind2], rhs)])
394      --)
395
396 schemeE d s p (fvs, AnnCase scrut bndr [(DataAlt dc, [bind1], rhs)])
397    | isUnboxedTupleCon dc
398    = --trace "automagic mashing of case alts (# a #)" (
399      schemeE d s p (fvs, AnnCase scrut bind1 [(DEFAULT, [bind1], rhs)])
400      --)
401
402 schemeE d s p (fvs, AnnCase scrut bndr alts)
403    = let
404         -- Top of stack is the return itbl, as usual.
405         -- underneath it is the pointer to the alt_code BCO.
406         -- When an alt is entered, it assumes the returned value is
407         -- on top of the itbl.
408         ret_frame_sizeW = 2
409
410         -- Env and depth in which to compile the alts, not including
411         -- any vars bound by the alts themselves
412         d' = d + ret_frame_sizeW + taggedIdSizeW bndr
413         p' = addToFM p bndr (d' - 1)
414
415         scrut_primrep = typePrimRep (idType bndr)
416         isAlgCase
417            | scrut_primrep == PtrRep
418            = True
419            | scrut_primrep `elem`
420              [CharRep, AddrRep, WordRep, IntRep, FloatRep, DoubleRep,
421               VoidRep, Int8Rep, Int16Rep, Int32Rep, Int64Rep,
422               Word8Rep, Word16Rep, Word32Rep, Word64Rep]
423            = False
424            | otherwise
425            =  pprPanic "ByteCodeGen.schemeE" (ppr scrut_primrep)
426
427         -- given an alt, return a discr and code for it.
428         codeAlt alt@(discr, binds_f, rhs)
429            | isAlgCase 
430            = let (unpack_code, d_after_unpack, p_after_unpack)
431                     = mkUnpackCode (filter (not.isTyVar) binds_f) d' p'
432              in  schemeE d_after_unpack s p_after_unpack rhs
433                                         `thenBc` \ rhs_code -> 
434                  returnBc (my_discr alt, unpack_code `appOL` rhs_code)
435            | otherwise 
436            = ASSERT(null binds_f) 
437              schemeE d' s p' rhs        `thenBc` \ rhs_code ->
438              returnBc (my_discr alt, rhs_code)
439
440         my_discr (DEFAULT, binds, rhs) = NoDiscr
441         my_discr (DataAlt dc, binds, rhs) 
442            | isUnboxedTupleCon dc
443            = unboxedTupleException
444            | otherwise
445            = DiscrP (dataConTag dc - fIRST_TAG)
446         my_discr (LitAlt l, binds, rhs)
447            = case l of MachInt i     -> DiscrI (fromInteger i)
448                        MachFloat r   -> DiscrF (fromRational r)
449                        MachDouble r  -> DiscrD (fromRational r)
450                        MachChar i    -> DiscrI i
451                        _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
452
453         maybe_ncons 
454            | not isAlgCase = Nothing
455            | otherwise 
456            = case [dc | (DataAlt dc, _, _) <- alts] of
457                 []     -> Nothing
458                 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
459
460      in 
461      mapBc codeAlt alts                                 `thenBc` \ alt_stuff ->
462      mkMultiBranch maybe_ncons alt_stuff                `thenBc` \ alt_final ->
463      let 
464          alt_final_ac = ARGCHECK (taggedIdSizeW bndr) `consOL` alt_final
465          alt_bco_name = getName bndr
466          alt_bco      = mkProtoBCO alt_bco_name alt_final_ac (Left alts)
467      in
468      schemeE (d + ret_frame_sizeW) 
469              (d + ret_frame_sizeW) p scrut              `thenBc` \ scrut_code ->
470
471      emitBc alt_bco                                     `thenBc_`
472      returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
473
474
475 schemeE d s p (fvs, AnnNote note body)
476    = schemeE d s p body
477
478 schemeE d s p other
479    = pprPanic "ByteCodeGen.schemeE: unhandled case" 
480                (pprCoreExpr (deAnnotate other))
481
482
483 -- Compile code to do a tail call.  Specifically, push the fn,
484 -- slide the on-stack app back down to the sequel depth,
485 -- and enter.  Four cases:
486 --
487 -- 0.  (Nasty hack).
488 --     An application "PrelGHC.tagToEnum# <type> unboxed-int".
489 --     The int will be on the stack.  Generate a code sequence
490 --     to convert it to the relevant constructor, SLIDE and ENTER.
491 --
492 -- 1.  A nullary constructor.  Push its closure on the stack 
493 --     and SLIDE and RETURN.
494 --
495 -- 2.  (Another nasty hack).  Spot (# a::VoidRep, b #) and treat
496 --     it simply as  b  -- since the representations are identical
497 --     (the VoidRep takes up zero stack space).  Also, spot
498 --     (# b #) and treat it as  b.
499 --
500 -- 3.  The fn denotes a ccall.  Defer to generateCCall.
501 --
502 -- 4.  Application of a non-nullary constructor, by defn saturated.
503 --     Split the args into ptrs and non-ptrs, and push the nonptrs, 
504 --     then the ptrs, and then do PACK and RETURN.
505 --
506 -- 5.  Otherwise, it must be a function call.  Push the args
507 --     right to left, SLIDE and ENTER.
508
509 schemeT :: Int          -- Stack depth
510         -> Sequel       -- Sequel depth
511         -> BCEnv        -- stack env
512         -> AnnExpr Id VarSet 
513         -> BcM BCInstrList
514
515 schemeT d s p app
516
517 --   | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
518 --   = panic "schemeT ?!?!"
519
520 --   | trace ("\nschemeT\n" ++ showSDoc (pprCoreExpr (deAnnotate app)) ++ "\n") False
521 --   = error "?!?!" 
522
523    -- Case 0
524    | Just (arg, constr_names) <- maybe_is_tagToEnum_call
525    = pushAtom True d p arg              `thenBc` \ (push, arg_words) ->
526      implement_tagToId constr_names     `thenBc` \ tagToId_sequence ->
527      returnBc (push `appOL`  tagToId_sequence            
528                     `appOL`  mkSLIDE 1 (d+arg_words-s)
529                     `snocOL` ENTER)
530
531    -- Case 1
532    | is_con_call && null args_r_to_l
533    = returnBc (
534         (PUSH_G (Left (getName con)) `consOL` mkSLIDE 1 (d-s))
535         `snocOL` ENTER
536      )
537
538    -- Case 2
539    | let isVoidRepAtom (_, AnnVar v)    = VoidRep == typePrimRep (idType v)
540          isVoidRepAtom (_, AnnNote n e) = isVoidRepAtom e
541      in  is_con_call && isUnboxedTupleCon con 
542          && ( (args_r_to_l `lengthIs` 2 && isVoidRepAtom (last (args_r_to_l)))
543               || (isSingleton args_r_to_l)
544             )
545    = --trace (if isSingleton args_r_to_l
546      --       then "schemeT: unboxed singleton"
547      --       else "schemeT: unboxed pair with Void first component") (
548      schemeT d s p (head args_r_to_l)
549      --)
550
551    -- Case 3
552    | Just (CCall ccall_spec) <- isFCallId_maybe fn
553    = generateCCall d s p ccall_spec fn args_r_to_l
554
555    -- Cases 4 and 5
556    | otherwise
557    = if   is_con_call && isUnboxedTupleCon con
558      then unboxedTupleException
559      else do_pushery d (map snd args_final_r_to_l)
560
561    where
562       -- Detect and extract relevant info for the tagToEnum kludge.
563       maybe_is_tagToEnum_call
564          = let extract_constr_Names ty
565                   = case splitTyConApp_maybe (repType ty) of
566                        (Just (tyc, [])) |  isDataTyCon tyc
567                                         -> map getName (tyConDataCons tyc)
568                        other -> panic "maybe_is_tagToEnum_call.extract_constr_Ids"
569            in 
570            case app of
571               (_, AnnApp (_, AnnApp (_, AnnVar v) (_, AnnType t)) arg)
572                  -> case isPrimOpId_maybe v of
573                        Just TagToEnumOp -> Just (snd arg, extract_constr_Names t)
574                        other            -> Nothing
575               other -> Nothing
576
577       -- Extract the args (R->L) and fn
578       (args_r_to_l_raw, fn) = chomp app
579       chomp expr
580          = case snd expr of
581               AnnVar v    -> ([], v)
582               AnnApp f a  -> case chomp f of (az, f) -> (a:az, f)
583               AnnNote n e -> chomp e
584               other       -> pprPanic "schemeT" 
585                                 (ppr (deAnnotate (panic "schemeT.chomp", other)))
586          
587       args_r_to_l = filter (not.isTypeAtom.snd) args_r_to_l_raw
588       isTypeAtom (AnnType _) = True
589       isTypeAtom _           = False
590
591       -- decide if this is a constructor call, and rearrange
592       -- args appropriately.
593       maybe_dcon  = isDataConId_maybe fn
594       is_con_call = case maybe_dcon of Nothing -> False; Just _ -> True
595       (Just con)  = maybe_dcon
596
597       args_final_r_to_l
598          | not is_con_call
599          = args_r_to_l
600          | otherwise
601          = filter (not.isPtr.snd) args_r_to_l ++ filter (isPtr.snd) args_r_to_l
602            where isPtr = isFollowableRep . atomRep
603
604       -- make code to push the args and then do the SLIDE-ENTER thing
605       tag_when_push = not is_con_call
606       narg_words    = sum (map (get_arg_szw . atomRep . snd) args_r_to_l)
607       get_arg_szw   = if tag_when_push then taggedSizeW else untaggedSizeW
608
609       do_pushery d (arg:args)
610          = pushAtom tag_when_push d p arg       `thenBc` \ (push, arg_words) ->
611            do_pushery (d+arg_words) args        `thenBc` \ more_push_code ->
612            returnBc (push `appOL` more_push_code)
613       do_pushery d []
614          | Just (CCall ccall_spec) <- isFCallId_maybe fn
615          = panic "schemeT.do_pushery: unexpected ccall"
616          | otherwise
617          = case maybe_dcon of
618               Just con -> returnBc (
619                              (PACK con narg_words `consOL`
620                               mkSLIDE 1 (d - narg_words - s)) `snocOL`
621                               ENTER
622                           )
623               Nothing
624                  -> pushAtom True d p (AnnVar fn)       
625                                                 `thenBc` \ (push, arg_words) ->
626                     returnBc (push `appOL` mkSLIDE (narg_words+arg_words) 
627                                                    (d - s - narg_words)
628                               `snocOL` ENTER)
629
630
631
632 {- Deal with a CCall.  Taggedly push the args onto the stack R->L,
633    deferencing ForeignObj#s and (ToDo: adjusting addrs to point to
634    payloads in Ptr/Byte arrays).  Then, generate the marshalling
635    (machine) code for the ccall, and create bytecodes to call that and
636    then return in the right way.  
637 -}
638 generateCCall :: Int -> Sequel          -- stack and sequel depths
639               -> BCEnv
640               -> CCallSpec              -- where to call
641               -> Id                     -- of target, for type info
642               -> [AnnExpr Id VarSet]    -- args (atoms)
643               -> BcM BCInstrList
644
645 generateCCall d0 s p ccall_spec@(CCallSpec target cconv safety) fn args_r_to_l
646    = let 
647          -- useful constants
648          addr_usizeW = untaggedSizeW AddrRep
649          addr_tsizeW = taggedSizeW AddrRep
650
651          -- Get the args on the stack, with tags and suitably
652          -- dereferenced for the CCall.  For each arg, return the
653          -- depth to the first word of the bits for that arg, and the
654          -- PrimRep of what was actually pushed.
655
656          pargs d [] = returnBc []
657          pargs d ((_,a):az) 
658             = let rep_arg = atomRep a
659               in case rep_arg of
660                     -- Don't push the FO; instead push the Addr# it
661                     -- contains.
662                     ForeignObjRep
663                        -> pushAtom False{-irrelevant-} d p a
664                                                         `thenBc` \ (push_fo, _) ->
665                           let foro_szW = taggedSizeW ForeignObjRep
666                               d_now    = d + addr_tsizeW
667                               code     = push_fo `appOL` toOL [
668                                             UPK_TAG addr_usizeW 0 0,
669                                             SLIDE addr_tsizeW foro_szW
670                                          ]
671                           in  pargs d_now az            `thenBc` \ rest ->
672                               returnBc ((code, AddrRep) : rest)
673
674                     ArrayRep
675                        -> pargs (d + addr_tsizeW) az    `thenBc` \ rest ->
676                           parg_ArrayishRep arrPtrsHdrSize d p a
677                                                         `thenBc` \ code ->
678                           returnBc ((code,AddrRep):rest)
679
680                     ByteArrayRep
681                        -> pargs (d + addr_tsizeW) az    `thenBc` \ rest ->
682                           parg_ArrayishRep arrWordsHdrSize d p a
683                                                         `thenBc` \ code ->
684                           returnBc ((code,AddrRep):rest)
685
686                     -- Default case: push taggedly, but otherwise intact.
687                     other
688                        -> pushAtom True d p a           `thenBc` \ (code_a, sz_a) ->
689                           pargs (d+sz_a) az             `thenBc` \ rest ->
690                           returnBc ((code_a, rep_arg) : rest)
691
692          -- Do magic for Ptr/Byte arrays.  Push a ptr to the array on
693          -- the stack but then advance it over the headers, so as to
694          -- point to the payload.
695          parg_ArrayishRep hdrSizeW d p a
696             = pushAtom False{-irrel-} d p a `thenBc` \ (push_fo, _) ->
697               -- The ptr points at the header.  Advance it over the
698               -- header and then pretend this is an Addr# (push a tag).
699               returnBc (push_fo `snocOL` 
700                         SWIZZLE 0 (hdrSizeW * untaggedSizeW PtrRep
701                                             * wORD_SIZE) 
702                         `snocOL`
703                         PUSH_TAG addr_usizeW)
704
705      in
706          pargs d0 args_r_to_l                           `thenBc` \ code_n_reps ->
707      let
708          (pushs_arg, a_reps_pushed_r_to_l) = unzip code_n_reps
709
710          push_args    = concatOL pushs_arg
711          d_after_args = d0 + sum (map taggedSizeW a_reps_pushed_r_to_l)
712          a_reps_pushed_RAW
713             | null a_reps_pushed_r_to_l || head a_reps_pushed_r_to_l /= VoidRep
714             = panic "ByteCodeGen.generateCCall: missing or invalid World token?"
715             | otherwise
716             = reverse (tail a_reps_pushed_r_to_l)
717
718          -- Now: a_reps_pushed_RAW are the reps which are actually on the stack.
719          -- push_args is the code to do that.
720          -- d_after_args is the stack depth once the args are on.
721
722          -- Get the result rep.
723          (returns_void, r_rep)
724             = case maybe_getCCallReturnRep (idType fn) of
725                  Nothing -> (True,  VoidRep)
726                  Just rr -> (False, rr) 
727          {-
728          Because the Haskell stack grows down, the a_reps refer to 
729          lowest to highest addresses in that order.  The args for the call
730          are on the stack.  Now push an unboxed, tagged Addr# indicating
731          the C function to call.  Then push a dummy placeholder for the 
732          result.  Finally, emit a CCALL insn with an offset pointing to the 
733          Addr# just pushed, and a literal field holding the mallocville
734          address of the piece of marshalling code we generate.
735          So, just prior to the CCALL insn, the stack looks like this 
736          (growing down, as usual):
737                  
738             <arg_n>
739             ...
740             <arg_1>
741             Addr# address_of_C_fn
742             <placeholder-for-result#> (must be an unboxed type)
743
744          The interpreter then calls the marshall code mentioned
745          in the CCALL insn, passing it (& <placeholder-for-result#>), 
746          that is, the addr of the topmost word in the stack.
747          When this returns, the placeholder will have been
748          filled in.  The placeholder is slid down to the sequel
749          depth, and we RETURN.
750
751          This arrangement makes it simple to do f-i-dynamic since the Addr#
752          value is the first arg anyway.  It also has the virtue that the
753          stack is GC-understandable at all times.
754
755          The marshalling code is generated specifically for this
756          call site, and so knows exactly the (Haskell) stack
757          offsets of the args, fn address and placeholder.  It
758          copies the args to the C stack, calls the stacked addr,
759          and parks the result back in the placeholder.  The interpreter
760          calls it as a normal C call, assuming it has a signature
761             void marshall_code ( StgWord* ptr_to_top_of_stack )
762          -}
763          -- resolve static address
764          get_target_info
765             = case target of
766                  DynamicTarget
767                     -> returnBc (False, panic "ByteCodeGen.generateCCall(dyn)")
768                  StaticTarget target
769                     -> let sym_to_find = _UNPK_ target in
770                        ioToBc (lookupSymbol sym_to_find) `thenBc` \res ->
771                        case res of
772                            Just aa -> case aa of Ptr a# -> returnBc (True, A# a#)
773                            Nothing -> ioToBc (linkFail "ByteCodeGen.generateCCall" 
774                                                        sym_to_find)
775                  CasmTarget _
776                     -> pprPanic "ByteCodeGen.generateCCall: casm" (ppr ccall_spec)
777      in
778          get_target_info        `thenBc` \ (is_static, static_target_addr) ->
779      let
780
781          -- Get the arg reps, zapping the leading Addr# in the dynamic case
782          a_reps -- | trace (showSDoc (ppr a_reps_pushed_RAW)) False = error "???"
783                 | is_static = a_reps_pushed_RAW
784                 | otherwise = if null a_reps_pushed_RAW 
785                               then panic "ByteCodeGen.generateCCall: dyn with no args"
786                               else tail a_reps_pushed_RAW
787
788          -- push the Addr#
789          (push_Addr, d_after_Addr)
790             | is_static
791             = (toOL [PUSH_UBX (Right static_target_addr) addr_usizeW,
792                      PUSH_TAG addr_usizeW],
793                d_after_args + addr_tsizeW)
794             | otherwise -- is already on the stack
795             = (nilOL, d_after_args)
796
797          -- Push the return placeholder.  For a call returning nothing,
798          -- this is a VoidRep (tag).
799          r_usizeW  = untaggedSizeW r_rep
800          r_tsizeW  = taggedSizeW r_rep
801          d_after_r = d_after_Addr + r_tsizeW
802          r_lit     = mkDummyLiteral r_rep
803          push_r    = (if   returns_void 
804                       then nilOL 
805                       else unitOL (PUSH_UBX (Left r_lit) r_usizeW))
806                       `appOL` 
807                       unitOL (PUSH_TAG r_usizeW)
808
809          -- generate the marshalling code we're going to call
810          r_offW       = 0 
811          addr_offW    = r_tsizeW
812          arg1_offW    = r_tsizeW + addr_tsizeW
813          args_offW    = map (arg1_offW +) 
814                             (init (scanl (+) 0 (map taggedSizeW a_reps)))
815      in
816          ioToBc (mkMarshalCode cconv
817                     (r_offW, r_rep) addr_offW
818                     (zip args_offW a_reps))     `thenBc` \ addr_of_marshaller ->
819          recordMallocBc addr_of_marshaller      `thenBc_`
820      let
821          -- do the call
822          do_call      = unitOL (CCALL addr_of_marshaller)
823          -- slide and return
824          wrapup       = mkSLIDE r_tsizeW (d_after_r - r_tsizeW - s)
825                         `snocOL` RETURN r_rep
826      in
827          --trace (show (arg1_offW, args_offW  ,  (map taggedSizeW a_reps) )) (
828          returnBc (
829          push_args `appOL`
830          push_Addr `appOL` push_r `appOL` do_call `appOL` wrapup
831          )
832          --)
833
834
835 -- Make a dummy literal, to be used as a placeholder for FFI return
836 -- values on the stack.
837 mkDummyLiteral :: PrimRep -> Literal
838 mkDummyLiteral pr
839    = case pr of
840         CharRep   -> MachChar 0
841         IntRep    -> MachInt 0
842         WordRep   -> MachWord 0
843         DoubleRep -> MachDouble 0
844         FloatRep  -> MachFloat 0
845         AddrRep   | taggedSizeW AddrRep == taggedSizeW WordRep -> MachWord 0
846         _         -> moan64 "mkDummyLiteral" (ppr pr)
847
848
849 -- Convert (eg) 
850 --     PrelGHC.Char# -> PrelGHC.State# PrelGHC.RealWorld
851 --                   -> (# PrelGHC.State# PrelGHC.RealWorld, PrelGHC.Int# #)
852 --
853 -- to  Just IntRep
854 -- and check that an unboxed pair is returned wherein the first arg is VoidRep'd.
855 --
856 -- Alternatively, for call-targets returning nothing, convert
857 --
858 --     PrelGHC.Char# -> PrelGHC.State# PrelGHC.RealWorld
859 --                   -> (# PrelGHC.State# PrelGHC.RealWorld #)
860 --
861 -- to  Nothing
862
863 maybe_getCCallReturnRep :: Type -> Maybe PrimRep
864 maybe_getCCallReturnRep fn_ty
865    = let (a_tys, r_ty) = splitRepFunTys fn_ty
866          maybe_r_rep_to_go  
867             = if isSingleton r_reps then Nothing else Just (r_reps !! 1)
868          (r_tycon, r_reps) 
869             = case splitTyConApp_maybe (repType r_ty) of
870                       (Just (tyc, tys)) -> (tyc, map typePrimRep tys)
871                       Nothing -> blargh
872          ok = ( ( r_reps `lengthIs` 2 && VoidRep == head r_reps)
873                 || r_reps == [VoidRep] )
874               && isUnboxedTupleTyCon r_tycon
875               && case maybe_r_rep_to_go of
876                     Nothing    -> True
877                     Just r_rep -> r_rep /= PtrRep
878                                   -- if it was, it would be impossible 
879                                   -- to create a valid return value 
880                                   -- placeholder on the stack
881          blargh = pprPanic "maybe_getCCallReturn: can't handle:" 
882                            (pprType fn_ty)
883      in 
884      --trace (showSDoc (ppr (a_reps, r_reps))) (
885      if ok then maybe_r_rep_to_go else blargh
886      --)
887
888 atomRep (AnnVar v)    = typePrimRep (idType v)
889 atomRep (AnnLit l)    = literalPrimRep l
890 atomRep (AnnNote n b) = atomRep (snd b)
891 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
892 atomRep (AnnLam x e) | isTyVar x = atomRep (snd e)
893 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
894
895
896 -- Compile code which expects an unboxed Int on the top of stack,
897 -- (call it i), and pushes the i'th closure in the supplied list 
898 -- as a consequence.
899 implement_tagToId :: [Name] -> BcM BCInstrList
900 implement_tagToId names
901    = ASSERT(not (null names))
902      getLabelsBc (length names)                 `thenBc` \ labels ->
903      getLabelBc                                 `thenBc` \ label_fail ->
904      getLabelBc                                 `thenBc` \ label_exit ->
905      zip4 labels (tail labels ++ [label_fail])
906                  [0 ..] names                   `bind`   \ infos ->
907      map (mkStep label_exit) infos              `bind`   \ steps ->
908      returnBc (concatOL steps
909                `appOL` 
910                toOL [LABEL label_fail, CASEFAIL, LABEL label_exit])
911      where
912         mkStep l_exit (my_label, next_label, n, name_for_n)
913            = toOL [LABEL my_label, 
914                    TESTEQ_I n next_label, 
915                    PUSH_G (Left name_for_n), 
916                    JMP l_exit]
917
918
919 -- Make code to unpack the top-of-stack constructor onto the stack, 
920 -- adding tags for the unboxed bits.  Takes the PrimReps of the 
921 -- constructor's arguments.  off_h and off_s are travelling offsets
922 -- along the constructor and the stack.
923 --
924 -- Supposing a constructor in the heap has layout
925 --
926 --      Itbl p_1 ... p_i np_1 ... np_j
927 --
928 -- then we add to the stack, shown growing down, the following:
929 --
930 --    (previous stack)
931 --         p_i
932 --         ...
933 --         p_1
934 --         np_j
935 --         tag_for(np_j)
936 --         ..
937 --         np_1
938 --         tag_for(np_1)
939 --
940 -- so that in the common case (ptrs only) a single UNPACK instr can
941 -- copy all the payload of the constr onto the stack with no further ado.
942
943 mkUnpackCode :: [Id]    -- constr args
944              -> Int     -- depth before unpack
945              -> BCEnv   -- env before unpack
946              -> (BCInstrList, Int, BCEnv)
947 mkUnpackCode vars d p
948    = --trace ("mkUnpackCode: " ++ showSDocDebug (ppr vars)
949      --       ++ " --> " ++ show d' ++ "\n" ++ showSDocDebug (ppBCEnv p')
950      --       ++ "\n") (
951      (code_p `appOL` code_np, d', p')
952      --)
953      where
954         -- vars with reps
955         vreps = [(var, typePrimRep (idType var)) | var <- vars]
956
957         -- ptrs and nonptrs, forward
958         vreps_p  = filter (isFollowableRep.snd) vreps
959         vreps_np = filter (not.isFollowableRep.snd) vreps
960
961         -- the order in which we will augment the environment
962         vreps_env = reverse vreps_p ++ reverse vreps_np
963
964         -- new env and depth
965         vreps_env_tszsw = map (taggedSizeW.snd) vreps_env
966         p' = addListToFM p (zip (map fst vreps_env) 
967                                 (mkStackOffsets d vreps_env_tszsw))
968         d' = d + sum vreps_env_tszsw
969
970         -- code to unpack the ptrs
971         ptrs_szw = sum (map (untaggedSizeW.snd) vreps_p)
972         code_p | null vreps_p = nilOL
973                | otherwise    = unitOL (UNPACK ptrs_szw)
974
975         -- code to unpack the nonptrs
976         vreps_env_uszw = sum (map (untaggedSizeW.snd) vreps_env)
977         code_np = do_nptrs vreps_env_uszw ptrs_szw (reverse (map snd vreps_np))
978         do_nptrs off_h off_s [] = nilOL
979         do_nptrs off_h off_s (npr:nprs)
980            | npr `elem` [IntRep, WordRep, FloatRep, DoubleRep, CharRep, AddrRep]
981            = approved
982            | otherwise
983            = moan64 "ByteCodeGen.mkUnpackCode" (ppr npr)
984              where
985                 approved = UPK_TAG usizeW (off_h-usizeW) off_s   `consOL` theRest
986                 theRest  = do_nptrs (off_h-usizeW) (off_s + tsizeW) nprs
987                 usizeW   = untaggedSizeW npr
988                 tsizeW   = taggedSizeW npr
989
990
991 -- Push an atom onto the stack, returning suitable code & number of
992 -- stack words used.  Pushes it either tagged or untagged, since 
993 -- pushAtom is used to set up the stack prior to copying into the
994 -- heap for both APs (requiring tags) and constructors (which don't).
995 --
996 -- NB this means NO GC between pushing atoms for a constructor and
997 -- copying them into the heap.  It probably also means that 
998 -- tail calls MUST be of the form atom{atom ... atom} since if the
999 -- expression head was allowed to be arbitrary, there could be GC
1000 -- in between pushing the arg atoms and completing the head.
1001 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
1002 -- isn't a problem; but only if arbitrary graph construction for the
1003 -- head doesn't leave this BCO, since GC might happen at the start of
1004 -- each BCO (we consult doYouWantToGC there).
1005 --
1006 -- Blargh.  JRS 001206
1007 --
1008 -- NB (further) that the env p must map each variable to the highest-
1009 -- numbered stack slot for it.  For example, if the stack has depth 4 
1010 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
1011 -- the tag in stack[5], the stack will have depth 6, and p must map v to
1012 -- 5 and not to 4.  Stack locations are numbered from zero, so a depth
1013 -- 6 stack has valid words 0 .. 5.
1014
1015 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> BcM (BCInstrList, Int)
1016 pushAtom tagged d p (AnnVar v)
1017
1018    | idPrimRep v == VoidRep
1019    = if tagged then returnBc (unitOL (PUSH_TAG 0), 1) 
1020                else panic "ByteCodeGen.pushAtom(VoidRep,untaggedly)"
1021
1022    | isFCallId v
1023    = pprPanic "pushAtom: shouldn't get an FCallId here" (ppr v)
1024
1025    | Just primop <- isPrimOpId_maybe v
1026    = returnBc (unitOL (PUSH_G (Right primop)), 1)
1027
1028    | otherwise
1029    = let  {-
1030           str = "\npushAtom " ++ showSDocDebug (ppr v) 
1031                ++ " :: " ++ showSDocDebug (pprType (idType v))
1032                ++ ", depth = " ++ show d
1033                ++ ", tagged = " ++ show tagged ++ ", env =\n" ++ 
1034                showSDocDebug (ppBCEnv p)
1035                ++ " --> words: " ++ show (snd result) ++ "\n" ++
1036                showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
1037                ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
1038          -}
1039
1040          result
1041             = case lookupBCEnv_maybe p v of
1042                  Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), nwords)
1043                  Nothing  -> ASSERT(sz_t == 1) (unitOL (PUSH_G (Left nm)), nwords)
1044
1045          nm = case isDataConId_maybe v of
1046                  Just c  -> getName c
1047                  Nothing -> getName v
1048
1049          sz_t   = taggedIdSizeW v
1050          sz_u   = untaggedIdSizeW v
1051          nwords = if tagged then sz_t else sz_u
1052      in
1053          returnBc result
1054
1055 pushAtom True d p (AnnLit lit)
1056    = pushAtom False d p (AnnLit lit)            `thenBc` \ (ubx_code, ubx_size) ->
1057      returnBc (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
1058
1059 pushAtom False d p (AnnLit lit)
1060    = case lit of
1061         MachWord w   -> code WordRep
1062         MachInt i    -> code IntRep
1063         MachFloat r  -> code FloatRep
1064         MachDouble r -> code DoubleRep
1065         MachChar c   -> code CharRep
1066         MachStr s    -> pushStr s
1067      where
1068         code rep
1069            = let size_host_words = untaggedSizeW rep
1070              in  returnBc (unitOL (PUSH_UBX (Left lit) size_host_words), 
1071                            size_host_words)
1072
1073         pushStr s 
1074            = let getMallocvilleAddr
1075                     = case s of
1076                          CharStr s i -> returnBc (A# s)
1077
1078                          FastString _ l ba -> 
1079                             -- sigh, a string in the heap is no good to us.
1080                             -- We need a static C pointer, since the type of 
1081                             -- a string literal is Addr#.  So, copy the string 
1082                             -- into C land and introduce a memory leak 
1083                             -- at the same time.
1084                             let n = I# l
1085                             -- CAREFUL!  Chars are 32 bits in ghc 4.09+
1086                             in  ioToBc (mallocBytes (n+1)) `thenBc` \ (Ptr a#) ->
1087                                 recordMallocBc (A# a#)     `thenBc_`
1088                                 ioToBc (
1089                                    do strncpy (Ptr a#) ba (fromIntegral n)
1090                                       writeCharOffAddr (A# a#) n '\0'
1091                                       return (A# a#)
1092                                    )
1093                          other -> panic "ByteCodeGen.pushAtom.pushStr"
1094              in
1095                 getMallocvilleAddr `thenBc` \ addr ->
1096                 -- Get the addr on the stack, untaggedly
1097                    returnBc (unitOL (PUSH_UBX (Right addr) 1), 1)
1098
1099
1100
1101
1102
1103 pushAtom tagged d p (AnnApp f (_, AnnType _))
1104    = pushAtom tagged d p (snd f)
1105
1106 pushAtom tagged d p (AnnNote note e)
1107    = pushAtom tagged d p (snd e)
1108
1109 pushAtom tagged d p (AnnLam x e) 
1110    | isTyVar x 
1111    = pushAtom tagged d p (snd e)
1112
1113 pushAtom tagged d p other
1114    = pprPanic "ByteCodeGen.pushAtom" 
1115               (pprCoreExpr (deAnnotate (undefined, other)))
1116
1117 foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
1118
1119
1120 -- Given a bunch of alts code and their discrs, do the donkey work
1121 -- of making a multiway branch using a switch tree.
1122 -- What a load of hassle!
1123 mkMultiBranch :: Maybe Int      -- # datacons in tycon, if alg alt
1124                                 -- a hint; generates better code
1125                                 -- Nothing is always safe
1126               -> [(Discr, BCInstrList)] 
1127               -> BcM BCInstrList
1128 mkMultiBranch maybe_ncons raw_ways
1129    = let d_way     = filter (isNoDiscr.fst) raw_ways
1130          notd_ways = naturalMergeSortLe 
1131                         (\w1 w2 -> leAlt (fst w1) (fst w2))
1132                         (filter (not.isNoDiscr.fst) raw_ways)
1133
1134          mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
1135          mkTree [] range_lo range_hi = returnBc the_default
1136
1137          mkTree [val] range_lo range_hi
1138             | range_lo `eqAlt` range_hi 
1139             = returnBc (snd val)
1140             | otherwise
1141             = getLabelBc                                `thenBc` \ label_neq ->
1142               returnBc (mkTestEQ (fst val) label_neq 
1143                         `consOL` (snd val
1144                         `appOL`   unitOL (LABEL label_neq)
1145                         `appOL`   the_default))
1146
1147          mkTree vals range_lo range_hi
1148             = let n = length vals `div` 2
1149                   vals_lo = take n vals
1150                   vals_hi = drop n vals
1151                   v_mid = fst (head vals_hi)
1152               in
1153               getLabelBc                                `thenBc` \ label_geq ->
1154               mkTree vals_lo range_lo (dec v_mid)       `thenBc` \ code_lo ->
1155               mkTree vals_hi v_mid range_hi             `thenBc` \ code_hi ->
1156               returnBc (mkTestLT v_mid label_geq
1157                         `consOL` (code_lo
1158                         `appOL`   unitOL (LABEL label_geq)
1159                         `appOL`   code_hi))
1160  
1161          the_default 
1162             = case d_way of [] -> unitOL CASEFAIL
1163                             [(_, def)] -> def
1164
1165          -- None of these will be needed if there are no non-default alts
1166          (mkTestLT, mkTestEQ, init_lo, init_hi)
1167             | null notd_ways
1168             = panic "mkMultiBranch: awesome foursome"
1169             | otherwise
1170             = case fst (head notd_ways) of {
1171               DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
1172                             \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
1173                             DiscrI minBound,
1174                             DiscrI maxBound );
1175               DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
1176                             \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
1177                             DiscrF minF,
1178                             DiscrF maxF );
1179               DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
1180                             \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
1181                             DiscrD minD,
1182                             DiscrD maxD );
1183               DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
1184                             \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
1185                             DiscrP algMinBound,
1186                             DiscrP algMaxBound )
1187               }
1188
1189          (algMinBound, algMaxBound)
1190             = case maybe_ncons of
1191                  Just n  -> (0, n - 1)
1192                  Nothing -> (minBound, maxBound)
1193
1194          (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
1195          (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
1196          (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
1197          (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
1198          NoDiscr     `eqAlt` NoDiscr     = True
1199          _           `eqAlt` _           = False
1200
1201          (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
1202          (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
1203          (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
1204          (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
1205          NoDiscr     `leAlt` NoDiscr     = True
1206          _           `leAlt` _           = False
1207
1208          isNoDiscr NoDiscr = True
1209          isNoDiscr _       = False
1210
1211          dec (DiscrI i) = DiscrI (i-1)
1212          dec (DiscrP i) = DiscrP (i-1)
1213          dec other      = other         -- not really right, but if you
1214                 -- do cases on floating values, you'll get what you deserve
1215
1216          -- same snotty comment applies to the following
1217          minF, maxF :: Float
1218          minD, maxD :: Double
1219          minF = -1.0e37
1220          maxF =  1.0e37
1221          minD = -1.0e308
1222          maxD =  1.0e308
1223      in
1224          mkTree notd_ways init_lo init_hi
1225
1226 \end{code}
1227
1228 %************************************************************************
1229 %*                                                                      *
1230 \subsection{Supporting junk for the compilation schemes}
1231 %*                                                                      *
1232 %************************************************************************
1233
1234 \begin{code}
1235
1236 -- Describes case alts
1237 data Discr 
1238    = DiscrI Int
1239    | DiscrF Float
1240    | DiscrD Double
1241    | DiscrP Int
1242    | NoDiscr
1243
1244 instance Outputable Discr where
1245    ppr (DiscrI i) = int i
1246    ppr (DiscrF f) = text (show f)
1247    ppr (DiscrD d) = text (show d)
1248    ppr (DiscrP i) = int i
1249    ppr NoDiscr    = text "DEF"
1250
1251
1252 -- Find things in the BCEnv (the what's-on-the-stack-env)
1253 -- See comment preceding pushAtom for precise meaning of env contents
1254 --lookupBCEnv :: BCEnv -> Id -> Int
1255 --lookupBCEnv env nm
1256 --   = case lookupFM env nm of
1257 --        Nothing -> pprPanic "lookupBCEnv" 
1258 --                            (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
1259 --        Just xx -> xx
1260
1261 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
1262 lookupBCEnv_maybe = lookupFM
1263
1264
1265 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
1266 taggedIdSizeW   = taggedSizeW   . typePrimRep . idType
1267 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
1268
1269 unboxedTupleException :: a
1270 unboxedTupleException 
1271    = throwDyn 
1272         (Panic 
1273            ("Bytecode generator can't handle unboxed tuples.  Possibly due\n" ++
1274             "\tto foreign import/export decls in source.  Workaround:\n" ++
1275             "\tcompile this module to a .o file, then restart session."))
1276
1277
1278 mkSLIDE n d = if d == 0 then nilOL else unitOL (SLIDE n d)
1279 bind x f    = f x
1280
1281 \end{code}
1282
1283 %************************************************************************
1284 %*                                                                      *
1285 \subsection{The bytecode generator's monad}
1286 %*                                                                      *
1287 %************************************************************************
1288
1289 \begin{code}
1290 data BcM_State 
1291    = BcM_State { bcos      :: [ProtoBCO Name],  -- accumulates completed BCOs
1292                  nextlabel :: Int,              -- for generating local labels
1293                  malloced  :: [Addr] }          -- ptrs malloced for current BCO
1294                                                 -- Should be free()d when it is GCd
1295 type BcM r = BcM_State -> IO (BcM_State, r)
1296
1297 ioToBc :: IO a -> BcM a
1298 ioToBc io st = do x <- io 
1299                   return (st, x)
1300
1301 runBc :: BcM_State -> BcM r -> IO (BcM_State, r)
1302 runBc st0 m = do (st1, res) <- m st0
1303                  return (st1, res)
1304
1305 thenBc :: BcM a -> (a -> BcM b) -> BcM b
1306 thenBc expr cont st0
1307    = do (st1, q) <- expr st0
1308         (st2, r) <- cont q st1
1309         return (st2, r)
1310
1311 thenBc_ :: BcM a -> BcM b -> BcM b
1312 thenBc_ expr cont st0
1313    = do (st1, q) <- expr st0
1314         (st2, r) <- cont st1
1315         return (st2, r)
1316
1317 returnBc :: a -> BcM a
1318 returnBc result st = return (st, result)
1319
1320
1321 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
1322 mapBc f []     = returnBc []
1323 mapBc f (x:xs)
1324   = f x          `thenBc` \ r  ->
1325     mapBc f xs   `thenBc` \ rs ->
1326     returnBc (r:rs)
1327
1328 emitBc :: ([Addr] -> ProtoBCO Name) -> BcM ()
1329 emitBc bco st
1330    = return (st{bcos = bco (malloced st) : bcos st, malloced=[]}, ())
1331
1332 newbcoBc :: BcM ()
1333 newbcoBc st
1334    | not (null (malloced st)) 
1335    = panic "ByteCodeGen.newbcoBc: missed prior emitBc?"
1336    | otherwise
1337    = return (st, ())
1338
1339 recordMallocBc :: Addr -> BcM ()
1340 recordMallocBc a st
1341    = return (st{malloced = a : malloced st}, ())
1342
1343 getLabelBc :: BcM Int
1344 getLabelBc st
1345    = return (st{nextlabel = 1 + nextlabel st}, nextlabel st)
1346
1347 getLabelsBc :: Int -> BcM [Int]
1348 getLabelsBc n st
1349    = let ctr = nextlabel st 
1350      in return (st{nextlabel = ctr+n}, [ctr .. ctr+n-1])
1351
1352 \end{code}