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