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