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