[project @ 2002-04-05 23:24:25 by sof]
[ghc-hetmet.git] / ghc / compiler / ghci / ByteCodeLink.lhs
1 %
2 % (c) The University of Glasgow 2000
3 %
4 \section[ByteCodeLink]{Bytecode assembler and linker}
5
6 \begin{code}
7
8 {-# OPTIONS -optc-DNON_POSIX_SOURCE #-}
9
10 module ByteCodeLink ( UnlinkedBCO, UnlinkedBCOExpr, assembleBCO,
11                       ClosureEnv, HValue, filterNameMap,
12                       linkIModules, linkIExpr, linkFail,
13                       iNTERP_STACK_CHECK_THRESH
14                    ) where
15
16 #include "HsVersions.h"
17
18 import Outputable
19 import Name             ( Name, getName, nameModule, toRdrName, isExternalName )
20 import RdrName          ( rdrNameOcc, rdrNameModule )
21 import OccName          ( occNameString )
22 import FiniteMap        ( FiniteMap, addListToFM, filterFM,
23                           addToFM, lookupFM, emptyFM )
24 import CoreSyn
25 import Literal          ( Literal(..) )
26 import PrimOp           ( PrimOp, primOpOcc )
27 import PrimRep          ( PrimRep(..) )
28 import Constants        ( wORD_SIZE )
29 import Module           ( ModuleName, moduleName, moduleNameFS )
30 import Linker           ( lookupSymbol )
31 import FastString       ( FastString(..) )
32 import ByteCodeInstr    ( BCInstr(..), ProtoBCO(..) )
33 import ByteCodeItbls    ( ItblEnv, ItblPtr )
34 import FiniteMap
35 import Panic            ( GhcException(..) )
36 import Util             ( notNull )
37
38 import Control.Monad    ( when, foldM )
39 import Control.Monad.ST ( runST )
40 import Data.Array.IArray ( array )
41
42 import GHC.Word         ( Word(..) )
43 import Data.Array.MArray ( MArray, newArray_, readArray, writeArray )
44 import Data.Array.ST    ( castSTUArray )
45 import Data.Array.Base  ( UArray(..) )
46 import Foreign.Ptr      ( Ptr, nullPtr )
47 import Foreign          ( Word16, Ptr(..), free )
48 import System.Mem.Weak  ( addFinalizer )
49 import Data.Int         ( Int64 )
50
51 import System.IO        ( fixIO )
52 import Control.Exception ( throwDyn )
53
54 import GlaExts          ( BCO#, newBCO#, unsafeCoerce#, 
55                           ByteArray#, Array#, addrToHValue#, mkApUpd0# )
56
57 #if __GLASGOW_HASKELL__ >= 503
58 import GHC.Arr          ( Array(..) )
59 import GHC.IOBase       ( IO(..) )
60 #else
61 import PrelArr          ( Array(..) )
62 import PrelIOBase       ( IO(..) )
63 #endif
64 \end{code}
65
66 %************************************************************************
67 %*                                                                      *
68 \subsection{Top-level stuff}
69 %*                                                                      *
70 %************************************************************************
71
72 \begin{code}
73 -- Linking stuff
74 linkIModules :: ItblEnv    -- incoming global itbl env; returned updated
75              -> ClosureEnv -- incoming global closure env; returned updated
76              -> [([UnlinkedBCO], ItblEnv)]
77              -> IO ([HValue], ItblEnv, ClosureEnv)
78 linkIModules gie gce mods 
79    = do let (bcoss, ies) = unzip mods
80             bcos         = concat bcoss
81             final_gie    = foldr plusFM gie ies
82         (final_gce, linked_bcos) <- linkSomeBCOs True final_gie gce bcos
83         return (linked_bcos, final_gie, final_gce)
84
85
86 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
87           -> IO HValue    -- IO BCO# really
88 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
89    = do (aux_ce, _) <- linkSomeBCOs False ie ce aux_ul_bcos
90         (_, [root_bco]) <- linkSomeBCOs False ie aux_ce [root_ul_bco]
91         return root_bco
92
93 -- Link a bunch of BCOs and return them + updated closure env.
94 linkSomeBCOs :: Bool    -- False <=> add _all_ BCOs to returned closure env
95                         -- True  <=> add only toplevel BCOs to closure env
96              -> ItblEnv 
97              -> ClosureEnv 
98              -> [UnlinkedBCO]
99              -> IO (ClosureEnv, [HValue])
100 linkSomeBCOs toplevs_only ie ce_in ul_bcos
101    = do let nms = map nameOfUnlinkedBCO ul_bcos
102         hvals <- fixIO 
103                     ( \ hvs -> let ce_out = addListToFM ce_in (zipLazily nms hvs)
104                                in  mapM (linkBCO ie ce_out) ul_bcos )
105
106         let ce_all_additions = zip nms hvals
107             ce_top_additions = filter (isExternalName.fst) ce_all_additions
108             ce_additions     = if toplevs_only then ce_top_additions 
109                                                else ce_all_additions
110             ce_out = -- make sure we're not inserting duplicate names into the 
111                      -- closure environment, which leads to trouble.
112                      ASSERT (all (not . (`elemFM` ce_in)) (map fst ce_additions))
113                      addListToFM ce_in ce_additions
114         return (ce_out, hvals)
115      where
116         -- A lazier zip, in which no demand is propagated to the second
117         -- list unless some demand is propagated to the snd of one of the
118         -- result list elems.
119         zipLazily []     ys = []
120         zipLazily (x:xs) ys = (x, head ys) : zipLazily xs (tail ys)
121
122
123 data UnlinkedBCO
124    = UnlinkedBCO Name
125                  (SizedSeq Word16)               -- insns
126                  (SizedSeq (Either Word FAST_STRING))    -- literals
127                         -- Either literal words or a pointer to a asciiz
128                         -- string, denoting a label whose *address* should
129                         -- be determined at link time
130                  (SizedSeq (Either Name PrimOp)) -- ptrs
131                  (SizedSeq Name)                 -- itbl refs
132
133 nameOfUnlinkedBCO (UnlinkedBCO nm _ _ _ _) = nm
134
135 -- When translating expressions, we need to distinguish the root
136 -- BCO for the expression
137 type UnlinkedBCOExpr = (UnlinkedBCO, [UnlinkedBCO])
138
139 instance Outputable UnlinkedBCO where
140    ppr (UnlinkedBCO nm insns lits ptrs itbls)
141       = sep [text "BCO", ppr nm, text "with", 
142              int (sizeSS insns), text "insns",
143              int (sizeSS lits), text "lits",
144              int (sizeSS ptrs), text "ptrs",
145              int (sizeSS itbls), text "itbls"]
146
147
148 -- these need a proper home
149 type ClosureEnv = FiniteMap Name HValue
150 data HValue     = HValue  -- dummy type, actually a pointer to some Real Code.
151
152 -- remove all entries for a given set of modules from the environment;
153 -- note that this removes all local names too (ie. temporary bindings from
154 -- the command line).
155 filterNameMap :: [ModuleName] -> FiniteMap Name a -> FiniteMap Name a
156 filterNameMap mods env 
157    = filterFM (\n _ -> isExternalName n 
158                         && moduleName (nameModule n) `elem` mods) env
159 \end{code}
160
161 %************************************************************************
162 %*                                                                      *
163 \subsection{The bytecode assembler}
164 %*                                                                      *
165 %************************************************************************
166
167 The object format for bytecodes is: 16 bits for the opcode, and 16 for
168 each field -- so the code can be considered a sequence of 16-bit ints.
169 Each field denotes either a stack offset or number of items on the
170 stack (eg SLIDE), and index into the pointer table (eg PUSH_G), an
171 index into the literal table (eg PUSH_I/D/L), or a bytecode address in
172 this BCO.
173
174 \begin{code}
175 -- Top level assembler fn.
176 assembleBCO :: ProtoBCO Name -> IO UnlinkedBCO
177
178 assembleBCO (ProtoBCO nm instrs origin malloced)
179    = let
180          -- pass 1: collect up the offsets of the local labels.
181          -- Remember that the first insn starts at offset 1 since offset 0
182          -- (eventually) will hold the total # of insns.
183          label_env = mkLabelEnv emptyFM 1 instrs
184
185          mkLabelEnv env i_offset [] = env
186          mkLabelEnv env i_offset (i:is)
187             = let new_env 
188                      = case i of LABEL n -> addToFM env n i_offset ; _ -> env
189               in  mkLabelEnv new_env (i_offset + instrSize16s i) is
190
191          findLabel lab
192             = case lookupFM label_env lab of
193                  Just bco_offset -> bco_offset
194                  Nothing -> pprPanic "assembleBCO.findLabel" (int lab)
195      in
196      do  -- pass 2: generate the instruction, ptr and nonptr bits
197          insns <- return emptySS :: IO (SizedSeq Word16)
198          lits  <- return emptySS :: IO (SizedSeq (Either Word FAST_STRING))
199          ptrs  <- return emptySS :: IO (SizedSeq (Either Name PrimOp))
200          itbls <- return emptySS :: IO (SizedSeq Name)
201          let init_asm_state = (insns,lits,ptrs,itbls)
202          (final_insns, final_lits, final_ptrs, final_itbls) 
203             <- mkBits findLabel init_asm_state instrs
204
205          let ul_bco = UnlinkedBCO nm final_insns final_lits final_ptrs final_itbls
206
207          -- 8 Aug 01: Finalisers aren't safe when attached to non-primitive
208          -- objects, since they might get run too early.  Disable this until
209          -- we figure out what to do.
210          -- when (notNull malloced) (addFinalizer ul_bco (mapM_ zonk malloced))
211
212          return ul_bco
213      where
214          zonk ptr = do -- putStrLn ("freeing malloc'd block at " ++ show (A# a#))
215                            free ptr
216
217 -- instrs nonptrs ptrs itbls
218 type AsmState = (SizedSeq Word16, 
219                  SizedSeq (Either Word FAST_STRING),
220                  SizedSeq (Either Name PrimOp), 
221                  SizedSeq Name)
222
223 data SizedSeq a = SizedSeq !Int [a]
224 emptySS = SizedSeq 0 []
225 addToSS (SizedSeq n r_xs) x = return (SizedSeq (n+1) (x:r_xs))
226 addListToSS (SizedSeq n r_xs) xs 
227    = return (SizedSeq (n + length xs) (reverse xs ++ r_xs))
228 sizeSS (SizedSeq n r_xs) = n
229 listFromSS (SizedSeq n r_xs) = return (reverse r_xs)
230
231
232 -- This is where all the action is (pass 2 of the assembler)
233 mkBits :: (Int -> Int)                  -- label finder
234        -> AsmState
235        -> [BCInstr]                     -- instructions (in)
236        -> IO AsmState
237
238 mkBits findLabel st proto_insns
239   = foldM doInstr st proto_insns
240     where
241        doInstr :: AsmState -> BCInstr -> IO AsmState
242        doInstr st i
243           = case i of
244                SWIZZLE   stkoff n -> instr3 st i_SWIZZLE stkoff n
245                ARGCHECK  n        -> instr2 st i_ARGCHECK n
246                STKCHECK  n        -> instr2 st i_STKCHECK n
247                PUSH_L    o1       -> instr2 st i_PUSH_L o1
248                PUSH_LL   o1 o2    -> instr3 st i_PUSH_LL o1 o2
249                PUSH_LLL  o1 o2 o3 -> instr4 st i_PUSH_LLL o1 o2 o3
250                PUSH_G    nm       -> do (p, st2) <- ptr st nm
251                                         instr2 st2 i_PUSH_G p
252                PUSH_AS   nm pk    -> do (p, st2)  <- ptr st (Left nm)
253                                         (np, st3) <- ctoi_itbl st2 pk
254                                         instr3 st3 i_PUSH_AS p np
255                PUSH_UBX  (Left lit) nws  
256                                   -> do (np, st2) <- literal st lit
257                                         instr3 st2 i_PUSH_UBX np nws
258                PUSH_UBX  (Right aa) nws  
259                                   -> do (np, st2) <- addr st aa
260                                         instr3 st2 i_PUSH_UBX np nws
261
262                PUSH_TAG  tag      -> instr2 st i_PUSH_TAG tag
263                SLIDE     n by     -> instr3 st i_SLIDE n by
264                ALLOC     n        -> instr2 st i_ALLOC n
265                MKAP      off sz   -> instr3 st i_MKAP off sz
266                UNPACK    n        -> instr2 st i_UNPACK n
267                UPK_TAG   n m k    -> instr4 st i_UPK_TAG n m k
268                PACK      dcon sz  -> do (itbl_no,st2) <- itbl st dcon
269                                         instr3 st2 i_PACK itbl_no sz
270                LABEL     lab      -> return st
271                TESTLT_I  i l      -> do (np, st2) <- int st i
272                                         instr3 st2 i_TESTLT_I np (findLabel l)
273                TESTEQ_I  i l      -> do (np, st2) <- int st i
274                                         instr3 st2 i_TESTEQ_I np (findLabel l)
275                TESTLT_F  f l      -> do (np, st2) <- float st f
276                                         instr3 st2 i_TESTLT_F np (findLabel l)
277                TESTEQ_F  f l      -> do (np, st2) <- float st f
278                                         instr3 st2 i_TESTEQ_F np (findLabel l)
279                TESTLT_D  d l      -> do (np, st2) <- double st d
280                                         instr3 st2 i_TESTLT_D np (findLabel l)
281                TESTEQ_D  d l      -> do (np, st2) <- double st d
282                                         instr3 st2 i_TESTEQ_D np (findLabel l)
283                TESTLT_P  i l      -> instr3 st i_TESTLT_P i (findLabel l)
284                TESTEQ_P  i l      -> instr3 st i_TESTEQ_P i (findLabel l)
285                CASEFAIL           -> instr1 st i_CASEFAIL
286                JMP       l        -> instr2 st i_JMP (findLabel l)
287                ENTER              -> instr1 st i_ENTER
288                RETURN    rep      -> do (itbl_no,st2) <- itoc_itbl st rep
289                                         instr2 st2 i_RETURN itbl_no
290                CCALL     m_addr   -> do (np, st2) <- addr st m_addr
291                                         instr2 st2 i_CCALL np
292
293        i2s :: Int -> Word16
294        i2s = fromIntegral
295
296        instr1 (st_i0,st_l0,st_p0,st_I0) i1
297           = do st_i1 <- addToSS st_i0 (i2s i1)
298                return (st_i1,st_l0,st_p0,st_I0)
299
300        instr2 (st_i0,st_l0,st_p0,st_I0) i1 i2
301           = do st_i1 <- addToSS st_i0 (i2s i1)
302                st_i2 <- addToSS st_i1 (i2s i2)
303                return (st_i2,st_l0,st_p0,st_I0)
304
305        instr3 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3
306           = do st_i1 <- addToSS st_i0 (i2s i1)
307                st_i2 <- addToSS st_i1 (i2s i2)
308                st_i3 <- addToSS st_i2 (i2s i3)
309                return (st_i3,st_l0,st_p0,st_I0)
310
311        instr4 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3 i4
312           = do st_i1 <- addToSS st_i0 (i2s i1)
313                st_i2 <- addToSS st_i1 (i2s i2)
314                st_i3 <- addToSS st_i2 (i2s i3)
315                st_i4 <- addToSS st_i3 (i2s i4)
316                return (st_i4,st_l0,st_p0,st_I0)
317
318        float (st_i0,st_l0,st_p0,st_I0) f
319           = do let ws = mkLitF f
320                st_l1 <- addListToSS st_l0 (map Left ws)
321                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
322
323        double (st_i0,st_l0,st_p0,st_I0) d
324           = do let ws = mkLitD d
325                st_l1 <- addListToSS st_l0 (map Left ws)
326                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
327
328        int (st_i0,st_l0,st_p0,st_I0) i
329           = do let ws = mkLitI i
330                st_l1 <- addListToSS st_l0 (map Left ws)
331                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
332
333        int64 (st_i0,st_l0,st_p0,st_I0) i
334           = do let ws = mkLitI64 i
335                st_l1 <- addListToSS st_l0 (map Left ws)
336                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
337
338        addr (st_i0,st_l0,st_p0,st_I0) a
339           = do let ws = mkLitPtr a
340                st_l1 <- addListToSS st_l0 (map Left ws)
341                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
342
343        litlabel (st_i0,st_l0,st_p0,st_I0) fs
344           = do st_l1 <- addListToSS st_l0 [Right fs]
345                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
346
347        ptr (st_i0,st_l0,st_p0,st_I0) p
348           = do st_p1 <- addToSS st_p0 p
349                return (sizeSS st_p0, (st_i0,st_l0,st_p1,st_I0))
350
351        itbl (st_i0,st_l0,st_p0,st_I0) dcon
352           = do st_I1 <- addToSS st_I0 (getName dcon)
353                return (sizeSS st_I0, (st_i0,st_l0,st_p0,st_I1))
354
355        literal st (MachLabel fs)  = litlabel st fs
356        literal st (MachWord w)    = int st (fromIntegral w)
357        literal st (MachInt j)     = int st (fromIntegral j)
358        literal st (MachFloat r)   = float st (fromRational r)
359        literal st (MachDouble r)  = double st (fromRational r)
360        literal st (MachChar c)    = int st c
361        literal st (MachInt64 ii)  = int64 st (fromIntegral ii)
362        literal st (MachWord64 ii) = int64 st (fromIntegral ii)
363        literal st other           = pprPanic "ByteCodeLink.literal" (ppr other)
364
365        ctoi_itbl st pk
366           = addr st ret_itbl_addr
367             where
368                ret_itbl_addr 
369                   = case pk of
370                        PtrRep    -> stg_ctoi_ret_R1p_info
371                        WordRep   -> stg_ctoi_ret_R1n_info
372                        IntRep    -> stg_ctoi_ret_R1n_info
373                        AddrRep   -> stg_ctoi_ret_R1n_info
374                        CharRep   -> stg_ctoi_ret_R1n_info
375                        FloatRep  -> stg_ctoi_ret_F1_info
376                        DoubleRep -> stg_ctoi_ret_D1_info
377                        VoidRep   -> stg_ctoi_ret_V_info
378                        other     -> pprPanic "ByteCodeLink.ctoi_itbl" (ppr pk)
379
380        itoc_itbl st pk
381           = addr st ret_itbl_addr
382             where
383                ret_itbl_addr 
384                   = case pk of
385                        CharRep   -> stg_gc_unbx_r1_info
386                        IntRep    -> stg_gc_unbx_r1_info
387                        WordRep   -> stg_gc_unbx_r1_info
388                        AddrRep   -> stg_gc_unbx_r1_info
389                        FloatRep  -> stg_gc_f1_info
390                        DoubleRep -> stg_gc_d1_info
391                        VoidRep   -> nullPtr
392                        -- Interpreter.c spots this special case
393                        other     -> pprPanic "ByteCodeLink.itoc_itbl" (ppr pk)
394                      
395 foreign label "stg_ctoi_ret_R1p_info" stg_ctoi_ret_R1p_info :: Ptr ()
396 foreign label "stg_ctoi_ret_R1n_info" stg_ctoi_ret_R1n_info :: Ptr ()
397 foreign label "stg_ctoi_ret_F1_info"  stg_ctoi_ret_F1_info :: Ptr ()
398 foreign label "stg_ctoi_ret_D1_info"  stg_ctoi_ret_D1_info :: Ptr ()
399 foreign label "stg_ctoi_ret_V_info"   stg_ctoi_ret_V_info :: Ptr ()
400
401 foreign label "stg_gc_unbx_r1_info" stg_gc_unbx_r1_info :: Ptr ()
402 foreign label "stg_gc_f1_info"      stg_gc_f1_info :: Ptr ()
403 foreign label "stg_gc_d1_info"      stg_gc_d1_info :: Ptr ()
404
405 -- The size in 16-bit entities of an instruction.
406 instrSize16s :: BCInstr -> Int
407 instrSize16s instr
408    = case instr of
409         STKCHECK _     -> 2
410         ARGCHECK _     -> 2
411         PUSH_L   _     -> 2
412         PUSH_LL  _ _   -> 3
413         PUSH_LLL _ _ _ -> 4
414         PUSH_G   _     -> 2
415         PUSH_AS  _ _   -> 3
416         PUSH_UBX _ _   -> 3
417         PUSH_TAG _     -> 2
418         SLIDE    _ _   -> 3
419         ALLOC    _     -> 2
420         MKAP     _ _   -> 3
421         UNPACK   _     -> 2
422         UPK_TAG  _ _ _ -> 4
423         PACK     _ _   -> 3
424         LABEL    _     -> 0     -- !!
425         TESTLT_I _ _   -> 3
426         TESTEQ_I _ _   -> 3
427         TESTLT_F _ _   -> 3
428         TESTEQ_F _ _   -> 3
429         TESTLT_D _ _   -> 3
430         TESTEQ_D _ _   -> 3
431         TESTLT_P _ _   -> 3
432         TESTEQ_P _ _   -> 3
433         JMP      _     -> 2
434         CASEFAIL       -> 1
435         ENTER          -> 1
436         RETURN   _     -> 2
437
438
439 -- Make lists of host-sized words for literals, so that when the
440 -- words are placed in memory at increasing addresses, the
441 -- bit pattern is correct for the host's word size and endianness.
442 mkLitI   :: Int    -> [Word]
443 mkLitF   :: Float  -> [Word]
444 mkLitD   :: Double -> [Word]
445 mkLitPtr :: Ptr () -> [Word]
446 mkLitI64 :: Int64  -> [Word]
447
448 mkLitF f
449    = runST (do
450         arr <- newArray_ ((0::Int),0)
451         writeArray arr 0 f
452         f_arr <- castSTUArray arr
453         w0 <- readArray f_arr 0
454         return [w0 :: Word]
455      )
456
457 mkLitD d
458    | wORD_SIZE == 4
459    = runST (do
460         arr <- newArray_ ((0::Int),1)
461         writeArray arr 0 d
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 d
471         d_arr <- castSTUArray arr
472         w0 <- readArray d_arr 0
473         return [w0 :: Word]
474      )
475
476 mkLitI64 ii
477    | wORD_SIZE == 4
478    = runST (do
479         arr <- newArray_ ((0::Int),1)
480         writeArray arr 0 ii
481         d_arr <- castSTUArray arr
482         w0 <- readArray d_arr 0
483         w1 <- readArray d_arr 1
484         return [w0 :: Word,w1]
485      )
486    | wORD_SIZE == 8
487    = runST (do
488         arr <- newArray_ ((0::Int),0)
489         writeArray arr 0 ii
490         d_arr <- castSTUArray arr
491         w0 <- readArray d_arr 0
492         return [w0 :: Word]
493      )
494
495 mkLitI i
496    = runST (do
497         arr <- newArray_ ((0::Int),0)
498         writeArray arr 0 i
499         i_arr <- castSTUArray arr
500         w0 <- readArray i_arr 0
501         return [w0 :: Word]
502      )
503
504 mkLitPtr a
505    = runST (do
506         arr <- newArray_ ((0::Int),0)
507         writeArray arr 0 a
508         a_arr <- castSTUArray arr
509         w0 <- readArray a_arr 0
510         return [w0 :: Word]
511      )
512 \end{code}
513
514 %************************************************************************
515 %*                                                                      *
516 \subsection{Linking interpretables into something we can run}
517 %*                                                                      *
518 %************************************************************************
519
520 \begin{code}
521
522 {- 
523 data BCO# = BCO# ByteArray#             -- instrs   :: Array Word16#
524                  ByteArray#             -- literals :: Array Word32#
525                  PtrArray#              -- ptrs     :: Array HValue
526                  ByteArray#             -- itbls    :: Array Addr#
527 -}
528
529 linkBCO ie ce (UnlinkedBCO nm insnsSS literalsSS ptrsSS itblsSS)
530    = do insns    <- listFromSS insnsSS
531         literals <- listFromSS literalsSS
532         ptrs     <- listFromSS ptrsSS
533         itbls    <- listFromSS itblsSS
534
535         linked_ptrs     <- mapM (lookupCE ce) ptrs
536         linked_itbls    <- mapM (lookupIE ie) itbls
537         linked_literals <- mapM lookupLiteral literals
538
539         let n_insns    = sizeSS insnsSS
540             n_literals = sizeSS literalsSS
541             n_ptrs     = sizeSS ptrsSS
542             n_itbls    = sizeSS itblsSS
543
544         let ptrs_arr = array (0, n_ptrs-1) (indexify linked_ptrs)
545                        :: Array Int HValue
546             ptrs_parr = case ptrs_arr of Array lo hi parr -> parr
547
548             itbls_arr = array (0, n_itbls-1) (indexify linked_itbls)
549                         :: UArray Int ItblPtr
550             itbls_barr = case itbls_arr of UArray lo hi barr -> barr
551
552             insns_arr | n_insns > 65535
553                       = panic "linkBCO: >= 64k insns in BCO"
554                       | otherwise 
555                       = array (0, n_insns) 
556                               (indexify (fromIntegral n_insns:insns))
557                         :: UArray Int Word16
558             insns_barr = case insns_arr of UArray lo hi barr -> barr
559
560             literals_arr = array (0, n_literals-1) (indexify linked_literals)
561                            :: UArray Int Word
562             literals_barr = case literals_arr of UArray lo hi barr -> barr
563
564             indexify :: [a] -> [(Int, a)]
565             indexify xs = zip [0..] xs
566
567         BCO bco# <- newBCO insns_barr literals_barr ptrs_parr itbls_barr
568
569         -- WAS: return (unsafeCoerce# bco#)
570         case mkApUpd0# (unsafeCoerce# bco#) of
571            (# final_bco #) -> return final_bco
572
573
574 data BCO = BCO BCO#
575
576 newBCO :: ByteArray# -> ByteArray# -> Array# a -> ByteArray# -> IO BCO
577 newBCO a b c d
578    = IO (\s -> case newBCO# a b c d s of (# s1, bco #) -> (# s1, BCO bco #))
579
580
581 lookupLiteral :: Either Word FAST_STRING -> IO Word
582 lookupLiteral (Left w) = return w
583 lookupLiteral (Right addr_of_label_string)
584    = do let label_to_find = _UNPK_ addr_of_label_string
585         m <- lookupSymbol label_to_find 
586         case m of
587            -- Can't be bothered to find the official way to convert Addr# to Word#;
588            -- the FFI/Foreign designers make it too damn difficult
589            -- Hence we apply the Blunt Instrument, which works correctly
590            -- on all reasonable architectures anyway
591            Just (Ptr addr) -> return (W# (unsafeCoerce# addr))
592            Nothing         -> linkFail "ByteCodeLink: can't find label" 
593                                        label_to_find
594
595 lookupCE :: ClosureEnv -> Either Name PrimOp -> IO HValue
596 lookupCE ce (Right primop)
597    = do let sym_to_find = primopToCLabel primop "closure"
598         m <- lookupSymbol sym_to_find
599         case m of
600            Just (Ptr addr) -> case addrToHValue# addr of
601                                  (# hval #) -> return hval
602            Nothing -> linkFail "ByteCodeLink.lookupCE(primop)" sym_to_find
603 lookupCE ce (Left nm)
604    = case lookupFM ce nm of
605         Just aa -> return aa
606         Nothing 
607            -> ASSERT2(isExternalName nm, ppr nm)
608               do let sym_to_find = nameToCLabel nm "closure"
609                  m <- lookupSymbol sym_to_find
610                  case m of
611                     Just (Ptr addr) -> case addrToHValue# addr of
612                                           (# hval #) -> return hval
613                     Nothing         -> linkFail "ByteCodeLink.lookupCE" sym_to_find
614
615 lookupIE :: ItblEnv -> Name -> IO (Ptr a)
616 lookupIE ie con_nm 
617    = case lookupFM ie con_nm of
618         Just (Ptr a) -> return (Ptr a)
619         Nothing
620            -> do -- try looking up in the object files.
621                  let sym_to_find1 = nameToCLabel con_nm "con_info"
622                  m <- lookupSymbol sym_to_find1
623                  case m of
624                     Just addr -> return addr
625                     Nothing 
626                        -> do -- perhaps a nullary constructor?
627                              let sym_to_find2 = nameToCLabel con_nm "static_info"
628                              n <- lookupSymbol sym_to_find2
629                              case n of
630                                 Just addr -> return addr
631                                 Nothing   -> linkFail "ByteCodeLink.lookupIE" 
632                                                 (sym_to_find1 ++ " or " ++ sym_to_find2)
633
634 linkFail :: String -> String -> IO a
635 linkFail who what
636    = throwDyn (ProgramError $
637         unlines [ ""
638                 , "During interactive linking, GHCi couldn't find the following symbol:"
639                 , ' ' : ' ' : what 
640                 , "This may be due to you not asking GHCi to load extra object files,"
641                 , "archives or DLLs needed by your current session.  Restart GHCi, specifying"
642                 , "the missing library using the -L/path/to/object/dir and -lmissinglibname"
643                 , "flags, or simply by naming the relevant files on the GHCi command line."
644                 , "Alternatively, this link failure might indicate a bug in GHCi."
645                 , "If you suspect the latter, please send a bug report to:"
646                 , "  glasgow-haskell-bugs@haskell.org"
647                 ])
648
649 -- HACKS!!!  ToDo: cleaner
650 nameToCLabel :: Name -> String{-suffix-} -> String
651 nameToCLabel n suffix
652    = _UNPK_(moduleNameFS (rdrNameModule rn)) 
653      ++ '_':occNameString(rdrNameOcc rn) ++ '_':suffix
654      where rn = toRdrName n
655
656 primopToCLabel :: PrimOp -> String{-suffix-} -> String
657 primopToCLabel primop suffix
658    = let str = "PrelPrimopWrappers_" ++ occNameString (primOpOcc primop) ++ '_':suffix
659      in --trace ("primopToCLabel: " ++ str)
660         str
661
662 \end{code}
663
664 %************************************************************************
665 %*                                                                      *
666 \subsection{Connect to actual values for bytecode opcodes}
667 %*                                                                      *
668 %************************************************************************
669
670 \begin{code}
671
672 #include "Bytecodes.h"
673
674 i_ARGCHECK = (bci_ARGCHECK :: Int)
675 i_PUSH_L   = (bci_PUSH_L :: Int)
676 i_PUSH_LL  = (bci_PUSH_LL :: Int)
677 i_PUSH_LLL = (bci_PUSH_LLL :: Int)
678 i_PUSH_G   = (bci_PUSH_G :: Int)
679 i_PUSH_AS  = (bci_PUSH_AS :: Int)
680 i_PUSH_UBX = (bci_PUSH_UBX :: Int)
681 i_PUSH_TAG = (bci_PUSH_TAG :: Int)
682 i_SLIDE    = (bci_SLIDE :: Int)
683 i_ALLOC    = (bci_ALLOC :: Int)
684 i_MKAP     = (bci_MKAP :: Int)
685 i_UNPACK   = (bci_UNPACK :: Int)
686 i_UPK_TAG  = (bci_UPK_TAG :: Int)
687 i_PACK     = (bci_PACK :: Int)
688 i_TESTLT_I = (bci_TESTLT_I :: Int)
689 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
690 i_TESTLT_F = (bci_TESTLT_F :: Int)
691 i_TESTEQ_F = (bci_TESTEQ_F :: Int)
692 i_TESTLT_D = (bci_TESTLT_D :: Int)
693 i_TESTEQ_D = (bci_TESTEQ_D :: Int)
694 i_TESTLT_P = (bci_TESTLT_P :: Int)
695 i_TESTEQ_P = (bci_TESTEQ_P :: Int)
696 i_CASEFAIL = (bci_CASEFAIL :: Int)
697 i_ENTER    = (bci_ENTER :: Int)
698 i_RETURN   = (bci_RETURN :: Int)
699 i_STKCHECK = (bci_STKCHECK :: Int)
700 i_JMP      = (bci_JMP :: Int)
701 #ifdef bci_CCALL
702 i_CCALL    = (bci_CCALL :: Int)
703 i_SWIZZLE  = (bci_SWIZZLE :: Int)
704 #else
705 i_CCALL    = error "Sorry pal, you need to bootstrap to use i_CCALL."
706 i_SWIZZLE  = error "Sorry pal, you need to bootstrap to use i_SWIZZLE."
707 #endif
708
709 iNTERP_STACK_CHECK_THRESH = (INTERP_STACK_CHECK_THRESH :: Int)
710
711 \end{code}