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