5067aea2e07271a9353a278c58714de9366df201
[ghc-hetmet.git] / ghc / compiler / ghci / ByteCodeAsm.lhs
1 %
2 % (c) The University of Glasgow 2002
3 %
4 \section[ByteCodeLink]{Bytecode assembler and linker}
5
6 \begin{code}
7 {-# OPTIONS -optc-DNON_POSIX_SOURCE #-}
8
9 module ByteCodeAsm (  
10         assembleBCOs, assembleBCO,
11
12         CompiledByteCode(..), 
13         UnlinkedBCO(..), BCOPtr(..), bcoFreeNames,
14         SizedSeq, sizeSS, ssElts,
15         iNTERP_STACK_CHECK_THRESH
16   ) where
17
18 #include "HsVersions.h"
19
20 import ByteCodeInstr
21 import ByteCodeItbls    ( ItblEnv, mkITbls )
22
23 import Name             ( Name, getName )
24 import NameSet
25 import FiniteMap        ( addToFM, lookupFM, emptyFM )
26 import Literal          ( Literal(..) )
27 import TyCon            ( TyCon )
28 import PrimOp           ( PrimOp )
29 import Constants        ( wORD_SIZE )
30 import FastString       ( FastString(..) )
31 import SMRep            ( CgRep(..), StgWord )
32 import FiniteMap
33 import Outputable
34
35 import Control.Monad    ( foldM )
36 import Control.Monad.ST ( runST )
37
38 import GHC.Word         ( Word(..) )
39 import Data.Array.MArray
40 import Data.Array.Unboxed ( listArray )
41 import Data.Array.Base  ( UArray(..) )
42 import Data.Array.ST    ( castSTUArray )
43 import Foreign          ( Word16, free )
44 import Data.Int         ( Int64 )
45 import Data.Char        ( ord )
46
47 import GHC.Base         ( ByteArray# )
48 import GHC.IOBase       ( IO(..) )
49 import GHC.Ptr          ( Ptr(..) )
50
51 -- -----------------------------------------------------------------------------
52 -- Unlinked BCOs
53
54 -- CompiledByteCode represents the result of byte-code 
55 -- compiling a bunch of functions and data types
56
57 data CompiledByteCode 
58   = ByteCode [UnlinkedBCO] -- Bunch of interpretable bindings
59              ItblEnv       -- A mapping from DataCons to their itbls
60
61 instance Outputable CompiledByteCode where
62   ppr (ByteCode bcos _) = ppr bcos
63
64
65 data UnlinkedBCO
66    = UnlinkedBCO {
67         unlinkedBCOName   :: Name,
68         unlinkedBCOArity  :: Int,
69         unlinkedBCOInstrs :: ByteArray#,                         -- insns
70         unlinkedBCOBitmap :: ByteArray#,                         -- bitmap
71         unlinkedBCOLits   :: (SizedSeq (Either Word FastString)), -- literals
72                         -- Either literal words or a pointer to a asciiz
73                         -- string, denoting a label whose *address* should
74                         -- be determined at link time
75         unlinkedBCOPtrs   :: (SizedSeq BCOPtr),         -- ptrs
76         unlinkedBCOItbls  :: (SizedSeq Name)            -- itbl refs
77    }
78
79 data BCOPtr
80   = BCOPtrName   Name
81   | BCOPtrPrimOp PrimOp
82   | BCOPtrBCO    UnlinkedBCO
83
84 -- | Finds external references.  Remember to remove the names
85 -- defined by this group of BCOs themselves
86 bcoFreeNames :: UnlinkedBCO -> NameSet
87 bcoFreeNames bco
88   = bco_refs bco `minusNameSet` mkNameSet [unlinkedBCOName bco]
89   where
90     bco_refs (UnlinkedBCO _ _ _ _ _ ptrs itbls)
91         = unionManyNameSets (
92              mkNameSet [ n | BCOPtrName n <- ssElts ptrs ] :
93              mkNameSet (ssElts itbls) :
94              map bco_refs [ bco | BCOPtrBCO bco <- ssElts ptrs ]
95           )
96
97 instance Outputable UnlinkedBCO where
98    ppr (UnlinkedBCO nm arity insns bitmap lits ptrs itbls)
99       = sep [text "BCO", ppr nm, text "with", 
100              int (sizeSS lits), text "lits",
101              int (sizeSS ptrs), text "ptrs",
102              int (sizeSS itbls), text "itbls"]
103
104 -- -----------------------------------------------------------------------------
105 -- The bytecode assembler
106
107 -- The object format for bytecodes is: 16 bits for the opcode, and 16
108 -- for each field -- so the code can be considered a sequence of
109 -- 16-bit ints.  Each field denotes either a stack offset or number of
110 -- items on the stack (eg SLIDE), and index into the pointer table (eg
111 -- PUSH_G), an index into the literal table (eg PUSH_I/D/L), or a
112 -- bytecode address in this BCO.
113
114 -- Top level assembler fn.
115 assembleBCOs :: [ProtoBCO Name] -> [TyCon] -> IO CompiledByteCode
116 assembleBCOs proto_bcos tycons
117   = do  itblenv <- mkITbls tycons
118         bcos    <- mapM assembleBCO proto_bcos
119         return (ByteCode bcos itblenv)
120
121 assembleBCO :: ProtoBCO Name -> IO UnlinkedBCO
122 assembleBCO (ProtoBCO nm instrs bitmap bsize arity origin malloced)
123    = let
124          -- pass 1: collect up the offsets of the local labels.
125          -- Remember that the first insn starts at offset 1 since offset 0
126          -- (eventually) will hold the total # of insns.
127          label_env = mkLabelEnv emptyFM 1 instrs
128
129          mkLabelEnv env i_offset [] = env
130          mkLabelEnv env i_offset (i:is)
131             = let new_env 
132                      = case i of LABEL n -> addToFM env n i_offset ; _ -> env
133               in  mkLabelEnv new_env (i_offset + instrSize16s i) is
134
135          findLabel lab
136             = case lookupFM label_env lab of
137                  Just bco_offset -> bco_offset
138                  Nothing -> pprPanic "assembleBCO.findLabel" (int lab)
139      in
140      do  -- pass 2: generate the instruction, ptr and nonptr bits
141          insns <- return emptySS :: IO (SizedSeq Word16)
142          lits  <- return emptySS :: IO (SizedSeq (Either Word FastString))
143          ptrs  <- return emptySS :: IO (SizedSeq BCOPtr)
144          itbls <- return emptySS :: IO (SizedSeq Name)
145          let init_asm_state = (insns,lits,ptrs,itbls)
146          (final_insns, final_lits, final_ptrs, final_itbls) 
147             <- mkBits findLabel init_asm_state instrs
148
149          let asm_insns = ssElts final_insns
150              n_insns   = sizeSS final_insns
151
152              insns_arr
153                  | n_insns > 65535 = panic "linkBCO: >= 64k insns in BCO"
154                  | otherwise = mkInstrArray n_insns asm_insns
155              insns_barr = case insns_arr of UArray _lo _hi barr -> barr
156
157              bitmap_arr = mkBitmapArray bsize bitmap
158              bitmap_barr = case bitmap_arr of UArray _lo _hi barr -> barr
159
160          let ul_bco = UnlinkedBCO nm arity insns_barr bitmap_barr final_lits 
161                                         final_ptrs final_itbls
162
163          -- 8 Aug 01: Finalisers aren't safe when attached to non-primitive
164          -- objects, since they might get run too early.  Disable this until
165          -- we figure out what to do.
166          -- when (notNull malloced) (addFinalizer ul_bco (mapM_ zonk malloced))
167
168          return ul_bco
169      where
170          zonk ptr = do -- putStrLn ("freeing malloc'd block at " ++ show (A# a#))
171                            free ptr
172
173 mkBitmapArray :: Int -> [StgWord] -> UArray Int StgWord
174 mkBitmapArray bsize bitmap
175   = listArray (0, length bitmap) (fromIntegral bsize : bitmap)
176
177 mkInstrArray :: Int -> [Word16] -> UArray Int Word16
178 mkInstrArray n_insns asm_insns
179   = listArray (0, n_insns) (fromIntegral n_insns : asm_insns)
180
181 -- instrs nonptrs ptrs itbls
182 type AsmState = (SizedSeq Word16, 
183                  SizedSeq (Either Word FastString),
184                  SizedSeq BCOPtr, 
185                  SizedSeq Name)
186
187 data SizedSeq a = SizedSeq !Int [a]
188 emptySS = SizedSeq 0 []
189
190 -- Why are these two monadic???
191 addToSS (SizedSeq n r_xs) x = return (SizedSeq (n+1) (x:r_xs))
192 addListToSS (SizedSeq n r_xs) xs 
193    = return (SizedSeq (n + length xs) (reverse xs ++ r_xs))
194
195 ssElts :: SizedSeq a -> [a]
196 ssElts (SizedSeq n r_xs) = reverse r_xs
197
198 sizeSS :: SizedSeq a -> Int
199 sizeSS (SizedSeq n r_xs) = n
200
201 -- Bring in all the bci_ bytecode constants.
202 #include "Bytecodes.h"
203
204 -- This is where all the action is (pass 2 of the assembler)
205 mkBits :: (Int -> Int)                  -- label finder
206        -> AsmState
207        -> [BCInstr]                     -- instructions (in)
208        -> IO AsmState
209
210 mkBits findLabel st proto_insns
211   = foldM doInstr st proto_insns
212     where
213        doInstr :: AsmState -> BCInstr -> IO AsmState
214        doInstr st i
215           = case i of
216                STKCHECK  n        -> instr2 st bci_STKCHECK n
217                PUSH_L    o1       -> instr2 st bci_PUSH_L o1
218                PUSH_LL   o1 o2    -> instr3 st bci_PUSH_LL o1 o2
219                PUSH_LLL  o1 o2 o3 -> instr4 st bci_PUSH_LLL o1 o2 o3
220                PUSH_G    nm       -> do (p, st2) <- ptr st (BCOPtrName nm)
221                                         instr2 st2 bci_PUSH_G p
222                PUSH_PRIMOP op     -> do (p, st2) <- ptr st (BCOPtrPrimOp op)
223                                         instr2 st2 bci_PUSH_G p
224                PUSH_BCO proto     -> do ul_bco <- assembleBCO proto
225                                         (p, st2) <- ptr st (BCOPtrBCO ul_bco)
226                                         instr2 st2 bci_PUSH_G p
227                PUSH_ALTS proto    -> do ul_bco <- assembleBCO proto
228                                         (p, st2) <- ptr st (BCOPtrBCO ul_bco)
229                                         instr2 st2 bci_PUSH_ALTS p
230                PUSH_ALTS_UNLIFTED proto pk -> do 
231                                         ul_bco <- assembleBCO proto
232                                         (p, st2) <- ptr st (BCOPtrBCO ul_bco)
233                                         instr2 st2 (push_alts pk) p
234                PUSH_UBX  (Left lit) nws  
235                                   -> do (np, st2) <- literal st lit
236                                         instr3 st2 bci_PUSH_UBX np nws
237                PUSH_UBX  (Right aa) nws  
238                                   -> do (np, st2) <- addr st aa
239                                         instr3 st2 bci_PUSH_UBX np nws
240
241                PUSH_APPLY_N         -> do instr1 st bci_PUSH_APPLY_N
242                PUSH_APPLY_V         -> do instr1 st bci_PUSH_APPLY_V
243                PUSH_APPLY_F         -> do instr1 st bci_PUSH_APPLY_F
244                PUSH_APPLY_D         -> do instr1 st bci_PUSH_APPLY_D
245                PUSH_APPLY_L         -> do instr1 st bci_PUSH_APPLY_L
246                PUSH_APPLY_P         -> do instr1 st bci_PUSH_APPLY_P
247                PUSH_APPLY_PP        -> do instr1 st bci_PUSH_APPLY_PP
248                PUSH_APPLY_PPP       -> do instr1 st bci_PUSH_APPLY_PPP
249                PUSH_APPLY_PPPP      -> do instr1 st bci_PUSH_APPLY_PPPP
250                PUSH_APPLY_PPPPP     -> do instr1 st bci_PUSH_APPLY_PPPPP
251                PUSH_APPLY_PPPPPP    -> do instr1 st bci_PUSH_APPLY_PPPPPP
252
253                SLIDE     n by     -> instr3 st bci_SLIDE n by
254                ALLOC_AP  n        -> instr2 st bci_ALLOC_AP n
255                ALLOC_PAP arity n  -> instr3 st bci_ALLOC_PAP arity n
256                MKAP      off sz   -> instr3 st bci_MKAP off sz
257                UNPACK    n        -> instr2 st bci_UNPACK n
258                PACK      dcon sz  -> do (itbl_no,st2) <- itbl st dcon
259                                         instr3 st2 bci_PACK itbl_no sz
260                LABEL     lab      -> return st
261                TESTLT_I  i l      -> do (np, st2) <- int st i
262                                         instr3 st2 bci_TESTLT_I np (findLabel l)
263                TESTEQ_I  i l      -> do (np, st2) <- int st i
264                                         instr3 st2 bci_TESTEQ_I np (findLabel l)
265                TESTLT_F  f l      -> do (np, st2) <- float st f
266                                         instr3 st2 bci_TESTLT_F np (findLabel l)
267                TESTEQ_F  f l      -> do (np, st2) <- float st f
268                                         instr3 st2 bci_TESTEQ_F np (findLabel l)
269                TESTLT_D  d l      -> do (np, st2) <- double st d
270                                         instr3 st2 bci_TESTLT_D np (findLabel l)
271                TESTEQ_D  d l      -> do (np, st2) <- double st d
272                                         instr3 st2 bci_TESTEQ_D np (findLabel l)
273                TESTLT_P  i l      -> instr3 st bci_TESTLT_P i (findLabel l)
274                TESTEQ_P  i l      -> instr3 st bci_TESTEQ_P i (findLabel l)
275                CASEFAIL           -> instr1 st bci_CASEFAIL
276                SWIZZLE   stkoff n -> instr3 st bci_SWIZZLE stkoff n
277                JMP       l        -> instr2 st bci_JMP (findLabel l)
278                ENTER              -> instr1 st bci_ENTER
279                RETURN             -> instr1 st bci_RETURN
280                RETURN_UBX rep     -> instr1 st (return_ubx rep)
281                CCALL off m_addr   -> do (np, st2) <- addr st m_addr
282                                         instr3 st2 bci_CCALL off np
283
284        i2s :: Int -> Word16
285        i2s = fromIntegral
286
287        instr1 (st_i0,st_l0,st_p0,st_I0) i1
288           = do st_i1 <- addToSS st_i0 i1
289                return (st_i1,st_l0,st_p0,st_I0)
290
291        instr2 (st_i0,st_l0,st_p0,st_I0) i1 i2
292           = do st_i1 <- addToSS st_i0 (i2s i1)
293                st_i2 <- addToSS st_i1 (i2s i2)
294                return (st_i2,st_l0,st_p0,st_I0)
295
296        instr3 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3
297           = do st_i1 <- addToSS st_i0 (i2s i1)
298                st_i2 <- addToSS st_i1 (i2s i2)
299                st_i3 <- addToSS st_i2 (i2s i3)
300                return (st_i3,st_l0,st_p0,st_I0)
301
302        instr4 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3 i4
303           = do st_i1 <- addToSS st_i0 (i2s i1)
304                st_i2 <- addToSS st_i1 (i2s i2)
305                st_i3 <- addToSS st_i2 (i2s i3)
306                st_i4 <- addToSS st_i3 (i2s i4)
307                return (st_i4,st_l0,st_p0,st_I0)
308
309        float (st_i0,st_l0,st_p0,st_I0) f
310           = do let ws = mkLitF f
311                st_l1 <- addListToSS st_l0 (map Left ws)
312                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
313
314        double (st_i0,st_l0,st_p0,st_I0) d
315           = do let ws = mkLitD d
316                st_l1 <- addListToSS st_l0 (map Left ws)
317                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
318
319        int (st_i0,st_l0,st_p0,st_I0) i
320           = do let ws = mkLitI i
321                st_l1 <- addListToSS st_l0 (map Left ws)
322                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
323
324        int64 (st_i0,st_l0,st_p0,st_I0) i
325           = do let ws = mkLitI64 i
326                st_l1 <- addListToSS st_l0 (map Left ws)
327                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
328
329        addr (st_i0,st_l0,st_p0,st_I0) a
330           = do let ws = mkLitPtr a
331                st_l1 <- addListToSS st_l0 (map Left ws)
332                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
333
334        litlabel (st_i0,st_l0,st_p0,st_I0) fs
335           = do st_l1 <- addListToSS st_l0 [Right fs]
336                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
337
338        ptr (st_i0,st_l0,st_p0,st_I0) p
339           = do st_p1 <- addToSS st_p0 p
340                return (sizeSS st_p0, (st_i0,st_l0,st_p1,st_I0))
341
342        itbl (st_i0,st_l0,st_p0,st_I0) dcon
343           = do st_I1 <- addToSS st_I0 (getName dcon)
344                return (sizeSS st_I0, (st_i0,st_l0,st_p0,st_I1))
345
346        literal st (MachLabel fs _) = litlabel st fs
347        literal st (MachWord w)     = int st (fromIntegral w)
348        literal st (MachInt j)      = int st (fromIntegral j)
349        literal st (MachFloat r)    = float st (fromRational r)
350        literal st (MachDouble r)   = double st (fromRational r)
351        literal st (MachChar c)     = int st (ord c)
352        literal st (MachInt64 ii)   = int64 st (fromIntegral ii)
353        literal st (MachWord64 ii)  = int64 st (fromIntegral ii)
354        literal st other            = pprPanic "ByteCodeLink.literal" (ppr other)
355
356
357 push_alts NonPtrArg = bci_PUSH_ALTS_N
358 push_alts FloatArg  = bci_PUSH_ALTS_F
359 push_alts DoubleArg = bci_PUSH_ALTS_D
360 push_alts VoidArg   = bci_PUSH_ALTS_V
361 push_alts LongArg   = bci_PUSH_ALTS_L
362 push_alts PtrArg    = bci_PUSH_ALTS_P
363
364 return_ubx NonPtrArg = bci_RETURN_N
365 return_ubx FloatArg  = bci_RETURN_F
366 return_ubx DoubleArg = bci_RETURN_D
367 return_ubx VoidArg   = bci_RETURN_V
368 return_ubx LongArg   = bci_RETURN_L
369 return_ubx PtrArg    = bci_RETURN_P
370
371
372 -- The size in 16-bit entities of an instruction.
373 instrSize16s :: BCInstr -> Int
374 instrSize16s instr
375    = case instr of
376         STKCHECK{}              -> 2
377         PUSH_L{}                -> 2
378         PUSH_LL{}               -> 3
379         PUSH_LLL{}              -> 4
380         PUSH_G{}                -> 2
381         PUSH_PRIMOP{}           -> 2
382         PUSH_BCO{}              -> 2
383         PUSH_ALTS{}             -> 2
384         PUSH_ALTS_UNLIFTED{}    -> 2
385         PUSH_UBX{}              -> 3
386         PUSH_APPLY_N{}          -> 1
387         PUSH_APPLY_V{}          -> 1
388         PUSH_APPLY_F{}          -> 1
389         PUSH_APPLY_D{}          -> 1
390         PUSH_APPLY_L{}          -> 1
391         PUSH_APPLY_P{}          -> 1
392         PUSH_APPLY_PP{}         -> 1
393         PUSH_APPLY_PPP{}        -> 1
394         PUSH_APPLY_PPPP{}       -> 1
395         PUSH_APPLY_PPPPP{}      -> 1
396         PUSH_APPLY_PPPPPP{}     -> 1
397         SLIDE{}                 -> 3
398         ALLOC_AP{}              -> 2
399         ALLOC_PAP{}             -> 3
400         MKAP{}                  -> 3
401         UNPACK{}                -> 2
402         PACK{}                  -> 3
403         LABEL{}                 -> 0    -- !!
404         TESTLT_I{}              -> 3
405         TESTEQ_I{}              -> 3
406         TESTLT_F{}              -> 3
407         TESTEQ_F{}              -> 3
408         TESTLT_D{}              -> 3
409         TESTEQ_D{}              -> 3
410         TESTLT_P{}              -> 3
411         TESTEQ_P{}              -> 3
412         JMP{}                   -> 2
413         CASEFAIL{}              -> 1
414         ENTER{}                 -> 1
415         RETURN{}                -> 1
416         RETURN_UBX{}            -> 1
417         CCALL{}                 -> 3
418         SWIZZLE{}               -> 3
419
420 -- Make lists of host-sized words for literals, so that when the
421 -- words are placed in memory at increasing addresses, the
422 -- bit pattern is correct for the host's word size and endianness.
423 mkLitI   :: Int    -> [Word]
424 mkLitF   :: Float  -> [Word]
425 mkLitD   :: Double -> [Word]
426 mkLitPtr :: Ptr () -> [Word]
427 mkLitI64 :: Int64  -> [Word]
428
429 mkLitF f
430    = runST (do
431         arr <- newArray_ ((0::Int),0)
432         writeArray arr 0 f
433         f_arr <- castSTUArray arr
434         w0 <- readArray f_arr 0
435         return [w0 :: Word]
436      )
437
438 mkLitD d
439    | wORD_SIZE == 4
440    = runST (do
441         arr <- newArray_ ((0::Int),1)
442         writeArray arr 0 d
443         d_arr <- castSTUArray arr
444         w0 <- readArray d_arr 0
445         w1 <- readArray d_arr 1
446         return [w0 :: Word, w1]
447      )
448    | wORD_SIZE == 8
449    = runST (do
450         arr <- newArray_ ((0::Int),0)
451         writeArray arr 0 d
452         d_arr <- castSTUArray arr
453         w0 <- readArray d_arr 0
454         return [w0 :: Word]
455      )
456
457 mkLitI64 ii
458    | wORD_SIZE == 4
459    = runST (do
460         arr <- newArray_ ((0::Int),1)
461         writeArray arr 0 ii
462         d_arr <- castSTUArray arr
463         w0 <- readArray d_arr 0
464         w1 <- readArray d_arr 1
465         return [w0 :: Word,w1]
466      )
467    | wORD_SIZE == 8
468    = runST (do
469         arr <- newArray_ ((0::Int),0)
470         writeArray arr 0 ii
471         d_arr <- castSTUArray arr
472         w0 <- readArray d_arr 0
473         return [w0 :: Word]
474      )
475
476 mkLitI i
477    = runST (do
478         arr <- newArray_ ((0::Int),0)
479         writeArray arr 0 i
480         i_arr <- castSTUArray arr
481         w0 <- readArray i_arr 0
482         return [w0 :: Word]
483      )
484
485 mkLitPtr a
486    = runST (do
487         arr <- newArray_ ((0::Int),0)
488         writeArray arr 0 a
489         a_arr <- castSTUArray arr
490         w0 <- readArray a_arr 0
491         return [w0 :: Word]
492      )
493
494 iNTERP_STACK_CHECK_THRESH = (INTERP_STACK_CHECK_THRESH :: Int)
495 \end{code}