2 % (c) The University of Glasgow 2000
4 \section[ByteCodeLink]{Bytecode assembler and linker}
7 module ByteCodeLink ( UnlinkedBCO, UnlinkedBCOExpr, assembleBCO,
8 ClosureEnv, HValue, linkSomeBCOs, filterNameMap,
9 iNTERP_STACK_CHECK_THRESH
12 #include "HsVersions.h"
15 import Name ( Name, getName, nameModule, toRdrName, isGlobalName )
16 import RdrName ( rdrNameOcc, rdrNameModule )
17 import OccName ( occNameString )
18 import FiniteMap ( FiniteMap, addListToFM, filterFM,
19 addToFM, lookupFM, emptyFM )
21 import Literal ( Literal(..) )
22 import PrimOp ( PrimOp, primOpOcc )
23 import PrimRep ( PrimRep(..) )
24 import Constants ( wORD_SIZE )
25 import Module ( ModuleName, moduleName, moduleNameFS )
26 import Linker ( lookupSymbol )
27 import FastString ( FastString(..) )
28 import ByteCodeInstr ( BCInstr(..), ProtoBCO(..) )
29 import ByteCodeItbls ( ItblEnv, ItblPtr )
32 import Monad ( foldM )
34 import MArray ( castSTUArray,
35 newFloatArray, writeFloatArray,
36 newDoubleArray, writeDoubleArray,
37 newIntArray, writeIntArray,
38 newAddrArray, writeAddrArray )
39 import Foreign ( Word16, Ptr(..) )
40 import Addr ( Word, Addr )
42 import PrelBase ( Int(..) )
43 import PrelGHC ( BCO#, newBCO#, unsafeCoerce#,
44 ByteArray#, Array#, addrToHValue#, mkApUpd0# )
45 import IOExts ( fixIO )
47 import PrelArr ( Array(..) )
48 import PrelIOBase ( IO(..) )
52 %************************************************************************
54 \subsection{Top-level stuff}
56 %************************************************************************
60 -- Link a bunch of BCOs and return them + updated closure env.
61 linkSomeBCOs :: Bool -- False <=> add _all_ BCOs to returned closure env
62 -- True <=> add only toplevel BCOs to closure env
66 -> IO (ClosureEnv, [HValue])
67 linkSomeBCOs toplevs_only ie ce_in ul_bcos
68 = do let nms = map nameOfUnlinkedBCO ul_bcos
70 ( \ hvs -> let ce_out = addListToFM ce_in (zipLazily nms hvs)
71 in mapM (linkBCO ie ce_out) ul_bcos )
73 let ce_all_additions = zip nms hvals
74 ce_top_additions = filter (isGlobalName.fst) ce_all_additions
75 ce_additions = if toplevs_only then ce_top_additions
77 ce_out = addListToFM ce_in ce_additions
78 return (ce_out, hvals)
80 -- A lazier zip, in which no demand is propagated to the second
81 -- list unless some demand is propagated to the snd of one of the
84 zipLazily (x:xs) ys = (x, head ys) : zipLazily xs (tail ys)
89 (SizedSeq Word16) -- insns
90 (SizedSeq Word) -- literals
91 (SizedSeq (Either Name PrimOp)) -- ptrs
92 (SizedSeq Name) -- itbl refs
94 nameOfUnlinkedBCO (UnlinkedBCO nm _ _ _ _) = nm
96 -- When translating expressions, we need to distinguish the root
97 -- BCO for the expression
98 type UnlinkedBCOExpr = (UnlinkedBCO, [UnlinkedBCO])
100 instance Outputable UnlinkedBCO where
101 ppr (UnlinkedBCO nm insns lits ptrs itbls)
102 = sep [text "BCO", ppr nm, text "with",
103 int (sizeSS insns), text "insns",
104 int (sizeSS lits), text "lits",
105 int (sizeSS ptrs), text "ptrs",
106 int (sizeSS itbls), text "itbls"]
109 -- these need a proper home
110 type ClosureEnv = FiniteMap Name HValue
111 data HValue = HValue -- dummy type, actually a pointer to some Real Code.
113 -- remove all entries for a given set of modules from the environment
114 filterNameMap :: [ModuleName] -> FiniteMap Name a -> FiniteMap Name a
115 filterNameMap mods env
116 = filterFM (\n _ -> moduleName (nameModule n) `notElem` mods) env
120 %************************************************************************
122 \subsection{The bytecode assembler}
124 %************************************************************************
126 The object format for bytecodes is: 16 bits for the opcode, and 16 for
127 each field -- so the code can be considered a sequence of 16-bit ints.
128 Each field denotes either a stack offset or number of items on the
129 stack (eg SLIDE), and index into the pointer table (eg PUSH_G), an
130 index into the literal table (eg PUSH_I/D/L), or a bytecode address in
134 -- Top level assembler fn.
135 assembleBCO :: ProtoBCO Name -> IO UnlinkedBCO
137 assembleBCO (ProtoBCO nm instrs origin)
139 -- pass 1: collect up the offsets of the local labels.
140 -- Remember that the first insn starts at offset 1 since offset 0
141 -- (eventually) will hold the total # of insns.
142 label_env = mkLabelEnv emptyFM 1 instrs
144 mkLabelEnv env i_offset [] = env
145 mkLabelEnv env i_offset (i:is)
147 = case i of LABEL n -> addToFM env n i_offset ; _ -> env
148 in mkLabelEnv new_env (i_offset + instrSize16s i) is
151 = case lookupFM label_env lab of
152 Just bco_offset -> bco_offset
153 Nothing -> pprPanic "assembleBCO.findLabel" (int lab)
155 do -- pass 2: generate the instruction, ptr and nonptr bits
156 insns <- return emptySS :: IO (SizedSeq Word16)
157 lits <- return emptySS :: IO (SizedSeq Word)
158 ptrs <- return emptySS :: IO (SizedSeq (Either Name PrimOp))
159 itbls <- return emptySS :: IO (SizedSeq Name)
160 let init_asm_state = (insns,lits,ptrs,itbls)
161 (final_insns, final_lits, final_ptrs, final_itbls)
162 <- mkBits findLabel init_asm_state instrs
164 return (UnlinkedBCO nm final_insns final_lits final_ptrs final_itbls)
166 -- instrs nonptrs ptrs itbls
167 type AsmState = (SizedSeq Word16, SizedSeq Word,
168 SizedSeq (Either Name PrimOp), SizedSeq Name)
170 data SizedSeq a = SizedSeq !Int [a]
171 emptySS = SizedSeq 0 []
172 addToSS (SizedSeq n r_xs) x = return (SizedSeq (n+1) (x:r_xs))
173 addListToSS (SizedSeq n r_xs) xs
174 = return (SizedSeq (n + length xs) (reverse xs ++ r_xs))
175 sizeSS (SizedSeq n r_xs) = n
176 listFromSS (SizedSeq n r_xs) = return (reverse r_xs)
179 -- This is where all the action is (pass 2 of the assembler)
180 mkBits :: (Int -> Int) -- label finder
182 -> [BCInstr] -- instructions (in)
185 mkBits findLabel st proto_insns
186 = foldM doInstr st proto_insns
188 doInstr :: AsmState -> BCInstr -> IO AsmState
191 ARGCHECK n -> instr2 st i_ARGCHECK n
192 STKCHECK n -> instr2 st i_STKCHECK n
193 PUSH_L o1 -> instr2 st i_PUSH_L o1
194 PUSH_LL o1 o2 -> instr3 st i_PUSH_LL o1 o2
195 PUSH_LLL o1 o2 o3 -> instr4 st i_PUSH_LLL o1 o2 o3
196 PUSH_G nm -> do (p, st2) <- ptr st nm
197 instr2 st2 i_PUSH_G p
198 PUSH_AS nm pk -> do (p, st2) <- ptr st (Left nm)
199 (np, st3) <- ctoi_itbl st2 pk
200 instr3 st3 i_PUSH_AS p np
201 PUSH_UBX lit nws -> do (np, st2) <- literal st lit
202 instr3 st2 i_PUSH_UBX np nws
203 PUSH_TAG tag -> instr2 st i_PUSH_TAG tag
204 SLIDE n by -> instr3 st i_SLIDE n by
205 ALLOC n -> instr2 st i_ALLOC n
206 MKAP off sz -> instr3 st i_MKAP off sz
207 UNPACK n -> instr2 st i_UNPACK n
208 UPK_TAG n m k -> instr4 st i_UPK_TAG n m k
209 PACK dcon sz -> do (itbl_no,st2) <- itbl st dcon
210 instr3 st2 i_PACK itbl_no sz
211 LABEL lab -> return st
212 TESTLT_I i l -> do (np, st2) <- int st i
213 instr3 st2 i_TESTLT_I np (findLabel l)
214 TESTEQ_I i l -> do (np, st2) <- int st i
215 instr3 st2 i_TESTEQ_I np (findLabel l)
216 TESTLT_F f l -> do (np, st2) <- float st f
217 instr3 st2 i_TESTLT_F np (findLabel l)
218 TESTEQ_F f l -> do (np, st2) <- float st f
219 instr3 st2 i_TESTEQ_F np (findLabel l)
220 TESTLT_D d l -> do (np, st2) <- double st d
221 instr3 st2 i_TESTLT_D np (findLabel l)
222 TESTEQ_D d l -> do (np, st2) <- double st d
223 instr3 st2 i_TESTEQ_D np (findLabel l)
224 TESTLT_P i l -> instr3 st i_TESTLT_P i (findLabel l)
225 TESTEQ_P i l -> instr3 st i_TESTEQ_P i (findLabel l)
226 CASEFAIL -> instr1 st i_CASEFAIL
227 ENTER -> instr1 st i_ENTER
228 RETURN rep -> do (itbl_no,st2) <- itoc_itbl st rep
229 instr2 st2 i_RETURN itbl_no
234 instr1 (st_i0,st_l0,st_p0,st_I0) i1
235 = do st_i1 <- addToSS st_i0 (i2s i1)
236 return (st_i1,st_l0,st_p0,st_I0)
238 instr2 (st_i0,st_l0,st_p0,st_I0) i1 i2
239 = do st_i1 <- addToSS st_i0 (i2s i1)
240 st_i2 <- addToSS st_i1 (i2s i2)
241 return (st_i2,st_l0,st_p0,st_I0)
243 instr3 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3
244 = do st_i1 <- addToSS st_i0 (i2s i1)
245 st_i2 <- addToSS st_i1 (i2s i2)
246 st_i3 <- addToSS st_i2 (i2s i3)
247 return (st_i3,st_l0,st_p0,st_I0)
249 instr4 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3 i4
250 = do st_i1 <- addToSS st_i0 (i2s i1)
251 st_i2 <- addToSS st_i1 (i2s i2)
252 st_i3 <- addToSS st_i2 (i2s i3)
253 st_i4 <- addToSS st_i3 (i2s i4)
254 return (st_i4,st_l0,st_p0,st_I0)
256 float (st_i0,st_l0,st_p0,st_I0) f
257 = do let ws = mkLitF f
258 st_l1 <- addListToSS st_l0 ws
259 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
261 double (st_i0,st_l0,st_p0,st_I0) d
262 = do let ws = mkLitD d
263 st_l1 <- addListToSS st_l0 ws
264 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
266 int (st_i0,st_l0,st_p0,st_I0) i
267 = do let ws = mkLitI i
268 st_l1 <- addListToSS st_l0 ws
269 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
271 addr (st_i0,st_l0,st_p0,st_I0) a
272 = do let ws = mkLitA a
273 st_l1 <- addListToSS st_l0 ws
274 return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
276 ptr (st_i0,st_l0,st_p0,st_I0) p
277 = do st_p1 <- addToSS st_p0 p
278 return (sizeSS st_p0, (st_i0,st_l0,st_p1,st_I0))
280 itbl (st_i0,st_l0,st_p0,st_I0) dcon
281 = do st_I1 <- addToSS st_I0 (getName dcon)
282 return (sizeSS st_I0, (st_i0,st_l0,st_p0,st_I1))
284 literal st (MachWord w) = int st (fromIntegral w)
285 literal st (MachInt j) = int st (fromIntegral j)
286 literal st (MachFloat r) = float st (fromRational r)
287 literal st (MachDouble r) = double st (fromRational r)
288 literal st (MachChar c) = int st c
291 = addr st ret_itbl_addr
293 ret_itbl_addr = case pk of
294 PtrRep -> stg_ctoi_ret_R1p_info
295 WordRep -> stg_ctoi_ret_R1n_info
296 IntRep -> stg_ctoi_ret_R1n_info
297 AddrRep -> stg_ctoi_ret_R1n_info
298 CharRep -> stg_ctoi_ret_R1n_info
299 FloatRep -> stg_ctoi_ret_F1_info
300 DoubleRep -> stg_ctoi_ret_D1_info
301 _ -> pprPanic "mkBits.ctoi_itbl" (ppr pk)
304 = addr st ret_itbl_addr
306 ret_itbl_addr = case pk of
307 CharRep -> stg_gc_unbx_r1_info
308 IntRep -> stg_gc_unbx_r1_info
309 FloatRep -> stg_gc_f1_info
310 DoubleRep -> stg_gc_d1_info
312 foreign label "stg_ctoi_ret_R1p_info" stg_ctoi_ret_R1p_info :: Addr
313 foreign label "stg_ctoi_ret_R1n_info" stg_ctoi_ret_R1n_info :: Addr
314 foreign label "stg_ctoi_ret_F1_info" stg_ctoi_ret_F1_info :: Addr
315 foreign label "stg_ctoi_ret_D1_info" stg_ctoi_ret_D1_info :: Addr
317 foreign label "stg_gc_unbx_r1_info" stg_gc_unbx_r1_info :: Addr
318 foreign label "stg_gc_f1_info" stg_gc_f1_info :: Addr
319 foreign label "stg_gc_d1_info" stg_gc_d1_info :: Addr
321 -- The size in 16-bit entities of an instruction.
322 instrSize16s :: BCInstr -> Int
354 -- Make lists of host-sized words for literals, so that when the
355 -- words are placed in memory at increasing addresses, the
356 -- bit pattern is correct for the host's word size and endianness.
357 mkLitI :: Int -> [Word]
358 mkLitF :: Float -> [Word]
359 mkLitD :: Double -> [Word]
360 mkLitA :: Addr -> [Word]
364 arr <- newFloatArray ((0::Int),0)
365 writeFloatArray arr 0 f
366 f_arr <- castSTUArray arr
367 w0 <- readWordArray f_arr 0
374 arr <- newDoubleArray ((0::Int),1)
375 writeDoubleArray arr 0 d
376 d_arr <- castSTUArray arr
377 w0 <- readWordArray d_arr 0
378 w1 <- readWordArray d_arr 1
383 arr <- newDoubleArray ((0::Int),0)
384 writeDoubleArray arr 0 d
385 d_arr <- castSTUArray arr
386 w0 <- readWordArray d_arr 0
392 arr <- newIntArray ((0::Int),0)
393 writeIntArray arr 0 i
394 i_arr <- castSTUArray arr
395 w0 <- readWordArray i_arr 0
401 arr <- newAddrArray ((0::Int),0)
402 writeAddrArray arr 0 a
403 a_arr <- castSTUArray arr
404 w0 <- readWordArray a_arr 0
410 %************************************************************************
412 \subsection{Linking interpretables into something we can run}
414 %************************************************************************
419 data BCO# = BCO# ByteArray# -- instrs :: array Word16#
420 ByteArray# -- literals :: array Word32#
421 PtrArray# -- ptrs :: Array HValue
422 ByteArray# -- itbls :: Array Addr#
425 linkBCO ie ce (UnlinkedBCO nm insnsSS literalsSS ptrsSS itblsSS)
426 = do insns <- listFromSS insnsSS
427 literals <- listFromSS literalsSS
428 ptrs <- listFromSS ptrsSS
429 itbls <- listFromSS itblsSS
431 linked_ptrs <- mapM (lookupCE ce) ptrs
432 linked_itbls <- mapM (lookupIE ie) itbls
434 let n_insns = sizeSS insnsSS
435 n_literals = sizeSS literalsSS
436 n_ptrs = sizeSS ptrsSS
437 n_itbls = sizeSS itblsSS
439 let ptrs_arr = array (0, n_ptrs-1) (indexify linked_ptrs)
441 ptrs_parr = case ptrs_arr of Array lo hi parr -> parr
443 itbls_arr = array (0, n_itbls-1) (indexify linked_itbls)
444 :: UArray Int ItblPtr
445 itbls_barr = case itbls_arr of UArray lo hi barr -> barr
447 insns_arr | n_insns > 65535
448 = panic "linkBCO: >= 64k insns in BCO"
451 (indexify (fromIntegral n_insns:insns))
453 insns_barr = case insns_arr of UArray lo hi barr -> barr
455 literals_arr = array (0, n_literals-1) (indexify literals)
457 literals_barr = case literals_arr of UArray lo hi barr -> barr
459 indexify :: [a] -> [(Int, a)]
460 indexify xs = zip [0..] xs
462 BCO bco# <- newBCO insns_barr literals_barr ptrs_parr itbls_barr
464 -- WAS: return (unsafeCoerce# bco#)
465 case mkApUpd0# (unsafeCoerce# bco#) of
466 (# final_bco #) -> return final_bco
471 newBCO :: ByteArray# -> ByteArray# -> Array# a -> ByteArray# -> IO BCO
473 = IO (\s -> case newBCO# a b c d s of (# s1, bco #) -> (# s1, BCO bco #))
476 lookupCE :: ClosureEnv -> Either Name PrimOp -> IO HValue
477 lookupCE ce (Right primop)
478 = do m <- lookupSymbol (primopToCLabel primop "closure")
480 Just (Ptr addr) -> case addrToHValue# addr of
481 (# hval #) -> return hval
482 Nothing -> pprPanic "ByteCodeGen.lookupCE(primop)" (ppr primop)
483 lookupCE ce (Left nm)
484 = case lookupFM ce nm of
487 -> do m <- lookupSymbol (nameToCLabel nm "closure")
489 Just (Ptr addr) -> case addrToHValue# addr of
490 (# hval #) -> return hval
491 Nothing -> pprPanic "ByteCodeGen.lookupCE" (ppr nm)
493 lookupIE :: ItblEnv -> Name -> IO (Ptr a)
495 = case lookupFM ie con_nm of
496 Just (Ptr a) -> return (Ptr a)
498 -> do -- try looking up in the object files.
499 m <- lookupSymbol (nameToCLabel con_nm "con_info")
501 Just addr -> return addr
503 -> do -- perhaps a nullary constructor?
504 n <- lookupSymbol (nameToCLabel con_nm "static_info")
506 Just addr -> return addr
507 Nothing -> pprPanic "ByteCodeGen.lookupIE" (ppr con_nm)
509 -- HACKS!!! ToDo: cleaner
510 nameToCLabel :: Name -> String{-suffix-} -> String
511 nameToCLabel n suffix
512 = _UNPK_(moduleNameFS (rdrNameModule rn))
513 ++ '_':occNameString(rdrNameOcc rn) ++ '_':suffix
514 where rn = toRdrName n
516 primopToCLabel :: PrimOp -> String{-suffix-} -> String
517 primopToCLabel primop suffix
518 = let str = "PrelPrimopWrappers_" ++ occNameString (primOpOcc primop) ++ '_':suffix
519 in --trace ("primopToCLabel: " ++ str)
524 %************************************************************************
526 \subsection{Connect to actual values for bytecode opcodes}
528 %************************************************************************
532 #include "Bytecodes.h"
534 i_ARGCHECK = (bci_ARGCHECK :: Int)
535 i_PUSH_L = (bci_PUSH_L :: Int)
536 i_PUSH_LL = (bci_PUSH_LL :: Int)
537 i_PUSH_LLL = (bci_PUSH_LLL :: Int)
538 i_PUSH_G = (bci_PUSH_G :: Int)
539 i_PUSH_AS = (bci_PUSH_AS :: Int)
540 i_PUSH_UBX = (bci_PUSH_UBX :: Int)
541 i_PUSH_TAG = (bci_PUSH_TAG :: Int)
542 i_SLIDE = (bci_SLIDE :: Int)
543 i_ALLOC = (bci_ALLOC :: Int)
544 i_MKAP = (bci_MKAP :: Int)
545 i_UNPACK = (bci_UNPACK :: Int)
546 i_UPK_TAG = (bci_UPK_TAG :: Int)
547 i_PACK = (bci_PACK :: Int)
548 i_TESTLT_I = (bci_TESTLT_I :: Int)
549 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
550 i_TESTLT_F = (bci_TESTLT_F :: Int)
551 i_TESTEQ_F = (bci_TESTEQ_F :: Int)
552 i_TESTLT_D = (bci_TESTLT_D :: Int)
553 i_TESTEQ_D = (bci_TESTEQ_D :: Int)
554 i_TESTLT_P = (bci_TESTLT_P :: Int)
555 i_TESTEQ_P = (bci_TESTEQ_P :: Int)
556 i_CASEFAIL = (bci_CASEFAIL :: Int)
557 i_ENTER = (bci_ENTER :: Int)
558 i_RETURN = (bci_RETURN :: Int)
559 i_STKCHECK = (bci_STKCHECK :: Int)
561 iNTERP_STACK_CHECK_THRESH = (INTERP_STACK_CHECK_THRESH :: Int)