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