[project @ 2000-12-12 15:58:48 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 )
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 import TyCon            ( tyConFamilySize )
26 import Util             ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem )
27 import Var              ( isTyVar )
28 import VarSet           ( VarSet, varSetElems )
29 import PrimRep          ( getPrimRepSize, isFollowableRep )
30 import Constants        ( wORD_SIZE )
31
32 import Monad            ( foldM )
33 import Foreign          ( Addr, Word16, Word32, nullAddr )
34 import ST               ( runST )
35 --import MutableArray   ( readWord32Array,
36 --                        newFloatArray, writeFloatArray,
37 --                        newDoubleArray, writeDoubleArray,
38 --                        newIntArray, writeIntArray,
39 --                        newAddrArray, writeAddrArray )
40
41 import MArray
42 \end{code}
43
44 Entry point.
45
46 \begin{code}
47 byteCodeGen :: [CoreBind] -> [ProtoBCO Name]
48 byteCodeGen binds
49    = let flatBinds = concatMap getBind binds
50          getBind (NonRec bndr rhs) = [(bndr, freeVars rhs)]
51          getBind (Rec binds)       = [(bndr, freeVars rhs) | (bndr,rhs) <- binds]
52          final_state = runBc (BcM_State [] 0) 
53                              (mapBc schemeR flatBinds `thenBc_` returnBc ())
54      in  
55          case final_state of
56             BcM_State bcos final_ctr -> bcos
57 \end{code}
58
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection{Bytecodes, and Outputery.}
63 %*                                                                      *
64 %************************************************************************
65
66 \begin{code}
67
68 type LocalLabel = Int
69
70 data UnboxedLit = UnboxedI Int | UnboxedF Float | UnboxedD Double
71
72 data BCInstr
73    -- Messing with the stack
74    = ARGCHECK  Int
75    -- Push locals (existing bits of the stack)
76    | PUSH_L    Int{-offset-}
77    | PUSH_LL   Int Int{-2 offsets-}
78    | PUSH_LLL  Int Int Int{-3 offsets-}
79    -- Push a ptr
80    | PUSH_G    Name
81    -- Push an alt continuation
82    | PUSH_AS   Name PrimRep     -- push alts and BCO_ptr_ret_info
83                                 -- PrimRep so we know which itbl
84    -- Pushing literals
85    | PUSH_UBX  Literal  -- push this int/float/double, NO TAG, on the stack
86    | PUSH_TAG  Int      -- push this tag on the stack
87
88    | SLIDE     Int{-this many-} Int{-down by this much-}
89    -- To do with the heap
90    | ALLOC     Int      -- make an AP_UPD with this many payload words, zeroed
91    | MKAP      Int{-ptr to AP_UPD is this far down stack-} Int{-# words-}
92    | UNPACK    Int      -- unpack N ptr words from t.o.s Constr
93    | UPK_TAG   Int Int Int
94                         -- unpack N non-ptr words from offset M in constructor
95                         -- K words down the stack
96    | PACK      DataCon Int
97    -- For doing case trees
98    | LABEL     LocalLabel
99    | TESTLT_I  Int    LocalLabel
100    | TESTEQ_I  Int    LocalLabel
101    | TESTLT_F  Float  LocalLabel
102    | TESTEQ_F  Float  LocalLabel
103    | TESTLT_D  Double LocalLabel
104    | TESTEQ_D  Double LocalLabel
105    | TESTLT_P  Int    LocalLabel
106    | TESTEQ_P  Int    LocalLabel
107    | CASEFAIL
108    -- To Infinity And Beyond
109    | ENTER
110    | RETURN     -- unboxed value on TOS.  Use tag to find underlying ret itbl
111                 -- and return as per that.
112
113
114 instance Outputable BCInstr where
115    ppr (ARGCHECK n)          = text "ARGCHECK" <+> int n
116    ppr (PUSH_L offset)       = text "PUSH_L  " <+> int offset
117    ppr (PUSH_LL o1 o2)       = text "PUSH_LL " <+> int o1 <+> int o2
118    ppr (PUSH_LLL o1 o2 o3)   = text "PUSH_LLL" <+> int o1 <+> int o2 <+> int o3
119    ppr (PUSH_G nm)           = text "PUSH_G  " <+> ppr nm
120    ppr (PUSH_AS nm pk)       = text "PUSH_AS " <+> ppr nm <+> ppr pk
121    ppr (SLIDE n d)           = text "SLIDE   " <+> int n <+> int d
122    ppr (ALLOC sz)            = text "ALLOC   " <+> int sz
123    ppr (MKAP offset sz)      = text "MKAP    " <+> int offset <+> int sz
124    ppr (UNPACK sz)           = text "UNPACK  " <+> int sz
125    ppr (PACK dcon sz)        = text "PACK    " <+> ppr dcon <+> ppr sz
126    ppr (LABEL     lab)       = text "__"       <> int lab <> colon
127    ppr (TESTLT_I  i lab)     = text "TESTLT_I" <+> int i <+> text "__" <> int lab
128    ppr (TESTEQ_I  i lab)     = text "TESTEQ_I" <+> int i <+> text "__" <> int lab
129    ppr (TESTLT_F  f lab)     = text "TESTLT_F" <+> float f <+> text "__" <> int lab
130    ppr (TESTEQ_F  f lab)     = text "TESTEQ_F" <+> float f <+> text "__" <> int lab
131    ppr (TESTLT_D  d lab)     = text "TESTLT_D" <+> double d <+> text "__" <> int lab
132    ppr (TESTEQ_D  d lab)     = text "TESTEQ_D" <+> double d <+> text "__" <> int lab
133    ppr (TESTLT_P  i lab)     = text "TESTLT_P" <+> int i <+> text "__" <> int lab
134    ppr (TESTEQ_P  i lab)     = text "TESTEQ_P" <+> int i <+> text "__" <> int lab
135    ppr CASEFAIL              = text "CASEFAIL"
136    ppr ENTER                 = text "ENTER"
137    ppr RETURN                = text "RETURN"
138
139 pprAltCode discrs_n_codes
140    = vcat (map f discrs_n_codes)
141      where f (discr, code) = ppr discr <> colon <+> vcat (map ppr (fromOL code))
142
143 instance Outputable a => Outputable (ProtoBCO a) where
144    ppr (ProtoBCO name instrs origin)
145       = (text "ProtoBCO" <+> ppr name <> colon)
146         $$ nest 6 (vcat (map ppr instrs))
147         $$ case origin of
148               Left alts -> vcat (map (pprCoreAlt.deAnnAlt) alts)
149               Right rhs -> pprCoreExpr (deAnnotate rhs)
150 \end{code}
151
152 %************************************************************************
153 %*                                                                      *
154 \subsection{Compilation schema for the bytecode generator.}
155 %*                                                                      *
156 %************************************************************************
157
158 \begin{code}
159
160 type BCInstrList = OrdList BCInstr
161
162 data ProtoBCO a 
163    = ProtoBCO a                         -- name, in some sense
164               [BCInstr]                 -- instrs
165                                         -- what the BCO came from
166               (Either [AnnAlt Id VarSet]
167                       (AnnExpr Id VarSet))
168
169
170 type Sequel = Int       -- back off to this depth before ENTER
171
172 -- Maps Ids to the offset from the stack _base_ so we don't have
173 -- to mess with it after each push/pop.
174 type BCEnv = FiniteMap Id Int   -- To find vars on the stack
175
176
177 -- Create a BCO and do a spot of peephole optimisation on the insns
178 -- at the same time.
179 mkProtoBCO nm instrs_ordlist origin
180    = ProtoBCO nm (peep (fromOL instrs_ordlist)) origin
181      where
182         peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
183            = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
184         peep (PUSH_L off1 : PUSH_L off2 : rest)
185            = PUSH_LL off1 off2 : peep rest
186         peep (i:rest)
187            = i : peep rest
188         peep []
189            = []
190
191
192 -- Compile code for the right hand side of a let binding.
193 -- Park the resulting BCO in the monad.  Also requires the
194 -- variable to which this value was bound, so as to give the
195 -- resulting BCO a name.
196 schemeR :: (Id, AnnExpr Id VarSet) -> BcM ()
197 schemeR (nm, rhs) = schemeR_wrk rhs nm (collect [] rhs)
198
199 collect xs (_, AnnLam x e) 
200    = collect (if isTyVar x then xs else (x:xs)) e
201 collect xs not_lambda
202    = (reverse xs, not_lambda)
203
204 schemeR_wrk original_body nm (args, body)
205    = let fvs       = filter (not.isTyVar) (varSetElems (fst original_body))
206          all_args  = fvs ++ reverse args
207          szsw_args = map taggedIdSizeW all_args
208          szw_args  = sum szsw_args
209          p_init    = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
210          argcheck  = if null args then nilOL else unitOL (ARGCHECK szw_args)
211      in
212      schemeE szw_args 0 p_init body             `thenBc` \ body_code ->
213      emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) (Right original_body))
214
215 -- Let szsw be the sizes in words of some items pushed onto the stack,
216 -- which has initial depth d'.  Return the values which the stack environment
217 -- should map these items to.
218 mkStackOffsets :: Int -> [Int] -> [Int]
219 mkStackOffsets original_depth szsw
220    = map (subtract 1) (tail (scanl (+) original_depth szsw))
221
222 -- Compile code to apply the given expression to the remaining args
223 -- on the stack, returning a HNF.
224 schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
225
226 -- Delegate tail-calls to schemeT.
227 schemeE d s p e@(fvs, AnnApp f a) 
228    = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnApp f a))
229 schemeE d s p e@(fvs, AnnVar v)
230    | isFollowableRep (typePrimRep (idType v))
231    = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnVar v))
232    | otherwise
233    = -- returning an unboxed value.  Heave it on the stack, SLIDE, and RETURN.
234      let (push, szw) = pushAtom True d p (AnnVar v)
235      in  returnBc (push                         -- value onto stack
236                    `snocOL` SLIDE szw (d-s)     -- clear to sequel
237                    `snocOL` RETURN)             -- go
238
239 schemeE d s p (fvs, AnnLit literal)
240    = let (push, szw) = pushAtom True d p (AnnLit literal)
241      in  returnBc (push                         -- value onto stack
242                    `snocOL` SLIDE szw (d-s)     -- clear to sequel
243                    `snocOL` RETURN)             -- go
244
245 schemeE d s p (fvs, AnnLet binds b)
246    = let (xs,rhss) = case binds of AnnNonRec x rhs  -> ([x],[rhs])
247                                    AnnRec xs_n_rhss -> unzip xs_n_rhss
248          n     = length xs
249          fvss  = map (filter (not.isTyVar).varSetElems.fst) rhss
250          sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
251
252          -- This p', d' defn is safe because all the items being pushed
253          -- are ptrs, so all have size 1.  d' and p' reflect the stack
254          -- after the closures have been allocated in the heap (but not
255          -- filled in), and pointers to them parked on the stack.
256          p'    = addListToFM p (zipE xs (mkStackOffsets d (nOfThem n 1)))
257          d'    = d + n
258
259          infos = zipE4 fvss sizes xs [n, n-1 .. 1]
260          zipE  = zipEqual "schemeE"
261          zipE4 = zipWith4Equal "schemeE" (\a b c d -> (a,b,c,d))
262
263          -- ToDo: don't build thunks for things with no free variables
264          buildThunk dd ([], size, id, off)
265             = PUSH_G (getName id) 
266               `consOL` unitOL (MKAP (off+size-1) size)
267          buildThunk dd ((fv:fvs), size, id, off)
268             = case pushAtom True dd p' (AnnVar fv) of
269                  (push_code, pushed_szw)
270                     -> push_code `appOL`
271                        buildThunk (dd+pushed_szw) (fvs, size, id, off)
272
273          thunkCode = concatOL (map (buildThunk d') infos)
274          allocCode = toOL (map ALLOC sizes)
275      in
276      schemeE d' s p' b                                  `thenBc`  \ bodyCode ->
277      mapBc schemeR (zip xs rhss)                        `thenBc_`
278      returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
279
280
281 schemeE d s p (fvs, AnnCase scrut bndr alts)
282    = let
283         -- Top of stack is the return itbl, as usual.
284         -- underneath it is the pointer to the alt_code BCO.
285         -- When an alt is entered, it assumes the returned value is
286         -- on top of the itbl.
287         ret_frame_sizeW = 2
288
289         -- Env and depth in which to compile the alts, not including
290         -- any vars bound by the alts themselves
291         d' = d + ret_frame_sizeW + taggedIdSizeW bndr
292         p' = addToFM p bndr (d' - 1)
293
294         scrut_primrep = typePrimRep (idType bndr)
295         isAlgCase
296            = case scrut_primrep of
297                 IntRep -> False ; FloatRep -> False ; DoubleRep -> False
298                 PtrRep -> True
299                 other  -> pprPanic "ByteCodeGen.schemeE" (ppr other)
300
301         -- given an alt, return a discr and code for it.
302         codeAlt alt@(discr, binds_f, rhs)
303            | isAlgCase 
304            = let binds_r      = reverse binds_f
305                  binds_r_szsw = map untaggedIdSizeW binds_r
306                  binds_szw    = sum binds_r_szsw
307                  p''          = addListToFM 
308                                    p' (zip binds_r (mkStackOffsets d' binds_r_szsw))
309                  d''          = d' + binds_szw
310                  unpack_code  = mkUnpackCode 0 0 (map (typePrimRep.idType) binds_f)
311              in schemeE d'' s p'' rhs   `thenBc` \ rhs_code -> 
312                 returnBc (my_discr alt, unpack_code `appOL` rhs_code)
313            | otherwise 
314            = ASSERT(null binds_f) 
315              schemeE d' s p' rhs        `thenBc` \ rhs_code ->
316              returnBc (my_discr alt, rhs_code)
317
318         my_discr (DEFAULT, binds, rhs)  = NoDiscr
319         my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc)
320         my_discr (LitAlt l, binds, rhs)
321            = case l of MachInt i     -> DiscrI (fromInteger i)
322                        MachFloat r   -> DiscrF (fromRational r)
323                        MachDouble r  -> DiscrD (fromRational r)
324
325         maybe_ncons 
326            | not isAlgCase = Nothing
327            | otherwise 
328            = case [dc | (DataAlt dc, _, _) <- alts] of
329                 []     -> Nothing
330                 (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
331
332      in 
333      mapBc codeAlt alts                                 `thenBc` \ alt_stuff ->
334      mkMultiBranch maybe_ncons alt_stuff                `thenBc` \ alt_final ->
335      let 
336          alt_bco_name = getName bndr
337          alt_bco      = mkProtoBCO alt_bco_name alt_final (Left alts)
338      in
339      schemeE (d + ret_frame_sizeW) 
340              (d + ret_frame_sizeW) p scrut              `thenBc` \ scrut_code ->
341
342      emitBc alt_bco                                     `thenBc_`
343      returnBc (PUSH_AS alt_bco_name scrut_primrep `consOL` scrut_code)
344
345
346 schemeE d s p (fvs, AnnNote note body)
347    = schemeE d s p body
348
349 schemeE d s p other
350    = pprPanic "ByteCodeGen.schemeE: unhandled case" 
351                (pprCoreExpr (deAnnotate other))
352
353
354 -- Compile code to do a tail call.  Doesn't need to be monadic.
355 schemeT :: Bool         -- do tagging?
356         -> Int          -- Stack depth
357         -> Sequel       -- Sequel depth
358         -> Int          -- # arg words so far
359         -> BCEnv        -- stack env
360         -> AnnExpr Id VarSet -> BCInstrList
361
362 schemeT enTag d s narg_words p (_, AnnApp f a)
363    = case snd a of
364         AnnType _ -> schemeT enTag d s narg_words p f
365         other
366            -> let (push, arg_words) = pushAtom enTag d p (snd a)
367               in push 
368                  `appOL` schemeT enTag (d+arg_words) s (narg_words+arg_words) p f
369
370 schemeT enTag d s narg_words p (_, AnnVar f)
371    | Just con <- isDataConId_maybe f
372    = ASSERT(enTag == False)
373      PACK con narg_words `consOL` (mkSLIDE 1 (d-s-1) `snocOL` ENTER)
374    | otherwise
375    = ASSERT(enTag == True)
376      let (push, arg_words) = pushAtom True d p (AnnVar f)
377      in  push 
378          `appOL`  mkSLIDE (narg_words+arg_words) (d - s - narg_words)
379          `snocOL` ENTER
380
381 mkSLIDE n d 
382    = if d == 0 then nilOL else unitOL (SLIDE n d)
383
384 should_args_be_tagged (_, AnnVar v)
385    = case isDataConId_maybe v of
386         Just dcon -> False; Nothing -> True
387 should_args_be_tagged (_, AnnApp f a)
388    = should_args_be_tagged f
389 should_args_be_tagged (_, other)
390    = panic "should_args_be_tagged: tail call to non-con, non-var"
391
392
393 -- Make code to unpack a constructor onto the stack, adding
394 -- tags for the unboxed bits.  Takes the PrimReps of the constructor's
395 -- arguments, and a travelling offset along both the constructor
396 -- (off_h) and the stack (off_s).
397 mkUnpackCode :: Int -> Int -> [PrimRep] -> BCInstrList
398 mkUnpackCode off_h off_s [] = nilOL
399 mkUnpackCode off_h off_s (r:rs)
400    | isFollowableRep r
401    = let (rs_ptr, rs_nptr) = span isFollowableRep (r:rs)
402          ptrs_szw = sum (map untaggedSizeW rs_ptr) 
403      in  ASSERT(ptrs_szw == length rs_ptr)
404          ASSERT(off_h == 0)
405          ASSERT(off_s == 0)
406          UNPACK ptrs_szw 
407          `consOL` mkUnpackCode (off_h + ptrs_szw) (off_s + ptrs_szw) rs_nptr
408    | otherwise
409    = case r of
410         IntRep    -> approved
411         FloatRep  -> approved
412         DoubleRep -> approved
413      where
414         approved = UPK_TAG usizeW off_h off_s   `consOL` theRest
415         theRest  = mkUnpackCode (off_h + usizeW) (off_s + tsizeW) rs
416         usizeW   = untaggedSizeW r
417         tsizeW   = taggedSizeW r
418
419 -- Push an atom onto the stack, returning suitable code & number of
420 -- stack words used.  Pushes it either tagged or untagged, since 
421 -- pushAtom is used to set up the stack prior to copying into the
422 -- heap for both APs (requiring tags) and constructors (which don't).
423 --
424 -- NB this means NO GC between pushing atoms for a constructor and
425 -- copying them into the heap.  It probably also means that 
426 -- tail calls MUST be of the form atom{atom ... atom} since if the
427 -- expression head was allowed to be arbitrary, there could be GC
428 -- in between pushing the arg atoms and completing the head.
429 -- (not sure; perhaps the allocate/doYouWantToGC interface means this
430 -- isn't a problem; but only if arbitrary graph construction for the
431 -- head doesn't leave this BCO, since GC might happen at the start of
432 -- each BCO (we consult doYouWantToGC there).
433 --
434 -- Blargh.  JRS 001206
435 --
436 -- NB (further) that the env p must map each variable to the highest-
437 -- numbered stack slot for it.  For example, if the stack has depth 4 
438 -- and we tagged-ly push (v :: Int#) on it, the value will be in stack[4],
439 -- the tag in stack[5], the stack will have depth 6, and p must map v to
440 -- 5 and not to 4.  Stack locations are numbered from zero, so a depth
441 -- 6 stack has valid words 0 .. 5.
442
443 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
444 pushAtom tagged d p (AnnVar v) 
445    = let str = "\npushAtom " ++ showSDocDebug (ppr v) ++ ", depth = " ++ show d
446                ++ ", env =\n" ++ 
447                showSDocDebug (nest 4 (vcat (map ppr (fmToList p))))
448                ++ " -->\n" ++
449                showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
450                ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
451          str' = if str == str then str else str
452
453          result
454             = case lookupBCEnv_maybe p v of
455                  Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), sz_t)
456                  Nothing  -> ASSERT(sz_t == 1) (unitOL (PUSH_G nm), sz_t)
457
458          nm     = getName v
459          sz_t   = taggedIdSizeW v
460          sz_u   = untaggedIdSizeW v
461          nwords = if tagged then sz_t else sz_u
462      in
463          --trace str'
464          result
465
466 pushAtom True d p (AnnLit lit)
467    = let (ubx_code, ubx_size) = pushAtom False d p (AnnLit lit)
468      in  (ubx_code `snocOL` PUSH_TAG ubx_size, 1 + ubx_size)
469
470 pushAtom False d p (AnnLit lit)
471    = case lit of
472         MachInt i    -> (code, untaggedSizeW IntRep)
473         MachFloat r  -> (code, untaggedSizeW FloatRep)
474         MachDouble r -> (code, untaggedSizeW DoubleRep)
475      where
476         code = unitOL (PUSH_UBX lit)
477
478 pushAtom tagged d p (AnnApp f (_, AnnType _))
479    = pushAtom tagged d p (snd f)
480
481 pushAtom tagged d p other
482    = pprPanic "ByteCodeGen.pushAtom" 
483               (pprCoreExpr (deAnnotate (undefined, other)))
484
485
486 -- Given a bunch of alts code and their discrs, do the donkey work
487 -- of making a multiway branch using a switch tree.
488 -- What a load of hassle!
489 mkMultiBranch :: Maybe Int      -- # datacons in tycon, if alg alt
490                                 -- a hint; generates better code
491                                 -- Nothing is always safe
492               -> [(Discr, BCInstrList)] 
493               -> BcM BCInstrList
494 mkMultiBranch maybe_ncons raw_ways
495    = let d_way     = filter (isNoDiscr.fst) raw_ways
496          notd_ways = naturalMergeSortLe 
497                         (\w1 w2 -> leAlt (fst w1) (fst w2))
498                         (filter (not.isNoDiscr.fst) raw_ways)
499
500          mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
501          mkTree [] range_lo range_hi = returnBc the_default
502
503          mkTree [val] range_lo range_hi
504             | range_lo `eqAlt` range_hi 
505             = returnBc (snd val)
506             | otherwise
507             = getLabelBc                                `thenBc` \ label_neq ->
508               returnBc (mkTestEQ (fst val) label_neq 
509                         `consOL` (snd val
510                         `appOL`   unitOL (LABEL label_neq)
511                         `appOL`   the_default))
512
513          mkTree vals range_lo range_hi
514             = let n = length vals `div` 2
515                   vals_lo = take n vals
516                   vals_hi = drop n vals
517                   v_mid = fst (head vals_hi)
518               in
519               getLabelBc                                `thenBc` \ label_geq ->
520               mkTree vals_lo range_lo (dec v_mid)       `thenBc` \ code_lo ->
521               mkTree vals_hi v_mid range_hi             `thenBc` \ code_hi ->
522               returnBc (mkTestLT v_mid label_geq
523                         `consOL` (code_lo
524                         `appOL`   unitOL (LABEL label_geq)
525                         `appOL`   code_hi))
526  
527          the_default 
528             = case d_way of [] -> unitOL CASEFAIL
529                             [(_, def)] -> def
530
531          -- None of these will be needed if there are no non-default alts
532          (mkTestLT, mkTestEQ, init_lo, init_hi)
533             | null notd_ways
534             = panic "mkMultiBranch: awesome foursome"
535             | otherwise
536             = case fst (head notd_ways) of {
537               DiscrI _ -> ( \(DiscrI i) fail_label -> TESTLT_I i fail_label,
538                             \(DiscrI i) fail_label -> TESTEQ_I i fail_label,
539                             DiscrI minBound,
540                             DiscrI maxBound );
541               DiscrF _ -> ( \(DiscrF f) fail_label -> TESTLT_F f fail_label,
542                             \(DiscrF f) fail_label -> TESTEQ_F f fail_label,
543                             DiscrF minF,
544                             DiscrF maxF );
545               DiscrD _ -> ( \(DiscrD d) fail_label -> TESTLT_D d fail_label,
546                             \(DiscrD d) fail_label -> TESTEQ_D d fail_label,
547                             DiscrD minD,
548                             DiscrD maxD );
549               DiscrP _ -> ( \(DiscrP i) fail_label -> TESTLT_P i fail_label,
550                             \(DiscrP i) fail_label -> TESTEQ_P i fail_label,
551                             DiscrP algMinBound,
552                             DiscrP algMaxBound )
553               }
554
555          (algMinBound, algMaxBound)
556             = case maybe_ncons of
557                  Just n  -> (fIRST_TAG, fIRST_TAG + n - 1)
558                  Nothing -> (minBound, maxBound)
559
560          (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
561          (DiscrF f1) `eqAlt` (DiscrF f2) = f1 == f2
562          (DiscrD d1) `eqAlt` (DiscrD d2) = d1 == d2
563          (DiscrP i1) `eqAlt` (DiscrP i2) = i1 == i2
564          NoDiscr     `eqAlt` NoDiscr     = True
565          _           `eqAlt` _           = False
566
567          (DiscrI i1) `leAlt` (DiscrI i2) = i1 <= i2
568          (DiscrF f1) `leAlt` (DiscrF f2) = f1 <= f2
569          (DiscrD d1) `leAlt` (DiscrD d2) = d1 <= d2
570          (DiscrP i1) `leAlt` (DiscrP i2) = i1 <= i2
571          NoDiscr     `leAlt` NoDiscr     = True
572          _           `leAlt` _           = False
573
574          isNoDiscr NoDiscr = True
575          isNoDiscr _       = False
576
577          dec (DiscrI i) = DiscrI (i-1)
578          dec (DiscrP i) = DiscrP (i-1)
579          dec other      = other         -- not really right, but if you
580                 -- do cases on floating values, you'll get what you deserve
581
582          -- same snotty comment applies to the following
583          minF, maxF :: Float
584          minD, maxD :: Double
585          minF = -1.0e37
586          maxF =  1.0e37
587          minD = -1.0e308
588          maxD =  1.0e308
589      in
590          mkTree notd_ways init_lo init_hi
591
592 \end{code}
593
594 %************************************************************************
595 %*                                                                      *
596 \subsection{Supporting junk for the compilation schemes}
597 %*                                                                      *
598 %************************************************************************
599
600 \begin{code}
601
602 -- Describes case alts
603 data Discr 
604    = DiscrI Int
605    | DiscrF Float
606    | DiscrD Double
607    | DiscrP Int
608    | NoDiscr
609
610 instance Outputable Discr where
611    ppr (DiscrI i) = int i
612    ppr (DiscrF f) = text (show f)
613    ppr (DiscrD d) = text (show d)
614    ppr (DiscrP i) = int i
615    ppr NoDiscr    = text "DEF"
616
617
618 -- Find things in the BCEnv (the what's-on-the-stack-env)
619 -- See comment preceding pushAtom for precise meaning of env contents
620 lookupBCEnv :: BCEnv -> Id -> Int
621 lookupBCEnv env nm
622    = case lookupFM env nm of
623         Nothing -> pprPanic "lookupBCEnv" 
624                             (ppr nm $$ char ' ' $$ vcat (map ppr (fmToList env)))
625         Just xx -> xx
626
627 lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
628 lookupBCEnv_maybe = lookupFM
629
630
631 -- When I push one of these on the stack, how much does Sp move by?
632 taggedSizeW :: PrimRep -> Int
633 taggedSizeW pr
634    | isFollowableRep pr = 1
635    | otherwise          = 1{-the tag-} + getPrimRepSize pr
636
637
638 -- The plain size of something, without tag.
639 untaggedSizeW :: PrimRep -> Int
640 untaggedSizeW pr
641    | isFollowableRep pr = 1
642    | otherwise          = getPrimRepSize pr
643
644
645 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
646 taggedIdSizeW   = taggedSizeW   . typePrimRep . idType
647 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
648
649 \end{code}
650
651 %************************************************************************
652 %*                                                                      *
653 \subsection{The bytecode generator's monad}
654 %*                                                                      *
655 %************************************************************************
656
657 \begin{code}
658 data BcM_State 
659    = BcM_State { bcos      :: [ProtoBCO Name],  -- accumulates completed BCOs
660                  nextlabel :: Int }             -- for generating local labels
661
662 type BcM result = BcM_State -> (result, BcM_State)
663
664 mkBcM_State :: [ProtoBCO Name] -> Int -> BcM_State
665 mkBcM_State = BcM_State
666
667 runBc :: BcM_State -> BcM () -> BcM_State
668 runBc init_st m = case m init_st of { (r,st) -> st }
669
670 thenBc :: BcM a -> (a -> BcM b) -> BcM b
671 thenBc expr cont st
672   = case expr st of { (result, st') -> cont result st' }
673
674 thenBc_ :: BcM a -> BcM b -> BcM b
675 thenBc_ expr cont st
676   = case expr st of { (result, st') -> cont st' }
677
678 returnBc :: a -> BcM a
679 returnBc result st = (result, st)
680
681 mapBc :: (a -> BcM b) -> [a] -> BcM [b]
682 mapBc f []     = returnBc []
683 mapBc f (x:xs)
684   = f x          `thenBc` \ r  ->
685     mapBc f xs   `thenBc` \ rs ->
686     returnBc (r:rs)
687
688 emitBc :: ProtoBCO Name -> BcM ()
689 emitBc bco st
690    = ((), st{bcos = bco : bcos st})
691
692 getLabelBc :: BcM Int
693 getLabelBc st
694    = (nextlabel st, st{nextlabel = 1 + nextlabel st})
695
696 \end{code}
697
698 %************************************************************************
699 %*                                                                      *
700 \subsection{The bytecode assembler}
701 %*                                                                      *
702 %************************************************************************
703
704 The object format for bytecodes is: 16 bits for the opcode, and 16 for
705 each field -- so the code can be considered a sequence of 16-bit ints.
706 Each field denotes either a stack offset or number of items on the
707 stack (eg SLIDE), and index into the pointer table (eg PUSH_G), an
708 index into the literal table (eg PUSH_I/D/L), or a bytecode address in
709 this BCO.
710
711 \begin{code}
712 -- An (almost) assembled BCO.
713 data BCO a = BCO [Word16]       -- instructions
714                  [Word32]       -- literal pool
715                  [a]            -- Names or HValues
716
717 -- Top level assembler fn.
718 assembleBCO :: ProtoBCO Name -> IO AsmState
719 assembleBCO (ProtoBCO nm instrs origin)
720    = let
721          -- pass 1: collect up the offsets of the local labels
722          label_env = mkLabelEnv emptyFM 0 instrs
723
724          mkLabelEnv env i_offset [] = env
725          mkLabelEnv env i_offset (i:is)
726             = let new_env 
727                      = case i of LABEL n -> addToFM env n i_offset ; _ -> env
728               in  mkLabelEnv new_env (i_offset + instrSizeB i) is
729
730          findLabel lab
731             = case lookupFM label_env lab of
732                  Just bco_offset -> bco_offset
733                  Nothing -> pprPanic "assembleBCO.findLabel" (int lab)
734
735          init_n_insns = 10
736          init_n_lits = 4
737          init_n_ptrs = 4
738      in
739      do  insns <- newXIOUArray init_n_insns :: IO (XIOUArray Word16)
740          lits  <- newXIOUArray init_n_lits  :: IO (XIOUArray Word32)
741          ptrs  <- newXIOArray  init_n_ptrs  -- :: IO (XIOArray Name)
742
743          -- pass 2: generate the instruction, ptr and nonptr bits
744          let init_asm_state = (insns,lits,ptrs)
745          final_asm_state <- mkBits findLabel init_asm_state instrs         
746      
747          return final_asm_state
748
749
750 -- instrs nonptrs ptrs
751 type AsmState = (XIOUArray Word16, XIOUArray Word32, XIOArray Name)
752
753
754 -- This is where all the action is (pass 2 of the assembler)
755 mkBits :: (Int -> Int)                  -- label finder
756        -> AsmState
757        -> [BCInstr]                     -- instructions (in)
758        -> IO AsmState
759
760 mkBits findLabel st proto_insns
761   = foldM doInstr st proto_insns
762   where
763    doInstr :: AsmState -> BCInstr -> IO AsmState
764    doInstr st i
765      = case i of
766         ARGCHECK  n        -> instr2 st i_ARGCHECK n
767 {-
768         PUSH_L    o1       -> do { instr2 i_PUSH_L o1 }
769         PUSH_LL   o1 o2    -> do { instr3 i_PUSH_LL o1 o2 }
770         PUSH_LLL  o1 o2 o3 -> do { instr4 i_PUSH_LLL o1 o2 o3 }
771         PUSH_G    nm       -> do { p <- ptr nm; instr2 i_PUSH_G p }
772         PUSH_AS   nm pk    -> do { p <- ptr nm ; np <- ret_itbl pk; 
773                                    instr3 i_PUSH_AS p np }
774         PUSH_UBX  lit      -> do { np <- literal lit; instr2 i_PUSH_UBX np }
775         PUSH_TAG  tag      -> do { instr2 i_PUSH_TAG tag }
776         SLIDE     n by     -> do { instr3 i_SLIDE n by }
777         ALLOC     n        -> do { instr2 i_ALLOC n }
778         MKAP      off sz   -> do { instr3 i_MKAP off sz }
779         UNPACK    n        -> do { instr2 i_UNPACK n }
780         UPK_TAG   n m k    -> do { instr4 i_UPK_TAG n m k }
781         PACK      dcon sz  -> do { np <- itbl dcon; instr3 i_PACK np sz }
782         LABEL     lab      -> do { instr0 }
783         TESTLT_I  i l      -> do { np <- int i; instr3 i_TESTLT_I np (findLabel l) }
784         TESTRQ_I  i l      -> do { np <- int i; instr3 i_TESTEQ_I np (findLabel l) }
785         TESTLT_F  f l      -> do { np <- float f; instr3 i_TESTLT_F np (findLabel l) }
786         TESTEQ_F  f l      -> do { np <- float f; instr3 i_TESTEQ_F np (findLabel l) }
787         TESTLT_D  d l      -> do { np <- double d; instr3 i_TESTLT_D np (findLabel l) }
788         TESTEQ_D  d l      -> do { np <- double d; instr3 i_TESTEQ_D np (findLabel l) }
789         TESTLT_P  i l      -> do { np <- int i; instr3 i_TESTLT_P np (findLabel l) }
790         TESTEQ_P  i l      -> do { np <- int i; instr3 i_TESTEQ_P np (findLabel l) }
791         CASEFAIL           -> do { instr1 i_CASEFAIL }
792         ENTER              -> do { instr1 i_ENTER }
793 -}
794      where
795         instr2 (st_i0,st_l0,st_p0) i1 i2
796            = do st_i1 <- addToXIOUArray st_i0 (i2s i1)
797                 st_i2 <- addToXIOUArray st_i1 (i2s i2)
798                 return (st_i2,st_l0,st_p0)
799
800         i2s :: Int -> Word16
801         i2s = fromIntegral
802
803 {-
804         instr2 i1 i2       = instr i1 >> instr i2
805         instr3 i1 i2 i3    = instr2 i1 i2 >> instr i3
806         instr4 i1 i2 i3 i4 = instr2 i1 i2 >> instr2 i3 i4
807
808         instr :: Word16 -> IO Ctrs
809         instr i 
810            = do n_is <- readIORef v_n_is
811                 writeInstr n_is i
812                 writeIORef v_n_is (n_is+1)
813
814
815         nop = go n_is n_lits n_ptrs instrs
816
817         instr1 i1 next
818            = do writeInstr r_is i1 n_is
819                 next (n_is+1) n_lits n_ptrs instrs
820         instr2 i1 i2 next
821            = do writeInstr r_is i1 n_is
822                 writeInstr r_is i1 (n_is+1)
823                 next (n_is+2) n_lits n_ptrs instrs
824         instr3 i1 i2 i3 next
825            = do writeInstr r_is i1 n_is
826                 writeInstr r_is i2 (n_is+1)
827                 writeInstr r_is i3 (n_is+2)
828                 next (n_is+3) n_lits n_ptrs instrs
829
830         ptr p n_is n_lits n_ptrs instrs
831            = do writeArray r_ptrs p n_ptrs
832                 mkBits n_is n_lits (n_ptrs+1) instrs
833
834         int i n_is n_lits n_ptrs instrs
835            = do n_lits <- doILit r_lits i n_lits
836                 mkBits n_is n_lits n_ptrs instrs
837
838         float f n_is n_lits n_ptrs instrs
839            = do n_lits <- doFLit r_lits f n_lits
840                 mkBits n_is n_lits n_ptrs instrs
841
842         double d n_is n_lits n_ptrs instrs
843            = do n_lits <- doDLit r_lits d n_lits
844                 mkBits n_is n_lits n_ptrs instrs
845
846         addr a n_is n_lits n_ptrs instrs
847            = do n_lits <- doALit r_lits a n_lits
848                 mkBits n_is n_lits n_ptrs instrs
849 -}
850
851 --writeInstr :: MutableByteArray# -> Int -> Int -> IO ()
852 --writeInstr arr# ix e = IO $ \s ->
853 --  case writeWord16Array# arr# ix e of
854
855
856
857 -- The size in bytes of an instruction.
858 instrSizeB :: BCInstr -> Int
859 instrSizeB instr
860    = case instr of
861         ARGCHECK _     -> 4
862         PUSH_L   _     -> 4
863         PUSH_LL  _ _   -> 6
864         PUSH_LLL _ _ _ -> 8
865         PUSH_G   _     -> 4
866         SLIDE    _ _   -> 6
867         ALLOC    _     -> 4
868         MKAP     _ _   -> 6
869         UNPACK   _     -> 4
870         PACK     _ _   -> 6
871         LABEL    _     -> 4
872         TESTLT_I _ _   -> 6
873         TESTEQ_I _ _   -> 6
874         TESTLT_F _ _   -> 6
875         TESTEQ_F _ _   -> 6
876         TESTLT_D _ _   -> 6
877         TESTEQ_D _ _   -> 6
878         TESTLT_P _ _   -> 6
879         TESTEQ_P _ _   -> 6
880         CASEFAIL       -> 2
881         ENTER          -> 2
882         RETURN         -> 2
883
884
885 -- Sizes of Int, Float and Double literals, in units of 32-bitses
886 intLitSz32s, floatLitSz32s, doubleLitSz32s, addrLitSz32s :: Int
887 intLitSz32s    = wORD_SIZE `div` 4
888 floatLitSz32s  = 1      -- Assume IEEE floats
889 doubleLitSz32s = 2
890 addrLitSz32s   = intLitSz32s
891
892 -- Make lists of 32-bit words for literals, so that when the
893 -- words are placed in memory at increasing addresses, the
894 -- bit pattern is correct for the host's word size and endianness.
895 mkILit :: Int    -> [Word32]
896 mkFLit :: Float  -> [Word32]
897 mkDLit :: Double -> [Word32]
898 mkALit :: Addr   -> [Word32]
899
900 mkFLit f
901    = runST (do
902         arr <- newFloatArray ((0::Int),0)
903         writeFloatArray arr 0 f
904         f_arr <- castSTUArray arr
905         w0 <- readWord32Array f_arr 0
906         return [w0]
907      )
908
909 mkDLit d
910    = runST (do
911         arr <- newDoubleArray ((0::Int),0)
912         writeDoubleArray arr 0 d
913         d_arr <- castSTUArray arr
914         w0 <- readWord32Array d_arr 0
915         w1 <- readWord32Array d_arr 1
916         return [w0,w1]
917      )
918
919 mkILit i
920    | wORD_SIZE == 4
921    = runST (do
922         arr <- newIntArray ((0::Int),0)
923         writeIntArray arr 0 i
924         i_arr <- castSTUArray arr
925         w0 <- readWord32Array i_arr 0
926         return [w0]
927      )
928    | wORD_SIZE == 8
929    = runST (do
930         arr <- newIntArray ((0::Int),0)
931         writeIntArray arr 0 i
932         i_arr <- castSTUArray arr
933         w0 <- readWord32Array i_arr 0
934         w1 <- readWord32Array i_arr 1
935         return [w0,w1]
936      )
937    
938 mkALit a
939    | wORD_SIZE == 4
940    = runST (do
941         arr <- newAddrArray ((0::Int),0)
942         writeAddrArray arr 0 a
943         a_arr <- castSTUArray arr
944         w0 <- readWord32Array a_arr 0
945         return [w0]
946      )
947    | wORD_SIZE == 8
948    = runST (do
949         arr <- newAddrArray ((0::Int),0)
950         writeAddrArray arr 0 a
951         a_arr <- castSTUArray arr
952         w0 <- readWord32Array a_arr 0
953         w1 <- readWord32Array a_arr 1
954         return [w0,w1]
955      )
956    
957
958
959 -- Zero-based expandable arrays
960 data XIOUArray ele = XIOUArray Int (IOUArray Int ele)
961 data XIOArray  ele = XIOArray  Int (IOArray Int ele)
962
963 newXIOUArray size
964    = do arr <- newArray (0, size-1)
965         return (XIOUArray 0 arr)
966
967 addToXIOUArray :: MArray IOUArray a IO
968                   => XIOUArray a -> a -> IO (XIOUArray a)
969 addToXIOUArray (XIOUArray n_arr arr) x
970    = case bounds arr of
971         (lo, hi) -> ASSERT(lo == 0)
972                     if   n_arr > hi
973                     then do new_arr <- newArray (0, 2*hi-1)
974                             copy hi arr new_arr
975                             addToXIOUArray (XIOUArray n_arr new_arr) x
976                     else do writeArray arr n_arr x
977                             return (XIOUArray (n_arr+1) arr)
978      where
979         copy :: MArray IOUArray a IO
980                 => Int -> IOUArray Int a -> IOUArray Int a -> IO ()
981         copy n src dst
982            | n < 0     = return ()
983            | otherwise = do nx <- readArray src n
984                             writeArray dst n nx
985                             copy (n-1) src dst
986
987
988
989 newXIOArray size
990    = do arr <- newArray (0, size-1)
991         return (XIOArray 0 arr)
992
993 addToXIOArray :: XIOArray a -> a -> IO (XIOArray a)
994 addToXIOArray (XIOArray n_arr arr) x
995    = case bounds arr of
996         (lo, hi) -> ASSERT(lo == 0)
997                     if   n_arr > hi
998                     then do new_arr <- newArray (0, 2*hi-1)
999                             copy hi arr new_arr
1000                             addToXIOArray (XIOArray n_arr new_arr) x
1001                     else do writeArray arr n_arr x
1002                             return (XIOArray (n_arr+1) arr)
1003      where
1004         copy :: Int -> IOArray Int a -> IOArray Int a -> IO ()
1005         copy n src dst
1006            | n < 0     = return ()
1007            | otherwise = do nx <- readArray src n
1008                             writeArray dst n nx
1009                             copy (n-1) src dst
1010
1011
1012 #include "Bytecodes.h"
1013
1014 i_ARGCHECK = (bci_ARGCHECK :: Int)
1015 i_PUSH_L   = (bci_PUSH_L   :: Int)
1016 i_PUSH_LL  = (bci_PUSH_LL  :: Int)
1017 i_PUSH_LLL = (bci_PUSH_LLL :: Int)
1018 i_PUSH_G   = (bci_PUSH_G   :: Int)
1019 i_PUSH_AS  = (bci_PUSH_AS  :: Int)
1020 i_PUSHT_I  = (bci_PUSHT_I  :: Int)
1021 i_PUSHT_F  = (bci_PUSHT_F  :: Int)
1022 i_PUSHT_D  = (bci_PUSHT_D  :: Int)
1023 i_PUSHU_I  = (bci_PUSHU_I  :: Int)
1024 i_PUSHU_F  = (bci_PUSHU_F  :: Int)
1025 i_PUSHU_D  = (bci_PUSHU_D  :: Int)
1026 i_SLIDE    = (bci_SLIDE    :: Int)
1027 i_ALLOC    = (bci_ALLOC    :: Int)
1028 i_MKAP     = (bci_MKAP     :: Int)
1029 i_UNPACK   = (bci_UNPACK   :: Int)
1030 i_PACK     = (bci_PACK     :: Int)
1031 i_LABEL    = (bci_LABEL    :: Int)
1032 i_TESTLT_I = (bci_TESTLT_I :: Int)
1033 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
1034 i_TESTLT_F = (bci_TESTLT_F :: Int)
1035 i_TESTEQ_F = (bci_TESTEQ_F :: Int)
1036 i_TESTLT_D = (bci_TESTLT_D :: Int)
1037 i_TESTEQ_D = (bci_TESTEQ_D :: Int)
1038 i_TESTLT_P = (bci_TESTLT_P :: Int)
1039 i_TESTEQ_P = (bci_TESTEQ_P :: Int)
1040 i_CASEFAIL = (bci_CASEFAIL :: Int)
1041 i_ENTER    = (bci_ENTER    :: Int)
1042 i_RETURN   = (bci_RETURN   :: Int)
1043
1044 \end{code}