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