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