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