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