[project @ 2001-01-03 16:45:04 by sewardj]
[ghc-hetmet.git] / ghc / compiler / ghci / ByteCodeGen.lhs
1 %
2 % (c) The University of Glasgow 2000
3 %
4 \section[ByteCodeGen]{Generate bytecode from Core}
5
6 \begin{code}
7 module ByteCodeGen ( UnlinkedBCO, UnlinkedBCOExpr, ItblEnv, ClosureEnv, HValue,
8                      filterNameMap,
9                      byteCodeGen, coreExprToBCOs, 
10                      linkIModules, linkIExpr
11                    ) where
12
13 #include "HsVersions.h"
14
15 import Outputable
16 import Name             ( Name, getName, nameModule, mkSysLocalName, toRdrName )
17 import RdrName          ( rdrNameOcc, rdrNameModule )
18 import OccName          ( occNameString )
19 import Id               ( Id, idType, isDataConId_maybe, mkVanillaId )
20 import OrdList          ( OrdList, consOL, snocOL, appOL, unitOL, 
21                           nilOL, toOL, concatOL, fromOL )
22 import FiniteMap        ( FiniteMap, addListToFM, listToFM, filterFM,
23                           addToFM, lookupFM, fmToList, emptyFM, plusFM )
24 import CoreSyn
25 import PprCore          ( pprCoreExpr, pprCoreAlt )
26 import Literal          ( Literal(..), literalPrimRep )
27 import PrimRep          ( PrimRep(..) )
28 import CoreFVs          ( freeVars )
29 import Type             ( typePrimRep )
30 import DataCon          ( DataCon, dataConTag, fIRST_TAG, dataConTyCon, 
31                           dataConRepArgTys )
32 import TyCon            ( TyCon, tyConFamilySize, isDataTyCon, tyConDataCons )
33 import Class            ( Class, classTyCon )
34 import Util             ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem, global )
35 import Var              ( isTyVar )
36 import VarSet           ( VarSet, varSetElems )
37 import PrimRep          ( getPrimRepSize, isFollowableRep )
38 import Constants        ( wORD_SIZE )
39 import CmdLineOpts      ( DynFlags, DynFlag(..) )
40 import ErrUtils         ( showPass, dumpIfSet_dyn )
41 import ClosureInfo      ( mkVirtHeapOffsets )
42 import Module           ( ModuleName, moduleName, moduleNameFS )
43 import Unique           ( mkPseudoUnique3 )
44 import Linker           ( lookupSymbol )
45
46 import List             ( intersperse )
47 import Monad            ( foldM )
48 import ST               ( runST )
49 import MArray           ( castSTUArray, 
50                           newFloatArray, writeFloatArray,
51                           newDoubleArray,  writeDoubleArray,
52                           newIntArray, writeIntArray,
53                           newAddrArray, writeAddrArray )
54 import Foreign          ( Storable(..), Word8, Word16, Word32, Ptr(..), 
55                           malloc, castPtr, plusPtr )
56 import Addr             ( Word, addrToInt, nullAddr )
57 import Bits             ( Bits(..), shiftR )
58
59 import PrelAddr         ( Addr(..) )
60 import PrelGHC          ( BCO#, newBCO#, unsafeCoerce#, 
61                           ByteArray#, Array#, addrToHValue# )
62 import IOExts           ( IORef, fixIO )
63 import ArrayBase        
64 import PrelArr          ( Array(..) )
65 import PrelIOBase       ( IO(..) )
66
67 \end{code}
68
69 %************************************************************************
70 %*                                                                      *
71 \subsection{Functions visible from outside this module.}
72 %*                                                                      *
73 %************************************************************************
74
75 \begin{code}
76
77 byteCodeGen :: DynFlags
78             -> [CoreBind] 
79             -> [TyCon] -> [Class]
80             -> IO ([UnlinkedBCO], ItblEnv)
81 byteCodeGen dflags binds local_tycons local_classes
82    = do showPass dflags "ByteCodeGen"
83         let tycs = local_tycons ++ map classTyCon local_classes
84         itblenv <- mkITbls tycs
85
86         let flatBinds = concatMap getBind binds
87             getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
88             getBind (Rec binds)       = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
89             final_state = runBc (BcM_State [] 0) 
90                                 (mapBc schemeR flatBinds `thenBc_` returnBc ())
91             (BcM_State proto_bcos final_ctr) = final_state
92
93         dumpIfSet_dyn dflags Opt_D_dump_BCOs
94            "Proto-bcos" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
95
96         bcos <- mapM assembleBCO proto_bcos
97
98         return (bcos, itblenv)
99         
100
101 -- Returns: (the root BCO for this expression, 
102 --           a list of auxilary BCOs resulting from compiling closures)
103 coreExprToBCOs :: DynFlags
104                -> CoreExpr
105                -> IO UnlinkedBCOExpr
106 coreExprToBCOs dflags expr
107  = do showPass dflags "ByteCodeGen"
108
109       -- create a totally bogus name for the top-level BCO; this
110       -- should be harmless, since it's never used for anything
111       let invented_name = mkSysLocalName (mkPseudoUnique3 0) SLIT("Expr-Top-Level")
112       let invented_id   = mkVanillaId invented_name (panic "invented_id's type")
113
114       let (BcM_State all_proto_bcos final_ctr) 
115              = runBc (BcM_State [] 0) 
116                      (schemeR (invented_id, freeVars expr))
117       dumpIfSet_dyn dflags Opt_D_dump_BCOs
118          "Proto-bcos" (vcat (intersperse (char ' ') (map ppr all_proto_bcos)))
119
120       let root_proto_bco 
121              = case filter ((== invented_name).nameOfProtoBCO) all_proto_bcos of
122                   [root_bco] -> root_bco
123           auxiliary_proto_bcos
124              = filter ((/= invented_name).nameOfProtoBCO) all_proto_bcos
125
126       auxiliary_bcos <- mapM assembleBCO auxiliary_proto_bcos
127       root_bco <- assembleBCO root_proto_bco
128
129       return (root_bco, auxiliary_bcos)
130
131
132 -- Linking stuff
133 linkIModules :: ItblEnv    -- incoming global itbl env; returned updated
134              -> ClosureEnv -- incoming global closure env; returned updated
135              -> [([UnlinkedBCO], ItblEnv)]
136              -> IO ([HValue], ItblEnv, ClosureEnv)
137 linkIModules gie gce mods 
138    = do let (bcoss, ies) = unzip mods
139             bcos = concat bcoss
140             final_gie = foldr plusFM gie ies
141         (final_gce, linked_bcos) <- linkSomeBCOs final_gie gce bcos
142         return (linked_bcos, final_gie, final_gce)
143
144
145 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
146           -> IO HValue    -- IO BCO# really
147 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
148    = do (aux_ce, _) <- linkSomeBCOs ie ce aux_ul_bcos
149         (_, [root_bco]) <- linkSomeBCOs ie aux_ce [root_ul_bco]
150         return root_bco
151
152 -- Link a bunch of BCOs and return them + updated closure env.
153 linkSomeBCOs :: ItblEnv -> ClosureEnv -> [UnlinkedBCO]
154                 -> IO (ClosureEnv, [HValue])
155 linkSomeBCOs ie ce_in ul_bcos
156    = do let nms = map nameOfUnlinkedBCO ul_bcos
157         hvals <- fixIO 
158                     ( \ hvs -> let ce_out = addListToFM ce_in (zipLazily nms hvs)
159                                in  mapM (linkBCO ie ce_out) ul_bcos )
160         let ce_out = addListToFM ce_in (zip nms hvals)
161         return (ce_out, hvals)
162      where
163         -- A lazier zip, in which no demand is propagated to the second
164         -- list unless some demand is propagated to the snd of one of the
165         -- result list elems.
166         zipLazily []     ys = []
167         zipLazily (x:xs) ys = (x, head ys) : zipLazily xs (tail ys)
168
169
170 data UnlinkedBCO
171    = UnlinkedBCO Name
172                  (SizedSeq Word16)      -- insns
173                  (SizedSeq Word)        -- literals
174                  (SizedSeq Name)        -- ptrs
175                  (SizedSeq Name)        -- itbl refs
176
177 nameOfUnlinkedBCO (UnlinkedBCO nm _ _ _ _) = nm
178
179 -- When translating expressions, we need to distinguish the root
180 -- BCO for the expression
181 type UnlinkedBCOExpr = (UnlinkedBCO, [UnlinkedBCO])
182
183 instance Outputable UnlinkedBCO where
184    ppr (UnlinkedBCO nm insns lits ptrs itbls)
185       = sep [text "BCO", ppr nm, text "with", 
186              int (sizeSS insns), text "insns",
187              int (sizeSS lits), text "lits",
188              int (sizeSS ptrs), text "ptrs",
189              int (sizeSS itbls), text "itbls"]
190
191
192 -- these need a proper home
193 type ItblEnv    = FiniteMap Name (Ptr StgInfoTable)
194 type ClosureEnv = FiniteMap Name HValue
195 data HValue     = HValue  -- dummy type, actually a pointer to some Real Code.
196
197 -- remove all entries for a given set of modules from the environment
198 filterNameMap :: [ModuleName] -> FiniteMap Name a -> FiniteMap Name a
199 filterNameMap mods env 
200    = filterFM (\n _ -> moduleName (nameModule n) `notElem` mods) env
201 \end{code}
202
203 %************************************************************************
204 %*                                                                      *
205 \subsection{Bytecodes, and Outputery.}
206 %*                                                                      *
207 %************************************************************************
208
209 \begin{code}
210
211 type LocalLabel = Int
212
213 data BCInstr
214    -- Messing with the stack
215    = ARGCHECK  Int
216    -- Push locals (existing bits of the stack)
217    | PUSH_L    Int{-offset-}
218    | PUSH_LL   Int Int{-2 offsets-}
219    | PUSH_LLL  Int Int Int{-3 offsets-}
220    -- Push a ptr
221    | PUSH_G    Name
222    -- Push an alt continuation
223    | PUSH_AS   Name PrimRep     -- push alts and BCO_ptr_ret_info
224                                 -- PrimRep so we know which itbl
225    -- Pushing literals
226    | PUSH_UBX  Literal  Int 
227                         -- push this int/float/double, NO TAG, on the stack
228                         -- Int is # of words to copy from literal pool
229    | PUSH_TAG  Int      -- push this tag on the stack
230
231    | SLIDE     Int{-this many-} Int{-down by this much-}
232    -- To do with the heap
233    | ALLOC     Int      -- make an AP_UPD with this many payload words, zeroed
234    | MKAP      Int{-ptr to AP_UPD is this far down stack-} Int{-# words-}
235    | UNPACK    Int      -- unpack N ptr words from t.o.s Constr
236    | UPK_TAG   Int Int Int
237                         -- unpack N non-ptr words from offset M in constructor
238                         -- K words down the stack
239    | PACK      DataCon Int
240                         -- after assembly, the DataCon is an index into the
241                         -- itbl array
242    -- For doing case trees
243    | LABEL     LocalLabel
244    | TESTLT_I  Int    LocalLabel
245    | TESTEQ_I  Int    LocalLabel
246    | TESTLT_F  Float  LocalLabel
247    | TESTEQ_F  Float  LocalLabel
248    | TESTLT_D  Double LocalLabel
249    | TESTEQ_D  Double LocalLabel
250
251    -- The Int value is a constructor number and therefore
252    -- stored in the insn stream rather than as an offset into
253    -- the literal pool.
254    | TESTLT_P  Int    LocalLabel
255    | TESTEQ_P  Int    LocalLabel
256
257    | CASEFAIL
258    -- To Infinity And Beyond
259    | ENTER
260    | RETURN     PrimRep
261                 -- unboxed value on TOS.  Use tag to find underlying ret itbl
262                 -- and return as per that.
263
264
265 instance Outputable BCInstr where
266    ppr (ARGCHECK n)          = text "ARGCHECK" <+> int n
267    ppr (PUSH_L offset)       = text "PUSH_L  " <+> int offset
268    ppr (PUSH_LL o1 o2)       = text "PUSH_LL " <+> int o1 <+> int o2
269    ppr (PUSH_LLL o1 o2 o3)   = text "PUSH_LLL" <+> int o1 <+> int o2 <+> int o3
270    ppr (PUSH_G nm)           = text "PUSH_G  " <+> ppr nm
271    ppr (PUSH_AS nm pk)       = text "PUSH_AS " <+> ppr nm <+> ppr pk
272    ppr (PUSH_UBX lit nw)     = text "PUSH_UBX" <+> parens (int nw) <+> ppr lit
273    ppr (PUSH_TAG n)          = text "PUSH_TAG" <+> int n
274    ppr (SLIDE n d)           = text "SLIDE   " <+> int n <+> int d
275    ppr (ALLOC sz)            = text "ALLOC   " <+> int sz
276    ppr (MKAP offset sz)      = text "MKAP    " <+> int sz <+> text "words," 
277                                                <+> int offset <+> text "stkoff"
278    ppr (UNPACK sz)           = text "UNPACK  " <+> int sz
279    ppr (UPK_TAG n m k)       = text "UPK_TAG " <+> int n <> text "words" 
280                                                <+> int m <> text "conoff"
281                                                <+> int k <> text "stkoff"
282    ppr (PACK dcon sz)        = text "PACK    " <+> ppr dcon <+> ppr sz
283    ppr (LABEL     lab)       = text "__"       <> int lab <> colon
284    ppr (TESTLT_I  i lab)     = text "TESTLT_I" <+> int i <+> text "__" <> int lab
285    ppr (TESTEQ_I  i lab)     = text "TESTEQ_I" <+> int i <+> text "__" <> int lab
286    ppr (TESTLT_F  f lab)     = text "TESTLT_F" <+> float f <+> text "__" <> int lab
287    ppr (TESTEQ_F  f lab)     = text "TESTEQ_F" <+> float f <+> text "__" <> int lab
288    ppr (TESTLT_D  d lab)     = text "TESTLT_D" <+> double d <+> text "__" <> int lab
289    ppr (TESTEQ_D  d lab)     = text "TESTEQ_D" <+> double d <+> text "__" <> int lab
290    ppr (TESTLT_P  i lab)     = text "TESTLT_P" <+> int i <+> text "__" <> int lab
291    ppr (TESTEQ_P  i lab)     = text "TESTEQ_P" <+> int i <+> text "__" <> int lab
292    ppr CASEFAIL              = text "CASEFAIL"
293    ppr ENTER                 = text "ENTER"
294    ppr (RETURN pk)           = text "RETURN  " <+> ppr pk
295
296 instance Outputable a => Outputable (ProtoBCO a) where
297    ppr (ProtoBCO name instrs origin)
298       = (text "ProtoBCO" <+> ppr name <> colon)
299         $$ nest 6 (vcat (map ppr instrs))
300         $$ case origin of
301               Left alts -> vcat (map (pprCoreAlt.deAnnAlt) alts)
302               Right rhs -> pprCoreExpr (deAnnotate rhs)
303 \end{code}
304
305 %************************************************************************
306 %*                                                                      *
307 \subsection{Compilation schema for the bytecode generator.}
308 %*                                                                      *
309 %************************************************************************
310
311 \begin{code}
312
313 type BCInstrList = OrdList BCInstr
314
315 data ProtoBCO a 
316    = ProtoBCO a                         -- name, in some sense
317               [BCInstr]                 -- instrs
318                                         -- what the BCO came from
319               (Either [AnnAlt Id VarSet]
320                       (AnnExpr Id VarSet))
321
322 nameOfProtoBCO (ProtoBCO nm insns origin) = nm
323
324
325 type Sequel = Int       -- back off to this depth before ENTER
326
327 -- Maps Ids to the offset from the stack _base_ so we don't have
328 -- to mess with it after each push/pop.
329 type BCEnv = FiniteMap Id Int   -- To find vars on the stack
330
331
332 -- Create a BCO and do a spot of peephole optimisation on the insns
333 -- at the same time.
334 mkProtoBCO nm instrs_ordlist origin
335    = ProtoBCO nm (id {-peep-} (fromOL instrs_ordlist)) origin
336      where
337         peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
338            = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
339         peep (PUSH_L off1 : PUSH_L off2 : rest)
340            = PUSH_LL off1 off2 : peep rest
341         peep (i:rest)
342            = i : peep rest
343         peep []
344            = []
345
346
347 -- Compile code for the right hand side of a let binding.
348 -- Park the resulting BCO in the monad.  Also requires the
349 -- variable to which this value was bound, so as to give the
350 -- resulting BCO a name.
351 schemeR :: (Id, AnnExpr Id VarSet) -> BcM ()
352 schemeR (nm, rhs) 
353 {-
354    | trace (showSDoc (
355               (char ' '
356                $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
357                $$ pprCoreExpr (deAnnotate rhs)
358                $$ char ' '
359               ))) False
360    = undefined
361 -}
362    | otherwise
363    = schemeR_wrk rhs nm (collect [] rhs)
364
365
366 collect xs (_, AnnLam x e) 
367    = collect (if isTyVar x then xs else (x:xs)) e
368 collect xs not_lambda
369    = (reverse xs, not_lambda)
370
371 schemeR_wrk original_body nm (args, body)
372    = let fvs       = filter (not.isTyVar) (varSetElems (fst original_body))
373          all_args  = fvs ++ reverse args
374          szsw_args = map taggedIdSizeW all_args
375          szw_args  = sum szsw_args
376          p_init    = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
377          argcheck  = {-if null args then nilOL else-} unitOL (ARGCHECK szw_args)
378      in
379      schemeE szw_args 0 p_init body             `thenBc` \ body_code ->
380      emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) (Right original_body))
381
382 -- Let szsw be the sizes in words of some items pushed onto the stack,
383 -- which has initial depth d'.  Return the values which the stack environment
384 -- should map these items to.
385 mkStackOffsets :: Int -> [Int] -> [Int]
386 mkStackOffsets original_depth szsw
387    = map (subtract 1) (tail (scanl (+) original_depth szsw))
388
389 -- Compile code to apply the given expression to the remaining args
390 -- on the stack, returning a HNF.
391 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
392
393 -- Delegate tail-calls to schemeT.
394 schemeE d s p e@(fvs, AnnApp f a) 
395    = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnApp f a))
396 schemeE d s p e@(fvs, AnnVar v)
397    | isFollowableRep v_rep
398    = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnVar v))
399    | otherwise
400    = -- returning an unboxed value.  Heave it on the stack, SLIDE, and RETURN.
401      let (push, szw) = pushAtom True d p (AnnVar v)
402      in  returnBc (push                         -- value onto stack
403                    `snocOL` SLIDE szw (d-s)     -- clear to sequel
404                    `snocOL` RETURN v_rep)       -- go
405    where
406       v_rep = typePrimRep (idType v)
407
408 schemeE d s p (fvs, AnnLit literal)
409    = let (push, szw) = pushAtom True d p (AnnLit literal)
410          l_rep = literalPrimRep literal
411      in  returnBc (push                         -- value onto stack
412                    `snocOL` SLIDE szw (d-s)     -- clear to sequel
413                    `snocOL` RETURN l_rep)               -- go
414
415 schemeE d s p (fvs, AnnLet binds b)
416    = let (xs,rhss) = case binds of AnnNonRec x rhs  -> ([x],[rhs])
417                                    AnnRec xs_n_rhss -> unzip xs_n_rhss
418          n     = length xs
419          fvss  = map (filter (not.isTyVar).varSetElems.fst) rhss
420
421          -- Sizes of tagged free vars, + 1 for the fn
422          sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
423
424          -- This p', d' defn is safe because all the items being pushed
425          -- are ptrs, so all have size 1.  d' and p' reflect the stack
426          -- after the closures have been allocated in the heap (but not
427          -- filled in), and pointers to them parked on the stack.
428          p'    = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
429          d'    = d + n
430
431          infos = zipE4 fvss sizes xs [n, n-1 .. 1]
432          zipE  = zipEqual "schemeE"
433          zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
434
435          -- ToDo: don't build thunks for things with no free variables
436          buildThunk dd ([], size, id, off)
437             = PUSH_G (getName id) 
438               `consOL` unitOL (MKAP (off+size-1) size)
439          buildThunk dd ((fv:fvs), size, id, off)
440             = case pushAtom True dd p' (AnnVar fv) of
441                  (push_code, pushed_szw)
442                     -> push_code `appOL`
443                        buildThunk (dd+pushed_szw) (fvs, size, id, off)
444
445          thunkCode = concatOL (map (buildThunk d') infos)
446          allocCode = toOL (map ALLOC sizes)
447      in
448      schemeE d' s p' b                                  `thenBc`  \ bodyCode ->
449      mapBc schemeR (zip xs rhss)                        `thenBc_`
450      returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
451
452
453 schemeE d s p (fvs, AnnCase scrut bndr alts)
454    = let
455         -- Top of stack is the return itbl, as usual.
456         -- underneath it is the pointer to the alt_code BCO.
457         -- When an alt is entered, it assumes the returned value is
458         -- on top of the itbl.
459         ret_frame_sizeW = 2
460
461         -- Env and depth in which to compile the alts, not including
462         -- any vars bound by the alts themselves
463         d' = d + ret_frame_sizeW + taggedIdSizeW bndr
464         p' = addToFM p bndr (d' - 1)
465
466         scrut_primrep = typePrimRep (idType bndr)
467         isAlgCase
468            = case scrut_primrep of
469                 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
470                 PtrRep -> True
471                 other  -> pprPanic "ByteCodeGen.schemeE" (ppr other)
472
473         -- given an alt, return a discr and code for it.
474         codeAlt alt@(discr, binds_f, rhs)
475            | isAlgCase 
476            = let binds_r      = reverse binds_f
477                  binds_r_szsw = map untaggedIdSizeW binds_r
478                  binds_szw    = sum binds_r_szsw
479                  p''          = addListToFM 
480                                    p' (zip binds_r (mkStackOffsets d' binds_r_szsw))
481                  d''          = d' + binds_szw
482                  unpack_code  = mkUnpackCode 0 0 (map (typePrimRep.idType) binds_f)
483              in schemeE d'' s p'' rhs   `thenBc` \ rhs_code -> 
484                 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
485            | otherwise 
486            = ASSERT(null binds_f) 
487              schemeE d' s p' rhs        `thenBc` \ rhs_code ->
488              returnBc (my_discr alt, rhs_code)
489
490         my_discr (DEFAULT, binds, rhs)  = NoDiscr
491         my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc)
492         my_discr (LitAlt l, binds, rhs)
493            = case l of MachInt i     -> DiscrI (fromInteger i)
494                        MachFloat r   -> DiscrF (fromRational r)
495                        MachDouble r  -> DiscrD (fromRational r)
496
497         maybe_ncons 
498            | not isAlgCase = Nothing
499            | otherwise 
500            = case [dc | (DataAlt dc, _, _) <- alts] of
501                 []     -> Nothing
502                 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
503
504      in 
505      mapBc codeAlt alts                                 `thenBc` \ alt_stuff ->
506      mkMultiBranch maybe_ncons alt_stuff                `thenBc` \ alt_final ->
507      let 
508          alt_bco_name = getName bndr
509          alt_bco      = mkProtoBCO alt_bco_name alt_final (Left alts)
510      in
511      schemeE (d + ret_frame_sizeW) 
512              (d + ret_frame_sizeW) p scrut              `thenBc` \ scrut_code ->
513
514      emitBc alt_bco                                     `thenBc_`
515      returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
516
517
518 schemeE d s p (fvs, AnnNote note body)
519    = schemeE d s p body
520
521 schemeE d s p other
522    = pprPanic "ByteCodeGen.schemeE: unhandled case" 
523                (pprCoreExpr (deAnnotate other))
524
525
526 -- Compile code to do a tail call.  Doesn't need to be monadic.
527 schemeT :: Bool         -- do tagging?
528         -> Int          -- Stack depth
529         -> Sequel       -- Sequel depth
530         -> Int          -- # arg words so far
531         -> BCEnv        -- stack env
532         -> AnnExpr Id VarSet 
533         -> BCInstrList
534
535 schemeT enTag d s narg_words p (_, AnnApp f a)
536    = case snd a of
537         AnnType _ -> schemeT enTag d s narg_words p f
538         other
539            -> let (push, arg_words) = pushAtom enTag d p (snd a)
540               in push 
541                  `appOL` schemeT enTag (d+arg_words) s (narg_words+arg_words) p f
542
543 schemeT enTag d s narg_words p (_, AnnVar f)
544    | Just con <- isDataConId_maybe f
545    = ASSERT(enTag == False)
546      PACK con narg_words `consOL` (mkSLIDE 1 (d-s-1) `snocOL` ENTER)
547    | otherwise
548    = ASSERT(enTag == True)
549      let (push, arg_words) = pushAtom True d p (AnnVar f)
550      in  push 
551          `appOL`  mkSLIDE (narg_words+arg_words) (d - s - narg_words)
552          `snocOL` ENTER
553
554 mkSLIDE n d 
555    = if d == 0 then nilOL else unitOL (SLIDE n d)
556
557 should_args_be_tagged (_, AnnVar v)
558    = case isDataConId_maybe v of
559         Just dcon -> False; Nothing -> True
560 should_args_be_tagged (_, AnnApp f a)
561    = should_args_be_tagged f
562 should_args_be_tagged (_, other)
563    = panic "should_args_be_tagged: tail call to non-con, non-var"
564
565
566 -- Make code to unpack a constructor onto the stack, adding
567 -- tags for the unboxed bits.  Takes the PrimReps of the constructor's
568 -- arguments, and a travelling offset along both the constructor
569 -- (off_h) and the stack (off_s).
570 mkUnpackCode :: Int -> Int -> [PrimRep] -> BCInstrList
571 mkUnpackCode off_h off_s [] = nilOL
572 mkUnpackCode off_h off_s (r:rs)
573    | isFollowableRep r
574    = let (rs_ptr, rs_nptr) = span isFollowableRep (r:rs)
575          ptrs_szw = sum (map untaggedSizeW rs_ptr) 
576      in  ASSERT(ptrs_szw == length rs_ptr)
577          ASSERT(off_h == 0)
578          ASSERT(off_s == 0)
579          UNPACK ptrs_szw 
580          `consOL` mkUnpackCode (off_h + ptrs_szw) (off_s + ptrs_szw) rs_nptr
581    | otherwise
582    = case r of
583         IntRep    -> approved
584         FloatRep  -> approved
585         DoubleRep -> approved
586      where
587         approved = UPK_TAG usizeW off_h off_s   `consOL` theRest
588         theRest  = mkUnpackCode (off_h + usizeW) (off_s + tsizeW) rs
589         usizeW   = untaggedSizeW r
590         tsizeW   = taggedSizeW r
591
592 -- Push an atom onto the stack, returning suitable code & number of
593 -- stack words used.  Pushes it either tagged or untagged, since 
594 -- pushAtom is used to set up the stack prior to copying into the
595 -- heap for both APs (requiring tags) and constructors (which don't).
596 --
597 -- NB this means NO GC between pushing atoms for a constructor and
598 -- copying them into the heap.  It probably also means that 
599 -- tail calls MUST be of the form atom{atom ... atom} since if the
600 -- expression head was allowed to be arbitrary, there could be GC
601 -- in between pushing the arg atoms and completing the head.
602 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
603 -- isn't a problem; but only if arbitrary graph construction for the
604 -- head doesn't leave this BCO, since GC might happen at the start of
605 -- each BCO (we consult doYouWantToGC there).
606 --
607 -- Blargh.  JRS 001206
608 --
609 -- NB (further) that the env p must map each variable to the highest-
610 -- numbered stack slot for it.  For example, if the stack has depth 4 
611 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
612 -- the tag in stack[5], the stack will have depth 6, and p must map v to
613 -- 5 and not to 4.  Stack locations are numbered from zero, so a depth
614 -- 6 stack has valid words 0 .. 5.
615
616 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
617 pushAtom tagged d p (AnnVar v) 
618    = let str = "\npushAtom " ++ showSDocDebug (ppr v) ++ ", depth = " ++ show d
619                ++ ", env =\n" ++ 
620                showSDocDebug (nest 4 (vcat (map ppr (fmToList p))))
621                ++ " -->\n" ++
622                showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
623                ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
624          str' = if str == str then str else str
625
626          result
627             = case lookupBCEnv_maybe p v of
628                  Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), sz_t)
629                  Nothing  -> ASSERT(sz_t == 1) (unitOL (PUSH_G nm), sz_t)
630
631          nm     = getName v
632          sz_t   = taggedIdSizeW v
633          sz_u   = untaggedIdSizeW v
634          nwords = if tagged then sz_t else sz_u
635      in
636          --trace str'
637          result
638
639 pushAtom True d p (AnnLit lit)
640    = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
641      in  (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
642
643 pushAtom False d p (AnnLit lit)
644    = case lit of
645         MachInt i    -> code IntRep
646         MachFloat r  -> code FloatRep
647         MachDouble r -> code DoubleRep
648         MachChar c   -> code CharRep
649      where
650         code rep
651            = let size_host_words = untaggedSizeW rep
652              in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
653
654 pushAtom tagged d p (AnnApp f (_, AnnType _))
655    = pushAtom tagged d p (snd f)
656
657 pushAtom tagged d p other
658    = pprPanic "ByteCodeGen.pushAtom" 
659               (pprCoreExpr (deAnnotate (undefined, other)))
660
661
662 -- Given a bunch of alts code and their discrs, do the donkey work
663 -- of making a multiway branch using a switch tree.
664 -- What a load of hassle!
665 mkMultiBranch :: Maybe Int      -- # datacons in tycon, if alg alt
666                                 -- a hint; generates better code
667                                 -- Nothing is always safe
668               -> [(Discr, BCInstrList)] 
669               -> BcM BCInstrList
670 mkMultiBranch maybe_ncons raw_ways
671    = let d_way     = filter (isNoDiscr.fst) raw_ways
672          notd_ways = naturalMergeSortLe 
673                         (\w1 w2 -> leAlt (fst w1) (fst w2))
674                         (filter (not.isNoDiscr.fst) raw_ways)
675
676          mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
677          mkTree [] range_lo range_hi = returnBc the_default
678
679          mkTree [val] range_lo range_hi
680             | range_lo `eqAlt` range_hi 
681             = returnBc (snd val)
682             | otherwise
683             = getLabelBc                                `thenBc` \ label_neq ->
684               returnBc (mkTestEQ (fst val) label_neq 
685                         `consOL` (snd val
686                         `appOL`   unitOL (LABEL label_neq)
687                         `appOL`   the_default))
688
689          mkTree vals range_lo range_hi
690             = let n = length vals `div` 2
691                   vals_lo = take n vals
692                   vals_hi = drop n vals
693                   v_mid = fst (head vals_hi)
694               in
695               getLabelBc                                `thenBc` \ label_geq ->
696               mkTree vals_lo range_lo (dec v_mid)       `thenBc` \ code_lo ->
697               mkTree vals_hi v_mid range_hi             `thenBc` \ code_hi ->
698               returnBc (mkTestLT v_mid label_geq
699                         `consOL` (code_lo
700                         `appOL`   unitOL (LABEL label_geq)
701                         `appOL`   code_hi))
702  
703          the_default 
704             = case d_way of [] -> unitOL CASEFAIL
705                             [(_, def)] -> def
706
707          -- None of these will be needed if there are no non-default alts
708          (mkTestLT, mkTestEQ, init_lo, init_hi)
709             | null notd_ways
710             = panic "mkMultiBranch: awesome foursome"
711             | otherwise
712             = case fst (head notd_ways) of {
713               DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
714                             \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
715                             DiscrI minBound,
716                             DiscrI maxBound );
717               DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
718                             \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
719                             DiscrF minF,
720                             DiscrF maxF );
721               DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
722                             \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
723                             DiscrD minD,
724                             DiscrD maxD );
725               DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
726                             \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
727                             DiscrP algMinBound,
728                             DiscrP algMaxBound )
729               }
730
731          (algMinBound, algMaxBound)
732             = case maybe_ncons of
733                  Just n  -> (fIRST_TAG, fIRST_TAG + n - 1)
734                  Nothing -> (minBound, maxBound)
735
736          (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
737          (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
738          (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
739          (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
740          NoDiscr     `eqAlt` NoDiscr     = True
741          _           `eqAlt` _           = False
742
743          (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
744          (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
745          (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
746          (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
747          NoDiscr     `leAlt` NoDiscr     = True
748          _           `leAlt` _           = False
749
750          isNoDiscr NoDiscr = True
751          isNoDiscr _       = False
752
753          dec (DiscrI i) = DiscrI (i-1)
754          dec (DiscrP i) = DiscrP (i-1)
755          dec other      = other         -- not really right, but if you
756                 -- do cases on floating values, you'll get what you deserve
757
758          -- same snotty comment applies to the following
759          minF, maxF :: Float
760          minD, maxD :: Double
761          minF = -1.0e37
762          maxF =  1.0e37
763          minD = -1.0e308
764          maxD =  1.0e308
765      in
766          mkTree notd_ways init_lo init_hi
767
768 \end{code}
769
770 %************************************************************************
771 %*                                                                      *
772 \subsection{Supporting junk for the compilation schemes}
773 %*                                                                      *
774 %************************************************************************
775
776 \begin{code}
777
778 -- Describes case alts
779 data Discr 
780    = DiscrI Int
781    | DiscrF Float
782    | DiscrD Double
783    | DiscrP Int
784    | NoDiscr
785
786 instance Outputable Discr where
787    ppr (DiscrI i) = int i
788    ppr (DiscrF f) = text (show f)
789    ppr (DiscrD d) = text (show d)
790    ppr (DiscrP i) = int i
791    ppr NoDiscr    = text "DEF"
792
793
794 -- Find things in the BCEnv (the what's-on-the-stack-env)
795 -- See comment preceding pushAtom for precise meaning of env contents
796 --lookupBCEnv :: BCEnv -> Id -> Int
797 --lookupBCEnv env nm
798 --   = case lookupFM env nm of
799 --        Nothing -> pprPanic "lookupBCEnv" 
800 --                            (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
801 --        Just xx -> xx
802
803 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
804 lookupBCEnv_maybe = lookupFM
805
806
807 -- When I push one of these on the stack, how much does Sp move by?
808 taggedSizeW :: PrimRep -> Int
809 taggedSizeW pr
810    | isFollowableRep pr = 1
811    | otherwise          = 1{-the tag-} + getPrimRepSize pr
812
813
814 -- The plain size of something, without tag.
815 untaggedSizeW :: PrimRep -> Int
816 untaggedSizeW pr
817    | isFollowableRep pr = 1
818    | otherwise          = getPrimRepSize pr
819
820
821 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
822 taggedIdSizeW   = taggedSizeW   . typePrimRep . idType
823 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
824
825 \end{code}
826
827 %************************************************************************
828 %*                                                                      *
829 \subsection{The bytecode generator's monad}
830 %*                                                                      *
831 %************************************************************************
832
833 \begin{code}
834 data BcM_State 
835    = BcM_State { bcos      :: [ProtoBCO Name],  -- accumulates completed BCOs
836                  nextlabel :: Int }             -- for generating local labels
837
838 type BcM result = BcM_State -> (result, BcM_State)
839
840 runBc :: BcM_State -> BcM () -> BcM_State
841 runBc init_st m = case m init_st of { (r,st) -> st }
842
843 thenBc :: BcM a -> (a -> BcM b) -> BcM b
844 thenBc expr cont st
845   = case expr st of { (result, st') -> cont result st' }
846
847 thenBc_ :: BcM a -> BcM b -> BcM b
848 thenBc_ expr cont st
849   = case expr st of { (result, st') -> cont st' }
850
851 returnBc :: a -> BcM a
852 returnBc result st = (result, st)
853
854 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
855 mapBc f []     = returnBc []
856 mapBc f (x:xs)
857   = f x          `thenBc` \ r  ->
858     mapBc f xs   `thenBc` \ rs ->
859     returnBc (r:rs)
860
861 emitBc :: ProtoBCO Name -> BcM ()
862 emitBc bco st
863    = ((), st{bcos = bco : bcos st})
864
865 getLabelBc :: BcM Int
866 getLabelBc st
867    = (nextlabel st, st{nextlabel = 1 + nextlabel st})
868
869 \end{code}
870
871 %************************************************************************
872 %*                                                                      *
873 \subsection{The bytecode assembler}
874 %*                                                                      *
875 %************************************************************************
876
877 The object format for bytecodes is: 16 bits for the opcode, and 16 for
878 each field -- so the code can be considered a sequence of 16-bit ints.
879 Each field denotes either a stack offset or number of items on the
880 stack (eg SLIDE), and index into the pointer table (eg PUSH_G), an
881 index into the literal table (eg PUSH_I/D/L), or a bytecode address in
882 this BCO.
883
884 \begin{code}
885 -- Top level assembler fn.
886 assembleBCO :: ProtoBCO Name -> IO UnlinkedBCO
887
888 assembleBCO (ProtoBCO nm instrs origin)
889    = let
890          -- pass 1: collect up the offsets of the local labels.
891          -- Remember that the first insn starts at offset 1 since offset 0
892          -- (eventually) will hold the total # of insns.
893          label_env = mkLabelEnv emptyFM 1 instrs
894
895          mkLabelEnv env i_offset [] = env
896          mkLabelEnv env i_offset (i:is)
897             = let new_env 
898                      = case i of LABEL n -> addToFM env n i_offset ; _ -> env
899               in  mkLabelEnv new_env (i_offset + instrSizeB i) is
900
901          findLabel lab
902             = case lookupFM label_env lab of
903                  Just bco_offset -> bco_offset
904                  Nothing -> pprPanic "assembleBCO.findLabel" (int lab)
905      in
906      do  -- pass 2: generate the instruction, ptr and nonptr bits
907          insns <- return emptySS :: IO (SizedSeq Word16)
908          lits  <- return emptySS :: IO (SizedSeq Word)
909          ptrs  <- return emptySS :: IO (SizedSeq Name)
910          itbls <- return emptySS :: IO (SizedSeq Name)
911          let init_asm_state = (insns,lits,ptrs,itbls)
912          (final_insns, final_lits, final_ptrs, final_itbls) 
913             <- mkBits findLabel init_asm_state instrs         
914
915          return (UnlinkedBCO nm final_insns final_lits final_ptrs final_itbls)
916
917 -- instrs nonptrs ptrs itbls
918 type AsmState = (SizedSeq Word16, SizedSeq Word, SizedSeq Name, SizedSeq Name)
919
920 data SizedSeq a = SizedSeq !Int [a]
921 emptySS = SizedSeq 0 []
922 addToSS (SizedSeq n r_xs) x = return (SizedSeq (n+1) (x:r_xs))
923 addListToSS (SizedSeq n r_xs) xs 
924    = return (SizedSeq (n + length xs) (reverse xs ++ r_xs))
925 sizeSS (SizedSeq n r_xs) = n
926 listFromSS (SizedSeq n r_xs) = return (reverse r_xs)
927
928
929 -- This is where all the action is (pass 2 of the assembler)
930 mkBits :: (Int -> Int)                  -- label finder
931        -> AsmState
932        -> [BCInstr]                     -- instructions (in)
933        -> IO AsmState
934
935 mkBits findLabel st proto_insns
936   = foldM doInstr st proto_insns
937     where
938        doInstr :: AsmState -> BCInstr -> IO AsmState
939        doInstr st i
940           = case i of
941                ARGCHECK  n        -> instr2 st i_ARGCHECK n
942                PUSH_L    o1       -> instr2 st i_PUSH_L o1
943                PUSH_LL   o1 o2    -> instr3 st i_PUSH_LL o1 o2
944                PUSH_LLL  o1 o2 o3 -> instr4 st i_PUSH_LLL o1 o2 o3
945                PUSH_G    nm       -> do (p, st2) <- ptr st nm
946                                         instr2 st2 i_PUSH_G p
947                PUSH_AS   nm pk    -> do (p, st2)  <- ptr st nm
948                                         (np, st3) <- ctoi_itbl st2 pk
949                                         instr3 st3 i_PUSH_AS p np
950                PUSH_UBX  lit nws  -> do (np, st2) <- literal st lit
951                                         instr3 st2 i_PUSH_UBX np nws
952                PUSH_TAG  tag      -> instr2 st i_PUSH_TAG tag
953                SLIDE     n by     -> instr3 st i_SLIDE n by
954                ALLOC     n        -> instr2 st i_ALLOC n
955                MKAP      off sz   -> instr3 st i_MKAP off sz
956                UNPACK    n        -> instr2 st i_UNPACK n
957                UPK_TAG   n m k    -> instr4 st i_UPK_TAG n m k
958                PACK      dcon sz  -> do (itbl_no,st2) <- itbl st dcon
959                                         instr3 st2 i_PACK itbl_no sz
960                LABEL     lab      -> return st
961                TESTLT_I  i l      -> do (np, st2) <- int st i
962                                         instr3 st2 i_TESTLT_I np (findLabel l)
963                TESTEQ_I  i l      -> do (np, st2) <- int st i
964                                         instr3 st2 i_TESTEQ_I np (findLabel l)
965                TESTLT_F  f l      -> do (np, st2) <- float st f
966                                         instr3 st2 i_TESTLT_F np (findLabel l)
967                TESTEQ_F  f l      -> do (np, st2) <- float st f
968                                         instr3 st2 i_TESTEQ_F np (findLabel l)
969                TESTLT_D  d l      -> do (np, st2) <- double st d
970                                         instr3 st2 i_TESTLT_D np (findLabel l)
971                TESTEQ_D  d l      -> do (np, st2) <- double st d
972                                         instr3 st2 i_TESTEQ_D np (findLabel l)
973                TESTLT_P  i l      -> instr3 st i_TESTLT_P i (findLabel l)
974                TESTEQ_P  i l      -> instr3 st i_TESTEQ_P i (findLabel l)
975                CASEFAIL           -> instr1 st i_CASEFAIL
976                ENTER              -> instr1 st i_ENTER
977                RETURN rep         -> do (itbl_no,st2) <- itoc_itbl st rep
978                                         instr2 st2 i_RETURN itbl_no
979
980        i2s :: Int -> Word16
981        i2s = fromIntegral
982
983        instr1 (st_i0,st_l0,st_p0,st_I0) i1
984           = do st_i1 <- addToSS st_i0 (i2s i1)
985                return (st_i1,st_l0,st_p0,st_I0)
986
987        instr2 (st_i0,st_l0,st_p0,st_I0) i1 i2
988           = do st_i1 <- addToSS st_i0 (i2s i1)
989                st_i2 <- addToSS st_i1 (i2s i2)
990                return (st_i2,st_l0,st_p0,st_I0)
991
992        instr3 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3
993           = do st_i1 <- addToSS st_i0 (i2s i1)
994                st_i2 <- addToSS st_i1 (i2s i2)
995                st_i3 <- addToSS st_i2 (i2s i3)
996                return (st_i3,st_l0,st_p0,st_I0)
997
998        instr4 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3 i4
999           = do st_i1 <- addToSS st_i0 (i2s i1)
1000                st_i2 <- addToSS st_i1 (i2s i2)
1001                st_i3 <- addToSS st_i2 (i2s i3)
1002                st_i4 <- addToSS st_i3 (i2s i4)
1003                return (st_i4,st_l0,st_p0,st_I0)
1004
1005        float (st_i0,st_l0,st_p0,st_I0) f
1006           = do let ws = mkLitF f
1007                st_l1 <- addListToSS st_l0 ws
1008                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1009
1010        double (st_i0,st_l0,st_p0,st_I0) d
1011           = do let ws = mkLitD d
1012                st_l1 <- addListToSS st_l0 ws
1013                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1014
1015        int (st_i0,st_l0,st_p0,st_I0) i
1016           = do let ws = mkLitI i
1017                st_l1 <- addListToSS st_l0 ws
1018                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1019
1020        addr (st_i0,st_l0,st_p0,st_I0) a
1021           = do let ws = mkLitA a
1022                st_l1 <- addListToSS st_l0 ws
1023                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
1024
1025        ptr (st_i0,st_l0,st_p0,st_I0) p
1026           = do st_p1 <- addToSS st_p0 p
1027                return (sizeSS st_p0, (st_i0,st_l0,st_p1,st_I0))
1028
1029        itbl (st_i0,st_l0,st_p0,st_I0) dcon
1030           = do st_I1 <- addToSS st_I0 (getName dcon)
1031                return (sizeSS st_I0, (st_i0,st_l0,st_p0,st_I1))
1032
1033        literal st (MachInt j)    = int st (fromIntegral j)
1034        literal st (MachFloat r)  = float st (fromRational r)
1035        literal st (MachDouble r) = double st (fromRational r)
1036        literal st (MachChar c)   = int st c
1037
1038        ctoi_itbl st pk
1039           = addr st ret_itbl_addr
1040             where
1041                ret_itbl_addr = case pk of
1042                                   IntRep    -> stg_ctoi_ret_R1_info
1043                                   FloatRep  -> stg_ctoi_ret_F1_info
1044                                   DoubleRep -> stg_ctoi_ret_D1_info
1045                                where  -- TEMP HACK
1046                                   stg_ctoi_ret_F1_info = nullAddr
1047                                   stg_ctoi_ret_D1_info = nullAddr
1048
1049        itoc_itbl st pk
1050           = addr st ret_itbl_addr
1051             where
1052                ret_itbl_addr = case pk of
1053                                   IntRep    -> stg_gc_unbx_r1_info
1054                                   FloatRep  -> stg_gc_f1_info
1055                                   DoubleRep -> stg_gc_d1_info
1056                      
1057 foreign label "stg_ctoi_ret_R1_info" stg_ctoi_ret_R1_info :: Addr
1058 --foreign label "stg_ctoi_ret_F1_info" stg_ctoi_ret_F1_info :: Addr
1059 --foreign label "stg_ctoi_ret_D1_info" stg_ctoi_ret_D1_info :: Addr
1060
1061 foreign label "stg_gc_unbx_r1_info" stg_gc_unbx_r1_info :: Addr
1062 foreign label "stg_gc_f1_info"      stg_gc_f1_info :: Addr
1063 foreign label "stg_gc_d1_info"      stg_gc_d1_info :: Addr
1064
1065 -- The size in bytes of an instruction.
1066 instrSizeB :: BCInstr -> Int
1067 instrSizeB instr
1068    = case instr of
1069         ARGCHECK _     -> 4
1070         PUSH_L   _     -> 4
1071         PUSH_LL  _ _   -> 6
1072         PUSH_LLL _ _ _ -> 8
1073         PUSH_G   _     -> 4
1074         PUSH_AS  _ _   -> 6
1075         PUSH_UBX _ _   -> 6
1076         PUSH_TAG _     -> 4
1077         SLIDE    _ _   -> 6
1078         ALLOC    _     -> 4
1079         MKAP     _ _   -> 6
1080         UNPACK   _     -> 4
1081         UPK_TAG  _ _ _ -> 8
1082         PACK     _ _   -> 6
1083         LABEL    _     -> 0     -- !!
1084         TESTLT_I _ _   -> 6
1085         TESTEQ_I _ _   -> 6
1086         TESTLT_F _ _   -> 6
1087         TESTEQ_F _ _   -> 6
1088         TESTLT_D _ _   -> 6
1089         TESTEQ_D _ _   -> 6
1090         TESTLT_P _ _   -> 6
1091         TESTEQ_P _ _   -> 6
1092         CASEFAIL       -> 2
1093         ENTER          -> 2
1094         RETURN   _     -> 4
1095
1096
1097 -- Make lists of host-sized words for literals, so that when the
1098 -- words are placed in memory at increasing addresses, the
1099 -- bit pattern is correct for the host's word size and endianness.
1100 mkLitI :: Int    -> [Word]
1101 mkLitF :: Float  -> [Word]
1102 mkLitD :: Double -> [Word]
1103 mkLitA :: Addr   -> [Word]
1104
1105 mkLitF f
1106    = runST (do
1107         arr <- newFloatArray ((0::Int),0)
1108         writeFloatArray arr 0 f
1109         f_arr <- castSTUArray arr
1110         w0 <- readWordArray f_arr 0
1111         return [w0]
1112      )
1113
1114 mkLitD d
1115    | wORD_SIZE == 4
1116    = runST (do
1117         arr <- newDoubleArray ((0::Int),0)
1118         writeDoubleArray arr 0 d
1119         d_arr <- castSTUArray arr
1120         w0 <- readWordArray d_arr 0
1121         w1 <- readWordArray d_arr 1
1122         return [w0,w1]
1123      )
1124    | wORD_SIZE == 8
1125    = runST (do
1126         arr <- newDoubleArray ((0::Int),0)
1127         writeDoubleArray arr 0 d
1128         d_arr <- castSTUArray arr
1129         w0 <- readWordArray d_arr 0
1130         return [w0]
1131      )
1132
1133 mkLitI i
1134    = runST (do
1135         arr <- newIntArray ((0::Int),0)
1136         writeIntArray arr 0 i
1137         i_arr <- castSTUArray arr
1138         w0 <- readWordArray i_arr 0
1139         return [w0]
1140      )
1141
1142 mkLitA a
1143    = runST (do
1144         arr <- newAddrArray ((0::Int),0)
1145         writeAddrArray arr 0 a
1146         a_arr <- castSTUArray arr
1147         w0 <- readWordArray a_arr 0
1148         return [w0]
1149      )
1150
1151 \end{code}
1152
1153 %************************************************************************
1154 %*                                                                      *
1155 \subsection{Linking interpretables into something we can run}
1156 %*                                                                      *
1157 %************************************************************************
1158
1159 \begin{code}
1160
1161 {- 
1162 data BCO# = BCO# ByteArray#             -- instrs   :: array Word16#
1163                  ByteArray#             -- literals :: array Word32#
1164                  PtrArray#              -- ptrs     :: Array HValue
1165                  ByteArray#             -- itbls    :: Array Addr#
1166 -}
1167
1168 GLOBAL_VAR(v_cafTable, [], [HValue])
1169
1170 --addCAF :: HValue -> IO ()
1171 --addCAF x = do xs <- readIORef v_cafTable; writeIORef v_cafTable (x:xs)
1172
1173 --bcosToHValue :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr -> IO HValue
1174 --bcosToHValue ie ce (root_bco, other_bcos)
1175 --   = do linked_expr <- linkIExpr ie ce (root_bco, other_bcos)
1176 --      return linked_expr
1177
1178 linkBCO ie ce (UnlinkedBCO nm insnsSS literalsSS ptrsSS itblsSS)
1179    = do insns    <- listFromSS insnsSS
1180         literals <- listFromSS literalsSS
1181         ptrs     <- listFromSS ptrsSS
1182         itbls    <- listFromSS itblsSS
1183
1184         linked_ptrs  <- mapM (lookupCE ce) ptrs
1185         linked_itbls <- mapM (lookupIE ie) itbls
1186
1187         let n_insns    = sizeSS insnsSS
1188             n_literals = sizeSS literalsSS
1189             n_ptrs     = sizeSS ptrsSS
1190             n_itbls    = sizeSS itblsSS
1191
1192         let ptrs_arr = array (0, n_ptrs-1) (indexify linked_ptrs)
1193                        :: Array Int HValue
1194             ptrs_parr = case ptrs_arr of Array lo hi parr -> parr
1195
1196             itbls_arr = array (0, n_itbls-1) (indexify linked_itbls)
1197                         :: UArray Int Addr
1198             itbls_barr = case itbls_arr of UArray lo hi barr -> barr
1199
1200             insns_arr | n_insns > 65535
1201                       = panic "linkBCO: >= 64k insns in BCO"
1202                       | otherwise 
1203                       = array (0, n_insns) 
1204                               (indexify (fromIntegral n_insns:insns))
1205                         :: UArray Int Word16
1206             insns_barr = case insns_arr of UArray lo hi barr -> barr
1207
1208             literals_arr = array (0, n_literals-1) (indexify literals)
1209                            :: UArray Int Word
1210             literals_barr = case literals_arr of UArray lo hi barr -> barr
1211
1212             indexify :: [a] -> [(Int, a)]
1213             indexify xs = zip [0..] xs
1214
1215         BCO bco# <- newBCO insns_barr literals_barr ptrs_parr itbls_barr
1216
1217         return (unsafeCoerce# bco#)
1218
1219
1220 data BCO = BCO BCO#
1221
1222 newBCO :: ByteArray# -> ByteArray# -> Array# a -> ByteArray# -> IO BCO
1223 newBCO a b c d
1224    = IO (\s -> case newBCO# a b c d s of (# s1, bco #) -> (# s1, BCO bco #))
1225
1226
1227 lookupCE :: ClosureEnv -> Name -> IO HValue
1228 lookupCE ce nm 
1229    = case lookupFM ce nm of
1230         Just aa -> return aa
1231         Nothing 
1232            -> do m <- lookupSymbol (nameToCLabel nm "closure")
1233                  case m of
1234                     Just (A# addr) -> case addrToHValue# addr of
1235                                          (# hval #) -> return hval
1236                     Nothing        -> pprPanic "ByteCodeGen.lookupCE" (ppr nm)
1237
1238 lookupIE :: ItblEnv -> Name -> IO Addr
1239 lookupIE ie con_nm 
1240    = case lookupFM ie con_nm of
1241         Just (Ptr a) -> return a
1242         Nothing      
1243            -> do -- try looking up in the object files.
1244                  m <- lookupSymbol (nameToCLabel con_nm "con_info")
1245                  case m of
1246                     Just addr -> return addr
1247                     Nothing   -> pprPanic "ByteCodeGen.lookupIE" (ppr con_nm)
1248
1249 -- HACK!!!  ToDo: cleaner
1250 nameToCLabel :: Name -> String{-suffix-} -> String
1251 nameToCLabel n suffix
1252    = _UNPK_(moduleNameFS (rdrNameModule rn)) 
1253      ++ '_':occNameString(rdrNameOcc rn) ++ '_':suffix
1254      where rn = toRdrName n
1255
1256
1257 {-
1258 lookupCon ie con = 
1259   case lookupFM ie con of
1260     Just (Ptr addr) -> return addr
1261     Nothing   -> do
1262         -- try looking up in the object files.
1263         m <- lookupSymbol (nameToCLabel con "con_info")
1264         case m of
1265             Just addr -> return addr
1266             Nothing   -> pprPanic "linkIExpr" (ppr con)
1267
1268 -- nullary constructors don't have normal _con_info tables.
1269 lookupNullaryCon ie con =
1270   case lookupFM ie con of
1271     Just (Ptr addr) -> return (ConApp addr)
1272     Nothing -> do
1273         -- try looking up in the object files.
1274         m <- lookupSymbol (nameToCLabel con "closure")
1275         case m of
1276             Just (A# addr) -> return (Native (unsafeCoerce# addr))
1277             Nothing   -> pprPanic "lookupNullaryCon" (ppr con)
1278
1279
1280 lookupNative ce var =
1281   unsafeInterleaveIO (do
1282       case lookupFM ce var of
1283         Just e  -> return (Native e)
1284         Nothing -> do
1285             -- try looking up in the object files.
1286             let lbl = (nameToCLabel var "closure")
1287             m <- lookupSymbol lbl
1288             case m of
1289                 Just (A# addr)
1290                     -> do addCAF (unsafeCoerce# addr)
1291                           return (Native (unsafeCoerce# addr))
1292                 Nothing   -> pprPanic "linkIExpr" (ppr var)
1293   )
1294
1295 -- some VarI/VarP refer to top-level interpreted functions; we change
1296 -- them into Natives here.
1297 lookupVar ce f v =
1298   unsafeInterleaveIO (
1299         case lookupFM ce (getName v) of
1300             Nothing -> return (f v)
1301             Just e  -> return (Native e)
1302   )
1303 -}
1304 \end{code}
1305
1306 %************************************************************************
1307 %*                                                                      *
1308 \subsection{Manufacturing of info tables for DataCons}
1309 %*                                                                      *
1310 %************************************************************************
1311
1312 \begin{code}
1313
1314 #if __GLASGOW_HASKELL__ <= 408
1315 type ItblPtr = Addr
1316 #else
1317 type ItblPtr = Ptr StgInfoTable
1318 #endif
1319
1320 -- Make info tables for the data decls in this module
1321 mkITbls :: [TyCon] -> IO ItblEnv
1322 mkITbls [] = return emptyFM
1323 mkITbls (tc:tcs) = do itbls  <- mkITbl tc
1324                       itbls2 <- mkITbls tcs
1325                       return (itbls `plusFM` itbls2)
1326
1327 mkITbl :: TyCon -> IO ItblEnv
1328 mkITbl tc
1329 --   | trace ("TYCON: " ++ showSDoc (ppr tc)) False
1330 --   = error "?!?!"
1331    | not (isDataTyCon tc) 
1332    = return emptyFM
1333    | n == length dcs  -- paranoia; this is an assertion.
1334    = make_constr_itbls dcs
1335      where
1336         dcs = tyConDataCons tc
1337         n   = tyConFamilySize tc
1338
1339 cONSTR :: Int
1340 cONSTR = 1  -- as defined in ghc/includes/ClosureTypes.h
1341
1342 -- Assumes constructors are numbered from zero, not one
1343 make_constr_itbls :: [DataCon] -> IO ItblEnv
1344 make_constr_itbls cons
1345    | length cons <= 8
1346    = do is <- mapM mk_vecret_itbl (zip cons [0..])
1347         return (listToFM is)
1348    | otherwise
1349    = do is <- mapM mk_dirret_itbl (zip cons [0..])
1350         return (listToFM is)
1351      where
1352         mk_vecret_itbl (dcon, conNo)
1353            = mk_itbl dcon conNo (vecret_entry conNo)
1354         mk_dirret_itbl (dcon, conNo)
1355            = mk_itbl dcon conNo stg_interp_constr_entry
1356
1357         mk_itbl :: DataCon -> Int -> Addr -> IO (Name,ItblPtr)
1358         mk_itbl dcon conNo entry_addr
1359            = let (tot_wds, ptr_wds, _) 
1360                     = mkVirtHeapOffsets typePrimRep (dataConRepArgTys dcon)
1361                  ptrs = ptr_wds
1362                  nptrs  = tot_wds - ptr_wds
1363                  itbl  = StgInfoTable {
1364                            ptrs = fromIntegral ptrs, nptrs = fromIntegral nptrs,
1365                            tipe = fromIntegral cONSTR,
1366                            srtlen = fromIntegral conNo,
1367                            code0 = fromIntegral code0, code1 = fromIntegral code1,
1368                            code2 = fromIntegral code2, code3 = fromIntegral code3,
1369                            code4 = fromIntegral code4, code5 = fromIntegral code5,
1370                            code6 = fromIntegral code6, code7 = fromIntegral code7 
1371                         }
1372                  -- Make a piece of code to jump to "entry_label".
1373                  -- This is the only arch-dependent bit.
1374                  -- On x86, if entry_label has an address 0xWWXXYYZZ,
1375                  -- emit   movl $0xWWXXYYZZ,%eax  ;  jmp *%eax
1376                  -- which is
1377                  -- B8 ZZ YY XX WW FF E0
1378                  (code0,code1,code2,code3,code4,code5,code6,code7)
1379                     = (0xB8, byte 0 entry_addr_w, byte 1 entry_addr_w, 
1380                              byte 2 entry_addr_w, byte 3 entry_addr_w, 
1381                        0xFF, 0xE0, 
1382                        0x90 {-nop-})
1383
1384                  entry_addr_w :: Word32
1385                  entry_addr_w = fromIntegral (addrToInt entry_addr)
1386              in
1387                  do addr <- malloc
1388                     --putStrLn ("SIZE of itbl is " ++ show (sizeOf itbl))
1389                     --putStrLn ("# ptrs  of itbl is " ++ show ptrs)
1390                     --putStrLn ("# nptrs of itbl is " ++ show nptrs)
1391                     poke addr itbl
1392                     return (getName dcon, addr `plusPtr` 8)
1393
1394
1395 byte :: Int -> Word32 -> Word32
1396 byte 0 w = w .&. 0xFF
1397 byte 1 w = (w `shiftR` 8) .&. 0xFF
1398 byte 2 w = (w `shiftR` 16) .&. 0xFF
1399 byte 3 w = (w `shiftR` 24) .&. 0xFF
1400
1401
1402 vecret_entry 0 = stg_interp_constr1_entry
1403 vecret_entry 1 = stg_interp_constr2_entry
1404 vecret_entry 2 = stg_interp_constr3_entry
1405 vecret_entry 3 = stg_interp_constr4_entry
1406 vecret_entry 4 = stg_interp_constr5_entry
1407 vecret_entry 5 = stg_interp_constr6_entry
1408 vecret_entry 6 = stg_interp_constr7_entry
1409 vecret_entry 7 = stg_interp_constr8_entry
1410
1411 -- entry point for direct returns for created constr itbls
1412 foreign label "stg_interp_constr_entry" stg_interp_constr_entry :: Addr
1413 -- and the 8 vectored ones
1414 foreign label "stg_interp_constr1_entry" stg_interp_constr1_entry :: Addr
1415 foreign label "stg_interp_constr2_entry" stg_interp_constr2_entry :: Addr
1416 foreign label "stg_interp_constr3_entry" stg_interp_constr3_entry :: Addr
1417 foreign label "stg_interp_constr4_entry" stg_interp_constr4_entry :: Addr
1418 foreign label "stg_interp_constr5_entry" stg_interp_constr5_entry :: Addr
1419 foreign label "stg_interp_constr6_entry" stg_interp_constr6_entry :: Addr
1420 foreign label "stg_interp_constr7_entry" stg_interp_constr7_entry :: Addr
1421 foreign label "stg_interp_constr8_entry" stg_interp_constr8_entry :: Addr
1422
1423
1424
1425
1426
1427 -- Ultra-minimalist version specially for constructors
1428 data StgInfoTable = StgInfoTable {
1429    ptrs :: Word16,
1430    nptrs :: Word16,
1431    srtlen :: Word16,
1432    tipe :: Word16,
1433    code0, code1, code2, code3, code4, code5, code6, code7 :: Word8
1434 }
1435
1436
1437 instance Storable StgInfoTable where
1438
1439    sizeOf itbl 
1440       = (sum . map (\f -> f itbl))
1441         [fieldSz ptrs, fieldSz nptrs, fieldSz srtlen, fieldSz tipe,
1442          fieldSz code0, fieldSz code1, fieldSz code2, fieldSz code3, 
1443          fieldSz code4, fieldSz code5, fieldSz code6, fieldSz code7]
1444
1445    alignment itbl 
1446       = (sum . map (\f -> f itbl))
1447         [fieldAl ptrs, fieldAl nptrs, fieldAl srtlen, fieldAl tipe,
1448          fieldAl code0, fieldAl code1, fieldAl code2, fieldAl code3, 
1449          fieldAl code4, fieldAl code5, fieldAl code6, fieldAl code7]
1450
1451    poke a0 itbl
1452       = do a1 <- store (ptrs   itbl) (castPtr a0)
1453            a2 <- store (nptrs  itbl) a1
1454            a3 <- store (tipe   itbl) a2
1455            a4 <- store (srtlen itbl) a3
1456            a5 <- store (code0  itbl) a4
1457            a6 <- store (code1  itbl) a5
1458            a7 <- store (code2  itbl) a6
1459            a8 <- store (code3  itbl) a7
1460            a9 <- store (code4  itbl) a8
1461            aA <- store (code5  itbl) a9
1462            aB <- store (code6  itbl) aA
1463            aC <- store (code7  itbl) aB
1464            return ()
1465
1466    peek a0
1467       = do (a1,ptrs)   <- load (castPtr a0)
1468            (a2,nptrs)  <- load a1
1469            (a3,tipe)   <- load a2
1470            (a4,srtlen) <- load a3
1471            (a5,code0)  <- load a4
1472            (a6,code1)  <- load a5
1473            (a7,code2)  <- load a6
1474            (a8,code3)  <- load a7
1475            (a9,code4)  <- load a8
1476            (aA,code5)  <- load a9
1477            (aB,code6)  <- load aA
1478            (aC,code7)  <- load aB
1479            return StgInfoTable { ptrs = ptrs, nptrs = nptrs, 
1480                                  srtlen = srtlen, tipe = tipe,
1481                                  code0 = code0, code1 = code1, code2 = code2,
1482                                  code3 = code3, code4 = code4, code5 = code5,
1483                                  code6 = code6, code7 = code7 }
1484
1485 fieldSz :: (Storable a, Storable b) => (a -> b) -> a -> Int
1486 fieldSz sel x = sizeOf (sel x)
1487
1488 fieldAl :: (Storable a, Storable b) => (a -> b) -> a -> Int
1489 fieldAl sel x = alignment (sel x)
1490
1491 store :: Storable a => a -> Ptr a -> IO (Ptr b)
1492 store x addr = do poke addr x
1493                   return (castPtr (addr `plusPtr` sizeOf x))
1494
1495 load :: Storable a => Ptr a -> IO (Ptr b, a)
1496 load addr = do x <- peek addr
1497                return (castPtr (addr `plusPtr` sizeOf x), x)
1498
1499 \end{code}
1500
1501 %************************************************************************
1502 %*                                                                      *
1503 \subsection{Connect to actual values for bytecode opcodes}
1504 %*                                                                      *
1505 %************************************************************************
1506
1507 \begin{code}
1508
1509 #include "Bytecodes.h"
1510
1511 i_ARGCHECK = (bci_ARGCHECK :: Int)
1512 i_PUSH_L   = (bci_PUSH_L :: Int)
1513 i_PUSH_LL  = (bci_PUSH_LL :: Int)
1514 i_PUSH_LLL = (bci_PUSH_LLL :: Int)
1515 i_PUSH_G   = (bci_PUSH_G :: Int)
1516 i_PUSH_AS  = (bci_PUSH_AS :: Int)
1517 i_PUSH_UBX = (bci_PUSH_UBX :: Int)
1518 i_PUSH_TAG = (bci_PUSH_TAG :: Int)
1519 i_SLIDE    = (bci_SLIDE :: Int)
1520 i_ALLOC    = (bci_ALLOC :: Int)
1521 i_MKAP     = (bci_MKAP :: Int)
1522 i_UNPACK   = (bci_UNPACK :: Int)
1523 i_UPK_TAG  = (bci_UPK_TAG :: Int)
1524 i_PACK     = (bci_PACK :: Int)
1525 i_TESTLT_I = (bci_TESTLT_I :: Int)
1526 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
1527 i_TESTLT_F = (bci_TESTLT_F :: Int)
1528 i_TESTEQ_F = (bci_TESTEQ_F :: Int)
1529 i_TESTLT_D = (bci_TESTLT_D :: Int)
1530 i_TESTEQ_D = (bci_TESTEQ_D :: Int)
1531 i_TESTLT_P = (bci_TESTLT_P :: Int)
1532 i_TESTEQ_P = (bci_TESTEQ_P :: Int)
1533 i_CASEFAIL = (bci_CASEFAIL :: Int)
1534 i_ENTER    = (bci_ENTER :: Int)
1535 i_RETURN   = (bci_RETURN :: Int)
1536
1537 \end{code}