4d2fa738765dc4af40651321da5668e166a989de
[ghc-hetmet.git] / ghc / compiler / ghci / ByteCodeGen.lhs
1 %
2 % (c) The University of Glasgow 2002
3 %
4 \section[ByteCodeGen]{Generate bytecode from Core}
5
6 \begin{code}
7 module ByteCodeGen ( UnlinkedBCO, byteCodeGen, coreExprToBCOs ) where
8
9 #include "HsVersions.h"
10
11 import ByteCodeInstr
12 import ByteCodeFFI      ( mkMarshalCode, moan64 )
13 import ByteCodeAsm      ( CompiledByteCode(..), UnlinkedBCO, 
14                           assembleBCO, assembleBCOs, iNTERP_STACK_CHECK_THRESH )
15 import ByteCodeLink     ( lookupStaticPtr )
16
17 import Outputable
18 import Name             ( Name, getName, mkSystemVarName )
19 import Id
20 import FiniteMap
21 import ForeignCall      ( ForeignCall(..), CCallTarget(..), CCallSpec(..) )
22 import HscTypes         ( TypeEnv, typeEnvTyCons, typeEnvClasses )
23 import CoreUtils        ( exprType )
24 import CoreSyn
25 import PprCore          ( pprCoreExpr )
26 import Literal          ( Literal(..), literalType )
27 import PrimOp           ( PrimOp(..) )
28 import CoreFVs          ( freeVars )
29 import Type             ( isUnLiftedType, splitTyConApp_maybe )
30 import DataCon          ( DataCon, dataConTag, fIRST_TAG, dataConTyCon, 
31                           isUnboxedTupleCon, isNullaryRepDataCon, dataConWorkId,
32                           dataConRepArity )
33 import TyCon            ( TyCon, tyConFamilySize, isDataTyCon, 
34                           tyConDataCons, isUnboxedTupleTyCon )
35 import Class            ( Class, classTyCon )
36 import Type             ( Type, repType, splitFunTys, dropForAlls, pprType )
37 import Util
38 import DataCon          ( dataConRepArity )
39 import Var              ( isTyVar )
40 import VarSet           ( VarSet, varSetElems )
41 import TysPrim          ( arrayPrimTyCon, mutableArrayPrimTyCon,
42                           byteArrayPrimTyCon, mutableByteArrayPrimTyCon
43                         )
44 import DynFlags ( DynFlags, DynFlag(..) )
45 import ErrUtils         ( showPass, dumpIfSet_dyn )
46 import Unique           ( mkPseudoUniqueE )
47 import FastString       ( FastString(..), unpackFS )
48 import Panic            ( GhcException(..) )
49 import SMRep            ( typeCgRep, arrWordsHdrSize, arrPtrsHdrSize, StgWord, 
50                           CgRep(..), cgRepSizeW, isFollowableArg, idCgRep )
51 import Bitmap           ( intsToReverseBitmap, mkBitmap )
52 import OrdList
53 import Constants        ( wORD_SIZE )
54
55 import Data.List        ( intersperse, sortBy, zip4, zip5, partition )
56 import Foreign          ( Ptr, castPtr, mallocBytes, pokeByteOff, Word8 )
57 import Foreign.C        ( CInt )
58 import Control.Exception        ( throwDyn )
59
60 import GHC.Exts         ( Int(..), ByteArray# )
61
62 import Control.Monad    ( when )
63 import Data.Char        ( ord, chr )
64
65 -- -----------------------------------------------------------------------------
66 -- Generating byte code for a complete module 
67
68 byteCodeGen :: DynFlags
69             -> [CoreBind]
70             -> [TyCon]
71             -> IO CompiledByteCode
72 byteCodeGen dflags binds tycs
73    = do showPass dflags "ByteCodeGen"
74
75         let flatBinds = [ (bndr, freeVars rhs) 
76                         | (bndr, rhs) <- flattenBinds binds]
77
78         (BcM_State final_ctr mallocd, proto_bcos)
79            <- runBc (mapM schemeTopBind flatBinds)
80
81         when (notNull mallocd)
82              (panic "ByteCodeGen.byteCodeGen: missing final emitBc?")
83
84         dumpIfSet_dyn dflags Opt_D_dump_BCOs
85            "Proto-BCOs" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
86
87         assembleBCOs proto_bcos tycs
88         
89 -- -----------------------------------------------------------------------------
90 -- Generating byte code for an expression
91
92 -- Returns: (the root BCO for this expression, 
93 --           a list of auxilary BCOs resulting from compiling closures)
94 coreExprToBCOs :: DynFlags
95                -> CoreExpr
96                -> IO UnlinkedBCO
97 coreExprToBCOs dflags expr
98  = do showPass dflags "ByteCodeGen"
99
100       -- create a totally bogus name for the top-level BCO; this
101       -- should be harmless, since it's never used for anything
102       let invented_name  = mkSystemVarName (mkPseudoUniqueE 0) FSLIT("ExprTopLevel")
103           invented_id    = mkLocalId invented_name (panic "invented_id's type")
104           
105       (BcM_State final_ctr mallocd, proto_bco) 
106          <- runBc (schemeTopBind (invented_id, freeVars expr))
107
108       when (notNull mallocd)
109            (panic "ByteCodeGen.coreExprToBCOs: missing final emitBc?")
110
111       dumpIfSet_dyn dflags Opt_D_dump_BCOs "Proto-BCOs" (ppr proto_bco)
112
113       assembleBCO proto_bco
114
115
116 -- -----------------------------------------------------------------------------
117 -- Compilation schema for the bytecode generator
118
119 type BCInstrList = OrdList BCInstr
120
121 type Sequel = Int       -- back off to this depth before ENTER
122
123 -- Maps Ids to the offset from the stack _base_ so we don't have
124 -- to mess with it after each push/pop.
125 type BCEnv = FiniteMap Id Int   -- To find vars on the stack
126
127 ppBCEnv :: BCEnv -> SDoc
128 ppBCEnv p
129    = text "begin-env"
130      $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (fmToList p))))
131      $$ text "end-env"
132      where
133         pp_one (var, offset) = int offset <> colon <+> ppr var <+> ppr (idCgRep var)
134         cmp_snd x y = compare (snd x) (snd y)
135
136 -- Create a BCO and do a spot of peephole optimisation on the insns
137 -- at the same time.
138 mkProtoBCO
139    :: name
140    -> BCInstrList
141    -> Either  [AnnAlt Id VarSet] (AnnExpr Id VarSet)
142    -> Int
143    -> Int
144    -> [StgWord]
145    -> Bool      -- True <=> is a return point, rather than a function
146    -> [Ptr ()]
147    -> ProtoBCO name
148 mkProtoBCO nm instrs_ordlist origin arity bitmap_size bitmap
149   is_ret mallocd_blocks
150    = ProtoBCO {
151         protoBCOName = nm,
152         protoBCOInstrs = maybe_with_stack_check,
153         protoBCOBitmap = bitmap,
154         protoBCOBitmapSize = bitmap_size,
155         protoBCOArity = arity,
156         protoBCOExpr = origin,
157         protoBCOPtrs = mallocd_blocks
158       }
159      where
160         -- Overestimate the stack usage (in words) of this BCO,
161         -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit
162         -- stack check.  (The interpreter always does a stack check
163         -- for iNTERP_STACK_CHECK_THRESH words at the start of each
164         -- BCO anyway, so we only need to add an explicit on in the
165         -- (hopefully rare) cases when the (overestimated) stack use
166         -- exceeds iNTERP_STACK_CHECK_THRESH.
167         maybe_with_stack_check
168            | is_ret = peep_d
169                 -- don't do stack checks at return points;
170                 -- everything is aggregated up to the top BCO
171                 -- (which must be a function)
172            | stack_overest >= 65535
173            = pprPanic "mkProtoBCO: stack use won't fit in 16 bits" 
174                       (int stack_overest)
175            | stack_overest >= iNTERP_STACK_CHECK_THRESH
176            = STKCHECK stack_overest : peep_d
177            | otherwise
178            = peep_d     -- the supposedly common case
179              
180         stack_overest = sum (map bciStackUse peep_d)
181
182         -- Merge local pushes
183         peep_d = peep (fromOL instrs_ordlist)
184
185         peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
186            = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
187         peep (PUSH_L off1 : PUSH_L off2 : rest)
188            = PUSH_LL off1 (off2-1) : peep rest
189         peep (i:rest)
190            = i : peep rest
191         peep []
192            = []
193
194 argBits :: [CgRep] -> [Bool]
195 argBits [] = []
196 argBits (rep : args)
197   | isFollowableArg rep = False : argBits args
198   | otherwise = take (cgRepSizeW rep) (repeat True) ++ argBits args
199
200 -- -----------------------------------------------------------------------------
201 -- schemeTopBind
202
203 -- Compile code for the right-hand side of a top-level binding
204
205 schemeTopBind :: (Id, AnnExpr Id VarSet) -> BcM (ProtoBCO Name)
206
207
208 schemeTopBind (id, rhs)
209   | Just data_con <- isDataConWorkId_maybe id,
210     isNullaryRepDataCon data_con
211   =     -- Special case for the worker of a nullary data con.
212         -- It'll look like this:        Nil = /\a -> Nil a
213         -- If we feed it into schemeR, we'll get 
214         --      Nil = Nil
215         -- because mkConAppCode treats nullary constructor applications
216         -- by just re-using the single top-level definition.  So
217         -- for the worker itself, we must allocate it directly.
218     emitBc (mkProtoBCO (getName id) (toOL [PACK data_con 0, ENTER])
219                        (Right rhs) 0 0 [{-no bitmap-}] False{-not alts-})
220
221   | otherwise
222   = schemeR [{- No free variables -}] (id, rhs)
223
224 -- -----------------------------------------------------------------------------
225 -- schemeR
226
227 -- Compile code for a right-hand side, to give a BCO that,
228 -- when executed with the free variables and arguments on top of the stack,
229 -- will return with a pointer to the result on top of the stack, after
230 -- removing the free variables and arguments.
231 --
232 -- Park the resulting BCO in the monad.  Also requires the
233 -- variable to which this value was bound, so as to give the
234 -- resulting BCO a name. 
235
236 schemeR :: [Id]                 -- Free vars of the RHS, ordered as they
237                                 -- will appear in the thunk.  Empty for
238                                 -- top-level things, which have no free vars.
239         -> (Id, AnnExpr Id VarSet)
240         -> BcM (ProtoBCO Name)
241 schemeR fvs (nm, rhs) 
242 {-
243    | trace (showSDoc (
244               (char ' '
245                $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
246                $$ pprCoreExpr (deAnnotate rhs)
247                $$ char ' '
248               ))) False
249    = undefined
250    | otherwise
251 -}
252    = schemeR_wrk fvs nm rhs (collect [] rhs)
253
254 collect xs (_, AnnNote note e) = collect xs e
255 collect xs (_, AnnLam x e)     = collect (if isTyVar x then xs else (x:xs)) e
256 collect xs (_, not_lambda)     = (reverse xs, not_lambda)
257
258 schemeR_wrk fvs nm original_body (args, body)
259    = let 
260          all_args  = reverse args ++ fvs
261          arity     = length all_args
262          -- all_args are the args in reverse order.  We're compiling a function
263          -- \fv1..fvn x1..xn -> e 
264          -- i.e. the fvs come first
265
266          szsw_args = map idSizeW all_args
267          szw_args  = sum szsw_args
268          p_init    = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
269
270          -- make the arg bitmap
271          bits = argBits (reverse (map idCgRep all_args))
272          bitmap_size = length bits
273          bitmap = mkBitmap bits
274      in
275      schemeE szw_args 0 p_init body             `thenBc` \ body_code ->
276      emitBc (mkProtoBCO (getName nm) body_code (Right original_body)
277                 arity bitmap_size bitmap False{-not alts-})
278
279
280 fvsToEnv :: BCEnv -> VarSet -> [Id]
281 -- Takes the free variables of a right-hand side, and
282 -- delivers an ordered list of the local variables that will
283 -- be captured in the thunk for the RHS
284 -- The BCEnv argument tells which variables are in the local
285 -- environment: these are the ones that should be captured
286 --
287 -- The code that constructs the thunk, and the code that executes
288 -- it, have to agree about this layout
289 fvsToEnv p fvs = [v | v <- varSetElems fvs, 
290                       isId v,           -- Could be a type variable
291                       v `elemFM` p]
292
293 -- -----------------------------------------------------------------------------
294 -- schemeE
295
296 -- Compile code to apply the given expression to the remaining args
297 -- on the stack, returning a HNF.
298 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr' Id VarSet -> BcM BCInstrList
299
300 -- Delegate tail-calls to schemeT.
301 schemeE d s p e@(AnnApp f a) 
302    = schemeT d s p e
303
304 schemeE d s p e@(AnnVar v)
305    | not (isUnLiftedType v_type)
306    =  -- Lifted-type thing; push it in the normal way
307      schemeT d s p e
308
309    | otherwise
310    = -- Returning an unlifted value.  
311      -- Heave it on the stack, SLIDE, and RETURN.
312      pushAtom d p (AnnVar v)    `thenBc` \ (push, szw) ->
313      returnBc (push                     -- value onto stack
314                `appOL`  mkSLIDE szw (d-s)       -- clear to sequel
315                `snocOL` RETURN_UBX v_rep)       -- go
316    where
317       v_type = idType v
318       v_rep = typeCgRep v_type
319
320 schemeE d s p (AnnLit literal)
321    = pushAtom d p (AnnLit literal)      `thenBc` \ (push, szw) ->
322      let l_rep = typeCgRep (literalType literal)
323      in  returnBc (push                         -- value onto stack
324                    `appOL`  mkSLIDE szw (d-s)   -- clear to sequel
325                    `snocOL` RETURN_UBX l_rep)   -- go
326
327
328 schemeE d s p (AnnLet (AnnNonRec x (_,rhs)) (_,body))
329    | (AnnVar v, args_r_to_l) <- splitApp rhs,
330      Just data_con <- isDataConWorkId_maybe v,
331      dataConRepArity data_con == length args_r_to_l
332    =    -- Special case for a non-recursive let whose RHS is a 
333         -- saturatred constructor application.
334         -- Just allocate the constructor and carry on
335      mkConAppCode d s p data_con args_r_to_l    `thenBc` \ alloc_code ->
336      schemeE (d+1) s (addToFM p x d) body       `thenBc` \ body_code ->
337      returnBc (alloc_code `appOL` body_code)
338
339 -- General case for let.  Generates correct, if inefficient, code in
340 -- all situations.
341 schemeE d s p (AnnLet binds (_,body))
342    = let (xs,rhss) = case binds of AnnNonRec x rhs  -> ([x],[rhs])
343                                    AnnRec xs_n_rhss -> unzip xs_n_rhss
344          n_binds = length xs
345
346          fvss  = map (fvsToEnv p' . fst) rhss
347
348          -- Sizes of free vars
349          sizes = map (\rhs_fvs -> sum (map idSizeW rhs_fvs)) fvss
350
351          -- the arity of each rhs
352          arities = map (length . fst . collect []) rhss
353
354          -- This p', d' defn is safe because all the items being pushed
355          -- are ptrs, so all have size 1.  d' and p' reflect the stack
356          -- after the closures have been allocated in the heap (but not
357          -- filled in), and pointers to them parked on the stack.
358          p'    = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n_binds 1)))
359          d'    = d + n_binds
360          zipE  = zipEqual "schemeE"
361
362          -- ToDo: don't build thunks for things with no free variables
363          build_thunk dd [] size bco off
364             = returnBc (PUSH_BCO bco
365                         `consOL` unitOL (MKAP (off+size) size))
366          build_thunk dd (fv:fvs) size bco off = do
367               (push_code, pushed_szw) <- pushAtom dd p' (AnnVar fv) 
368               more_push_code <- build_thunk (dd+pushed_szw) fvs size bco off
369               returnBc (push_code `appOL` more_push_code)
370
371          alloc_code = toOL (zipWith mkAlloc sizes arities)
372            where mkAlloc sz 0     = ALLOC_AP sz
373                  mkAlloc sz arity = ALLOC_PAP arity sz
374
375          compile_bind d' fvs x rhs size off = do
376                 bco <- schemeR fvs (x,rhs)
377                 build_thunk d' fvs size bco off
378
379          compile_binds = 
380             [ compile_bind d' fvs x rhs size n
381             | (fvs, x, rhs, size, n) <- 
382                 zip5 fvss xs rhss sizes [n_binds, n_binds-1 .. 1]
383             ]
384      in do
385      body_code <- schemeE d' s p' body
386      thunk_codes <- sequence compile_binds
387      returnBc (alloc_code `appOL` concatOL thunk_codes `appOL` body_code)
388
389
390
391 schemeE d s p (AnnCase scrut bndr _ [(DataAlt dc, [bind1, bind2], rhs)])
392    | isUnboxedTupleCon dc, VoidArg <- typeCgRep (idType bind1)
393         -- Convert 
394         --      case .... of x { (# VoidArg'd-thing, a #) -> ... }
395         -- to
396         --      case .... of a { DEFAULT -> ... }
397         -- becuse the return convention for both are identical.
398         --
399         -- Note that it does not matter losing the void-rep thing from the
400         -- envt (it won't be bound now) because we never look such things up.
401
402    = --trace "automagic mashing of case alts (# VoidArg, a #)" $
403      doCase d s p scrut bind2 [(DEFAULT, [], rhs)] True{-unboxed tuple-}
404
405    | isUnboxedTupleCon dc, VoidArg <- typeCgRep (idType bind2)
406    = --trace "automagic mashing of case alts (# a, VoidArg #)" $
407      doCase d s p scrut bind1 [(DEFAULT, [], rhs)] True{-unboxed tuple-}
408
409 schemeE d s p (AnnCase scrut bndr _ [(DataAlt dc, [bind1], rhs)])
410    | isUnboxedTupleCon dc
411         -- Similarly, convert
412         --      case .... of x { (# a #) -> ... }
413         -- to
414         --      case .... of a { DEFAULT -> ... }
415    = --trace "automagic mashing of case alts (# a #)"  $
416      doCase d s p scrut bind1 [(DEFAULT, [], rhs)] True{-unboxed tuple-}
417
418 schemeE d s p (AnnCase scrut bndr _ alts)
419    = doCase d s p scrut bndr alts False{-not an unboxed tuple-}
420
421 schemeE d s p (AnnNote note (_, body))
422    = schemeE d s p body
423
424 schemeE d s p other
425    = pprPanic "ByteCodeGen.schemeE: unhandled case" 
426                (pprCoreExpr (deAnnotate' other))
427
428
429 -- Compile code to do a tail call.  Specifically, push the fn,
430 -- slide the on-stack app back down to the sequel depth,
431 -- and enter.  Four cases:
432 --
433 -- 0.  (Nasty hack).
434 --     An application "GHC.Prim.tagToEnum# <type> unboxed-int".
435 --     The int will be on the stack.  Generate a code sequence
436 --     to convert it to the relevant constructor, SLIDE and ENTER.
437 --
438 -- 1.  The fn denotes a ccall.  Defer to generateCCall.
439 --
440 -- 2.  (Another nasty hack).  Spot (# a::VoidArg, b #) and treat
441 --     it simply as  b  -- since the representations are identical
442 --     (the VoidArg takes up zero stack space).  Also, spot
443 --     (# b #) and treat it as  b.
444 --
445 -- 3.  Application of a constructor, by defn saturated.
446 --     Split the args into ptrs and non-ptrs, and push the nonptrs, 
447 --     then the ptrs, and then do PACK and RETURN.
448 --
449 -- 4.  Otherwise, it must be a function call.  Push the args
450 --     right to left, SLIDE and ENTER.
451
452 schemeT :: Int          -- Stack depth
453         -> Sequel       -- Sequel depth
454         -> BCEnv        -- stack env
455         -> AnnExpr' Id VarSet 
456         -> BcM BCInstrList
457
458 schemeT d s p app
459
460 --   | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
461 --   = panic "schemeT ?!?!"
462
463 --   | trace ("\nschemeT\n" ++ showSDoc (pprCoreExpr (deAnnotate' app)) ++ "\n") False
464 --   = error "?!?!" 
465
466    -- Case 0
467    | Just (arg, constr_names) <- maybe_is_tagToEnum_call
468    = pushAtom d p arg                   `thenBc` \ (push, arg_words) ->
469      implement_tagToId constr_names     `thenBc` \ tagToId_sequence ->
470      returnBc (push `appOL`  tagToId_sequence            
471                     `appOL`  mkSLIDE 1 (d+arg_words-s)
472                     `snocOL` ENTER)
473
474    -- Case 1
475    | Just (CCall ccall_spec) <- isFCallId_maybe fn
476    = generateCCall d s p ccall_spec fn args_r_to_l
477
478    -- Case 2: Constructor application
479    | Just con <- maybe_saturated_dcon,
480      isUnboxedTupleCon con
481    = case args_r_to_l of
482         [arg1,arg2] | isVoidArgAtom arg1 -> 
483                   unboxedTupleReturn d s p arg2
484         [arg1,arg2] | isVoidArgAtom arg2 -> 
485                   unboxedTupleReturn d s p arg1
486         _other -> unboxedTupleException
487
488    -- Case 3: Ordinary data constructor
489    | Just con <- maybe_saturated_dcon
490    = mkConAppCode d s p con args_r_to_l `thenBc` \ alloc_con ->
491      returnBc (alloc_con         `appOL` 
492                mkSLIDE 1 (d - s) `snocOL`
493                ENTER)
494
495    -- Case 4: Tail call of function 
496    | otherwise
497    = doTailCall d s p fn args_r_to_l
498
499    where
500       -- Detect and extract relevant info for the tagToEnum kludge.
501       maybe_is_tagToEnum_call
502          = let extract_constr_Names ty
503                  | Just (tyc, []) <- splitTyConApp_maybe (repType ty),
504                    isDataTyCon tyc
505                    = map (getName . dataConWorkId) (tyConDataCons tyc)
506                    -- NOTE: use the worker name, not the source name of
507                    -- the DataCon.  See DataCon.lhs for details.
508                  | otherwise
509                    = panic "maybe_is_tagToEnum_call.extract_constr_Ids"
510            in
511            case app of
512               (AnnApp (_, AnnApp (_, AnnVar v) (_, AnnType t)) arg)
513                  -> case isPrimOpId_maybe v of
514                        Just TagToEnumOp -> Just (snd arg, extract_constr_Names t)
515                        other            -> Nothing
516               other -> Nothing
517
518         -- Extract the args (R->L) and fn
519         -- The function will necessarily be a variable, 
520         -- because we are compiling a tail call
521       (AnnVar fn, args_r_to_l) = splitApp app
522
523       -- Only consider this to be a constructor application iff it is
524       -- saturated.  Otherwise, we'll call the constructor wrapper.
525       n_args = length args_r_to_l
526       maybe_saturated_dcon  
527         = case isDataConWorkId_maybe fn of
528                 Just con | dataConRepArity con == n_args -> Just con
529                 _ -> Nothing
530
531 -- -----------------------------------------------------------------------------
532 -- Generate code to build a constructor application, 
533 -- leaving it on top of the stack
534
535 mkConAppCode :: Int -> Sequel -> BCEnv
536              -> DataCon                 -- The data constructor
537              -> [AnnExpr' Id VarSet]    -- Args, in *reverse* order
538              -> BcM BCInstrList
539
540 mkConAppCode orig_d s p con []  -- Nullary constructor
541   = ASSERT( isNullaryRepDataCon con )
542     returnBc (unitOL (PUSH_G (getName (dataConWorkId con))))
543         -- Instead of doing a PACK, which would allocate a fresh
544         -- copy of this constructor, use the single shared version.
545
546 mkConAppCode orig_d s p con args_r_to_l 
547   = ASSERT( dataConRepArity con == length args_r_to_l )
548     do_pushery orig_d (non_ptr_args ++ ptr_args)
549  where
550         -- The args are already in reverse order, which is the way PACK
551         -- expects them to be.  We must push the non-ptrs after the ptrs.
552       (ptr_args, non_ptr_args) = partition isPtrAtom args_r_to_l
553
554       do_pushery d (arg:args)
555          = pushAtom d p arg                     `thenBc` \ (push, arg_words) ->
556            do_pushery (d+arg_words) args        `thenBc` \ more_push_code ->
557            returnBc (push `appOL` more_push_code)
558       do_pushery d []
559          = returnBc (unitOL (PACK con n_arg_words))
560          where
561            n_arg_words = d - orig_d
562
563
564 -- -----------------------------------------------------------------------------
565 -- Returning an unboxed tuple with one non-void component (the only
566 -- case we can handle).
567 --
568 -- Remember, we don't want to *evaluate* the component that is being
569 -- returned, even if it is a pointed type.  We always just return.
570
571 unboxedTupleReturn
572         :: Int -> Sequel -> BCEnv
573         -> AnnExpr' Id VarSet -> BcM BCInstrList
574 unboxedTupleReturn d s p arg = do
575   (push, sz) <- pushAtom d p arg
576   returnBc (push `appOL`
577             mkSLIDE sz (d-s) `snocOL`
578             RETURN_UBX (atomRep arg))
579
580 -- -----------------------------------------------------------------------------
581 -- Generate code for a tail-call
582
583 doTailCall
584         :: Int -> Sequel -> BCEnv
585         -> Id -> [AnnExpr' Id VarSet]
586         -> BcM BCInstrList
587 doTailCall init_d s p fn args
588   = do_pushes init_d args (map atomRep args)
589   where
590   do_pushes d [] reps = do
591         ASSERT( null reps ) return ()
592         (push_fn, sz) <- pushAtom d p (AnnVar fn)
593         ASSERT( sz == 1 ) return ()
594         returnBc (push_fn `appOL` (
595                   mkSLIDE ((d-init_d) + 1) (init_d - s) `appOL`
596                   unitOL ENTER))
597   do_pushes d args reps = do
598       let (push_apply, n, rest_of_reps) = findPushSeq reps
599           (these_args, rest_of_args) = splitAt n args
600       (next_d, push_code) <- push_seq d these_args
601       instrs <- do_pushes (next_d + 1) rest_of_args rest_of_reps 
602                 --                ^^^ for the PUSH_APPLY_ instruction
603       returnBc (push_code `appOL` (push_apply `consOL` instrs))
604
605   push_seq d [] = return (d, nilOL)
606   push_seq d (arg:args) = do
607     (push_code, sz) <- pushAtom d p arg 
608     (final_d, more_push_code) <- push_seq (d+sz) args
609     return (final_d, push_code `appOL` more_push_code)
610
611 -- v. similar to CgStackery.findMatch, ToDo: merge
612 findPushSeq (PtrArg: PtrArg: PtrArg: PtrArg: PtrArg: PtrArg: rest)
613   = (PUSH_APPLY_PPPPPP, 6, rest)
614 findPushSeq (PtrArg: PtrArg: PtrArg: PtrArg: PtrArg: rest)
615   = (PUSH_APPLY_PPPPP, 5, rest)
616 findPushSeq (PtrArg: PtrArg: PtrArg: PtrArg: rest)
617   = (PUSH_APPLY_PPPP, 4, rest)
618 findPushSeq (PtrArg: PtrArg: PtrArg: rest)
619   = (PUSH_APPLY_PPP, 3, rest)
620 findPushSeq (PtrArg: PtrArg: rest)
621   = (PUSH_APPLY_PP, 2, rest)
622 findPushSeq (PtrArg: rest)
623   = (PUSH_APPLY_P, 1, rest)
624 findPushSeq (VoidArg: rest)
625   = (PUSH_APPLY_V, 1, rest)
626 findPushSeq (NonPtrArg: rest)
627   = (PUSH_APPLY_N, 1, rest)
628 findPushSeq (FloatArg: rest)
629   = (PUSH_APPLY_F, 1, rest)
630 findPushSeq (DoubleArg: rest)
631   = (PUSH_APPLY_D, 1, rest)
632 findPushSeq (LongArg: rest)
633   = (PUSH_APPLY_L, 1, rest)
634 findPushSeq _
635   = panic "ByteCodeGen.findPushSeq"
636
637 -- -----------------------------------------------------------------------------
638 -- Case expressions
639
640 doCase  :: Int -> Sequel -> BCEnv
641         -> AnnExpr Id VarSet -> Id -> [AnnAlt Id VarSet]
642         -> Bool  -- True <=> is an unboxed tuple case, don't enter the result
643         -> BcM BCInstrList
644 doCase d s p (_,scrut)
645  bndr alts is_unboxed_tuple
646   = let
647         -- Top of stack is the return itbl, as usual.
648         -- underneath it is the pointer to the alt_code BCO.
649         -- When an alt is entered, it assumes the returned value is
650         -- on top of the itbl.
651         ret_frame_sizeW = 2
652
653         -- An unlifted value gets an extra info table pushed on top
654         -- when it is returned.
655         unlifted_itbl_sizeW | isAlgCase = 0
656                             | otherwise = 1
657
658         -- depth of stack after the return value has been pushed
659         d_bndr = d + ret_frame_sizeW + idSizeW bndr
660
661         -- depth of stack after the extra info table for an unboxed return
662         -- has been pushed, if any.  This is the stack depth at the
663         -- continuation.
664         d_alts = d_bndr + unlifted_itbl_sizeW
665
666         -- Env in which to compile the alts, not including
667         -- any vars bound by the alts themselves
668         p_alts = addToFM p bndr (d_bndr - 1)
669
670         bndr_ty = idType bndr
671         isAlgCase = not (isUnLiftedType bndr_ty) && not is_unboxed_tuple
672
673         -- given an alt, return a discr and code for it.
674         codeALt alt@(DEFAULT, _, (_,rhs))
675            = schemeE d_alts s p_alts rhs        `thenBc` \ rhs_code ->
676              returnBc (NoDiscr, rhs_code)
677         codeAlt alt@(discr, bndrs, (_,rhs))
678            -- primitive or nullary constructor alt: no need to UNPACK
679            | null real_bndrs = do
680                 rhs_code <- schemeE d_alts s p_alts rhs
681                 returnBc (my_discr alt, rhs_code)
682            -- algebraic alt with some binders
683            | ASSERT(isAlgCase) otherwise =
684              let
685                  (ptrs,nptrs) = partition (isFollowableArg.idCgRep) real_bndrs
686                  ptr_sizes    = map idSizeW ptrs
687                  nptrs_sizes  = map idSizeW nptrs
688                  bind_sizes   = ptr_sizes ++ nptrs_sizes
689                  size         = sum ptr_sizes + sum nptrs_sizes
690                  -- the UNPACK instruction unpacks in reverse order...
691                  p' = addListToFM p_alts 
692                         (zip (reverse (ptrs ++ nptrs))
693                           (mkStackOffsets d_alts (reverse bind_sizes)))
694              in do
695              rhs_code <- schemeE (d_alts+size) s p' rhs
696              return (my_discr alt, unitOL (UNPACK size) `appOL` rhs_code)
697            where
698              real_bndrs = filter (not.isTyVar) bndrs
699
700
701         my_discr (DEFAULT, binds, rhs) = NoDiscr {-shouldn't really happen-}
702         my_discr (DataAlt dc, binds, rhs) 
703            | isUnboxedTupleCon dc
704            = unboxedTupleException
705            | otherwise
706            = DiscrP (dataConTag dc - fIRST_TAG)
707         my_discr (LitAlt l, binds, rhs)
708            = case l of MachInt i     -> DiscrI (fromInteger i)
709                        MachFloat r   -> DiscrF (fromRational r)
710                        MachDouble r  -> DiscrD (fromRational r)
711                        MachChar i    -> DiscrI (ord i)
712                        _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
713
714         maybe_ncons 
715            | not isAlgCase = Nothing
716            | otherwise 
717            = case [dc | (DataAlt dc, _, _) <- alts] of
718                 []     -> Nothing
719                 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
720
721         -- the bitmap is relative to stack depth d, i.e. before the
722         -- BCO, info table and return value are pushed on.
723         -- This bit of code is v. similar to buildLivenessMask in CgBindery,
724         -- except that here we build the bitmap from the known bindings of
725         -- things that are pointers, whereas in CgBindery the code builds the
726         -- bitmap from the free slots and unboxed bindings.
727         -- (ToDo: merge?)
728         bitmap = intsToReverseBitmap d{-size-} (sortLe (<=) rel_slots)
729           where
730           binds = fmToList p
731           rel_slots = concat (map spread binds)
732           spread (id, offset)
733                 | isFollowableArg (idCgRep id) = [ rel_offset ]
734                 | otherwise = []
735                 where rel_offset = d - offset - 1
736
737      in do
738      alt_stuff <- mapM codeAlt alts
739      alt_final <- mkMultiBranch maybe_ncons alt_stuff
740      let 
741          alt_bco_name = getName bndr
742          alt_bco = mkProtoBCO alt_bco_name alt_final (Left alts)
743                         0{-no arity-} d{-bitmap size-} bitmap True{-is alts-}
744      -- in
745 --     trace ("case: bndr = " ++ showSDocDebug (ppr bndr) ++ "\ndepth = " ++ show d ++ "\nenv = \n" ++ showSDocDebug (ppBCEnv p) ++
746 --           "\n      bitmap = " ++ show bitmap) $ do
747      scrut_code <- schemeE (d + ret_frame_sizeW) (d + ret_frame_sizeW) p scrut
748      alt_bco' <- emitBc alt_bco
749      let push_alts
750             | isAlgCase = PUSH_ALTS alt_bco'
751             | otherwise = PUSH_ALTS_UNLIFTED alt_bco' (typeCgRep bndr_ty)
752      returnBc (push_alts `consOL` scrut_code)
753
754
755 -- -----------------------------------------------------------------------------
756 -- Deal with a CCall.
757
758 -- Taggedly push the args onto the stack R->L,
759 -- deferencing ForeignObj#s and adjusting addrs to point to
760 -- payloads in Ptr/Byte arrays.  Then, generate the marshalling
761 -- (machine) code for the ccall, and create bytecodes to call that and
762 -- then return in the right way.  
763
764 generateCCall :: Int -> Sequel          -- stack and sequel depths
765               -> BCEnv
766               -> CCallSpec              -- where to call
767               -> Id                     -- of target, for type info
768               -> [AnnExpr' Id VarSet]   -- args (atoms)
769               -> BcM BCInstrList
770
771 generateCCall d0 s p ccall_spec@(CCallSpec target cconv safety) fn args_r_to_l
772    = let 
773          -- useful constants
774          addr_sizeW = cgRepSizeW NonPtrArg
775
776          -- Get the args on the stack, with tags and suitably
777          -- dereferenced for the CCall.  For each arg, return the
778          -- depth to the first word of the bits for that arg, and the
779          -- CgRep of what was actually pushed.
780
781          pargs d [] = returnBc []
782          pargs d (a:az) 
783             = let arg_ty = repType (exprType (deAnnotate' a))
784
785               in case splitTyConApp_maybe arg_ty of
786                     -- Don't push the FO; instead push the Addr# it
787                     -- contains.
788                     Just (t, _)
789                      | t == arrayPrimTyCon || t == mutableArrayPrimTyCon
790                        -> pargs (d + addr_sizeW) az     `thenBc` \ rest ->
791                           parg_ArrayishRep arrPtrsHdrSize d p a
792                                                         `thenBc` \ code ->
793                           returnBc ((code,NonPtrArg):rest)
794
795                      | t == byteArrayPrimTyCon || t == mutableByteArrayPrimTyCon
796                        -> pargs (d + addr_sizeW) az     `thenBc` \ rest ->
797                           parg_ArrayishRep arrWordsHdrSize d p a
798                                                         `thenBc` \ code ->
799                           returnBc ((code,NonPtrArg):rest)
800
801                     -- Default case: push taggedly, but otherwise intact.
802                     other
803                        -> pushAtom d p a                `thenBc` \ (code_a, sz_a) ->
804                           pargs (d+sz_a) az             `thenBc` \ rest ->
805                           returnBc ((code_a, atomRep a) : rest)
806
807          -- Do magic for Ptr/Byte arrays.  Push a ptr to the array on
808          -- the stack but then advance it over the headers, so as to
809          -- point to the payload.
810          parg_ArrayishRep hdrSize d p a
811             = pushAtom d p a `thenBc` \ (push_fo, _) ->
812               -- The ptr points at the header.  Advance it over the
813               -- header and then pretend this is an Addr#.
814               returnBc (push_fo `snocOL` SWIZZLE 0 hdrSize)
815
816      in
817          pargs d0 args_r_to_l                   `thenBc` \ code_n_reps ->
818      let
819          (pushs_arg, a_reps_pushed_r_to_l) = unzip code_n_reps
820
821          push_args    = concatOL pushs_arg
822          d_after_args = d0 + sum (map cgRepSizeW a_reps_pushed_r_to_l)
823          a_reps_pushed_RAW
824             | null a_reps_pushed_r_to_l || head a_reps_pushed_r_to_l /= VoidArg
825             = panic "ByteCodeGen.generateCCall: missing or invalid World token?"
826             | otherwise
827             = reverse (tail a_reps_pushed_r_to_l)
828
829          -- Now: a_reps_pushed_RAW are the reps which are actually on the stack.
830          -- push_args is the code to do that.
831          -- d_after_args is the stack depth once the args are on.
832
833          -- Get the result rep.
834          (returns_void, r_rep)
835             = case maybe_getCCallReturnRep (idType fn) of
836                  Nothing -> (True,  VoidArg)
837                  Just rr -> (False, rr) 
838          {-
839          Because the Haskell stack grows down, the a_reps refer to 
840          lowest to highest addresses in that order.  The args for the call
841          are on the stack.  Now push an unboxed Addr# indicating
842          the C function to call.  Then push a dummy placeholder for the 
843          result.  Finally, emit a CCALL insn with an offset pointing to the 
844          Addr# just pushed, and a literal field holding the mallocville
845          address of the piece of marshalling code we generate.
846          So, just prior to the CCALL insn, the stack looks like this 
847          (growing down, as usual):
848                  
849             <arg_n>
850             ...
851             <arg_1>
852             Addr# address_of_C_fn
853             <placeholder-for-result#> (must be an unboxed type)
854
855          The interpreter then calls the marshall code mentioned
856          in the CCALL insn, passing it (& <placeholder-for-result#>), 
857          that is, the addr of the topmost word in the stack.
858          When this returns, the placeholder will have been
859          filled in.  The placeholder is slid down to the sequel
860          depth, and we RETURN.
861
862          This arrangement makes it simple to do f-i-dynamic since the Addr#
863          value is the first arg anyway.
864
865          The marshalling code is generated specifically for this
866          call site, and so knows exactly the (Haskell) stack
867          offsets of the args, fn address and placeholder.  It
868          copies the args to the C stack, calls the stacked addr,
869          and parks the result back in the placeholder.  The interpreter
870          calls it as a normal C call, assuming it has a signature
871             void marshall_code ( StgWord* ptr_to_top_of_stack )
872          -}
873          -- resolve static address
874          get_target_info
875             = case target of
876                  DynamicTarget
877                     -> returnBc (False, panic "ByteCodeGen.generateCCall(dyn)")
878                  StaticTarget target
879                     -> ioToBc (lookupStaticPtr target) `thenBc` \res ->
880                        returnBc (True, res)
881      in
882          get_target_info        `thenBc` \ (is_static, static_target_addr) ->
883      let
884
885          -- Get the arg reps, zapping the leading Addr# in the dynamic case
886          a_reps --  | trace (showSDoc (ppr a_reps_pushed_RAW)) False = error "???"
887                 | is_static = a_reps_pushed_RAW
888                 | otherwise = if null a_reps_pushed_RAW 
889                               then panic "ByteCodeGen.generateCCall: dyn with no args"
890                               else tail a_reps_pushed_RAW
891
892          -- push the Addr#
893          (push_Addr, d_after_Addr)
894             | is_static
895             = (toOL [PUSH_UBX (Right static_target_addr) addr_sizeW],
896                d_after_args + addr_sizeW)
897             | otherwise -- is already on the stack
898             = (nilOL, d_after_args)
899
900          -- Push the return placeholder.  For a call returning nothing,
901          -- this is a VoidArg (tag).
902          r_sizeW   = cgRepSizeW r_rep
903          d_after_r = d_after_Addr + r_sizeW
904          r_lit     = mkDummyLiteral r_rep
905          push_r    = (if   returns_void 
906                       then nilOL 
907                       else unitOL (PUSH_UBX (Left r_lit) r_sizeW))
908
909          -- generate the marshalling code we're going to call
910          r_offW       = 0 
911          addr_offW    = r_sizeW
912          arg1_offW    = r_sizeW + addr_sizeW
913          args_offW    = map (arg1_offW +) 
914                             (init (scanl (+) 0 (map cgRepSizeW a_reps)))
915      in
916          ioToBc (mkMarshalCode cconv
917                     (r_offW, r_rep) addr_offW
918                     (zip args_offW a_reps))     `thenBc` \ addr_of_marshaller ->
919          recordMallocBc addr_of_marshaller      `thenBc_`
920      let
921          -- Offset of the next stack frame down the stack.  The CCALL
922          -- instruction needs to describe the chunk of stack containing
923          -- the ccall args to the GC, so it needs to know how large it
924          -- is.  See comment in Interpreter.c with the CCALL instruction.
925          stk_offset   = d_after_r - s
926
927          -- do the call
928          do_call      = unitOL (CCALL stk_offset (castPtr addr_of_marshaller))
929          -- slide and return
930          wrapup       = mkSLIDE r_sizeW (d_after_r - r_sizeW - s)
931                         `snocOL` RETURN_UBX r_rep
932      in
933          --trace (show (arg1_offW, args_offW  ,  (map cgRepSizeW a_reps) )) $
934          returnBc (
935          push_args `appOL`
936          push_Addr `appOL` push_r `appOL` do_call `appOL` wrapup
937          )
938
939
940 -- Make a dummy literal, to be used as a placeholder for FFI return
941 -- values on the stack.
942 mkDummyLiteral :: CgRep -> Literal
943 mkDummyLiteral pr
944    = case pr of
945         NonPtrArg -> MachWord 0
946         DoubleArg -> MachDouble 0
947         FloatArg  -> MachFloat 0
948         _         -> moan64 "mkDummyLiteral" (ppr pr)
949
950
951 -- Convert (eg) 
952 --     GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld
953 --                   -> (# GHC.Prim.State# GHC.Prim.RealWorld, GHC.Prim.Int# #)
954 --
955 -- to  Just IntRep
956 -- and check that an unboxed pair is returned wherein the first arg is VoidArg'd.
957 --
958 -- Alternatively, for call-targets returning nothing, convert
959 --
960 --     GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld
961 --                   -> (# GHC.Prim.State# GHC.Prim.RealWorld #)
962 --
963 -- to  Nothing
964
965 maybe_getCCallReturnRep :: Type -> Maybe CgRep
966 maybe_getCCallReturnRep fn_ty
967    = let (a_tys, r_ty) = splitFunTys (dropForAlls fn_ty)
968          maybe_r_rep_to_go  
969             = if isSingleton r_reps then Nothing else Just (r_reps !! 1)
970          (r_tycon, r_reps) 
971             = case splitTyConApp_maybe (repType r_ty) of
972                       (Just (tyc, tys)) -> (tyc, map typeCgRep tys)
973                       Nothing -> blargh
974          ok = ( ( r_reps `lengthIs` 2 && VoidArg == head r_reps)
975                 || r_reps == [VoidArg] )
976               && isUnboxedTupleTyCon r_tycon
977               && case maybe_r_rep_to_go of
978                     Nothing    -> True
979                     Just r_rep -> r_rep /= PtrArg
980                                   -- if it was, it would be impossible 
981                                   -- to create a valid return value 
982                                   -- placeholder on the stack
983          blargh = pprPanic "maybe_getCCallReturn: can't handle:" 
984                            (pprType fn_ty)
985      in 
986      --trace (showSDoc (ppr (a_reps, r_reps))) $
987      if ok then maybe_r_rep_to_go else blargh
988
989 -- Compile code which expects an unboxed Int on the top of stack,
990 -- (call it i), and pushes the i'th closure in the supplied list 
991 -- as a consequence.
992 implement_tagToId :: [Name] -> BcM BCInstrList
993 implement_tagToId names
994    = ASSERT( notNull names )
995      getLabelsBc (length names)                 `thenBc` \ labels ->
996      getLabelBc                                 `thenBc` \ label_fail ->
997      getLabelBc                                 `thenBc` \ label_exit ->
998      zip4 labels (tail labels ++ [label_fail])
999                  [0 ..] names                   `bind`   \ infos ->
1000      map (mkStep label_exit) infos              `bind`   \ steps ->
1001      returnBc (concatOL steps
1002                `appOL` 
1003                toOL [LABEL label_fail, CASEFAIL, LABEL label_exit])
1004      where
1005         mkStep l_exit (my_label, next_label, n, name_for_n)
1006            = toOL [LABEL my_label, 
1007                    TESTEQ_I n next_label, 
1008                    PUSH_G name_for_n, 
1009                    JMP l_exit]
1010
1011
1012 -- -----------------------------------------------------------------------------
1013 -- pushAtom
1014
1015 -- Push an atom onto the stack, returning suitable code & number of
1016 -- stack words used.
1017 --
1018 -- The env p must map each variable to the highest- numbered stack
1019 -- slot for it.  For example, if the stack has depth 4 and we
1020 -- tagged-ly push (v :: Int#) on it, the value will be in stack[4],
1021 -- the tag in stack[5], the stack will have depth 6, and p must map v
1022 -- to 5 and not to 4.  Stack locations are numbered from zero, so a
1023 -- depth 6 stack has valid words 0 .. 5.
1024
1025 pushAtom :: Int -> BCEnv -> AnnExpr' Id VarSet -> BcM (BCInstrList, Int)
1026
1027 pushAtom d p (AnnApp f (_, AnnType _))
1028    = pushAtom d p (snd f)
1029
1030 pushAtom d p (AnnNote note e)
1031    = pushAtom d p (snd e)
1032
1033 pushAtom d p (AnnLam x e) 
1034    | isTyVar x 
1035    = pushAtom d p (snd e)
1036
1037 pushAtom d p (AnnVar v)
1038
1039    | idCgRep v == VoidArg
1040    = returnBc (nilOL, 0)
1041
1042    | isFCallId v
1043    = pprPanic "pushAtom: shouldn't get an FCallId here" (ppr v)
1044
1045    | Just primop <- isPrimOpId_maybe v
1046    = returnBc (unitOL (PUSH_PRIMOP primop), 1)
1047
1048    | Just d_v <- lookupBCEnv_maybe p v  -- v is a local variable
1049    = returnBc (toOL (nOfThem sz (PUSH_L (d-d_v+sz-2))), sz)
1050          -- d - d_v                 the number of words between the TOS 
1051          --                         and the 1st slot of the object
1052          --
1053          -- d - d_v - 1             the offset from the TOS of the 1st slot
1054          --
1055          -- d - d_v - 1 + sz - 1    the offset from the TOS of the last slot
1056          --                         of the object.
1057          --
1058          -- Having found the last slot, we proceed to copy the right number of
1059          -- slots on to the top of the stack.
1060
1061     | otherwise  -- v must be a global variable
1062     = ASSERT(sz == 1) 
1063       returnBc (unitOL (PUSH_G (getName v)), sz)
1064
1065     where
1066          sz = idSizeW v
1067
1068
1069 pushAtom d p (AnnLit lit)
1070    = case lit of
1071         MachLabel fs _ -> code NonPtrArg
1072         MachWord w     -> code NonPtrArg
1073         MachInt i      -> code PtrArg
1074         MachFloat r    -> code FloatArg
1075         MachDouble r   -> code DoubleArg
1076         MachChar c     -> code NonPtrArg
1077         MachStr s      -> pushStr s
1078      where
1079         code rep
1080            = let size_host_words = cgRepSizeW rep
1081              in  returnBc (unitOL (PUSH_UBX (Left lit) size_host_words), 
1082                            size_host_words)
1083
1084         pushStr s 
1085            = let getMallocvilleAddr
1086                     = case s of
1087                          FastString _ l ba -> 
1088                             -- sigh, a string in the heap is no good to us.
1089                             -- We need a static C pointer, since the type of 
1090                             -- a string literal is Addr#.  So, copy the string 
1091                             -- into C land and remember the pointer so we can
1092                             -- free it later.
1093                             let n = I# l
1094                             -- CAREFUL!  Chars are 32 bits in ghc 4.09+
1095                             in  ioToBc (mallocBytes (n+1)) `thenBc` \ ptr ->
1096                                 recordMallocBc ptr         `thenBc_`
1097                                 ioToBc (
1098                                    do memcpy ptr ba (fromIntegral n)
1099                                       pokeByteOff ptr n (fromIntegral (ord '\0') :: Word8)
1100                                       return ptr
1101                                    )
1102                          other -> panic "ByteCodeGen.pushAtom.pushStr"
1103              in
1104                 getMallocvilleAddr `thenBc` \ addr ->
1105                 -- Get the addr on the stack, untaggedly
1106                    returnBc (unitOL (PUSH_UBX (Right addr) 1), 1)
1107
1108 pushAtom d p other
1109    = pprPanic "ByteCodeGen.pushAtom" 
1110               (pprCoreExpr (deAnnotate (undefined, other)))
1111
1112 foreign import ccall unsafe "memcpy"
1113  memcpy :: Ptr a -> ByteArray# -> CInt -> IO ()
1114
1115
1116 -- -----------------------------------------------------------------------------
1117 -- Given a bunch of alts code and their discrs, do the donkey work
1118 -- of making a multiway branch using a switch tree.
1119 -- What a load of hassle!
1120
1121 mkMultiBranch :: Maybe Int      --  # datacons in tycon, if alg alt
1122                                 -- a hint; generates better code
1123                                 -- Nothing is always safe
1124               -> [(Discr, BCInstrList)] 
1125               -> BcM BCInstrList
1126 mkMultiBranch maybe_ncons raw_ways
1127    = let d_way     = filter (isNoDiscr.fst) raw_ways
1128          notd_ways = sortLe 
1129                         (\w1 w2 -> leAlt (fst w1) (fst w2))
1130                         (filter (not.isNoDiscr.fst) raw_ways)
1131
1132          mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
1133          mkTree [] range_lo range_hi = returnBc the_default
1134
1135          mkTree [val] range_lo range_hi
1136             | range_lo `eqAlt` range_hi 
1137             = returnBc (snd val)
1138             | otherwise
1139             = getLabelBc                                `thenBc` \ label_neq ->
1140               returnBc (mkTestEQ (fst val) label_neq 
1141                         `consOL` (snd val
1142                         `appOL`   unitOL (LABEL label_neq)
1143                         `appOL`   the_default))
1144
1145          mkTree vals range_lo range_hi
1146             = let n = length vals `div` 2
1147                   vals_lo = take n vals
1148                   vals_hi = drop n vals
1149                   v_mid = fst (head vals_hi)
1150               in
1151               getLabelBc                                `thenBc` \ label_geq ->
1152               mkTree vals_lo range_lo (dec v_mid)       `thenBc` \ code_lo ->
1153               mkTree vals_hi v_mid range_hi             `thenBc` \ code_hi ->
1154               returnBc (mkTestLT v_mid label_geq
1155                         `consOL` (code_lo
1156                         `appOL`   unitOL (LABEL label_geq)
1157                         `appOL`   code_hi))
1158  
1159          the_default 
1160             = case d_way of [] -> unitOL CASEFAIL
1161                             [(_, def)] -> def
1162
1163          -- None of these will be needed if there are no non-default alts
1164          (mkTestLT, mkTestEQ, init_lo, init_hi)
1165             | null notd_ways
1166             = panic "mkMultiBranch: awesome foursome"
1167             | otherwise
1168             = case fst (head notd_ways) of {
1169               DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
1170                             \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
1171                             DiscrI minBound,
1172                             DiscrI maxBound );
1173               DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
1174                             \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
1175                             DiscrF minF,
1176                             DiscrF maxF );
1177               DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
1178                             \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
1179                             DiscrD minD,
1180                             DiscrD maxD );
1181               DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
1182                             \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
1183                             DiscrP algMinBound,
1184                             DiscrP algMaxBound )
1185               }
1186
1187          (algMinBound, algMaxBound)
1188             = case maybe_ncons of
1189                  Just n  -> (0, n - 1)
1190                  Nothing -> (minBound, maxBound)
1191
1192          (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
1193          (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
1194          (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
1195          (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
1196          NoDiscr     `eqAlt` NoDiscr     = True
1197          _           `eqAlt` _           = False
1198
1199          (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
1200          (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
1201          (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
1202          (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
1203          NoDiscr     `leAlt` NoDiscr     = True
1204          _           `leAlt` _           = False
1205
1206          isNoDiscr NoDiscr = True
1207          isNoDiscr _       = False
1208
1209          dec (DiscrI i) = DiscrI (i-1)
1210          dec (DiscrP i) = DiscrP (i-1)
1211          dec other      = other         -- not really right, but if you
1212                 -- do cases on floating values, you'll get what you deserve
1213
1214          -- same snotty comment applies to the following
1215          minF, maxF :: Float
1216          minD, maxD :: Double
1217          minF = -1.0e37
1218          maxF =  1.0e37
1219          minD = -1.0e308
1220          maxD =  1.0e308
1221      in
1222          mkTree notd_ways init_lo init_hi
1223
1224
1225 -- -----------------------------------------------------------------------------
1226 -- Supporting junk for the compilation schemes
1227
1228 -- Describes case alts
1229 data Discr 
1230    = DiscrI Int
1231    | DiscrF Float
1232    | DiscrD Double
1233    | DiscrP Int
1234    | NoDiscr
1235
1236 instance Outputable Discr where
1237    ppr (DiscrI i) = int i
1238    ppr (DiscrF f) = text (show f)
1239    ppr (DiscrD d) = text (show d)
1240    ppr (DiscrP i) = int i
1241    ppr NoDiscr    = text "DEF"
1242
1243
1244 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
1245 lookupBCEnv_maybe = lookupFM
1246
1247 idSizeW :: Id -> Int
1248 idSizeW id = cgRepSizeW (typeCgRep (idType id))
1249
1250 unboxedTupleException :: a
1251 unboxedTupleException 
1252    = throwDyn 
1253         (Panic 
1254            ("Bytecode generator can't handle unboxed tuples.  Possibly due\n" ++
1255             "\tto foreign import/export decls in source.  Workaround:\n" ++
1256             "\tcompile this module to a .o file, then restart session."))
1257
1258
1259 mkSLIDE n d = if d == 0 then nilOL else unitOL (SLIDE n d)
1260 bind x f    = f x
1261
1262 splitApp :: AnnExpr' id ann -> (AnnExpr' id ann, [AnnExpr' id ann])
1263         -- The arguments are returned in *right-to-left* order
1264 splitApp (AnnApp (_,f) (_,a))
1265                | isTypeAtom a = splitApp f
1266                | otherwise    = case splitApp f of 
1267                                      (f', as) -> (f', a:as)
1268 splitApp (AnnNote n (_,e))    = splitApp e
1269 splitApp e                    = (e, [])
1270
1271
1272 isTypeAtom :: AnnExpr' id ann -> Bool
1273 isTypeAtom (AnnType _) = True
1274 isTypeAtom _           = False
1275
1276 isVoidArgAtom :: AnnExpr' id ann -> Bool
1277 isVoidArgAtom (AnnVar v)        = typeCgRep (idType v) == VoidArg
1278 isVoidArgAtom (AnnNote n (_,e)) = isVoidArgAtom e
1279 isVoidArgAtom _                 = False
1280
1281 atomRep :: AnnExpr' Id ann -> CgRep
1282 atomRep (AnnVar v)    = typeCgRep (idType v)
1283 atomRep (AnnLit l)    = typeCgRep (literalType l)
1284 atomRep (AnnNote n b) = atomRep (snd b)
1285 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
1286 atomRep (AnnLam x e) | isTyVar x = atomRep (snd e)
1287 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
1288
1289 isPtrAtom :: AnnExpr' Id ann -> Bool
1290 isPtrAtom e = atomRep e == PtrArg
1291
1292 -- Let szsw be the sizes in words of some items pushed onto the stack,
1293 -- which has initial depth d'.  Return the values which the stack environment
1294 -- should map these items to.
1295 mkStackOffsets :: Int -> [Int] -> [Int]
1296 mkStackOffsets original_depth szsw
1297    = map (subtract 1) (tail (scanl (+) original_depth szsw))
1298
1299 -- -----------------------------------------------------------------------------
1300 -- The bytecode generator's monad
1301
1302 data BcM_State 
1303    = BcM_State { 
1304         nextlabel :: Int,               -- for generating local labels
1305         malloced  :: [Ptr ()] }         -- ptrs malloced for current BCO
1306                                         -- Should be free()d when it is GCd
1307
1308 newtype BcM r = BcM (BcM_State -> IO (BcM_State, r))
1309
1310 ioToBc :: IO a -> BcM a
1311 ioToBc io = BcM $ \st -> do 
1312   x <- io 
1313   return (st, x)
1314
1315 runBc :: BcM r -> IO (BcM_State, r)
1316 runBc (BcM m) = m (BcM_State 0 []) 
1317
1318 thenBc :: BcM a -> (a -> BcM b) -> BcM b
1319 thenBc (BcM expr) cont = BcM $ \st0 -> do
1320   (st1, q) <- expr st0
1321   let BcM k = cont q 
1322   (st2, r) <- k st1
1323   return (st2, r)
1324
1325 thenBc_ :: BcM a -> BcM b -> BcM b
1326 thenBc_ (BcM expr) (BcM cont) = BcM $ \st0 -> do
1327   (st1, q) <- expr st0
1328   (st2, r) <- cont st1
1329   return (st2, r)
1330
1331 returnBc :: a -> BcM a
1332 returnBc result = BcM $ \st -> (return (st, result))
1333
1334 instance Monad BcM where
1335   (>>=) = thenBc
1336   (>>)  = thenBc_
1337   return = returnBc
1338
1339 emitBc :: ([Ptr ()] -> ProtoBCO Name) -> BcM (ProtoBCO Name)
1340 emitBc bco
1341   = BcM $ \st -> return (st{malloced=[]}, bco (malloced st))
1342
1343 recordMallocBc :: Ptr a -> BcM ()
1344 recordMallocBc a
1345   = BcM $ \st -> return (st{malloced = castPtr a : malloced st}, ())
1346
1347 getLabelBc :: BcM Int
1348 getLabelBc
1349   = BcM $ \st -> return (st{nextlabel = 1 + nextlabel st}, nextlabel st)
1350
1351 getLabelsBc :: Int -> BcM [Int]
1352 getLabelsBc n
1353   = BcM $ \st -> let ctr = nextlabel st 
1354                  in return (st{nextlabel = ctr+n}, [ctr .. ctr+n-1])
1355 \end{code}