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