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