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