2973c03e47f033dfaab7dcf8b20e999cb0658d0b
[ghc-hetmet.git] / compiler / ghci / ByteCodeItbls.lhs
1 %
2 % (c) The University of Glasgow 2000-2006
3 %
4 ByteCodeItbls: Generate infotables for interpreter-made bytecodes
5
6 \begin{code}
7 {-# OPTIONS -optc-DNON_POSIX_SOURCE #-}
8
9 module ByteCodeItbls ( ItblEnv, ItblPtr(..), itblCode, mkITbls
10                      , StgInfoTable(..)
11                      ) where
12
13 #include "HsVersions.h"
14
15 import ByteCodeFFI      ( newExec )
16 import Name             ( Name, getName )
17 import NameEnv
18 import SMRep            ( typeCgRep )
19 import DataCon          ( DataCon, dataConRepArgTys, dataConIdentity )
20 import TyCon            ( TyCon, tyConFamilySize, isDataTyCon, tyConDataCons )
21 import Constants        ( mIN_PAYLOAD_SIZE, wORD_SIZE )
22 import CgHeapery        ( mkVirtHeapOffsets )
23 import FastString       ( FastString(..) )
24 import Util             ( lengthIs, listLengthCmp )
25
26 import Foreign
27 import Foreign.C
28 import Foreign.C.String
29 import Data.Bits        ( Bits(..), shiftR )
30
31 import GHC.Exts         ( Int(I#), addr2Int# )
32 import GHC.Ptr          ( Ptr(..) )
33 import GHC.Prim
34
35 import Outputable
36 \end{code}
37
38 %************************************************************************
39 %*                                                                      *
40 \subsection{Manufacturing of info tables for DataCons}
41 %*                                                                      *
42 %************************************************************************
43
44 \begin{code}
45 newtype ItblPtr = ItblPtr (Ptr ()) deriving Show
46
47 itblCode :: ItblPtr -> Ptr ()
48 itblCode (ItblPtr ptr)
49    = (castPtr ptr)
50 #ifdef GHCI_TABLES_NEXT_TO_CODE
51                  `plusPtr` (3 * wORD_SIZE)
52 #endif
53
54 type ItblEnv = NameEnv (Name, ItblPtr)
55         -- We need the Name in the range so we know which
56         -- elements to filter out when unloading a module
57
58 mkItblEnv :: [(Name,ItblPtr)] -> ItblEnv
59 mkItblEnv pairs = mkNameEnv [(n, (n,p)) | (n,p) <- pairs]
60
61
62 -- Make info tables for the data decls in this module
63 mkITbls :: [TyCon] -> IO ItblEnv
64 mkITbls [] = return emptyNameEnv
65 mkITbls (tc:tcs) = do itbls  <- mkITbl tc
66                       itbls2 <- mkITbls tcs
67                       return (itbls `plusNameEnv` itbls2)
68
69 mkITbl :: TyCon -> IO ItblEnv
70 mkITbl tc
71    | not (isDataTyCon tc) 
72    = return emptyNameEnv
73    | dcs `lengthIs` n -- paranoia; this is an assertion.
74    = make_constr_itbls dcs
75      where
76         dcs = tyConDataCons tc
77         n   = tyConFamilySize tc
78
79 #include "../includes/ClosureTypes.h"
80 cONSTR :: Int   -- Defined in ClosureTypes.h
81 cONSTR = CONSTR 
82
83 -- Assumes constructors are numbered from zero, not one
84 make_constr_itbls :: [DataCon] -> IO ItblEnv
85 make_constr_itbls cons
86    = do is <- mapM mk_dirret_itbl (zip cons [0..])
87         return (mkItblEnv is)
88      where
89         mk_dirret_itbl (dcon, conNo)
90            = mk_itbl dcon conNo stg_interp_constr_entry
91
92         mk_itbl :: DataCon -> Int -> Ptr () -> IO (Name,ItblPtr)
93         mk_itbl dcon conNo entry_addr = do
94            let rep_args = [ (typeCgRep arg,arg) | arg <- dataConRepArgTys dcon ]
95                (tot_wds, ptr_wds, _) = mkVirtHeapOffsets False{-not a THUNK-} rep_args
96
97                ptrs  = ptr_wds
98                nptrs = tot_wds - ptr_wds
99                nptrs_really
100                   | ptrs + nptrs >= mIN_PAYLOAD_SIZE = nptrs
101                   | otherwise = mIN_PAYLOAD_SIZE - ptrs
102                code = mkJumpToAddr entry_addr
103                itbl  = StgInfoTable {
104 #ifndef GHCI_TABLES_NEXT_TO_CODE
105                            entry = entry_addr,
106 #endif
107                            ptrs  = fromIntegral ptrs, 
108                            nptrs = fromIntegral nptrs_really,
109                            tipe  = fromIntegral cONSTR,
110                            srtlen = fromIntegral conNo
111 #ifdef GHCI_TABLES_NEXT_TO_CODE
112                          , code  = code
113 #endif
114                         }
115            qNameCString <- newCString $ dataConIdentity dcon 
116            let conInfoTbl = StgConInfoTable {
117                                  conDesc = qNameCString,
118                                  infoTable = itbl
119                             }
120                -- Make a piece of code to jump to "entry_label".
121                -- This is the only arch-dependent bit.
122            addrCon <- newExec [conInfoTbl]
123                     --putStrLn ("SIZE of itbl is " ++ show (sizeOf itbl))
124                     --putStrLn ("# ptrs  of itbl is " ++ show ptrs)
125                     --putStrLn ("# nptrs of itbl is " ++ show nptrs_really)
126            return (getName dcon, ItblPtr (castFunPtrToPtr addrCon))
127
128
129 -- Make code which causes a jump to the given address.  This is the
130 -- only arch-dependent bit of the itbl story.  The returned list is
131 -- itblCodeLength elements (bytes) long.
132
133 -- For sparc_TARGET_ARCH, i386_TARGET_ARCH, etc.
134 #include "nativeGen/NCG.h"
135
136 itblCodeLength :: Int
137 itblCodeLength = length (mkJumpToAddr undefined)
138
139 mkJumpToAddr :: Ptr () -> [ItblCode]
140
141 ptrToInt (Ptr a#) = I# (addr2Int# a#)
142
143 #if sparc_TARGET_ARCH
144 -- After some consideration, we'll try this, where
145 -- 0x55555555 stands in for the address to jump to.
146 -- According to ghc/includes/MachRegs.h, %g3 is very
147 -- likely indeed to be baggable.
148 --
149 --   0000 07155555              sethi   %hi(0x55555555), %g3
150 --   0004 8610E155              or      %g3, %lo(0x55555555), %g3
151 --   0008 81C0C000              jmp     %g3
152 --   000c 01000000              nop
153
154 type ItblCode = Word32
155 mkJumpToAddr a
156    = let w32 = fromIntegral (ptrToInt a)
157
158          hi22, lo10 :: Word32 -> Word32
159          lo10 x = x .&. 0x3FF
160          hi22 x = (x `shiftR` 10) .&. 0x3FFFF
161
162      in  [ 0x07000000 .|. (hi22 w32),
163            0x8610E000 .|. (lo10 w32),
164            0x81C0C000,
165            0x01000000 ]
166
167 #elif powerpc_TARGET_ARCH
168 -- We'll use r12, for no particular reason.
169 -- 0xDEADBEEF stands for the adress:
170 -- 3D80DEAD lis r12,0xDEAD
171 -- 618CBEEF ori r12,r12,0xBEEF
172 -- 7D8903A6 mtctr r12
173 -- 4E800420 bctr
174
175 type ItblCode = Word32
176 mkJumpToAddr a =
177     let w32 = fromIntegral (ptrToInt a)
178         hi16 x = (x `shiftR` 16) .&. 0xFFFF
179         lo16 x = x .&. 0xFFFF
180     in  [
181         0x3D800000 .|. hi16 w32,
182         0x618C0000 .|. lo16 w32,
183         0x7D8903A6, 0x4E800420
184         ]
185
186 #elif i386_TARGET_ARCH
187 -- Let the address to jump to be 0xWWXXYYZZ.
188 -- Generate   movl $0xWWXXYYZZ,%eax  ;  jmp *%eax
189 -- which is
190 -- B8 ZZ YY XX WW FF E0
191
192 type ItblCode = Word8
193 mkJumpToAddr a
194    = let w32 = fromIntegral (ptrToInt a) :: Word32
195          insnBytes :: [Word8]
196          insnBytes
197             = [0xB8, byte0 w32, byte1 w32, 
198                      byte2 w32, byte3 w32, 
199                0xFF, 0xE0]
200      in
201          insnBytes
202
203 #elif x86_64_TARGET_ARCH
204 -- Generates:
205 --      jmpq *.L1(%rip)
206 --      .align 8
207 -- .L1: 
208 --      .quad <addr>
209 --
210 -- We need a full 64-bit pointer (we can't assume the info table is
211 -- allocated in low memory).  Assuming the info pointer is aligned to
212 -- an 8-byte boundary, the addr will also be aligned.
213
214 type ItblCode = Word8
215 mkJumpToAddr a
216    = let w64 = fromIntegral (ptrToInt a) :: Word64
217          insnBytes :: [Word8]
218          insnBytes
219             = [0xff, 0x25, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
220                byte0 w64, byte1 w64, byte2 w64, byte3 w64,
221                byte4 w64, byte5 w64, byte6 w64, byte7 w64]
222      in
223          insnBytes
224
225 #elif alpha_TARGET_ARCH
226 type ItblCode = Word32
227 mkJumpToAddr a
228     = [ 0xc3800000      -- br   at, .+4
229       , 0xa79c000c      -- ldq  at, 12(at)
230       , 0x6bfc0000      -- jmp  (at)    # with zero hint -- oh well
231       , 0x47ff041f      -- nop
232       , fromIntegral (w64 .&. 0x0000FFFF)
233       , fromIntegral ((w64 `shiftR` 32) .&. 0x0000FFFF) ]
234     where w64 = fromIntegral (ptrToInt a) :: Word64
235
236 #else
237 type ItblCode = Word32
238 mkJumpToAddr a
239     = undefined
240 #endif
241
242
243 byte0, byte1, byte2, byte3, byte4, byte5, byte6, byte7
244    :: (Integral w, Bits w) => w -> Word8
245 byte0 w = fromIntegral w
246 byte1 w = fromIntegral (w `shiftR` 8)
247 byte2 w = fromIntegral (w `shiftR` 16)
248 byte3 w = fromIntegral (w `shiftR` 24)
249 byte4 w = fromIntegral (w `shiftR` 32)
250 byte5 w = fromIntegral (w `shiftR` 40)
251 byte6 w = fromIntegral (w `shiftR` 48)
252 byte7 w = fromIntegral (w `shiftR` 56)
253
254
255 #ifndef __HADDOCK__
256 -- entry point for direct returns for created constr itbls
257 foreign import ccall "&stg_interp_constr_entry" stg_interp_constr_entry :: Ptr ()
258 #endif
259
260
261
262
263 -- Ultra-minimalist version specially for constructors
264 #if SIZEOF_VOID_P == 8
265 type HalfWord = Word32
266 #else
267 type HalfWord = Word16
268 #endif
269
270 data StgConInfoTable = StgConInfoTable {
271    conDesc   :: CString,
272    infoTable :: StgInfoTable
273 }
274
275 instance Storable StgConInfoTable where
276    sizeOf conInfoTable    
277       = sum [ sizeOf (conDesc conInfoTable)
278             , sizeOf (infoTable conInfoTable) ]
279    alignment conInfoTable = SIZEOF_VOID_P
280    peek ptr 
281       = runState (castPtr ptr) $ do
282 #ifdef GHCI_TABLES_NEXT_TO_CODE
283            desc <- load
284 #endif
285            itbl <- load
286 #ifndef GHCI_TABLES_NEXT_TO_CODE
287            desc <- load
288 #endif
289            return  
290               StgConInfoTable 
291               { 
292 #ifdef GHCI_TABLES_NEXT_TO_CODE
293                 conDesc   = castPtr $ ptr `plusPtr` wORD_SIZE `plusPtr` desc
294 #else
295                 conDesc   = desc
296 #endif
297               , infoTable = itbl
298               }
299    poke ptr itbl 
300       = runState (castPtr ptr) $ do
301 #ifdef GHCI_TABLES_NEXT_TO_CODE
302            store (conDesc itbl `minusPtr` (ptr `plusPtr` wORD_SIZE))
303 #endif
304            store (infoTable itbl)
305 #ifndef GHCI_TABLES_NEXT_TO_CODE
306            store (conDesc itbl)
307 #endif
308
309 data StgInfoTable = StgInfoTable {
310 #ifndef GHCI_TABLES_NEXT_TO_CODE
311    entry  :: Ptr (),
312 #endif
313    ptrs   :: HalfWord,
314    nptrs  :: HalfWord,
315    tipe   :: HalfWord,
316    srtlen :: HalfWord
317 #ifdef GHCI_TABLES_NEXT_TO_CODE
318  , code   :: [ItblCode]
319 #endif
320   }
321
322 instance Storable StgInfoTable where
323
324    sizeOf itbl 
325       = sum
326         [
327 #ifndef GHCI_TABLES_NEXT_TO_CODE
328          fieldSz entry itbl,
329 #endif
330          fieldSz ptrs itbl,
331          fieldSz nptrs itbl,
332          fieldSz tipe itbl,
333          fieldSz srtlen itbl
334 #ifdef GHCI_TABLES_NEXT_TO_CODE
335         ,fieldSz (head.code) itbl * itblCodeLength
336 #endif
337         ]
338
339    alignment itbl 
340       = SIZEOF_VOID_P
341
342    poke a0 itbl
343       = runState (castPtr a0)
344       $ do
345 #ifndef GHCI_TABLES_NEXT_TO_CODE
346            store (entry  itbl)
347 #endif
348            store (ptrs   itbl)
349            store (nptrs  itbl)
350            store (tipe   itbl)
351            store (srtlen itbl)
352 #ifdef GHCI_TABLES_NEXT_TO_CODE
353            sequence_ (map store (code itbl))
354 #endif
355
356    peek a0
357       = runState (castPtr a0)
358       $ do
359 #ifndef GHCI_TABLES_NEXT_TO_CODE
360            entry  <- load
361 #endif
362            ptrs   <- load
363            nptrs  <- load
364            tipe   <- load
365            srtlen <- load
366 #ifdef GHCI_TABLES_NEXT_TO_CODE
367            code   <- sequence (replicate itblCodeLength load)
368 #endif
369            return 
370               StgInfoTable { 
371 #ifndef GHCI_TABLES_NEXT_TO_CODE
372                  entry  = entry,
373 #endif
374                  ptrs   = ptrs,
375                  nptrs  = nptrs, 
376                  tipe   = tipe,
377                  srtlen = srtlen
378 #ifdef GHCI_TABLES_NEXT_TO_CODE
379                 ,code   = code
380 #endif
381               }
382
383 fieldSz :: (Storable a, Storable b) => (a -> b) -> a -> Int
384 fieldSz sel x = sizeOf (sel x)
385
386 newtype State s m a = State (s -> m (s, a))
387
388 instance Monad m => Monad (State s m) where
389   return a      = State (\s -> return (s, a))
390   State m >>= k = State (\s -> m s >>= \(s', a) -> case k a of State n -> n s')
391   fail str      = State (\s -> fail str)
392
393 class (Monad m, Monad (t m)) => MonadT t m where
394   lift :: m a -> t m a
395
396 instance Monad m => MonadT (State s) m where
397   lift m        = State (\s -> m >>= \a -> return (s, a))
398
399 runState :: (Monad m) => s -> State s m a -> m a
400 runState s (State m) = m s >>= return . snd
401
402 type PtrIO = State (Ptr Word8) IO
403
404 advance :: Storable a => PtrIO (Ptr a)
405 advance = State adv where
406     adv addr = case castPtr addr of { addrCast -> return
407         (addr `plusPtr` sizeOfPointee addrCast, addrCast) }
408
409 sizeOfPointee :: (Storable a) => Ptr a -> Int
410 sizeOfPointee addr = sizeOf (typeHack addr)
411     where typeHack = undefined :: Ptr a -> a
412
413 store :: Storable a => a -> PtrIO ()
414 store x = do addr <- advance
415              lift (poke addr x)
416
417 load :: Storable a => PtrIO a
418 load = do addr <- advance
419           lift (peek addr)
420
421 \end{code}